Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions lib/screens/home_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -602,14 +602,29 @@ class HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
child: SegmentedButton<TabGroup>(
segments: [
for (final g in groups)
ButtonSegment(value: g, label: Text(g.label)),
ButtonSegment(
value: g,
// Always one line: on very narrow phones the
// label shrinks instead of wrapping.
label: FittedBox(
fit: BoxFit.scaleDown,
child: Text(g.label,
maxLines: 1, softWrap: false),
),
),
],
selected: {current.group},
showSelectedIcon: false,
// Same corners as the chips below (Material 3: 8).
// Same corners as the chips below (Material 3: 8);
// smaller text and padding so four labels fit.
style: ButtonStyle(
shape: WidgetStatePropertyAll(RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8))),
textStyle: const WidgetStatePropertyAll(TextStyle(
fontSize: 13, fontWeight: FontWeight.w500)),
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 6)),
visualDensity: VisualDensity.compact,
),
onSelectionChanged: (selection) =>
_selectGroup(selection.first),
Expand Down
28 changes: 28 additions & 0 deletions lib/services/html_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart';
import 'package:view_source_vibe/services/detection/engine.dart';
import 'package:view_source_vibe/models/html_file.dart';
import 'package:view_source_vibe/models/app_tab.dart';
import 'package:view_source_vibe/services/site_data_cleaner.dart' as site_data;
import 'package:re_highlight/re_highlight.dart';
import 'package:re_editor/re_editor.dart';
import 'dart:async';
Expand Down Expand Up @@ -108,6 +109,10 @@ class HtmlService extends ChangeNotifier {
/// Deletes every cookie (the "Always clean cookies" setting); a seam for
/// tests.
final Future<void> Function() _deleteAllCookies;

/// Removes the browser's data for one site (long-press Reload); a seam
/// for tests.
final Future<void> Function(Uri url) _clearSiteData;
final ResourceSizeLookup _sizeLookup;
final FreshLoadMeasurer _freshMeasurer;
final BrowserScreenshot? _browserScreenshotOverride;
Expand Down Expand Up @@ -1615,6 +1620,7 @@ class HtmlService extends ChangeNotifier {
NativeCookieReader? nativeCookies,
ResourceSizeLookup? sizeLookup,
Future<void> Function()? deleteAllCookies,
Future<void> Function(Uri url)? clearSiteData,
FreshLoadMeasurer? freshLoadMeasurer,
BrowserScreenshot? browserScreenshot,
BrowserPlatform? browserPlatform,
Expand All @@ -1632,6 +1638,7 @@ class HtmlService extends ChangeNotifier {
_nativeCookies = nativeCookies ?? _nativeCookiesFromManager,
_deleteAllCookies = deleteAllCookies ??
(() => CookieManager.instance().deleteAllCookies()),
_clearSiteData = clearSiteData ?? site_data.clearSiteData,
_sizeLookup = sizeLookup ?? _lookupResourceSize,
_browserScreenshotOverride = browserScreenshot,
_freshMeasurer = freshLoadMeasurer ??
Expand Down Expand Up @@ -2265,6 +2272,27 @@ Technical details: $message''';
}
}

/// Long-press Reload: forget everything the browser stored for the open
/// site (cookies, cache, storage), then load it again on the same tab.
/// Returns the host that was cleared, or null when nothing was (a local
/// file is only reloaded).
Future<String?> reloadWithClearedSiteData() async {
final file = _currentFile;
if (file == null) return null;
final url = file.isUrl ? Uri.tryParse(file.path) : null;
String? cleared;
if (url != null && url.host.isNotEmpty) {
try {
await _clearSiteData(url);
cleared = url.host;
} catch (e) {
debugPrint('Clearing site data failed: $e');
}
}
await reloadCurrentFile(switchToTab: _activeTabIndex);
return cleared;
}

/// Pull-to-refresh: reloads what is open. A local file is re-read from
/// disk; a URL is loaded again. A file without a path (picked or shared
/// bytes) cannot be re-read and stays as it is.
Expand Down
65 changes: 65 additions & 0 deletions lib/services/site_data_cleaner.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

/// Whether a website-data record belongs to [host]. Records are named by
/// their registrable domain ("w3.org"), the host may be a subdomain of it
/// ("www.w3.org").
bool siteDataRecordMatches(String host, String? recordName) {
if (recordName == null || recordName.isEmpty || host.isEmpty) return false;
final h = host.toLowerCase();
final r = recordName.toLowerCase();
return h == r || h.endsWith('.$r') || r.endsWith('.$h');
}

/// Removes everything the in-app browser stored for the site of [url]:
/// cookies (also those set on a parent domain), cache, local storage,
/// IndexedDB and the like. Each step is best effort; a step a platform
/// does not support is skipped.
///
/// On Apple platforms and Linux this is per site. Android's WebView cache is
/// shared by all sites and can only be cleared as a whole, so there (and as a
/// fallback elsewhere) the whole cache is cleared; other sites' cookies and
/// storage stay.
Future<void> clearSiteData(Uri url) async {
final host = url.host;
final webUri = WebUri(url.toString());

final cookies = CookieManager.instance();
try {
for (final cookie in await cookies.getCookies(url: webUri)) {
await cookies.deleteCookie(
url: webUri,
name: cookie.name,
domain: cookie.domain,
path: cookie.path ?? '/',
);
}
await cookies.deleteCookies(url: webUri);
} catch (e) {
debugPrint('Clearing cookies for $host failed: $e');
}

final storage = WebStorageManager.instance();
try {
if (defaultTargetPlatform == TargetPlatform.android) {
await storage.deleteOrigin(origin: url.origin);
await InAppWebViewController.clearAllCache();
} else {
final records =
await storage.fetchDataRecords(dataTypes: WebsiteDataType.ALL);
final ofSite = [
for (final r in records)
if (siteDataRecordMatches(host, r.displayName)) r,
];
if (ofSite.isNotEmpty) {
await storage.removeDataFor(
dataTypes: WebsiteDataType.ALL, dataRecords: ofSite);
}
}
} catch (e) {
debugPrint('Clearing site storage for $host failed, clearing cache: $e');
try {
await InAppWebViewController.clearAllCache();
} catch (_) {}
}
}
59 changes: 40 additions & 19 deletions lib/widgets/url_input.dart
Original file line number Diff line number Diff line change
Expand Up @@ -533,32 +533,53 @@ class _UrlInputProgress extends StatelessWidget {
}
}

/// Reloads the open page or file and stays on the current tab. Disabled
/// while nothing is loaded; while loading, the progress ring takes its place
/// (tap it to stop).
/// Reloads the open page or file and stays on the current tab. A long press
/// first clears everything the browser stored for the site (cookies, cache,
/// storage). Disabled while nothing is loaded; while loading, the progress
/// ring takes its place (tap it to stop).
class _ReloadButton extends StatelessWidget {
const _ReloadButton();

Future<void> _clearAndReload(BuildContext context) async {
final messenger = ScaffoldMessenger.maybeOf(context);
HapticFeedback.mediumImpact();
final host = await context.read<HtmlService>().reloadWithClearedSiteData();
messenger?.showSnackBar(SnackBar(
content: Text(host == null
? 'Reloaded'
: 'Cleared cookies, cache and storage for $host'),
duration: const Duration(seconds: 3),
));
}

@override
Widget build(BuildContext context) {
final hasFile =
context.select<HtmlService, bool>((s) => s.currentFile != null);
return IconButton(
icon: const Icon(Icons.refresh, size: 22),
tooltip: 'Reload',
// Narrow, so the clear button sits close (~12px between glyphs).
padding: EdgeInsets.zero,
constraints: const BoxConstraints(minWidth: 36, minHeight: 40),
style: IconButton.styleFrom(
tapTargetSize: MaterialTapTargetSize.shrinkWrap),
onPressed: hasFile
? () {
final service = context.read<HtmlService>();
service
.reloadCurrentFile(switchToTab: service.activeTabIndex)
.ignore();
}
: null,
// The tooltip shows on hover only: on touch, a long press is the
// clear-and-reload gesture, not "show tooltip".
return Tooltip(
message: 'Reload (hold to clear site data first)',
triggerMode: TooltipTriggerMode.manual,
child: GestureDetector(
onLongPress: hasFile ? () => _clearAndReload(context) : null,
child: IconButton(
icon: const Icon(Icons.refresh, size: 22),
// Narrow, so the clear button sits close (~12px between glyphs).
padding: EdgeInsets.zero,
constraints: const BoxConstraints(minWidth: 36, minHeight: 40),
style: IconButton.styleFrom(
tapTargetSize: MaterialTapTargetSize.shrinkWrap),
onPressed: hasFile
? () {
final service = context.read<HtmlService>();
service
.reloadCurrentFile(switchToTab: service.activeTabIndex)
.ignore();
}
: null,
),
),
);
}
}
Expand Down
77 changes: 77 additions & 0 deletions test/services/site_data_reload_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:view_source_vibe/models/html_file.dart';
import 'package:view_source_vibe/services/html_service.dart';
import 'package:view_source_vibe/services/inspection_store.dart';
import 'package:view_source_vibe/services/site_data_cleaner.dart';

import '../fixtures/inspection/pump.dart';

HtmlFile _file(String path, {bool isUrl = true}) => HtmlFile(
name: 'index.html',
path: path,
content: '<html><body>hi</body></html>',
lastModified: DateTime(2026),
size: 28,
isUrl: isUrl,
);

void main() {
TestWidgetsFlutterBinding.ensureInitialized();

group('siteDataRecordMatches', () {
test('matches the domain itself and its subdomains', () {
expect(siteDataRecordMatches('w3.org', 'w3.org'), isTrue);
expect(siteDataRecordMatches('www.w3.org', 'w3.org'), isTrue);
expect(siteDataRecordMatches('WWW.W3.ORG', 'w3.org'), isTrue);
});

test('does not match other sites that only share a suffix', () {
expect(siteDataRecordMatches('notw3.org', 'w3.org'), isFalse);
expect(siteDataRecordMatches('w3.org', 'example.com'), isFalse);
expect(siteDataRecordMatches('w3.org', null), isFalse);
expect(siteDataRecordMatches('w3.org', ''), isFalse);
});
});

group('reloadWithClearedSiteData', () {
HtmlService make(List<Uri> cleared) => HtmlService(
store: InspectionStore(),
serverFetcher: SilentServerFetcher(),
browserLoader: SilentBrowserLoader(),
metadataExtractor: (html, base, {headers}) async => {},
clearSiteData: (url) async => cleared.add(url),
);

test('clears the open site, then reloads it', () async {
final cleared = <Uri>[];
final service = make(cleared);
addTearDown(service.dispose);
await service.loadFile(_file('https://www.w3.org/standards/'));

final host = await service.reloadWithClearedSiteData();

expect(host, 'www.w3.org');
expect(cleared, [Uri.parse('https://www.w3.org/standards/')]);
expect(service.currentInputText, 'https://www.w3.org/standards/');
});

test('a local file is only reloaded, nothing is cleared', () async {
final cleared = <Uri>[];
final service = make(cleared);
addTearDown(service.dispose);
await service.loadFile(_file('', isUrl: false));

expect(await service.reloadWithClearedSiteData(), isNull);
expect(cleared, isEmpty);
});

test('nothing open: nothing happens', () async {
final cleared = <Uri>[];
final service = make(cleared);
addTearDown(service.dispose);

expect(await service.reloadWithClearedSiteData(), isNull);
expect(cleared, isEmpty);
});
});
}
3 changes: 2 additions & 1 deletion test/title_navigation_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ void main() {
matching: find.byTooltip('Back'),
);
expect(back, findsOneWidget);
expect(find.byTooltip('Reload'), findsOneWidget);
expect(find.byTooltip('Reload (hold to clear site data first)'),
findsOneWidget);
expect(tester.getTopLeft(back).dy,
greaterThan(tester.getBottomLeft(titleText).dy));
});
Expand Down
Loading