Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions flow-typed/npm/pngjs_v7.x.x.js
Original file line number Diff line number Diff line change
@@ -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,
};
}
}
4 changes: 2 additions & 2 deletions packages/new-app-screen/src/NewAppScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
*/

import Links from './Links';
import RuntimeVersion from './RuntimeVersion';
import {ThemedText, useTheme} from './Theme';
import * as React from 'react';
import {
Expand Down Expand Up @@ -135,8 +136,7 @@ function getHermesLabel(): React.Node {

return (
<ThemedText color="secondary" style={styles.label}>
JS Engine: Hermes (
{global.HermesInternal.getRuntimeProperties?.()['OSS Release Version']})
JS Engine: Hermes ({RuntimeVersion.hermes})
</ThemedText>
);
}
Expand Down
16 changes: 16 additions & 0 deletions packages/new-app-screen/src/RuntimeVersion.js
Original file line number Diff line number Diff line change
@@ -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;
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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;
Expand Down
43 changes: 43 additions & 0 deletions private/react-native-fantom/__docs__/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,49 @@ Similar to Jest, you can also run Fantom in watch mode using `--watch`:
yarn fantom <regexForTestFiles> --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(<Screen />));
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__/<test-file>.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]
Expand Down
75 changes: 71 additions & 4 deletions private/react-native-fantom/__docs__/rendering.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<test-file>.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.
3 changes: 2 additions & 1 deletion private/react-native-fantom/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
153 changes: 153 additions & 0 deletions private/react-native-fantom/runner/__tests__/snapshotUtils-test.js
Original file line number Diff line number Diff line change
@@ -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');
});
Loading
Loading