Skip to content

Commit a63eb54

Browse files
authored
refactor(core): one shared touch module that components import directly, reached by Lab through internal/touch (#8465)
refactor(core): one shared touch module that components import directly, reached by Lab through internal/touch Co-authored-by: vjeux <vjeux@users.noreply.github.com>
1 parent d5cd551 commit a63eb54

7 files changed

Lines changed: 328 additions & 0 deletions

File tree

‎.changeset/touch-support.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@astryxdesign/core': patch
3+
---
4+
5+
[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.
6+
7+
@vjeux

‎packages/core/package.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -818,6 +818,11 @@
818818
"source": "./src/Markdown/remark.ts",
819819
"types": "./dist/Markdown/remark.d.ts",
820820
"default": "./dist/Markdown/remark.js"
821+
},
822+
"./internal/touch": {
823+
"source": "./src/internal/touch.ts",
824+
"types": "./dist/internal/touch.d.ts",
825+
"default": "./dist/internal/touch.js"
821826
}
822827
},
823828
"files": [
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/**
4+
* @file touch.test.ts
5+
* @input The internal `internal/touch` entry and the gesture core
6+
* @output INV13's entry checks: the entry re-exports the gesture core's
7+
* primitives by name, the same values a Core component imports by path, and
8+
* no gathering object; importing it attaches no window or document
9+
* listeners, so a page with only a fine pointer runs none (`spec:AST-094`
10+
* FR19, FR24)
11+
* @position Unit tests of packages/core/src/internal/touch.ts
12+
* (architecture:react-component-runtime INV13)
13+
*/
14+
15+
import {afterEach, describe, expect, it, vi} from 'vitest';
16+
17+
afterEach(() => {
18+
vi.restoreAllMocks();
19+
});
20+
21+
describe('internal/touch', () => {
22+
it('re-exports the gesture core by name, the same values Core imports by path', async () => {
23+
const entry: Record<string, unknown> = await import('./touch');
24+
const arena = await import('../gestures/GestureArena');
25+
const recognizer = await import('../gestures/GestureRecognizer');
26+
expect(entry.GestureArena).toBe(arena.GestureArena);
27+
expect(entry.GestureRecognizer).toBe(recognizer.GestureRecognizer);
28+
for (const name of ['TapGestureRecognizer', 'LongPressGestureRecognizer']) {
29+
expect(typeof entry[name], name).toBe('function');
30+
}
31+
// Named re-exports only: no gathering object a component would carry
32+
// whole (architecture:component-style-authoring INV6).
33+
expect(entry).not.toHaveProperty('touchModule');
34+
});
35+
36+
it('attaches no window or document listeners when it loads', async () => {
37+
vi.resetModules();
38+
const onWindow = vi.spyOn(window, 'addEventListener');
39+
const onDocument = vi.spyOn(document, 'addEventListener');
40+
await import('./touch');
41+
expect(onWindow).not.toHaveBeenCalled();
42+
expect(onDocument).not.toHaveBeenCalled();
43+
});
44+
});
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/**
4+
* @file touch.ts
5+
* @input The gesture core: the arena, the recognizers, and their geometry
6+
* @output `@astryxdesign/core/internal/touch`: the gesture core's primitives
7+
* for Lab components, re-exported by name
8+
* @position An internal entry reserved for Astryx's own packages:
9+
* undocumented, outside the public API and its compatibility promise
10+
* (spec:AST-017 FR21), versioned in lockstep with Core, and allowed only in
11+
* Core and Lab by the `@astryx/no-core-internal-import` lint rule
12+
* (architecture:react-component-runtime INV13). Core components import the
13+
* same modules by relative path. Named re-exports only, never a gathering
14+
* object: a bundler keeps one copy per page and only what a component uses
15+
* (architecture:component-style-authoring INV6). Importing it attaches no
16+
* listeners: a recognizer listens only once a component starts it under a
17+
* coarse pointer (`spec:AST-094` FR19, FR24).
18+
*
19+
* SYNC: When modified, update scripts/touch-support-bundle.test.mjs and
20+
* touch.test.ts.
21+
*/
22+
23+
export {browserClock, GestureArena} from '../gestures/GestureArena';
24+
export {
25+
ALL_NATIVE_TOUCH,
26+
GestureRecognizer,
27+
isActive,
28+
isTerminal,
29+
isTransitionAllowed,
30+
MANIPULATION,
31+
} from '../gestures/GestureRecognizer';
32+
export {
33+
angleBetween,
34+
centroid,
35+
distance,
36+
travel,
37+
unwrapAngle,
38+
} from '../gestures/geometry';
39+
export {LongPressGestureRecognizer} from '../gestures/LongPressGestureRecognizer';
40+
export {TapGestureRecognizer} from '../gestures/TapGestureRecognizer';
41+
export {DEFAULT_ENVIRONMENT} from '../gestures/types';
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/**
4+
* @file core-internal-entries.test.mjs
5+
* @input The repository's ESLint config
6+
* @output Pins who may import Core's internal entries
7+
* (`@astryxdesign/core/internal/*`, spec:AST-017 FR21,
8+
* architecture:react-component-runtime INV13): only Core and Lab, through
9+
* the shared `@astryx/no-core-internal-import` rule
10+
* @position Node test over the lint config, so it needs no build; the rule's
11+
* own cases live beside it in internal/eslint-plugin-astryx
12+
*/
13+
14+
import {createRequire} from 'node:module';
15+
import path from 'node:path';
16+
import {describe, expect, it} from 'vitest';
17+
18+
const REPO = path.resolve(import.meta.dirname, '..');
19+
const require = createRequire(path.join(REPO, 'package.json'));
20+
const {ESLint} = require('eslint');
21+
22+
const eslint = new ESLint({cwd: REPO});
23+
const RULE = '@astryx/no-core-internal-import';
24+
25+
/** The rule's severity as the repository's config resolves it for `file`. */
26+
async function severityAt(file) {
27+
const config = await eslint.calculateConfigForFile(path.join(REPO, file));
28+
const setting = config.rules?.[RULE];
29+
const level = Array.isArray(setting) ? setting[0] : setting;
30+
return level === 2 || level === 'error'
31+
? 'error'
32+
: level === 1 || level === 'warn'
33+
? 'warn'
34+
: 'off';
35+
}
36+
37+
describe('core internal entries in lint', () => {
38+
it('are refused outside Core and Lab', async () => {
39+
for (const file of [
40+
'apps/docsite/src/Example.tsx',
41+
'packages/charts/src/Example.tsx',
42+
]) {
43+
expect(await severityAt(file), file).toBe('error');
44+
}
45+
});
46+
47+
it('are allowed in Core and Lab', async () => {
48+
for (const file of [
49+
'packages/lab/src/Example/Example.tsx',
50+
'packages/core/src/Example/Example.tsx',
51+
]) {
52+
expect(await severityAt(file), file).toBe('off');
53+
}
54+
});
55+
});

‎scripts/sync-exports.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,10 @@ const FILE_MODULE_SUBPATH_EXPORTS = [
234234
'CodeBlock/languages/thrift',
235235
'CodeBlock/languages/toml',
236236
'Markdown/remark',
237+
// Internal entries for Astryx's own packages: undocumented, outside the
238+
// public API, and allowed by lint only in Core and Lab
239+
// (architecture:react-component-runtime INV13).
240+
'internal/touch',
237241
];
238242

239243
/**
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/**
4+
* @file touch-support-bundle.test.mjs
5+
* @input Core's source, bundled with the PR size report's esbuild options
6+
* (.github/scripts/lib/component-size.js); core's package.json; core's and
7+
* the CLI's docs; core's and Lab's component source
8+
* @output Pins architecture:react-component-runtime INV13's bundle and
9+
* boundary claims: Core's public entries carry none of the touch and gesture
10+
* module until a component imports it; two components that import it share
11+
* one copy per page; only the internal `internal/touch` entry reaches it,
12+
* and no consumer doc or component `import()` does
13+
* @position Node test over source, so it needs no build
14+
*/
15+
16+
import fs from 'node:fs';
17+
import {createRequire} from 'node:module';
18+
import os from 'node:os';
19+
import path from 'node:path';
20+
import {afterAll, describe, expect, it} from 'vitest';
21+
22+
const REPO = path.resolve(import.meta.dirname, '..');
23+
const CORE_SRC = path.join(REPO, 'packages/core/src');
24+
const require = createRequire(path.join(REPO, 'package.json'));
25+
const esbuild = require('esbuild');
26+
27+
/** The gesture core the internal entry re-exports. */
28+
const PRIMITIVE_INPUT = /^packages\/core\/src\/gestures\//;
29+
30+
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-touch-module-'));
31+
afterAll(() => {
32+
fs.rmSync(scratch, {recursive: true, force: true});
33+
});
34+
35+
/**
36+
* Each output of a build of `entries`, with the bytes each source module puts
37+
* in it, built as the size report builds a component import. React and StyleX
38+
* stay external: they hold no touch code.
39+
*/
40+
function outputsOf(entries) {
41+
const result = esbuild.buildSync({
42+
absWorkingDir: REPO,
43+
entryPoints: entries,
44+
outdir: path.join(scratch, 'out'),
45+
bundle: true,
46+
splitting: true,
47+
minify: true,
48+
format: 'esm',
49+
platform: 'browser',
50+
define: {'process.env.NODE_ENV': '"production"'},
51+
loader: {'.css': 'empty'},
52+
external: [
53+
'react',
54+
'react/*',
55+
'react-dom',
56+
'react-dom/*',
57+
'@stylexjs/stylex',
58+
],
59+
metafile: true,
60+
write: false,
61+
logLevel: 'silent',
62+
});
63+
return Object.values(result.metafile.outputs).map(output =>
64+
Object.fromEntries(
65+
Object.entries(output.inputs).map(([input, {bytesInOutput}]) => [
66+
input,
67+
bytesInOutput,
68+
]),
69+
),
70+
);
71+
}
72+
73+
/** The inputs matching `pattern` that put bytes in `bytes`. */
74+
function bytesOf(bytes, pattern = PRIMITIVE_INPUT) {
75+
return Object.entries(bytes).filter(
76+
([input, size]) => pattern.test(input) && size > 0,
77+
);
78+
}
79+
80+
/** A scratch entry module with `source`. */
81+
function entryWith(name, source) {
82+
const file = path.join(scratch, name);
83+
fs.writeFileSync(file, source);
84+
return file;
85+
}
86+
87+
/** Every file under `dir` whose name matches `pattern`. */
88+
function filesUnder(dir, pattern) {
89+
const found = [];
90+
for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
91+
const full = path.join(dir, entry.name);
92+
if (entry.isDirectory()) {
93+
if (entry.name !== 'node_modules' && entry.name !== 'dist') {
94+
found.push(...filesUnder(full, pattern));
95+
}
96+
} else if (pattern.test(entry.name)) {
97+
found.push(full);
98+
}
99+
}
100+
return found;
101+
}
102+
103+
describe('the touch module in bundles', () => {
104+
it.each([
105+
['the root entry', 'index.ts'],
106+
['the hooks entry', 'hooks/index.ts'],
107+
['the utils entry', 'utils/index.ts'],
108+
])('is absent from %s', (_name, entry) => {
109+
for (const bytes of outputsOf([path.join(CORE_SRC, entry)])) {
110+
expect(bytesOf(bytes)).toEqual([]);
111+
}
112+
});
113+
114+
it('is one copy that two components importing it share', () => {
115+
const component = name =>
116+
entryWith(
117+
`${name}.ts`,
118+
`import {GestureArena} from ${JSON.stringify(
119+
path.join(CORE_SRC, 'internal/touch.ts'),
120+
)};
121+
export const ${name} = () => new GestureArena();
122+
`,
123+
);
124+
const outputs = outputsOf([component('First'), component('Second')]);
125+
const holding = outputs.filter(
126+
bytes => bytes['packages/core/src/gestures/GestureArena.ts'] > 0,
127+
);
128+
expect(holding).toHaveLength(1);
129+
for (const bytes of outputs.filter(output => output !== holding[0])) {
130+
expect(bytesOf(bytes)).toEqual([]);
131+
}
132+
});
133+
});
134+
135+
describe('the touch module internals', () => {
136+
it('have no entry in the exports map beside the internal touch entry', () => {
137+
const {exports} = JSON.parse(
138+
fs.readFileSync(path.join(REPO, 'packages/core/package.json'), 'utf8'),
139+
);
140+
expect(exports['./internal/touch']?.source).toBe('./src/internal/touch.ts');
141+
const other = Object.keys(exports).filter(key =>
142+
/^\.\/(gestures|motion|touch-support)(\/|$)/.test(key),
143+
);
144+
expect(other).toEqual([]);
145+
});
146+
147+
it('are named by no consumer doc', () => {
148+
const docs = [
149+
...filesUnder(CORE_SRC, /\.doc(\.[a-z]+)?\.mjs$/),
150+
...filesUnder(path.join(REPO, 'packages/cli/assets/docs'), /\.mjs$/),
151+
];
152+
const naming = docs.filter(file =>
153+
/\b(GestureArena|GestureRecognizer)\b|@astryxdesign\/core\/internal\//.test(
154+
fs.readFileSync(file, 'utf8'),
155+
),
156+
);
157+
expect(naming.map(file => path.relative(REPO, file))).toEqual([]);
158+
});
159+
160+
it('are never loaded through an import() in Core or Lab source', () => {
161+
const sources = [
162+
...filesUnder(CORE_SRC, /\.(ts|tsx)$/),
163+
...filesUnder(path.join(REPO, 'packages/lab/src'), /\.(ts|tsx)$/),
164+
].filter(file => !/\.(test|spec)\.(ts|tsx)$|__tests__/.test(file));
165+
const dynamic = sources.filter(file =>
166+
/\bimport\(\s*['"][^'"]*(\/gestures\/|\/motion\/|touch-support|internal\/touch)/.test(
167+
fs.readFileSync(file, 'utf8'),
168+
),
169+
);
170+
expect(dynamic.map(file => path.relative(REPO, file))).toEqual([]);
171+
});
172+
});

0 commit comments

Comments
 (0)