Skip to content

Feat: theme - css variable reference #263#265

Merged
github-actions[bot] merged 3 commits intomainfrom
theme-reference-api
Oct 27, 2025
Merged

Feat: theme - css variable reference #263#265
github-actions[bot] merged 3 commits intomainfrom
theme-reference-api

Conversation

@black7375
Copy link
Contributor

@black7375 black7375 commented Oct 27, 2025

Description

theme supports with reference

Related Issue

Summary by CodeRabbit

  • New Features

    • Added base usage for theme() and support for reference variables in theming system.
    • Introduced specialized token definition types for enhanced type safety in theme configurations.
    • New public API types for improved token resolution.
  • Improvements

    • Enabled stricter TypeScript type checking to catch more potential errors.
    • Enhanced token resolution system for more robust theme handling.

Additional context

Checklist

@changeset-bot
Copy link

changeset-bot bot commented Oct 27, 2025

🦋 Changeset detected

Latest commit: 6482954

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@mincho-js/css Minor
@mincho-js/react Patch
@mincho-js/vite Patch
react-babel Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@github-actions
Copy link
Contributor

Triggered from #265 by @​black7375.

Checking if we can fast forward main (7488b27) to theme-reference-api (6482954).

Target branch (main):

commit 7488b27101a6a646dfe0136966e76df4672a74d3 (HEAD -> main, origin/main)
Author: alstjr7375 <alstjr7375@daum.net>
Date:   Sat Sep 20 00:00:00 2025 +0900

    Chore: use tsgo in vscode

Pull request (theme-reference-api):

commit 6482954eb32b6a69037d45ba1f4f0da5b80a411c (pull_request/theme-reference-api)
Author: alstjr7375 <alstjr7375@daum.net>
Date:   Tue Sep 23 00:00:00 2025 +0900

    Feat: `theme` - Support `this.` type #263

It is possible to fast forward main (7488b27) to theme-reference-api (6482954). If you have write access to the target repository, you can add a comment with /fast-forward to fast forward main to theme-reference-api.

@coderabbitai
Copy link

coderabbitai bot commented Oct 27, 2025

Walkthrough

This PR introduces a two-pass token resolution system for theming in @mincho-js/css, renames the className utility to identifierName across the codebase, enables stricter TypeScript checking via noImplicitThis, and expands the theme type system with specialized token definitions and getter support for semantic references.

Changes

Cohort / File(s) Summary
Configuration & Versioning
.changeset/petite-bats-lick.md, configs/tsconfig-custom/tsconfig.base.json
Added minor version bump changeset for "@mincho-js/css" noting theme() additions; enabled noImplicitThis TypeScript compiler option for stricter type checking.
Utility Rename
packages/css/src/utils.ts, packages/css/src/css/index.ts, packages/css/src/rules/index.ts
Renamed exported utility function className to identifierName; updated all imports and usages across CSS module. No behavioral changes—symbol rename only.
Theme System Refactoring
packages/css/src/theme/index.ts
Introduced two-pass token resolution: Pass 1 (assignTokenVariables) assigns CSS variables for all tokens; Pass 2 (resolveSemanticTokens) resolves semantic token getters. Updated globalTheme and theme function signatures with new generic constraints and return types. Added internal utilities for stable CSS var creation and nested token processing.
Theme Type System Expansion
packages/css/src/theme/types.ts
Expanded ThemeValue to include getter variant { get(): TokenPrimitiveValue }; introduced TokenDefinitionBase<TokenType, TokenValue> and specialized token definition types (color, dimension, fontFamily, fontWeight, duration, cubicBezier, number); added TokenCompositeValue.resolved getter; updated ResolveTheme to remove readonly constraint; extended ResolveThemeValue to handle new token types.

Sequence Diagram(s)

sequenceDiagram
    participant User as User Code
    participant GlobalTheme as globalTheme()
    participant Pass1 as Pass 1: assignTokenVariables
    participant Pass2 as Pass 2: resolveSemanticTokens
    participant CSS as CSS Output

    User->>GlobalTheme: Input tokens + selector
    GlobalTheme->>Pass1: Process all tokens
    rect rgb(220, 240, 255)
        Note over Pass1: Assign CSS variables<br/>for each token<br/>(create placeholders for refs)
    end
    Pass1->>Pass2: Token graph complete
    rect rgb(240, 220, 255)
        Note over Pass2: Resolve semantic getters<br/>by evaluating against graph
    end
    Pass2->>CSS: Return CSS vars + resolved tokens
    CSS-->>User: [className, ResolveThemeOutput]
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • packages/css/src/theme/index.ts: Requires careful review of the two-pass token resolution logic, new internal utilities (getCSSVarByPath, setByPath, TokenProcessingContext), and type-safe token traversal patterns.
  • packages/css/src/theme/types.ts: Multiple new type definitions and unions (TokenDefinitionBase, TokenAllDefinition, specialized token definitions) plus modifications to ResolveTheme and ResolveThemeValue; verify type inference and getter semantics.
  • Public API surface changes: Updated function signatures for globalTheme and theme with new generic constraints and return types require validation of backward compatibility and type safety.
  • Utility rename propagation: While mechanical, verify all usages of classNameidentifierName are complete across test assertions and imports.

Possibly related PRs

Poem

🐰 A two-pass dance through token trees,
Semantic getters put at ease,
identifierName rings anew,
Types expand like morning dew—
Your theme now blooms with stricter rules! 🌱

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.04% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ❓ Inconclusive The pull request description is present and follows the template structure with all required sections included. However, the Description section contains only "theme supports with reference," which is too vague to adequately convey what the PR implements. The description does not explain the two-pass token resolution system, the new public API changes to globalTheme and theme functions, the purpose of the className → identifierName rename, the TypeScript config changes, or the extended type definitions. While the Related Issue section is properly filled with #263, the Additional context and Checklist sections remain empty, and the main Description section lacks the clarity and specificity needed for reviewers to understand the scope and impact of these significant changes.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Feat: theme - css variable reference #263" is directly related to the primary changes in this pull request. The substantial modifications to packages/css/src/theme/index.ts and packages/css/src/theme/types.ts implement a two-pass token resolution system that enables CSS variable references in the theme system, which aligns precisely with the title's focus. While the changeset also includes a utility rename (className → identifierName) and a TypeScript config update, the title appropriately emphasizes the main feature being introduced without requiring coverage of every detail.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch theme-reference-api

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@black7375 black7375 changed the title Feat: theme - css variable refernce #263 Feat: theme - css variable reference #263 Oct 27, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/css/src/theme/index.ts (1)

479-500: Consider logging a warning when using the color fallback.

The fallback to #000000 (line 499) for invalid color objects could silently mask configuration errors. Consider adding a console warning when this fallback is used so developers are alerted to malformed color tokens.

   // Fallback for invalid color object
+  console.warn(`Invalid color object, falling back to #000000:`, value);
   return "#000000" as CSSVarValue;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7488b27 and 6482954.

📒 Files selected for processing (7)
  • .changeset/petite-bats-lick.md (1 hunks)
  • configs/tsconfig-custom/tsconfig.base.json (1 hunks)
  • packages/css/src/css/index.ts (11 hunks)
  • packages/css/src/rules/index.ts (29 hunks)
  • packages/css/src/theme/index.ts (25 hunks)
  • packages/css/src/theme/types.ts (8 hunks)
  • packages/css/src/utils.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (4)
packages/css/src/theme/index.ts (4)
packages/css/src/theme/types.ts (3)
  • Theme (8-10)
  • ResolveTheme (154-160)
  • TokenValue (140-140)
packages/css/src/types.ts (1)
  • Resolve (1-3)
packages/transform-to-vanilla/src/types/style-rule.ts (3)
  • CSSVarValue (119-119)
  • PureCSSVarKey (117-117)
  • PureCSSVarFunction (122-124)
packages/css/src/utils.ts (3)
  • camelToKebab (31-33)
  • getVarName (20-29)
  • identifierName (5-11)
packages/css/src/rules/index.ts (2)
packages/css/src/utils.ts (1)
  • identifierName (5-11)
packages/css/src/rules/createRuntimeFn.ts (1)
  • variants (98-102)
packages/css/src/theme/types.ts (2)
packages/transform-to-vanilla/src/index.ts (2)
  • NonNullableString (8-8)
  • NonNullableString (10-10)
packages/transform-to-vanilla/src/types/style-rule.ts (1)
  • PureCSSVarFunction (122-124)
packages/css/src/css/index.ts (1)
packages/css/src/utils.ts (1)
  • identifierName (5-11)
🪛 markdownlint-cli2 (0.18.1)
.changeset/petite-bats-lick.md

5-5: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

🔇 Additional comments (16)
.changeset/petite-bats-lick.md (1)

1-6: LGTM!

The changeset correctly documents the minor version bump and describes the new theme reference feature. The markdown linter warning about line 5 using emphasis instead of a heading is a false positive—this is the standard changeset format for this repository.

packages/css/src/css/index.ts (1)

16-16: LGTM! Clean API rename from className to identifierName.

The import statement correctly updates to the renamed function, and all usages throughout the test suite have been consistently updated.

packages/css/src/utils.ts (1)

5-11: LGTM! Function renamed for better clarity.

The rename from className to identifierName is more semantically accurate since this function generates regex patterns for matching identifiers, not just class names.

packages/css/src/rules/index.ts (1)

13-13: LGTM! Import statement correctly updated.

The import and all usages throughout the file have been consistently updated to use identifierName instead of className.

packages/css/src/theme/index.ts (7)

32-70: LGTM! Well-designed public API for the new two-pass token resolution system.

The updated signatures use const generics for better type inference and ThisType to enable semantic token references via getters. This is a breaking change to the public API, but it's appropriately documented in the changeset.

The use of ThisType<ResolveThemeOutput<ThemeTokens>> is particularly elegant—it allows theme tokens with getters to reference other resolved tokens via this, enabling semantic token patterns like:

{
  color: {
    base: { blue: "#0000ff" },
    semantic: {
      get primary() { return this.color.base.blue; }
    }
  }
}

95-131: LGTM! Clear two-pass orchestration.

The algorithm cleanly separates variable assignment (Pass 1) from semantic token resolution (Pass 2). The shared TokenProcessingContext with cssVarMap ensures consistent CSS variable names across both passes.


148-267: LGTM! Comprehensive Pass 1 implementation handles all token types.

The implementation correctly:

  • Uses Object.getOwnPropertyDescriptors to detect getters vs. regular properties
  • Creates placeholder references for getters (resolved in Pass 2)
  • Handles structured token values (dimension, duration, etc.)
  • Recursively processes nested themes
  • Preserves getter semantics on TokenCompositeValue's resolved property

The TokenCompositeValue handling (lines 221-248) is particularly well done—it extracts the composed value and individual properties while preserving the getter for the resolved property in the output.


274-336: LGTM! Pass 2 correctly resolves semantic token references.

The key insight is line 294: descriptor.get.call(resolvedTokens) invokes the getter with the resolved token structure as this, allowing semantic tokens to reference other tokens' CSS variables. The computed var() reference is then stored in both vars (for CSS output) and resolvedTokens (for type-safe API).


338-413: LGTM! Comprehensive type guards correctly identify token shapes.

The isStructuredTokenValue function (lines 366-386) is particularly important—it determines whether a token's $value should be processed as a single unit vs. recursed into as a nested object. This correctly handles:

  • dimension/duration with {value, unit} structure
  • cubicBezier arrays
  • fontFamily strings/arrays
  • color objects with color space definitions

415-459: LGTM! Path utilities ensure consistent variable names and safe nested access.

The caching in getCSSVarByPath (lines 420-429) is crucial—it ensures that the same path always maps to the same CSS variable name across both passes, even though createVar() generates unique identifiers with hashes.


591-1210: LGTM! Excellent test coverage with proper hash normalization.

The test utilities (lines 610-656) elegantly solve the problem of testing hashed CSS variable names:

  • stripHash removes hash suffixes for comparison
  • normalizeVars and normalizeResolvedTokens recursively normalize the output
  • validateHashFormat ensures variables have the expected structure

The comprehensive test suite validates:

  • All primitive and structured token types
  • Nested themes and arrays
  • Semantic token references via getters
  • TokenCompositeValue with resolved getters
  • Complex mixed structures
packages/css/src/theme/types.ts (4)

1-46: LGTM! Well-structured token definition type hierarchy.

The new type structure provides:

  1. TokenDefinitionBase<TokenType, TokenValue> - Generic base for all specialized token definitions
  2. TokenAllDefinition - Union type covering all specialized token types
  3. Getter variant in ThemeValue - Enables semantic token references

This design provides excellent type safety and enables the specialized token handling in the theme resolution logic.


48-138: LGTM! Specialized token definitions follow W3C Design Tokens spec.

Each definition properly extends TokenDefinitionBase with:

  • Literal $type for discriminated union behavior
  • Correctly typed $value for each token type
  • Optional $description inherited from base

The definitions cover:

  • color - String or complex color space object
  • dimension - Numeric value with unit
  • fontFamily - String or array of font families
  • fontWeight - Numeric or named weight
  • duration - Time value with unit
  • cubicBezier - Four-number array for easing
  • number - Plain numeric value

277-329: LGTM! Comprehensive test coverage for specialized token definitions.

The test validates that each specialized token definition:

  1. Satisfies its specific interface (e.g., TokenColorDefinition)
  2. Extends the union type TokenAllDefinition

This ensures the type hierarchy is correctly structured and all definitions are properly included in the union.


154-172: Readonly removal is intentional and necessary for token construction.

Line 155 removes readonly from ResolveTheme because the resolvedTokens object must be mutable during the two-pass token resolution process:

  1. assignTokenVariables uses setByPath(resolvedTokens, currentPath, varRef) to populate the structure
  2. resolveSemanticTokens calls getters with descriptor.get.call(resolvedTokens) for token references

The object is only mutated during construction in assignTokensWithPrefix (lines 127-128) and returned as immutable in practice. No mutations were found in the codebase after the object is returned, and Object.freeze is not applied. While the theoretical risk of consumer mutations exists, the current implementation relies on TypeScript typing and usage patterns to maintain immutability semantics.

configs/tsconfig-custom/tsconfig.base.json (1)

103-103: LGTM! Enabling noImplicitThis is verified safe.

Enabling this TypeScript compiler option improves type safety by preventing implicit any type on this. The theme changes in this PR use explicit ThisType<...> annotations, which aligns well with this stricter checking. Compilation verification confirms no implicit this errors are introduced.

@black7375
Copy link
Contributor Author

/fast-forward

@github-actions
Copy link
Contributor

Triggered from #265 (comment) by @​black7375.

Trying to fast forward main (7488b27) to theme-reference-api (6482954).

Target branch (main):

commit 7488b27101a6a646dfe0136966e76df4672a74d3 (HEAD -> main, origin/main)
Author: alstjr7375 <alstjr7375@daum.net>
Date:   Sat Sep 20 00:00:00 2025 +0900

    Chore: use tsgo in vscode

Pull request (theme-reference-api):

commit 6482954eb32b6a69037d45ba1f4f0da5b80a411c (pull_request/theme-reference-api)
Author: alstjr7375 <alstjr7375@daum.net>
Date:   Tue Sep 23 00:00:00 2025 +0900

    Feat: `theme` - Support `this.` type #263

Fast forwarding main (7488b27) to theme-reference-api (6482954).

$ git push origin 6482954eb32b6a69037d45ba1f4f0da5b80a411c:main
To https://github.com/mincho-js/mincho.git
   7488b27..6482954  6482954eb32b6a69037d45ba1f4f0da5b80a411c -> main

@github-actions github-actions bot merged commit 6482954 into main Oct 27, 2025
12 checks passed
@github-actions github-actions bot deleted the theme-reference-api branch October 27, 2025 16:39
@github-actions github-actions bot mentioned this pull request Oct 27, 2025
This was referenced Nov 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant