An open source design system that's fully customizable and agent ready
TypeScript
feat(native): contracts keep value callbacks, typed text slots, and number sets (#7985)
Cindy Zhang92f70a2edd4c
diff --git a/packages/native/README.md b/packages/native/README.mdindex c49d4f0376..468688cec9 100644--- a/packages/native/README.md+++ b/packages/native/README.md@@ -34,6 +34,22 @@ const props: SelectorProps = {};```+How core documentation becomes a contract:++- A callback whose arguments are values followed by the DOM event that caused+ them, such as `(checked: boolean, e: ChangeEvent) => void`, keeps the values+ in the core; the event stays on the web.+- A callback that carries only an event stays on the web, unless the component+ names it in `callbacks`, as a button's `onClick` would. Its core form takes no+ arguments. A callback with an event before a value stays on the web either+ way.+- Free-form content becomes a typed slot only where a component declares one+ in `slots`; `text` is a string, as for a badge's label or a heading's words.+- A closed set of numbers, such as a heading level, is a Swift enum with raw+ values.+- A core prop may share a platform toolkit's name only when the component+ declares in `sameMeaning` that it means the same thing there.+## Working on it```shdiff --git a/packages/native/scripts/core-docs.mjs b/packages/native/scripts/core-docs.mjsindex 57791085a4..358c889089 100644--- a/packages/native/scripts/core-docs.mjs+++ b/packages/native/scripts/core-docs.mjs@@ -23,9 +23,13 @@ export const CORE_ROOT = path.join('core',);-/** @param {string} name */+/**+ * @param {string} name A component name for `<Name>/<Name>.doc.mjs`, or a+ * path such as `Text/Heading` relative to core's `src`.+ */export async function loadCoreDoc(name) {- const file = path.join(CORE_ROOT, 'src', name, `${name}.doc.mjs`);+ const relative = name.includes('/') ? name : `${name}/${name}`;+ const file = path.join(CORE_ROOT, 'src', `${relative}.doc.mjs`);if (!fs.existsSync(file)) {throw new Error(`No core documentation for "${name}" at ${file}; run pnpm install`,diff --git a/packages/native/src/contract/fromComponentDoc.test.ts b/packages/native/src/contract/fromComponentDoc.test.tsnew file mode 100644index 0000000000..0b7c3c74eb--- /dev/null+++ b/packages/native/src/contract/fromComponentDoc.test.ts@@ -0,0 +1,97 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {fromComponentDoc, type ComponentDocLike} from './fromComponentDoc.js';+import {generateSwift} from './generateSwift.js';++const doc: ComponentDocLike = {+ name: 'Toggle',+ props: [+ {name: 'label', type: 'ReactNode', required: true},+ {name: 'icon', type: 'ReactNode'},+ {name: 'level', type: '1 | 2 | 3'},+ {+ name: 'onChange',+ type: '(on: boolean, e: ChangeEvent<HTMLInputElement>) => void',+ },+ {name: 'onClick', type: '(e: MouseEvent) => void'},+ {name: 'onFocus', type: '(e: FocusEvent) => void'},+ {name: 'onPick', type: '(e: MouseEvent, value: string) => void'},+ ],+};++describe('fromComponentDoc', () => {+ const contract = fromComponentDoc(doc, {+ name: 'Toggle',+ baseTarget: 'control',+ slots: {label: 'text'},+ callbacks: ['onClick', 'onPick'],+ sameMeaning: {onClick: 'a press in Compose too'},+ });++ it('gives declared content a typed text slot and leaves the rest on the web', () => {+ expect(contract.core.label).toEqual({+ type: {kind: 'string'},+ optional: false,+ });+ expect(contract.webOnly.map(prop => prop.name)).toContain('icon');+ });++ it('keeps a value callback and a declared press, and leaves other event callbacks on the web', () => {+ expect(contract.core.onChange?.type).toEqual({+ kind: 'fn',+ args: [{kind: 'boolean'}],+ });+ expect(contract.core.onClick?.type).toEqual({kind: 'fn', args: []});+ expect(contract.webOnly).toContainEqual({+ name: 'onFocus',+ reason: 'callback argument: DOM event',+ });+ // `callbacks` never drops values: an event before a value stays on the web.+ expect(contract.core).not.toHaveProperty('onPick');+ expect(contract.webOnly.map(prop => prop.name)).toContain('onPick');+ });++ it('refuses a toolkit name unless the component declares the same meaning', () => {+ const plain = fromComponentDoc(doc, {+ name: 'Toggle',+ baseTarget: 'control',+ callbacks: ['onClick'],+ });+ expect(plain.core).not.toHaveProperty('onClick');+ expect(+ plain.webOnly.find(prop => prop.name === 'onClick')?.reason,+ ).toContain('compose');+ });++ it('writes a closed set of numbers as a Swift enum with raw values', () => {+ const swift = generateSwift([contract])['Toggle.swift'];+ expect(swift).toContain(+ 'public enum ToggleLevel: Int, CaseIterable, Sendable {',+ );+ expect(swift).toContain(' case v1 = 1');+ });++ it('reads one component of a file that documents several', () => {+ const stack: ComponentDocLike = {+ name: 'Stack',+ components: [+ {name: 'Stack', props: [{name: 'gap', type: '0 | 0.5 | 1'}]},+ {name: 'VStack', props: [{name: 'wrap', type: 'boolean'}]},+ ],+ };+ const vstack = fromComponentDoc(stack, {+ name: 'VStack',+ baseTarget: 'container',+ doc: {file: 'Stack', component: 'VStack'},+ });+ expect(Object.keys(vstack.core)).toEqual(['wrap']);+ expect(() =>+ fromComponentDoc(stack, {+ name: 'Missing',+ baseTarget: 'root',+ doc: {file: 'Stack', component: 'Missing'},+ }),+ ).toThrow('does not document "Missing"');+ });+});diff --git a/packages/native/src/contract/fromComponentDoc.ts b/packages/native/src/contract/fromComponentDoc.tsindex 1e85851999..98f7e6904b 100644--- a/packages/native/src/contract/fromComponentDoc.ts+++ b/packages/native/src/contract/fromComponentDoc.ts@@ -17,25 +17,62 @@ import type {ComponentContract,PropMap,PropSpec,+ PropType,WebOnlyProp,} from './types.js';import type {NativePlatform} from '../platforms.js';-/** The subset of a ComponentDoc this reader needs. */+interface DocProp {+ readonly name: string;+ readonly type?: unknown;+ readonly required?: boolean;+ readonly description?: unknown;+}++/**+ * The subset of a ComponentDoc this reader needs. A file that documents+ * several components, such as Stack with HStack and VStack, lists them in+ * `components`.+ */export interface ComponentDocLike {readonly name: string;- readonly props?: ReadonlyArray<{+ readonly props?: ReadonlyArray<DocProp>;+ readonly components?: ReadonlyArray<{readonly name: string;- readonly type?: unknown;- readonly required?: boolean;- readonly description?: unknown;+ readonly props?: ReadonlyArray<DocProp>;}>;}+/**+ * Typed slots (AST-082 FR4) for documented free-form content. `text` is a+ * string in the core contract, as a badge's label or a heading's words.+ */+export type SlotKind = 'text';+/** What the native package adds to one core component. */export interface NativeAdditions {readonly name: string;readonly baseTarget: BaseTarget;+ /**+ * Where core documents the component when it is not `<Name>/<Name>.doc.mjs`:+ * `file` relative to core's `src` without `.doc.mjs`, and `component` when+ * the file documents several components.+ */+ readonly doc?: {readonly file: string; readonly component?: string};+ /** Documented free-form content props, given a typed slot in the core. */+ readonly slots?: Readonly<Record<string, SlotKind>>;+ /**+ * Callbacks whose only documented argument is a DOM event but which name a+ * moment every platform has, such as a button's press. Their core form+ * takes no arguments.+ */+ readonly callbacks?: readonly string[];+ /**+ * Core props whose name a platform toolkit also uses, with the same meaning+ * (AST-082 FR8 forbids only a different meaning), and why: a button's+ * `onClick` is a press in Compose too.+ */+ readonly sameMeaning?: Readonly<Record<string, string>>;/*** Portable definitions for named types the documentation references. Fields* the web type has that are not portable are left out on purpose.@@ -51,6 +88,28 @@ export interface NativeAdditions {readonly webOnly?: Readonly<Record<string, string>>;}+/** The documented props of the component the additions name. */+function documentedProps(+ doc: ComponentDocLike,+ additions: NativeAdditions,+): ReadonlyArray<DocProp> {+ const wanted = additions.doc?.component;+ if (wanted == null) {+ return doc.props ?? [];+ }+ const entry = doc.components?.find(component => component.name === wanted);+ if (!entry) {+ throw new Error(+ `${additions.name}: core documentation "${doc.name}" does not document "${wanted}"`,+ );+ }+ return entry.props ?? [];+}++const SLOT_TYPES: Readonly<Record<SlotKind, PropType>> = {+ text: {kind: 'string'},+};+export function fromComponentDoc(doc: ComponentDocLike,additions: NativeAdditions,@@ -58,8 +117,15 @@ export function fromComponentDoc(const core: Record<string, PropSpec> = {};const webOnly: WebOnlyProp[] = [];const types = additions.types ?? {};+ const describe = (prop: DocProp) =>+ typeof prop.description === 'string' ? {doc: prop.description} : {};- for (const prop of doc.props ?? []) {+ for (const prop of documentedProps(doc, additions)) {+ // `id` and `isHidden` are shared base props on every platform (FR7), so a+ // documented prop of either name is the base prop, not a core prop.+ if (prop.name === 'id' || prop.name === 'isHidden') {+ continue;+ }const declaredWebOnly = additions.webOnly?.[prop.name];if (declaredWebOnly) {webOnly.push({name: prop.name, reason: declaredWebOnly});@@ -76,13 +142,39 @@ export function fromComponentDoc(webOnly.push({name: prop.name, reason: 'HTML attribute'});continue;}- const parsed = parseDocType(String(prop.type ?? ''));+ const slot = additions.slots?.[prop.name];+ const slotNameProblem =+ slot &&+ coreNameProblem(prop.name, prop.name in (additions.sameMeaning ?? {}));+ if (slotNameProblem) {+ webOnly.push({name: prop.name, reason: slotNameProblem});+ continue;+ }+ if (slot) {+ core[prop.name] = {+ type: SLOT_TYPES[slot],+ optional: prop.required !== true,+ ...describe(prop),+ };+ continue;+ }+ let parsed = parseDocType(String(prop.type ?? ''));+ if (+ !parsed.ok &&+ parsed.eventOnly === true &&+ additions.callbacks?.includes(prop.name)+ ) {+ parsed = {ok: true, type: {kind: 'fn', args: []}};+ }if (!parsed.ok) {webOnly.push({name: prop.name, reason: parsed.reason});continue;}// A portable type can still carry a name another platform owns.- const nameProblem = coreNameProblem(prop.name);+ const nameProblem = coreNameProblem(+ prop.name,+ prop.name in (additions.sameMeaning ?? {}),+ );if (nameProblem) {webOnly.push({name: prop.name, reason: nameProblem});continue;@@ -116,7 +208,7 @@ export function fromComponentDoc(core[prop.name] = {type,optional: prop.required !== true,- ...(typeof prop.description === 'string' ? {doc: prop.description} : {}),+ ...describe(prop),};}@@ -127,5 +219,8 @@ export function fromComponentDoc(core,platforms: additions.platforms ?? {},webOnly,+ sameMeaning: Object.keys(additions.sameMeaning ?? {}).filter(+ name => name in core,+ ),};}diff --git a/packages/native/src/contract/generateSwift.ts b/packages/native/src/contract/generateSwift.tsindex 5dcc6a2280..90a385f80a 100644--- a/packages/native/src/contract/generateSwift.ts+++ b/packages/native/src/contract/generateSwift.ts@@ -25,6 +25,11 @@ const pascal = (text: string) =>const ident = (name: string) =>SWIFT_KEYWORDS.has(name) ? `\`${name}\`` : name;+/** `1` → `v1`, `0.5` → `v0_5`, `-1` → `vMinus1`. */+function numberCaseName(value: number): string {+ return `v${String(value).replace('-', 'Minus').replace('.', '_')}`;+}+function caseName(value: string): string {const name = camel(value.replace(/[^A-Za-z0-9_-]/g, '-'));return ident(/^[0-9]/.test(name) ? `v${name}` : name || 'empty');@@ -52,6 +57,17 @@ class SwiftWriter {);return name;}+ case 'numberEnum': {+ const name = `${owner}${pascal(prop)}`;+ const raw = type.values.every(Number.isInteger) ? 'Int' : 'Double';+ const cases = type.values.map(+ value => ` case ${numberCaseName(value)} = ${value}`,+ );+ this.decls.push(+ `public enum ${name}: ${raw}, CaseIterable, Sendable {\n${cases.join('\n')}\n}`,+ );+ return name;+ }case 'array':return `[${this.type(owner, prop, type.of)}]`;case 'record': {diff --git a/packages/native/src/contract/generateTypeScript.ts b/packages/native/src/contract/generateTypeScript.tsindex df8e43bb93..8cacae379f 100644--- a/packages/native/src/contract/generateTypeScript.ts+++ b/packages/native/src/contract/generateTypeScript.ts@@ -21,6 +21,8 @@ function tsType(type: PropType): string {return type.kind;case 'enum':return type.values.map(value => `'${value}'`).join(' | ');+ case 'numberEnum':+ return type.values.join(' | ');case 'array': {const inner = tsType(type.of);return `ReadonlyArray<${inner}>`;diff --git a/packages/native/src/contract/index.ts b/packages/native/src/contract/index.tsindex 41dd49823b..adc7c650a6 100644--- a/packages/native/src/contract/index.ts+++ b/packages/native/src/contract/index.ts@@ -14,7 +14,11 @@ import {checkContract, type ContractIssue} from './rules.js';import type {ComponentContract} from './types.js';export {fromComponentDoc} from './fromComponentDoc.js';-export type {ComponentDocLike, NativeAdditions} from './fromComponentDoc.js';+export type {+ ComponentDocLike,+ NativeAdditions,+ SlotKind,+} from './fromComponentDoc.js';export {generateSwift} from './generateSwift.js';export {generateTypeScript} from './generateTypeScript.js';export {parseDocType} from './parseDocType.js';@@ -22,8 +26,12 @@ export {checkContract, coreNameProblem} from './rules.js';export type {ContractIssue} from './rules.js';export type * from './types.js';-/** Loads one core component's documentation by component name. */-export type ComponentDocLoader = (name: string) => Promise<ComponentDocLike>;+/**+ * Loads one core documentation file: a component name for+ * `<Name>/<Name>.doc.mjs`, or a path such as `Text/Heading` relative to core's+ * `src` without `.doc.mjs`.+ */+export type ComponentDocLoader = (file: string) => Promise<ComponentDocLike>;export interface BuiltContracts {readonly contracts: readonly ComponentContract[];@@ -38,7 +46,8 @@ export async function buildContracts(const warnings: ContractIssue[] = [];const errors: ContractIssue[] = [];for (const additions of NATIVE_COMPONENTS) {- const contract = fromComponentDoc(await loadDoc(additions.name), additions);+ const doc = await loadDoc(additions.doc?.file ?? additions.name);+ const contract = fromComponentDoc(doc, additions);for (const issue of checkContract(contract)) {(issue.level === 'error' ? errors : warnings).push(issue);}diff --git a/packages/native/src/contract/parseDocType.test.ts b/packages/native/src/contract/parseDocType.test.tsindex 7eb8bfa14b..a286a2bbf1 100644--- a/packages/native/src/contract/parseDocType.test.ts+++ b/packages/native/src/contract/parseDocType.test.ts@@ -50,3 +50,48 @@ describe('parseDocType', () => {}});});++describe('parseDocType callbacks and closed number sets', () => {+ it('keeps the values of a value callback and leaves its DOM event on the web', () => {+ expect(+ parseDocType(+ '(checked: boolean, e: ChangeEvent<HTMLInputElement>) => void',+ ),+ ).toEqual({ok: true, type: {kind: 'fn', args: [{kind: 'boolean'}]}});+ expect(+ parseDocType('(value: string, event: React.ChangeEvent) => void'),+ ).toEqual({ok: true, type: {kind: 'fn', args: [{kind: 'string'}]}});+ });++ it.each([+ '(e: FocusEvent<HTMLInputElement>) => void',+ '(event: MouseEvent) => void',+ ])('keeps the event-only callback %s on the web', type => {+ expect(parseDocType(type)).toEqual({+ ok: false,+ reason: 'callback argument: DOM event',+ eventOnly: true,+ });+ });++ it('refuses an event that is not last', () => {+ const parsed = parseDocType('(e: MouseEvent, value: string) => void');+ expect(parsed).toMatchObject({+ ok: false,+ reason: 'callback argument: DOM event',+ });+ expect(parsed).not.toHaveProperty('eventOnly');+ });++ it('reads a closed set of numbers', () => {+ expect(parseDocType('1 | 2 | 3')).toEqual({+ ok: true,+ type: {kind: 'numberEnum', values: [1, 2, 3]},+ });+ expect(parseDocType('0 | 0.5 | 1')).toEqual({+ ok: true,+ type: {kind: 'numberEnum', values: [0, 0.5, 1]},+ });+ expect(parseDocType("1 | 'auto'").ok).toBe(false);+ });+});diff --git a/packages/native/src/contract/parseDocType.ts b/packages/native/src/contract/parseDocType.tsindex f589b158c1..5c0017c4de 100644--- a/packages/native/src/contract/parseDocType.ts+++ b/packages/native/src/contract/parseDocType.ts@@ -11,7 +11,12 @@ import type {PropSpec, PropType} from './types.js';export type ParsedType =| {readonly ok: true; readonly type: PropType}- | {readonly ok: false; readonly reason: string};+ | {+ readonly ok: false;+ readonly reason: string;+ /** True for a callback whose only arguments are DOM events. */+ readonly eventOnly?: boolean;+ };/** Web-only types, keyed by name, with the reason each has no native form. */const WEB_ONLY_TYPES: Readonly<Record<string, string>> = {@@ -33,8 +38,17 @@ const WEB_ONLY_TYPES: Readonly<Record<string, string>> = {ChangeEvent: 'DOM event',DragEvent: 'DOM event',ClipboardEvent: 'DOM event',+ FormEvent: 'DOM event',+ TouchEvent: 'DOM event',+ SyntheticEvent: 'DOM event',};+/** True for a DOM event type, with or without its element parameter. */+function isDomEvent(text: string): boolean {+ const name = /^(?:React\.)?([A-Z]\w*)(?:<[\s\S]*>)?$/.exec(text.trim())?.[1];+ return name != null && WEB_ONLY_TYPES[name] === 'DOM event';+}+const ok = (type: PropType): ParsedType => ({ok: true, type});const no = (reason: string): ParsedType => ({ok: false, reason});@@ -134,10 +148,24 @@ function parseFunction(text: string): ParsedType | null {);}const params = arrow[0].slice(1, -1).trim();- const args: PropType[] = [];- for (const param of params ? splitTop(params, ',') : []) {+ const types = (params ? splitTop(params, ',') : []).map(param => {const match = /^([A-Za-z_$][\w$]*)\??\s*:\s*([\s\S]+)$/.exec(param);- const parsed = parseDocType(match ? match[2] : param);+ return match ? match[2] : param;+ });+ // A value callback ends with the DOM event that caused it, as in+ // `(checked: boolean, e: ChangeEvent) => void`. The values are the portable+ // callback; the trailing event is the web's part. A callback that carries+ // only an event stays on the web.+ let end = types.length;+ while (end > 0 && isDomEvent(types[end - 1])) {+ end--;+ }+ if (end === 0 && types.length > 0) {+ return {ok: false, reason: 'callback argument: DOM event', eventOnly: true};+ }+ const args: PropType[] = [];+ for (const type of types.slice(0, end)) {+ const parsed = parseDocType(type);if (!parsed.ok) {return no(`callback argument: ${parsed.reason}`);}@@ -148,8 +176,9 @@ function parseFunction(text: string): ParsedType | null {/*** Parses a documented type string. Supported portable forms: `string`,- * `number`, `boolean`, closed string unions, arrays, plain object literals,- * callbacks with portable arguments, and named types. A union of different+ * `number`, `boolean`, closed string or number unions, arrays, plain object+ * literals, callbacks with portable arguments (a trailing DOM event argument+ * is the web's part), and named types. A union of different* kinds has no Swift or Kotlin form.*/export function parseDocType(raw: string): ParsedType {@@ -170,6 +199,9 @@ export function parseDocType(raw: string): ParsedType {if (members.every(m => /^'[^']*'$/.test(m))) {return ok({kind: 'enum', values: members.map(m => m.slice(1, -1))});}+ if (members.every(m => /^-?\d+(?:\.\d+)?$/.test(m))) {+ return ok({kind: 'numberEnum', values: members.map(Number)});+ }const webOnly = members.find(m => WEB_ONLY_TYPES[m] != null);if (webOnly) {return no(WEB_ONLY_TYPES[webOnly]);@@ -187,6 +219,9 @@ export function parseDocType(raw: string): ParsedType {if (WEB_ONLY_TYPES[t] != null) {return no(WEB_ONLY_TYPES[t]);}+ if (isDomEvent(t)) {+ return no('DOM event');+ }const generic = /^(?:Readonly)?Array<([\s\S]+)>$/.exec(t);if (t.endsWith('[]') || generic) {diff --git a/packages/native/src/contract/rules.ts b/packages/native/src/contract/rules.tsindex 16f601f911..236d2a5351 100644--- a/packages/native/src/contract/rules.ts+++ b/packages/native/src/contract/rules.ts@@ -29,15 +29,21 @@ export interface ContractIssue {readonly message: string;}-/** Why a core prop name is not allowed, or null when it is. */-export function coreNameProblem(name: string): string | null {+/**+ * Why a core prop name is not allowed, or null when it is. A toolkit name is+ * allowed when the component declares it has the same meaning there.+ */+export function coreNameProblem(+ name: string,+ sameMeaning = false,+): string | null {if (SWIFT_KEYWORDS.has(name)) {return `"${name}" is a Swift keyword`;}if (KOTLIN_KEYWORDS.has(name)) {return `"${name}" is a Kotlin keyword`;}- if (RECLAIMED.has(name)) {+ if (RECLAIMED.has(name) || sameMeaning) {return null;}for (const [toolkit, names] of Object.entries(TOOLKIT_NAMES)) {@@ -73,8 +79,9 @@ export function checkContract(contract: ComponentContract): ContractIssue[] {const collect = (props: PropMap) =>Object.values(props).forEach(spec => namedTypesIn(spec.type, referenced));+ const sameMeaning = new Set(contract.sameMeaning ?? []);for (const name of Object.keys(contract.core)) {- const problem = coreNameProblem(name);+ const problem = coreNameProblem(name, sameMeaning.has(name));if (problem) {add('error',diff --git a/packages/native/src/contract/types.ts b/packages/native/src/contract/types.tsindex b47ed20820..dec3d3eee8 100644--- a/packages/native/src/contract/types.ts+++ b/packages/native/src/contract/types.ts@@ -16,6 +16,8 @@ export type PropType =| {kind: 'number'}| {kind: 'boolean'}| {kind: 'enum'; values: readonly string[]}+ /** A closed set of numbers, such as a heading level or a spacing step. */+ | {kind: 'numberEnum'; values: readonly number[]}| {kind: 'array'; of: PropType}| {kind: 'record'; fields: Readonly<Record<string, PropSpec>>}| {kind: 'fn'; args: readonly PropType[]}@@ -49,4 +51,6 @@ export interface ComponentContract {readonly platforms: Readonly<Partial<Record<NativePlatform, PropMap>>>;/** Core-doc props that stay in the web contract. */readonly webOnly: readonly WebOnlyProp[];+ /** Core props that share a toolkit name with the same meaning (FR8). */+ readonly sameMeaning?: readonly string[];}