Skip to content

Minimal screenshot tool. #4074

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
6 changes: 6 additions & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ dev_dependencies:
dart_style: ^3.0.0
lints: ">=5.0.0 <7.0.0"
matcher: ^0.12.15
puppeteer: ^3.18.0
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might need to discuss if we want a non-dart-team dependency here (even if it is a dev-dependency)
cc @szakarias wdyt?

sass: ^1.87.0
shelf: ^1.4.2
shelf_static: ^1.1.3
test: ^1.24.2
test_descriptor: ^2.0.1
test_process: ^2.0.3
Expand All @@ -36,3 +39,6 @@ dev_dependencies:

executables:
dartdoc: null

dependency_overrides:
archive: ^4.0.0
43 changes: 43 additions & 0 deletions test/end2end/dartdoc_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:io';

import 'package:analyzer/file_system/file_system.dart';
import 'package:dartdoc/src/dartdoc.dart' show Dartdoc, DartdocResults;
import 'package:dartdoc/src/dartdoc_options.dart';
Expand All @@ -15,9 +17,13 @@ import 'package:dartdoc/src/package_config_provider.dart';
import 'package:dartdoc/src/package_meta.dart';
import 'package:dartdoc/src/warnings.dart';
import 'package:path/path.dart' as path;
import 'package:shelf/shelf_io.dart';
import 'package:shelf_static/shelf_static.dart';
import 'package:test/test.dart';

import '../src/utils.dart';
import 'screenshot_utils.dart';
import 'test_browser.dart';

final _resourceProvider = pubPackageMetaProvider.resourceProvider;
final _pathContext = _resourceProvider.pathContext;
Expand Down Expand Up @@ -51,6 +57,8 @@ void main() {
// Set up the pub metadata for our test packages.
runPubGet(testPackageToolError.path);
runPubGet(_testSkyEnginePackage.path);

if (isScreenshotDirSet) {}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

intentional?

Copy link
Collaborator Author

@isoos isoos Jul 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. We want to run screenshots only when the output directory is set, regular tests should run without if - at least for now.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But the "then" branch is empty...

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, my bad, mobile view of the code needs more attention.

No, this is not intentional, a leftover, will fix it once I'm with a computer.

});

setUp(() async {
Expand Down Expand Up @@ -203,6 +211,41 @@ void main() {
expect(level2.exists, isTrue);
expect(level2.readAsStringSync(),
contains('<link rel="canonical" href="$prefix/ex/Apple/m.html">'));

if (isScreenshotDirSet) {
final server = await _setupStaticHttpServer(tempDir.path);
final browser = TestBrowser(origin: 'http://localhost:${server.port}');
final allPaths = Directory(tempDir.path)
.listSync(recursive: true, followLinks: true)
.map((f) => path.relative(f.path, from: tempDir.path))
.where((p) => p.endsWith('.html'))
.toList();
final paths = [
'index.html',
'ex/index.html',
'ex/HtmlInjection-class.html',
'ex/IntSet/sum.html',
];
assert(paths.every(allPaths.contains));
try {
await browser.startBrowser();
final session = await browser.createSession();
await session.withPage<void>(fn: (page) async {
for (final p in paths) {
await page.gotoOrigin('/$p');
final prefix = p.replaceAll('.html', '').replaceAll('.', '-');
await page.takeScreenshots(selector: 'body', prefix: prefix);
}
});
} finally {
await server.close();
await browser.close();
}
}
});
}, timeout: Timeout.factor(12));
}

Future<HttpServer> _setupStaticHttpServer(String path) async {
return await serve(createStaticHandler(path), 'localhost', 0);
}
110 changes: 110 additions & 0 deletions test/end2end/screenshot_utils.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:io';

import 'package:path/path.dart' as p;
import 'package:puppeteer/puppeteer.dart';

// Default screen with 16:10 ratio.
final desktopDeviceViewport = DeviceViewport(width: 1280, height: 800);

final _screenshotDir = Platform.environment['SCREENSHOT_DIR'];
final isScreenshotDirSet = _screenshotDir != null && _screenshotDir!.isNotEmpty;

// Set this variable to enable screenshot files to be updated with new takes.
// The default is to throw an exception to prevent accidental overrides from
// separate tests.
final _allowScreeshotUpdates = Platform.environment['SCREENSHOT_UPDATE'] == '1';

// Note: The default values are the last, so we don't need reset
// the original values after taking the screenshots.
final _themes = ['dark', 'light'];
final _viewports = {
'mobile': DeviceViewport(width: 400, height: 800),
'tablet': DeviceViewport(width: 768, height: 1024),
'desktop': desktopDeviceViewport,
};

extension ScreenshotPageExt on Page {
Future<void> writeScreenshotToFile(String path) async {
await File(path).writeAsBytes(await screenshot());
}

/// Takes screenshots **if** `SCREENSHOT_DIR` environment variable is set.
///
/// Iterates over viewports and themes, and generates screenshot files with the
/// following pattern:
/// - `SCREENSHOT_DIR/$prefix-desktop-dark.png`
/// - `SCREENSHOT_DIR/$prefix-desktop-light.png`
/// - `SCREENSHOT_DIR/$prefix-mobile-dark.png`
/// - `SCREENSHOT_DIR/$prefix-mobile-light.png`
/// - `SCREENSHOT_DIR/$prefix-tablet-dark.png`
/// - `SCREENSHOT_DIR/$prefix-tablet-light.png`
Future<void> takeScreenshots({
required String selector,
required String prefix,
}) async {
final handle = await $(selector);
await handle.takeScreenshots(prefix);
}
}

extension ScreenshotElementHandleExt on ElementHandle {
/// Takes screenshots **if** `SCREENSHOT_DIR` environment variable is set.
///
/// Iterates over viewports and themes, and generates screenshot files with the
/// following pattern:
/// - `SCREENSHOT_DIR/$prefix-desktop-dark.png`
/// - `SCREENSHOT_DIR/$prefix-desktop-light.png`
/// - `SCREENSHOT_DIR/$prefix-mobile-dark.png`
/// - `SCREENSHOT_DIR/$prefix-mobile-light.png`
/// - `SCREENSHOT_DIR/$prefix-tablet-dark.png`
/// - `SCREENSHOT_DIR/$prefix-tablet-light.png`
Future<void> takeScreenshots(String prefix) async {
final body = await page.$('body');
final bodyClassAttr = (await body
.evaluate<String>('el => el.getAttribute("class")')) as String;
final bodyClasses = [
...bodyClassAttr.split(' '),
'--ongoing-screenshot',
];

for (final vp in _viewports.entries) {
await page.setViewport(vp.value);

for (final theme in _themes) {
final newClasses = [
...bodyClasses.where((c) => !c.endsWith('-theme')),
'$theme-theme',
];
await body.evaluate<String>('(el, v) => el.setAttribute("class", v)',
args: [newClasses.join(' ')]);

// The presence of the element is verified, continue only if screenshots are enabled.
if (!isScreenshotDirSet) continue;

// Arbitrary delay in the hope that potential ongoing updates complete.
await Future<void>.delayed(Duration(milliseconds: 500));

final path = p.join(_screenshotDir!, '$prefix-${vp.key}-$theme.png');
await _writeScreenshotToFile(path);
}
}

// restore the original body class attributes
await body.evaluate<String>('(el, v) => el.setAttribute("class", v)',
args: [bodyClassAttr]);
}

Future<void> _writeScreenshotToFile(String path) async {
final file = File(path);
final exists = file.existsSync();
if (exists && !_allowScreeshotUpdates) {
throw Exception('Screenshot update is detected in: $path');
}
await file.parent.create(recursive: true);
await File(path).writeAsBytes(await screenshot());
}
}
Loading