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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ All notable, user-facing changes to View Source Vibe are documented here.
- Settings → Behavior: **Load lazy content** (off by default) scrolls the page once after it loads — and back to the top — so lazy images and embeds are actually fetched and measured; a banner above the Browser tab shows while this happens. Plus **Disable browser cache** and **Always clean cookies**.
- Settings → Behavior: **Low resource mode** (off by default) for older devices. The Browser and Reader tabs each run their own WebView, and both stay alive at once; in this mode the WebView of a hidden tab is paused (and its media stopped) until its tab is selected again, media in the Browser tab only plays after a tap, Android marks hidden pages as waived renderer priority so the system can reclaim their memory, and both WebViews are suspended while the app is in the background.

- **Structure** tab (web pages in the browser): a wireframe of the rendered page in page proportions, coloured by owner (page, own frame, third party, advertising, social) or by element kind, with the heading outline. Tap a box for its size, owner and source line.

### Improved
- **Size** tab: download size first (Lighthouse-style total byte weight), cache hits counted, and resources that load late (lazy content, ads after scrolling) included. While "Load lazy content" is off, a note explains that totals may be underestimated because lazy resources were never fetched.
- Keyboard shortcuts (Cmd/Ctrl+L focuses the location bar, Cmd/Ctrl+arrow keys switch tabs) and mouse-wheel tab switching on desktop.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ Each page opens into a set of tabs:

- **📱 Read**
- **Source:** HTML, CSS, JS, XML and JSON with syntax highlighting, search, word wrap and line numbers.
- **Structure:** A wireframe of the rendered page, coloured by who owns each box (page, own frames, third parties, ads), with the heading outline.
- **DOM Tree:** Navigate the document structure.
- **Browser:** Built-in browser with tabs ("Surf & View Source"), plus Reader Mode and RSS/Atom feed support.

Expand Down
2 changes: 2 additions & 0 deletions lib/models/app_tab.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ enum AppTab {
media(TabGroup.page, 'Media', Icons.perm_media_outlined, 'media'),
services(TabGroup.page, 'Services', Icons.layers_outlined, 'services'),
reader(TabGroup.page, 'Reader', Icons.chrome_reader_mode, 'reader'),
structure(TabGroup.code, 'Structure', Icons.dashboard_outlined, 'structure'),
domTree(TabGroup.code, 'DOM Tree', Icons.account_tree_outlined, 'dom-tree'),
source(TabGroup.code, 'Source', Icons.code, 'source'),
size(TabGroup.network, 'Size', Icons.scale_outlined, 'page-size'),
Expand Down Expand Up @@ -61,6 +62,7 @@ List<AppTab> visibleTabsFor({
AppTab.privacy =>
metadata,
AppTab.reader => isHtml,
AppTab.structure => browser && isHtml,
AppTab.domTree => isHtmlOrXml,
AppTab.source => true,
AppTab.headers ||
Expand Down
12 changes: 12 additions & 0 deletions lib/models/inspection/page_inspection.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'dart:typed_data';
import 'browser_snapshot.dart';
import 'file_snapshot.dart';
import 'observed.dart';
import 'page_layout.dart';
import 'permission_request.dart';
import 'server_snapshot.dart';

Expand All @@ -14,6 +15,10 @@ const kFreshLoadNotMeasured = Unavailable<BrowserSnapshot>(
const kNoScreenshot =
Unavailable<Uint8List>(UnavailableReason.notApplicable, 'no screenshot');

/// [PageInspection.layout] before the browser measured it.
const kLayoutNotMeasured =
Unavailable<PageLayout>(UnavailableReason.notApplicable, 'not measured yet');

/// What is being inspected.
sealed class InspectionTarget {
const InspectionTarget();
Expand Down Expand Up @@ -76,6 +81,9 @@ class PageInspection {
final Observed<Uint8List> liveScreenshot;
final Observed<Uint8List> freshScreenshot;

/// The boxes of the live page (Structure tab).
final Observed<PageLayout> layout;

/// Native permission requests the page made (all denied), oldest first.
final List<PermissionRequestEvent> permissionRequests;

Expand All @@ -94,6 +102,7 @@ class PageInspection {
this.freshEstimates = const {},
this.liveScreenshot = kNoScreenshot,
this.freshScreenshot = kNoScreenshot,
this.layout = kLayoutNotMeasured,
this.permissionRequests = const [],
});

Expand All @@ -116,6 +125,7 @@ class PageInspection {
freshEstimates = const {},
liveScreenshot = kNoScreenshot,
freshScreenshot = kNoScreenshot,
layout = kLayoutNotMeasured,
permissionRequests = const [];

PageInspection copyWith({
Expand All @@ -131,6 +141,7 @@ class PageInspection {
Map<String, Observed<int>>? freshEstimates,
Observed<Uint8List>? liveScreenshot,
Observed<Uint8List>? freshScreenshot,
Observed<PageLayout>? layout,
List<PermissionRequestEvent>? permissionRequests,
}) =>
PageInspection(
Expand All @@ -150,6 +161,7 @@ class PageInspection {
freshEstimates: freshEstimates ?? this.freshEstimates,
liveScreenshot: liveScreenshot ?? this.liveScreenshot,
freshScreenshot: freshScreenshot ?? this.freshScreenshot,
layout: layout ?? this.layout,
permissionRequests: permissionRequests ?? this.permissionRequests,
);

Expand Down
54 changes: 54 additions & 0 deletions lib/models/inspection/page_layout.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
enum LayoutKind { landmark, frame, heading, media, block }

/// One measured box of the page, in CSS pixels in page space.
class LayoutBlock {
final String tag, role, id, classes, src, text;
final double x, y, width, height;
final int depth, descendants;
final LayoutKind kind;

/// position: fixed or sticky (overlaps the content).
final bool fixed;

const LayoutBlock({
required this.tag,
required this.role,
required this.id,
required this.classes,
required this.src,
required this.text,
required this.x,
required this.y,
required this.width,
required this.height,
required this.depth,
required this.descendants,
required this.kind,
required this.fixed,
});

double get area => width * height;
}

/// The page's measured layout: the viewport, the whole document and the
/// first qualifying boxes ([totalBlocks] counts all of them).
class PageLayout {
final double viewportWidth, viewportHeight, width, height;
final int totalBlocks;
final List<LayoutBlock> blocks;

/// The page had more elements than the script scanned.
final bool scanCapped;

bool get truncated => totalBlocks > blocks.length;

const PageLayout({
required this.viewportWidth,
required this.viewportHeight,
required this.width,
required this.height,
required this.totalBlocks,
required this.blocks,
this.scanCapped = false,
});
}
4 changes: 4 additions & 0 deletions lib/screens/about_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ class AboutScreen extends StatelessWidget {
Icons.code,
'Source viewer: HTML, CSS, JS, XML, JSON with syntax highlighting, search, word wrap and beautify'
),
(
Icons.dashboard_outlined,
'Structure: a wireframe of the rendered page, coloured by who owns each box'
),
(Icons.account_tree_outlined, 'DOM Tree explorer'),
(Icons.chrome_reader_mode, 'Reader mode and RSS/Atom feeds'),
(
Expand Down
2 changes: 2 additions & 0 deletions lib/screens/home_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import 'package:view_source_vibe/widgets/permissions_view.dart';
import 'package:view_source_vibe/widgets/request_timeline_view.dart';
import 'package:view_source_vibe/widgets/sovereignty_view.dart';
import 'package:view_source_vibe/widgets/dom_tree_view.dart';
import 'package:view_source_vibe/widgets/structure_view.dart';
import 'package:view_source_vibe/widgets/keep_alive_wrapper.dart';
import 'package:view_source_vibe/widgets/browser_view.dart';
import 'package:view_source_vibe/widgets/reader_view.dart';
Expand Down Expand Up @@ -421,6 +422,7 @@ class HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
AppTab.media => page(tab, const MediaView()),
AppTab.services => page(tab, const ServicesView()),
AppTab.reader => readerView,
AppTab.structure => page(tab, const StructureView()),
AppTab.domTree => page(tab, const DomTreeView()),
AppTab.source => sourceView,
AppTab.size => page(tab, const PageSizeView()),
Expand Down
7 changes: 4 additions & 3 deletions lib/services/collectors/collector_world.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'package:flutter/foundation.dart' show TargetPlatform;
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

import 'vsv_collect_js.dart';
import 'vsv_layout_js.dart';

/// The JavaScript world the collector runs in. iOS and macOS (WKWebView) have
/// isolated worlds: the page cannot see or alter the collector there. Android
Expand All @@ -11,14 +12,14 @@ ContentWorld? collectorWorld(TargetPlatform platform) =>
? ContentWorld.world(name: 'vsv')
: null;

/// Bootstrap + collector + scroll-through as one document-start user script,
/// in every frame. In an isolated world the fetch/XHR patch is skipped
/// Bootstrap + collector + scroll-through + layout measurement as one
/// document-start user script, in every frame. In an isolated world the fetch/XHR patch is skipped
/// (`__vsv_isolated`): it would only patch the isolated copy of those objects.
UserScript collectorUserScript(TargetPlatform platform) {
final world = collectorWorld(platform);
return UserScript(
source: '${world != null ? 'window.__vsv_isolated = true;\n' : ''}'
'$vsvResourceBootstrapJs\n$vsvCollectJs\n$vsvScrollThroughJs',
'$vsvResourceBootstrapJs\n$vsvCollectJs\n$vsvScrollThroughJs\n$vsvLayoutJs',
injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START,
// Also in iframes: they post their resources (ads, embeds) to the top
// frame, so the page size counts them.
Expand Down
101 changes: 101 additions & 0 deletions lib/services/collectors/layout_payload.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import 'dart:convert';

import '../../models/inspection/observed.dart';
import '../../models/inspection/page_layout.dart';

const _noLayout = Unavailable<PageLayout>(
UnavailableReason.notApplicable, 'the page has no layout');

/// Parses the JSON string returned by `__vsv_layout()`. A non-String result
/// is [Unavailable]; an unparsable one [Failed]; a page without layout
/// (`empty`, or a zero-size document) is [Unavailable] with a reason. A page
/// with a size but no qualifying boxes is [Present] with no blocks.
Observed<PageLayout> parseLayoutPayload(Object? raw, {required Uri pageUrl}) {
if (raw is! String) {
return Unavailable(UnavailableReason.unsupportedPlatform,
'evaluateJavascript returned ${raw == null ? 'null' : raw.runtimeType}, not a String');
}
try {
final m = jsonDecode(raw);
if (m is! Map) return const Failed('layout payload is not an object');
if (m['empty'] == true) return _noLayout;
final blocks = <LayoutBlock>[];
final list = m['blocks'];
if (list is List) {
for (final b in list) {
final block = b is Map ? _block(b, pageUrl) : null;
if (block != null) blocks.add(block);
}
}
final total = _int(m['total']) ?? blocks.length;
final width = _num(m['w']), height = _num(m['h']);
final vw = _num(m['vw']), vh = _num(m['vh']);
if (width == null || height == null || vw == null || vh == null) {
return const Failed('layout payload has no document or viewport size');
}
if (width <= 0 || height <= 0) return _noLayout;
return Present(
PageLayout(
viewportWidth: vw,
viewportHeight: vh,
width: width,
height: height,
totalBlocks: total,
blocks: blocks,
scanCapped: m['scanCapped'] == 1 || m['scanCapped'] == true,
),
source: DataSource.browser);
} catch (e) {
return Failed('$e');
}
}

double? _num(Object? v) => v is num ? v.toDouble() : null;
int? _int(Object? v) => v is num ? v.toInt() : null;

String _str(Object? v) => v is String ? v : '';

LayoutBlock? _block(Map b, Uri pageUrl) {
final kind = switch (b['k']) {
'landmark' => LayoutKind.landmark,
'frame' => LayoutKind.frame,
'heading' => LayoutKind.heading,
'media' => LayoutKind.media,
'block' => LayoutKind.block,
_ => null,
};
final x = _num(b['x']), y = _num(b['y']);
final w = _num(b['w']), h = _num(b['h']);
final depth = _int(b['d']), descendants = _int(b['n']);
if (kind == null ||
x == null ||
y == null ||
w == null ||
h == null ||
depth == null ||
descendants == null) {
return null;
}
var src = _str(b['s']);
if (src.isNotEmpty) {
try {
src = pageUrl.resolve(src).toString();
} catch (_) {}
}
return LayoutBlock(
tag: _str(b['t']),
role: _str(b['r']),
id: _str(b['i']),
classes: _str(b['c']),
src: src,
text: _str(b['tx']),
x: x,
y: y,
width: w,
height: h,
depth: depth,
descendants: descendants,
kind: kind,
fixed: b['f'] == 1 || b['f'] == true,
);
}
95 changes: 95 additions & 0 deletions lib/services/collectors/vsv_layout_js.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// Browser-side JavaScript that measures the page's boxes. Read-only: it reads
// layout (getBoundingClientRect, getComputedStyle) and never scrolls, resizes
// or writes to the page. Keep this ES5-ish (no arrow functions, no let/const).

/// Defines `window.__vsv_layout()`, which returns a JSON string:
/// `{v, vw, vh, w, h, total, scanCapped, blocks: [{t, r, i, c, x, y, w, h, d, n, k, s,
/// f, tx}]}` with coordinates in page space, or `{v: 1, empty: true}` when the
/// document has no layout. `blocks` holds the first 400 qualifying elements
/// in document order; `total` counts all of them. `h` grows to the lowest
/// block (a page whose body scrolls); blocks right of the document width
/// (carousel slides) are skipped; `scanCapped` is 1 when the page had more
/// elements than were scanned.
const String vsvLayoutJs = r'''
(function() {
var MAX_BLOCKS = 400, MAX_SCAN = 20000, MAX_DEPTH = 12;
var LANDMARK_TAGS = {header: 1, nav: 1, main: 1, article: 1, section: 1,
aside: 1, footer: 1, form: 1, dialog: 1};
var LANDMARK_ROLES = {banner: 1, navigation: 1, main: 1, complementary: 1,
contentinfo: 1, search: 1, form: 1, region: 1, dialog: 1};

function kindOf(tag, role, w, h, vArea) {
if (tag === 'iframe') return 'frame';
if (/^h[1-6]$/.test(tag)) return 'heading';
if (LANDMARK_TAGS[tag] === 1 || (role && LANDMARK_ROLES[role] === 1)) return 'landmark';
if (tag === 'video' || tag === 'canvas') return 'media';
if (tag === 'img' && w * h >= 10000) return 'media';
return w * h >= 0.15 * vArea ? 'maybe' : '';
}

function depthOf(el, body) {
var d = 0, p = el;
while (p && p !== body && d < 100) { p = p.parentNode; d++; }
return d;
}

function sourceOf(el, tag) {
var s = '';
if (tag === 'iframe') s = el.src || '';
else if (tag === 'img' || tag === 'video') s = el.currentSrc || el.src || '';
return /^data:/i.test(s) ? '' : s.slice(0, 2000);
}

window.__vsv_layout = function() {
var body = document.body;
var se = document.scrollingElement || document.documentElement;
var docW = se ? se.scrollWidth : 0, docH = se ? se.scrollHeight : 0;
if (!body || !docW || !docH) return JSON.stringify({v: 1, empty: true});
var sx = window.pageXOffset || window.scrollX || 0;
var sy = window.pageYOffset || window.scrollY || 0;
var vw = window.innerWidth || 0, vh = window.innerHeight || 0;
var vArea = vw * vh;
var all = body.getElementsByTagName('*');
var limit = Math.min(all.length, MAX_SCAN);
var blocks = [], total = 0;
for (var i = 0; i < limit; i++) {
var el = all[i];
var tag = String(el.tagName || '').toLowerCase();
var rect = el.getBoundingClientRect();
if (rect.width < 1 || rect.height < 1) continue;
var x = rect.left + sx, y = rect.top + sy;
if (x + rect.width <= 0 || y + rect.height <= 0) continue;
if (x >= docW) continue;
var role = el.getAttribute('role') || '';
var kind = kindOf(tag, role, rect.width, rect.height, vArea);
if (!kind) continue;
var depth = depthOf(el, body);
var n = el.getElementsByTagName('*').length;
if (kind === 'maybe') {
if (n < 20 || depth > MAX_DEPTH) continue;
kind = 'block';
}
var cs = getComputedStyle(el);
if (cs.visibility === 'hidden') continue;
total++;
if (y + rect.height > docH) docH = Math.ceil(y + rect.height);
if (blocks.length >= MAX_BLOCKS) continue;
blocks.push({
t: tag, r: role,
i: String(el.id || '').slice(0, 60),
c: String(el.className && el.className.baseVal !== undefined ? el.className.baseVal : (el.className || ''))
.replace(/^\s+|\s+$/g, '').split(/\s+/).slice(0, 2).join(' ').slice(0, 60),
x: Math.round(x), y: Math.round(y),
w: Math.round(rect.width), h: Math.round(rect.height),
d: depth, n: n, k: kind, s: sourceOf(el, tag),
f: cs.position === 'fixed' || cs.position === 'sticky' ? 1 : 0,
tx: kind === 'heading'
? String(el.textContent || '').replace(/\s+/g, ' ').replace(/^ | $/g, '').slice(0, 80)
: ''
});
}
return JSON.stringify({v: 1, vw: vw, vh: vh, w: docW, h: docH,
total: total, scanCapped: all.length > MAX_SCAN ? 1 : 0, blocks: blocks});
};
})();
''';
Loading
Loading