Skip to content

docs(openspec): propose sizes tokens editor - #127

Closed
vkaltyrin wants to merge 21 commits into
feature/ds-versionsfrom
feature/sizes-tokens-editor
Closed

vkaltyrin wants to merge 21 commits into
feature/ds-versionsfrom
feature/sizes-tokens-editor

Conversation

@vkaltyrin

@vkaltyrin vkaltyrin commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Что это

OpenSpec change add-sizes-tokens-editor. В PR только артефакты change: реализация будет после согласования.

PR перебазирован на #109 (версии, журнал и многопользовательское редактирование): база — feature/ds-versions.

Радиусы, отступы и тени темы переводятся на прототип SDDS Portal и на операции ds-service, как «Палитра», «Цвета» и «Типографика» (#121). Прежний экран «Формы» убирается.

Ключевые решения

  • Один экран «Отступы, радиусы и тени». Основа — экран «Отступы и радиусы» прототипа. Раздел «Тени» добавлен:
    • в редакторе прототипа теней нет;
    • в данных у каждой темы 12 теней, их используют компоненты;
    • текущий клиент их правит;
    • документация прототипа описывает тени той же схемой Direction / Character / Size.
  • Тени на борде — списком по размерам. У каждого варианта своя строка с превью на отдельной плашке, чтобы крупные тени не заходили на соседние.
  • Цвет слоя тени — HEX или ступень палитры темы.
    • Выбор цвета такой же, как в «Цветах»: вкладки Custom и Library, свотч внутри поля.
    • Ссылка [type.shade.step][opacity] хранится как у стопов градиента в feat(ds): градиент как вид значения цветового токена #122 и раскрывается в HEX для потребителей.
    • Ссылка на цветовой токен отклонена: у токенов есть режимы Light и Dark, а у теней режима нет.
  • Одно значение в px. ds-service переводит его в формат каждой платформы: на вебе rem при базе 16, тень — CSS-строка на слой.
  • Своё значение платформы — как у цветов в feat(ds): градиент как вид значения цветового токена #122.
    • Основное значение — веб, iOS и Android строятся из него.
    • «+» у значения добавляет строку «↳ iOS» / «↳ Android» с признаком overridden.
    • Если старые данные расходятся с вебом, инспектор предлагает сохранить их как свои значения. Так при первой правке они не теряются молча.
  • Вычисляемые радиусы. Это не токены темы, а смещение у значений компонентов: в base у Button и IconButton радиус задан как round.l −2. Они показываются на борде и в инспекторе источника и доступны только для чтения.
  • Тень — четыре варианта размера ({down|up}.{soft|hard}.<размер>). Создаётся и удаляется размер целиком.
  • Создание и удаление — как у цветов: окно «Новый токен» у каждого раздела, подтверждение удаления, если токен используют компоненты.
  • round.circle — полное скругление: значение не правится. В темах оно записано по-разному.
  • Без своей кнопки сброса и без отключения токенов. Отмена правок — общий журнал изменений feat(ds): версии, журнал изменений и версионная палитра #109.

ds-service

  • GET /api/ds/tenants/{tenantId}/size-tokens отдаёт радиусы, отступы и тени в px. У каждого токена:
    • свои значения платформ;
    • компоненты, которые его используют;
    • вычисляемые радиусы.
  • PUT …/size-tokens/{tokenId}/value пишет значение в текущую тему.
  • POST …/size-tokens и DELETE …/size-tokens/{tokenId} создают и удаляют токены во всех темах дизайн-системы.
  • Права — как у операций цветового токена.

Модель #109

  • Ревизия. Общего счётчика темы editRevision и 409 TENANT_EDIT_CONFLICT нет. Операции пишут предметные
    редакции: базовая редакция — X-DS-Base-Revision или baseRevisions по платформам, метаданные — в
    X-DS-Mutation-Metadata. Правки разных токенов не конфликтуют, при правке одного значения побеждает последняя
    запись с предупреждением.
  • Версии. Чтение принимает versionId: опубликованная версия открывается только для чтения. Использование
    и вычисляемые радиусы читаются из конфигураций компонентов на той же границе.
  • Создание — с Idempotency-Key и уникальностью имени под блокировкой.
  • Удаление логическое: опубликованные версии сохраняют токен, отмена — через журнал. Журнал и откат для
    shape, spacing и shadow уже покрыты общими обработчиками feat(ds): версии, журнал изменений и версионная палитра #109.
  • Клиент: общая очередь feat(ds): версии, журнал изменений и версионная палитра #109 с автоповтором и SSE, переход из журнала по ?tokenId. Баннера прежнего
    черновика нет: неподтверждённые записи отправляет сессия редактора.

Зависимость

Артефакты

  • openspec/changes/add-sizes-tokens-editor/proposal.md
  • openspec/changes/add-sizes-tokens-editor/design.md — решения, контракты, таблица расхождений с прототипом, риски
  • openspec/changes/add-sizes-tokens-editor/specs/sizes-tokens-api/spec.md
  • openspec/changes/add-sizes-tokens-editor/specs/sizes-tokens-editor/spec.md
  • openspec/changes/add-sizes-tokens-editor/tasks.md

Проверки

  • openspec validate add-sizes-tokens-editor --type change --strict — PASS на 1.6.0 и 1.4.1.
  • openspec validate --specs --strict — PASS (78).

@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9947f4c7-e2d4-4016-8984-b91957bd6393

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@vkaltyrin vkaltyrin self-assigned this Oct 20, 2026
@vkaltyrin
vkaltyrin force-pushed the feature/sizes-tokens-editor branch from 87b813c to 51c5974 Compare October 21, 2026 09:09
@vkaltyrin
vkaltyrin changed the base branch from dev to feature/ds-versions October 21, 2026 09:09
миграцией V8 (V7 занята версионированием #109). Реализация начинается после него; если этот change окажется
первым, миграция колонки переходит сюда вместе с учётом признака в начальных значениях новых тем, журнале и
откате.
- [Сессия редактора восстанавливает записи общими маршрутами] → `PUT /tenants/{id}/token-values` и общие

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Восстановление правок не сохраняет изменение overridden.
Восстановление поручено общей сессии через PUT token-values, которому предписано сохранять существующий overridden. Но в базе #109 локальная запись TokenChange содержит значения платформ без этого признака.
Если пользователь добавит своё значение Android и закроет страницу до сохранения, восстановление запишет число, но оставит overridden: false. Следующая правка веба затрёт Android. При удалении своего значения возможна обратная ситуация: останется true.
Нужно сохранять и повторять исходную команду size-tokens с platforms либо расширить общий формат восстановления явным изменением overridden. Нужны сценарии восстановления добавления и удаления своего значения до подтверждения сервером.

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.

Исправлено

- **WHEN** ответ создания не получен из-за сети или `5xx`
- **THEN** клиент MUST повторить запрос с тем же `Idempotency-Key` и тем же телом, чтобы токен не создался дважды

### Requirement: Удаление токена размеров

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Подтверждение удаления проверяет выбранную тень вместо всего размера.
Подтверждение требуется только при использовании выбранного токена, а API удаляет сразу четыре варианта размера. Например, выбранный up.soft.m может не использоваться, тогда как down.hard.m используется компонентами. По сценарию «Токен без связей» клиент удалит весь размер без подтверждения и сбросит ссылки компонентов.
Нужно определять необходимость подтверждения по объединению использований всех четырёх вариантов и показывать в окне полный список затронутых компонентов.

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.

Исправлено

…isions

Add token_value_revisions.overridden and token_value_creation_baselines.overridden
(V8). The flag is a subject field of a value revision: the token-value journal
handler shows it, the creation baseline and the field reverter restore it, new
themes start with false, and every shared value write (token-values PUT, color
tokens, palette rewrites, token value API, theme initializer) keeps the flag of
the latest revision instead of resetting it.
Read radii, spacing and shadows from token_revisions and token_value_revisions
on the transaction boundary with versionId (canEdit is false on a published
version) and component usage and derived radii from the latest revisions of
component configurations on the same boundary. A value change locks the design
system and the token values, rereads them and writes draft revisions of the
changed values only with the /value and /overridden paths and a per-platform
base revision. Creation writes definitions and values in every theme under the
name key lock with Idempotency-Key support; deletion writes tombstones in every
theme and clears component references. The theme edit revision, its lock and
TENANT_EDIT_CONFLICT are removed; mutations return X-DS-Mutation-Metadata.

A shadow layer color may be a palette step reference [type.shade.step][opacity]:
it is validated against the theme palette, stored in every platform value and
resolved to #RRGGBBAA with colorRef on read.
Shadow layer colors that reference a palette step take part in the theme
palette like color token references: the palette snapshot carries shadow tokens
and the references of their layers, ramp links and linked counts include them
(group by the name rule, not in color token assignments), ramp removal rewrites
the layer color in place, and the revert dependency check rejects restoring a
layer reference to a removed ramp. GET token-values returns the resolved
sourceValue.
…ting model

The size-tokens read refers to VersionId; value change, creation and deletion
refer to OptionalBaseRevision (creation also to OptionalIdempotencyKey) and
describe the X-DS-Mutation-Metadata headers. Bodies and responses drop
editRevision and TENANT_EDIT_CONFLICT, deletion takes no body, value changes
take per-platform baseRevisions, shadow layers carry colorRef and accept a
palette step reference, and tenant token values document sourceValue.
…visions

Read the base theme with the derived round.l -2 and a published version with
versionId, edit radii and shadows with and without own platform values, edit
one value concurrently (warning in the mutation metadata) and different tokens
independently, keep the own flag through the shared token-values save, revert
an own platform value from the journal, repeat a creation with the same
Idempotency-Key, delete with component references reset while the published
version keeps the token, delete a token created in the draft without a journal
entry, and link a shadow layer color to the palette: validation, resolution in
size-tokens and token-values with sourceValue, ramp links, ramp removal and the
revert dependency conflict.
Size token operations follow contract v2: no editRevision, base revisions
of the web, iOS and Android values from subjectRevisions taken when the
command is sent, an Idempotency-Key on creation, mutations through
subjectMutation with X-DS-Mutation-Metadata and errors with details.field.
The queue keeps the 400 ms quiet window and generations, retries network
and 5xx errors after 1 s doubling up to 30 s and reports its state as the
size-tokens autosave source.

Every unconfirmed operation is kept in the theme localStorage as the
original size-tokens command (method, path, body with platforms, base
revisions, idempotency key) and is replayed by the same command when the
theme editor session starts, even if the section is not open; it is never
turned into a ds_draft TokenChange.

The section reads with versionId and is read-only for a published version,
selects ?tokenId through useAddressedToken and reports an unavailable
source, rereads after local queues when the theme model is replaced, and
size-tokens truncated metadata refreshes theme tokens. Shadow size deletion
is confirmed by the union of usage of its four variants with the new dialog
texts. The legacy draft banner and legacyDraft are removed.
The swatch inside the layer color field opens the ColorPickerPopover of the
colors section with Custom and Library tabs. A Library step is sent as the
[type.shade.step][opacity] reference, and the field shows the step name
(Gray 900) by colorRef with the reference opacity; HEX input or a Custom
color replaces the reference. The picker rules move into size-tokens.css
under the section root, the popover opens left of the inspector.
The + of a tree section appears on hover and focus of the section heading
row, as for groups in the colors section, instead of anywhere over the
section.
@vkaltyrin
vkaltyrin force-pushed the feature/sizes-tokens-editor branch from d1119b5 to 73aad34 Compare October 21, 2026 14:41
@vkaltyrin vkaltyrin closed this Oct 22, 2026
@vkaltyrin
vkaltyrin deleted the feature/sizes-tokens-editor branch October 22, 2026 05:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants