diff --git a/flow-typed/npm/pngjs_v7.x.x.js b/flow-typed/npm/pngjs_v7.x.x.js
new file mode 100644
index 000000000000..39ad8a87b324
--- /dev/null
+++ b/flow-typed/npm/pngjs_v7.x.x.js
@@ -0,0 +1,17 @@
+/**
+ * @flow strict
+ * @format
+ */
+
+declare module 'pngjs/lib/png' {
+ declare export class PNG {
+ constructor(options: {width: number, height: number}): void;
+ width: number;
+ height: number;
+ data: Buffer;
+ static sync: {
+ read(buffer: Buffer): PNG,
+ write(image: PNG): Buffer,
+ };
+ }
+}
diff --git a/packages/new-app-screen/src/NewAppScreen.js b/packages/new-app-screen/src/NewAppScreen.js
index 21319a89de0b..1f712fdaf4b4 100644
--- a/packages/new-app-screen/src/NewAppScreen.js
+++ b/packages/new-app-screen/src/NewAppScreen.js
@@ -9,6 +9,7 @@
*/
import Links from './Links';
+import RuntimeVersion from './RuntimeVersion';
import {ThemedText, useTheme} from './Theme';
import * as React from 'react';
import {
@@ -135,8 +136,7 @@ function getHermesLabel(): React.Node {
return (
- JS Engine: Hermes (
- {global.HermesInternal.getRuntimeProperties?.()['OSS Release Version']})
+ JS Engine: Hermes ({RuntimeVersion.hermes})
);
}
diff --git a/packages/new-app-screen/src/RuntimeVersion.js b/packages/new-app-screen/src/RuntimeVersion.js
new file mode 100644
index 000000000000..12de14e8cee4
--- /dev/null
+++ b/packages/new-app-screen/src/RuntimeVersion.js
@@ -0,0 +1,16 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+const RuntimeVersion: {hermes: string | void} = {
+ hermes:
+ global.HermesInternal?.getRuntimeProperties?.()?.['OSS Release Version'],
+};
+
+export default RuntimeVersion;
diff --git a/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js b/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js
index 923c9944ad6b..d4ef3a3e39ca 100644
--- a/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js
+++ b/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js
@@ -12,6 +12,7 @@ import type {
RootTag,
TurboModule,
} from '../../../../../Libraries/TurboModule/RCTExport';
+import type {UnsafeObject} from '../../../../../Libraries/Types/CodegenTypes';
import * as TurboModuleRegistry from '../../../../../Libraries/TurboModule/TurboModuleRegistry';
@@ -116,6 +117,7 @@ interface Spec extends TurboModule {
surfaceId: RootTag,
config: RenderFormatOptions,
) => string;
+ takeScreenshot(surfaceId: RootTag): UnsafeObject;
registerAsset(uri: string, filePath: string): void;
registerFont(filePath: string): void;
reportTestSuiteResultsJSON: (results: string) => void;
diff --git a/private/react-native-fantom/__docs__/README.md b/private/react-native-fantom/__docs__/README.md
index d59edb57e937..038f4c2dceef 100644
--- a/private/react-native-fantom/__docs__/README.md
+++ b/private/react-native-fantom/__docs__/README.md
@@ -124,6 +124,49 @@ Similar to Jest, you can also run Fantom in watch mode using `--watch`:
yarn fantom --watch
```
+### PNG screenshots
+
+`root.takeScreenshot()` captures the currently mounted Fabric revision into an
+immutable `Screenshot`. Capture after `runTask` to include its mounted updates;
+capture itself does not flush pending React work. The bitmap remains usable
+after later updates or root destruction.
+
+```javascript
+const root = Fantom.createRoot();
+Fantom.runTask(() => root.render());
+const screenshot = root.takeScreenshot();
+expect(screenshot).toMatchSnapshot();
+expect(screenshot.isEqual(root.takeScreenshot())).toBe(true);
+```
+
+The headless renderer paints Yoga's mounted frames with CPU Skia. Text uses the
+same layout and bundled fonts as intrinsic measurement, so the measured sizes
+and painted content agree. `isEqual()` compares bitmap dimensions and pixels in
+memory.
+
+`toMatchSnapshot()` compares a SHA-256 hash of the bitmap dimensions and pixels
+with the value in Jest's `.snap` file. The expected PNG is not read for
+comparison. The runner also keeps an inspectable image in
+`__snapshots__/.screenshots/`, named from the test, label and
+assertion number. Capture defers PNG encoding until an image must be saved;
+encoded bytes are cached for repeated saves. A matching hash passes even if the
+PNG is missing, and the runner regenerates that image.
+
+`toMatchInlineSnapshot()` embeds the screenshot's type and hash directly in the
+test source. It does not encode or save an image, so inline failures report a
+text diff.
+
+New snapshots are saved during a normal local run. `--updateSnapshot` (`-u`)
+accepts changed hashes and PNGs together; CI requires an existing matching hash.
+A mismatch leaves the baseline unchanged, saves a difference image alongside the
+received image, and reports all three image paths for inspection. Unused images
+are removed only during a successful snapshot update with no skipped or filtered
+tests. Negated snapshot assertions are unsupported.
+
+See [Rendering](rendering.md) for the painting architecture, supported features,
+font selection and the configuration that keeps shared baselines consistent
+across Linux and macOS.
+
### Interactive REPL
> [!WARNING]
diff --git a/private/react-native-fantom/__docs__/rendering.md b/private/react-native-fantom/__docs__/rendering.md
index 8b6d7c87b195..f6250e2c15c2 100644
--- a/private/react-native-fantom/__docs__/rendering.md
+++ b/private/react-native-fantom/__docs__/rendering.md
@@ -72,7 +72,74 @@ and x86 optimized stages producing different rounded channel values when
compositing the same pixels, including color emoji. These settings apply only to
Fantom's Skia library.
-The scalar selector is an optional `SK_RASTER_PIPELINE_FORCE_SCALAR` definition
-in the pinned Skia source. Gradle patches its prepared source copy, and CMake
-validates the selector without modifying the source. Keep the internal target's
-flags and the public GN flags aligned when changing Skia.
+The pinned Skia source adds optional scalar-stage selection and makes the forced
+raster pipeline apply to sprite and saved-layer compositing. This keeps native
+pixel-format defaults from selecting byte-based alpha rounding instead. Gradle
+patches its prepared source copy, and CMake validates the scalar selector
+without modifying the source. Keep the internal target's flags and the public GN
+flags aligned when changing Skia.
+
+## Screenshot snapshots
+
+`root.takeScreenshot()` paints the currently mounted revision into an immutable
+CPU bitmap. It does not flush pending React work. Captures survive later commits
+and root destruction. Use `isEqual()` to compare their dimensions and pixel rows
+in memory. `saveToFile()` writes a PNG, creating parent directories and
+replacing an existing file.
+
+Use `Fantom.unstable_produceFramesForDuration()` to capture repeatable animation
+states without waiting for real time. Native layout animations need
+`@fantom_flags useSharedAnimatedBackend:true` in the test and produce
+intermediate mounted revisions. Native opacity and transform updates applied
+directly to views are visible to screenshots only after they are committed to
+the mounted tree.
+
+`toMatchSnapshot()` stores a SHA-256 hash of the image dimensions and
+premultiplied RGBA pixel rows. It compares that hash with the ordinary Jest
+snapshot value; it does not decode an expected PNG. An inspectable PNG is kept
+beside the `.snap` file in `.screenshots`. PNG encoding is deferred
+until an image must be saved, and PNG bytes are cached for repeated saves. A
+matching hash passes even when the standalone PNG is missing; the runner
+recreates that image from the matching capture without updating the hash.
+
+`toMatchInlineSnapshot()` embeds the same `{type: 'Screenshot', hash}` value in
+the test source. It compares hashes without encoding or saving PNGs, including
+when the inline snapshot is created, updated or fails. Inline failures use
+ordinary text snapshot diagnostics.
+
+Snapshot mismatches retain the received PNG and save a difference PNG in the
+same temporary directory. Failure diagnostics include the paths to the expected,
+received and difference images, including in CI and redirected output. The
+difference highlights changed pixels in red over faded unchanged content; it
+does not affect hash comparison. Missing or unreadable images retain their
+original diagnostics without a difference image. Snapshot updates copy it into
+the baseline directory before cleaning up the temporary file. Unused images are
+removed only during a full successful snapshot update; empty, failed, skipped or
+filtered suites preserve their baselines.
+
+### Painting
+
+The painter traverses Fabric's mounted child order, including stacking changes.
+Yoga supplies the frames for flow and absolute positioning. Overflow clips
+descendants to the view's rounded bounds; each view restores its canvas state
+before painting siblings. Nonidentity affine transforms are centered on the
+view, while identity transforms preserve child coordinates without extra
+floating-point translations. Singular transforms are skipped.
+
+`View`, styled and nested `Text`, `TextInput`, `Image` and `ScrollView` use this
+shared canvas. Text inputs paint values or placeholders, including multiline and
+secure entry. Scroll views offset their content to show the current viewport.
+Backgrounds, solid borders, rounded corners and opacity follow the mounted
+props.
+
+Images support local PNG files (`file://` or filesystem paths) and base64 PNG
+data URIs, with resize modes and tint. Supply network images as local fixtures.
+The shared asset resolver maps bundled `require()` sources to native files while
+keeping their React Native URIs stable in text snapshots.
+
+An empty root produces a transparent viewport; a destroyed root cannot be
+captured. Viewport offsets do not move the screenshot's origin. The renderer
+does not reproduce Android or iOS platform chrome, shadows or perspective
+transforms. Additional font fixtures can be registered with
+`NativeFantom.registerFont()` before mounting; the default fonts need no
+per-test registration.
diff --git a/private/react-native-fantom/package.json b/private/react-native-fantom/package.json
index d670926f5e0b..ef13f2a0d218 100644
--- a/private/react-native-fantom/package.json
+++ b/private/react-native-fantom/package.json
@@ -10,7 +10,8 @@
"dependencies": {
"@expo-google-fonts/noto-color-emoji": "0.4.7",
"babel-plugin-istanbul": "^7.0.0",
- "dejavu-fonts-ttf": "2.37.3"
+ "dejavu-fonts-ttf": "2.37.3",
+ "pngjs": "7.0.0"
},
"peerDependencies": {
"jest": "^29.7.0",
diff --git a/private/react-native-fantom/runner/__tests__/snapshotCI-test.js b/private/react-native-fantom/runner/__tests__/snapshotCI-test.js
index 9ff3703800bd..a8c54c55cb4b 100644
--- a/private/react-native-fantom/runner/__tests__/snapshotCI-test.js
+++ b/private/react-native-fantom/runner/__tests__/snapshotCI-test.js
@@ -17,7 +17,9 @@ import os from 'node:os';
import path from 'node:path';
function evaluate(state: SnapshotState, snapshotResults: TestSnapshotResults) {
- return updateSnapshotsAndGetJestSnapshotResult(state, [snapshotResults]);
+ return updateSnapshotsAndGetJestSnapshotResult(state, [
+ {status: 'failed', snapshotResults},
+ ]);
}
describe('Fantom snapshot update modes', () => {
diff --git a/private/react-native-fantom/runner/__tests__/snapshotUtils-test.js b/private/react-native-fantom/runner/__tests__/snapshotUtils-test.js
new file mode 100644
index 000000000000..62f355bc2334
--- /dev/null
+++ b/private/react-native-fantom/runner/__tests__/snapshotUtils-test.js
@@ -0,0 +1,153 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+import {updateSnapshotsAndGetJestSnapshotResult} from '../snapshotUtils';
+import {SnapshotState} from 'jest-snapshot';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+let directory: string;
+beforeEach(() => {
+ directory = fs.mkdtempSync(path.join(os.tmpdir(), 'fantom-snapshot-test-'));
+});
+afterEach(() => fs.rmSync(directory, {recursive: true, force: true}));
+
+it('does not overwrite an existing snapshot on mismatch without -u', () => {
+ const filePath = path.join(directory, 'example.snap');
+ fs.writeFileSync(filePath, 'exports[`test 1`] = `old hash`;\n');
+ for (const mode of ['new', 'none'] as const) {
+ const state = new SnapshotState(filePath, {
+ updateSnapshot: mode,
+ rootDir: directory,
+ snapshotFormat: {},
+ });
+ const result = updateSnapshotsAndGetJestSnapshotResult(state, [
+ {
+ status: 'failed',
+ snapshotResults: {'test 1': {pass: false, value: 'new hash'}},
+ },
+ ]);
+ expect(result.unmatched).toBe(1);
+ expect(result.updated).toBe(0);
+ expect(fs.readFileSync(filePath, 'utf8')).toContain('old hash');
+ expect(fs.readFileSync(filePath, 'utf8')).not.toContain('new hash');
+ }
+});
+
+it('updates a hash once with -u and counts passing snapshots once', () => {
+ const filePath = path.join(directory, 'example.snap');
+ fs.writeFileSync(filePath, 'exports[`test 1`] = `old hash`;\n');
+ const state = new SnapshotState(filePath, {
+ updateSnapshot: 'all',
+ rootDir: directory,
+ snapshotFormat: {},
+ });
+ const result = updateSnapshotsAndGetJestSnapshotResult(state, [
+ {
+ status: 'passed',
+ snapshotResults: {'test 1': {pass: false, value: 'new hash'}},
+ },
+ ]);
+ expect(result.updated).toBe(1);
+ expect(fs.readFileSync(filePath, 'utf8')).toContain('new hash');
+ const matching = new SnapshotState(filePath, {
+ updateSnapshot: 'none',
+ rootDir: directory,
+ snapshotFormat: {},
+ });
+ const matched = updateSnapshotsAndGetJestSnapshotResult(matching, [
+ {
+ status: 'passed',
+ snapshotResults: {'test 1': {pass: true}},
+ },
+ ]);
+ expect(matched.matched).toBe(1);
+ expect(matched.unchecked).toBe(0);
+});
+
+it('counts a new snapshot once', () => {
+ const state = new SnapshotState(path.join(directory, 'example.snap'), {
+ updateSnapshot: 'new',
+ rootDir: directory,
+ snapshotFormat: {},
+ });
+ const result = updateSnapshotsAndGetJestSnapshotResult(state, [
+ {
+ status: 'passed',
+ snapshotResults: {'test 1': {pass: false, value: 'new hash'}},
+ },
+ ]);
+ expect(result.added).toBe(1);
+ expect(result.matched).toBe(0);
+ expect(result.updated).toBe(0);
+ expect(result.unmatched).toBe(0);
+});
+
+it('preserves unchecked snapshots when no tests ran with -u', () => {
+ const filePath = path.join(directory, 'example.snap');
+ const contents =
+ '// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`test 1`] = `old hash`;\n';
+ fs.writeFileSync(filePath, contents);
+ const state = new SnapshotState(filePath, {
+ updateSnapshot: 'all',
+ rootDir: directory,
+ snapshotFormat: {},
+ });
+ const result = updateSnapshotsAndGetJestSnapshotResult(state, []);
+ expect(fs.readFileSync(filePath, 'utf8')).toBe(contents);
+ expect(result.unchecked).toBe(0);
+ expect(result.uncheckedKeys).toEqual([]);
+});
+
+it('preserves unchecked snapshots after skipped or failed tests with -u', () => {
+ const filePath = path.join(directory, 'example.snap');
+ const contents =
+ '// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`other test 1`] = `other hash`;\n\nexports[`removed test 1`] = `removed hash`;\n\nexports[`test 1`] = `old hash`;\n';
+ for (const status of ['pending', 'failed'] as const) {
+ fs.writeFileSync(filePath, contents);
+ const state = new SnapshotState(filePath, {
+ updateSnapshot: 'all',
+ rootDir: directory,
+ snapshotFormat: {},
+ });
+ const result = updateSnapshotsAndGetJestSnapshotResult(state, [
+ {
+ status: 'passed',
+ snapshotResults: {'test 1': {pass: true}},
+ },
+ {status, snapshotResults: {}},
+ ]);
+ expect(fs.readFileSync(filePath, 'utf8')).toBe(contents);
+ expect(result.unchecked).toBe(0);
+ expect(result.uncheckedKeys).toEqual([]);
+ }
+});
+
+it('removes unchecked snapshots after a full successful update', () => {
+ const filePath = path.join(directory, 'example.snap');
+ fs.writeFileSync(
+ filePath,
+ 'exports[`test 1`] = `old hash`;\nexports[`removed test 1`] = `removed hash`;\n',
+ );
+ const state = new SnapshotState(filePath, {
+ updateSnapshot: 'all',
+ rootDir: directory,
+ snapshotFormat: {},
+ });
+ updateSnapshotsAndGetJestSnapshotResult(state, [
+ {
+ status: 'passed',
+ snapshotResults: {'test 1': {pass: true}},
+ },
+ ]);
+ expect(fs.readFileSync(filePath, 'utf8')).toContain('old hash');
+ expect(fs.readFileSync(filePath, 'utf8')).not.toContain('removed hash');
+});
diff --git a/private/react-native-fantom/runner/runner.js b/private/react-native-fantom/runner/runner.js
index 999950b26476..b831446b647b 100644
--- a/private/react-native-fantom/runner/runner.js
+++ b/private/react-native-fantom/runner/runner.js
@@ -8,6 +8,7 @@
* @format
*/
+import type {ScreenshotResult} from '../runtime/ScreenshotContext';
import type {
FailureDetail,
TestCaseResult,
@@ -47,6 +48,12 @@ import {
buildJSTracesOutputPath,
getTestBuildOutputPath,
} from './paths';
+import {
+ createScreenshotDifferences,
+ formatScreenshotFailure,
+ getScreenshotConfig,
+ processScreenshotResults,
+} from './screenshots/screenshotUtils';
import {
getInitialSnapshotData,
processInlineSnapshotResults,
@@ -64,6 +71,7 @@ import {
// $FlowExpectedError[untyped-import]
import {formatResultsErrors} from 'jest-message-util';
import {SnapshotState, buildSnapshotResolver} from 'jest-snapshot';
+import {randomUUID} from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import readline from 'node:readline';
@@ -80,13 +88,23 @@ if (EnvironmentOptions.profileJS) {
function buildError(
failureDetail: FailureDetail,
sourceMapPath: string,
+ screenshotResults: ReadonlyArray = [],
): Error {
- const error = new Error(failureDetail.message);
+ const error = new Error(
+ formatScreenshotFailure(failureDetail.message, screenshotResults),
+ );
if (failureDetail.stack != null) {
- error.stack = symbolicateStackTrace(sourceMapPath, failureDetail.stack);
+ error.stack = symbolicateStackTrace(
+ sourceMapPath,
+ formatScreenshotFailure(failureDetail.stack, screenshotResults),
+ );
}
if (failureDetail.cause != null) {
- error.cause = buildError(failureDetail.cause, sourceMapPath);
+ error.cause = buildError(
+ failureDetail.cause,
+ sourceMapPath,
+ screenshotResults,
+ );
}
return error;
}
@@ -225,6 +243,14 @@ module.exports = async function runTest(
let coverageMap: CoverageMap = {};
const snapshotResolver = await buildSnapshotResolver(config);
const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath);
+ const screenshotConfig = getScreenshotConfig(
+ snapshotPath,
+ path.join(
+ TEST_BUILD_OUTPUT_PATH,
+ 'screenshots',
+ `${randomUUID()}-${path.basename(testPath)}`,
+ ),
+ );
const snapshotState = new SnapshotState(snapshotPath, {
updateSnapshot: globalConfig.updateSnapshot,
snapshotFormat: config.snapshotFormat,
@@ -257,12 +283,13 @@ module.exports = async function runTest(
{
ancestorTitles,
duration: 0,
- failureDetails: [] as Array,
+ failureDetails: [] as Array,
failureMessages: [] as Array,
fullName: title,
numPassingAsserts: 0,
snapshotResults: {} as TestSnapshotResults,
inlineSnapshotResults: [] as TestInlineSnapshotResults,
+ screenshotResults: [] as Array,
status: 'pending' as TestCaseResult['status'],
testFilePath: testPath,
title,
@@ -330,6 +357,10 @@ module.exports = async function runTest(
snapshotConfig: {
updateSnapshot: snapshotState._updateSnapshot,
data: getInitialSnapshotData(snapshotState),
+ screenshots: {
+ ...screenshotConfig,
+ receivedDirectory: `${screenshotConfig.receivedDirectory}-${testResultsByConfig.length}`,
+ },
},
jsHeapSnapshotOutputPathTemplate,
jsHeapSnapshotOutputPathTemplateToken,
@@ -456,18 +487,30 @@ module.exports = async function runTest(
}
const testResults =
- nullthrows(processedResult.testResults).map(testResult => ({
- ancestorTitles: [] as Array,
- testFilePath: testPath,
- ...testResult,
- failureMessages: testResult.failureMessages.map(maybeStackTrace =>
- symbolicateStackTrace(sourceMapPath, maybeStackTrace),
- ),
- failureDetails: testResult.failureDetails.map(failureDetails =>
- buildError(failureDetails, sourceMapPath),
- ),
- snapshotResults: testResult.snapshotResults,
- })) ?? [];
+ nullthrows(processedResult.testResults).map(testResult => {
+ const screenshotResults = createScreenshotDifferences(
+ testResult.screenshotResults,
+ globalConfig.updateSnapshot,
+ );
+ return {
+ ancestorTitles: [] as Array,
+ testFilePath: testPath,
+ ...testResult,
+ screenshotResults,
+ failureMessages: testResult.failureMessages.map(maybeStackTrace =>
+ symbolicateStackTrace(
+ sourceMapPath,
+ formatScreenshotFailure(maybeStackTrace, screenshotResults),
+ ),
+ ),
+ failureDetails: testResult.failureDetails.map(failureDetail =>
+ failureDetail == null
+ ? undefined
+ : buildError(failureDetail, sourceMapPath, screenshotResults),
+ ),
+ snapshotResults: testResult.snapshotResults,
+ };
+ }) ?? [];
// Process inline snapshot results (requires source map for symbolication)
if (hasInlineSnapshotUpdates) {
@@ -553,13 +596,15 @@ module.exports = async function runTest(
const testResults = testResultsByConfig.flat();
- const snapshotResults = testResults.map(
- testResult => testResult.snapshotResults,
+ processScreenshotResults(
+ screenshotConfig,
+ testResults.flatMap(result => result.screenshotResults),
+ globalConfig.updateSnapshot,
+ testResults,
);
-
const snapshotResult = updateSnapshotsAndGetJestSnapshotResult(
snapshotState,
- snapshotResults,
+ testResults,
);
printBenchmarkResultsRanking(benchmarkResults);
diff --git a/private/react-native-fantom/runner/screenshots/__tests__/imageDiff-test.js b/private/react-native-fantom/runner/screenshots/__tests__/imageDiff-test.js
new file mode 100644
index 000000000000..10783588b0d4
--- /dev/null
+++ b/private/react-native-fantom/runner/screenshots/__tests__/imageDiff-test.js
@@ -0,0 +1,99 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+import createImageDiff from '../imageDiff';
+import {Buffer} from 'node:buffer';
+import {PNG} from 'pngjs/lib/png';
+
+const png = PNG.sync.write(new PNG({width: 2, height: 1}));
+
+it('highlights changed pixels and fades unchanged content without modifying inputs', () => {
+ const baseline = new PNG({width: 2, height: 1});
+ baseline.data.set([0, 0, 0, 255, 0, 0, 255, 255]);
+ const capture = new PNG({width: 2, height: 1});
+ capture.data.set([0, 0, 0, 255, 0, 255, 0, 255]);
+ const expected = PNG.sync.write(baseline);
+ const received = PNG.sync.write(capture);
+ const originalExpected = Buffer.from(expected);
+ const originalReceived = Buffer.from(received);
+ const encoded = createImageDiff(expected, received);
+ expect(encoded).not.toBe(null);
+ if (encoded == null) {
+ return;
+ }
+ const diff = PNG.sync.read(encoded);
+ expect(diff.width).toBe(2);
+ expect(diff.height).toBe(1);
+ expect(diff.data[0]).toBeGreaterThan(200);
+ expect(diff.data[0]).toBe(diff.data[1]);
+ expect(diff.data[1]).toBe(diff.data[2]);
+ expect([...diff.data.subarray(4, 8)]).toEqual([255, 0, 0, 255]);
+ expect(expected.equals(originalExpected)).toBe(true);
+ expect(received.equals(originalReceived)).toBe(true);
+});
+
+it('marks alpha changes even when compositing onto white would hide them', () => {
+ const baseline = new PNG({width: 1, height: 1});
+ baseline.data.set([255, 255, 255, 255]);
+ const capture = new PNG({width: 1, height: 1});
+ capture.data.set([255, 255, 255, 128]);
+ const encoded = createImageDiff(
+ PNG.sync.write(baseline),
+ PNG.sync.write(capture),
+ );
+ expect(encoded).not.toBe(null);
+ if (encoded != null) {
+ expect([...PNG.sync.read(encoded).data]).toEqual([255, 0, 0, 255]);
+ }
+});
+
+it('marks added and removed dimensions, including transparent pixels', () => {
+ const baseline = PNG.sync.write(new PNG({width: 2, height: 1}));
+ const capture = PNG.sync.write(new PNG({width: 1, height: 2}));
+ for (const [expected, received] of [
+ [baseline, capture],
+ [capture, baseline],
+ ]) {
+ const encoded = createImageDiff(expected, received);
+ expect(encoded).not.toBe(null);
+ if (encoded == null) {
+ continue;
+ }
+ const diff = PNG.sync.read(encoded);
+ expect(diff.width).toBe(2);
+ expect(diff.height).toBe(2);
+ expect([...diff.data.subarray(0, 4)]).toEqual([255, 255, 255, 255]);
+ expect([...diff.data.subarray(4, 8)]).toEqual([255, 0, 0, 255]);
+ expect([...diff.data.subarray(8, 12)]).toEqual([255, 0, 0, 255]);
+ expect([...diff.data.subarray(12, 16)]).toEqual([255, 255, 255, 255]);
+ }
+});
+
+it('isolates corrupt PNGs and oversized diff canvases', () => {
+ expect(createImageDiff(Buffer.from('invalid'), png)).toBe(null);
+ const corrupt = Buffer.from(png);
+ corrupt[corrupt.length - 5] = (corrupt[corrupt.length - 5] + 1) % 256;
+ expect(createImageDiff(png, corrupt)).toBe(null);
+ const wide = Buffer.from(png);
+ wide.writeUInt32BE(16000, 16);
+ wide.writeUInt32BE(1, 20);
+ const tall = Buffer.from(png);
+ tall.writeUInt32BE(1, 16);
+ tall.writeUInt32BE(16000, 20);
+ expect(createImageDiff(wide, tall)).toBe(null);
+});
+
+it('rejects PNGs with conflicting dimension headers', () => {
+ const small = PNG.sync.write(new PNG({width: 1, height: 1}));
+ const wide = PNG.sync.write(new PNG({width: 10, height: 1}));
+ const conflicting = Buffer.concat([small.subarray(0, 33), wide.subarray(8)]);
+ expect(createImageDiff(conflicting, small)).toBe(null);
+ expect(createImageDiff(small, conflicting)).toBe(null);
+});
diff --git a/private/react-native-fantom/runner/screenshots/__tests__/screenshotUtils-test.js b/private/react-native-fantom/runner/screenshots/__tests__/screenshotUtils-test.js
new file mode 100644
index 000000000000..af0c7f10c698
--- /dev/null
+++ b/private/react-native-fantom/runner/screenshots/__tests__/screenshotUtils-test.js
@@ -0,0 +1,304 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+import type {ScreenshotResult} from '../../../runtime/ScreenshotContext';
+
+import {
+ createScreenshotDifferences,
+ formatScreenshotFailure,
+ getScreenshotConfig,
+ processScreenshotResults,
+} from '../screenshotUtils';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import {PNG} from 'pngjs/lib/png';
+
+let directory: string;
+const passedTests = [{status: 'passed' as const}];
+beforeEach(() => {
+ directory = fs.mkdtempSync(path.join(os.tmpdir(), 'fantom-screenshot-test-'));
+});
+afterEach(() => {
+ jest.restoreAllMocks();
+ fs.rmSync(directory, {recursive: true, force: true});
+});
+
+function createResult(
+ isNew: boolean,
+ pass: boolean,
+): {...ScreenshotResult, receivedPath: string} {
+ const config = getScreenshotConfig(
+ path.join(directory, '__snapshots__', 'example-test.js.snap'),
+ directory,
+ );
+ const expectedPath = path.join(config.snapshotDirectory, 'image.png');
+ const receivedPath = path.join(directory, 'actual.png');
+ fs.writeFileSync(receivedPath, 'new image');
+ if (!isNew) {
+ fs.mkdirSync(config.snapshotDirectory, {recursive: true});
+ fs.writeFileSync(expectedPath, 'old image');
+ }
+ return {fileName: 'image.png', expectedPath, receivedPath, pass, isNew};
+}
+
+function getConfig() {
+ return getScreenshotConfig(
+ path.join(directory, '__snapshots__', 'example-test.js.snap'),
+ directory,
+ );
+}
+
+function createPngResult(): {...ScreenshotResult, receivedPath: string} {
+ const result = createResult(false, false);
+ const baseline = new PNG({width: 1, height: 1});
+ baseline.data.set([0, 0, 255, 255]);
+ const capture = new PNG({width: 1, height: 1});
+ capture.data.set([0, 255, 0, 255]);
+ fs.writeFileSync(result.expectedPath, PNG.sync.write(baseline));
+ fs.writeFileSync(result.receivedPath, PNG.sync.write(capture));
+ return result;
+}
+
+for (const mode of ['none', 'new'] as const) {
+ it(`saves a difference beside the received PNG in ${mode} mode`, () => {
+ const result = createPngResult();
+ const baseline = fs.readFileSync(result.expectedPath);
+ const received = fs.readFileSync(result.receivedPath);
+ const [processed] = createScreenshotDifferences([result], mode);
+ const differencePath = processed.differencePath;
+ expect(differencePath).toBe(path.join(directory, 'actual.diff.png'));
+ if (differencePath == null) {
+ throw new Error('Missing difference PNG');
+ }
+ expect([...PNG.sync.read(fs.readFileSync(differencePath)).data]).toEqual([
+ 255, 0, 0, 255,
+ ]);
+ expect(fs.readFileSync(result.expectedPath).equals(baseline)).toBe(true);
+ expect(fs.readFileSync(result.receivedPath).equals(received)).toBe(true);
+ const message = `Expected screenshot: ${result.expectedPath}\nReceived screenshot: ${result.receivedPath}\nOpen these files.`;
+ expect(formatScreenshotFailure(message, [processed])).toContain(
+ `Received screenshot: ${result.receivedPath}\nDifference screenshot: ${differencePath}\nOpen these files.`,
+ );
+ expect(formatScreenshotFailure('unrelated error', [processed])).toBe(
+ 'unrelated error',
+ );
+ });
+}
+
+it('adds each difference to the matching diagnostic block without matching path prefixes', () => {
+ const result = createResult(false, false);
+ const first = {...result, differencePath: `${directory}/first.diff.png`};
+ const second = {
+ ...result,
+ receivedPath: `${result.receivedPath}.other.png`,
+ differencePath: `${directory}/second.$&.diff.png`,
+ };
+ const block = (item: Readonly<{...ScreenshotResult, receivedPath: string}>) =>
+ `Expected screenshot: ${item.expectedPath}\nReceived screenshot: ${item.receivedPath}`;
+ const message = `${block(second)}\nOther error\n${block(first)}`;
+ const expected = `${block(second)}\nDifference screenshot: ${second.differencePath}\nOther error\n${block(first)}\nDifference screenshot: ${first.differencePath}`;
+ expect(formatScreenshotFailure(message, [first, second])).toBe(expected);
+ expect(formatScreenshotFailure(expected, [first, second])).toBe(expected);
+});
+
+it('formats repeated diagnostic blocks without changing unrelated path mentions', () => {
+ const result = createResult(false, false);
+ const processed = {...result, differencePath: `${directory}/actual.diff.png`};
+ const block = `Expected screenshot: ${result.expectedPath}\nReceived screenshot: ${result.receivedPath}`;
+ const unrelated = `Other error mentions Received screenshot: ${result.receivedPath}`;
+ const formatted = `${block}\nDifference screenshot: ${processed.differencePath}`;
+ expect(
+ formatScreenshotFailure(`${unrelated}\n${block}\n${block}`, [processed]),
+ ).toBe(`${unrelated}\n${formatted}\n${formatted}`);
+ expect(
+ formatScreenshotFailure(`Received screenshot: ${result.receivedPath}`, [
+ processed,
+ ]),
+ ).toBe(`Received screenshot: ${result.receivedPath}`);
+});
+
+it('does not generate differences for passes, updates or missing baselines', () => {
+ const result = createPngResult();
+ for (const unchanged of [
+ {...result, pass: true},
+ {...result, isNew: true},
+ {...result, receivedPath: null},
+ ]) {
+ expect(createScreenshotDifferences([unchanged], 'none')[0]).toBe(unchanged);
+ }
+ expect(createScreenshotDifferences([result], 'all')[0]).toBe(result);
+ expect(fs.existsSync(path.join(directory, 'actual.diff.png'))).toBe(false);
+});
+
+it('continues generating differences after missing, corrupt or unwritable files', () => {
+ const consoleError = jest
+ .spyOn(console, 'error')
+ .mockImplementation(() => {});
+ const result = createPngResult();
+ const missing = path.join(directory, 'missing.png');
+ const corrupt = path.join(directory, 'corrupt.png');
+ fs.writeFileSync(corrupt, 'not a PNG');
+ const writeFileSync = fs.writeFileSync;
+ jest.spyOn(fs, 'writeFileSync').mockImplementation((file, data, options) => {
+ if (file === path.join(directory, 'unwritable.diff.png')) {
+ throw new Error('Cannot write difference');
+ }
+ return writeFileSync(file, data, options);
+ });
+ const unwritable = path.join(directory, 'unwritable.png');
+ fs.copyFileSync(result.receivedPath, unwritable);
+ const results = createScreenshotDifferences(
+ [
+ {...result, expectedPath: missing},
+ {...result, receivedPath: corrupt},
+ {...result, receivedPath: unwritable},
+ result,
+ ],
+ 'none',
+ );
+ for (const failed of results.slice(0, 3)) {
+ expect(failed.differencePath).toBe(undefined);
+ }
+ expect(results[3].differencePath).toBe(
+ path.join(directory, 'actual.diff.png'),
+ );
+ expect(consoleError).toHaveBeenCalledTimes(2);
+ expect(consoleError).toHaveBeenNthCalledWith(
+ 1,
+ expect.stringContaining(missing),
+ );
+ expect(consoleError).toHaveBeenNthCalledWith(
+ 2,
+ `Failed to create Fantom screenshot difference between ${result.expectedPath} and ${unwritable}: Error: Cannot write difference`,
+ );
+});
+
+it('creates new images next to Jest snapshots', () => {
+ const result = createResult(true, false);
+ processScreenshotResults(getConfig(), [result], 'new', passedTests);
+ expect(result.expectedPath).toContain(
+ '__snapshots__/example-test.js.screenshots/',
+ );
+ expect(fs.readFileSync(result.expectedPath, 'utf8')).toBe('new image');
+ expect(
+ result.receivedPath == null || !fs.existsSync(result.receivedPath),
+ ).toBe(true);
+});
+
+it('preserves both images for a mismatch without -u', () => {
+ const result = createResult(false, false);
+ processScreenshotResults(getConfig(), [result], 'new', [{status: 'failed'}]);
+ expect(fs.readFileSync(result.expectedPath, 'utf8')).toBe('old image');
+ expect(fs.readFileSync(result.receivedPath, 'utf8')).toBe('new image');
+});
+
+it('updates existing baselines with -u', () => {
+ const result = createResult(false, false);
+ processScreenshotResults(getConfig(), [result], 'all', passedTests);
+ expect(fs.readFileSync(result.expectedPath, 'utf8')).toBe('new image');
+});
+
+it('tolerates a received image disappearing after it is copied', () => {
+ const result = createResult(false, false);
+ const copyFileSync = fs.copyFileSync;
+ jest.spyOn(fs, 'copyFileSync').mockImplementation((source, destination) => {
+ copyFileSync(source, destination);
+ fs.unlinkSync(source);
+ });
+ processScreenshotResults(getConfig(), [result], 'all', passedTests);
+ expect(fs.readFileSync(result.expectedPath, 'utf8')).toBe('new image');
+});
+
+it('fails when a received image is missing before it can be copied', () => {
+ const result = createResult(false, false);
+ fs.unlinkSync(result.receivedPath);
+ expect(() =>
+ processScreenshotResults(getConfig(), [result], 'all', passedTests),
+ ).toThrow();
+ expect(fs.readFileSync(result.expectedPath, 'utf8')).toBe('old image');
+});
+
+it('continues saving other captures after a copy error and retains the failed capture', () => {
+ const result = createResult(false, false);
+ const config = getConfig();
+ const otherReceivedPath = path.join(directory, 'other.png');
+ const otherExpectedPath = path.join(config.snapshotDirectory, 'other.png');
+ fs.writeFileSync(otherReceivedPath, 'other image');
+ const other = {
+ ...result,
+ fileName: 'other.png',
+ expectedPath: otherExpectedPath,
+ receivedPath: otherReceivedPath,
+ };
+ expect(() =>
+ processScreenshotResults(
+ config,
+ [{...result, expectedPath: config.snapshotDirectory}, other],
+ 'all',
+ passedTests,
+ ),
+ ).toThrow(config.snapshotDirectory);
+ expect(fs.readFileSync(result.receivedPath, 'utf8')).toBe('new image');
+ expect(fs.readFileSync(result.expectedPath, 'utf8')).toBe('old image');
+ expect(fs.readFileSync(otherExpectedPath, 'utf8')).toBe('other image');
+ expect(fs.existsSync(otherReceivedPath)).toBe(false);
+});
+
+it('does not create missing baselines in CI', () => {
+ const result = createResult(true, false);
+ processScreenshotResults(getConfig(), [result], 'none', [{status: 'failed'}]);
+ expect(fs.existsSync(result.expectedPath)).toBe(false);
+ expect(fs.existsSync(result.receivedPath)).toBe(true);
+});
+
+it('keeps existing images for successful hash matches', () => {
+ const result = createResult(false, true);
+ fs.unlinkSync(result.receivedPath);
+ const matchingResult = {...result, receivedPath: null};
+ processScreenshotResults(getConfig(), [matchingResult], 'none', passedTests);
+ expect(fs.readFileSync(result.expectedPath, 'utf8')).toBe('old image');
+ expect(
+ result.receivedPath == null || !fs.existsSync(result.receivedPath),
+ ).toBe(true);
+});
+
+for (const mode of ['new', 'none', 'all'] as const) {
+ it(`recreates a missing image with a matching hash in ${mode} mode`, () => {
+ const result = createResult(false, true);
+ fs.unlinkSync(result.expectedPath);
+ processScreenshotResults(getConfig(), [result], mode, passedTests);
+ expect(fs.readFileSync(result.expectedPath, 'utf8')).toBe('new image');
+ expect(fs.existsSync(result.receivedPath)).toBe(false);
+ });
+}
+
+it('preserves unchecked baselines when no tests ran', () => {
+ const result = createResult(false, true);
+ processScreenshotResults(getConfig(), [], 'all', []);
+ expect(fs.readFileSync(result.expectedPath, 'utf8')).toBe('old image');
+});
+
+for (const status of ['failed', 'pending'] as const) {
+ it(`preserves unchecked baselines after a ${status} test`, () => {
+ const result = createResult(false, true);
+ processScreenshotResults(getConfig(), [], 'all', [
+ ...passedTests,
+ {status},
+ ]);
+ expect(fs.readFileSync(result.expectedPath, 'utf8')).toBe('old image');
+ });
+}
+
+it('removes unchecked baselines with -u after a successful suite', () => {
+ const result = createResult(false, true);
+ processScreenshotResults(getConfig(), [], 'all', passedTests);
+ expect(fs.existsSync(result.expectedPath)).toBe(false);
+});
diff --git a/private/react-native-fantom/runner/screenshots/imageDiff.js b/private/react-native-fantom/runner/screenshots/imageDiff.js
new file mode 100644
index 000000000000..f12c08670a80
--- /dev/null
+++ b/private/react-native-fantom/runner/screenshots/imageDiff.js
@@ -0,0 +1,69 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict
+ * @format
+ */
+
+import {getPngDimensions} from './pngUtils';
+import {Buffer} from 'node:buffer';
+import {PNG} from 'pngjs/lib/png';
+
+export default function createImageDiff(
+ expected: Buffer,
+ received: Buffer,
+): ?Buffer {
+ const expectedSize = getPngDimensions(expected);
+ const receivedSize = getPngDimensions(received);
+ if (expectedSize == null || receivedSize == null) {
+ return null;
+ }
+ const width = Math.max(expectedSize.width, receivedSize.width);
+ const height = Math.max(expectedSize.height, receivedSize.height);
+ if (width * height > 16 * 1024 * 1024) {
+ return null;
+ }
+ try {
+ const baseline = PNG.sync.read(expected);
+ const capture = PNG.sync.read(received);
+ const diff = new PNG({width, height});
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const a = (y * baseline.width + x) * 4;
+ const b = (y * capture.width + x) * 4;
+ const offset = (y * width + x) * 4;
+ const inBaseline = x < baseline.width && y < baseline.height;
+ const inCapture = x < capture.width && y < capture.height;
+ const changed =
+ inBaseline !== inCapture ||
+ (inBaseline &&
+ inCapture &&
+ (baseline.data[a] !== capture.data[b] ||
+ baseline.data[a + 1] !== capture.data[b + 1] ||
+ baseline.data[a + 2] !== capture.data[b + 2] ||
+ baseline.data[a + 3] !== capture.data[b + 3]));
+ const shade = inBaseline
+ ? Math.round(
+ 255 -
+ (255 -
+ (baseline.data[a] * 0.2126 +
+ baseline.data[a + 1] * 0.7152 +
+ baseline.data[a + 2] * 0.0722)) *
+ (baseline.data[a + 3] / 255) *
+ 0.15,
+ )
+ : 255;
+ diff.data[offset] = changed ? 255 : shade;
+ diff.data[offset + 1] = changed ? 0 : shade;
+ diff.data[offset + 2] = changed ? 0 : shade;
+ diff.data[offset + 3] = 255;
+ }
+ }
+ return PNG.sync.write(diff);
+ } catch {
+ return null;
+ }
+}
diff --git a/private/react-native-fantom/runner/screenshots/pngUtils.js b/private/react-native-fantom/runner/screenshots/pngUtils.js
new file mode 100644
index 000000000000..84aa4d88b644
--- /dev/null
+++ b/private/react-native-fantom/runner/screenshots/pngUtils.js
@@ -0,0 +1,46 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict
+ * @format
+ */
+
+import {Buffer} from 'node:buffer';
+
+export function getPngDimensions(
+ png: Buffer,
+): ?Readonly<{width: number, height: number}> {
+ if (
+ png.length < 33 ||
+ png.length > 32 * 1024 * 1024 ||
+ !png
+ .subarray(0, 8)
+ .equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) ||
+ png.toString('ascii', 12, 16) !== 'IHDR' ||
+ png.readUInt32BE(8) !== 13
+ ) {
+ return null;
+ }
+ const width = png.readUInt32BE(16);
+ const height = png.readUInt32BE(20);
+ if (width === 0 || height === 0 || width * height > 16 * 1024 * 1024) {
+ return null;
+ }
+ let offset = 33;
+ while (offset + 12 <= png.length) {
+ const length = png.readUInt32BE(offset);
+ const type = png.toString('ascii', offset + 4, offset + 8);
+ const end = offset + length + 12;
+ if (end > png.length || type === 'IHDR') {
+ return null;
+ }
+ if (type === 'IEND') {
+ return length === 0 ? {width, height} : null;
+ }
+ offset = end;
+ }
+ return null;
+}
diff --git a/private/react-native-fantom/runner/screenshots/screenshotUtils.js b/private/react-native-fantom/runner/screenshots/screenshotUtils.js
new file mode 100644
index 000000000000..2e6ed451ba6c
--- /dev/null
+++ b/private/react-native-fantom/runner/screenshots/screenshotUtils.js
@@ -0,0 +1,151 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+import type {
+ ScreenshotConfig,
+ ScreenshotResult,
+ UpdateSnapshot,
+} from '../../runtime/ScreenshotContext';
+import type {TestCaseResult} from '../../runtime/setup';
+
+import createImageDiff from './imageDiff';
+import fs from 'node:fs';
+import path from 'node:path';
+
+export function getScreenshotConfig(
+ snapshotPath: string,
+ receivedDirectory: string,
+): ScreenshotConfig {
+ const snapshotDirectory = path.join(
+ path.dirname(snapshotPath),
+ `${path.basename(snapshotPath, '.snap')}.screenshots`,
+ );
+ return {
+ snapshotDirectory,
+ receivedDirectory,
+ files: fs.existsSync(snapshotDirectory)
+ ? fs.readdirSync(snapshotDirectory).filter(file => file.endsWith('.png'))
+ : [],
+ };
+}
+
+export function createScreenshotDifferences(
+ results: ReadonlyArray,
+ updateSnapshot: UpdateSnapshot,
+): Array {
+ return results.map(result => {
+ const receivedPath = result.receivedPath;
+ if (
+ result.pass ||
+ result.isNew ||
+ receivedPath == null ||
+ updateSnapshot === 'all'
+ ) {
+ return result;
+ }
+ try {
+ const difference = createImageDiff(
+ fs.readFileSync(result.expectedPath),
+ fs.readFileSync(receivedPath),
+ );
+ if (difference == null) {
+ return result;
+ }
+ const differencePath = path.join(
+ path.dirname(receivedPath),
+ `${path.basename(receivedPath, '.png')}.diff.png`,
+ );
+ fs.writeFileSync(differencePath, difference);
+ return {...result, differencePath};
+ } catch (error: unknown) {
+ console.error(
+ `Failed to create Fantom screenshot difference between ${result.expectedPath} and ${receivedPath}: ${String(error)}`,
+ );
+ return result;
+ }
+ });
+}
+
+export function formatScreenshotFailure(
+ message: string,
+ results: ReadonlyArray,
+): string {
+ const differences = new Map();
+ for (const result of results) {
+ if (result.differencePath != null && result.receivedPath != null) {
+ differences.set(
+ `Expected screenshot: ${result.expectedPath}\nReceived screenshot: ${result.receivedPath}`,
+ `Difference screenshot: ${result.differencePath}`,
+ );
+ }
+ }
+ const lines = message.split('\n');
+ return lines
+ .flatMap((line, index) => {
+ const difference = differences.get(`${lines[index - 1]}\n${line}`);
+ return difference == null || lines[index + 1] === difference
+ ? [line]
+ : [line, difference];
+ })
+ .join('\n');
+}
+
+export function processScreenshotResults(
+ config: ScreenshotConfig,
+ results: ReadonlyArray,
+ updateSnapshot: UpdateSnapshot,
+ testResults: ReadonlyArray>,
+): void {
+ const used = new Set();
+ const errors: Array = [];
+ for (const result of results) {
+ used.add(result.fileName);
+ const receivedPath = result.receivedPath;
+ if (receivedPath == null) {
+ continue;
+ }
+ if (
+ !result.pass &&
+ updateSnapshot !== 'all' &&
+ !(result.isNew && updateSnapshot === 'new')
+ ) {
+ continue;
+ }
+ try {
+ fs.mkdirSync(config.snapshotDirectory, {recursive: true});
+ fs.copyFileSync(receivedPath, result.expectedPath);
+ fs.rmSync(receivedPath, {force: true});
+ } catch (error: unknown) {
+ errors.push(`${result.expectedPath}: ${String(error)}`);
+ }
+ }
+ if (
+ errors.length === 0 &&
+ updateSnapshot === 'all' &&
+ testResults.length > 0 &&
+ testResults.every(result => result.status === 'passed')
+ ) {
+ for (const file of config.files) {
+ if (!used.has(file)) {
+ const imagePath = path.join(config.snapshotDirectory, file);
+ try {
+ fs.rmSync(imagePath, {force: true});
+ } catch (error: unknown) {
+ errors.push(`${imagePath}: ${String(error)}`);
+ }
+ }
+ }
+ }
+ if (errors.length > 0) {
+ throw new Error(
+ `Failed to process Fantom screenshot snapshots:\n${errors.join('\n')}`,
+ );
+ }
+}
diff --git a/private/react-native-fantom/runner/snapshotUtils.js b/private/react-native-fantom/runner/snapshotUtils.js
index f44edbbe6540..ff1edbf4629c 100644
--- a/private/react-native-fantom/runner/snapshotUtils.js
+++ b/private/react-native-fantom/runner/snapshotUtils.js
@@ -8,17 +8,15 @@
* @format
*/
-import type {
- TestInlineSnapshotResults,
- TestSnapshotResults,
-} from '../runtime/snapshotContext';
+import type {TestCaseResult} from '../runtime/setup';
+import type {TestInlineSnapshotResults} from '../runtime/snapshotContext';
import type {SnapshotState} from 'jest-snapshot';
import {symbolicateStackTrace} from './utils';
import fs from 'node:fs';
import path from 'node:path';
-type JestSnapshotResult = {
+export type JestSnapshotResult = {
added: number,
fileDeleted: boolean,
matched: number,
@@ -295,9 +293,15 @@ export function saveInlineSnapshotsToSource(
export const updateSnapshotsAndGetJestSnapshotResult = (
snapshotState: SnapshotState,
- testSnapshotResults: Array,
+ testResults: ReadonlyArray<
+ Readonly<{
+ status: TestCaseResult['status'],
+ snapshotResults: TestCaseResult['snapshotResults'],
+ ...
+ }>,
+ >,
): JestSnapshotResult => {
- for (const snapshotResults of testSnapshotResults) {
+ for (const {snapshotResults} of testResults) {
for (const [key, result] of Object.entries(snapshotResults)) {
if (result.pass) {
snapshotState.matched++;
@@ -314,7 +318,6 @@ export const updateSnapshotsAndGetJestSnapshotResult = (
snapshotState._dirty = true;
snapshotState._snapshotData[key] = addExtraLineBreaks(result.value);
snapshotState.added++;
- snapshotState.matched++;
snapshotState._uncheckedKeys.delete(key);
continue;
@@ -332,8 +335,11 @@ export const updateSnapshotsAndGetJestSnapshotResult = (
}
}
- const uncheckedCount = snapshotState.getUncheckedCount();
- const uncheckedKeys = snapshotState.getUncheckedKeys();
+ const allTestsPassed =
+ testResults.length > 0 &&
+ testResults.every(result => result.status === 'passed');
+ const uncheckedCount = allTestsPassed ? snapshotState.getUncheckedCount() : 0;
+ const uncheckedKeys = allTestsPassed ? snapshotState.getUncheckedKeys() : [];
if (uncheckedCount) {
snapshotState.removeUncheckedKeys();
}
@@ -343,7 +349,8 @@ export const updateSnapshotsAndGetJestSnapshotResult = (
added: snapshotState.added,
fileDeleted: status.deleted,
matched: snapshotState.matched,
- unchecked: status.deleted ? 0 : snapshotState.getUncheckedCount(),
+ unchecked:
+ status.deleted || !allTestsPassed ? 0 : snapshotState.getUncheckedCount(),
uncheckedKeys: [...uncheckedKeys],
unmatched: snapshotState.unmatched,
updated: snapshotState.updated,
diff --git a/private/react-native-fantom/runtime/ScreenshotContext.js b/private/react-native-fantom/runtime/ScreenshotContext.js
new file mode 100644
index 000000000000..813ad9d86172
--- /dev/null
+++ b/private/react-native-fantom/runtime/ScreenshotContext.js
@@ -0,0 +1,99 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+import type Screenshot from '../src/Screenshot';
+
+export type ScreenshotConfig = Readonly<{
+ snapshotDirectory: string,
+ receivedDirectory: string,
+ files: ReadonlyArray,
+}>;
+
+export type ScreenshotResult = Readonly<{
+ fileName: string,
+ expectedPath: string,
+ receivedPath: ?string,
+ differencePath?: string,
+ pass: boolean,
+ isNew: boolean,
+}>;
+
+export type UpdateSnapshot = 'all' | 'new' | 'none';
+
+function getFileName(key: string): string {
+ let hash = 0;
+ let secondHash = 0;
+ for (let index = 0; index < key.length; index++) {
+ const character = key.charCodeAt(index);
+ hash = (hash * 31 + character) % 4294967291;
+ secondHash = (secondHash * 37 + character) % 4294967279;
+ }
+ const name = key.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 100);
+ return `${name}-${hash.toString(16)}-${secondHash.toString(16)}.png`;
+}
+
+export class ScreenshotContext {
+ #config: ?ScreenshotConfig;
+ #results: Array = [];
+
+ configure(config: ?ScreenshotConfig): void {
+ this.#config = config;
+ }
+
+ setTargetTest(_testFullName: string): void {
+ this.#results = [];
+ }
+
+ record(
+ screenshot: Screenshot,
+ key: string,
+ matchesHash: boolean,
+ isNew: boolean,
+ ): boolean {
+ const config = this.#config;
+ if (config == null) {
+ throw new Error(
+ 'Screenshot snapshots must run inside a Fantom Jest test.',
+ );
+ }
+ const fileName = getFileName(key);
+ const expectedPath = `${config.snapshotDirectory}/${fileName}`;
+ const receivedPath =
+ matchesHash && config.files.includes(fileName)
+ ? null
+ : `${config.receivedDirectory}/${fileName}`;
+ if (receivedPath != null) {
+ screenshot.saveToFile(receivedPath);
+ }
+ this.#results.push({
+ fileName,
+ expectedPath,
+ receivedPath,
+ pass: matchesHash,
+ isNew,
+ });
+ return matchesHash;
+ }
+
+ getFailureMessage(): string {
+ const result = this.#results[this.#results.length - 1];
+ const receivedPath = result?.receivedPath;
+ if (receivedPath == null) {
+ throw new Error('No failing screenshot to report.');
+ }
+ return `Expected screenshot: ${result.expectedPath}\nReceived screenshot: ${receivedPath}\nOpen these files to compare the images. Rerun the test with --updateSnapshot (-u) to accept the new screenshot.`;
+ }
+
+ getResults(): Array {
+ return [...this.#results];
+ }
+}
+
+export const screenshotContext: ScreenshotContext = new ScreenshotContext();
diff --git a/private/react-native-fantom/runtime/__tests__/ScreenshotContext-test.js b/private/react-native-fantom/runtime/__tests__/ScreenshotContext-test.js
new file mode 100644
index 000000000000..488624ca43ad
--- /dev/null
+++ b/private/react-native-fantom/runtime/__tests__/ScreenshotContext-test.js
@@ -0,0 +1,216 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+import type {ScreenshotConfig} from '../ScreenshotContext';
+
+import Screenshot from '../../src/Screenshot';
+import runtimeExpect from '../expect';
+import {ScreenshotContext, screenshotContext} from '../ScreenshotContext';
+import {setupSnapshotConfig, snapshotContext} from '../snapshotContext';
+
+function createScreenshot() {
+ const saveToFile = jest.fn<[string], void>();
+ const screenshot = new Screenshot({
+ saveToFile,
+ getHash: () => 'pixel-hash',
+ isEqual: () => true,
+ });
+ return {screenshot, saveToFile};
+}
+
+function createContext(files: Array = []): ScreenshotContext {
+ const context = new ScreenshotContext();
+ context.configure({
+ snapshotDirectory: '/snapshots',
+ receivedDirectory: '/received',
+ files,
+ });
+ context.setTargetTest('Example renders');
+ return context;
+}
+
+it('reports a missing failure without an incidental property access error', () => {
+ expect(() => createContext().getFailureMessage()).toThrow(
+ 'No failing screenshot to report.',
+ );
+});
+
+for (const mode of ['new', 'none', 'all'] as const) {
+ it(`compares inline screenshot hashes without saving images in ${mode} mode`, () => {
+ const {screenshot, saveToFile} = createScreenshot();
+ const serialized =
+ '\nObject {\n "hash": "pixel-hash",\n "type": "Screenshot",\n}\n';
+ setupSnapshotConfig({updateSnapshot: mode, data: {}});
+ snapshotContext.setTargetTest('inline screenshot');
+ runtimeExpect(screenshot).toMatchInlineSnapshot(serialized);
+ expect(snapshotContext.getInlineSnapshotResults()).toEqual([{pass: true}]);
+
+ const mismatch = () =>
+ runtimeExpect(screenshot).toMatchInlineSnapshot(
+ serialized.replace('pixel-hash', 'old-hash'),
+ );
+ if (mode === 'all') {
+ mismatch();
+ } else {
+ let message;
+ try {
+ mismatch();
+ } catch (error) {
+ message = error.message;
+ }
+ expect(message).toContain('Expected to match inline snapshot.');
+ }
+ expect(snapshotContext.getInlineSnapshotResults()[1].value).toBe(
+ serialized,
+ );
+ expect(snapshotContext.getSnapshotResults()).toEqual({});
+ expect(screenshotContext.getResults()).toEqual([]);
+ expect(saveToFile).not.toHaveBeenCalled();
+ });
+}
+
+it('creates an inline screenshot hash without saving an image', () => {
+ const {screenshot, saveToFile} = createScreenshot();
+ setupSnapshotConfig({updateSnapshot: 'new', data: {}});
+ snapshotContext.setTargetTest('inline screenshot');
+ runtimeExpect(screenshot).toMatchInlineSnapshot();
+ expect(snapshotContext.getInlineSnapshotResults()[0].isNew).toBe(true);
+ expect(snapshotContext.getInlineSnapshotResults()[0].value).toContain(
+ '"hash": "pixel-hash"',
+ );
+ expect(screenshotContext.getResults()).toEqual([]);
+ expect(saveToFile).not.toHaveBeenCalled();
+});
+
+it('writes an inspectable image for a new snapshot and exposes failure paths', () => {
+ const context = createContext();
+ const {screenshot, saveToFile} = createScreenshot();
+ expect(context.record(screenshot, 'Example renders 1', false, true)).toBe(
+ false,
+ );
+ const result = context.getResults()[0];
+ expect(result.isNew).toBe(true);
+ expect(saveToFile).toHaveBeenCalledWith(result.receivedPath);
+ expect(context.getFailureMessage()).toContain(result.expectedPath);
+ expect(context.getFailureMessage()).toContain('--updateSnapshot');
+});
+
+it('does not encode or save a passing screenshot', () => {
+ const {screenshot, saveToFile} = createScreenshot();
+ const initial = createContext();
+ initial.record(screenshot, 'Example renders 1', false, true);
+ const context = createContext([initial.getResults()[0].fileName]);
+ saveToFile.mockClear();
+ expect(context.record(screenshot, 'Example renders 1', true, false)).toBe(
+ true,
+ );
+ expect(saveToFile).not.toHaveBeenCalled();
+ expect(context.getResults()[0].receivedPath).toBe(null);
+});
+
+it('saves a matching screenshot when its standalone image is missing', () => {
+ const context = createContext();
+ const {screenshot, saveToFile} = createScreenshot();
+ expect(context.record(screenshot, 'Example renders 1', true, false)).toBe(
+ true,
+ );
+ expect(saveToFile).toHaveBeenCalledTimes(1);
+ expect(context.getResults()[0].pass).toBe(true);
+});
+
+for (const mode of ['new', 'none', 'all'] as const) {
+ it(`matches the stored hash without an image in ${mode} mode`, () => {
+ const {screenshot, saveToFile} = createScreenshot();
+ setupSnapshotConfig({
+ updateSnapshot: mode,
+ data: {'Example renders 1': 'pixel-hash'},
+ screenshots: {
+ snapshotDirectory: '/snapshots',
+ receivedDirectory: '/received',
+ files: [],
+ },
+ });
+ snapshotContext.setTargetTest('Example renders');
+ screenshotContext.setTargetTest('Example renders');
+ snapshotContext.toMatchSnapshot('pixel-hash', null, screenshot);
+ expect(snapshotContext.getSnapshotResults()['Example renders 1'].pass).toBe(
+ true,
+ );
+ expect(saveToFile).toHaveBeenCalledTimes(1);
+ });
+}
+
+it('keeps names bounded and distinguishes sanitized snapshot keys', () => {
+ const context = createContext();
+ const {screenshot} = createScreenshot();
+ context.record(screenshot, `${'a'.repeat(400)}: ../first 1`, false, true);
+ context.record(screenshot, `${'a'.repeat(400)}: ..\\first 1`, false, true);
+ const [first, second] = context.getResults();
+ expect(first.fileName.length).toBeLessThan(255);
+ expect(first.fileName).not.toContain('/');
+ expect(first.fileName).not.toBe(second.fileName);
+});
+
+it('uses normal snapshot keys and honors new, update, and CI modes', () => {
+ const {screenshot} = createScreenshot();
+ const config: ScreenshotConfig = {
+ snapshotDirectory: '/snapshots',
+ receivedDirectory: '/received',
+ files: [],
+ };
+ const key = 'Example renders: image 2';
+ setupSnapshotConfig({updateSnapshot: 'new', data: {}, screenshots: config});
+ snapshotContext.setTargetTest('Example renders');
+ screenshotContext.setTargetTest('Example renders');
+ snapshotContext.toMatchSnapshot('text', null);
+ snapshotContext.toMatchSnapshot('pixel-hash', 'image', screenshot);
+ expect(Object.keys(snapshotContext.getSnapshotResults())).toEqual([
+ 'Example renders 1',
+ key,
+ ]);
+ const fileName = screenshotContext.getResults()[0].fileName;
+ for (const mode of ['new', 'none', 'all'] as const) {
+ setupSnapshotConfig({
+ updateSnapshot: mode,
+ data: {'Example renders 1': 'text', [key]: 'old-hash'},
+ screenshots: {...config, files: [fileName]},
+ });
+ snapshotContext.setTargetTest('Example renders');
+ snapshotContext.toMatchSnapshot('text', null);
+ const match = () =>
+ snapshotContext.toMatchSnapshot('pixel-hash', 'image', screenshot);
+ if (mode === 'all') {
+ match();
+ } else {
+ expect(match).toThrow('Expected to match snapshot.');
+ }
+ expect(snapshotContext.getSnapshotResults()[key]).toEqual({
+ pass: false,
+ value: 'pixel-hash',
+ });
+ }
+});
+
+it('requires configuration and propagates save errors', () => {
+ const {screenshot} = createScreenshot();
+ expect(() =>
+ new ScreenshotContext().record(screenshot, 'test 1', false, true),
+ ).toThrow('inside a Fantom Jest test');
+ const failure = new Screenshot({
+ saveToFile: () => {
+ throw new Error('Cannot save PNG');
+ },
+ getHash: () => 'hash',
+ isEqual: () => false,
+ });
+ expect(() => createContext().record(failure, 'test 1', false, true)).toThrow(
+ 'Cannot save PNG',
+ );
+});
diff --git a/private/react-native-fantom/runtime/__tests__/setup-test.js b/private/react-native-fantom/runtime/__tests__/setup-test.js
new file mode 100644
index 000000000000..d860ac8e5004
--- /dev/null
+++ b/private/react-native-fantom/runtime/__tests__/setup-test.js
@@ -0,0 +1,168 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+const jestExpect = expect;
+const jestRuntime = jest;
+const globalNames = [
+ 'describe',
+ 'fdescribe',
+ 'xdescribe',
+ 'it',
+ 'fit',
+ 'xit',
+ 'test',
+ 'xtest',
+ 'afterAll',
+ 'afterEach',
+ 'beforeAll',
+ 'beforeEach',
+ 'expect',
+ 'jest',
+ '$$RunTests$$',
+];
+let descriptors: Map;
+
+jest.mock('../expect', () => () => {});
+jest.mock('../patchWeakRef', () => () => {});
+jest.mock(
+ '../../../../packages/react-native/src/private/testing/fantom/specs/NativeFantom',
+ () => ({
+ __esModule: true,
+ default: {
+ validateEmptyMessageQueue: jest.fn(),
+ reportTestSuiteResultsJSON: jest.fn(),
+ },
+ }),
+);
+
+beforeEach(() => {
+ descriptors = new Map(
+ globalNames.map(name => [
+ name,
+ Object.getOwnPropertyDescriptor(global, name),
+ ]),
+ );
+ jestRuntime.resetModules();
+});
+
+afterEach(() => {
+ for (const [name, descriptor] of descriptors) {
+ if (descriptor == null) {
+ delete global[name];
+ } else {
+ Object.defineProperty(global, name, descriptor);
+ }
+ }
+});
+
+function results() {
+ const NativeFantom =
+ require('../../../../packages/react-native/src/private/testing/fantom/specs/NativeFantom').default;
+ let report;
+ jestRuntime
+ .spyOn(NativeFantom, 'reportTestSuiteResultsJSON')
+ .mockImplementation(json => {
+ report = JSON.parse(json);
+ });
+ global.$$RunTests$$();
+ return report?.testResults ?? [];
+}
+
+it('runs teardown after a failed test before running the next test', () => {
+ const {registerTest} = require('../setup');
+ const events = [];
+ registerTest(
+ () => {
+ beforeEach(() => {
+ events.push('setup');
+ });
+ afterEach(() => {
+ events.push('teardown');
+ });
+ it('fails', () => {
+ events.push('failed test');
+ throw new Error('assertion failed');
+ });
+ it('passes', () => {
+ events.push('next test');
+ });
+ },
+ {data: {}, updateSnapshot: 'none'},
+ );
+ const [failed, passed] = results();
+ jestExpect(failed.status).toBe('failed');
+ jestExpect(failed.failureMessages[0]).toContain('assertion failed');
+ jestExpect(passed.status).toBe('passed');
+ jestExpect(events).toEqual([
+ 'setup',
+ 'failed test',
+ 'teardown',
+ 'setup',
+ 'next test',
+ 'teardown',
+ ]);
+});
+
+for (const nonErrorPosition of ['test', 'teardown']) {
+ it(`keeps error details aligned when ${nonErrorPosition} throws a non-Error value`, () => {
+ const {registerTest} = require('../setup');
+ const error = new Error('ordinary error');
+ const errors =
+ nonErrorPosition === 'test'
+ ? ['non-error failure', error]
+ : [error, 'non-error failure'];
+ registerTest(
+ () => {
+ afterEach(() => {
+ throw errors[1];
+ });
+ it(`fails with non-Error in ${nonErrorPosition}`, () => {
+ throw errors[0];
+ });
+ },
+ {data: {}, updateSnapshot: 'none'},
+ );
+ const [failed] = results();
+ const nonErrorIndex = nonErrorPosition === 'test' ? 0 : 1;
+ const errorIndex = 1 - nonErrorIndex;
+ jestExpect(failed.failureMessages.length).toBe(2);
+ jestExpect(failed.failureDetails.length).toBe(2);
+ jestExpect(failed.failureDetails[nonErrorIndex]).toBe(null);
+ jestExpect(failed.failureDetails[errorIndex].message).toBe(
+ 'ordinary error',
+ );
+ jestExpect(failed.failureMessages[nonErrorIndex]).toContain(
+ 'non-error failure',
+ );
+ jestExpect(failed.failureMessages[errorIndex]).toContain('ordinary error');
+ });
+}
+
+it('runs teardown after a failed setup and retains both errors', () => {
+ const {registerTest} = require('../setup');
+ registerTest(
+ () => {
+ beforeEach(() => {
+ throw new Error('setup failed');
+ });
+ afterEach(() => {
+ throw new Error('teardown failed');
+ });
+ it('does not run', () => {
+ throw new Error('test should not run');
+ });
+ },
+ {data: {}, updateSnapshot: 'none'},
+ );
+ const [failed] = results();
+ jestExpect(failed.status).toBe('failed');
+ jestExpect(failed.failureDetails[0].message).toBe('setup failed');
+ jestExpect(failed.failureDetails[1].message).toBe('teardown failed');
+});
diff --git a/private/react-native-fantom/runtime/expect.js b/private/react-native-fantom/runtime/expect.js
index 1623f0961e10..8362f4710532 100644
--- a/private/react-native-fantom/runtime/expect.js
+++ b/private/react-native-fantom/runtime/expect.js
@@ -520,12 +520,15 @@ class Expect {
).blameToPreviousFrame();
}
+ const Screenshot = require('../src/Screenshot').default;
+ const screenshot =
+ this.#received instanceof Screenshot ? this.#received : undefined;
const receivedValue = format(this.#received, {
plugins: [plugins.ReactElement],
});
try {
- snapshotContext.toMatchSnapshot(receivedValue, expected);
+ snapshotContext.toMatchSnapshot(receivedValue, expected, screenshot);
} catch (err) {
throw new ErrorWithCustomBlame(err.message).blameToPreviousFrame();
}
diff --git a/private/react-native-fantom/runtime/setup.js b/private/react-native-fantom/runtime/setup.js
index 91cbb2f897d9..1f0bef4a4104 100644
--- a/private/react-native-fantom/runtime/setup.js
+++ b/private/react-native-fantom/runtime/setup.js
@@ -10,6 +10,7 @@
import type {CoverageMap} from '../runner/coverage/types.flow';
import type {BenchmarkResult} from '../src/Benchmark';
+import type {ScreenshotResult} from './ScreenshotContext';
import type {
SnapshotConfig,
TestInlineSnapshotResults,
@@ -20,6 +21,7 @@ import {getConstants} from '../src/Constants';
import expect from './expect';
import {createMockFunction} from './mocks';
import patchWeakRef from './patchWeakRef';
+import {screenshotContext} from './ScreenshotContext';
import {setupSnapshotConfig, snapshotContext} from './snapshotContext';
export type TestCaseResult = {
@@ -29,10 +31,11 @@ export type TestCaseResult = {
status: 'passed' | 'failed' | 'pending',
duration: number,
failureMessages: Array,
- failureDetails: Array,
+ failureDetails: Array,
numPassingAsserts: number,
snapshotResults: TestSnapshotResults,
inlineSnapshotResults: TestInlineSnapshotResults,
+ screenshotResults: Array,
// location: string,
};
@@ -323,46 +326,49 @@ function runSpec(spec: Spec): TestCaseResult {
numPassingAsserts: 0,
snapshotResults: {},
inlineSnapshotResults: [],
+ screenshotResults: [],
};
if (!shouldRunSuite(spec)) {
return result;
}
- let status: 'passed' | 'failed' | 'pending';
- let error: unknown;
+ const errors: Array = [];
const start = Date.now();
snapshotContext.setTargetTest(result.fullName);
+ screenshotContext.setTargetTest(result.fullName);
try {
invokeHooks(spec.parentContext, 'beforeEachHooks');
spec.implementation();
- invokeHooks(spec.parentContext, 'afterEachHooks');
+ } catch (e: unknown) {
+ errors.push(e);
+ }
- status = 'passed';
+ try {
+ invokeHooks(spec.parentContext, 'afterEachHooks');
} catch (e: unknown) {
- error = e;
- status = 'failed';
+ errors.push(e);
}
- result.status = status;
+ result.status = errors.length === 0 ? 'passed' : 'failed';
result.duration = Date.now() - start;
- if (status === 'failed' && error != null) {
+ for (const error of errors) {
if (error instanceof Error) {
- result.failureMessages = [error.stack ?? error.message ?? String(error)];
- result.failureDetails = [serializeError(error)];
+ result.failureMessages.push(
+ error.stack ?? error.message ?? String(error),
+ );
+ result.failureDetails.push(serializeError(error));
} else {
- result.failureMessages = [`Non-error value thrown: ${String(error)}`];
- result.failureDetails = [];
+ result.failureMessages.push(`Non-error value thrown: ${String(error)}`);
+ result.failureDetails.push(null);
}
- } else {
- result.failureMessages = [];
- result.failureDetails = [];
}
result.snapshotResults = snapshotContext.getSnapshotResults();
result.inlineSnapshotResults = snapshotContext.getInlineSnapshotResults();
+ result.screenshotResults = screenshotContext.getResults();
return result;
}
diff --git a/private/react-native-fantom/runtime/snapshotContext.js b/private/react-native-fantom/runtime/snapshotContext.js
index e89b54c80ba1..245d381a62bc 100644
--- a/private/react-native-fantom/runtime/snapshotContext.js
+++ b/private/react-native-fantom/runtime/snapshotContext.js
@@ -8,11 +8,16 @@
* @format
*/
+import type Screenshot from '../src/Screenshot';
+import type {ScreenshotConfig} from './ScreenshotContext';
+
+import {screenshotContext} from './ScreenshotContext';
import {diff} from 'jest-diff';
export type SnapshotConfig = {
updateSnapshot: 'all' | 'new' | 'none',
data: {[key: string]: string},
+ screenshots?: ScreenshotConfig,
};
export type TestSnapshotResults = {
@@ -32,8 +37,6 @@ export type InlineSnapshotResult =
export type TestInlineSnapshotResults = Array;
-const COMPARISON_EQUALS_STRING = 'Compared values have no visual difference.';
-
const INDENTATION_REGEX: RegExp = /^([^\S\n]*)\S/m;
let snapshotConfig: ?SnapshotConfig;
@@ -94,57 +97,48 @@ class SnapshotContext {
};
}
- toMatchSnapshot(received: string, label: ?string): void {
+ toMatchSnapshot(
+ received: string,
+ label: ?string,
+ screenshot?: Screenshot,
+ ): void {
const snapshotState = this.#snapshotState;
if (snapshotState == null) {
throw new Error(
'Snapshot state is not set, call `setTargetTest()` first',
);
}
-
- const snapshotKey = `${snapshotState.testFullName}${
- label != null ? `: ${label}` : ''
- } ${++snapshotState.callCount}`;
-
- if (snapshotConfig == null) {
+ const config = snapshotConfig;
+ if (config == null) {
throw new Error(
'Snapshot config is not set. Did you forget to call `setupSnapshotConfig`?',
);
}
-
- const updateSnapshot = snapshotConfig.updateSnapshot;
- const snapshot = snapshotConfig.data[snapshotKey];
-
- if (snapshot == null) {
- snapshotState.snapshotResults[snapshotKey] = {
- pass: false,
- value: received,
- };
-
- if (updateSnapshot === 'none') {
- throw new Error(
- `Expected to have snapshot \`${snapshotKey}\` but it was not found.`,
- );
- }
-
- return;
+ const key = `${snapshotState.testFullName}${label != null ? `: ${label}` : ''} ${++snapshotState.callCount}`;
+ const snapshot = config.data[key];
+ const isNew = snapshot == null;
+ let pass = snapshot === received;
+ if (screenshot != null) {
+ pass = screenshotContext.record(screenshot, key, pass, isNew);
}
-
- const result = diff(snapshot, received) ?? 'Failed to compare output';
- if (result !== COMPARISON_EQUALS_STRING) {
- snapshotState.snapshotResults[snapshotKey] = {
- pass: false,
- value: received,
- };
-
- if (updateSnapshot !== 'all') {
- throw new Error(`Expected to match snapshot.\n${result}`);
- }
-
+ snapshotState.snapshotResults[key] = pass
+ ? {pass: true}
+ : {pass: false, value: received};
+ if (
+ pass ||
+ config.updateSnapshot === 'all' ||
+ (isNew && config.updateSnapshot === 'new')
+ ) {
return;
}
-
- snapshotState.snapshotResults[snapshotKey] = {pass: true};
+ const message = isNew
+ ? `Expected to have snapshot \`${key}\` but it was not found.`
+ : `Expected to match snapshot.\n${diff(snapshot, received) ?? 'Failed to compare output'}`;
+ throw new Error(
+ screenshot == null
+ ? message
+ : `${message}\n${screenshotContext.getFailureMessage()}`,
+ );
}
toMatchInlineSnapshot(
@@ -221,4 +215,5 @@ export const snapshotContext: SnapshotContext = new SnapshotContext();
export function setupSnapshotConfig(config: SnapshotConfig) {
snapshotConfig = config;
+ screenshotContext.configure(config.screenshots);
}
diff --git a/private/react-native-fantom/src/Screenshot.js b/private/react-native-fantom/src/Screenshot.js
new file mode 100644
index 000000000000..7f6ef71e9012
--- /dev/null
+++ b/private/react-native-fantom/src/Screenshot.js
@@ -0,0 +1,38 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+type NativeScreenshot = {
+ saveToFile(filePath: string): void,
+ isEqual(other: NativeScreenshot): boolean,
+ getHash(): string,
+};
+
+export default class Screenshot {
+ #nativeScreenshot: NativeScreenshot;
+
+ constructor(nativeScreenshot: NativeScreenshot) {
+ this.#nativeScreenshot = nativeScreenshot;
+ }
+
+ saveToFile(filePath: string): void {
+ this.#nativeScreenshot.saveToFile(filePath);
+ }
+
+ isEqual(other: Screenshot): boolean {
+ return (
+ other instanceof Screenshot &&
+ this.#nativeScreenshot.isEqual(other.#nativeScreenshot)
+ );
+ }
+
+ toJSON(): {type: 'Screenshot', hash: string} {
+ return {type: 'Screenshot', hash: this.#nativeScreenshot.getHash()};
+ }
+}
diff --git a/private/react-native-fantom/src/__tests__/FantomAnimationScreenshot-itest.js b/private/react-native-fantom/src/__tests__/FantomAnimationScreenshot-itest.js
new file mode 100644
index 000000000000..5812c4b31e7b
--- /dev/null
+++ b/private/react-native-fantom/src/__tests__/FantomAnimationScreenshot-itest.js
@@ -0,0 +1,91 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @fantom_flags useSharedAnimatedBackend:true
+ * @flow strict-local
+ * @format
+ */
+
+import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
+
+import type {Root} from '@react-native/fantom';
+
+import * as Fantom from '@react-native/fantom';
+import * as React from 'react';
+import {Animated, Easing, View} from 'react-native';
+
+let root: Root;
+let animation: ?Animated.CompositeAnimation;
+
+beforeEach(() => {
+ root = Fantom.createRoot({
+ viewportWidth: 200,
+ viewportHeight: 80,
+ devicePixelRatio: 1,
+ });
+ animation = null;
+});
+
+afterEach(() => {
+ if (animation != null) {
+ Fantom.runTask(() => animation?.stop());
+ }
+ root.destroy();
+});
+
+it('captures the initial, intermediate and final states of a native layout animation', () => {
+ const marginLeft = new Animated.Value(0);
+ Fantom.runTask(() =>
+ root.render(
+
+
+ ,
+ ),
+ );
+ const initial = root.takeScreenshot();
+ expect(initial).toMatchSnapshot('initial');
+
+ let finished = false;
+ Fantom.runTask(() => {
+ animation = Animated.timing(marginLeft, {
+ toValue: 120,
+ duration: 1000,
+ easing: Easing.linear,
+ useNativeDriver: true,
+ });
+ animation.start(result => {
+ finished = result.finished;
+ });
+ });
+ Fantom.unstable_produceFramesForDuration(500);
+ const intermediate = root.takeScreenshot();
+ expect(intermediate.isEqual(initial)).toBe(false);
+ expect(intermediate).toMatchSnapshot('intermediate');
+ expect(finished).toBe(false);
+
+ Fantom.unstable_produceFramesForDuration(600);
+ Fantom.runWorkLoop();
+ const final = root.takeScreenshot();
+ expect(final.isEqual(initial)).toBe(false);
+ expect(final.isEqual(intermediate)).toBe(false);
+ expect(final).toMatchSnapshot('final');
+ expect(finished).toBe(true);
+});
diff --git a/private/react-native-fantom/src/__tests__/FantomRendering-itest.js b/private/react-native-fantom/src/__tests__/FantomRendering-itest.js
new file mode 100644
index 000000000000..2d0aa3a66b43
--- /dev/null
+++ b/private/react-native-fantom/src/__tests__/FantomRendering-itest.js
@@ -0,0 +1,58 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
+
+import type {Root} from '@react-native/fantom';
+
+import {
+ AbsolutePositionScene,
+ OverflowScene,
+ StackingScene,
+ TransformScene,
+} from './fixtures/RenderingEdgeCases';
+import * as Fantom from '@react-native/fantom';
+import * as React from 'react';
+
+let root: Root;
+
+beforeEach(() => {
+ root = Fantom.createRoot();
+});
+
+afterEach(() => {
+ root.destroy();
+});
+
+describe('Fantom rendering edge cases', () => {
+ it('preserves sibling z-index order and nested stacking after updates', () => {
+ Fantom.runTask(() => root.render());
+ expect(root.takeScreenshot()).toMatchSnapshot();
+ Fantom.runTask(() => root.render());
+ expect(root.takeScreenshot()).toMatchSnapshot('updated stacking');
+ });
+
+ it('clips overflowing descendants to rounded bounds without clipping siblings', () => {
+ Fantom.runTask(() => root.render());
+ expect(root.takeScreenshot()).toMatchSnapshot('visible overflow');
+ Fantom.runTask(() => root.render());
+ expect(root.takeScreenshot()).toMatchSnapshot('hidden overflow');
+ });
+
+ it('positions absolute children within bordered parents without affecting flow', () => {
+ Fantom.runTask(() => root.render());
+ expect(root.takeScreenshot()).toMatchSnapshot();
+ });
+
+ it('renders affine transforms and skips singular siblings at fractional coordinates', () => {
+ Fantom.runTask(() => root.render());
+ expect(root.takeScreenshot()).toMatchSnapshot();
+ });
+});
diff --git a/private/react-native-fantom/src/__tests__/FantomScreenSnapshots-itest.js b/private/react-native-fantom/src/__tests__/FantomScreenSnapshots-itest.js
new file mode 100644
index 000000000000..ae30a85a7e42
--- /dev/null
+++ b/private/react-native-fantom/src/__tests__/FantomScreenSnapshots-itest.js
@@ -0,0 +1,71 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
+
+import type {Root, RootConfig} from '@react-native/fantom';
+import type {HostInstance, ScrollViewInstance} from 'react-native';
+
+import RuntimeVersion from '../../../../packages/new-app-screen/src/RuntimeVersion';
+import FeedScreen from './fixtures/FeedScreen';
+import TravelScreen from './fixtures/TravelScreen';
+import * as Fantom from '@react-native/fantom';
+import {NewAppScreen} from '@react-native/new-app-screen';
+import * as React from 'react';
+import {createRef} from 'react';
+
+const rootConfig: RootConfig = {
+ viewportWidth: 402,
+ viewportHeight: 874,
+ devicePixelRatio: 3,
+};
+
+describe('Fantom screen snapshots', () => {
+ let root: Root;
+ const hermesVersion = RuntimeVersion.hermes;
+
+ beforeEach(() => {
+ RuntimeVersion.hermes = '';
+ root = Fantom.createRoot(rootConfig);
+ });
+
+ afterEach(() => {
+ RuntimeVersion.hermes = hermesVersion;
+ root.destroy();
+ });
+
+ it('captures the default New App Screen', () => {
+ Fantom.runTask(() => root.render());
+ expect(root.takeScreenshot()).toMatchSnapshot();
+ });
+
+ it('captures the travel screen, entered text, and scrolling', () => {
+ const scrollRef = createRef();
+ Fantom.runTask(() => root.render());
+ expect(root.takeScreenshot()).toMatchSnapshot();
+ Fantom.runTask(() =>
+ root.render(),
+ );
+ expect(root.takeScreenshot()).toMatchSnapshot('entered text');
+ Fantom.scrollTo(scrollRef, {x: 0, y: 180});
+ expect(root.takeScreenshot()).toMatchSnapshot('scrolled');
+ });
+
+ it('captures the feed and its scrolled viewport', () => {
+ const feedRef = createRef();
+ Fantom.runTask(() => root.render());
+ const initial = root.takeScreenshot();
+ expect(initial).toMatchSnapshot();
+ Fantom.scrollTo(feedRef, {x: 0, y: 360});
+ expect(root.takeScreenshot()).toMatchSnapshot('scrolled');
+ Fantom.scrollTo(feedRef, {x: 0, y: 0});
+ expect(root.takeScreenshot().isEqual(initial)).toBe(true);
+ });
+});
diff --git a/private/react-native-fantom/src/__tests__/FantomScreenshot-itest.js b/private/react-native-fantom/src/__tests__/FantomScreenshot-itest.js
new file mode 100644
index 000000000000..18ba63975ca3
--- /dev/null
+++ b/private/react-native-fantom/src/__tests__/FantomScreenshot-itest.js
@@ -0,0 +1,325 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
+
+import type {Root, RootConfig} from '@react-native/fantom';
+import type {HostInstance} from 'react-native';
+
+import * as Fantom from '@react-native/fantom';
+import nullthrows from 'nullthrows';
+import * as React from 'react';
+import {createRef, useState} from 'react';
+import {Image, ScrollView, Text, TextInput, View} from 'react-native';
+
+component ScrollableInputs(
+ scrollRef: React.RefObject,
+ nameRef: React.RefObject,
+ notesRef: React.RefObject,
+ scrollHeight?: number,
+) {
+ const [name, setName] = useState('');
+ const [notes, setNotes] = useState('');
+
+ return (
+
+ Fixed heading
+
+
+
+
+
+
+
+ );
+}
+
+const rootConfig: RootConfig = {
+ viewportWidth: 8,
+ viewportHeight: 4,
+ devicePixelRatio: 1,
+};
+
+let roots: Array;
+
+beforeEach(() => {
+ roots = [];
+});
+
+afterEach(() => {
+ for (const root of roots) {
+ root.destroy();
+ }
+});
+
+function createRoot(config: RootConfig): Root {
+ const root = Fantom.createRoot(config);
+ roots.push(root);
+ return root;
+}
+
+describe('Fantom screenshot snapshots', () => {
+ it('matches an inline screenshot hash', () => {
+ const root = createRoot(rootConfig);
+ Fantom.runTask(() =>
+ root.render(),
+ );
+ expect(root.takeScreenshot()).toMatchInlineSnapshot(`
+ Object {
+ "hash": "7ce176afc63d276869ec36bb0ad16f57098496278cfa87967206be51e2752102",
+ "type": "Screenshot",
+ }
+ `);
+ });
+
+ for (const devicePixelRatio of [3, 1, 1.5, 2]) {
+ const title =
+ 'renders gray text, translucent layers and a resized image consistently';
+ it(
+ devicePixelRatio === 3
+ ? title
+ : `${title} at pixel ratio ${devicePixelRatio}`,
+ () => {
+ const root = createRoot({
+ viewportWidth: 160,
+ viewportHeight: 140,
+ devicePixelRatio,
+ });
+ Fantom.runTask(() =>
+ root.render(
+
+
+ Gray text 123
+
+
+
+
+
+ ,
+ ),
+ );
+ expect(root.takeScreenshot()).toMatchSnapshot();
+ },
+ );
+ }
+
+ it('renders scaled text and inputs like equivalent explicit font sizes', () => {
+ const config: RootConfig = {
+ viewportWidth: 256,
+ viewportHeight: 200,
+ devicePixelRatio: 1,
+ };
+ const unscaled = createRoot(config);
+ const scaled = createRoot({...config, fontScale: 2});
+ const elements = (fontSize: number, lineHeight: number) => (
+
+ Fantom
+
+
+
+ );
+ Fantom.runTask(() => {
+ unscaled.render(elements(16, 24));
+ scaled.render(elements(16, 24));
+ });
+ const screenshot = scaled.takeScreenshot();
+ const unscaledScreenshot = unscaled.takeScreenshot();
+ expect(unscaledScreenshot).toMatchSnapshot('fontScale 1');
+ expect(screenshot).toMatchSnapshot('fontScale 2');
+ expect(screenshot.isEqual(unscaledScreenshot)).toBe(false);
+ Fantom.runTask(() => unscaled.render(elements(32, 48)));
+ expect(screenshot.isEqual(unscaled.takeScreenshot())).toBe(true);
+ });
+
+ it('captures the mounted revision without flushing pending work', () => {
+ const root = createRoot({
+ viewportWidth: 20,
+ viewportHeight: 10,
+ devicePixelRatio: 2,
+ });
+ Fantom.runTask(() =>
+ root.render(),
+ );
+ Fantom.scheduleTask(() =>
+ root.render(),
+ );
+ const pending = root.takeScreenshot();
+ expect(
+ root.getRenderedOutput({props: ['backgroundColor']}).toJSX(),
+ ).toEqual();
+ Fantom.runWorkLoop();
+ expect(root.takeScreenshot().isEqual(pending)).toBe(false);
+ });
+
+ for (const scrollHeight of [undefined, 400]) {
+ const viewport =
+ scrollHeight == null ? 'remaining screen' : 'inset viewport';
+ it(`captures entered text and scrolling in the ${viewport}`, () => {
+ const root = createRoot({
+ viewportWidth: 402,
+ viewportHeight: 874,
+ devicePixelRatio: 1,
+ });
+ const scrollRef = createRef();
+ const nameRef = createRef();
+ const notesRef = createRef();
+
+ Fantom.runTask(() =>
+ root.render(
+ ,
+ ),
+ );
+ expect(nullthrows(scrollRef.current).scrollTop).toBe(0);
+ const scrollBounds = nullthrows(
+ scrollRef.current,
+ ).getBoundingClientRect();
+ expect(nullthrows(scrollRef.current).scrollHeight).toBeGreaterThan(
+ scrollBounds.height + 240,
+ );
+ if (scrollHeight != null) {
+ expect(scrollBounds.height).toBe(scrollHeight);
+ expect(scrollBounds.x).toBe(20);
+ expect(scrollBounds.width).toBe(362);
+ expect(scrollBounds.y).toBeGreaterThan(0);
+ expect(scrollBounds.bottom).toBeLessThan(874);
+ }
+
+ const before = root.takeScreenshot();
+
+ Fantom.dispatchNativeEvent(nameRef, 'change', {
+ text: 'Ada Lovelace',
+ eventCount: 1,
+ });
+ const name = root.takeScreenshot();
+ expect(name.isEqual(before)).toBe(false);
+
+ Fantom.dispatchNativeEvent(notesRef, 'change', {
+ text: 'Build my first screen.\nExplore the learning links.',
+ eventCount: 1,
+ });
+ const inputs = root.takeScreenshot();
+ expect(inputs.isEqual(name)).toBe(false);
+
+ const inputBounds = nullthrows(nameRef.current).getBoundingClientRect();
+ Fantom.scrollTo(scrollRef, {x: 0, y: 240});
+ expect(nullthrows(scrollRef.current).scrollTop).toBe(240);
+ expect(nullthrows(scrollRef.current).getBoundingClientRect().y).toBe(
+ scrollBounds.y,
+ );
+ expect(nullthrows(nameRef.current).getBoundingClientRect().y).toBe(
+ inputBounds.y,
+ );
+
+ expect(root.takeScreenshot().isEqual(inputs)).toBe(false);
+
+ Fantom.scrollTo(scrollRef, {x: 0, y: 0});
+ expect(root.takeScreenshot().isEqual(inputs)).toBe(true);
+ });
+ }
+
+ it('captures a mounted root and its update', () => {
+ const root = createRoot(rootConfig);
+ Fantom.runTask(() =>
+ root.render(),
+ );
+ const screenshot = root.takeScreenshot();
+ expect(screenshot).toMatchSnapshot();
+ Fantom.runTask(() =>
+ root.render(),
+ );
+ expect(root.takeScreenshot()).toMatchSnapshot('updated');
+ });
+
+ it('uses the same snapshot numbering for screenshots and other values', () => {
+ const root = createRoot(rootConfig);
+ Fantom.runTask(() =>
+ root.render(),
+ );
+ expect('before screenshot').toMatchSnapshot();
+ expect(root.takeScreenshot()).toMatchSnapshot('screen');
+ expect('after screenshot').toMatchSnapshot();
+ });
+
+ it('retains pixels across root updates and destruction and compares dimensions', () => {
+ const root = Fantom.createRoot(rootConfig);
+ const smaller = Fantom.createRoot({...rootConfig, viewportWidth: 4});
+ Fantom.runTask(() =>
+ root.render(),
+ );
+ const red = root.takeScreenshot();
+ const sameRed = root.takeScreenshot();
+ expect(red.isEqual(sameRed)).toBe(true);
+ expect(sameRed.isEqual(red)).toBe(true);
+ expect(red.toJSON()).toEqual(sameRed.toJSON());
+ Fantom.runTask(() =>
+ root.render(),
+ );
+ const blue = root.takeScreenshot();
+ expect(red.isEqual(blue)).toBe(false);
+ expect(blue.isEqual(red)).toBe(false);
+ expect(red.toJSON()).not.toEqual(blue.toJSON());
+ Fantom.runTask(() =>
+ smaller.render(),
+ );
+ expect(red.isEqual(smaller.takeScreenshot())).toBe(false);
+ root.destroy();
+ smaller.destroy();
+ expect(red.isEqual(sameRed)).toBe(true);
+ expect(red).toMatchSnapshot('retained red');
+ expect(blue).toMatchSnapshot('retained blue');
+ expect(red.isEqual(blue)).toBe(false);
+ expect(() => root.takeScreenshot()).toThrow(
+ 'Cannot capture a screenshot of a destroyed root.',
+ );
+ expect(() => expect(red).not.toMatchSnapshot()).toThrow(
+ 'Snapshot matchers cannot be used with not.',
+ );
+ });
+});
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomAnimationScreenshot-itest.js.screenshots/captures_the_initial__intermediate_and_final_states_of_a_native_layout_animation__final_3-ac006828-a0ffaa8e.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomAnimationScreenshot-itest.js.screenshots/captures_the_initial__intermediate_and_final_states_of_a_native_layout_animation__final_3-ac006828-a0ffaa8e.png
new file mode 100644
index 000000000000..b12f531d7355
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomAnimationScreenshot-itest.js.screenshots/captures_the_initial__intermediate_and_final_states_of_a_native_layout_animation__final_3-ac006828-a0ffaa8e.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomAnimationScreenshot-itest.js.screenshots/captures_the_initial__intermediate_and_final_states_of_a_native_layout_animation__initial_1-899b4f8c-3d24e04e.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomAnimationScreenshot-itest.js.screenshots/captures_the_initial__intermediate_and_final_states_of_a_native_layout_animation__initial_1-899b4f8c-3d24e04e.png
new file mode 100644
index 000000000000..2742cb4577da
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomAnimationScreenshot-itest.js.screenshots/captures_the_initial__intermediate_and_final_states_of_a_native_layout_animation__initial_1-899b4f8c-3d24e04e.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomAnimationScreenshot-itest.js.screenshots/captures_the_initial__intermediate_and_final_states_of_a_native_layout_animation__intermediate_2-d44b4451-27ed6abd.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomAnimationScreenshot-itest.js.screenshots/captures_the_initial__intermediate_and_final_states_of_a_native_layout_animation__intermediate_2-d44b4451-27ed6abd.png
new file mode 100644
index 000000000000..bd4b45c05777
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomAnimationScreenshot-itest.js.screenshots/captures_the_initial__intermediate_and_final_states_of_a_native_layout_animation__intermediate_2-d44b4451-27ed6abd.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomAnimationScreenshot-itest.js.snap b/private/react-native-fantom/src/__tests__/__snapshots__/FantomAnimationScreenshot-itest.js.snap
new file mode 100644
index 000000000000..952b69967408
--- /dev/null
+++ b/private/react-native-fantom/src/__tests__/__snapshots__/FantomAnimationScreenshot-itest.js.snap
@@ -0,0 +1,22 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`captures the initial, intermediate and final states of a native layout animation: final 3`] = `
+Object {
+ "hash": "ca2cee740993b25d861e3ab7877b9145d9b61da827186f910e7f8fc565c90068",
+ "type": "Screenshot",
+}
+`;
+
+exports[`captures the initial, intermediate and final states of a native layout animation: initial 1`] = `
+Object {
+ "hash": "47ecf073addddc0874d9c73abc39ff10b6f42eee82370d3171915c4744127865",
+ "type": "Screenshot",
+}
+`;
+
+exports[`captures the initial, intermediate and final states of a native layout animation: intermediate 2`] = `
+Object {
+ "hash": "9f8383850e11b42f14a416d4782048496e5558382631a7bbba6b125a91aba309",
+ "type": "Screenshot",
+}
+`;
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_clips_overflowing_descendants_to_rounded_bounds_without_clipping_sibling-46ec444f-c400ac01.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_clips_overflowing_descendants_to_rounded_bounds_without_clipping_sibling-46ec444f-c400ac01.png
new file mode 100644
index 000000000000..dee9dcd11f5f
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_clips_overflowing_descendants_to_rounded_bounds_without_clipping_sibling-46ec444f-c400ac01.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_clips_overflowing_descendants_to_rounded_bounds_without_clipping_sibling-c8cb4e7-4d1a8bcc.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_clips_overflowing_descendants_to_rounded_bounds_without_clipping_sibling-c8cb4e7-4d1a8bcc.png
new file mode 100644
index 000000000000..c6ea5eb9699d
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_clips_overflowing_descendants_to_rounded_bounds_without_clipping_sibling-c8cb4e7-4d1a8bcc.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_positions_absolute_children_within_bordered_parents_without_affecting_fl-c6ab977f-e6c6a7e3.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_positions_absolute_children_within_bordered_parents_without_affecting_fl-c6ab977f-e6c6a7e3.png
new file mode 100644
index 000000000000..ad195f2ead77
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_positions_absolute_children_within_bordered_parents_without_affecting_fl-c6ab977f-e6c6a7e3.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_preserves_sibling_z-index_order_and_nested_stacking_after_updates_1-3a143b48-fc012bee.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_preserves_sibling_z-index_order_and_nested_stacking_after_updates_1-3a143b48-fc012bee.png
new file mode 100644
index 000000000000..952bee709738
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_preserves_sibling_z-index_order_and_nested_stacking_after_updates_1-3a143b48-fc012bee.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_preserves_sibling_z-index_order_and_nested_stacking_after_updates__updat-86e82409-b38e5e97.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_preserves_sibling_z-index_order_and_nested_stacking_after_updates__updat-86e82409-b38e5e97.png
new file mode 100644
index 000000000000..37ff9c7e5912
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_preserves_sibling_z-index_order_and_nested_stacking_after_updates__updat-86e82409-b38e5e97.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_renders_affine_transforms_and_skips_singular_siblings_at_fractional_coor-5663aa1e-9691f54d.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_renders_affine_transforms_and_skips_singular_siblings_at_fractional_coor-5663aa1e-9691f54d.png
new file mode 100644
index 000000000000..1855c204300e
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.screenshots/Fantom_rendering_edge_cases_renders_affine_transforms_and_skips_singular_siblings_at_fractional_coor-5663aa1e-9691f54d.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.snap b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.snap
new file mode 100644
index 000000000000..1006e3bcf17a
--- /dev/null
+++ b/private/react-native-fantom/src/__tests__/__snapshots__/FantomRendering-itest.js.snap
@@ -0,0 +1,43 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Fantom rendering edge cases clips overflowing descendants to rounded bounds without clipping siblings: hidden overflow 2`] = `
+Object {
+ "hash": "d96b7c47c122e6fa6e7baa6176704599759933d9dcadc45eacf2151600428a9e",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom rendering edge cases clips overflowing descendants to rounded bounds without clipping siblings: visible overflow 1`] = `
+Object {
+ "hash": "d1abab448c9de50610e7bb36a4b0d3a44ab91693a67c518c0f907de1c0d86533",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom rendering edge cases positions absolute children within bordered parents without affecting flow 1`] = `
+Object {
+ "hash": "97a42fd0b859db84a7e455b5e9d4f9e239be2b03941cb7dc0f8a515988005fbc",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom rendering edge cases preserves sibling z-index order and nested stacking after updates 1`] = `
+Object {
+ "hash": "02d66a4bc95ebd7d9d6d6ec4ccf666ac88fda34aa5b5d1ec4dfbf3eb8e02db52",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom rendering edge cases preserves sibling z-index order and nested stacking after updates: updated stacking 2`] = `
+Object {
+ "hash": "508558e0f125fdad08b6eb73d7977836b389def8f63854edb6f063ffa17c2a75",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom rendering edge cases renders affine transforms and skips singular siblings at fractional coordinates 1`] = `
+Object {
+ "hash": "a2e0e843ad978f06363351b91a5140658fb69e8d97049766cbf330959d580daf",
+ "type": "Screenshot",
+}
+`;
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_default_New_App_Screen_1-be80b08-e2d37810.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_default_New_App_Screen_1-be80b08-e2d37810.png
new file mode 100644
index 000000000000..726d551fe3e6
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_default_New_App_Screen_1-be80b08-e2d37810.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_feed_and_its_scrolled_viewport_1-7d02926c-40d84b27.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_feed_and_its_scrolled_viewport_1-7d02926c-40d84b27.png
new file mode 100644
index 000000000000..fa1ac63f5b78
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_feed_and_its_scrolled_viewport_1-7d02926c-40d84b27.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_feed_and_its_scrolled_viewport__scrolled_2-26d16dd1-857e230.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_feed_and_its_scrolled_viewport__scrolled_2-26d16dd1-857e230.png
new file mode 100644
index 000000000000..5d1529b9ccef
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_feed_and_its_scrolled_viewport__scrolled_2-26d16dd1-857e230.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_travel_screen__entered_text__and_scrolling_1-c7cc76f7-dec535b.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_travel_screen__entered_text__and_scrolling_1-c7cc76f7-dec535b.png
new file mode 100644
index 000000000000..9266b37dc97b
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_travel_screen__entered_text__and_scrolling_1-c7cc76f7-dec535b.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_travel_screen__entered_text__and_scrolling__entered_text_2-8697fbe5-4d63854c.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_travel_screen__entered_text__and_scrolling__entered_text_2-8697fbe5-4d63854c.png
new file mode 100644
index 000000000000..2ebd170ba156
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_travel_screen__entered_text__and_scrolling__entered_text_2-8697fbe5-4d63854c.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_travel_screen__entered_text__and_scrolling__scrolled_3-e34fba52-c255cd01.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_travel_screen__entered_text__and_scrolling__scrolled_3-e34fba52-c255cd01.png
new file mode 100644
index 000000000000..b731b2068d36
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.screenshots/Fantom_screen_snapshots_captures_the_travel_screen__entered_text__and_scrolling__scrolled_3-e34fba52-c255cd01.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.snap b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.snap
new file mode 100644
index 000000000000..b55f4182ac74
--- /dev/null
+++ b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.snap
@@ -0,0 +1,43 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Fantom screen snapshots captures the default New App Screen 1`] = `
+Object {
+ "hash": "5597b8c0ba6b4d0b508b6cfb6b311b4ed637534357438c68e6515ec27144118c",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screen snapshots captures the feed and its scrolled viewport 1`] = `
+Object {
+ "hash": "a71fd606e25d99e9afc33d276138ae2db1d42352ec0995d23bdaefab811eba17",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screen snapshots captures the feed and its scrolled viewport: scrolled 2`] = `
+Object {
+ "hash": "033cb89f80f8db1e3c408dded78240ce04f006b48e239220de330d43e4a61ce9",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screen snapshots captures the travel screen, entered text, and scrolling 1`] = `
+Object {
+ "hash": "e0b9e388c8a46c11c7ed39be08f1a076544832b74e6b784f5c4f271fe25867de",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screen snapshots captures the travel screen, entered text, and scrolling: entered text 2`] = `
+Object {
+ "hash": "58c4eff04819a3ae95cba4a78c488bae92a28ea17692564877920f5333b7d28f",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screen snapshots captures the travel screen, entered text, and scrolling: scrolled 3`] = `
+Object {
+ "hash": "88171d2631826041e43b4936215241ef648c0b7c741b2dcbb302d21af6fe646f",
+ "type": "Screenshot",
+}
+`;
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_captures_a_mounted_root_and_its_update_1-494e02a7-4443fa4d.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_captures_a_mounted_root_and_its_update_1-494e02a7-4443fa4d.png
new file mode 100644
index 000000000000..7f0c8ff1226c
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_captures_a_mounted_root_and_its_update_1-494e02a7-4443fa4d.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_captures_a_mounted_root_and_its_update__updated_2-5f9f2516-5ff04b44.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_captures_a_mounted_root_and_its_update__updated_2-5f9f2516-5ff04b44.png
new file mode 100644
index 000000000000..04e6063bb2c2
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_captures_a_mounted_root_and_its_update__updated_2-5f9f2516-5ff04b44.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_gray_text__translucent_layers_and_a_resized_image_consistently_1-cc3adee6-aad411c.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_gray_text__translucent_layers_and_a_resized_image_consistently_1-cc3adee6-aad411c.png
new file mode 100644
index 000000000000..a19187eeee0d
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_gray_text__translucent_layers_and_a_resized_image_consistently_1-cc3adee6-aad411c.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_gray_text__translucent_layers_and_a_resized_image_consistently_a-212ca480-68d9409c.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_gray_text__translucent_layers_and_a_resized_image_consistently_a-212ca480-68d9409c.png
new file mode 100644
index 000000000000..668eec6f446b
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_gray_text__translucent_layers_and_a_resized_image_consistently_a-212ca480-68d9409c.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_gray_text__translucent_layers_and_a_resized_image_consistently_a-d49cf163-e7947093.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_gray_text__translucent_layers_and_a_resized_image_consistently_a-d49cf163-e7947093.png
new file mode 100644
index 000000000000..a59d1d06eb26
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_gray_text__translucent_layers_and_a_resized_image_consistently_a-d49cf163-e7947093.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_gray_text__translucent_layers_and_a_resized_image_consistently_a-d49cf524-e79475ec.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_gray_text__translucent_layers_and_a_resized_image_consistently_a-d49cf524-e79475ec.png
new file mode 100644
index 000000000000..ed8c55017df8
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_gray_text__translucent_layers_and_a_resized_image_consistently_a-d49cf524-e79475ec.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_scaled_text_and_inputs_like_equivalent_explicit_font_sizes__font-f334712f-dc85824e.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_scaled_text_and_inputs_like_equivalent_explicit_font_sizes__font-f334712f-dc85824e.png
new file mode 100644
index 000000000000..e7914cec74be
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_scaled_text_and_inputs_like_equivalent_explicit_font_sizes__font-f334712f-dc85824e.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_scaled_text_and_inputs_like_equivalent_explicit_font_sizes__font-f33474f1-dc8587a8.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_scaled_text_and_inputs_like_equivalent_explicit_font_sizes__font-f33474f1-dc8587a8.png
new file mode 100644
index 000000000000..f14c1722207c
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_renders_scaled_text_and_inputs_like_equivalent_explicit_font_sizes__font-f33474f1-dc8587a8.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_retains_pixels_across_root_updates_and_destruction_and_compares_dimensio-aae099ae-82943b69.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_retains_pixels_across_root_updates_and_destruction_and_compares_dimensio-aae099ae-82943b69.png
new file mode 100644
index 000000000000..04e6063bb2c2
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_retains_pixels_across_root_updates_and_destruction_and_compares_dimensio-aae099ae-82943b69.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_retains_pixels_across_root_updates_and_destruction_and_compares_dimensio-b3cc79e9-cdf14636.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_retains_pixels_across_root_updates_and_destruction_and_compares_dimensio-b3cc79e9-cdf14636.png
new file mode 100644
index 000000000000..7f0c8ff1226c
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_retains_pixels_across_root_updates_and_destruction_and_compares_dimensio-b3cc79e9-cdf14636.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_uses_the_same_snapshot_numbering_for_screenshots_and_other_values__scree-8cb2723d-4b555e09.png b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_uses_the_same_snapshot_numbering_for_screenshots_and_other_values__scree-8cb2723d-4b555e09.png
new file mode 100644
index 000000000000..7f0c8ff1226c
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.screenshots/Fantom_screenshot_snapshots_uses_the_same_snapshot_numbering_for_screenshots_and_other_values__scree-8cb2723d-4b555e09.png differ
diff --git a/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.snap b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.snap
new file mode 100644
index 000000000000..054de6882459
--- /dev/null
+++ b/private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenshot-itest.js.snap
@@ -0,0 +1,82 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Fantom screenshot snapshots captures a mounted root and its update 1`] = `
+Object {
+ "hash": "7ce176afc63d276869ec36bb0ad16f57098496278cfa87967206be51e2752102",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screenshot snapshots captures a mounted root and its update: updated 2`] = `
+Object {
+ "hash": "6776b08d89b43a18000707a6c428ff070d3416f812e7841862688ce23de01eba",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screenshot snapshots renders gray text, translucent layers and a resized image consistently 1`] = `
+Object {
+ "hash": "a8cc60158a96a1cbeb3fcc00440de4873c49088ce57742f4fa2d0cada28879db",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screenshot snapshots renders gray text, translucent layers and a resized image consistently at pixel ratio 1 1`] = `
+Object {
+ "hash": "730d828dd3fdb645695a9013cc7fe33521d447922aa6e370808d74d675c6447e",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screenshot snapshots renders gray text, translucent layers and a resized image consistently at pixel ratio 1.5 1`] = `
+Object {
+ "hash": "ca9a34175147ddee02d02c2ab46c9515c8d7205650d437e837ac2ea50d7b1af4",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screenshot snapshots renders gray text, translucent layers and a resized image consistently at pixel ratio 2 1`] = `
+Object {
+ "hash": "f4c961ba63f504075bfa5dc72a33f363b1ae15ec39551ea6c7078f819f508b40",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screenshot snapshots renders scaled text and inputs like equivalent explicit font sizes: fontScale 1 1`] = `
+Object {
+ "hash": "51f11368745b4752dbbe86dcfa8006f5a90c6b4532edc5459be6c2dffde65164",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screenshot snapshots renders scaled text and inputs like equivalent explicit font sizes: fontScale 2 2`] = `
+Object {
+ "hash": "d6787d29529adbc2b9a7f77e30d28dfbd301d6b7a7d7662aebe528b6852dcf5d",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screenshot snapshots retains pixels across root updates and destruction and compares dimensions: retained blue 2`] = `
+Object {
+ "hash": "6776b08d89b43a18000707a6c428ff070d3416f812e7841862688ce23de01eba",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screenshot snapshots retains pixels across root updates and destruction and compares dimensions: retained red 1`] = `
+Object {
+ "hash": "7ce176afc63d276869ec36bb0ad16f57098496278cfa87967206be51e2752102",
+ "type": "Screenshot",
+}
+`;
+
+exports[`Fantom screenshot snapshots uses the same snapshot numbering for screenshots and other values 1`] = `"before screenshot"`;
+
+exports[`Fantom screenshot snapshots uses the same snapshot numbering for screenshots and other values 3`] = `"after screenshot"`;
+
+exports[`Fantom screenshot snapshots uses the same snapshot numbering for screenshots and other values: screen 2`] = `
+Object {
+ "hash": "7ce176afc63d276869ec36bb0ad16f57098496278cfa87967206be51e2752102",
+ "type": "Screenshot",
+}
+`;
diff --git a/private/react-native-fantom/src/__tests__/fixtures/FeedScreen.js b/private/react-native-fantom/src/__tests__/fixtures/FeedScreen.js
new file mode 100644
index 000000000000..1deddaadbb22
--- /dev/null
+++ b/private/react-native-fantom/src/__tests__/fixtures/FeedScreen.js
@@ -0,0 +1,593 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+import type {HostInstance} from 'react-native';
+
+import * as React from 'react';
+import {
+ Image,
+ ScrollView,
+ StyleSheet,
+ Text,
+ TextInput,
+ View,
+} from 'react-native';
+
+const ASSETS = {
+ bunny: require('../../../../../packages/rn-tester/js/assets/bunny.png'),
+ ducky: require('../../../../../packages/rn-tester/js/assets/rubber-ducky.png'),
+ flowers: require('../../../../../packages/rn-tester/js/assets/flowers.png'),
+ hawk: require('../../../../../packages/rn-tester/js/assets/hawk.png'),
+ home: require('../../../../../packages/rn-tester/js/assets/bottom-nav-components-icon-light.png'),
+ hotdog: require('./feed-hotdog.png'),
+ like: require('../../../../../packages/rn-tester/js/assets/like.png'),
+ search: require('../../../../../packages/rn-tester/js/assets/search-icon.png'),
+ trees: require('./feed-trees.png'),
+};
+
+const STORIES = [
+ {name: 'Your story', avatar: ASSETS.bunny, isOwn: true},
+ {name: 'hawk.eye', avatar: ASSETS.hawk, isOwn: false},
+ {name: 'ducky', avatar: ASSETS.ducky, isOwn: false},
+ {name: 'flower_power', avatar: ASSETS.flowers, isOwn: false},
+ {name: 'hotdog_lover', avatar: ASSETS.hotdog, isOwn: false},
+];
+
+const POSTS = [
+ {
+ author: 'Hawk Eye',
+ avatar: ASSETS.hawk,
+ location: 'Muir Woods',
+ time: '2h',
+ text: 'Spent the whole morning among the redwoods. The light this time of the year is unreal!',
+ tags: ['nature', 'weekend'],
+ image: ASSETS.trees,
+ likedBy: 'ducky',
+ likes: 1204,
+ comments: 87,
+ },
+ {
+ author: 'Rubber Ducky',
+ avatar: ASSETS.ducky,
+ location: 'Fisherman’s Wharf',
+ time: '5h',
+ text: 'Found the best hot dog in town. Not sharing the address though.',
+ tags: ['food'],
+ image: ASSETS.hotdog,
+ likedBy: 'bunny',
+ likes: 342,
+ comments: 12,
+ },
+];
+
+function formatCount(count: number): string {
+ return String(count).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
+}
+
+component StatusBar() {
+ return (
+
+ 9:41
+
+ {[6, 9, 12, 15].map(height => (
+
+ ))}
+
+
+
+
+
+ );
+}
+
+component Header() {
+ return (
+
+ Feed
+
+ ♥
+
+ 3
+
+
+
+ );
+}
+
+component SearchBar() {
+ return (
+
+
+
+
+ );
+}
+
+component Stories() {
+ return (
+
+ {STORIES.map(story => (
+
+
+
+
+ {story.isOwn ? (
+
+ +
+
+ ) : null}
+
+ {story.name}
+
+
+ ))}
+
+ );
+}
+
+component Post(post: (typeof POSTS)[number]) {
+ return (
+
+
+
+
+
+ {post.author} ✓
+
+
+ {post.location} · {post.time}
+
+
+ •••
+
+
+ {post.text}
+ {post.tags.map(tag => (
+
+ {' #' + tag}
+
+ ))}
+
+
+
+
+
+ {formatCount(post.likes)}
+
+
+
+ {post.comments}
+
+
+ Share
+
+
+
+ Liked by {post.likedBy} and{' '}
+ {formatCount(post.likes - 1)} others
+
+
+ );
+}
+
+component TabBar() {
+ return (
+
+
+
+ Home
+
+
+
+ Explore
+
+
+ +
+
+
+ ♡
+ Activity
+
+
+
+ Profile
+
+
+
+ );
+}
+
+export default component FeedScreen(feedRef?: React.RefSetter) {
+ return (
+
+
+
+
+
+
+ {POSTS.map(post => (
+
+ ))}
+
+
+
+ );
+}
+
+const PRIMARY_COLOR = '#1877F2';
+
+const styles = StyleSheet.create({
+ screen: {
+ flex: 1,
+ backgroundColor: '#F0F2F5',
+ },
+ statusBar: {
+ height: 44,
+ paddingHorizontal: 28,
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ backgroundColor: 'white',
+ },
+ statusBarTime: {
+ fontSize: 16,
+ fontWeight: '600',
+ },
+ statusBarIcons: {
+ flexDirection: 'row',
+ alignItems: 'flex-end',
+ gap: 2,
+ },
+ signalBar: {
+ width: 3,
+ borderRadius: 1,
+ backgroundColor: 'black',
+ },
+ battery: {
+ marginLeft: 6,
+ width: 24,
+ height: 12,
+ padding: 1.5,
+ borderRadius: 3.5,
+ borderWidth: 1,
+ borderColor: 'rgba(0, 0, 0, 0.4)',
+ },
+ batteryLevel: {
+ width: '80%',
+ flex: 1,
+ borderRadius: 1.5,
+ backgroundColor: 'black',
+ },
+ header: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ paddingHorizontal: 16,
+ paddingBottom: 8,
+ backgroundColor: 'white',
+ },
+ headerTitle: {
+ fontSize: 30,
+ fontWeight: '800',
+ letterSpacing: -0.5,
+ },
+ headerButton: {
+ width: 40,
+ height: 40,
+ borderRadius: 20,
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: '#E4E6EB',
+ },
+ headerButtonIcon: {
+ fontSize: 22,
+ color: '#E41E3F',
+ },
+ badge: {
+ position: 'absolute',
+ top: -2,
+ right: -2,
+ minWidth: 18,
+ height: 18,
+ paddingHorizontal: 5,
+ borderRadius: 9,
+ borderWidth: 2,
+ borderColor: 'white',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: '#E41E3F',
+ },
+ badgeText: {
+ color: 'white',
+ fontSize: 9,
+ fontWeight: '700',
+ },
+ searchBar: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ paddingHorizontal: 16,
+ paddingBottom: 12,
+ backgroundColor: 'white',
+ borderBottomWidth: StyleSheet.hairlineWidth,
+ borderBottomColor: '#DADDE1',
+ },
+ searchIcon: {
+ position: 'absolute',
+ left: 28,
+ top: 12,
+ width: 20,
+ height: 20,
+ zIndex: 1,
+ tintColor: '#65676B',
+ },
+ searchInput: {
+ flex: 1,
+ height: 44,
+ paddingLeft: 42,
+ paddingRight: 16,
+ borderRadius: 22,
+ fontSize: 15,
+ backgroundColor: '#F0F2F5',
+ },
+ feed: {
+ flex: 1,
+ },
+ stories: {
+ marginTop: 8,
+ flexGrow: 0,
+ backgroundColor: 'white',
+ },
+ storiesContent: {
+ paddingHorizontal: 12,
+ paddingVertical: 12,
+ gap: 12,
+ },
+ story: {
+ width: 72,
+ alignItems: 'center',
+ },
+ storyRing: {
+ backgroundColor: '#D62976',
+ padding: 3,
+ borderRadius: 36,
+ experimental_backgroundImage:
+ 'linear-gradient(45deg, #FEDA75, #FA7E1E, #D62976, #962FBF)',
+ },
+ storyRingSeen: {
+ padding: 3,
+ borderRadius: 36,
+ backgroundColor: '#DADDE1',
+ },
+ storyAvatar: {
+ width: 62,
+ height: 62,
+ borderRadius: 31,
+ borderWidth: 3,
+ borderColor: 'white',
+ backgroundColor: '#FFF8E1',
+ },
+ storyAddButton: {
+ position: 'absolute',
+ top: 48,
+ right: 2,
+ width: 22,
+ height: 22,
+ borderRadius: 11,
+ borderWidth: 2,
+ borderColor: 'white',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: PRIMARY_COLOR,
+ },
+ storyAddButtonText: {
+ color: 'white',
+ fontSize: 14,
+ fontWeight: '700',
+ lineHeight: 16,
+ },
+ storyName: {
+ marginTop: 6,
+ fontSize: 12,
+ color: '#050505',
+ },
+ post: {
+ marginTop: 8,
+ paddingVertical: 12,
+ backgroundColor: 'white',
+ },
+ postHeader: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ paddingHorizontal: 16,
+ },
+ postAvatar: {
+ width: 40,
+ height: 40,
+ borderRadius: 20,
+ backgroundColor: '#FFF3E0',
+ },
+ postAuthor: {
+ flex: 1,
+ marginLeft: 10,
+ },
+ postAuthorName: {
+ fontSize: 15,
+ fontWeight: '600',
+ color: '#050505',
+ },
+ verified: {
+ color: PRIMARY_COLOR,
+ fontSize: 13,
+ },
+ postMeta: {
+ marginTop: 2,
+ fontSize: 13,
+ color: '#65676B',
+ },
+ postMore: {
+ fontSize: 12,
+ color: '#65676B',
+ letterSpacing: 1,
+ },
+ postText: {
+ marginTop: 10,
+ marginBottom: 12,
+ paddingHorizontal: 16,
+ fontSize: 15,
+ lineHeight: 21,
+ color: '#050505',
+ },
+ hashtag: {
+ color: PRIMARY_COLOR,
+ fontWeight: '500',
+ },
+ postImage: {
+ width: '100%',
+ height: 260,
+ backgroundColor: '#E4E6EB',
+ },
+ postActions: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ paddingHorizontal: 16,
+ paddingTop: 12,
+ gap: 20,
+ },
+ postAction: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 6,
+ },
+ postActionIcon: {
+ width: 22,
+ height: 22,
+ },
+ postActionText: {
+ fontSize: 14,
+ fontWeight: '500',
+ color: '#65676B',
+ },
+ commentIcon: {
+ width: 20,
+ height: 18,
+ borderRadius: 9,
+ borderBottomLeftRadius: 2,
+ borderWidth: 2,
+ borderColor: '#65676B',
+ },
+ shareButton: {
+ marginLeft: 'auto',
+ paddingHorizontal: 14,
+ paddingVertical: 6,
+ borderRadius: 16,
+ borderWidth: 1,
+ borderColor: '#CED0D4',
+ },
+ shareButtonText: {
+ fontSize: 13,
+ fontWeight: '600',
+ color: '#050505',
+ },
+ postLikedBy: {
+ marginTop: 10,
+ paddingHorizontal: 16,
+ fontSize: 13,
+ color: '#65676B',
+ },
+ bold: {
+ fontWeight: '700',
+ color: '#050505',
+ },
+ tabBar: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'space-around',
+ paddingTop: 8,
+ paddingBottom: 28,
+ backgroundColor: 'white',
+ borderTopWidth: StyleSheet.hairlineWidth,
+ borderTopColor: '#DADDE1',
+ boxShadow: '0 -2px 12px rgba(0, 0, 0, 0.06)',
+ },
+ tab: {
+ width: 64,
+ alignItems: 'center',
+ gap: 4,
+ },
+ tabIcon: {
+ width: 26,
+ height: 26,
+ resizeMode: 'contain',
+ tintColor: '#65676B',
+ },
+ tabIconActive: {
+ tintColor: PRIMARY_COLOR,
+ },
+ tabGlyphIcon: {
+ height: 26,
+ fontSize: 26,
+ lineHeight: 26,
+ color: '#65676B',
+ },
+ tabAvatar: {
+ width: 26,
+ height: 26,
+ borderRadius: 13,
+ borderWidth: 1,
+ borderColor: '#CED0D4',
+ backgroundColor: '#FFF8E1',
+ },
+ tabLabel: {
+ fontSize: 11,
+ fontWeight: '500',
+ color: '#65676B',
+ },
+ tabLabelActive: {
+ color: PRIMARY_COLOR,
+ fontWeight: '700',
+ },
+ createButton: {
+ backgroundColor: PRIMARY_COLOR,
+ width: 48,
+ height: 48,
+ borderRadius: 16,
+ alignItems: 'center',
+ justifyContent: 'center',
+ experimental_backgroundImage: 'linear-gradient(135deg, #3B9BFF, #1462D8)',
+ boxShadow: '0 4px 10px rgba(24, 119, 242, 0.4)',
+ },
+ createButtonText: {
+ color: 'white',
+ fontSize: 28,
+ fontWeight: '400',
+ lineHeight: 32,
+ },
+ homeIndicator: {
+ position: 'absolute',
+ bottom: 8,
+ left: '50%',
+ width: 134,
+ height: 5,
+ marginLeft: -67,
+ borderRadius: 2.5,
+ backgroundColor: 'black',
+ },
+});
diff --git a/private/react-native-fantom/src/__tests__/fixtures/RenderingEdgeCases.js b/private/react-native-fantom/src/__tests__/fixtures/RenderingEdgeCases.js
new file mode 100644
index 000000000000..338084bc3d0b
--- /dev/null
+++ b/private/react-native-fantom/src/__tests__/fixtures/RenderingEdgeCases.js
@@ -0,0 +1,214 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+import * as React from 'react';
+import {View} from 'react-native';
+
+component Layer(
+ left: number,
+ top: number,
+ backgroundColor: string,
+ zIndex: number,
+) {
+ return (
+
+ );
+}
+
+export component StackingScene(zIndex: number) {
+ return (
+
+
+
+
+
+
+
+
+
+
+ );
+}
+
+export component OverflowScene(overflow: 'visible' | 'hidden') {
+ return (
+
+
+
+
+
+
+
+
+
+ );
+}
+
+export component AbsolutePositionScene() {
+ return (
+
+
+
+
+
+
+
+ );
+}
+
+export component TransformScene() {
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+}
diff --git a/private/react-native-fantom/src/__tests__/fixtures/TravelScreen.js b/private/react-native-fantom/src/__tests__/fixtures/TravelScreen.js
new file mode 100644
index 000000000000..22a2616bda3c
--- /dev/null
+++ b/private/react-native-fantom/src/__tests__/fixtures/TravelScreen.js
@@ -0,0 +1,173 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @flow strict-local
+ * @format
+ */
+
+import type {ScrollViewInstance} from 'react-native';
+
+import * as React from 'react';
+import {
+ Image,
+ ScrollView,
+ StyleSheet,
+ Text,
+ TextInput,
+ View,
+} from 'react-native';
+
+export default component TravelScreen(
+ query: string = '',
+ scrollRef?: React.RefObject,
+) {
+ return (
+
+
+ WEEKEND CLUB
+ Find your next escape.
+ Small adventures. Great memories.
+
+
+
+
+
+ For you
+
+ Outdoors
+ City breaks
+
+
+ A little closer to nature
+ See all
+
+
+
+
+ TRAIL OF THE WEEK
+
+ The quiet side of the mountains
+
+
+ Follow the pines to an open valley, with room to slow down and
+ take it all in.
+
+
+ 6.4 km loop
+ Easy pace
+ 4.9 rating
+
+
+ Explore this trail
+
+
+
+
+ Make a day of it
+
+ Pack a picnic, invite a friend, and save a little time for the
+ scenic route home.
+
+
+
+ Your saved places
+
+ Keep your favorite escapes together. Your next weekend starts here.
+
+
+
+
+ Discover
+ Saved
+ Profile
+
+
+ );
+}
+
+const styles = StyleSheet.create({
+ screen: {flex: 1, backgroundColor: '#f6f7f2'},
+ header: {paddingTop: 40, paddingHorizontal: 24, paddingBottom: 20, gap: 10},
+ eyebrow: {fontSize: 11, fontWeight: '700', color: '#426c58'},
+ title: {fontSize: 28, fontWeight: '700', color: '#203c30'},
+ subtitle: {fontSize: 14, color: '#718078'},
+ search: {
+ height: 48,
+ borderRadius: 12,
+ backgroundColor: 'white',
+ borderWidth: 1,
+ borderColor: '#dce3d9',
+ paddingHorizontal: 16,
+ fontSize: 14,
+ color: '#203c30',
+ marginTop: 8,
+ },
+ feed: {flex: 1},
+ content: {paddingHorizontal: 24, paddingBottom: 24, gap: 18},
+ categories: {flexDirection: 'row', alignItems: 'center', gap: 24},
+ selected: {
+ paddingHorizontal: 18,
+ paddingVertical: 10,
+ backgroundColor: '#254f3d',
+ borderRadius: 20,
+ },
+ selectedText: {fontSize: 13, fontWeight: '600', color: 'white'},
+ category: {fontSize: 13, color: '#758077'},
+ section: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ },
+ sectionTitle: {fontSize: 16, fontWeight: '700', color: '#203c30'},
+ link: {fontSize: 12, fontWeight: '600', color: '#426c58'},
+ card: {
+ borderRadius: 18,
+ backgroundColor: 'white',
+ overflow: 'hidden',
+ borderWidth: 1,
+ borderColor: '#e1e6dc',
+ },
+ photo: {width: '100%', height: 180},
+ cardBody: {padding: 20, gap: 12},
+ cardTitle: {fontSize: 20, fontWeight: '700', color: '#203c30'},
+ description: {fontSize: 14, lineHeight: 21, color: '#718078'},
+ details: {
+ flexDirection: 'row',
+ justifyContent: 'space-between',
+ paddingVertical: 4,
+ },
+ detail: {fontSize: 11, color: '#426c58'},
+ button: {
+ backgroundColor: '#254f3d',
+ borderRadius: 10,
+ paddingVertical: 14,
+ alignItems: 'center',
+ },
+ buttonText: {fontSize: 14, fontWeight: '600', color: 'white'},
+ tip: {padding: 20, backgroundColor: '#eaf0e1', borderRadius: 14, gap: 10},
+ navigation: {
+ height: 72,
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'space-around',
+ backgroundColor: 'white',
+ borderTopWidth: 1,
+ borderTopColor: '#e1e6dc',
+ },
+ activeNav: {fontSize: 13, fontWeight: '700', color: '#254f3d'},
+});
diff --git a/private/react-native-fantom/src/__tests__/fixtures/feed-hotdog.png b/private/react-native-fantom/src/__tests__/fixtures/feed-hotdog.png
new file mode 100644
index 000000000000..97257260bd43
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/fixtures/feed-hotdog.png differ
diff --git a/private/react-native-fantom/src/__tests__/fixtures/feed-trees.png b/private/react-native-fantom/src/__tests__/fixtures/feed-trees.png
new file mode 100644
index 000000000000..fb44ed6efbf2
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/fixtures/feed-trees.png differ
diff --git a/private/react-native-fantom/src/__tests__/fixtures/travelImage.png b/private/react-native-fantom/src/__tests__/fixtures/travelImage.png
new file mode 100644
index 000000000000..dc689d7de6c6
Binary files /dev/null and b/private/react-native-fantom/src/__tests__/fixtures/travelImage.png differ
diff --git a/private/react-native-fantom/src/index.js b/private/react-native-fantom/src/index.js
index 99c3885d0ad8..2d5ee2504383 100644
--- a/private/react-native-fantom/src/index.js
+++ b/private/react-native-fantom/src/index.js
@@ -23,6 +23,7 @@ import NativeFantom, {
import * as Benchmark from './Benchmark';
import {getConstants} from './Constants';
import getFantomRenderedOutput from './getFantomRenderedOutput';
+import Screenshot from './Screenshot';
import {Dimensions, LogBox} from 'react-native';
import {
getInternalInstanceHandleFromPublicInstance,
@@ -120,6 +121,7 @@ class Root {
#devicePixelRatio: number;
#fontScale: number;
#document: ?Document;
+ #destroyed: boolean = false;
constructor(config?: RootConfig) {
this.#viewportWidth = config?.viewportWidth ?? DEFAULT_VIEWPORT_WIDTH;
@@ -188,6 +190,17 @@ class Root {
popDimensions(this.#surfaceId);
NativeFantom.flushMessageQueue();
this.#document = null;
+ this.#destroyed = true;
+ }
+
+ /**
+ * Captures the mounted pixels without flushing pending React work.
+ */
+ takeScreenshot(): Screenshot {
+ if (this.#destroyed) {
+ throw new Error('Cannot capture a screenshot of a destroyed root.');
+ }
+ return new Screenshot(NativeFantom.takeScreenshot(this.#surfaceId));
}
getRenderedOutput(config: RenderOutputConfig = {}): FantomRenderedOutput {
@@ -204,6 +217,7 @@ class Root {
export type {Root};
export {NativeEventCategory};
+export type {default as Screenshot} from './Screenshot';
const DEFAULT_TASK_PRIORITY = unstable_ImmediatePriority;
diff --git a/private/react-native-fantom/tester/CMakeLists.txt b/private/react-native-fantom/tester/CMakeLists.txt
index 856e9d5babf4..62d1a1db5eb3 100644
--- a/private/react-native-fantom/tester/CMakeLists.txt
+++ b/private/react-native-fantom/tester/CMakeLists.txt
@@ -161,6 +161,7 @@ target_link_libraries(fantom_tester
gflags
glog
fantom_skia
+ OpenSSL::Crypto
# hermes
hermes-engine::hermesvm
diff --git a/private/react-native-fantom/tester/src/NativeFantom.cpp b/private/react-native-fantom/tester/src/NativeFantom.cpp
index ab5e2fd30160..0567b1746af1 100644
--- a/private/react-native-fantom/tester/src/NativeFantom.cpp
+++ b/private/react-native-fantom/tester/src/NativeFantom.cpp
@@ -14,12 +14,14 @@
#include
#include
#include
+#include
#include
#include
#include "TesterAppDelegate.h"
#include
+#include "render/ImageRenderer.h"
#include "render/RenderFormatOptions.h"
#include "render/RenderOutput.h"
#include "render/TextLayout.h"
@@ -115,6 +117,22 @@ std::string NativeFantom::getRenderedOutput(
viewTree, formatOptions);
}
+jsi::Object NativeFantom::takeScreenshot(
+ jsi::Runtime& runtime,
+ SurfaceId surfaceId) {
+ try {
+ auto screenshot = ImageRenderer{}.capture(
+ appDelegate_.mountingManager_->getViewTree(surfaceId), assetPaths_);
+ auto object = jsi::Object::createFromHostObject(runtime, screenshot);
+ object.setExternalMemoryPressure(runtime, screenshot->getMemorySize());
+ return object;
+ } catch (const std::exception& error) {
+ throw jsi::JSError(
+ runtime,
+ std::string("Cannot render Fantom screenshot: ") + error.what());
+ }
+}
+
void NativeFantom::registerAsset(
jsi::Runtime& /*runtime*/,
const std::string& uri,
diff --git a/private/react-native-fantom/tester/src/NativeFantom.h b/private/react-native-fantom/tester/src/NativeFantom.h
index ce9ce6fae407..b26aa851c17e 100644
--- a/private/react-native-fantom/tester/src/NativeFantom.h
+++ b/private/react-native-fantom/tester/src/NativeFantom.h
@@ -102,6 +102,7 @@ class NativeFantom : public NativeFantomCxxSpec {
SurfaceId surfaceId,
NativeFantomGetRenderedOutputRenderFormatOptions options);
+ jsi::Object takeScreenshot(jsi::Runtime &runtime, SurfaceId surfaceId);
void registerAsset(jsi::Runtime &runtime, const std::string &uri, const std::string &filePath);
void registerFont(jsi::Runtime &runtime, const std::string &filePath);
diff --git a/private/react-native-fantom/tester/src/render/ImageRenderer.cpp b/private/react-native-fantom/tester/src/render/ImageRenderer.cpp
new file mode 100644
index 000000000000..6848f06a43e3
--- /dev/null
+++ b/private/react-native-fantom/tester/src/render/ImageRenderer.cpp
@@ -0,0 +1,456 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include "ImageRenderer.h"
+#include "../stubs/FantomTextInput.h"
+#include "TextLayout.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace facebook::react {
+namespace {
+
+SkPaint color(SharedColor value) {
+ SkPaint paint;
+ paint.setAntiAlias(true);
+ paint.setColor(SkColorSetARGB(
+ alphaFromColor(value),
+ redFromColor(value),
+ greenFromColor(value),
+ blueFromColor(value)));
+ return paint;
+}
+
+SkRRect roundedRect(Size size, const BorderRadii& radii) {
+ std::array corners{};
+ int index = 0;
+ for (const auto& radius :
+ {radii.topLeft, radii.topRight, radii.bottomRight, radii.bottomLeft}) {
+ corners[index++] = SkVector::Make(
+ std::min(radius.horizontal, size.width / 2),
+ std::min(radius.vertical, size.height / 2));
+ }
+ SkRRect rect;
+ rect.setRectRadii(SkRect::MakeWH(size.width, size.height), corners.data());
+ return rect;
+}
+
+sk_sp loadImage(const std::string& uri) {
+ constexpr std::string_view prefix = "data:image/png;base64,";
+ sk_sp bytes;
+ if (uri.starts_with(prefix)) {
+ const auto encoded = std::string_view(uri).substr(prefix.size());
+ size_t decodedSize = 0;
+ if (SkBase64::Decode(
+ encoded.data(), encoded.size(), nullptr, &decodedSize) !=
+ SkBase64::kNoError) {
+ throw std::runtime_error("Cannot decode Fantom PNG data source");
+ }
+ bytes = SkData::MakeUninitialized(decodedSize);
+ if (SkBase64::Decode(
+ encoded.data(),
+ encoded.size(),
+ bytes->writable_data(),
+ &decodedSize) != SkBase64::kNoError) {
+ throw std::runtime_error("Cannot decode Fantom PNG data source");
+ }
+ } else {
+ if (uri.starts_with("http:") || uri.starts_with("https:") ||
+ uri.starts_with("data:")) {
+ throw std::runtime_error(
+ "Fantom screenshots support local PNG files and data:image/png;base64 sources: " +
+ uri.substr(0, 100));
+ }
+ const auto path = uri.starts_with("file://") ? uri.substr(7) : uri;
+ bytes = SkData::MakeFromFileName(path.c_str());
+ }
+ const auto codec = bytes ? SkCodec::MakeFromData(std::move(bytes)) : nullptr;
+ if (!codec || codec->getEncodedFormat() != SkEncodedImageFormat::kPNG) {
+ throw std::runtime_error(
+ "Cannot decode Fantom PNG image: " + uri.substr(0, 100));
+ }
+ SkBitmap bitmap;
+ const auto info = codec->getInfo()
+ .makeColorType(kN32_SkColorType)
+ .makeAlphaType(kPremul_SkAlphaType);
+ if (!bitmap.tryAllocPixels(info)) {
+ throw std::bad_alloc();
+ }
+ if (codec->getPixels(bitmap.pixmap()) != SkCodec::kSuccess) {
+ throw std::runtime_error("Cannot decode Fantom PNG pixels");
+ }
+ bitmap.setImmutable();
+ auto image = SkImage::MakeFromBitmap(bitmap);
+ if (!image) {
+ throw std::runtime_error("Cannot create Fantom PNG image");
+ }
+ return image;
+}
+
+void paintBorders(SkCanvas& canvas, Size size, const BorderMetrics& border) {
+ const auto& widths = border.borderWidths;
+ if (widths.left + widths.right + widths.top + widths.bottom <= 0) {
+ return;
+ }
+ canvas.save();
+ SkPath ring;
+ ring.addRRect(roundedRect(size, border.borderRadii));
+ const Size innerSize{
+ .width = std::max(0, size.width - widths.left - widths.right),
+ .height = std::max(0, size.height - widths.top - widths.bottom)};
+ if (innerSize.width > 0 && innerSize.height > 0) {
+ auto innerRadii = border.borderRadii;
+ const auto inset = [](CornerRadii& radius,
+ Float horizontal,
+ Float vertical) {
+ radius.horizontal = std::max(0, radius.horizontal - horizontal);
+ radius.vertical = std::max(0, radius.vertical - vertical);
+ };
+ inset(innerRadii.topLeft, widths.left, widths.top);
+ inset(innerRadii.topRight, widths.right, widths.top);
+ inset(innerRadii.bottomLeft, widths.left, widths.bottom);
+ inset(innerRadii.bottomRight, widths.right, widths.bottom);
+ auto inner = roundedRect(innerSize, innerRadii);
+ inner.offset(widths.left, widths.top);
+ ring.addRRect(inner);
+ }
+ ring.setFillType(SkPathFillType::kEvenOdd);
+ canvas.clipPath(ring, true);
+ if (border.borderColors.top &&
+ border.borderColors.top == border.borderColors.right &&
+ border.borderColors.top == border.borderColors.bottom &&
+ border.borderColors.top == border.borderColors.left) {
+ canvas.drawPaint(color(border.borderColors.top));
+ canvas.restore();
+ return;
+ }
+ const auto edge = [&](std::initializer_list points,
+ SharedColor value) {
+ if (!value) {
+ return;
+ }
+ SkPath path;
+ for (auto point = points.begin(); point != points.end(); ++point) {
+ if (point == points.begin()) {
+ path.moveTo(point->x, point->y);
+ } else {
+ path.lineTo(point->x, point->y);
+ }
+ }
+ path.close();
+ canvas.drawPath(path, color(value));
+ };
+ const auto w = size.width;
+ const auto h = size.height;
+ edge(
+ {{.x = 0, .y = 0},
+ {.x = w, .y = 0},
+ {.x = w - widths.right, .y = widths.top},
+ {.x = widths.left, .y = widths.top}},
+ border.borderColors.top);
+ edge(
+ {{.x = w, .y = 0},
+ {.x = w, .y = h},
+ {.x = w - widths.right, .y = h - widths.bottom},
+ {.x = w - widths.right, .y = widths.top}},
+ border.borderColors.right);
+ edge(
+ {{.x = w, .y = h},
+ {.x = 0, .y = h},
+ {.x = widths.left, .y = h - widths.bottom},
+ {.x = w - widths.right, .y = h - widths.bottom}},
+ border.borderColors.bottom);
+ edge(
+ {{.x = 0, .y = h},
+ {.x = 0, .y = 0},
+ {.x = widths.left, .y = widths.top},
+ {.x = widths.left, .y = h - widths.bottom}},
+ border.borderColors.left);
+ canvas.restore();
+}
+void paintImage(
+ SkCanvas& canvas,
+ const StubView& view,
+ const ImageProps& props,
+ const AssetPathMap& assetPaths) {
+ auto source =
+ props.sources.empty() ? props.defaultSource : props.sources.front();
+ if (view.state) {
+ source = static_cast&>(*view.state)
+ .getData()
+ .getImageSource();
+ }
+ const auto size = view.layoutMetrics.frame.size;
+ if (source.uri.empty() || size.width <= 0 || size.height <= 0) {
+ return;
+ }
+ const auto asset = assetPaths.find(source.uri);
+ auto image =
+ loadImage(asset == assetPaths.end() ? source.uri : asset->second);
+ const double width = image->width();
+ const double height = image->height();
+ double sx = size.width / width;
+ double sy = size.height / height;
+ switch (props.resizeMode) {
+ case ImageResizeMode::Cover:
+ sx = sy = std::max(sx, sy);
+ break;
+ case ImageResizeMode::Contain:
+ sx = sy = std::min(sx, sy);
+ break;
+ case ImageResizeMode::Center:
+ sx = sy = std::min(1.0, std::min(sx, sy));
+ break;
+ case ImageResizeMode::Repeat:
+ case ImageResizeMode::None:
+ sx = sy = 1.0 / std::max(source.scale, 1);
+ break;
+ case ImageResizeMode::Stretch:
+ break;
+ }
+ canvas.save();
+ canvas.clipRRect(
+ roundedRect(
+ size, props.resolveBorderMetrics(view.layoutMetrics).borderRadii),
+ true);
+ SkPaint paint;
+ paint.setAntiAlias(true);
+ if (props.tintColor && *props.tintColor) {
+ paint.setColorFilter(
+ SkColorFilters::Blend(
+ color(*props.tintColor).getColor(), SkBlendMode::kSrcIn));
+ }
+ const SkSamplingOptions sampling(SkFilterMode::kLinear);
+ if (props.resizeMode == ImageResizeMode::Repeat) {
+ SkMatrix scale;
+ scale.setScale(static_cast(sx), static_cast(sy));
+ paint.setShader(image->makeShader(
+ SkTileMode::kRepeat, SkTileMode::kRepeat, sampling, scale));
+ canvas.drawRect(SkRect::MakeWH(size.width, size.height), paint);
+ } else {
+ const auto destination = SkRect::MakeXYWH(
+ static_cast((size.width - width * sx) / 2),
+ static_cast((size.height - height * sy) / 2),
+ static_cast(width * sx),
+ static_cast(height * sy));
+ canvas.drawImageRect(image, destination, sampling, &paint);
+ }
+ canvas.restore();
+}
+
+void paintView(
+ SkCanvas& canvas,
+ const StubView& view,
+ const AssetPathMap& assetPaths) {
+ const auto& metrics = view.layoutMetrics;
+ if (metrics.displayType == DisplayType::None) {
+ return;
+ }
+ const auto* props = dynamic_cast(view.props.get());
+ canvas.save();
+ canvas.translate(metrics.frame.origin.x, metrics.frame.origin.y);
+ if (props) {
+ const auto& matrix = props->resolveTransform(metrics).matrix;
+ const auto determinant = static_cast(matrix[0]) * matrix[5] -
+ static_cast(matrix[1]) * matrix[4];
+ if (determinant == 0 || !std::isfinite(determinant)) {
+ canvas.restore();
+ return;
+ }
+ SkMatrix transform;
+ transform.setAll(
+ matrix[0],
+ matrix[4],
+ matrix[12],
+ matrix[1],
+ matrix[5],
+ matrix[13],
+ 0,
+ 0,
+ 1);
+ if (!transform.isIdentity()) {
+ canvas.translate(
+ metrics.frame.size.width / 2, metrics.frame.size.height / 2);
+ canvas.concat(transform);
+ canvas.translate(
+ -metrics.frame.size.width / 2, -metrics.frame.size.height / 2);
+ }
+ if (props->opacity < 1) {
+ canvas.saveLayerAlpha(
+ nullptr, static_cast(std::round(255 * props->opacity)));
+ }
+ const auto border = props->resolveBorderMetrics(metrics);
+ if (props->backgroundColor) {
+ canvas.drawRRect(
+ roundedRect(metrics.frame.size, border.borderRadii),
+ color(props->backgroundColor));
+ }
+ if (props->getClipsContentToBounds()) {
+ canvas.clipRRect(
+ roundedRect(metrics.frame.size, border.borderRadii), true);
+ }
+ }
+
+ const std::string_view name(view.componentName ? view.componentName : "");
+ if (name == "Paragraph" && view.state) {
+ const auto& state =
+ static_cast&>(*view.state)
+ .getData();
+ const auto frame = metrics.getContentFrame();
+ canvas.save();
+ canvas.translate(frame.origin.x, frame.origin.y);
+ canvas.clipRect(SkRect::MakeWH(frame.size.width, frame.size.height));
+ paintText(
+ &canvas,
+ layoutText(
+ &canvas,
+ state.attributedString,
+ state.paragraphAttributes,
+ frame.size.width),
+ frame.size.width);
+ canvas.restore();
+ } else if (
+ const auto* input =
+ dynamic_cast(view.props.get())) {
+ auto attributes =
+ input->getEffectiveTextAttributes(metrics.fontSizeMultiplier);
+ const bool placeholder = input->text.empty();
+ if (placeholder) {
+ attributes.foregroundColor = input->placeholderTextColor
+ ? input->placeholderTextColor
+ : colorFromRGBA(128, 128, 128, 255);
+ }
+ auto text = placeholder ? input->placeholder : input->text;
+ if (!placeholder && input->secureTextEntry) {
+ std::string masked;
+ for (const unsigned char character : text) {
+ if ((character & 0xc0) != 0x80) {
+ masked += "•";
+ }
+ }
+ text = masked;
+ }
+ AttributedString string;
+ string.appendFragment(
+ {.string = text, .textAttributes = attributes, .parentShadowView = {}});
+ const auto frame = metrics.getContentFrame();
+ auto paragraph = input->paragraphAttributes;
+ if (!input->multiline) {
+ paragraph.maximumNumberOfLines = 1;
+ }
+ auto layout = layoutText(&canvas, string, paragraph, frame.size.width);
+ canvas.save();
+ canvas.translate(frame.origin.x, frame.origin.y);
+ canvas.clipRect(SkRect::MakeWH(frame.size.width, frame.size.height));
+ if (!input->multiline) {
+ canvas.translate(
+ 0,
+ std::max(
+ 0, (frame.size.height - layout.measurement.size.height) / 2));
+ }
+ paintText(&canvas, layout, frame.size.width);
+ canvas.restore();
+ } else if (
+ const auto* image = dynamic_cast(view.props.get())) {
+ paintImage(canvas, view, *image, assetPaths);
+ }
+
+ canvas.save();
+ if (name == "ScrollView") {
+ canvas.clipRect(
+ SkRect::MakeWH(metrics.frame.size.width, metrics.frame.size.height));
+ if (view.state) {
+ const auto& state =
+ static_cast&>(*view.state)
+ .getData();
+ canvas.translate(-state.contentOffset.x, -state.contentOffset.y);
+ }
+ }
+ for (const auto& child : view.children) {
+ paintView(canvas, *child, assetPaths);
+ }
+ canvas.restore();
+
+ if (props) {
+ paintBorders(
+ canvas, metrics.frame.size, props->resolveBorderMetrics(metrics));
+ if (props->opacity < 1) {
+ canvas.restore();
+ }
+ }
+ canvas.restore();
+}
+
+SkBitmap renderSurface(
+ const StubViewTree& tree,
+ const AssetPathMap& assetPaths) {
+ const auto& root = tree.getRootStubView();
+ const auto scale = root.layoutMetrics.pointScaleFactor;
+ const auto width = std::ceil(
+ static_cast(root.layoutMetrics.frame.size.width) * scale);
+ const auto height = std::ceil(
+ static_cast(root.layoutMetrics.frame.size.height) * scale);
+ if (!std::isfinite(width) || !std::isfinite(height) || width <= 0 ||
+ height <= 0 || width * height > 64.0 * 1024 * 1024) {
+ throw std::runtime_error(
+ "Invalid Fantom screenshot dimensions (maximum 64 million pixels)");
+ }
+ SkBitmap surface;
+ if (!surface.tryAllocPixels(
+ SkImageInfo::Make(
+ static_cast(width),
+ static_cast(height),
+ kBGRA_8888_SkColorType,
+ kPremul_SkAlphaType))) {
+ throw std::bad_alloc();
+ }
+ surface.eraseColor(SK_ColorTRANSPARENT);
+ SkCanvas canvas(surface);
+ canvas.scale(scale, scale);
+ for (const auto& child : root.children) {
+ paintView(canvas, *child, assetPaths);
+ }
+ return surface;
+}
+} // namespace
+
+std::shared_ptr ImageRenderer::capture(
+ const StubViewTree& tree,
+ const AssetPathMap& assetPaths) const {
+ return std::make_shared(renderSurface(tree, assetPaths));
+}
+
+std::vector ImageRenderer::render(
+ const StubViewTree& tree) const {
+ return capture(tree)->getPNG();
+}
+
+void ImageRenderer::renderToFile(
+ const StubViewTree& tree,
+ const std::string& filePath) const {
+ capture(tree)->saveToFile(filePath);
+}
+
+} // namespace facebook::react
diff --git a/private/react-native-fantom/tester/src/render/ImageRenderer.h b/private/react-native-fantom/tester/src/render/ImageRenderer.h
new file mode 100644
index 000000000000..68f638748e74
--- /dev/null
+++ b/private/react-native-fantom/tester/src/render/ImageRenderer.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include
+#include
+#include
+#include
+#include "Screenshot.h"
+
+namespace facebook::react {
+
+using AssetPathMap = std::unordered_map;
+
+// Renders a mounted revision without consulting React or the live shadow tree.
+// The encoded bytes can also be retained by a mount transaction recorder.
+class ImageRenderer {
+ public:
+ std::shared_ptr capture(const StubViewTree &tree, const AssetPathMap &assetPaths = {}) const;
+ std::vector render(const StubViewTree &tree) const;
+ void renderToFile(const StubViewTree &tree, const std::string &filePath) const;
+};
+
+} // namespace facebook::react
diff --git a/private/react-native-fantom/tester/src/render/Screenshot.cpp b/private/react-native-fantom/tester/src/render/Screenshot.cpp
new file mode 100644
index 000000000000..970f0f4d14e5
--- /dev/null
+++ b/private/react-native-fantom/tester/src/render/Screenshot.cpp
@@ -0,0 +1,196 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include "Screenshot.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace facebook::react {
+
+Screenshot::Screenshot(Surface surface) : surface_(std::move(surface)) {
+ surface_.setImmutable();
+}
+
+size_t Screenshot::getMemorySize() const {
+ return static_cast(surface_.rowBytes()) * surface_.height() +
+ (png_ ? png_->size() : 0);
+}
+
+const std::string& Screenshot::getHash() {
+ if (hash_) {
+ return *hash_;
+ }
+ auto context = std::unique_ptr(
+ EVP_MD_CTX_new(), EVP_MD_CTX_free);
+ if (!context ||
+ EVP_DigestInit_ex(context.get(), EVP_sha256(), nullptr) != 1) {
+ throw std::runtime_error("Cannot initialize screenshot hash");
+ }
+ const auto width = surface_.width();
+ const auto height = surface_.height();
+ std::array dimensions{};
+ for (size_t index = 0; index < 4; ++index) {
+ dimensions[index] = static_cast(width >> (24 - index * 8));
+ dimensions[index + 4] =
+ static_cast(height >> (24 - index * 8));
+ }
+ if (EVP_DigestUpdate(context.get(), dimensions.data(), dimensions.size()) !=
+ 1) {
+ throw std::runtime_error("Cannot hash screenshot dimensions");
+ }
+ const auto* data = static_cast(surface_.getPixels());
+ if (data == nullptr) {
+ throw std::runtime_error("Cannot read screenshot pixels");
+ }
+ const auto stride = static_cast(surface_.rowBytes());
+ const auto pixels = std::span(data, stride * height);
+ std::vector row(static_cast(width) * 4);
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x) {
+ const auto offset = static_cast(x) * 4;
+ const auto pixel = pixels.subspan(y * stride + offset, 4);
+ row[offset] = pixel[2];
+ row[offset + 1] = pixel[1];
+ row[offset + 2] = pixel[0];
+ row[offset + 3] = pixel[3];
+ }
+ if (EVP_DigestUpdate(context.get(), row.data(), row.size()) != 1) {
+ throw std::runtime_error("Cannot hash screenshot pixels");
+ }
+ }
+ std::array digest{};
+ unsigned int length = 0;
+ if (EVP_DigestFinal_ex(context.get(), digest.data(), &length) != 1) {
+ throw std::runtime_error("Cannot finish screenshot hash");
+ }
+ constexpr std::string_view digits = "0123456789abcdef";
+ std::string hash;
+ for (const auto byte : std::span(digest.data(), length)) {
+ hash += digits[byte >> 4];
+ hash += digits[byte & 15];
+ }
+ hash_ = std::move(hash);
+ return *hash_;
+}
+
+bool Screenshot::isEqual(const Screenshot& other) const {
+ const auto width = surface_.width();
+ const auto height = surface_.height();
+ if (width != other.surface_.width() || height != other.surface_.height()) {
+ return false;
+ }
+ const auto* data = static_cast(surface_.getPixels());
+ const auto* otherData =
+ static_cast(other.surface_.getPixels());
+ if (data == nullptr || otherData == nullptr) {
+ throw std::runtime_error("Cannot read screenshot pixels");
+ }
+ const auto stride = static_cast(surface_.rowBytes());
+ const auto otherStride = static_cast(other.surface_.rowBytes());
+ const auto pixels = std::span(data, stride * height);
+ const auto otherPixels = std::span(otherData, otherStride * height);
+ const auto rowSize = static_cast(width) * 4;
+ for (int row = 0; row < height; ++row) {
+ if (!std::ranges::equal(
+ pixels.subspan(row * stride, rowSize),
+ otherPixels.subspan(row * otherStride, rowSize))) {
+ return false;
+ }
+ }
+ return true;
+}
+
+const std::vector& Screenshot::getPNG() {
+ if (!png_) {
+ SkDynamicMemoryWStream stream;
+ if (!SkPngEncoder::Encode(&stream, surface_.pixmap(), {})) {
+ throw std::runtime_error("Cannot encode Fantom screenshot PNG");
+ }
+ const auto bytes = stream.detachAsData();
+ const auto* data = static_cast(bytes->data());
+ const auto pixels = std::span(data, bytes->size());
+ png_ = std::vector(pixels.begin(), pixels.end());
+ }
+ return *png_;
+}
+
+void Screenshot::saveToFile(const std::string& filePath) {
+ if (filePath.empty() || filePath.find('\0') != std::string::npos) {
+ throw std::runtime_error(
+ "Screenshot path must be nonempty and contain no NUL characters");
+ }
+ const auto& bytes = getPNG();
+ const std::filesystem::path path(filePath);
+ if (path.has_parent_path()) {
+ std::filesystem::create_directories(path.parent_path());
+ }
+ std::ofstream file(filePath, std::ios::binary | std::ios::trunc);
+ // NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
+ file.write(
+ reinterpret_cast(bytes.data()),
+ static_cast(bytes.size()));
+ // NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
+ file.close();
+ if (!file) {
+ throw std::runtime_error("Cannot write Fantom screenshot to " + filePath);
+ }
+}
+
+jsi::Value Screenshot::get(jsi::Runtime& runtime, const jsi::PropNameID& name) {
+ const auto property = name.utf8(runtime);
+ if (property != "getHash" && property != "saveToFile" &&
+ property != "isEqual") {
+ return jsi::Value::undefined();
+ }
+ return jsi::Function::createFromHostFunction(
+ runtime,
+ name,
+ property == "getHash" ? 0 : 1,
+ [screenshot = shared_from_this(), property](
+ jsi::Runtime& runtime,
+ const jsi::Value& receiver,
+ const jsi::Value* arguments,
+ size_t count) -> jsi::Value {
+ const auto args = std::span(arguments, count);
+ try {
+ if (property == "getHash") {
+ return jsi::String::createFromUtf8(runtime, screenshot->getHash());
+ }
+ if (property == "isEqual") {
+ if (count != 1 || !args[0].isObject() ||
+ !args[0].asObject(runtime).isHostObject(runtime)) {
+ return false;
+ }
+ return screenshot->isEqual(
+ *args[0].asObject(runtime).getHostObject(runtime));
+ }
+ if (count != 1 || !args[0].isString()) {
+ throw jsi::JSError(runtime, "Expected a screenshot file path");
+ }
+ screenshot->saveToFile(args[0].asString(runtime).utf8(runtime));
+ if (receiver.isObject()) {
+ receiver.asObject(runtime).setExternalMemoryPressure(
+ runtime, screenshot->getMemorySize());
+ }
+ return jsi::Value::undefined();
+ } catch (const std::exception& error) {
+ throw jsi::JSError(runtime, error.what());
+ }
+ });
+}
+
+} // namespace facebook::react
diff --git a/private/react-native-fantom/tester/src/render/Screenshot.h b/private/react-native-fantom/tester/src/render/Screenshot.h
new file mode 100644
index 000000000000..74212131fd7e
--- /dev/null
+++ b/private/react-native-fantom/tester/src/render/Screenshot.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include
+
+#include
+#include
+#include
+#include
+#include
+
+namespace facebook::react {
+
+class Screenshot : public jsi::HostObject, public std::enable_shared_from_this {
+ public:
+ using Surface = SkBitmap;
+
+ explicit Screenshot(Surface surface);
+ size_t getMemorySize() const;
+ const std::string &getHash();
+ bool isEqual(const Screenshot &other) const;
+ const std::vector &getPNG();
+ void saveToFile(const std::string &filePath);
+ jsi::Value get(jsi::Runtime &runtime, const jsi::PropNameID &name) override;
+
+ private:
+ Surface surface_;
+ std::optional hash_;
+ std::optional> png_;
+};
+
+} // namespace facebook::react
diff --git a/private/react-native-fantom/tester/third-party/folly/CMakeLists.txt b/private/react-native-fantom/tester/third-party/folly/CMakeLists.txt
index 3f10fb51517e..f76bce84fb5f 100644
--- a/private/react-native-fantom/tester/third-party/folly/CMakeLists.txt
+++ b/private/react-native-fantom/tester/third-party/folly/CMakeLists.txt
@@ -38,6 +38,9 @@ SET(folly_runtime_SRC
folly/detail/Futex.cpp
folly/detail/SplitStringSimd.cpp
folly/detail/UniqueInstance.cpp
+ folly/detail/base64_detail/Base64Api.cpp
+ folly/detail/base64_detail/Base64SWAR.cpp
+ folly/detail/base64_detail/Base64_SSE4_2.cpp
folly/hash/SpookyHashV2.cpp
folly/io/IOBuf.cpp
folly/json/dynamic.cpp