Skip to content

feat(select): sync styles and API with Figma - #197

Open
khaliulin wants to merge 10 commits into
feature/form-caption-figma-syncfrom
feature/form-select-figma-sync
Open

khaliulin wants to merge 10 commits into
feature/form-caption-figma-syncfrom
feature/form-select-figma-sync

Conversation

@khaliulin

@khaliulin khaliulin commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Sync Select field styles, option geometry and API with the Figma reference. Keep Storybook examples limited to the displayed UI and preserve existing descriptions from main.

Changes

  1. Align Select field sizes, states, icons, overlay and option tokens; add a token-based CSS layer for the wrapper, readonly and FloatLabel layouts.
  2. Render captions through the shared ExtraCaptionComponent and add fluid layout support.
  3. Rename showCheckbox to showCheckmark and align its enabled and disabled option geometry with the live Select reference.
  4. Replace combinatorial examples with six single-instance stories: Default, Error, Disabled, Readonly, Fluid and FloatLabel.
  5. Bind stories to their Controls and produce dynamic HTML snippets for the current example only; preserve the 20 existing component, story and Control descriptions verbatim from origin/main.
  6. Update Select API documentation and preserve the original example components.
  • Restore all 8 original example component files. Apply only the typing/API compatibility changes needed to compile them against the current component. Keep existing descriptions verbatim and keep the current single-instance story list.

API changes

  • BREAKING: showCheckbox is renamed to showCheckmark (boolean, default true). Consumers must rename their template binding.
  • captionSeverity: ExtraCaptionSeverity, default base; accepts base, success, warning, danger and info and is forwarded to the shared caption component.
  • fluid: boolean, default false; stretches the field to its container width.
  • floatLabel suppresses the native placeholder while the floating label supplies the field label.
  • checkmarkIcon retains its existing API; its custom glyph is passed through a component-specific CSS property.

Technical notes for reviewers

  • The PR contains only Select implementation, styles, documentation and stories. The shared tokens file changes only components.select. Local rules, gates and reference exports are excluded.
  • Live Figma reference: Select section, UI Kit DS v3.0, checked on 2026-11-17 in light and dark modes.
  • checkmarkSize uses dimension.size.500 (18px). The 7px icon inset and 27px text offset come from absolute coordinates in the Figma option master; those coordinates have no bound variables, so they are stored as Select component tokens.
  • The selected option is styled through aria-selected with sufficient specificity because the native selected class is absent in the tested PrimeNG rendering. Both checkmark modes retain the selected background.
  • Group headings follow the accepted shared rule: 12px text and 4px 10px padding through tokens, with uppercase text.
  • Stories manage disabled and invalid through FormControl, honor custom options and group field names, and serialize nondefault component inputs into the displayed snippet.

Visual changes

  • Options have 16px text, an 18px line height and a 42px row height. With showCheckmark=true, all labels start at 27px; the selected 18px icon starts at 7px and is vertically centered. With false, text starts at 10px.
  • Selected backgrounds use neutral.weak.active (light #cecfd2, dark #56595f); selected focus uses neutral.weak.hover (light #e2e2e4, dark #404348).
  • Field sizing, readonly appearance, focus/invalid treatment, muted icons and the FloatLabel layout follow the component token layer.
  • Group headings use the same compact typography and spacing as AutoComplete.

Verification

  • PASS: check-component select; check-stories-bg; check-stories-single (six stories, one instance each, no console errors); check-stories-controls (32 inputs).

  • PASS: check-stories-source for all six stories, plus changed Controls including grouping and custom options; snippets match the displayed UI.

  • PASS: check-stories-descriptions select, 20 existing descriptions match current origin/main verbatim.

  • PASS: live check-figma-values, 35 of 35 bound tokens in each theme; sizing mode padding was verified separately.

  • PASS: checkmark geometry checks in 16 combinations (two themes, four field sizes, checkmark on/off), including selected and focused colors.

  • PASS: TypeScript app typecheck, targeted Prettier check and git diff --check.

  • check-dt-refs: no Select dead references; the global gate still reports existing confirm-dialog dead references and token-name collisions in other components.

  • check-push is required and run immediately before push with this title and body.

  • Not verified: a full cross-browser suite or a full-component pixel-identical screenshot match.

  • PASS (example restoration): targeted strict Angular template compilation of all 8 restored examples; check-stories-bg; check-stories-source for the full current story list and changed Controls; check-stories-descriptions against origin/main; check-stories-single and check-stories-controls.

  • The restored standalone files remain available as source examples; restoring them does not add combinatorial stories to the current Storybook index.

Known issues and open questions

  • The Figma icon is vector artwork while the implementation uses the existing Tabler webfont. Geometry matches, but glyph rasterization differs; the measured Figma text box is 52px wide versus an intrinsic browser width of 51.8125px.
  • Group headings deliberately use the accepted 12px / 4px 10px rule. The live Figma master and overlay have different heading typography and retain taller spacing, so the complete grouped overlay is not pixel-identical.
  • FloatLabel keeps the interactive floating behavior of the existing input components; the reference depicts a statically raised label.
  • Existing failures in the global token-reference gate are outside this component's scope.

Stack

Base: feature/form-caption-figma-sync (#193). Dependency stack: tokens-base (#192) ← caption (#193) ← Select (this PR).

Danil Khaliulin added 7 commits November 13, 2026 01:51
1. Добавлен вход captionSeverity (base, success, warning, danger, info; по умолчанию base) — цвет и иконка подписи по варианту Figma _<Caption>.
2. Подпись теперь рисует общий компонент extra-caption; класс .extra-select-caption и его css в токенах удалены.
3. В сторис добавлены Controls для всех 31 входа и недостающие привязки в шаблоне (captionSeverity, editable, required, loading, emptyMessage, emptyFilterMessage, appendTo, inputId, checkmarkIcon, group, optionLabel, optionValue, optionDisabled, optionGroupLabel, optionGroupChildren, ariaLabel, ariaLabelledBy, autofocus, tabindex); options можно подменить через Controls.
4. В docs/components-api/select.md добавлена строка captionSeverity.

Заметки для ревьюеров:
- API: новый необязательный вход captionSeverity; BREAKING только для тех, кто стилизовал .extra-select-caption, — стили нужно перенести на .extra-caption.
- Внутренняя переменная иконки отметки переименована --p-select-checkmark-content → --extra-select-checkmark-content (гейт запрещает сырые var(--p-*) в токенах; такой переменной PrimeNG не выпускает). Внешнее поведение не изменилось.
- Визуально: у подписи появилась иконка, базовый цвет fg.subtle → fg.muted, как в Figma.
- Переделка сторис по правилу «одна сторис — один пресет Figma» остаётся в ветке полной синхронизации Select.
1. Токены select приведены к эталону Figma: 23 замены (геометрия поля 272/12/12, радиус 10, размеры sm/lg, invalidBorderColor, опции padding 12/10 и цвета fg.default, группы fontWeight 400, overlay, иконки), extXlg приведён к моде xlarge DS (font 20, padding 12/14).
2. CSS слоя кита (select.ts на dt()): поле min-width 272 и max-width 100% против раздувания контентом, переопределение --p-select-dropdown-width, line-height по модам размеров, xlarge-мода поверх large, focus/invalid ring, readonly, FloatLabel по поведению InputText с геометрией референса, иконка info в float-режиме скрыта.
3. API: добавлен fluid (растягивает поле на контейнер), в float-режиме placeholder не передаётся в поле (лейбл в покое стоит в центре).
4. Сторис переделаны по шагу 4a: Default, Error, Disabled, Readonly, Fluid, FloatLabel — одна сторис один экземпляр; комбинаторные (Filter, Grouped, Custom, SelectedItem, Editable, Sizes, LabelPosition) и examples/ удалены; хост-компонент фиксирует ширину превью 272px по референсу; inputId открыт в Controls.
5. Документация API (docs/components-api/select.md) дополнена fluid.

Заметки для ревьюеров:
- API: новый @input fluid=false (не ломает); placeholder в float-режиме скрывается (поведение как у InputText/MultiSelect, по приёмке этих компонентов).
- Токены: 4 расхождения refDiffers из tokens-diff.json — ложные (составные значения из нескольких ссылок, строки идентичны эталону; те же два у принятого MultiSelect).
- Технические детали: p-select-sm/lg идут через токены select.root.sm/lg (спредятся в пресете); xlarge PrimeNG не знает — обёртка ставит p-select-xlg поверх large; ширина в stories фиксирована хост-компонентом с encapsulation: None.
- Известное отличие от Figma (вопрос дизайну, как у MultiSelect): референс рисует float-лейбл статично поднятым, код — классическое поведение PrimeNG.
1. Фон выбранной опции определяется aria-selected, а не наличием check-icon: PrimeNG не рендерит .p-select-option-check-icon при checkmark=false, и выбранная опция теряла фон selected (по приёмке).
2. Галочка рисуется только у выбранной опции при showCheckbox=true; у невыбранных убран фантомный резерв 16px под скрытую ::before (в Figma _<Select.Option> место под иконку есть только у варианта checkmark=true).
3. Ширина поля в FloatLabel: min-width переведён с select.dropdown.width на новый токен select.extend.width (272px, как multiselect.extend.width) — значение старого токена в CSS разворачивается в переопределяемую переменную --p-select-dropdown-width (40px) и сжимало поле до 46px в float-режиме.

Заметки для ревьюеров:
- Токены: select.extend.width = {dimension.size.1700} — тот же паттерн, что у multiselect.extend.width в PR 195.
- Поведение: showCheckbox=false скрывает только галочку, фон выбранной (selectedBackground / selectedFocusBackground) остаётся во всех состояниях — по контракту _<Select.Option>.
- Проверено: float-label поле 272 (обёртка 272), showCheckbox=false выбранная rgb(240,240,241)/rgb(162,165,169) без ::before, showCheckbox=true галочка только у выбранной; style-baselines select пересняты, 6/6 pass.
1. Заголовки групп опций в верхнем регистре: text-transform: uppercase на .p-select-option-group по контракту Figma _<Select.Group> (textCase UPPER).

Заметки для ревьюеров:
- База токенов: токена регистра в схеме PrimeUIX/эталоне нет, зона дизайнера в CSS-слое кита (прецеденты: menu-submenu-label, divider).
- Замер: «ГРУППА 1», weight 400, фон rgba(0,0,0,0) — совпадает с контрактом; style-baselines select пересняты, 6/6 pass.
1. Вход showCheckbox переименован в showCheckmark: галочка у выбранной опции — не чекбокс (чекбоксы у опций MultiSelect), имя сбивало с толку при использовании обоих компонентов.

Заметки для ревьюеров:
- BREAKING: [showCheckbox]="false" → [showCheckmark]="false"; дефолт true не менялся, миграция в comp-json/FORM/Select/CHANGES.md.
- Нейминг по правилу «показ элемента = show*» (docs/naming-rules.md); совпадает с осью Figma checkmark в _<Select.Option>, входом PrimeNG [checkmark] и нашим checkmarkIcon.
- Проверено в Storybook: showCheckmark=false — фон выбранной остаётся, галочки нет; true — галочка у выбранной; baselines пересняты, 6/6 pass.
1. option.selectedBackground: bg.neutral.medium.hover (#cecfd2) → bg.neutral.translucent.faint — выбранная опция в покое без фона, индикатор выбора — галочка (аналог чекбокса MultiSelect).
2. option.selectedFocusBackground: bg.neutral.medium.active (#a2a5a9) → bg.neutral.weak.default (#f0f0f1) — ховер по выбранной единый с невыбранной опцией.

Заметки для ревьюеров:
- Отклонение от эталона Figma (контракт _<Select.Option> ждёт medium.hover/medium.active для выбранной) — то же осознанное отклонение, что у MultiSelect по его приёмке; check-figma-values показывает эти 2 расхождения постоянно, это ожидаемо.
- Замер: выбранная в покое rgba(0,0,0,0) + галочка \uea5e (цвет fg.default), hover по выбранной rgb(240,240,241); style-baselines select пересняты, 6/6 pass.
1. Привести галочку и текст опций к геометрии актуального макета: иконка 18 пикселей, отступы 7 и 27 пикселей, высота строки 42 пикселя.
2. Восстановить токены фона выбранной опции и её фокуса, исправить приоритет селекторов и унифицировать заголовки групп.
3. Сделать примеры кода stories динамическими, связать их с Controls и вернуть исходные описания из main.

Заметки для ревьюеров:
- API: новых изменений публичного API в этом коммите нет; состояние формы управляется через FormControl.
- Токены: добавлены компонентные размеры галочки и абсолютные смещения из Figma; optionGroup использует общие значения 12 пикселей и 4 на 10 пикселей.
- Геометрия проверена в двух темах, четырёх размерах, с галочкой и без неё; различия растеризации векторной и шрифтовой иконки сохраняются.
Danil Khaliulin added 2 commits November 17, 2026 14:06
1. Восстановить 8 исходных example-файлов компонента вместо лишнего удаления.
2. Согласовать примеры с актуальными типами и API, сохранив исходные описания.
3. Проверить snippets текущих stories, изменённые Controls и строгую Angular-компиляцию восстановленных примеров.

Заметки для ревьюеров:
- Область: только примеры и stories select; производственные компоненты и токены в этом коммите не меняются.
- Stories: сохранён текущий список отдельных примеров; исходные example-файлы доступны рядом с ним.
- Проверки: Angular-компиляция восстановленных примеров и обязательные gates snippets и описаний проходят.
1. parameters.controls.expanded = true — панель Controls показывает описание, тип, дефолт и группы категорий.
2. Гейты: controls 32/32, descriptions 20/20, source 6/6.
@khaliulin
khaliulin force-pushed the feature/form-select-figma-sync branch from 5ff0a0f to 8ed484d Compare November 18, 2026 12:43
Включает глобальный controls.expanded в .storybook/preview.ts (иначе на ветке панель Controls остаётся компактной до мержа инфраструктурной ветки).
@khaliulin
khaliulin force-pushed the feature/form-select-figma-sync branch from 8ed484d to f39a6ee Compare November 18, 2026 12:45

This branch has not been deployed

No deployments
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.

1 participant