diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart index a44ce28..ef2ff24 100644 --- a/lib/screens/home_screen.dart +++ b/lib/screens/home_screen.dart @@ -276,19 +276,11 @@ class HomeScreenState extends State with TickerProviderStateMixin { }); } - Future _handleRefresh() async { - final htmlService = Provider.of(context, listen: false); - await htmlService.refresh(switchToTab: _tabController.index); - } - - Widget _buildRefreshable(Widget child, String tag) { + Widget _buildTabPage(Widget child, String tag) { final page = TabPageWrapper( tag: tag, focusNode: _tabFocusNode(tag), - child: RefreshIndicator( - onRefresh: _handleRefresh, - child: child, - ), + child: child, ); // Analysis tabs get the disclaimer; browser, reader, source and DOM tree // show the page itself. @@ -313,31 +305,28 @@ class HomeScreenState extends State with TickerProviderStateMixin { ); } - Widget _buildScrollableRefreshable(Widget child, String tag, + Widget _buildScrollableTabPage(Widget child, String tag, {bool hasScrollBody = true, bool useSliverToBoxAdapter = false}) { return TabPageWrapper( tag: tag, focusNode: _tabFocusNode(tag), - child: RefreshIndicator( - onRefresh: _handleRefresh, - child: CustomScrollView( - shrinkWrap: false, - physics: const AlwaysScrollableScrollPhysics(), - slivers: [ - if (useSliverToBoxAdapter) - SliverToBoxAdapter(child: child) - else if (hasScrollBody) - SliverFillRemaining( - hasScrollBody: true, - child: child, - ) - else - SliverFillRemaining( - hasScrollBody: false, - child: child, - ), - ], - ), + child: CustomScrollView( + shrinkWrap: false, + physics: const AlwaysScrollableScrollPhysics(), + slivers: [ + if (useSliverToBoxAdapter) + SliverToBoxAdapter(child: child) + else if (hasScrollBody) + SliverFillRemaining( + hasScrollBody: true, + child: child, + ) + else + SliverFillRemaining( + hasScrollBody: false, + child: child, + ), + ], ), ); } @@ -350,7 +339,7 @@ class HomeScreenState extends State with TickerProviderStateMixin { final sourceView = currentFile != null ? KeepAliveWrapper( key: const ValueKey('tab_source'), - child: _buildRefreshable( + child: _buildTabPage( SourceViewer( key: const ValueKey('file_viewer_source'), file: currentFile, @@ -358,7 +347,7 @@ class HomeScreenState extends State with TickerProviderStateMixin { 'source', ), ) - : _buildScrollableRefreshable( + : _buildScrollableTabPage( Center( key: const ValueKey('tab_source_empty'), child: htmlService.isLoading @@ -373,7 +362,7 @@ class HomeScreenState extends State with TickerProviderStateMixin { focusNode: _tabFocusNode('browser'), isBrowserTab: true, child: KeepAliveWrapper( - child: _buildRefreshable( + child: _buildTabPage( (currentFile != null && (currentFile.isUrl || isHtmlOrXml || @@ -398,7 +387,7 @@ class HomeScreenState extends State with TickerProviderStateMixin { final readerView = KeepAliveWrapper( key: const ValueKey('tab_reader'), - child: _buildRefreshable( + child: _buildTabPage( ReaderView( gestureRecognizers: { Factory( @@ -412,7 +401,7 @@ class HomeScreenState extends State with TickerProviderStateMixin { Widget page(AppTab tab, Widget view) => KeepAliveWrapper( key: ValueKey('tab_${tab.tag}'), - child: _buildRefreshable(view, tab.tag)); + child: _buildTabPage(view, tab.tag)); return [ for (final tab in _tabs) diff --git a/lib/services/derive/dom_tree.dart b/lib/services/derive/dom_tree.dart index 1f7bbaa..b6b28ca 100644 --- a/lib/services/derive/dom_tree.dart +++ b/lib/services/derive/dom_tree.dart @@ -213,3 +213,70 @@ DomTree buildDomTreeRecord((String, DomTreeKind) args) => typedef DomTreeBuilder = Future Function( String text, DomTreeKind kind); + +/// What to reveal in the DOM tree: an element found by tag/id/classes plus +/// its occurrence among same-signature elements in document order (most +/// elements have no id, so the signature alone is not always unique). +class DomReveal { + final String tag, id, classes; + final int occurrence; + const DomReveal( + {required this.tag, required this.id, required this.classes, required this.occurrence}); + + @override + bool operator ==(Object other) => + other is DomReveal && + other.tag == tag && + other.id == id && + other.classes == classes && + other.occurrence == occurrence; + + @override + int get hashCode => Object.hash(tag, id, classes, occurrence); +} + +bool _nodeMatches(DomTreeNode n, DomReveal r) { + if (!n.isElement) return false; + if (r.tag.isNotEmpty && n.label.toLowerCase() != r.tag.toLowerCase()) { + return false; + } + if (r.id.isNotEmpty && n.attributes['id'] != r.id) return false; + if (r.classes.isNotEmpty) { + final have = (n.attributes['class'] ?? '').split(RegExp(r'\s+')); + if (!r.classes.split(RegExp(r'\s+')).every(have.contains)) return false; + } + return true; +} + +/// The [r.occurrence]-th (0-based) element in document order that matches +/// [r], searched in the body subtree when there is one (layout blocks come +/// from body); null when there is no such node. +DomTreeNode? findNodeBySignature(List roots, DomReveal r) { + var start = roots; + for (final root in roots) { + for (final c in root.children) { + if (c.label.toLowerCase() == 'body') { + start = [c]; + break; + } + } + } + var n = 0; + DomTreeNode? found; + void walk(List nodes) { + for (final node in nodes) { + if (found != null) return; + if (_nodeMatches(node, r)) { + if (n == r.occurrence) { + found = node; + return; + } + n++; + } + walk(node.children); + } + } + + walk(start); + return found; +} diff --git a/lib/services/derive/structure_view.dart b/lib/services/derive/structure_view.dart index d744ada..64b82f1 100644 --- a/lib/services/derive/structure_view.dart +++ b/lib/services/derive/structure_view.dart @@ -62,13 +62,14 @@ class StructureModel { }); } -const double kMaxWireframeHeight = 6000; +/// The wireframe is never drawn wider than this, even when the page is. +const double kMaxWireframeWidth = 1000; -/// Scale from page pixels to logical pixels: fits [availableWidth], and -/// never lets the drawing exceed [kMaxWireframeHeight]. -double wireframeScale(PageLayout l, double availableWidth) { +/// Scale from page pixels to logical pixels: 1:1, so the drawing is as wide +/// as the page itself, capped at [kMaxWireframeWidth]. +double wireframeScale(PageLayout l) { if (l.width <= 0 || l.height <= 0) return 1; - return math.min(availableWidth / l.width, kMaxWireframeHeight / l.height); + return math.min(1.0, kMaxWireframeWidth / l.width); } /// The smallest block that contains the page point; null when none does. @@ -94,6 +95,53 @@ int? lineOfId(String source, String id) { return '\n'.allMatches(source.substring(0, m.start)).length + 1; } +/// Two blocks have the same signature when tag, id and classes match; the +/// signature plus the occurrence index identifies an element even without a +/// unique id. +bool sameBlockSignature(LayoutBlock a, LayoutBlock b) => + a.tag == b.tag && a.id == b.id && a.classes == b.classes; + +/// 0-based index of [target] among [blocks] (document order) that share its +/// signature. +int occurrenceOfBlock(List blocks, LayoutBlock target) { + var n = 0; + for (final b in blocks) { + if (identical(b, target)) return n; + if (sameBlockSignature(b, target)) n++; + } + return 0; +} + +/// 1-based line of the [occurrence]-th (0-based) opening tag in [source] that +/// matches [tag] and carries [id] (when non-empty) and all of [classes] (when +/// non-empty); null when there is no such tag. +int? lineOfSignature(String source, + {required String tag, String id = '', String classes = '', int occurrence = 0}) { + final tagRe = RegExp('<${RegExp.escape(tag)}\\b', caseSensitive: false); + final idRe = id.isEmpty + ? null + : RegExp('\\bid\\s*=\\s*(?:"${RegExp.escape(id)}"|\'${RegExp.escape(id)}\')'); + final classRe = RegExp('\\bclass\\s*=\\s*(?:"([^"]*)"|\'([^\']*)\')'); + final wanted = classes.isEmpty ? const [] : classes.split(RegExp(r'\s+')); + var n = 0; + for (final m in tagRe.allMatches(source)) { + final gt = source.indexOf('>', m.start); + if (gt < 0) continue; + final tagText = source.substring(m.start, gt); + if (idRe != null && !idRe.hasMatch(tagText)) continue; + if (wanted.isNotEmpty) { + final cm = classRe.firstMatch(tagText); + final have = (cm?.group(1) ?? cm?.group(2) ?? '').split(RegExp(r'\s+')); + if (!wanted.every(have.contains)) continue; + } + if (n == occurrence) { + return '\n'.allMatches(source.substring(0, m.start)).length + 1; + } + n++; + } + return null; +} + const _notInBrowser = Unavailable( UnavailableReason.notApplicable, 'only for pages loaded in the browser'); diff --git a/lib/services/html_service.dart b/lib/services/html_service.dart index 33e7ff3..0227854 100644 --- a/lib/services/html_service.dart +++ b/lib/services/html_service.dart @@ -8,6 +8,7 @@ import 'package:re_highlight/re_highlight.dart'; import 'package:re_editor/re_editor.dart'; import 'dart:async'; import 'dart:io' show HttpClient; +import 'dart:ui' as ui; import 'package:view_source_vibe/utils/code_beautifier.dart'; import 'package:view_source_vibe/utils/descriptive_filename.dart'; import 'package:view_source_vibe/utils/font_url.dart'; @@ -59,6 +60,7 @@ import 'package:view_source_vibe/services/derive/dom_tree.dart'; import 'package:view_source_vibe/services/derive/resource_matching.dart'; import 'package:view_source_vibe/services/derive/source_view.dart'; import 'package:view_source_vibe/services/derive/structure_view.dart'; +import 'package:view_source_vibe/services/screenshot_stitch.dart'; import 'package:view_source_vibe/services/inspection_store.dart'; import 'package:view_source_vibe/services/legacy_browser_adapter.dart'; import 'package:view_source_vibe/services/reader_service.dart'; @@ -463,17 +465,22 @@ class HtmlService extends ChangeNotifier { static const viewerTab = -1; static const sourceTab = -2; static const browserTab = -3; + static const domTreeTab = -4; int resolveTabRequest(int index) => switch (index) { viewerTab => viewerTabIndex, sourceTab => sourceTabIndex, browserTab => browserTabIndex >= 0 ? browserTabIndex : sourceTabIndex, + domTreeTab => domTreeTabIndex >= 0 ? domTreeTabIndex : sourceTabIndex, _ => index, }; /// Reader tab index (-1 when not shown; only HTML pages have it). int get readerTabIndex => tabIndexOf(AppTab.reader); + /// DOM tree tab index (-1 when not shown; only HTML/XML pages have it). + int get domTreeTabIndex => tabIndexOf(AppTab.domTree); + /// Source tab index; Source is always shown. int get sourceTabIndex => tabIndexOf(AppTab.source); @@ -989,6 +996,25 @@ class HtmlService extends ChangeNotifier { return text is Present ? lineOfId(text.value, id) : null; } + /// 1-based line of [s]'s opening tag in the Source tab's document: by id + /// when it has one, else by tag/classes plus its occurrence in document + /// order. Null when the document is unknown or has no matching tag. + int? sourceLineOfBlock(StructureBlock s) { + final text = sourceView.text; + if (text is! Present) return null; + final b = s.block; + if (b.id.isNotEmpty) { + final byId = lineOfId(text.value, b.id); + if (byId != null) return byId; + } + final layout = store.current.layout; + final blocks = + layout is Present ? layout.value.blocks : const []; + return lineOfSignature(text.value, + tag: b.tag, id: b.id, classes: b.classes, + occurrence: occurrenceOfBlock(blocks, b)); + } + Observed? _timelineModel; ({ InspectionTarget target, @@ -1649,6 +1675,49 @@ class HtmlService extends ChangeNotifier { notifyListeners(); } + /// Switches to the Source tab without selecting a line. + void showSourceTab() { + _requestedTabIndex = HtmlService.sourceTab; + notifyListeners(); + } + + DomReveal? _pendingDomReveal; + + /// The node the DOM tree tab should expand and scroll to when it next + /// builds; null when there is no pending reveal. + DomReveal? get pendingDomReveal => _pendingDomReveal; + + /// Switches to the DOM tree tab and scrolls to the node matching [r]. + void revealDomSignature(DomReveal r) { + _pendingDomReveal = r; + _requestedTabIndex = HtmlService.domTreeTab; + notifyListeners(); + } + + /// Switches to the DOM tree tab and scrolls to the element [s] represents, + /// matched by tag/id/classes (most elements have no id). + void revealDomBlock(StructureBlock s) { + final layout = store.current.layout; + final blocks = layout is Present ? layout.value.blocks : const []; + revealDomSignature(DomReveal( + tag: s.block.tag, + id: s.block.id, + classes: s.block.classes, + occurrence: occurrenceOfBlock(blocks, s.block), + )); + } + + /// Switches to the DOM tree tab and scrolls to the element with [id]. + void revealDomNode(String id) => + revealDomSignature(DomReveal(tag: '', id: id, classes: '', occurrence: 0)); + + /// The DOM tree tab handled the pending reveal. + void consumeDomReveal() { + if (_pendingDomReveal == null) return; + _pendingDomReveal = null; + notifyListeners(); + } + /// The UI handled the tab request. Listeners are told (outside of build), /// so a stale request does not linger in their selected state. void consumeTabSwitchRequest() { @@ -4445,6 +4514,67 @@ Technical details: $message'''; store.applyLiveScreenshot(gen, _screenshotOf(bytes)); } + /// Wider screenshot settings for the stitched full-page capture. + static final _fullPageScreenshotCfg = ScreenshotConfiguration( + compressFormat: CompressFormat.JPEG, quality: 70, snapshotWidth: 480); + + /// Max viewport shots stitched into a full-page screenshot (very tall + /// pages are clipped at this many screens). + static const _maxFullPageShots = 50; + + Observed _fullPageShot = kNoScreenshot; + + /// Full-page screenshot of the live browser (background of the Structure + /// tab); Unavailable until captured or when the platform gives none. + Observed get fullPageScreenshot => _fullPageShot; + + /// Scrolls the live browser through the page once, taking a screenshot per + /// viewport, stitches them into one full-page image and restores the scroll + /// position. Best effort: on any failure the viewport thumbnail remains. + Future _captureFullPageScreenshot(int gen) async { + final c = activeWebViewController; + if (c == null || _disposed) return; + bool stale() => _disposed || gen != store.current.generation; + try { + final dims = await c.evaluateJavascript( + source: '([Math.ceil(Math.max(document.scrollingElement ? ' + 'document.scrollingElement.scrollHeight : 0, document.body ? ' + 'document.body.scrollHeight : 0)), window.innerHeight, ' + 'window.innerWidth, Math.round(window.scrollY)]).join(",")'); + final parts = (dims?.toString() ?? '').split(','); + if (parts.length < 4) return; + final pageH = double.tryParse(parts[0]) ?? 0; + final vh = double.tryParse(parts[1]) ?? 0; + final iw = double.tryParse(parts[2]) ?? 0; + final oldY = double.tryParse(parts[3]) ?? 0; + if (pageH <= 0 || vh <= 0 || iw <= 0) return; + final shots = []; + final steps = (pageH / vh).ceil(); + for (var i = 0; i < steps && i < _maxFullPageShots; i++) { + if (stale()) return; + await c.scrollTo(x: 0, y: (i * vh).round()); + // Let the new scroll position render before capturing. + await Future.delayed(const Duration(milliseconds: 120)); + final shot = await c.takeScreenshot( + screenshotConfiguration: _fullPageScreenshotCfg); + if (shot != null && shot.isNotEmpty) shots.add(shot); + } + await c.scrollTo(x: 0, y: oldY.round()); + if (stale() || shots.isEmpty) return; + final image = await stitchScreenshots(shots, + pageHeight: pageH, viewportWidth: iw); + if (image == null) return; + final bytes = await image.toByteData(format: ui.ImageByteFormat.png); + image.dispose(); + if (stale() || bytes == null) return; + _fullPageShot = + Present(bytes.buffer.asUint8List(), source: DataSource.browser); + notifyListeners(); + } catch (e) { + debugPrint('Full-page screenshot unavailable: $e'); + } + } + /// Measures the live page's boxes for the Structure tab. Dropped when the /// user navigates meanwhile. Future collectLayout() async { @@ -4734,6 +4864,7 @@ Technical details: $message'''; void _scheduleBrowserRefreshes(int gen, String url, Uri uri) { _cancelBrowserRefreshes(); final policy = _browserPoll; + _fullPageShot = kNoScreenshot; _captureLiveScreenshot(gen).ignore(); if (!policy.enabled) { store.markBrowserSettled(gen); @@ -4783,6 +4914,7 @@ Technical details: $message'''; } store.markBrowserSettled(gen); _captureLiveScreenshot(gen).ignore(); + _captureFullPageScreenshot(gen).ignore(); collectLayout().ignore(); } else { next(); diff --git a/lib/services/screenshot_stitch.dart b/lib/services/screenshot_stitch.dart new file mode 100644 index 0000000..e249f69 --- /dev/null +++ b/lib/services/screenshot_stitch.dart @@ -0,0 +1,49 @@ +import 'dart:typed_data'; +import 'dart:ui' + show Canvas, FilterQuality, Image, Paint, PictureRecorder, Rect, + instantiateImageCodec; + +/// Stitches viewport screenshots taken while scrolling through a page into +/// one full-page image. [shots] are the screenshots in top-to-bottom order, +/// [pageHeight] and [viewportWidth] the page's CSS dimensions; the result's +/// width is the first shot's width and its height is the page height at that +/// scale. Returns null when no shot decodes. +Future stitchScreenshots( + List shots, { + required double pageHeight, + required double viewportWidth, +}) async { + final images = []; + for (final shot in shots) { + try { + final codec = await instantiateImageCodec(shot); + final frame = await codec.getNextFrame(); + codec.dispose(); + images.add(frame.image); + } catch (_) { + // Skip a shot that does not decode. + } + } + if (images.isEmpty || viewportWidth <= 0) return null; + final w = images.first.width.toDouble(); + final targetH = + (pageHeight * w / viewportWidth).clamp(1.0, 100000.0).ceilToDouble(); + final recorder = PictureRecorder(); + final canvas = Canvas(recorder); + canvas.clipRect(Rect.fromLTWH(0, 0, w, targetH)); + var y = 0.0; + for (final img in images) { + canvas.drawImageRect( + img, + Rect.fromLTWH(0, 0, img.width.toDouble(), img.height.toDouble()), + Rect.fromLTWH(0, y, w, img.height.toDouble()), + Paint()..filterQuality = FilterQuality.low, + ); + y += img.height; + img.dispose(); + } + final picture = recorder.endRecording(); + final out = await picture.toImage(w.ceil(), targetH.ceil()); + picture.dispose(); + return out; +} diff --git a/lib/widgets/dom_tree_view.dart b/lib/widgets/dom_tree_view.dart index 16c76cf..932b0c2 100644 --- a/lib/widgets/dom_tree_view.dart +++ b/lib/widgets/dom_tree_view.dart @@ -24,6 +24,22 @@ class _DomTreeViewState extends State { TreeController? _treeController; DomTree? _controllerTree; + /// The reveal handled from the Structure tab and the node it matched; the + /// node's row carries [_revealKey] so the view can scroll to it and is + /// highlighted like a selected line in the Source view. + DomReveal? _handledReveal; + DomTreeNode? _revealedNode; + final GlobalKey _revealKey = GlobalKey(); + + /// True while a reveal scroll is in progress: the tree then builds all + /// expanded rows (large finite cacheExtent) so the target row exists and + /// can be scrolled to precisely. + bool _revealScrolling = false; + + /// Cache extent used during a reveal scroll: ~30k rows; finite because an + /// infinite extent breaks the sliver's semantics rect. + static const double _revealCacheExtent = 1000000; + /// A controller for [tree]: root expanded, plus head/body/channel. TreeController _controllerFor(DomTree tree) { if (identical(tree, _controllerTree)) return _treeController!; @@ -31,9 +47,22 @@ class _DomTreeViewState extends State { if (old != null) { WidgetsBinding.instance.addPostFrameCallback((_) => old.dispose()); } + // Parent map so expandAncestors can walk up to a revealed node. + final parents = {}; + void walk(DomTreeNode node) { + for (final child in node.children) { + parents[child] = node; + walk(child); + } + } + + for (final root in tree.roots) { + walk(root); + } final controller = TreeController( roots: tree.roots, childrenProvider: (DomTreeNode node) => node.children, + parentProvider: (DomTreeNode node) => parents[node], ); if (tree.roots.isNotEmpty) { final root = tree.roots.first; @@ -101,6 +130,7 @@ class _DomTreeViewState extends State { final muted = TextStyle(fontSize: 11, color: theme.colorScheme.onSurfaceVariant); final controller = _controllerFor(tree); + _handlePendingReveal(context, tree, controller); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -117,10 +147,14 @@ class _DomTreeViewState extends State { primary: true, physics: const AlwaysScrollableScrollPhysics(), padding: EdgeInsets.only(bottom: bottomInset), + cacheExtent: _revealScrolling ? _revealCacheExtent : null, treeController: controller, nodeBuilder: (BuildContext context, TreeEntry entry) { + final revealed = identical(entry.node, _revealedNode); return DomTreeTile( + key: revealed ? _revealKey : null, + highlighted: revealed, entry: entry, onTap: () => controller.toggleExpansion(entry.node), ); @@ -132,6 +166,54 @@ class _DomTreeViewState extends State { ); } + /// Expands the ancestors of the pending reveal (from the Structure tab) and + /// scrolls its row into view. Elements without an id are matched by + /// tag/classes plus their occurrence in document order. + void _handlePendingReveal(BuildContext context, DomTree tree, + TreeController controller) { + final pending = + context.select((s) => s.pendingDomReveal); + if (pending == null || identical(pending, _handledReveal)) return; + _handledReveal = pending; + final service = context.read(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + final node = findNodeBySignature(tree.roots, pending); + if (node != null) { + _revealedNode = node; + // Build all expanded rows first, so the target row exists and the + // scroll can be exact (slivers otherwise build lazily). + setState(() => _revealScrolling = true); + controller.expandAncestors(node); + // Open the node itself one level, so its children are visible too. + controller.expand(node); + } + service.consumeDomReveal(); + if (node == null) return; + var attempts = 0; + void scroll() { + if (!mounted) return; + final ctx = _revealKey.currentContext; + if (ctx != null) { + Scrollable.ensureVisible(ctx, + duration: const Duration(milliseconds: 250), alignment: 0.3); + setState(() => _revealScrolling = false); + return; + } + if (++attempts < 20) { + WidgetsBinding.instance.addPostFrameCallback((_) => scroll()); + } else { + setState(() => _revealScrolling = false); + } + } + + // Wait for the expanded rows (with the reveal key) to be built. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) scroll(); + }); + }); + } + /// No text to parse: show why (the tree never shows another document). Widget _statusFor(BuildContext context, SourceView view, bool loading) { final theme = Theme.of(context); @@ -166,10 +248,15 @@ class DomTreeTile extends StatelessWidget { final TreeEntry entry; final VoidCallback onTap; + /// True for the node revealed from the Structure tab: its row is + /// highlighted like a selected line in the Source view. + final bool highlighted; + const DomTreeTile({ super.key, required this.entry, required this.onTap, + this.highlighted = false, }); /// Get color for specific tags @@ -307,7 +394,17 @@ class DomTreeTile extends StatelessWidget { color: Colors.grey, thickness: 1, ), - child: InkWell( + child: Container( + decoration: highlighted + ? BoxDecoration( + color: Theme.of(context) + .colorScheme + .primaryContainer + .withValues(alpha: 0.55), + borderRadius: BorderRadius.circular(4), + ) + : null, + child: InkWell( onTap: entry.hasChildren ? onTap : null, onLongPress: () { Clipboard.setData(ClipboardData(text: node.content)); @@ -423,6 +520,7 @@ class DomTreeTile extends StatelessWidget { ], ), ), + ), ), ); } diff --git a/lib/widgets/structure_painter.dart b/lib/widgets/structure_painter.dart index 3f4ae2b..e2fcd1d 100644 --- a/lib/widgets/structure_painter.dart +++ b/lib/widgets/structure_painter.dart @@ -1,3 +1,4 @@ +import 'dart:math' as math; import 'dart:ui' as ui; import 'package:material_ui/material_ui.dart'; @@ -51,17 +52,25 @@ class StructurePalette { } /// Draws the page's blocks in page proportions: [scale] logical px per CSS px. +/// When [background] is set (a screenshot of the page), it is drawn opaque +/// behind the blocks — over the whole drawing when [backgroundFullPage], else +/// over the first screen only. The blocks themselves are drawn 75% +/// transparent so the screenshot shows through. class StructurePainter extends CustomPainter { final StructureModel model; final double scale; final StructureColoring coloring; final ColorScheme scheme; + final ui.Image? background; + final bool backgroundFullPage; StructurePainter({ required this.model, required this.scale, required this.coloring, required this.scheme, + this.background, + this.backgroundFullPage = false, }); static const double minLabelWidth = 60; @@ -78,6 +87,21 @@ class StructurePainter extends CustomPainter { ..style = PaintingStyle.stroke ..color = scheme.outlineVariant); + // The screenshot is the background, fully opaque: the whole page when we + // have a full-page capture, else the first screen only. + if (background != null) { + final bgHeight = backgroundFullPage + ? size.height + : math.min(model.layout.viewportHeight * scale, size.height); + canvas.drawImageRect( + background!, + Rect.fromLTWH( + 0, 0, background!.width.toDouble(), background!.height.toDouble()), + Rect.fromLTWH(0, 0, size.width, bgHeight), + Paint()..filterQuality = FilterQuality.medium, + ); + } + final fill = Paint()..style = PaintingStyle.fill; final outline = Paint() ..style = PaintingStyle.stroke @@ -88,7 +112,8 @@ class StructurePainter extends CustomPainter { final b = s.block; final rect = Rect.fromLTWH( b.x * scale, b.y * scale, b.width * scale, b.height * scale); - fill.color = palette.of(s, coloring).withValues(alpha: 0.55); + // 75% transparent: the screenshot shows through the structure overlay. + fill.color = palette.of(s, coloring).withValues(alpha: 0.20); canvas.drawRect(rect, fill); if (b.fixed) { _dashedRect(canvas, rect, outline); @@ -149,5 +174,7 @@ class StructurePainter extends CustomPainter { !identical(old.model, model) || old.scale != scale || old.coloring != coloring || - old.scheme != scheme; + old.scheme != scheme || + old.background != background || + old.backgroundFullPage != backgroundFullPage; } diff --git a/lib/widgets/structure_view.dart b/lib/widgets/structure_view.dart index 22bc117..5648030 100644 --- a/lib/widgets/structure_view.dart +++ b/lib/widgets/structure_view.dart @@ -1,3 +1,6 @@ +import 'dart:typed_data'; +import 'dart:ui' as ui; + import 'package:material_ui/material_ui.dart'; import 'package:provider/provider.dart'; import 'package:view_source_vibe/models/inspection/observed.dart'; @@ -20,12 +23,73 @@ class StructureView extends StatefulWidget { class _StructureViewState extends State { StructureColoring _coloring = StructureColoring.owner; + /// The live browser's screenshot, decoded, drawn behind the wireframe. + ui.Image? _background; + Uint8List? _backgroundBytes; + + /// Whether [_background] covers the whole page (true) or only the first + /// screen (false). + bool _backgroundFullPage = false; + + @override + void dispose() { + _background?.dispose(); + super.dispose(); + } + + /// Decodes [bytes] into [_background]; a new screenshot replaces the old. + Future _loadBackground(Uint8List bytes) async { + try { + final codec = await ui.instantiateImageCodec(bytes); + final frame = await codec.getNextFrame(); + codec.dispose(); + final image = frame.image; + if (!mounted || !identical(bytes, _backgroundBytes)) { + image.dispose(); + return; + } + setState(() { + _background?.dispose(); + _background = image; + }); + } catch (_) { + // Not a decodable image: draw the wireframe without a background. + } + } + @override Widget build(BuildContext context) { final state = context .select>((s) => s.structureView); final hasBrowser = context .select((s) => s.store.current.target is UrlTarget); + final fullShot = context.select>( + (s) => s.fullPageScreenshot); + final liveShot = context.select>( + (s) => s.store.current.liveScreenshot); + // Prefer the full-page screenshot; fall back to the viewport thumbnail. + final useFull = fullShot is Present; + final shot = useFull ? fullShot : liveShot; + final bytes = shot is Present ? shot.value : null; + if (!identical(bytes, _backgroundBytes)) { + _backgroundBytes = bytes; + final b = bytes; + final full = useFull; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + _backgroundFullPage = full; + if (b == null) { + if (_background != null) { + setState(() { + _background?.dispose(); + _background = null; + }); + } + } else { + _loadBackground(b); + } + }); + } return switch (state) { Pending(:final detail) => Center( child: Column( @@ -76,6 +140,7 @@ class _StructureViewState extends State { Widget _model(BuildContext context, StructureModel model) { final scheme = Theme.of(context).colorScheme; final palette = StructurePalette(scheme); + final scale = wireframeScale(model.layout); return SingleChildScrollView( physics: const AlwaysScrollableScrollPhysics(), padding: const EdgeInsets.all(16), @@ -100,31 +165,6 @@ class _StructureViewState extends State { ), ), const SizedBox(height: 8), - Row( - children: [ - Expanded( - child: SegmentedButton( - showSelectedIcon: false, - segments: const [ - ButtonSegment( - value: StructureColoring.owner, label: Text('Owner')), - ButtonSegment( - value: StructureColoring.element, - label: Text('Element')), - ], - selected: {_coloring}, - onSelectionChanged: (s) => - setState(() => _coloring = s.first), - ), - ), - IconButton( - tooltip: 'Measure again', - icon: const Icon(Icons.refresh), - onPressed: () => context.read().collectLayout(), - ), - ], - ), - const SizedBox(height: 8), Wrap( spacing: 12, runSpacing: 4, @@ -145,24 +185,38 @@ class _StructureViewState extends State { ], ), const SizedBox(height: 12), + // The wireframe is as wide as the page (max 1000 px), centred in + // the tab; when that is wider than the tab it scrolls horizontally. LayoutBuilder(builder: (context, constraints) { - final scale = wireframeScale(model.layout, constraints.maxWidth); - return GestureDetector( - onTapUp: (d) => _openDetails( - context, - blockAt(model, d.localPosition.dx / scale, - d.localPosition.dy / scale)), - child: Semantics( - label: 'Page wireframe, ${model.blocks.length} blocks', - child: CustomPaint( - key: const Key('structure-wireframe'), - size: Size( - model.layout.width * scale, model.layout.height * scale), - painter: StructurePainter( - model: model, - scale: scale, - coloring: _coloring, - scheme: scheme), + final w = model.layout.width * scale; + final boxWidth = + w < constraints.maxWidth ? constraints.maxWidth : w; + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SizedBox( + width: boxWidth, + child: Center( + child: GestureDetector( + onTapUp: (d) => _openDetails( + context, + blockAt(model, d.localPosition.dx / scale, + d.localPosition.dy / scale)), + child: Semantics( + label: 'Page wireframe, ${model.blocks.length} blocks', + child: CustomPaint( + key: const Key('structure-wireframe'), + size: Size(model.layout.width * scale, + model.layout.height * scale), + painter: StructurePainter( + model: model, + scale: scale, + coloring: _coloring, + scheme: scheme, + background: _background, + backgroundFullPage: _backgroundFullPage), + ), + ), + ), ), ), ); @@ -178,6 +232,31 @@ class _StructureViewState extends State { padding: EdgeInsets.only(left: (h.level - 1) * 16.0, top: 2), child: Text(h.text.isEmpty ? '(empty h${h.level})' : h.text), ), + const SizedBox(height: 16), + Row( + children: [ + Expanded( + child: SegmentedButton( + showSelectedIcon: false, + segments: const [ + ButtonSegment( + value: StructureColoring.owner, label: Text('Owner')), + ButtonSegment( + value: StructureColoring.element, + label: Text('Element')), + ], + selected: {_coloring}, + onSelectionChanged: (s) => + setState(() => _coloring = s.first), + ), + ), + IconButton( + tooltip: 'Measure again', + icon: const Icon(Icons.refresh), + onPressed: () => context.read().collectLayout(), + ), + ], + ), ], ), ); @@ -187,7 +266,7 @@ class _StructureViewState extends State { if (s == null) return; final service = context.read(); final b = s.block; - final line = b.id.isEmpty ? null : service.sourceLineOfId(b.id); + final line = service.sourceLineOfBlock(s); String n(double v) => v.round().toString(); showModalBottomSheet( context: context, @@ -208,16 +287,33 @@ class _StructureViewState extends State { if (b.src.isNotEmpty) Text('Source: ${b.src}'), Text('Contains ${b.descendants} elements'), if (b.fixed) const Text('fixed'), - if (line != null) ...[ - const SizedBox(height: 8), - TextButton( - onPressed: () { - Navigator.of(sheet).pop(); - service.revealSourceLine(line); - }, - child: const Text('Show in source'), - ), - ], + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 4, + children: [ + TextButton.icon( + onPressed: () { + Navigator.of(sheet).pop(); + service.revealDomBlock(s); + }, + icon: const Icon(Icons.account_tree_outlined), + label: const Text('Open in DOM tree'), + ), + TextButton.icon( + onPressed: () { + Navigator.of(sheet).pop(); + if (line != null) { + service.revealSourceLine(line); + } else { + service.showSourceTab(); + } + }, + icon: const Icon(Icons.code), + label: const Text('Open in source'), + ), + ], + ), ], ), ), diff --git a/test/derive/structure_view_test.dart b/test/derive/structure_view_test.dart index b897e9c..206f9de 100644 --- a/test/derive/structure_view_test.dart +++ b/test/derive/structure_view_test.dart @@ -154,10 +154,41 @@ void main() { expect(m.blocks.map((b) => b.block.area), [250000, 100, 810000]); }); - test('wireframeScale', () { - expect(wireframeScale(layout(w: 400, h: 2000), 400), 1.0); - expect(wireframeScale(layout(w: 1200, h: 2400), 400), closeTo(1 / 3, 1e-9)); - expect(wireframeScale(layout(w: 400, h: 100000), 400), closeTo(0.06, 1e-9)); + test('wireframeScale: page width, capped at 1000', () { + expect(wireframeScale(layout(w: 400, h: 2000)), 1.0); + expect(wireframeScale(layout(w: 1000, h: 2000)), 1.0); + expect(wireframeScale(layout(w: 1200, h: 2400)), closeTo(1000 / 1200, 1e-9)); + // A very tall page no longer shrinks the drawing below page width. + expect(wireframeScale(layout(w: 400, h: 100000)), 1.0); + }); + + test('occurrenceOfBlock counts same-signature blocks in document order', () { + final blocks = [ + block('p', classes: 'a'), + block('div'), + block('p', classes: 'a'), + block('p', classes: 'b'), + block('p', classes: 'a', id: 'x'), + ]; + expect(occurrenceOfBlock(blocks, blocks[0]), 0); + expect(occurrenceOfBlock(blocks, blocks[2]), 1); + expect(occurrenceOfBlock(blocks, blocks[3]), 0); // different classes + expect(occurrenceOfBlock(blocks, blocks[4]), 0); // different id + expect(occurrenceOfBlock(blocks, block('p', classes: 'a')), 0); + }); + + test('lineOfSignature picks the occurrence-th matching opening tag', () { + const src = '\n\n

one

\n

two

' + '\n

three

\n\n'; + expect(lineOfSignature(src, tag: 'p', classes: 'a', occurrence: 0), 3); + expect(lineOfSignature(src, tag: 'p', classes: 'a', occurrence: 1), 4); + expect(lineOfSignature(src, tag: 'p', id: 'x', occurrence: 0), 4); + expect(lineOfSignature(src, tag: 'p', classes: 'b', occurrence: 0), 5); + expect(lineOfSignature(src, tag: 'p', occurrence: 2), 5); + expect(lineOfSignature(src, tag: 'p', id: 'nope', occurrence: 0), isNull); + expect(lineOfSignature(src, tag: 'table', occurrence: 0), isNull); + // Class attribute with single quotes also matches. + expect(lineOfSignature("

z

", tag: 'p', classes: 'a'), 1); }); test('blockAt picks the smallest box under the point', () { diff --git a/test/services/screenshot_stitch_test.dart b/test/services/screenshot_stitch_test.dart new file mode 100644 index 0000000..c3ea8ba --- /dev/null +++ b/test/services/screenshot_stitch_test.dart @@ -0,0 +1,61 @@ +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:view_source_vibe/services/screenshot_stitch.dart'; + +Future solidPng(int w, int h, ui.Color color) async { + final recorder = ui.PictureRecorder(); + final canvas = ui.Canvas(recorder); + canvas.drawRect( + ui.Rect.fromLTWH(0, 0, w.toDouble(), h.toDouble()), ui.Paint()..color = color); + final img = await recorder.endRecording().toImage(w, h); + final bytes = await img.toByteData(format: ui.ImageByteFormat.png); + img.dispose(); + return bytes!.buffer.asUint8List(); +} + +void main() { + test('stitchScreenshots stacks the shots and sizes to the page height', + () async { + final top = await solidPng(100, 50, const ui.Color(0xFF0000FF)); + final bottom = await solidPng(100, 50, const ui.Color(0xFF00FF00)); + // Viewport 100 CSS px wide, shots 100 px wide (scale 1), page 200 px tall. + final img = await stitchScreenshots([top, bottom], + pageHeight: 200, viewportWidth: 100); + expect(img, isNotNull); + expect(img!.width, 100); + expect(img.height, 200); + + final raw = await img.toByteData(format: ui.ImageByteFormat.rawStraightRgba); + final px = raw!.buffer.asUint8List(); + int at(int x, int y) => (y * img.width + x) * 4; + // Top shot in the top half, bottom shot below it. + expect(px[at(10, 10) + 2], 0xFF); // blue channel of the red... top is blue + expect(px[at(10, 10)], 0x00); + expect(px[at(10, 60) + 1], 0xFF); // green shot below + img.dispose(); + }); + + test('stitchScreenshots scales the page height to the shot width', + () async { + final shot = await solidPng(200, 100, const ui.Color(0xFFFFFFFF)); + // Viewport 400 CSS px wide, shot 200 px wide (scale 0.5), page 800 tall. + final img = await stitchScreenshots([shot, shot], + pageHeight: 800, viewportWidth: 400); + expect(img, isNotNull); + expect(img!.width, 200); + expect(img.height, 400); + img.dispose(); + }); + + test('stitchScreenshots returns null without decodable shots', () async { + expect( + await stitchScreenshots([], pageHeight: 100, viewportWidth: 100), + isNull); + expect( + await stitchScreenshots([Uint8List.fromList([1, 2, 3])], + pageHeight: 100, viewportWidth: 100), + isNull); + }); +} diff --git a/test/widgets/dom_tree_data_test.dart b/test/widgets/dom_tree_data_test.dart index 7797e75..aa6e747 100644 --- a/test/widgets/dom_tree_data_test.dart +++ b/test/widgets/dom_tree_data_test.dart @@ -61,6 +61,35 @@ void main() { test('empty text is an empty tree', () { expect(html('').roots, isEmpty); }); + + test('findNodeBySignature matches by tag/classes and occurrence', () { + final t = html('

one

' + '

two

three

' + ''); + DomTreeNode? n(DomReveal r) => findNodeBySignature(t.roots, r); + expect( + n(const DomReveal(tag: 'p', id: '', classes: 'a', occurrence: 0)) + ?.content, + contains('one')); + expect( + n(const DomReveal(tag: 'p', id: '', classes: 'a', occurrence: 1)) + ?.content, + contains('two')); + expect( + n(const DomReveal(tag: 'p', id: '', classes: 'b', occurrence: 0)) + ?.content, + contains('three')); + expect( + n(const DomReveal(tag: '', id: 'missing', classes: '', occurrence: 0)), + isNull); + // Head elements are not matched: the search runs in the body subtree. + final withHead = + html('t

x

'); + expect( + findNodeBySignature(withHead.roots, + const DomReveal(tag: 'title', id: '', classes: '', occurrence: 0)), + isNull); + }); }); group('DomTreeView', () { @@ -110,6 +139,56 @@ void main() { expect(service.domTreeBuilds, 2); }); + testWidgets('a pending reveal scrolls the node into view and highlights it', + (tester) async { + // Tall enough that the target sits far below the 800x600 test surface. + final fillers = List.generate(200, (i) => '
filler $i
').join(); + final deep = + '$fillers

x

'; + final p = fullPage().copyWith( + browser: browser(browserSnapshot(url: fullPageUrl, dom: deep))); + await show(tester, p); + // Collapsed: the deep node's row is not built yet. + expect(find.textContaining('id="deep"'), findsNothing); + + service.revealDomNode('wrap'); + await tester.pump(); + await tester.pumpAndSettle(); + expect(service.pendingDomReveal, isNull); + expect(service.requestedTabIndex, HtmlService.domTreeTab); + final row = find.textContaining('id="wrap"'); + expect(row, findsOneWidget); + // Scrolled into view (the test surface is 800x600). + final pos = tester.getTopLeft(row); + expect(pos.dy, greaterThanOrEqualTo(0)); + expect(pos.dy, lessThan(600)); + // The node is opened one level: its child is visible too. + expect(find.textContaining('id="deep"'), findsOneWidget); + // Highlighted like a selected line in the Source view. + expect( + find.byWidgetPredicate((w) => w is DomTreeTile && w.highlighted), + findsOneWidget); + }); + + testWidgets('a reveal without id matches by signature and scrolls to it', + (tester) async { + const doc = '

one

' + '

two

'; + final p = fullPage().copyWith( + browser: browser(browserSnapshot(url: fullPageUrl, dom: doc))); + await show(tester, p); + // Only the first matching

is visible; the one in the collapsed + // div is not built yet. + expect(find.textContaining('class="target"'), findsOneWidget); + + service.revealDomSignature( + const DomReveal(tag: 'p', id: '', classes: 'target', occurrence: 1)); + await tester.pump(); + await tester.pumpAndSettle(); + expect(service.pendingDomReveal, isNull); + expect(find.textContaining('class="target"'), findsNWidgets(2)); + }); + testWidgets('server HTML still pending: a message, no stale tree', (tester) async { final p = fullPage(); diff --git a/test/widgets/structure_data_test.dart b/test/widgets/structure_data_test.dart index f975d76..0c58b69 100644 --- a/test/widgets/structure_data_test.dart +++ b/test/widgets/structure_data_test.dart @@ -91,6 +91,30 @@ void main() { expect(find.textContaining('1000 × 100 px'), findsOneWidget); }); + testWidgets('the sheet opens the DOM tree at the tapped element', + (tester) async { + await show(tester, pageWithLayout()); + await tester.tapAt(wireframeOrigin(tester) + const Offset(20, 20)); + await tester.pumpAndSettle(); + expect(find.text('Open in DOM tree'), findsOneWidget); + expect(find.text('Open in source'), findsOneWidget); + await tester.tap(find.text('Open in DOM tree')); + await tester.pumpAndSettle(); + expect(service.pendingDomReveal?.id, 'top'); + expect(service.pendingDomReveal?.tag, 'header'); + expect(service.requestedTabIndex, HtmlService.domTreeTab); + }); + + testWidgets('the sheet opens the source view at the tapped element', + (tester) async { + await show(tester, pageWithLayout()); + await tester.tapAt(wireframeOrigin(tester) + const Offset(20, 20)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Open in source')); + await tester.pumpAndSettle(); + expect(service.requestedTabIndex, HtmlService.sourceTab); + }); + testWidgets('without a browser the tab says why', (tester) async { await show(tester, localFile()); expect(find.textContaining('only for pages loaded in the browser'),