Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

refactor(core): one shared touch module that components import directly, reached by Lab through internal/touch (#8465)

Christopher Chedeaua63eb54f562a
diff --git a/.changeset/touch-support.md b/.changeset/touch-support.md
new file mode 100644
index 0000000000..1eb09b40ec
--- /dev/null
+++ b/.changeset/touch-support.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Adds an internal entry, reserved for Astryx's own packages, through which Lab components reach the gesture core that Core components import directly. No component uses it yet, and apps import nothing new.
+
+@vjeux
diff --git a/packages/core/package.json b/packages/core/package.json
index 462f6f61ad..8bd491e627 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -818,6 +818,11 @@
"source": "./src/Markdown/remark.ts",
"types": "./dist/Markdown/remark.d.ts",
"default": "./dist/Markdown/remark.js"
+ },
+ "./internal/touch": {
+ "source": "./src/internal/touch.ts",
+ "types": "./dist/internal/touch.d.ts",
+ "default": "./dist/internal/touch.js"
}
},
"files": [
diff --git a/packages/core/src/internal/touch.test.ts b/packages/core/src/internal/touch.test.ts
new file mode 100644
index 0000000000..2f175885db
--- /dev/null
+++ b/packages/core/src/internal/touch.test.ts
@@ -0,0 +1,44 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file touch.test.ts
+ * @input The internal `internal/touch` entry and the gesture core
+ * @output INV13's entry checks: the entry re-exports the gesture core's
+ * primitives by name, the same values a Core component imports by path, and
+ * no gathering object; importing it attaches no window or document
+ * listeners, so a page with only a fine pointer runs none (`spec:AST-094`
+ * FR19, FR24)
+ * @position Unit tests of packages/core/src/internal/touch.ts
+ * (architecture:react-component-runtime INV13)
+ */
+
+import {afterEach, describe, expect, it, vi} from 'vitest';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('internal/touch', () => {
+ it('re-exports the gesture core by name, the same values Core imports by path', async () => {
+ const entry: Record<string, unknown> = await import('./touch');
+ const arena = await import('../gestures/GestureArena');
+ const recognizer = await import('../gestures/GestureRecognizer');
+ expect(entry.GestureArena).toBe(arena.GestureArena);
+ expect(entry.GestureRecognizer).toBe(recognizer.GestureRecognizer);
+ for (const name of ['TapGestureRecognizer', 'LongPressGestureRecognizer']) {
+ expect(typeof entry[name], name).toBe('function');
+ }
+ // Named re-exports only: no gathering object a component would carry
+ // whole (architecture:component-style-authoring INV6).
+ expect(entry).not.toHaveProperty('touchModule');
+ });
+
+ it('attaches no window or document listeners when it loads', async () => {
+ vi.resetModules();
+ const onWindow = vi.spyOn(window, 'addEventListener');
+ const onDocument = vi.spyOn(document, 'addEventListener');
+ await import('./touch');
+ expect(onWindow).not.toHaveBeenCalled();
+ expect(onDocument).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/internal/touch.ts b/packages/core/src/internal/touch.ts
new file mode 100644
index 0000000000..b1ff8a168b
--- /dev/null
+++ b/packages/core/src/internal/touch.ts
@@ -0,0 +1,41 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file touch.ts
+ * @input The gesture core: the arena, the recognizers, and their geometry
+ * @output `@astryxdesign/core/internal/touch`: the gesture core's primitives
+ * for Lab components, re-exported by name
+ * @position An internal entry reserved for Astryx's own packages:
+ * undocumented, outside the public API and its compatibility promise
+ * (spec:AST-017 FR21), versioned in lockstep with Core, and allowed only in
+ * Core and Lab by the `@astryx/no-core-internal-import` lint rule
+ * (architecture:react-component-runtime INV13). Core components import the
+ * same modules by relative path. Named re-exports only, never a gathering
+ * object: a bundler keeps one copy per page and only what a component uses
+ * (architecture:component-style-authoring INV6). Importing it attaches no
+ * listeners: a recognizer listens only once a component starts it under a
+ * coarse pointer (`spec:AST-094` FR19, FR24).
+ *
+ * SYNC: When modified, update scripts/touch-support-bundle.test.mjs and
+ * touch.test.ts.
+ */
+
+export {browserClock, GestureArena} from '../gestures/GestureArena';
+export {
+ ALL_NATIVE_TOUCH,
+ GestureRecognizer,
+ isActive,
+ isTerminal,
+ isTransitionAllowed,
+ MANIPULATION,
+} from '../gestures/GestureRecognizer';
+export {
+ angleBetween,
+ centroid,
+ distance,
+ travel,
+ unwrapAngle,
+} from '../gestures/geometry';
+export {LongPressGestureRecognizer} from '../gestures/LongPressGestureRecognizer';
+export {TapGestureRecognizer} from '../gestures/TapGestureRecognizer';
+export {DEFAULT_ENVIRONMENT} from '../gestures/types';
diff --git a/scripts/core-internal-entries.test.mjs b/scripts/core-internal-entries.test.mjs
new file mode 100644
index 0000000000..fa20018e03
--- /dev/null
+++ b/scripts/core-internal-entries.test.mjs
@@ -0,0 +1,55 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file core-internal-entries.test.mjs
+ * @input The repository's ESLint config
+ * @output Pins who may import Core's internal entries
+ * (`@astryxdesign/core/internal/*`, spec:AST-017 FR21,
+ * architecture:react-component-runtime INV13): only Core and Lab, through
+ * the shared `@astryx/no-core-internal-import` rule
+ * @position Node test over the lint config, so it needs no build; the rule's
+ * own cases live beside it in internal/eslint-plugin-astryx
+ */
+
+import {createRequire} from 'node:module';
+import path from 'node:path';
+import {describe, expect, it} from 'vitest';
+
+const REPO = path.resolve(import.meta.dirname, '..');
+const require = createRequire(path.join(REPO, 'package.json'));
+const {ESLint} = require('eslint');
+
+const eslint = new ESLint({cwd: REPO});
+const RULE = '@astryx/no-core-internal-import';
+
+/** The rule's severity as the repository's config resolves it for `file`. */
+async function severityAt(file) {
+ const config = await eslint.calculateConfigForFile(path.join(REPO, file));
+ const setting = config.rules?.[RULE];
+ const level = Array.isArray(setting) ? setting[0] : setting;
+ return level === 2 || level === 'error'
+ ? 'error'
+ : level === 1 || level === 'warn'
+ ? 'warn'
+ : 'off';
+}
+
+describe('core internal entries in lint', () => {
+ it('are refused outside Core and Lab', async () => {
+ for (const file of [
+ 'apps/docsite/src/Example.tsx',
+ 'packages/charts/src/Example.tsx',
+ ]) {
+ expect(await severityAt(file), file).toBe('error');
+ }
+ });
+
+ it('are allowed in Core and Lab', async () => {
+ for (const file of [
+ 'packages/lab/src/Example/Example.tsx',
+ 'packages/core/src/Example/Example.tsx',
+ ]) {
+ expect(await severityAt(file), file).toBe('off');
+ }
+ });
+});
diff --git a/scripts/sync-exports.js b/scripts/sync-exports.js
index 0bbe258f11..f366f12e26 100644
--- a/scripts/sync-exports.js
+++ b/scripts/sync-exports.js
@@ -234,6 +234,10 @@ const FILE_MODULE_SUBPATH_EXPORTS = [
'CodeBlock/languages/thrift',
'CodeBlock/languages/toml',
'Markdown/remark',
+ // Internal entries for Astryx's own packages: undocumented, outside the
+ // public API, and allowed by lint only in Core and Lab
+ // (architecture:react-component-runtime INV13).
+ 'internal/touch',
];
/**
diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs
new file mode 100644
index 0000000000..05c9140499
--- /dev/null
+++ b/scripts/touch-support-bundle.test.mjs
@@ -0,0 +1,172 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file touch-support-bundle.test.mjs
+ * @input Core's source, bundled with the PR size report's esbuild options
+ * (.github/scripts/lib/component-size.js); core's package.json; core's and
+ * the CLI's docs; core's and Lab's component source
+ * @output Pins architecture:react-component-runtime INV13's bundle and
+ * boundary claims: Core's public entries carry none of the touch and gesture
+ * module until a component imports it; two components that import it share
+ * one copy per page; only the internal `internal/touch` entry reaches it,
+ * and no consumer doc or component `import()` does
+ * @position Node test over source, so it needs no build
+ */
+
+import fs from 'node:fs';
+import {createRequire} from 'node:module';
+import os from 'node:os';
+import path from 'node:path';
+import {afterAll, describe, expect, it} from 'vitest';
+
+const REPO = path.resolve(import.meta.dirname, '..');
+const CORE_SRC = path.join(REPO, 'packages/core/src');
+const require = createRequire(path.join(REPO, 'package.json'));
+const esbuild = require('esbuild');
+
+/** The gesture core the internal entry re-exports. */
+const PRIMITIVE_INPUT = /^packages\/core\/src\/gestures\//;
+
+const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-touch-module-'));
+afterAll(() => {
+ fs.rmSync(scratch, {recursive: true, force: true});
+});
+
+/**
+ * Each output of a build of `entries`, with the bytes each source module puts
+ * in it, built as the size report builds a component import. React and StyleX
+ * stay external: they hold no touch code.
+ */
+function outputsOf(entries) {
+ const result = esbuild.buildSync({
+ absWorkingDir: REPO,
+ entryPoints: entries,
+ outdir: path.join(scratch, 'out'),
+ bundle: true,
+ splitting: true,
+ minify: true,
+ format: 'esm',
+ platform: 'browser',
+ define: {'process.env.NODE_ENV': '"production"'},
+ loader: {'.css': 'empty'},
+ external: [
+ 'react',
+ 'react/*',
+ 'react-dom',
+ 'react-dom/*',
+ '@stylexjs/stylex',
+ ],
+ metafile: true,
+ write: false,
+ logLevel: 'silent',
+ });
+ return Object.values(result.metafile.outputs).map(output =>
+ Object.fromEntries(
+ Object.entries(output.inputs).map(([input, {bytesInOutput}]) => [
+ input,
+ bytesInOutput,
+ ]),
+ ),
+ );
+}
+
+/** The inputs matching `pattern` that put bytes in `bytes`. */
+function bytesOf(bytes, pattern = PRIMITIVE_INPUT) {
+ return Object.entries(bytes).filter(
+ ([input, size]) => pattern.test(input) && size > 0,
+ );
+}
+
+/** A scratch entry module with `source`. */
+function entryWith(name, source) {
+ const file = path.join(scratch, name);
+ fs.writeFileSync(file, source);
+ return file;
+}
+
+/** Every file under `dir` whose name matches `pattern`. */
+function filesUnder(dir, pattern) {
+ const found = [];
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name !== 'node_modules' && entry.name !== 'dist') {
+ found.push(...filesUnder(full, pattern));
+ }
+ } else if (pattern.test(entry.name)) {
+ found.push(full);
+ }
+ }
+ return found;
+}
+
+describe('the touch module in bundles', () => {
+ it.each([
+ ['the root entry', 'index.ts'],
+ ['the hooks entry', 'hooks/index.ts'],
+ ['the utils entry', 'utils/index.ts'],
+ ])('is absent from %s', (_name, entry) => {
+ for (const bytes of outputsOf([path.join(CORE_SRC, entry)])) {
+ expect(bytesOf(bytes)).toEqual([]);
+ }
+ });
+
+ it('is one copy that two components importing it share', () => {
+ const component = name =>
+ entryWith(
+ `${name}.ts`,
+ `import {GestureArena} from ${JSON.stringify(
+ path.join(CORE_SRC, 'internal/touch.ts'),
+ )};
+export const ${name} = () => new GestureArena();
+`,
+ );
+ const outputs = outputsOf([component('First'), component('Second')]);
+ const holding = outputs.filter(
+ bytes => bytes['packages/core/src/gestures/GestureArena.ts'] > 0,
+ );
+ expect(holding).toHaveLength(1);
+ for (const bytes of outputs.filter(output => output !== holding[0])) {
+ expect(bytesOf(bytes)).toEqual([]);
+ }
+ });
+});
+
+describe('the touch module internals', () => {
+ it('have no entry in the exports map beside the internal touch entry', () => {
+ const {exports} = JSON.parse(
+ fs.readFileSync(path.join(REPO, 'packages/core/package.json'), 'utf8'),
+ );
+ expect(exports['./internal/touch']?.source).toBe('./src/internal/touch.ts');
+ const other = Object.keys(exports).filter(key =>
+ /^\.\/(gestures|motion|touch-support)(\/|$)/.test(key),
+ );
+ expect(other).toEqual([]);
+ });
+
+ it('are named by no consumer doc', () => {
+ const docs = [
+ ...filesUnder(CORE_SRC, /\.doc(\.[a-z]+)?\.mjs$/),
+ ...filesUnder(path.join(REPO, 'packages/cli/assets/docs'), /\.mjs$/),
+ ];
+ const naming = docs.filter(file =>
+ /\b(GestureArena|GestureRecognizer)\b|@astryxdesign\/core\/internal\//.test(
+ fs.readFileSync(file, 'utf8'),
+ ),
+ );
+ expect(naming.map(file => path.relative(REPO, file))).toEqual([]);
+ });
+
+ it('are never loaded through an import() in Core or Lab source', () => {
+ const sources = [
+ ...filesUnder(CORE_SRC, /\.(ts|tsx)$/),
+ ...filesUnder(path.join(REPO, 'packages/lab/src'), /\.(ts|tsx)$/),
+ ].filter(file => !/\.(test|spec)\.(ts|tsx)$|__tests__/.test(file));
+ const dynamic = sources.filter(file =>
+ /\bimport\(\s*['"][^'"]*(\/gestures\/|\/motion\/|touch-support|internal\/touch)/.test(
+ fs.readFileSync(file, 'utf8'),
+ ),
+ );
+ expect(dynamic.map(file => path.relative(REPO, file))).toEqual([]);
+ });
+});