-
Notifications
You must be signed in to change notification settings - Fork 127
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
base: main
Are you sure you want to change the base?
Minimal screenshot tool. #4074
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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'; | ||
|
@@ -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; | ||
|
@@ -51,6 +57,8 @@ void main() { | |
// Set up the pub metadata for our test packages. | ||
runPubGet(testPackageToolError.path); | ||
runPubGet(_testSkyEnginePackage.path); | ||
|
||
if (isScreenshotDirSet) {} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. intentional? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. But the "then" branch is empty... There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 { | ||
|
@@ -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); | ||
} |
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()); | ||
} | ||
} |
There was a problem hiding this comment.
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?