From e6004a8f3a80e472deb02a969a385bf6152af6e2 Mon Sep 17 00:00:00 2001 From: Jason Morse <35609178+JasonVMo@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:36:22 -0800 Subject: [PATCH 1/8] Add JSON component tokens for Button and MenuButton Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .changeset/round-buttons-layer.md | 7 + .../components/references/contracts.md | 8 +- .../references/styles-and-tokens.md | 71 ++-- .../spec-contracts/check-spec-contracts.cjs | 27 +- .../spec-contracts/token-companion.cjs | 94 +++++ .../components/src/common/tokenFields.ts | 34 ++ .../components/src/components/button/SPEC.md | 24 +- .../src/components/button/button.styles.ts | 393 +++++------------- .../src/components/button/button.test.tsx | 22 + .../button/button.tokens.types.test.ts | 24 ++ .../src/components/button/button.types.ts | 5 + .../src/components/button/spec/source.json | 2 +- .../src/components/button/spec/tokens.json | 121 ++++++ .../src/components/button/spec/tokens.yaml | 135 ------ .../src/components/button/useButton.ts | 5 + .../src/components/button/useButtonStyles.ts | 59 +-- .../src/components/menu-button/SPEC.md | 24 +- .../menu-button/menu-button.styles.ts | 21 +- .../menu-button/menu-button.test.tsx | 21 + .../menu-button/menu-button.types.ts | 2 + .../components/menu-button/spec/source.json | 2 +- .../components/menu-button/spec/tokens.json | 23 + .../components/menu-button/spec/tokens.yaml | 36 -- .../components/menu-button/useMenuButton.ts | 6 + .../menu-button/useMenuButtonStyles.ts | 31 +- packages/agentic/components/tsconfig.json | 3 +- packages/agentic/design/references/styling.md | 12 + packages/agentic/design/references/theming.md | 19 +- .../design/src/flex/flexThemeReference.ts | 26 ++ .../agentic/design/src/flex/themeState.ts | 1 + .../design/src/flex/themeState.types.ts | 4 + packages/agentic/design/src/index.ts | 1 + .../src/styling/componentTokens.test.ts | 122 ++++++ .../design/src/styling/componentTokens.ts | 332 +++++++++++++++ .../src/styling/componentTokens.types.ts | 48 +++ packages/agentic/design/src/styling/index.ts | 3 + .../__snapshots__/entryPoints.test.ts.snap | 3 + .../agentic/design/src/theming/themeSource.ts | 2 + .../references/component-patterns.md | 3 + .../src/component-patterns/slot.ts | 9 + packages/framework-base/src/index.ts | 2 +- 41 files changed, 1190 insertions(+), 597 deletions(-) create mode 100644 .changeset/round-buttons-layer.md create mode 100644 packages/agentic/components/scripts/spec-contracts/token-companion.cjs create mode 100644 packages/agentic/components/src/common/tokenFields.ts create mode 100644 packages/agentic/components/src/components/button/button.tokens.types.test.ts create mode 100644 packages/agentic/components/src/components/button/spec/tokens.json delete mode 100644 packages/agentic/components/src/components/button/spec/tokens.yaml create mode 100644 packages/agentic/components/src/components/menu-button/spec/tokens.json delete mode 100644 packages/agentic/components/src/components/menu-button/spec/tokens.yaml create mode 100644 packages/agentic/design/src/styling/componentTokens.test.ts create mode 100644 packages/agentic/design/src/styling/componentTokens.ts create mode 100644 packages/agentic/design/src/styling/componentTokens.types.ts diff --git a/.changeset/round-buttons-layer.md b/.changeset/round-buttons-layer.md new file mode 100644 index 00000000000..f8a3c24ff91 --- /dev/null +++ b/.changeset/round-buttons-layer.md @@ -0,0 +1,7 @@ +--- +'@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. diff --git a/packages/agentic/components/references/contracts.md b/packages/agentic/components/references/contracts.md index f8aa2040bf0..6d18739ed91 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/styles-and-tokens.md b/packages/agentic/components/references/styles-and-tokens.md index 8d34ff0748d..e8843f9e4d4 100644 --- a/packages/agentic/components/references/styles-and-tokens.md +++ b/packages/agentic/components/references/styles-and-tokens.md @@ -27,24 +27,47 @@ 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) -Use four layers: +Button and MenuButton import `spec/tokens.json` in their module-scoped `defineComponentTokens` calls. The ordered typed +axis tuple must match the JSON axes. Each slot contains flat React Native style keys and reviewed prop settings: -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. +```json +{ + "borderWidth": "tokens:strokeWidth.thin", + "when.size.medium": { + "paddingHorizontal": "tokens:spacing.componentBase250", + "when.iconOnly.true": { "paddingHorizontal": "tokens:spacing.componentBase150" } + } +} +``` + +`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. + +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. -Never create a style factory inside a hook or render function. +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. + +## 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 +79,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 +88,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 +100,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 +120,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/spec-contracts/check-spec-contracts.cjs b/packages/agentic/components/scripts/spec-contracts/check-spec-contracts.cjs index 40976ca9efe..499114d1ea5 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 00000000000..6b02c8e3c6c --- /dev/null +++ b/packages/agentic/components/scripts/spec-contracts/token-companion.cjs @@ -0,0 +1,94 @@ +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(); + 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('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); + } +} + +module.exports = { validateTokenCompanion }; diff --git a/packages/agentic/components/src/common/tokenFields.ts b/packages/agentic/components/src/common/tokenFields.ts new file mode 100644 index 00000000000..789a1d8d7b4 --- /dev/null +++ b/packages/agentic/components/src/common/tokenFields.ts @@ -0,0 +1,34 @@ +import type { ColorValue, DimensionValue } from 'react-native'; + +export function numericToken(value: unknown): number { + if (typeof value !== 'number' || !Number.isFinite(value)) throw new TypeError('expected a finite number'); + return value; +} + +export function stringToken(value: unknown): string { + if (typeof value !== 'string') throw new TypeError('expected a string'); + return value; +} + +export function dimensionToken(value: unknown): DimensionValue { + if (typeof value === 'string') { + if (value === 'auto' || (value.endsWith('%') && value.length > 1 && Number.isFinite(Number(value.slice(0, -1))))) { + return value as 'auto' | `${number}%`; + } + } + return numericToken(value); +} + +export function colorToken(value: unknown): ColorValue { + if (typeof value === 'string' || (typeof value === 'object' && value !== null && !Array.isArray(value))) return value as ColorValue; + throw new TypeError('expected a React Native color'); +} + +export function enumToken(...values: T) { + return (value: unknown): T[number] => { + if ((typeof value === 'string' || typeof value === 'number') && values.includes(value)) return value; + throw new TypeError(`expected ${values.join(', ')}`); + }; +} + +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 54207440e6a..36471850ff8 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 623640d3e9a..5f4fa8e4b00 100644 --- a/packages/agentic/components/src/components/button/button.styles.ts +++ b/packages/agentic/components/src/components/button/button.styles.ts @@ -1,308 +1,117 @@ -import { StyleSheet } from 'react-native'; import type { TextStyle, ViewStyle } from 'react-native'; +import { defineComponentTokens, getGapStyleValue, resolveTokenStates } from '@fluentui-react-native/design/styling'; +import type { CompiledComponentTokens, ComponentTokenPatch, TokenState } from '@fluentui-react-native/design/styling'; +import { colorToken, dimensionToken, enumToken, iconTokenProps, numericToken, stringToken } from '../../common/tokenFields'; +import type { IconElementProps } from '../../primitives/icon/icon.types'; +import type { ButtonState } from './button.types'; +import schema from './spec/tokens.json' with { type: 'json' }; + +export const buttonSizeAxis = ['size', ['small', 'medium', 'large']] as const; +const buttonTokenAxes = [ + buttonSizeAxis, + ['shape', ['rounded', 'square', 'circle']], + ['iconOnly', [false, true]], + ['appearance', ['primary', 'secondary', 'outline', 'subtle']], + ['selected', [false, true]], + ['visualState', ['rest', 'hovered', 'pressed', 'disabled']], +] as const; -import type { FlexTokens } from '@fluentui-react-native/design'; -import { - getGapStyleValue, - getThemedColorStyleFactory, - getThemedStateStyleFactory, - interactiveStatePriority, -} from '@fluentui-react-native/design/styling'; -import type { - ColorStyleDefinition, - StateNames, - StyleDefinition, - TextColorStyle, - ViewColorStyle, -} from '@fluentui-react-native/design/styling'; -import { cornerRadiusNone, size160, size200, size240 } from '@fluentui-react-native/design/tokens/global'; - -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: enumToken('flex-start', 'flex-end', 'center', 'stretch', 'baseline'), + alignSelf: enumToken('auto', 'flex-start', 'flex-end', 'center', 'stretch', 'baseline'), + borderStyle: enumToken('solid', 'dotted', 'dashed'), + flexDirection: enumToken('row', 'column', 'row-reverse', 'column-reverse'), + justifyContent: enumToken('flex-start', 'flex-end', 'center', 'space-between', 'space-around', 'space-evenly'), + 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', - }, - }, + style: { + flexShrink: numericToken, + textAlign: enumToken('auto', 'left', 'right', 'center', 'justify'), + fontFamily: stringToken, + fontSize: numericToken, + lineHeight: numericToken, + fontWeight: enumToken( + 'normal', + 'bold', + '100', + '200', + '300', + '400', + '500', + '600', + '700', + '800', + '900', + 100, + 200, + 300, + 400, + 500, + 600, + 700, + 800, + 900, + 'ultralight', + 'thin', + 'light', + 'regular', + 'medium', + 'semibold', + 'condensedBold', + 'condensed', + 'heavy', + 'black', + ), + color: colorToken, + }, + props: {}, }, + icon: { style: {}, props: iconTokenProps }, }; -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', - }, - }, -}; - -const getThemedBackgroundStyle = getThemedColorStyleFactory( - 'Button.background', - backgroundColorDefinition, - colorStateLevels, -); -const getThemedForegroundStyle = getThemedColorStyleFactory( - 'Button.foreground', - foregroundColorDefinition, - colorStateLevels, -); +type ButtonAxes = typeof buttonTokenAxes; +type ButtonDomains = typeof buttonTokenDomains; +type ButtonTokenState = TokenState; +export type ButtonTokens = CompiledComponentTokens; -function getColorStateSource(state: ButtonState): ColorState[] { - const source: ColorState[] = [state.appearance]; - if (state.selected) { - source.push('selected'); - } - if (state.disabled) { - source.push('disabled'); +declare module '@fluentui-react-native/design' { + interface ComponentTokenRegistry { + 'furn.button': ComponentTokenPatch; } - 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', + axes: buttonTokenAxes, + 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 c55776efd45..8ff50cbac26 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( + +