Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 23 additions & 23 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/theme/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
### Internal

- Collapse the `tsconfig.src.json`/`tsconfig.bin.json`/`tsconfig.test.json` projects into the repository-standard split of `tsconfig.build.json` and a default dev `tsconfig.json`. ([#81509](https://github.com/WordPress/gutenberg/pull/81509))
- Update Terrazzo packages to 2.5.0, use its resolver for mode overrides, and restore token linting with semantic WCAG AA contrast checks ([#81082](https://github.com/WordPress/gutenberg/pull/81082)).

### Bug Fixes

Expand Down
13 changes: 1 addition & 12 deletions packages/theme/bin/build-design-tokens/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,13 @@ const sources = await Promise.all(
);

const {
tokens: parsedTokens,
tokens,
sources: parsedSources,
resolver,
} = await parse( sources, {
config,
skipLint: true,

@ciampo ciampo Aug 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I couldn't find a good reason why we should skip those (recommended) checks, and so I re-enabled them. Only the naming-convention warning is disabled to preserve the existing generated token identifiers (since they use camelCase naming).

} );

// Temporary workaround for Terrazzo bug where `alphabetize: false` leaves token
// map keys in JSON Pointer form (e.g. `#/foo/bar`) while `aliasOf` references
// remain dot-delimited (e.g. `foo.bar`), breaking alias lookups. Transforms the
// map keys using the already-normalized `token.id`.
//
// See: https://github.com/terrazzoapp/terrazzo/issues/734
const tokens = Object.fromEntries(
Object.values( parsedTokens ).map( ( token ) => [ token.id, token ] )
);

Comment on lines -23 to -32

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue is fixed upstream, we can remove the workaround

const { outputFiles } = await build( tokens, {
sources: parsedSources,
config,
Expand Down
210 changes: 67 additions & 143 deletions packages/theme/bin/terrazzo-plugin-mode-overrides/index.ts

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes in this file are to use the new partial-resolver API for mode overrides (see terrazzoapp/terrazzo#762)

Original file line number Diff line number Diff line change
Expand Up @@ -2,60 +2,6 @@ import { basename } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { Plugin } from '@terrazzo/parser';

type DTCGPrimitiveValue =
| string
| number
| boolean
| { value: number; unit: string }
| { r: number; g: number; b: number; a?: number };

type DTCGValue = DTCGPrimitiveValue | Record< string, DTCGPrimitiveValue >;

interface DTCGExtensions {
[ key: string ]: unknown;
mode?: Record< string, DTCGValue >;
}

/**
* @see https://tr.designtokens.org/format/
*/
interface DTCGToken {
$value: DTCGValue;
$type?: string;
$description?: string;
$extensions?: DTCGExtensions;
}

interface DTCGGroup {
$type?: string;
$description?: string;
$extensions?: DTCGExtensions;
[ key: string ]:
| DTCGToken
| DTCGGroup
| string
| DTCGExtensions
| undefined;
}

type DTCGDocument = Record< string, DTCGGroup >;

interface ModeOverride {
path: string[];
$value: DTCGValue;
$type?: string;
}

/**
* Type guard to check if a value is a DTCG token (has $value).
*
* @param value - The value to check.
* @return True if the value is a DTCG token.
*/
function isDTCGToken( value: DTCGToken | DTCGGroup ): value is DTCGToken {
return '$value' in value;
}

/**
* Set a nested value in an object from a path array.
*
Expand All @@ -66,7 +12,7 @@ function isDTCGToken( value: DTCGToken | DTCGGroup ): value is DTCGToken {
function setNestedValue(
object: Record< string, unknown >,
pathParts: string[],
value: any
value: unknown
): void {
let current = object;

Expand All @@ -84,108 +30,85 @@ function setNestedValue(
}

/**
* Recursively extracts mode overrides from a DTCG token tree.
* Terrazzo plugin that generates mode-specific DTCG override files.
*
* @param object - The DTCG group to extract from.
* @param currentPath - The current path in the token tree.
* @param currentType - The $type inherited from parent groups.
* @return A map of mode names to their token overrides.
* @return A Terrazzo plugin that generates mode-specific DTCG override files.
*/
function getModeOverrides(
object: DTCGGroup,
currentPath: string[] = [],
currentType?: string
): Map< string, ModeOverride[] > {
const modeOverrides = new Map< string, ModeOverride[] >();

// Check if this group defines a $type that should be inherited by children
const groupType = object.$type ?? currentType;

for ( const [ key, value ] of Object.entries( object ) ) {
// Skip DTCG metadata keys
if ( key.startsWith( '$' ) ) {
continue;
}
export default function pluginModeOverrides(): Plugin {
const sourceByToken = new Map< string, string >();

const node = value as DTCGToken | DTCGGroup;

if ( isDTCGToken( node ) ) {
// Extract mode-specific values from extensions
const modes = node.$extensions?.mode;
if ( modes ) {
for ( const [ mode, modeValue ] of Object.entries( modes ) ) {
modeOverrides.set( mode, [
...( modeOverrides.get( mode ) ?? [] ),
{
path: [ ...currentPath, key ],
$value: modeValue,
$type: node.$type ?? groupType,
},
] );
return {
name: '@wordpress/terrazzo-plugin-mode-overrides',
enforce: 'pre',
async transform( { tokens } ) {
sourceByToken.clear();
for ( const [ id, token ] of Object.entries( tokens ) ) {
const { filename } = token.source;

if ( filename ) {
sourceByToken.set( id, filename );
}
}
} else {
// Recurse into nested groups, passing down the type
const nextPath = [ ...currentPath, key ];
const childOverrides = getModeOverrides(
node,
nextPath,
groupType
);
},
async build( { outputFile, resolver } ) {
const permutations = resolver.listPermutations?.();

// Merge child results
for ( const [ mode, overrides ] of childOverrides ) {
modeOverrides.set( mode, [
...( modeOverrides.get( mode ) ?? [] ),
...overrides,
] );
if ( ! permutations ) {
throw new Error(
'Could not enumerate mode permutations from the Terrazzo resolver.'
);
}
}
}

return modeOverrides;
}
const modifierNames = new Set(
permutations.flatMap( ( input ) => Object.keys( input ) )
);

/**
* Terrazzo plugin that generates mode-specific DTCG override files.
*
* For each mode found in tokens (via $extensions.mode), generates a separate
* JSON file per source file containing tokens that have values for that mode.
*
* @return A Terrazzo plugin that generates mode-specific DTCG override files.
*/
export default function pluginModeOverrides(): Plugin {
return {
name: '@wordpress/terrazzo-plugin-mode-overrides',
async build( { outputFile, sources } ) {
for ( const { filename, src } of sources ) {
if ( ! filename ) {
continue;
}
if ( modifierNames.size !== 1 ) {
throw new Error(
`Expected one mode modifier, received ${ modifierNames.size }.`
);
}

// Parse the source JSON file
let document: DTCGDocument;
try {
document = JSON.parse( src ) as DTCGDocument;
} catch ( error ) {
throw new Error(
`Could not parse ${ filename }\n\n${ error }`
);
}
const [ modeModifier ] = modifierNames;

// Extract mode overrides from this file
const fileOverrides = getModeOverrides( document );
for ( const input of permutations ) {
const mode = input[ modeModifier ];

// Generate a DTCG file for each mode found in this source file
for ( const [ mode, overrides ] of fileOverrides ) {
const output: Record< string, unknown > = {};
if ( ! mode || mode === '.' ) {
continue;
}

for ( const override of overrides ) {
const { path, $value, $type } = override;
setNestedValue( output, path, { $type, $value } );
const modeTokens = resolver.apply( input, {
sets: [],
modifiers: [ modeModifier ],
resolveAliases: false,
} );
const outputs = new Map<
string,
{ filename: URL; document: Record< string, unknown > }
>();

for ( const [ id, token ] of Object.entries( modeTokens ) ) {
const sourceFilename = sourceByToken.get( id );

if ( ! sourceFilename ) {
throw new Error( `Could not find source for ${ id }.` );
}

// Output as {basename}.{mode}.json (e.g., dimension.compact.json)
const sourceUrl = new URL( sourceFilename );
const output = outputs.get( sourceUrl.href ) ?? {
filename: sourceUrl,
document: {},
};

setNestedValue( output.document, id.split( '.' ), {
$type: token.$type,
$value: token.$value,
} );
outputs.set( sourceUrl.href, output );
}

for ( const { filename, document } of outputs.values() ) {
const sourceDir = new URL( './', filename );
const outFileName = `${ basename(
filename.pathname,
Expand All @@ -195,9 +118,10 @@ export default function pluginModeOverrides(): Plugin {
`modes/${ outFileName }`,
sourceDir
);

outputFile(
fileURLToPath( outFileUrl ),
JSON.stringify( output, null, '\t' )
JSON.stringify( document, null, '\t' )
);
}
}
Expand Down
Loading
Loading