diff --git a/.changeset/quiet-chevrons-pilot.md b/.changeset/quiet-chevrons-pilot.md new file mode 100644 index 0000000000..716eb0a5de --- /dev/null +++ b/.changeset/quiet-chevrons-pilot.md @@ -0,0 +1,9 @@ +--- +'@fluentui-react-native/components': minor +'@fluentui-react-native/design': minor +'@fluentui-react-native/extract-icons': minor +--- + +Add typed asset references to component tokens and use size-specific Fluent SVG chevrons in MenuButton on macOS, Windows, and Win32. The extractor can emit a provenance manifest for generated icons. + +Render the MenuButton chevron adapters directly without an extra React component layer. diff --git a/.changeset/round-buttons-layer.md b/.changeset/round-buttons-layer.md new file mode 100644 index 0000000000..81aed59bfe --- /dev/null +++ b/.changeset/round-buttons-layer.md @@ -0,0 +1,9 @@ +--- +'@fluentui-react-native/components': minor +'@fluentui-react-native/design': minor +'@fluentui-react-native/framework-base': minor +--- + +Add JSON component tokens and theme override layers for Button and MenuButton. Caller visual styles and slot props take precedence over component and theme defaults. + +Export reusable token validators and React Native style enum value lists from `@fluentui-react-native/design/styling` for custom components. diff --git a/apps/storybook/AGENTS.md b/apps/storybook/AGENTS.md index ee59fea47e..21b1370a8d 100644 --- a/apps/storybook/AGENTS.md +++ b/apps/storybook/AGENTS.md @@ -30,6 +30,8 @@ configuration, driver, and runtime behavior belongs to package-owned guidance: `prep` when switching renderer. Bundle before prep if Pods must embed the JavaScript bundle. Only `macos/Podfile` is hand-authored; Pods, lockfiles, workspaces, build products, and DerivedData are generated. +- macOS native smoke uses the instance-specific bundle embedded in the app. + The interactive development commands still use Metro. - Windows project files and registrations are generated. Preserve the app's declared helper and identity setup. - Win32 uses the prebuilt REX Paper host. Bundle before run; native build is diff --git a/apps/storybook/desktop.config.mts b/apps/storybook/desktop.config.mts index 1b277fc593..7d1c5469be 100644 --- a/apps/storybook/desktop.config.mts +++ b/apps/storybook/desktop.config.mts @@ -8,6 +8,17 @@ import { defineDesktopConfig } from '@fluentui-react-native/desktop-test/config' import appManifest from './app.json' with { type: 'json' }; +// RNSVG's WinMD must not target a newer SDK than the app. CI supplies the installed SDK. +const windowsSdkVersion = process.env.WindowsTargetPlatformVersion || '10.0.22621.0'; +const windowsArgs = [ + 'run-windows', + '--sln', + 'windows/AgenticStorybook.sln', + '--no-packager', + '--msbuildprops', + `WindowsTargetPlatformVersion=${windowsSdkVersion}`, +]; + const win32Host = { component: 'AgenticStorybook', windowTitle: 'Agentic Components Storybook (Win32)', @@ -18,7 +29,13 @@ export default defineDesktopConfig({ projectRoot: new URL('.', import.meta.url), targets: { macos: { host: { kind: 'react-native-test-app', renderer: 'fabric' } }, - windows: { host: { kind: 'react-native-test-app', renderer: 'fabric' } }, + windows: { + host: { kind: 'react-native-test-app', renderer: 'fabric' }, + commands: { + build: { command: 'rnc-cli', args: [...windowsArgs, '--no-deploy', '--no-launch'] }, + run: { command: 'rnc-cli', args: windowsArgs }, + }, + }, win32: { host: { kind: 'rex', renderer: 'paper', ...win32Host }, commands: { run: createWin32RunCommand(win32Host) } }, }, reporting: { artifactsRoot: './artifacts/desktop' }, @@ -50,6 +67,10 @@ export default defineDesktopConfig({ ], ], platformOptions: { + macos: { + // Native smoke builds an instance-specific bundle. Test that bundle rather than starting a second, cold Metro build at launch. + smoke: { native: { kind: 'macos' }, metro: false }, + }, windows: { smoke: createWindowsSmokeOptions({ windowTitle: 'Agentic Components Storybook', diff --git a/apps/storybook/react-native.config.js b/apps/storybook/react-native.config.js index e4f19eb331..a0bea1a30c 100644 --- a/apps/storybook/react-native.config.js +++ b/apps/storybook/react-native.config.js @@ -16,12 +16,5 @@ const project = (() => { })(); module.exports = { - dependencies: { - 'react-native-svg': { - platforms: { - windows: null, - }, - }, - }, ...(project ? { project } : undefined), }; diff --git a/packages/agentic/components/THIRD_PARTY_NOTICES.txt b/packages/agentic/components/THIRD_PARTY_NOTICES.txt new file mode 100644 index 0000000000..462fad9c96 --- /dev/null +++ b/packages/agentic/components/THIRD_PARTY_NOTICES.txt @@ -0,0 +1,28 @@ +Fluent System Icons +https://github.com/microsoft/fluentui-system-icons + +The generated Fluent icon modules use artwork from @fluentui/svg-icons and +code generated by @fluentui/react-native-icons. The adjacent generated +manifest records the package versions and hashes. The upstream MIT license: + +MIT License + +Copyright (c) 2020 Microsoft Corporation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/agentic/components/package.json b/packages/agentic/components/package.json index ba2855d559..21acc3e7d7 100644 --- a/packages/agentic/components/package.json +++ b/packages/agentic/components/package.json @@ -13,6 +13,7 @@ "AGENTS.md", "CHANGELOG.md", "README.md", + "THIRD_PARTY_NOTICES.txt", "jest.config.cjs", "lib/", "package.json", @@ -49,6 +50,9 @@ "clean": "fluentui-scripts clean", "format": "fluentui-scripts format", "lint": "fluentui-scripts lint", + "prebuild": "node ./scripts/generate-token-icons.cjs", + "prepack": "node ./scripts/generate-token-icons.cjs --check", + "check:token-icons": "node ./scripts/generate-token-icons.cjs --check", "report:spec-source-drift": "node ./scripts/spec-contracts/report-spec-source-drift.cjs", "test": "node ./scripts/spec-contracts/check-spec-contracts.cjs && yarn test:stories && fluentui-scripts jest", "test:stories": "tsc -p tsconfig.stories.json", @@ -57,11 +61,13 @@ "dependencies": { "@fluentui-react-native/design": "workspace:*", "@fluentui-react-native/framework-base": "workspace:*", - "@fluentui-react-native/native-core": "workspace:*" + "@fluentui-react-native/native-core": "workspace:*", + "@fluentui/react-native-icons": "2.0.347" }, "devDependencies": { "@babel/core": "catalog:", "@fluentui-react-native/desktop-driver": "workspace:*", + "@fluentui-react-native/extract-icons": "workspace:*", "@fluentui-react-native/scripts": "workspace:*", "@fluentui-react-native/storybook-desktop": "workspace:*", "@office-iss/react-native-win32": "^0.81.0", @@ -105,7 +111,12 @@ } }, "furn": { - "jestPlatform": "macos" + "jestPlatform": "macos", + "tokenAssets": { + "fluent-icon": { + "output": "src/common/generated/fluent-icons" + } + } }, "rnx-kit": { "kitType": "library", diff --git a/packages/agentic/components/references/contracts.md b/packages/agentic/components/references/contracts.md index f8aa2040bf..6d18739ed9 100644 --- a/packages/agentic/components/references/contracts.md +++ b/packages/agentic/components/references/contracts.md @@ -25,8 +25,12 @@ JSON provides unambiguous scalars, built-in Node parsing, deterministic atomic rewrites, and no additional parser dependency. Generator rewrites would also discard the main benefit of YAML comments. Keep this provenance in JSON. -`spec/tokens.yaml` remains YAML because it is concise, human-authored token -mapping data rather than a generated identity record. +Existing `spec/tokens.yaml` companions document version 1 bindings. Components +using the runtime token layer instead own a single `spec/tokens.json` companion +with `schemaVersion: 2`, `component`, `implementation`, an ordered `axes` list, +slot `bindings`, and `tokenGaps`. `SPEC.md` links the authoritative companion. +The component imports JSON directly; the checker must not regenerate its values. +See [Styles and tokens](styles-and-tokens.md) for selectors and resolution. ## Schema version 2 diff --git a/packages/agentic/components/references/source-boundaries.md b/packages/agentic/components/references/source-boundaries.md index 0982eb8e49..7d60357c82 100644 --- a/packages/agentic/components/references/source-boundaries.md +++ b/packages/agentic/components/references/source-boundaries.md @@ -21,6 +21,8 @@ or [primitive](primitives.md) reference when a change crosses component boundari - Production source may depend only on React / React Native native components, `@fluentui-react-native/design`, `@fluentui-react-native/framework-base`, and native-core's public modern platform entrypoints. +- Generated Fluent icon leaves may import `react-native-svg` and `@fluentui/react-native-icons/utils`. Do not import + the Fluent icons catalog from component code. The extractor and SVG catalog are build-time dependencies only. - Import native-core values only from platform-resolved files (for example `common/popupHost.macos.ts` importing `@fluentui-react-native/native-core/macos`). Shared files may use `import type` from `/macos`, whose types the `/windows` entrypoint exports identically. Never import its root, `/legacy`, or internals, and give hosts without a diff --git a/packages/agentic/components/references/styles-and-tokens.md b/packages/agentic/components/references/styles-and-tokens.md index 8d34ff0748..fd5e1ec3e2 100644 --- a/packages/agentic/components/references/styles-and-tokens.md +++ b/packages/agentic/components/references/styles-and-tokens.md @@ -27,24 +27,59 @@ value. array of layers; the design token reference (`@fluentui-react-native/design/references/tokens.md`) describes shadow and motion values. - Prefer Flex tokens for every mapped semantic value. -- Import named global tokens only when Flex has no equivalent, such as current Button icon dimensions or a true zero. -- Record a genuine token gap in the component spec. Do not replace it with a nearby token or numeric literal. +- Use typed JSON literals for fixed defaults such as Button's icon dimensions. In older TypeScript factories, use named + globals where appropriate. Record genuine semantic gaps; do not substitute unrelated tokens that currently match by value. - For compatibility with an existing V1 component, derive cross-platform mappings from its Win32, macOS, or Windows implementation. Do not use iOS as the canonical value unless the change explicitly targets iOS. - Consumers of the same theme source, revision, and resolved appearance share one `ThemeState`, and therefore token and style-cache identity. The design theming reference (`@fluentui-react-native/design/references/theming.md`) defines the cache keys and when a new state is created. -## Build styles in layers +## Component token companions (v2) + +Button and MenuButton import `spec/tokens.json` in their module-scoped `defineComponentTokens` calls. JSON is the only +runtime source of ordered axes. Use the component's state type for typed resolution and theme patches; don't redeclare +the axes in TypeScript. Reuse the named field validators from `@fluentui-react-native/design/styling`. Each slot contains +flat React Native style keys and reviewed prop settings: + +```json +{ + "borderWidth": "tokens:strokeWidth.thin", + "when.size.medium": { + "paddingHorizontal": "tokens:spacing.componentBase250", + "when.iconOnly.true": { "paddingHorizontal": "tokens:spacing.componentBase150" } + } +} +``` + +For private icon slots, `fluent-icon: ChevronDown16Regular` references a sized Fluent export. Component `prebuild` +scans every binding branch and extracts one private TSX leaf per referenced asset into the directory configured +under `furn.tokenAssets` in the package manifest. Commit generated modules and their provenance manifest; run +`yarn check:token-icons` to detect stale output without writing it. Group all SVG adapters and asset registries for a +component in its private `.assets.tsx`, even when they serve unrelated slots. Import only the generated +leaves the component needs, never a catalog barrel or a path read from JSON. Define hook-free SVG adapters with +`directComponent` from framework-base and use its JSX runtime so the `Icon` primitive can inline the adapter without an +extra React component layer. MenuButton uses the size-specific Fluent SVG chevron on all supported renderers; its +Variants story exercises the production trigger. + +`when..` is a literal selector key. Nest only later axes inside a branch. Matching rules combine by +property; the higher differing axis wins within the same layer. Provide a component-owned combined `visualState` for +exclusive presentation; Button's order is disabled, pressed, hovered, then rest. Independent booleans such as `selected` +remain separate. Do not mutate raw interaction state. -Use four layers: +Retrieve the cached definition with `getComponentTokens` using the original `ThemeState`, then pass the component state +directly to `resolveTokenStates`. A slot's domain splits the resolved `style` from `props`. Non-style icon color and +dimensions are presentation settings, not a basis for replacing caller sources or introducing a default icon. -1. A module-scoped `StyleSheet` for structural values that do not depend on theme, props, or state. -2. Module-scoped state factories for theme-independent state selectors. -3. Module-scoped themed factories for token-derived styles. -4. Per-instance style arrays that select cached objects and place user styles last. +Visual precedence is **component defaults, then theme layers, then caller visuals**. Even a base theme field overrides +a state-specific default. A caller's slot visual props and styles win through `attachSlotDefaults`; component-owned +handlers, refs, slot presence, and accessibility are not token overrides. Keep shared focus behavior and Menu popup +styling outside MenuButton's chevron tokens. -Never create a style factory inside a hook or render function. +## Legacy state-style factories + +For components without a v2 companion, use module-scoped structural styles, state factories, and themed factories, +then select cached styles and apply per-instance values. Never create a style factory inside a hook or render function. Reuse the design package's `@fluentui-react-native/design/styling` submodule. The design styling reference (`@fluentui-react-native/design/references/styling.md`) owns the factory and hierarchy semantics: @@ -56,8 +91,7 @@ styling reference (`@fluentui-react-native/design/references/styling.md`) owns t - `getThemedColorStyleFactory` converts semantic color keys and delegates its hierarchy and caching to `getThemedStateStyleFactory`. -These are the canonical Button mechanisms and cache plain resolved style objects in `state.themeStyles`. Do not wrap them -in another `StyleSheet.create` cache. Use +These factories cache plain resolved style objects in `state.themeStyles`. Do not wrap them in another `StyleSheet.create` cache. Use `themedStyleSheetFactory` only when a component genuinely needs a complete theme-only `StyleSheet.create` result that is not represented by a branched state definition. @@ -66,15 +100,8 @@ and user styles must remain outside the cache so one component instance cannot l ## Declare state hierarchy and precedence -Represent related axes as ordered hierarchy levels. Each level contains mutually exclusive states in priority order. -Button colors use: - -```ts -[['primary', 'secondary', 'outline', 'subtle'], ['selected'], ['disabled', 'pressed', 'hovered']]; -``` - -This means appearance is the base branch, selected refines it, and interaction is the final refinement. Put interaction -states in `disabled`, `pressed`, `hovered` order so the first active state has the required priority. +In legacy factories, represent related axes as ordered hierarchy levels. Each level contains mutually exclusive states +in priority order. Put exclusive interaction states in `disabled`, `pressed`, `hovered` order. Use `getThemedStateStyleFactory` for token-derived hierarchy definitions and `getStateStyleFactory` for theme-independent definitions. Use `getThemedColorStyleFactory` for semantic background, border, and foreground colors; @@ -85,21 +112,11 @@ An interaction may intentionally switch semantic keys. Button Subtle is transpar pressed token values provide visible stroke feedback. Do not assume a token named `Transparent` will produce visible interaction states; verify the resolved colors' `hover` and `pressed` values. -Build the state source from resolved state without hiding precedence in conditionals. Button pushes appearance, selected, -disabled, pressed, and hovered values, then lets the declared hierarchy select the winner. +Build the legacy factory's state source from resolved state; the declared hierarchy selects the winner. ## Group related layout axes -Combine axes that produce one coherent style object. Button selects size, shape, and content layout from one root style -hierarchy: - -```ts -[ - ['small', 'medium', 'large'], - ['rounded', 'square', 'circle'], - ['withContent', 'iconOnly'], -]; -``` +Group axes that produce one coherent style object; size, shape, and content layout can refine the same slot. Use separate factories for independent concerns such as typography, focus, and content visibility. This keeps unrelated state branches from multiplying into one large definition. @@ -115,7 +132,7 @@ token before assigning it to `ViewStyle['gap']`. ## Apply slot props in one stage -`useStyles.ts` should export `useStyles_unstable`, select styles, and call `attachSlotProps`; it +`useStyles.ts` should export `useStyles_unstable`, select styles, and apply slot props; it should not create factories. Export that hook directly from the package root under the same name. Compose root styles in this order: diff --git a/packages/agentic/components/scripts/generate-token-icons.cjs b/packages/agentic/components/scripts/generate-token-icons.cjs new file mode 100644 index 0000000000..da94f5f1da --- /dev/null +++ b/packages/agentic/components/scripts/generate-token-icons.cjs @@ -0,0 +1,67 @@ +const { spawnSync } = require('node:child_process'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { validateTokenCompanion } = require('./spec-contracts/token-companion.cjs'); + +const root = path.resolve(__dirname, '..'); +const { output } = require('../package.json').furn.tokenAssets['fluent-icon']; +const destination = path.resolve(root, output); +const check = process.argv[2] === '--check'; +const manifestName = 'manifest.generated.json'; + +if (!/^src\/common\/generated\/[a-z][a-z0-9-]*$/.test(output)) { + throw new Error('The Fluent icon output must be a dedicated directory under src/common/generated.'); +} + +const required = new Set(); +for (const file of fs.globSync('src/components/*/spec/tokens.json', { cwd: root }).sort()) { + const component = path.basename(path.dirname(path.dirname(file))); + const icons = validateTokenCompanion(fs.readFileSync(path.join(root, file), 'utf8'), component, file); + for (const icon of icons) required.add(icon); +} + +const staging = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'furn-token-icons-')); +try { + const jobs = [...required].sort().map((icon) => ({ output: `${icon}.generated.tsx`, icons: [icon] })); + const manifest = path.join(staging, manifestName); + if (jobs.length > 0) { + const config = path.join(staging, 'extraction.json'); + fs.writeFileSync(config, JSON.stringify({ extractIcons: jobs })); + // Repository prebuild runs before tsc has created the extractor's bin. + const cli = path.join(path.dirname(require.resolve('@fluentui-react-native/extract-icons/package.json')), 'src', 'cli.ts'); + const result = spawnSync(process.execPath, [cli, '--config', config, '--manifest', manifest], { stdio: 'inherit' }); + if (result.error) throw result.error; + if (result.status !== 0) throw new Error(`Token icon extraction failed (${result.signal ?? result.status}).`); + } else { + fs.writeFileSync(manifest, '{\n "schemaVersion": 1,\n "artifacts": []\n}\n'); + } + + const names = new Set([manifestName, ...jobs.map((job) => job.output)]); + const stale = fs.existsSync(destination) + ? fs.readdirSync(destination).filter((file) => /^[A-Z][A-Za-z0-9]*\.generated\.tsx$/.test(file) && !names.has(file)) + : []; + const changed = [...names].filter((file) => { + const target = path.join(destination, file); + return !fs.existsSync(target) || !fs.readFileSync(target).equals(fs.readFileSync(path.join(staging, file))); + }); + if (check && (changed.length || stale.length)) { + throw new Error(`Generated Fluent icons are out of date: ${[...changed, ...stale].join(', ')}. Run yarn prebuild.`); + } + if (!check) { + fs.mkdirSync(destination, { recursive: true }); + for (const file of changed) { + const target = path.join(destination, file); + const pending = `${target}.${process.pid}.tmp`; + try { + fs.copyFileSync(path.join(staging, file), pending); + fs.renameSync(pending, target); + } finally { + fs.rmSync(pending, { force: true }); + } + } + for (const file of stale) fs.unlinkSync(path.join(destination, file)); + } +} finally { + fs.rmSync(staging, { recursive: true, force: true }); +} diff --git a/packages/agentic/components/scripts/spec-contracts/check-spec-contracts.cjs b/packages/agentic/components/scripts/spec-contracts/check-spec-contracts.cjs index 40976ca9ef..499114d1ea 100644 --- a/packages/agentic/components/scripts/spec-contracts/check-spec-contracts.cjs +++ b/packages/agentic/components/scripts/spec-contracts/check-spec-contracts.cjs @@ -15,8 +15,9 @@ const { repositoryRoot, sourcePathFor, } = require('./common.cjs'); +const { validateTokenCompanion } = require('./token-companion.cjs'); -const requiredCompanions = ['tokens.yaml', 'accessibility.md', 'interaction.md', 'usage.md', 'source.json']; +const requiredCompanions = ['accessibility.md', 'interaction.md', 'usage.md', 'source.json']; const forbiddenCompanionPatterns = [ [/<(?:button|div|span|label|textarea)\b/, 'HTML element'], [/:focus-visible|:where\(|::before|::after/i, 'CSS selector'], @@ -517,7 +518,13 @@ function validateComponent(component, lock) { const source = validateSource(component, spec, lock); invariant(frontMatter.status === source.lifecycle, `${component}/SPEC.md status must match its source lifecycle.`); invariant(frontMatter.source === './spec/source.json', `${component}/SPEC.md must reference ./spec/source.json.`); - invariant(frontMatter.tokens === './spec/tokens.yaml', `${component}/SPEC.md must reference ./spec/tokens.yaml.`); + invariant( + frontMatter.tokens === './spec/tokens.yaml' || frontMatter.tokens === './spec/tokens.json', + `${component}/SPEC.md must reference ./spec/tokens.yaml or ./spec/tokens.json.`, + ); + const tokenFile = path.basename(frontMatter.tokens); + const alternate = tokenFile === 'tokens.json' ? 'tokens.yaml' : 'tokens.json'; + invariant(!fs.existsSync(path.join(componentRoot, 'spec', alternate)), `${component} must have only one token companion.`); invariant(frontMatter.accessibility === './spec/accessibility.md', `${component}/SPEC.md must reference ./spec/accessibility.md.`); invariant(frontMatter.interaction === './spec/interaction.md', `${component}/SPEC.md must reference ./spec/interaction.md.`); invariant(frontMatter.usage === './spec/usage.md', `${component}/SPEC.md must reference ./spec/usage.md.`); @@ -530,7 +537,7 @@ function validateComponent(component, lock) { `${component}/SPEC.md is missing its divergences section.`, ); - for (const companion of ['tokens.yaml', 'accessibility.md', 'interaction.md', 'usage.md']) { + for (const companion of [tokenFile, 'accessibility.md', 'interaction.md', 'usage.md']) { const companionPath = path.join(componentRoot, 'spec', companion); const content = fs.readFileSync(companionPath, 'utf8'); for (const [pattern, label] of forbiddenCompanionPatterns) { @@ -538,11 +545,15 @@ function validateComponent(component, lock) { } } - const tokens = fs.readFileSync(path.join(componentRoot, 'spec/tokens.yaml'), 'utf8'); - invariant(/^schemaVersion:\s*1\s*$/m.test(tokens), `${component}/spec/tokens.yaml must use schemaVersion 1.`); - invariant(new RegExp(`^component:\\s*${component}\\s*$`, 'm').test(tokens), `${component}/spec/tokens.yaml has the wrong component.`); - invariant(/^implementation:\s*\S+\s*$/m.test(tokens), `${component}/spec/tokens.yaml must identify its implementation.`); - invariant(/^tokenGaps:\s*(?:\[\])?\s*$/m.test(tokens), `${component}/spec/tokens.yaml must declare tokenGaps.`); + const tokens = fs.readFileSync(path.join(componentRoot, 'spec', tokenFile), 'utf8'); + if (tokenFile === 'tokens.json') { + validateTokenCompanion(tokens, component, `${component}/spec/${tokenFile}`); + } else { + invariant(/^schemaVersion:\s*1\s*$/m.test(tokens), `${component}/spec/tokens.yaml must use schemaVersion 1.`); + invariant(new RegExp(`^component:\\s*${component}\\s*$`, 'm').test(tokens), `${component}/spec/tokens.yaml has the wrong component.`); + invariant(/^implementation:\s*\S+\s*$/m.test(tokens), `${component}/spec/tokens.yaml must identify its implementation.`); + invariant(/^tokenGaps:\s*(?:\[\])?\s*$/m.test(tokens), `${component}/spec/tokens.yaml must declare tokenGaps.`); + } return source; } diff --git a/packages/agentic/components/scripts/spec-contracts/token-companion.cjs b/packages/agentic/components/scripts/spec-contracts/token-companion.cjs new file mode 100644 index 0000000000..397f4f841a --- /dev/null +++ b/packages/agentic/components/scripts/spec-contracts/token-companion.cjs @@ -0,0 +1,104 @@ +const { invariant } = require('./common.cjs'); + +function parseTokenJson(text, file) { + const parsed = JSON.parse(text); + const objects = []; + // JSON.parse has checked the grammar; this pass preserves duplicate keys. + const tokens = text.matchAll(/"(?:[^"\\]|\\.)*"|[{}:[\],]/g); + let previous; + for (const token of tokens) { + if (token[0] === '{') objects.push(new Set()); + if (token[0] === '}') objects.pop(); + if (token[0] === ':') { + const key = JSON.parse(previous[0]); + const fields = objects.at(-1); + if (fields.has(key)) { + const line = text.slice(0, previous.index).split('\n').length; + throw new Error(`${file}:${line}: duplicate token key "${key}".`); + } + fields.add(key); + } + previous = token; + } + return parsed; +} + +function validateTokenCompanion(text, component, file) { + const schema = parseTokenJson(text, file); + const plain = (value) => value !== null && typeof value === 'object' && !Array.isArray(value); + const safe = (key) => key !== 'constructor' && key !== 'prototype' && key !== '__proto__'; + invariant(plain(schema) && schema.schemaVersion === 2 && schema.component === component, `${file} has the wrong version or component.`); + invariant(typeof schema.implementation === 'string' && schema.implementation, `${file} must identify its implementation.`); + invariant(Array.isArray(schema.tokenGaps), `${file} must declare tokenGaps.`); + invariant(Array.isArray(schema.axes), `${file} must declare ordered axes.`); + invariant(plain(schema.bindings) && Object.keys(schema.bindings).length > 0, `${file} must declare slot bindings.`); + + const axes = new Set(); + const selectors = new Map(); + const fluentIcons = new Set(); + for (const [rank, axis] of schema.axes.entries()) { + invariant(Array.isArray(axis) && axis.length === 2, `${file}: expected [field, members] axis.`); + const [field, members] = axis; + invariant( + typeof field === 'string' && safe(field) && field && !field.includes('.') && !axes.has(field), + `${file}: invalid axis ${field}.`, + ); + axes.add(field); + invariant(Array.isArray(members) && members.length, `${file}: axis ${field} must have members.`); + for (const member of members) { + const type = typeof member; + invariant( + type === 'boolean' || + (type === 'number' && Number.isFinite(member) && !String(member).includes('.')) || + (type === 'string' && member && safe(member) && !member.includes('.')), + `${file}: invalid member of ${field}.`, + ); + const selector = `when.${field}.${member}`; + invariant(!selectors.has(selector), `${file}: ambiguous selector ${selector}.`); + selectors.set(selector, rank); + } + } + + function walk(node, path, rank) { + invariant(plain(node), `${path}: expected an object.`); + for (const [key, value] of Object.entries(node)) { + const field = `${path}.${key}`; + invariant(safe(key), `${field}: invalid token field.`); + if (key.startsWith('when.')) { + const next = selectors.get(key); + invariant(next > rank, `${field}: unknown, repeated, or out-of-order selector.`); + walk(value, field, next); + } else { + invariant(value !== null, `${field}: null token values are not supported.`); + if (typeof value === 'string' && value.startsWith('fluent-icon:')) { + const icon = value.slice('fluent-icon:'.length).replace(/^ /, ''); + const stem = icon.replace(/(?:Regular|Filled|Light|Color|HighContrast)$/, ''); + invariant( + /^[A-Z][A-Za-z0-9]*$/.test(icon) && stem !== icon && /[0-9]$/.test(stem), + `${field}: invalid sized Fluent icon export ${icon}.`, + ); + fluentIcons.add(icon); + } else if (typeof value === 'string' && value.startsWith('tokens:')) { + const parts = value.slice(7).split('.'); + const [group, name, member] = parts; + invariant( + name && + safe(name) && + safe(group) && + (group === 'color' ? parts.length === 3 && ['rest', 'hover', 'pressed', 'active'].includes(member) : parts.length === 2), + `${field}: malformed Flex reference ${value}.`, + ); + invariant(member !== 'active' || axes.has('visualState'), `${field}: active color requires a visualState axis.`); + } + } + } + } + + for (const [slot, node] of Object.entries(schema.bindings)) { + invariant(safe(slot), `${file}: invalid slot ${slot}.`); + walk(node, `${file}:${slot}`, -1); + } + return fluentIcons; +} + +module.exports = { validateTokenCompanion }; diff --git a/packages/agentic/components/src/common/generated/fluent-icons/ChevronDown16Regular.generated.tsx b/packages/agentic/components/src/common/generated/fluent-icons/ChevronDown16Regular.generated.tsx new file mode 100644 index 0000000000..bd9bc5d7aa --- /dev/null +++ b/packages/agentic/components/src/common/generated/fluent-icons/ChevronDown16Regular.generated.tsx @@ -0,0 +1,6 @@ +import { Path } from "react-native-svg"; +import type { SvgProps } from "react-native-svg"; +import type { FluentIconsProps } from "@fluentui/react-native-icons/utils"; +import { FluentSvg } from "@fluentui/react-native-icons/utils"; + +export const ChevronDown16Regular = /*#__PURE__*/(props: FluentIconsProps) => ; diff --git a/packages/agentic/components/src/common/generated/fluent-icons/ChevronDown20Regular.generated.tsx b/packages/agentic/components/src/common/generated/fluent-icons/ChevronDown20Regular.generated.tsx new file mode 100644 index 0000000000..ee56770f3f --- /dev/null +++ b/packages/agentic/components/src/common/generated/fluent-icons/ChevronDown20Regular.generated.tsx @@ -0,0 +1,10 @@ +import { Path } from "react-native-svg"; +import type { SvgProps } from "react-native-svg"; +import type { FluentIconsProps } from "@fluentui/react-native-icons/utils"; +import { FluentSvg } from "@fluentui/react-native-icons/utils"; +const ChevronDown20RegularPath0 = "M15.85 7.65c.2.2.2.5 0 .7l-5.46 5.49a.55.55 0 0 1-.78 0L4.15 8.35a.5.5 0 1 1 .7-.7L10 12.8l5.15-5.16c.2-.2.5-.2.7 0"; + +export const ChevronDownRegular = /*#__PURE__*/(props: FluentIconsProps) => ; + + +export const ChevronDown20Regular = /*#__PURE__*/(props: FluentIconsProps) => ; diff --git a/packages/agentic/components/src/common/generated/fluent-icons/manifest.generated.json b/packages/agentic/components/src/common/generated/fluent-icons/manifest.generated.json new file mode 100644 index 0000000000..919275ecbe --- /dev/null +++ b/packages/agentic/components/src/common/generated/fluent-icons/manifest.generated.json @@ -0,0 +1,41 @@ +{ + "schemaVersion": 1, + "catalog": { + "name": "@fluentui/svg-icons", + "version": "1.1.345", + "license": "MIT" + }, + "generator": { + "name": "@fluentui/react-native-icons", + "version": "2.0.347", + "license": "MIT" + }, + "artifacts": [ + { + "output": "ChevronDown16Regular.generated.tsx", + "requested": [ + "ChevronDown16Regular" + ], + "inputs": [ + { + "file": "chevron_down_16_regular.svg", + "sha256": "33efa668d236d70a945c00cbbd3fda019994794a5b5a2e17f5e66aac19abd199" + } + ], + "sha256": "c7aff7a7838da808198591893c3c57d556ef20ed8ac213ce56526d2236b197f4" + }, + { + "output": "ChevronDown20Regular.generated.tsx", + "requested": [ + "ChevronDown20Regular" + ], + "inputs": [ + { + "file": "chevron_down_20_regular.svg", + "sha256": "2584741754fe0e27641d7423ff96e675167119889fbc1e5129516973cbfb136a" + } + ], + "sha256": "84edeca38509494caf5be6ee1c5805231aa8273ed5d963a97ad08de4ac19f32d" + } + ] +} diff --git a/packages/agentic/components/src/common/iconTokenProps.ts b/packages/agentic/components/src/common/iconTokenProps.ts new file mode 100644 index 0000000000..2c88488854 --- /dev/null +++ b/packages/agentic/components/src/common/iconTokenProps.ts @@ -0,0 +1,3 @@ +import { colorToken, numericToken } from '@fluentui-react-native/design/styling'; + +export const iconTokenProps = { color: colorToken, width: numericToken, height: numericToken }; diff --git a/packages/agentic/components/src/components/button/SPEC.md b/packages/agentic/components/src/components/button/SPEC.md index 54207440e6..36471850ff 100644 --- a/packages/agentic/components/src/components/button/SPEC.md +++ b/packages/agentic/components/src/components/button/SPEC.md @@ -3,7 +3,7 @@ name: button platform: react-native (Windows, macOS) status: implemented source: ./spec/source.json -tokens: ./spec/tokens.yaml +tokens: ./spec/tokens.json accessibility: ./spec/accessibility.md interaction: ./spec/interaction.md usage: ./spec/usage.md @@ -60,8 +60,10 @@ layout and requires an action-oriented `accessibilityLabel`. props. - **BTN-002:** Render only supplied optional slots in the documented order, with the selected-icon fallback and wrapping content behavior. -- **BTN-003:** Resolve appearance, selection, disabled, pressed, and hovered - visual state from Flex tokens; user root style wins last. +- **BTN-003:** Resolve slot visuals from the component token companion, then + theme component-token layers, then caller visuals. Disabled, pressed, + hovered, and rest form one visual axis in that priority order. Selection + remains independent. Decorative accessibility and slot presence are unchanged. - **BTN-004:** Expose button semantics and a native name from plain content unless the caller supplies naming, merge caller accessibility state, warn for an unnamed icon-only button, and hide decorative icons. @@ -115,11 +117,11 @@ Button adds no component-owned motion. ## Conformance -| Requirement | Evidence | -| ----------- | ----------------------------------------------------------------------------- | -| BTN-001 | `button.types.ts`, `useButton.ts`, `button.test.tsx` | -| BTN-002 | `renderButton.tsx`, `button.test.tsx`, `button.stories.tsx` | -| BTN-003 | `button.styles.ts`, `useButtonStyles.ts`, `button.test.tsx` | -| BTN-004 | `useButton.ts`, `useButtonStyles.ts`, `button.test.tsx`, `button.stories.tsx` | -| BTN-005 | `useButton.ts`, `renderButton.tsx`, `button.test.tsx`, `button.stories.tsx` | -| BTN-006 | `useButton.ts`, `useButtonStyles.ts`, `renderButton.tsx`, `button.test.tsx` | +| Requirement | Evidence | +| ----------- | ------------------------------------------------------------------------------- | +| BTN-001 | `button.types.ts`, `useButton.ts`, `button.test.tsx` | +| BTN-002 | `renderButton.tsx`, `button.test.tsx`, `button.stories.tsx` | +| BTN-003 | `spec/tokens.json`, `button.styles.ts`, `useButtonStyles.ts`, `button.test.tsx` | +| BTN-004 | `useButton.ts`, `useButtonStyles.ts`, `button.test.tsx`, `button.stories.tsx` | +| BTN-005 | `useButton.ts`, `renderButton.tsx`, `button.test.tsx`, `button.stories.tsx` | +| BTN-006 | `useButton.ts`, `useButtonStyles.ts`, `renderButton.tsx`, `button.test.tsx` | diff --git a/packages/agentic/components/src/components/button/button.styles.ts b/packages/agentic/components/src/components/button/button.styles.ts index 623640d3e9..238aae9118 100644 --- a/packages/agentic/components/src/components/button/button.styles.ts +++ b/packages/agentic/components/src/components/button/button.styles.ts @@ -1,308 +1,88 @@ -import { StyleSheet } from 'react-native'; import type { TextStyle, ViewStyle } from 'react-native'; - -import type { FlexTokens } from '@fluentui-react-native/design'; import { + alignItemsToken, + alignSelfToken, + borderStyleToken, + colorToken, + defineComponentTokens, + dimensionToken, + flexDirectionToken, + fontWeightToken, getGapStyleValue, - getThemedColorStyleFactory, - getThemedStateStyleFactory, - interactiveStatePriority, -} from '@fluentui-react-native/design/styling'; -import type { - ColorStyleDefinition, - StateNames, - StyleDefinition, - TextColorStyle, - ViewColorStyle, + justifyContentToken, + numericToken, + resolveTokenStates, + stringToken, + textAlignToken, } from '@fluentui-react-native/design/styling'; -import { cornerRadiusNone, size160, size200, size240 } from '@fluentui-react-native/design/tokens/global'; +import type { CompiledComponentTokens, ComponentTokenPatch } from '@fluentui-react-native/design/styling'; +import type { IconElementProps } from '../../primitives/icon/icon.types'; +import { iconTokenProps } from '../../common/iconTokenProps'; +import type { ButtonState, ButtonTokenState } from './button.types'; +import schema from './spec/tokens.json' with { type: 'json' }; -import type { ButtonSize, ButtonState } from './button.types'; - -export const buttonStyles = StyleSheet.create({ +const buttonTokenDomains = { root: { - alignItems: 'center', - alignSelf: 'flex-start', - borderStyle: 'solid', - flexDirection: 'row', - justifyContent: 'center', + style: { + alignItems: alignItemsToken, + alignSelf: alignSelfToken, + borderStyle: borderStyleToken, + flexDirection: flexDirectionToken, + justifyContent: justifyContentToken, + borderWidth: numericToken, + minHeight: dimensionToken, + minWidth: dimensionToken, + borderRadius: dimensionToken, + paddingHorizontal: dimensionToken, + paddingVertical: dimensionToken, + gap: getGapStyleValue, + backgroundColor: colorToken, + borderColor: colorToken, + }, + props: {}, }, content: { - flexShrink: 1, - textAlign: 'center', - }, -}); - -const colorStateLevels = [['primary', 'secondary', 'outline', 'subtle'], ['selected'], interactiveStatePriority] as const; -type ColorStateLevels = typeof colorStateLevels; -type ColorState = StateNames; - -const backgroundColorDefinition: ColorStyleDefinition = { - primary: { - backgroundColor: 'backgroundBrandHeavy', - borderColor: 'strokeNeutralTransparent', - disabled: { - backgroundColor: 'backgroundNeutralHeavyDisabled', - }, - }, - secondary: { - backgroundColor: 'backgroundNeutralSubtle', - borderColor: 'strokeNeutralTransparent', - selected: { - backgroundColor: 'backgroundNeutralHeavy', - disabled: { - backgroundColor: 'backgroundNeutralHeavyDisabled', - }, - }, - disabled: { - backgroundColor: 'backgroundNeutralSubtleDisabled', - }, - }, - outline: { - backgroundColor: 'backgroundNeutralTransparent', - borderColor: 'strokeNeutralLoud', - selected: { - backgroundColor: 'backgroundNeutralHeavy', - borderColor: 'strokeNeutralHeavy', - disabled: { - backgroundColor: 'backgroundNeutralHeavyDisabled', - borderColor: 'strokeNeutralDisabled', - }, - }, - disabled: { - borderColor: 'strokeNeutralDisabled', - }, - }, - subtle: { - backgroundColor: 'backgroundNeutralTransparent', - borderColor: 'strokeNeutralTransparent', - hovered: { - backgroundColor: 'backgroundNeutralSubtle', - }, - pressed: { - backgroundColor: 'backgroundNeutralSubtle', - }, - selected: { - backgroundColor: 'backgroundNeutralSoft', - disabled: { - backgroundColor: 'backgroundNeutralSubtleDisabled', - }, - }, - }, -}; - -const foregroundColorDefinition: ColorStyleDefinition = { - primary: { - color: 'foregroundBrandOnloud', - disabled: { - color: 'foregroundNeutralDisabled', - }, - }, - secondary: { - color: 'foregroundNeutralPrimary', - selected: { - color: 'foregroundNeutralOnloud', - }, - disabled: { - color: 'foregroundNeutralDisabled', - }, - }, - outline: { - color: 'foregroundNeutralPrimary', - selected: { - color: 'foregroundNeutralOnloud', - }, - disabled: { - color: 'foregroundNeutralDisabled', - }, - }, - subtle: { - color: 'foregroundNeutralPrimary', - disabled: { - color: 'foregroundNeutralDisabled', - }, + style: { + flexShrink: numericToken, + textAlign: textAlignToken, + fontFamily: stringToken, + fontSize: numericToken, + lineHeight: numericToken, + fontWeight: fontWeightToken, + color: colorToken, + }, + props: {}, }, + icon: { style: {}, props: iconTokenProps }, }; -const getThemedBackgroundStyle = getThemedColorStyleFactory( - 'Button.background', - backgroundColorDefinition, - colorStateLevels, -); -const getThemedForegroundStyle = getThemedColorStyleFactory( - 'Button.foreground', - foregroundColorDefinition, - colorStateLevels, -); +type ButtonDomains = typeof buttonTokenDomains; +export type ButtonTokens = CompiledComponentTokens; -function getColorStateSource(state: ButtonState): ColorState[] { - const source: ColorState[] = [state.appearance]; - if (state.selected) { - source.push('selected'); +declare module '@fluentui-react-native/design' { + interface ComponentTokenRegistry { + 'furn.button': ComponentTokenPatch; } - if (state.disabled) { - source.push('disabled'); - } - if (state.pressed) { - source.push('pressed'); - } - if (state.hovered) { - source.push('hovered'); - } - return source; -} - -export function getButtonColorStyles(state: ButtonState): { - background: ViewColorStyle; - foreground: TextColorStyle; -} { - const source = getColorStateSource(state); - return { - background: getThemedBackgroundStyle(state, source), - foreground: getThemedForegroundStyle(state, source), - }; -} - -const rootStyleStateLevels = [ - ['small', 'medium', 'large'], - ['rounded', 'square', 'circle'], - ['withContent', 'iconOnly'], -] as const; -type RootStyleStateLevels = typeof rootStyleStateLevels; -type RootStyleState = StateNames; - -function createSizeStyle( - roundedRadius: NonNullable, - circleRadius: NonNullable, - withContent: ViewStyle, - iconOnly: ViewStyle, -) { - return { - rounded: { - borderRadius: roundedRadius, - iconOnly, - withContent, - }, - square: { - borderRadius: cornerRadiusNone, - iconOnly, - withContent, - }, - circle: { - borderRadius: circleRadius, - iconOnly, - withContent, - }, - }; -} - -function createRootStyleDefinition({ borderRadius, spacing, strokeWidth }: FlexTokens): StyleDefinition { - return { - borderWidth: strokeWidth.thin, - minHeight: size240, - minWidth: size240, - small: createSizeStyle( - borderRadius.base200, - borderRadius.circular, - { - gap: getGapStyleValue(spacing.componentBase50), - paddingHorizontal: spacing.componentBase200, - paddingVertical: spacing.componentBase100, - }, - { - paddingHorizontal: spacing.componentBase100, - paddingVertical: spacing.componentBase100, - }, - ), - medium: createSizeStyle( - borderRadius.base300, - borderRadius.circular, - { - gap: getGapStyleValue(spacing.componentBase100), - paddingHorizontal: spacing.componentBase250, - paddingVertical: spacing.componentBase150, - }, - { - paddingHorizontal: spacing.componentBase150, - paddingVertical: spacing.componentBase150, - }, - ), - large: createSizeStyle( - borderRadius.base400, - borderRadius.circular, - { - gap: getGapStyleValue(spacing.componentBase150), - paddingHorizontal: spacing.componentBase300, - paddingVertical: spacing.componentBase200, - }, - { - paddingHorizontal: spacing.componentBase250, - paddingVertical: spacing.componentBase250, - }, - ), - }; -} - -const getThemedRootStyle = getThemedStateStyleFactory('Button.root', createRootStyleDefinition, rootStyleStateLevels); - -function getRootStyleStateSource(state: ButtonState): RootStyleState[] { - return [state.size, state.shape, state.iconOnly ? 'iconOnly' : 'withContent']; -} - -export function getButtonRootStyle(state: ButtonState): ViewStyle { - return getThemedRootStyle(state, getRootStyleStateSource(state)); } -const contentStyleStateLevels = [['small', 'medium', 'large'], ['selected']] as const; -type ContentStyleStateLevels = typeof contentStyleStateLevels; -type ContentStyleState = StateNames; - -function createContentStyleDefinition({ - fontFamily, - fontSize, - fontWeight, - lineHeight, -}: FlexTokens): StyleDefinition { - const selected: TextStyle = { fontWeight: fontWeight.functionalSemibold }; - return { - fontFamily: fontFamily.functional, - small: { - fontSize: fontSize.functionalBodySmall, - fontWeight: fontWeight.functionalRegular, - lineHeight: lineHeight.functionalBodySmall, - selected, - }, - medium: { - fontSize: fontSize.functionalBodyMedium, - fontWeight: fontWeight.functionalRegular, - lineHeight: lineHeight.functionalBodyMedium, - selected, - }, - large: { - fontSize: fontSize.functionalBodyLarge, - fontWeight: fontWeight.functionalRegular, - lineHeight: lineHeight.functionalBodyLarge, - selected, - }, - }; -} - -const getThemedContentStyle = getThemedStateStyleFactory('Button.content', createContentStyleDefinition, contentStyleStateLevels); +export const buttonTokenDefinition = defineComponentTokens({ + id: 'furn.button', + slots: buttonTokenDomains, + schema, +}); -export function getButtonContentStyle(state: ButtonState, selected = state.selected): TextStyle { - const source: ContentStyleState[] = [state.size]; - if (selected) { - source.push('selected'); - } - return getThemedContentStyle(state, source); +export function getButtonVisualState(disabled: boolean, pressed: boolean, hovered: boolean): ButtonTokenState['visualState'] { + return disabled ? 'disabled' : pressed ? 'pressed' : hovered ? 'hovered' : 'rest'; } -const iconSizes: Record = { - small: size160, - medium: size200, - large: size200, -}; - -export function getButtonIconSize(size: ButtonSize): number { - return iconSizes[size]; +export function resolveButtonChrome(state: ButtonState): { + root: ViewStyle; + content: TextStyle; + icon: Pick; +} { + const { buttonTokens } = state; + const root = resolveTokenStates(buttonTokens.root, state).style; + const content = resolveTokenStates(buttonTokens.content, state).style; + const icon = resolveTokenStates(buttonTokens.icon, state).props; + return { root, content, icon }; } diff --git a/packages/agentic/components/src/components/button/button.test.tsx b/packages/agentic/components/src/components/button/button.test.tsx index c55776efd4..8ff50cbac2 100644 --- a/packages/agentic/components/src/components/button/button.test.tsx +++ b/packages/agentic/components/src/components/button/button.test.tsx @@ -8,6 +8,7 @@ import { render } from '../../common/renderWithTheme'; import type { RenderResult } from '@testing-library/react-native'; import { defaultFlexTokens } from '@fluentui-react-native/design/testing'; +import { FlexThemeReference, ThemeProvider } from '@fluentui-react-native/design'; import { Button } from './button'; import type { ButtonAppearance } from './button.types'; @@ -25,6 +26,27 @@ function getRootStyle(component: RenderResult): ViewStyle { } describe('Button', () => { + it('lets theme base values override state-specific defaults and caller visuals override the theme', async () => { + const theme = new FlexThemeReference({ + componentTokens: { + 'furn.button': { root: { backgroundColor: '#112233' }, content: { color: '#334455' }, icon: { width: 30, height: 31 } }, + }, + }); + const component = await render( + +