AI-native design editor. Open-source Figma alternative.
feat: let a collection name the attribute its modes switch by (#913)
Danila Poyarkov6c6f24409e27
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f5093023e..3ba906660 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -41,7 +41,7 @@- Fix lint issues outside the app: `openpencil lint --fix -o fixed.fig` binds colors to the variable they match and rounds subpixel geometry, and the `lint` and `lint_fix` tools let MCP clients and AI chat check a page and apply those fixes, plus radius, spacing, text size, group-to-frame, and hidden-layer suggestions on request. Lint messages carry each fix as data in `fix` and `suggestions`.- Mark layers with errors and warnings on the canvas while you work, and pin those outside the view to the canvas edge in their direction, with matching marks in the Layers panel and error and warning counts in the page list; hover a marker or pin for its issues or click it to open them in Lint, and turn markers on or off with View → Design issues.- Copy the document's variables as a CSS stylesheet or a Tailwind v4 theme from the variables dialog, or print them with `openpencil tokens`. Each collection's default mode goes in `:root` (or `@theme`, with a `@custom-variant` per mode), other modes override under their condition, `[data-theme="dark"]` unless the mode names a selector or `@media` query, and aliases stay `var()` references that follow the mode. Variables CSS cannot express, such as booleans, are named instead of written.-- Edit variables as design tokens in the redesigned variables dialog, opened from View → Variables…, the command palette, or the Design panel, and expandable to most of the window. Collections and the groups inside them are listed in a sidebar with counts; picking a group, a type filter, or a search, which matches names, CSS names, descriptions, and values with the command palette's typo-tolerant matching, narrows the list, which shows each variable's type, CSS name, and a value per mode. Names and number or text values edit in place, rows reorder by dragging, and Shift- or Cmd-clicking selects several to duplicate, move into a group, or delete from the context menu, the Delete key, or the side panel. Selecting one edits its name, CSS name (checked against CSS before it is saved), unit, per-mode values or CSS expressions such as `clamp()`, scopes, description, and publishing, and points a value at another variable of the same type or detaches it again. The collection settings rename and delete the collection, add, rename, duplicate, delete, and choose the default mode, and choose when each mode applies in plain words, such as *System is in dark mode* or *Screen is narrower than 640px*, with the CSS it writes shown underneath and a custom selector or `@media`, `@supports`, or `@container` query when no preset fits. The active collection's stylesheet updates live below the list, and copying offers CSS or a Tailwind v4 theme. Undo and redo work in the dialog as they do on the canvas, with one step per change and one per color picker session, while a field with uncommitted text keeps its own undo. The dialog lays out by its own width: in a narrow window or on a phone it shows one mode at a time and opens a variable, the collection settings, or the stylesheet over the list.+- Edit variables as design tokens in the redesigned variables dialog, opened from View → Variables…, the command palette, or the Design panel, and expandable to most of the window. Collections and the groups inside them are listed in a sidebar with counts; picking a group, a type filter, or a search, which matches names, CSS names, descriptions, and values with the command palette's typo-tolerant matching, narrows the list, which shows each variable's type, CSS name, and a value per mode. Names and number or text values edit in place, rows reorder by dragging, and Shift- or Cmd-clicking selects several to duplicate, move into a group, or delete from the context menu, the Delete key, or the side panel. Selecting one edits its name, CSS name (checked against CSS before it is saved), unit, per-mode values or CSS expressions such as `clamp()`, scopes, description, and publishing, and points a value at another variable of the same type or detaches it again. The collection settings rename and delete the collection, add, rename, duplicate, delete, and choose the default mode, and choose when each mode applies in plain words, such as *System is in dark mode* or *Screen is narrower than 640px*, with the CSS it writes shown underneath and a custom selector or `@media`, `@supports`, or `@container` query when no preset fits. Manually switched modes use an attribute named after the collection, such as `data-theme`, or one the collection names to match an existing codebase; it is saved in `.fig` files and used by exported code. The active collection's stylesheet updates live below the list, and copying offers CSS or a Tailwind v4 theme. Undo and redo work in the dialog as they do on the canvas, with one step per change and one per color picker session, while a field with uncommitted text keeps its own undo. The dialog lays out by its own width: in a narrow window or on a phone it shows one mode at a time and opens a variable, the collection settings, or the stylesheet over the list.- Follow collaborators and their AI agents from the avatars in the toolbar: an avatar counts that person's agents, hovering lists what each is doing and on which page, and clicking follows. A frame in their color and a “Following …” bar show whom you follow; Escape, clicking, scrolling, zooming, or switching pages stops it. Your own avatar renames your agents and leaves the room.- See where the built-in AI chat is working: while it replies, a cursor whose outlined label shows a sparkle and a callsign such as *Fern* marks the layers it edits. In a shared room, collaborators see each other's agents in the color of the person running them.- See which pages people and AI agents are working on: the Pages panel marks those pages in their colors and, on hover, shows who is there with what their agents are doing and a button to follow them; the command palette names who is there, and the chat offers **Go to page** while its reply works on a page you're not viewing. On phones, the room pill shows the people in the room as avatars beside the room's status.diff --git a/packages/core/src/editor/variables.ts b/packages/core/src/editor/variables.tsindex e6f79317e..e08cc91c5 100644--- a/packages/core/src/editor/variables.ts+++ b/packages/core/src/editor/variables.ts@@ -1,12 +1,13 @@import { omit, omitBy } from 'es-toolkit/object'import { isEmptyObject } from 'es-toolkit/predicate'-import type {- TokenExpression,- Variable,- VariableCollection,- VariableType,- VariableValue+import {+ isModeAttributeName,+ type TokenExpression,+ type Variable,+ type VariableCollection,+ type VariableType,+ type VariableValue} from '@open-pencil/scene-graph'import { reconcileVariableLayouts } from '#core/layout/variables'@@ -505,11 +506,35 @@ export function createVariableActions(ctx: EditorContext) {})}+ /**+ * Name the attribute manual modes are switched by; an empty name restores the default, and a+ * name no stylesheet can select on leaves the current one.+ */+ function setModeAttribute(collectionId: string, name: string | undefined) {+ const collection = ctx.graph.variableCollections.get(collectionId)+ if (!collection) return+ const previous = collection.modeAttribute+ const next = name?.trim() || undefined+ if (next === previous || (next !== undefined && !isModeAttributeName(next))) return+ const apply = (value: string | undefined) => {+ const target = ctx.graph.variableCollections.get(collectionId)+ if (target) target.modeAttribute = value+ ctx.requestRender()+ }+ apply(next)+ ctx.undo.push({+ label: 'Set mode attribute',+ forward: () => apply(next),+ inverse: () => apply(previous)+ })+ }+return {updateVariableToken,setModeCondition,duplicateVariable,setVariableOrder,+ setModeAttribute,getVariablesByType,getVariable,resolveColorVariable,diff --git a/packages/core/tests/editor/undo/variable/tokens.test.ts b/packages/core/tests/editor/undo/variable/tokens.test.tsindex 5eaabf9e2..b54f8298d 100644--- a/packages/core/tests/editor/undo/variable/tokens.test.ts+++ b/packages/core/tests/editor/undo/variable/tokens.test.ts@@ -175,4 +175,23 @@ describe('variable token undo', () => {editor.undo.undo()expect(gutter()?.expressions).toEqual({ light: { css: clamp, resolved: 24 } })})++ test('the mode attribute is set, ignored when invalid, cleared, and undone', () => {+ const editor = themeEditor()+ const attribute = () => editor.graph.variableCollections.get('theme')?.modeAttribute++ editor.setModeAttribute('theme', ' data-scheme ')+ expect(attribute()).toBe('data-scheme')++ editor.setModeAttribute('theme', 'data scheme"]')+ expect(attribute()).toBe('data-scheme')++ editor.setModeAttribute('theme', ' ')+ expect(attribute()).toBeUndefined()++ editor.undo.undo()+ expect(attribute()).toBe('data-scheme')+ editor.undo.undo()+ expect(attribute()).toBeUndefined()+ })})diff --git a/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts b/packages/core/tests/io/formats/fig/roundtrip/variables.test.tsindex b2a2eb64a..e1758a5b4 100644--- a/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts+++ b/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts@@ -316,7 +316,8 @@ describe('variable roundtrip', () => {{ modeId: '4:8', name: 'Dark', condition: '[data-theme="dark"]' }],defaultModeId: '4:7',- variableIds: []+ variableIds: [],+ modeAttribute: 'data-scheme'})const add = (id: string, name: string, extra: Partial<Variable>) =>graph.addVariable({@@ -347,6 +348,8 @@ describe('variable roundtrip', () => {{ modeId: '4:7', name: 'Light', condition: undefined },{ modeId: '4:8', name: 'Dark', condition: '[data-theme="dark"]' }])+ expect(reimported.variableCollections.get('4:70')?.modeAttribute).toBe('data-scheme')+ expect(reimported.variableCollections.get('4:70')?.pluginData).toBeUndefined()// Rebuilt on save, never duplicated into pass-through plugin data.expect(page.pluginData).toBeUndefined()})diff --git a/packages/docs/de/user-guide/variables.md b/packages/docs/de/user-guide/variables.mdindex 891905682..b0cefc722 100644--- a/packages/docs/de/user-guide/variables.md+++ b/packages/docs/de/user-guide/variables.md@@ -20,6 +20,7 @@ Variablen sind in Sammlungen organisiert. In einem breiten Dialog stehen sie in- **Sammlung wechseln:** in der Seitenleiste oder auf der Registerkarte darauf klicken- **Sammlung erstellen:** neben **Sammlungen** auf **+** oder in der Werkzeugleiste auf die Ordner-Schaltfläche (**Sammlung erstellen**) klicken- **Umbenennen oder löschen:** Ist keine Variable ausgewählt, bearbeitet die rechte Seite die Sammlung: Dort lässt sich der Name ändern oder die Sammlung über das Menü **⋯** neben dem Namen löschen (**Sammlung löschen**)+- **Umschalt-Attribut:** das Attribut, das manuell umgeschaltete Modi aktiviert, standardmäßig `data-theme` für eine Sammlung namens Theme; ein anderer Name wie `data-color-scheme` passt es an eine bestehende Codebasis an## Modi@@ -33,7 +34,7 @@ Der Standardmodus ist **Immer aktiv** und steht in `:root`. Jeder andere Modus h| Gilt wenn | CSS || --- | --- |-| **manuell umgeschaltet wird** | ein Attribut, das nach Sammlung und Modus benannt ist, etwa `[data-theme="dark"]` für den Modus Dunkel einer Sammlung Theme |+| **manuell umgeschaltet wird** | das Umschalt-Attribut der Sammlung mit dem Modus als Wert, etwa `[data-theme="dark"]` für den Modus Dunkel einer Sammlung Theme || **das System im Dunkelmodus ist** / **das System im Hellmodus ist** | `@media (prefers-color-scheme: dark)` / `light` || **hoher Kontrast aktiv ist** | `@media (prefers-contrast: more)` || **reduzierte Bewegung aktiv ist** | `@media (prefers-reduced-motion: reduce)` |diff --git a/packages/docs/es/user-guide/variables.md b/packages/docs/es/user-guide/variables.mdindex 8ac71b4ef..107e36681 100644--- a/packages/docs/es/user-guide/variables.md+++ b/packages/docs/es/user-guide/variables.md@@ -20,6 +20,7 @@ Las variables se organizan en colecciones. En un diálogo ancho aparecen en una- **Cambiar de colección:** haz clic en ella en la barra lateral o en su pestaña- **Crear una colección:** haz clic en **+** junto a **Colecciones** o en el botón de carpeta de la barra de herramientas (**Crear colección**)- **Renombrar o eliminar:** sin ninguna variable seleccionada, la parte derecha edita la colección: cambia su nombre o elimínala desde el menú **⋯** junto al nombre (**Eliminar colección**)+- **Atributo de cambio:** el atributo que activa los modos que se cambian manualmente, `data-theme` por defecto para una colección llamada Theme; escribe otro nombre, como `data-color-scheme`, para adaptarlo a un código existente## Modos@@ -33,7 +34,7 @@ El modo predeterminado es **Siempre activo** y va en `:root`. Todos los demás m| Se aplica cuando | CSS || --- | --- |-| **se cambia manualmente** | un atributo con el nombre de la colección y del modo, como `[data-theme="dark"]` para el modo Oscuro de una colección Theme |+| **se cambia manualmente** | el atributo de cambio de la colección con el modo como valor, como `[data-theme="dark"]` para el modo Oscuro de una colección Theme || **el sistema está en modo oscuro** / **el sistema está en modo claro** | `@media (prefers-color-scheme: dark)` / `light` || **el contraste alto está activado** | `@media (prefers-contrast: more)` || **la reducción de movimiento está activada** | `@media (prefers-reduced-motion: reduce)` |diff --git a/packages/docs/fr/user-guide/variables.md b/packages/docs/fr/user-guide/variables.mdindex 42d140af8..85539ef8a 100644--- a/packages/docs/fr/user-guide/variables.md+++ b/packages/docs/fr/user-guide/variables.md@@ -20,6 +20,7 @@ Les variables sont organisées en collections. Dans une boîte de dialogue large- **Changer de collection :** cliquez dessus dans la barre latérale ou sur son onglet- **Créer une collection :** cliquez sur **+** à côté de **Collections**, ou sur le bouton en forme de dossier dans la barre d’outils (**Créer une collection**)- **Renommer ou supprimer :** sans variable sélectionnée, la partie droite modifie la collection : changez son nom, ou supprimez-la depuis le menu **⋯** à côté du nom (**Supprimer la collection**)+- **Attribut de bascule :** l’attribut qui active les modes activés manuellement, `data-theme` par défaut pour une collection nommée Theme ; saisissez un autre nom, comme `data-color-scheme`, pour correspondre à un code existant## Modes@@ -33,7 +34,7 @@ Le mode par défaut est **Toujours actif** et va dans `:root`. Chaque autre mode| S’applique quand | CSS || --- | --- |-| **il est activé manuellement** | un attribut nommé d’après la collection et le mode, comme `[data-theme="dark"]` pour le mode Sombre d’une collection Theme |+| **il est activé manuellement** | l’attribut de bascule de la collection avec le mode pour valeur, comme `[data-theme="dark"]` pour le mode Sombre d’une collection Theme || **le système est en mode sombre** / **le système est en mode clair** | `@media (prefers-color-scheme: dark)` / `light` || **le contraste élevé est activé** | `@media (prefers-contrast: more)` || **la réduction des animations est activée** | `@media (prefers-reduced-motion: reduce)` |diff --git a/packages/docs/it/user-guide/variables.md b/packages/docs/it/user-guide/variables.mdindex 96dda5a0f..d62c90c4a 100644--- a/packages/docs/it/user-guide/variables.md+++ b/packages/docs/it/user-guide/variables.md@@ -20,6 +20,7 @@ Le variabili sono organizzate in raccolte. In una finestra larga sono elencate i- **Cambiare raccolta:** fai clic su di essa nella barra laterale o sulla sua scheda- **Creare una raccolta:** fai clic su **+** accanto a **Raccolte**, oppure sul pulsante a forma di cartella nella barra degli strumenti (**Crea raccolta**)- **Rinominare o eliminare:** senza alcuna variabile selezionata, la parte destra modifica la raccolta: cambia il nome, oppure eliminala dal menu **⋯** accanto al nome (**Elimina raccolta**)+- **Attributo di attivazione:** l’attributo che attiva le modalità attivate manualmente, `data-theme` per impostazione predefinita per una raccolta chiamata Theme; scrivi un altro nome, come `data-color-scheme`, per adattarlo a un codice esistente## Modalità@@ -33,7 +34,7 @@ La modalità predefinita è **Sempre attivo** e va in `:root`. Ogni altra modali| Si applica quando | CSS || --- | --- |-| **viene attivata manualmente** | un attributo che prende il nome dalla raccolta e dalla modalità, come `[data-theme="dark"]` per la modalità Scuro di una raccolta Theme |+| **viene attivata manualmente** | l’attributo di attivazione della raccolta con la modalità come valore, come `[data-theme="dark"]` per la modalità Scuro di una raccolta Theme || **il sistema è in modalità scura** / **il sistema è in modalità chiara** | `@media (prefers-color-scheme: dark)` / `light` || **il contrasto elevato è attivo** | `@media (prefers-contrast: more)` || **la riduzione del movimento è attiva** | `@media (prefers-reduced-motion: reduce)` |diff --git a/packages/docs/pl/user-guide/variables.md b/packages/docs/pl/user-guide/variables.mdindex 9b420a6e2..e2511646f 100644--- a/packages/docs/pl/user-guide/variables.md+++ b/packages/docs/pl/user-guide/variables.md@@ -20,6 +20,7 @@ Zmienne są łączone w kolekcje. W szerokim oknie są wypisane na pasku bocznym- **Przejście do kolekcji:** kliknij ją na pasku bocznym lub jej kartę- **Tworzenie kolekcji:** kliknij **+** obok **Kolekcje** albo przycisk z folderem na pasku narzędzi (**Utwórz kolekcję**)- **Zmiana nazwy lub usuwanie:** gdy żadna zmienna nie jest zaznaczona, prawa strona edytuje kolekcję: zmień jej nazwę albo usuń ją z menu **⋯** obok nazwy (**Usuń kolekcję**)+- **Atrybut przełączania:** atrybut, który włącza tryby przełączane ręcznie, domyślnie `data-theme` dla kolekcji o nazwie Theme; wpisz inną nazwę, np. `data-color-scheme`, aby dopasować go do istniejącego kodu## Tryby@@ -33,7 +34,7 @@ Tryb domyślny jest **Zawsze włączony** i trafia do `:root`. Każdy inny tryb| Obowiązuje, gdy | CSS || --- | --- |-| **przełączono ręcznie** | atrybut nazwany od kolekcji i trybu, na przykład `[data-theme="dark"]` dla trybu Dark kolekcji Theme |+| **przełączono ręcznie** | atrybut przełączania kolekcji z trybem jako wartością, na przykład `[data-theme="dark"]` dla trybu Dark kolekcji Theme || **system jest w trybie ciemnym** / **system jest w trybie jasnym** | `@media (prefers-color-scheme: dark)` / `light` || **włączony jest wysoki kontrast** | `@media (prefers-contrast: more)` || **włączone jest ograniczenie ruchu** | `@media (prefers-reduced-motion: reduce)` |diff --git a/packages/docs/ru/user-guide/variables.md b/packages/docs/ru/user-guide/variables.mdindex fb60a22f2..ff6d27d7e 100644--- a/packages/docs/ru/user-guide/variables.md+++ b/packages/docs/ru/user-guide/variables.md@@ -20,6 +20,7 @@ description: Переменные дизайна, коллекции, режим- **Переключить коллекцию:** щёлкните её на боковой панели или её вкладку- **Создать коллекцию:** нажмите **+** рядом с **Коллекции** или кнопку с папкой на панели инструментов (**Создать коллекцию**)- **Переименовать или удалить:** если переменная не выбрана, справа редактируется коллекция: измените её имя или удалите её через меню **⋯** рядом с именем (**Удалить коллекцию**)+- **Атрибут переключения:** атрибут, который включает режимы, переключаемые вручную, по умолчанию `data-theme` для коллекции Theme; укажите другое имя, например `data-color-scheme`, чтобы оно совпадало с существующим кодом## Режимы@@ -33,7 +34,7 @@ description: Переменные дизайна, коллекции, режим| Применяется, когда | CSS || --- | --- |-| **переключено вручную** | атрибут, названный по коллекции и режиму, например `[data-theme="dark"]` для режима Dark коллекции Theme |+| **переключено вручную** | атрибут переключения коллекции со значением режима, например `[data-theme="dark"]` для режима Dark коллекции Theme || **система в тёмном режиме** / **система в светлом режиме** | `@media (prefers-color-scheme: dark)` / `light` || **включён высокий контраст** | `@media (prefers-contrast: more)` || **включено уменьшение движения** | `@media (prefers-reduced-motion: reduce)` |diff --git a/packages/docs/user-guide/variables.md b/packages/docs/user-guide/variables.mdindex 667e635f3..392711ea3 100644--- a/packages/docs/user-guide/variables.md+++ b/packages/docs/user-guide/variables.md@@ -20,6 +20,7 @@ Variables are organized into collections. In a wide dialog they are listed in a- **Switch collection** — click it in the sidebar or its tab- **Create collection** — click **+** next to Collections, or the folder button in the toolbar- **Rename or delete** — with no variable selected, the right side edits the collection: change its name, or delete it from the **⋯** menu next to the name+- **Switch attribute** — the attribute that turns manually switched modes on, `data-theme` by default for a collection named Theme; type another name, such as `data-color-scheme`, to match an existing codebase## Modes@@ -33,7 +34,7 @@ The default mode is **Always on** and goes in `:root`. Every other mode has **Ap| Applies when | CSS || --- | --- |-| **Switched manually** | an attribute named after the collection and mode, such as `[data-theme="dark"]` for a Theme collection's Dark mode |+| **Switched manually** | the collection's switch attribute set to the mode, such as `[data-theme="dark"]` for a Theme collection's Dark mode || **System is in dark mode** / **System is in light mode** | `@media (prefers-color-scheme: dark)` / `light` || **High contrast is on** | `@media (prefers-contrast: more)` || **Reduced motion is on** | `@media (prefers-reduced-motion: reduce)` |diff --git a/packages/dom-css/src/tokens/index.ts b/packages/dom-css/src/tokens/index.tsindex 7c7aaade8..93969ab3e 100644--- a/packages/dom-css/src/tokens/index.ts+++ b/packages/dom-css/src/tokens/index.ts@@ -12,6 +12,7 @@ export {} from './names'export {buildTokenStylesheet,+ defaultModeAttributeName,defaultModeCondition,loadTokenValidator,modeAttribute,diff --git a/packages/dom-css/src/tokens/stylesheet.ts b/packages/dom-css/src/tokens/stylesheet.tsindex fa86cbfe4..9f4f0a4ab 100644--- a/packages/dom-css/src/tokens/stylesheet.ts+++ b/packages/dom-css/src/tokens/stylesheet.ts@@ -66,12 +66,20 @@ function modeSlug(collection: VariableCollection, mode: VariableCollectionMode):return plainSlug(mode)}+/** The attribute a collection's manual modes are switched by, unless it names its own. */+export function defaultModeAttributeName(collection: VariableCollection): string {+ return `data-${tokenSlug(collection.name) || 'mode'}`+}+/** The attribute that puts an element in a mode with no condition of its own: `data-theme`. */export function modeAttribute(collection: VariableCollection,mode: VariableCollectionMode): { name: string; value: string } {- return { name: `data-${tokenSlug(collection.name) || 'mode'}`, value: modeSlug(collection, mode) }+ return {+ name: collection.modeAttribute ?? defaultModeAttributeName(collection),+ value: modeSlug(collection, mode)+ }}/** The scope a mode applies in when it names none: `[data-theme="dark"]` for Theme / Dark. */diff --git a/packages/dom-css/tests/export/projection/tokens.test.ts b/packages/dom-css/tests/export/projection/tokens.test.tsindex 5eff8cca2..a3e9fd289 100644--- a/packages/dom-css/tests/export/projection/tokens.test.ts+++ b/packages/dom-css/tests/export/projection/tokens.test.ts@@ -59,6 +59,19 @@ describe('token references in design-to-code', () => {expect(inner.inlineStyle?.['background-color']).toBe('var(--color-primary)')})+ test('puts a node in its mode with the attribute its collection names', () => {+ const graph = designSystem()+ const theme = graph.variableCollections.get('theme')+ if (theme) theme.modeAttribute = 'data-scheme'+ const outer = card(graph, graph.getPages()[0].id, BLUE_500)+ card(graph, outer.id, BLUE_300, { variableModes: { theme: 'dark' } })++ const inner = child(element(graph, outer.id))++ expect(inner.attrs['data-scheme']).toBe('dark')+ expect(inner.attrs).not.toHaveProperty('data-theme')+ })+test('keeps literals where no attribute can bring back the mode the node is in', () => {const graph = designSystem()const outer = card(graph, graph.getPages()[0].id, BLUE_300, {diff --git a/packages/dom-css/tests/tokens/stylesheet.test.ts b/packages/dom-css/tests/tokens/stylesheet.test.tsindex 0a0f38982..6f097b7b9 100644--- a/packages/dom-css/tests/tokens/stylesheet.test.ts+++ b/packages/dom-css/tests/tokens/stylesheet.test.ts@@ -125,6 +125,17 @@ describe('token stylesheet', () => {)})+ test('switches manual modes by the attribute the collection names', async () => {+ const graph = designSystem()+ const theme = graph.variableCollections.get('theme')+ if (theme) theme.modeAttribute = 'data-scheme'++ const { css } = await tokenStylesheet(graph, { format: 'css' })++ expect(css).toContain('[data-scheme="dark"] {')+ expect(css).not.toContain('data-theme')+ })+test('declares an alias again where a mode changes what it points to', async () => {const graph = new SceneGraph()graph.addCollection({diff --git a/packages/fig/src/document/variables.ts b/packages/fig/src/document/variables.tsindex 447ac8adc..d5aa4fc52 100644--- a/packages/fig/src/document/variables.ts+++ b/packages/fig/src/document/variables.ts@@ -5,6 +5,7 @@ import type { SceneGraph, VariableValue } from '@open-pencil/scene-graph'import { extractPluginData } from '../node-change/plugin-data'import { readVariableMetadata } from '../node-change/variable/metadata'import {+ readModeAttribute,readModeConditions,readVariableToken,withoutTokenPluginData@@ -74,6 +75,7 @@ export function materializeVariableResources(}),defaultModeId: guidToString(modes[0].id),variableIds: [],+ modeAttribute: readModeAttribute(resource),pluginData: pluginData.length > 0 ? pluginData : undefined})}diff --git a/packages/fig/src/node-change/variable/metadata.ts b/packages/fig/src/node-change/variable/metadata.tsindex bdcb09171..99f899a15 100644--- a/packages/fig/src/node-change/variable/metadata.ts+++ b/packages/fig/src/node-change/variable/metadata.ts@@ -10,7 +10,12 @@ import {} from '@open-pencil/scene-graph'import { extractPluginData, mergePluginData } from '../plugin-data'-import { modeConditionsPluginData, tokenPluginData, withoutTokenPluginData } from './token'+import {+ modeAttributePluginData,+ modeConditionsPluginData,+ tokenPluginData,+ withoutTokenPluginData+} from './token'type VariableMetadata = Pick<Variable,@@ -74,9 +79,11 @@ export function collectionPluginDataNodeChange(modeKey: ModeKey): NodeChange['pluginData'] {const conditions = modeConditionsPluginData(collection, modeKey)+ const attribute = modeAttributePluginData(collection)return pluginDataNodeChange([...withoutTokenPluginData(collection.pluginData ?? []),- ...(conditions ? [conditions] : [])+ ...(conditions ? [conditions] : []),+ ...(attribute ? [attribute] : [])])}diff --git a/packages/fig/src/node-change/variable/token.ts b/packages/fig/src/node-change/variable/token.tsindex 55639cbf7..a009f6f38 100644--- a/packages/fig/src/node-change/variable/token.ts+++ b/packages/fig/src/node-change/variable/token.ts@@ -14,13 +14,13 @@ import {import { readNodeChangePluginData } from '../plugin-data'-const { token, modeConditions } = OPEN_PENCIL_PLUGIN_DATA+const { token, modeConditions, modeAttribute } = OPEN_PENCIL_PLUGIN_DATAtype TokenFields = Pick<Variable, 'unit' | 'expressions'>/** Plugin data other than the token entries, which are rebuilt on every save. */export function withoutTokenPluginData(pluginData: PluginDataEntry[]): PluginDataEntry[] {- return withoutPluginData(pluginData, [token, modeConditions])+ return withoutPluginData(pluginData, [token, modeConditions, modeAttribute])}function nonEmpty<T extends object>(record: T): T | undefined {@@ -51,6 +51,18 @@ export function readModeConditions(nc: NodeChange): Record<string, string> {return readNodeChangePluginData(nc, modeConditions) ?? {}}+export function readModeAttribute(nc: NodeChange): string | undefined {+ return readNodeChangePluginData(nc, modeAttribute)+}++export function modeAttributePluginData(+ collection: VariableCollection+): PluginDataEntry | undefined {+ return collection.modeAttribute+ ? pluginDataEntry(modeAttribute, collection.modeAttribute)+ : undefined+}+/** Mode ids in the file differ from the model's, so callers map them. */export function tokenPluginData(variable: Variable,diff --git a/packages/scene-graph/src/plugin-data/fields.ts b/packages/scene-graph/src/plugin-data/fields.tsindex 7a53c1695..7c87495a6 100644--- a/packages/scene-graph/src/plugin-data/fields.ts+++ b/packages/scene-graph/src/plugin-data/fields.ts@@ -5,6 +5,7 @@ import { isExportFormatId, type ExportFormatId } from '../export-format'import { clampExportScale } from '../export-scale'import type { Rect } from '../primitives'import {+ MODE_ATTRIBUTE_PATTERN,TOKEN_UNITS,type EnabledLibraryBinding,type ExportSetting,@@ -151,6 +152,11 @@ export const OPEN_PENCIL_PLUGIN_DATA = {token: jsonPluginDataField('token', token),/** Mode conditions by mode id, on each VARIABLE_SET. */modeConditions: jsonPluginDataField('modeConditions', v.record(v.string(), cssText)),+ /** The attribute that switches manual modes, on each VARIABLE_SET. */+ modeAttribute: jsonPluginDataField(+ 'modeAttribute',+ v.pipe(v.string(), v.trim(), v.maxLength(100), v.regex(MODE_ATTRIBUTE_PATTERN))+ ),/** One entry per paint picked in OkHCL, so the picker reopens on the same coordinates. */okhcl: jsonPluginDataField('okhcl', okhcl)} satisfies Record<string, PluginDataKey>diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.tsindex 4dd4dacf4..a03fd9bfe 100644--- a/packages/scene-graph/src/types.ts+++ b/packages/scene-graph/src/types.ts@@ -724,5 +724,17 @@ export interface VariableCollection {modes: VariableCollectionMode[]defaultModeId: stringvariableIds: string[]+ /**+ * The attribute that switches a mode with no condition of its own, `data-theme` for+ * `[data-theme="dark"]`. Absent means one named after the collection.+ */+ modeAttribute?: stringpluginData?: PluginDataEntry[]}++/** An HTML attribute name a stylesheet can select on unescaped: `data-theme`, `theme`. */+export const MODE_ATTRIBUTE_PATTERN = /^[A-Za-z_][\w-]*$/++export function isModeAttributeName(name: string): boolean {+ return name.length <= 100 && MODE_ATTRIBUTE_PATTERN.test(name)+}diff --git a/packages/vue/src/i18n/locales/de/variables.json b/packages/vue/src/i18n/locales/de/variables.jsonindex 310f91688..899620cfb 100644--- a/packages/vue/src/i18n/locales/de/variables.json+++ b/packages/vue/src/i18n/locales/de/variables.json@@ -71,6 +71,9 @@"expand": "Erweitern","collapse": "Einklappen","rowActions": "Aktionen für {name}",+ "modeAttribute": "Umschalt-Attribut",+ "modeAttributeHint": "Manuell umgeschaltete Modi werden mit {example} aktiviert.",+ "modeAttributeInvalid": "Verwenden Sie Buchstaben, Ziffern, Bindestriche und Unterstriche, beginnend mit einem Buchstaben.","stylesheet": "Stylesheet","mode": "Modus","scopeAllFills": "Alle Füllungen",diff --git a/packages/vue/src/i18n/locales/es/variables.json b/packages/vue/src/i18n/locales/es/variables.jsonindex 4c9374e9f..756ad17ce 100644--- a/packages/vue/src/i18n/locales/es/variables.json+++ b/packages/vue/src/i18n/locales/es/variables.json@@ -71,6 +71,9 @@"expand": "Expandir","collapse": "Contraer","rowActions": "Acciones de {name}",+ "modeAttribute": "Atributo de cambio",+ "modeAttributeHint": "Los modos que se cambian manualmente se activan con {example}.",+ "modeAttributeInvalid": "Usa letras, dígitos, guiones y guiones bajos, empezando por una letra.","stylesheet": "Hoja de estilos","mode": "Modo","scopeAllFills": "Todos los rellenos",diff --git a/packages/vue/src/i18n/locales/fr/variables.json b/packages/vue/src/i18n/locales/fr/variables.jsonindex 4b675d6d7..60a62570f 100644--- a/packages/vue/src/i18n/locales/fr/variables.json+++ b/packages/vue/src/i18n/locales/fr/variables.json@@ -71,6 +71,9 @@"expand": "Développer","collapse": "Réduire","rowActions": "Actions de {name}",+ "modeAttribute": "Attribut de bascule",+ "modeAttributeHint": "Les modes activés manuellement le sont avec {example}.",+ "modeAttributeInvalid": "Utilisez des lettres, chiffres, tirets et tirets bas, en commençant par une lettre.","stylesheet": "Feuille de style","mode": "Mode","scopeAllFills": "Tous les remplissages",diff --git a/packages/vue/src/i18n/locales/it/variables.json b/packages/vue/src/i18n/locales/it/variables.jsonindex 68918557e..3b89a47e2 100644--- a/packages/vue/src/i18n/locales/it/variables.json+++ b/packages/vue/src/i18n/locales/it/variables.json@@ -71,6 +71,9 @@"expand": "Espandi","collapse": "Comprimi","rowActions": "Azioni di {name}",+ "modeAttribute": "Attributo di attivazione",+ "modeAttributeHint": "Le modalità attivate manualmente si attivano con {example}.",+ "modeAttributeInvalid": "Usa lettere, cifre, trattini e trattini bassi, iniziando con una lettera.","stylesheet": "Foglio di stile","mode": "Modalità","scopeAllFills": "Tutti i riempimenti",diff --git a/packages/vue/src/i18n/locales/ja/variables.json b/packages/vue/src/i18n/locales/ja/variables.jsonindex c6c6831f5..507c2d89d 100644--- a/packages/vue/src/i18n/locales/ja/variables.json+++ b/packages/vue/src/i18n/locales/ja/variables.json@@ -71,6 +71,9 @@"expand": "展開","collapse": "折りたたむ","rowActions": "{name} のアクション",+ "modeAttribute": "切り替え属性",+ "modeAttributeHint": "手動で切り替えるモードは {example} でオンになります。",+ "modeAttributeInvalid": "英字で始め、英数字・ハイフン・アンダースコアのみを使ってください。","stylesheet": "スタイルシート","mode": "モード","scopeAllFills": "すべての塗り",diff --git a/packages/vue/src/i18n/locales/pl/variables.json b/packages/vue/src/i18n/locales/pl/variables.jsonindex b7c7cc9f1..fc8e2518d 100644--- a/packages/vue/src/i18n/locales/pl/variables.json+++ b/packages/vue/src/i18n/locales/pl/variables.json@@ -71,6 +71,9 @@"expand": "Rozwiń","collapse": "Zwiń","rowActions": "Akcje dla {name}",+ "modeAttribute": "Atrybut przełączania",+ "modeAttributeHint": "Tryby przełączane ręcznie włącza się za pomocą {example}.",+ "modeAttributeInvalid": "Użyj liter, cyfr, łączników i podkreśleń, zaczynając od litery.","stylesheet": "Arkusz stylów","mode": "Tryb","scopeAllFills": "Wszystkie wypełnienia",diff --git a/packages/vue/src/i18n/locales/ru/variables.json b/packages/vue/src/i18n/locales/ru/variables.jsonindex 07291e485..7f81f8bac 100644--- a/packages/vue/src/i18n/locales/ru/variables.json+++ b/packages/vue/src/i18n/locales/ru/variables.json@@ -71,6 +71,9 @@"expand": "Развернуть","collapse": "Свернуть","rowActions": "Действия с {name}",+ "modeAttribute": "Атрибут переключения",+ "modeAttributeHint": "Режимы, переключаемые вручную, включаются с помощью {example}.",+ "modeAttributeInvalid": "Используйте буквы, цифры, дефисы и подчёркивания, начиная с буквы.","stylesheet": "Таблица стилей","mode": "Режим","scopeAllFills": "Все заливки",diff --git a/packages/vue/src/i18n/locales/zh-cn/variables.json b/packages/vue/src/i18n/locales/zh-cn/variables.jsonindex 967197927..87da6273c 100644--- a/packages/vue/src/i18n/locales/zh-cn/variables.json+++ b/packages/vue/src/i18n/locales/zh-cn/variables.json@@ -71,6 +71,9 @@"expand": "展开","collapse": "收起","rowActions": "{name} 的操作",+ "modeAttribute": "切换属性",+ "modeAttributeHint": "手动切换的模式通过 {example} 启用。",+ "modeAttributeInvalid": "请使用字母、数字、连字符和下划线,并以字母开头。","stylesheet": "样式表","mode": "模式","scopeAllFills": "所有填充",diff --git a/packages/vue/src/i18n/messages/variables.ts b/packages/vue/src/i18n/messages/variables.tsindex ab35428a3..566808122 100644--- a/packages/vue/src/i18n/messages/variables.ts+++ b/packages/vue/src/i18n/messages/variables.ts@@ -78,6 +78,9 @@ export const variablesMessageDefaults = {expand: 'Expand',collapse: 'Collapse',rowActions: params('{name} actions'),+ modeAttribute: 'Switch attribute',+ modeAttributeHint: params('Modes switched manually are turned on with {example}.'),+ modeAttributeInvalid: 'Use letters, digits, hyphens and underscores, starting with a letter.',stylesheet: 'Stylesheet',mode: 'Mode',scopeAllFills: 'All fills',diff --git a/src/components/variables/CollectionInspector.vue b/src/components/variables/CollectionInspector.vueindex b6d137373..49aa3555d 100644--- a/src/components/variables/CollectionInspector.vue+++ b/src/components/variables/CollectionInspector.vue@@ -8,9 +8,10 @@ import {DropdownMenuTrigger} from 'reka-ui'import { tv } from 'tailwind-variants'-import { computed, reactive, watch } from 'vue'+import { computed, reactive, useId, watch } from 'vue'-import type { VariableCollection } from '@open-pencil/scene-graph'+import { defaultModeAttributeName } from '@open-pencil/dom-css/export'+import { isModeAttributeName, type VariableCollection } from '@open-pencil/scene-graph'import { useI18n } from '@open-pencil/vue'import {@@ -39,6 +40,7 @@ const emit = defineEmits<{done: []rename: [name: string]remove: []+ setModeAttribute: [name: string]addMode: []renameMode: [modeId: string, name: string]duplicateMode: [modeId: string]@@ -56,6 +58,7 @@ const dangerItem = useMenuUI({ item: 'justify-start gap-2 text-error' }).item/** Text fields edit a draft and commit on change, like the token fields. */const draft = reactive({name: '',+ attribute: '',modeNames: {} as Record<string, string>,custom: {} as Record<string, string>,widths: {} as Record<string, string>@@ -68,10 +71,12 @@ watch(() =>JSON.stringify([collection.name,+ collection.modeAttribute ?? '',collection.modes.map((mode) => [mode.modeId, mode.name, mode.condition ?? ''])]),() => {draft.name = collection.name+ draft.attribute = collection.modeAttribute ?? ''for (const mode of collection.modes) {const condition = parseModeCondition(mode.condition)draft.modeNames[mode.modeId] = mode.name@@ -88,6 +93,27 @@ function commitName() {else draft.name = collection.name}+const attributeErrorId = `${useId()}-attribute`+/** Blank restores the default; anything else must be an attribute a selector can name as is. */+const attributeInvalid = computed(() => {+ const name = draft.attribute.trim()+ return name !== '' && !isModeAttributeName(name)+})++/** A manual mode's selector, so the hint shows what the attribute switches. */+const attributeExample = computed(() => {+ const manual = collection.modes.find(+ (candidate) => candidate.modeId !== collection.defaultModeId && !candidate.condition+ )+ return (manual && modeConditionPlaceholder(collection, manual.modeId)) ?? ''+})++function commitAttribute() {+ if (attributeInvalid.value) return+ const name = draft.attribute.trim()+ if (name !== (collection.modeAttribute ?? '')) emit('setModeAttribute', name)+}+function mode(modeId: string) {return collection.modes.find((candidate) => candidate.modeId === modeId)}@@ -148,6 +174,11 @@ function done(event: KeyboardEvent) {if (event.target instanceof HTMLElement) event.target.blur()emit('done')}++/** An attribute the field refuses keeps the focus, so it can be corrected. */+function attributeDone(event: KeyboardEvent) {+ if (!attributeInvalid.value) done(event)+}</script><template>@@ -187,6 +218,27 @@ function done(event: KeyboardEvent) {</DropdownMenuPortal></DropdownMenuRoot></div>+ <label v-if="collection.modes.length > 1" :class="ui.field()">+ <span :class="ui.label()">{{ variables.modeAttribute }}</span>+ <AppInput+ v-model="draft.attribute"+ size="sm"+ :placeholder="defaultModeAttributeName(collection)"+ :state="attributeInvalid ? 'invalid' : 'idle'"+ :aria-invalid="attributeInvalid"+ :aria-describedby="attributeInvalid ? attributeErrorId : undefined"+ :ui="{ input: 'font-mono' }"+ data-test-id="variables-mode-attribute"+ @change="commitAttribute"+ @enter="attributeDone"+ />+ <p v-if="attributeInvalid" :id="attributeErrorId" :class="ui.error()" role="alert">+ {{ variables.modeAttributeInvalid }}+ </p>+ <span v-else-if="attributeExample" :class="ui.hint()">{{+ variables.modeAttributeHint({ example: attributeExample })+ }}</span>+ </label></section><section :class="ui.section()">diff --git a/src/components/variables/TokensPanel.vue b/src/components/variables/TokensPanel.vueindex 963f4fe94..0a5b25bae 100644--- a/src/components/variables/TokensPanel.vue+++ b/src/components/variables/TokensPanel.vue@@ -255,6 +255,10 @@ function reorder(sourceId: string, targetIndex: number, visibleIds: string[]) {if (collection.value) actions.reorder(collection.value.id, sourceId, targetIndex, visibleIds)}+function setModeAttribute(name: string) {+ if (collection.value) editor.setModeAttribute(collection.value.id, name)+}+function setCondition(modeId: string, condition: string) {if (collection.value) editor.setModeCondition(collection.value.id, modeId, condition)}@@ -296,7 +300,8 @@ const collectionInspector = computed(() => {onSetDefaultMode: ctx.setDefaultMode,onRemoveMode: ctx.removeMode,onSetCondition: setCondition,- onDone: focusList+ onDone: focusList,+ onSetModeAttribute: setModeAttribute}})const tableActions = {diff --git a/tests/e2e/variables/dialog.spec.ts b/tests/e2e/variables/dialog.spec.tsindex f358d652e..e70aafe8c 100644--- a/tests/e2e/variables/dialog.spec.ts+++ b/tests/e2e/variables/dialog.spec.ts@@ -155,6 +155,28 @@ test('a new mode is switched manually until a condition is picked', async () =>editor.canvas.assertNoErrors()})+test('manual modes switch by the attribute the collection names', async () => {+ const inspector = editor.page.getByTestId('collection-inspector')+ await inspector.getByTestId('variables-add-mode').click()+ const added = inspector.getByTestId('variables-mode').last()+ await expect(added.getByTestId('variables-mode-css')).toHaveText(+ '[data-test-collection="mode-3"]'+ )++ const attribute = inspector.getByTestId('variables-mode-attribute')+ await attribute.fill('data scheme')+ await expect(attribute).toHaveAttribute('aria-invalid', 'true')+ await attribute.press('Enter')+ // A refused attribute keeps the focus, so it can be corrected.+ await expect(attribute).toBeFocused()+ await attribute.fill('data-scheme')+ await attribute.press('Enter')++ await expect(added.getByTestId('variables-mode-css')).toHaveText('[data-scheme="mode-3"]')+ await expect(attribute).not.toHaveAttribute('aria-invalid', 'true')+ editor.canvas.assertNoErrors()+})+test('color swatch opens color picker', async () => {await createColorVariable('SwatchVar')// close dialog if open from previous test