From a0fdb74133fc3f1011d47e759d827304e742e0d5 Mon Sep 17 00:00:00 2001 From: Rim Zabarov Date: Sun, 22 Nov 2026 01:49:44 +0300 Subject: [PATCH 1/6] Components: live behaviour examples on 13 pages in place of script listings Clipboard events, country code and input/textarea state from code, quantity total on change, range slider filter on change, verification:complete, breadcrumb hidden items, dropdown change, Tabs.activate, Tree.open with sf-tree-open, modal:before-close refused while edits are unsaved, slider slideChange. Each example runs in a sandbox frame with its script in the JavaScript tab and an event log where the page names events. Co-Authored-By: Claude Opus 5.5 --- content/ru/components/actions/clipboard.md | 10 ++-- content/ru/components/forms/country-code.md | 6 +-- content/ru/components/forms/inputs.md | 9 ++-- content/ru/components/forms/quantity.md | 9 ++-- content/ru/components/forms/range-slider.md | 9 ++-- content/ru/components/forms/textarea.md | 9 ++-- content/ru/components/forms/verification.md | 7 +-- .../ru/components/navigation/breadcrumbs.md | 7 +-- content/ru/components/navigation/dropdown.md | 7 +-- content/ru/components/navigation/tabs.md | 9 +--- content/ru/components/navigation/tree.md | 14 ++--- content/ru/components/overlays-media/modal.md | 11 ++-- .../ru/components/overlays-media/slider.md | 16 +++--- .../breadcrumbs/hidden-items/index.html | 14 +++++ .../breadcrumbs/hidden-items/index.js | 7 +++ .../components/clipboard/events/index.html | 9 ++++ examples/components/clipboard/events/index.js | 9 ++++ .../country-code/set-state/index.html | 13 +++++ .../country-code/set-state/index.js | 15 ++++++ .../components/dropdown/change/index.html | 18 +++++++ examples/components/dropdown/change/index.js | 8 +++ .../components/inputs/set-state/index.html | 7 +++ examples/components/inputs/set-state/index.js | 21 ++++++++ .../components/modal/before-close/index.css | 5 ++ .../components/modal/before-close/index.html | 12 +++++ .../components/modal/before-close/index.js | 53 +++++++++++++++++++ examples/components/quantity/total/index.html | 11 ++++ examples/components/quantity/total/index.js | 12 +++++ .../components/range-slider/change/index.html | 4 ++ .../components/range-slider/change/index.js | 13 +++++ .../assets/place-01-16x9-label.svg | 1 + .../assets/place-02-16x9-label.svg | 1 + .../assets/place-03-16x9-label.svg | 1 + .../components/slider/slide-change/index.html | 7 +++ .../components/slider/slide-change/index.js | 20 +++++++ examples/components/tabs/activate/index.html | 19 +++++++ examples/components/tabs/activate/index.js | 8 +++ .../components/textarea/set-state/index.html | 7 +++ .../components/textarea/set-state/index.js | 23 ++++++++ examples/components/tree/open/index.html | 23 ++++++++ examples/components/tree/open/index.js | 16 ++++++ .../verification/complete/index.html | 10 ++++ .../components/verification/complete/index.js | 12 +++++ 43 files changed, 431 insertions(+), 71 deletions(-) create mode 100644 examples/components/breadcrumbs/hidden-items/index.html create mode 100644 examples/components/breadcrumbs/hidden-items/index.js create mode 100644 examples/components/clipboard/events/index.html create mode 100644 examples/components/clipboard/events/index.js create mode 100644 examples/components/country-code/set-state/index.html create mode 100644 examples/components/country-code/set-state/index.js create mode 100644 examples/components/dropdown/change/index.html create mode 100644 examples/components/dropdown/change/index.js create mode 100644 examples/components/inputs/set-state/index.html create mode 100644 examples/components/inputs/set-state/index.js create mode 100644 examples/components/modal/before-close/index.css create mode 100644 examples/components/modal/before-close/index.html create mode 100644 examples/components/modal/before-close/index.js create mode 100644 examples/components/quantity/total/index.html create mode 100644 examples/components/quantity/total/index.js create mode 100644 examples/components/range-slider/change/index.html create mode 100644 examples/components/range-slider/change/index.js create mode 100644 examples/components/slider/slide-change/assets/place-01-16x9-label.svg create mode 100644 examples/components/slider/slide-change/assets/place-02-16x9-label.svg create mode 100644 examples/components/slider/slide-change/assets/place-03-16x9-label.svg create mode 100644 examples/components/slider/slide-change/index.html create mode 100644 examples/components/slider/slide-change/index.js create mode 100644 examples/components/tabs/activate/index.html create mode 100644 examples/components/tabs/activate/index.js create mode 100644 examples/components/textarea/set-state/index.html create mode 100644 examples/components/textarea/set-state/index.js create mode 100644 examples/components/tree/open/index.html create mode 100644 examples/components/tree/open/index.js create mode 100644 examples/components/verification/complete/index.html create mode 100644 examples/components/verification/complete/index.js diff --git a/content/ru/components/actions/clipboard.md b/content/ru/components/actions/clipboard.md index 58a3e63c..a871c288 100644 --- a/content/ru/components/actions/clipboard.md +++ b/content/ru/components/actions/clipboard.md @@ -141,11 +141,11 @@ profile: reference | `sf:copy-success` | значение записано в буфер | `method` — `native` или `legacy`; `text` — скопированный текст | | `sf:copy-error` | значение не записано | `code` — `missing_source`, `missing_target`, `ambiguous_source`, `empty_source` или `denied` (браузер не дал записать) | -```js -document.addEventListener('sf:copy-success', (event) => { - console.log('Скопировано:', event.detail.text); -}); -``` +В примере страница слушает оба события и пишет под кнопкой, что +скопировано или почему не получилось. + +:::example {id="components/clipboard/events" label="События копирования" preview=sandbox log="sf:copy-success sf:copy-error" log_open=true} +::: Компонент регистрирует класс `Copy`, который собирает кнопку из параметров (`text`, `copy`, `done`, `error`, `label`, `size`, `type`, `scheme`). diff --git a/content/ru/components/forms/country-code.md b/content/ru/components/forms/country-code.md index f9c7bb62..720b9c74 100644 --- a/content/ru/components/forms/country-code.md +++ b/content/ru/components/forms/country-code.md @@ -164,10 +164,8 @@ profile: reference `dialCode` (выбрать страну). Изменение `value` и страны создаёт `input` и `change`. -```js -const field = document.querySelector('input[name="phone"]'); -SF.CountryCode.setState(field, {iso2: 'KZ'}); -``` +:::example {id="components/country-code/set-state" label="Страна из кода" preview=sandbox log="change" log_open=true} +::: Компонент регистрирует класс `CountryCode`. `SF.Loader` появляется к событию `sf-loader-init` на `window`; `SF.Loader.ready('CountryCode', callback)` diff --git a/content/ru/components/forms/inputs.md b/content/ru/components/forms/inputs.md index 72344591..f678e3fa 100644 --- a/content/ru/components/forms/inputs.md +++ b/content/ru/components/forms/inputs.md @@ -256,10 +256,11 @@ basis-60` растёт и начинает с доли строки. Кнопк подсказки возвращает приложение. После изменения `value` поле получает всплывающее событие `input`. -```js -const field = document.querySelector('input[name="email"]'); -SF.Input.setState(field, {invalid: true, errorMessage: 'Укажите рабочую почту'}); -``` +В примере страница проверяет адрес и показывает ошибку в подсказке поля, а +вторая кнопка меняет значение из кода. + +:::example {id="components/inputs/set-state" label="Состояние поля из кода" preview=sandbox log="input" log_open=false} +::: Функция возвращает `false`, если внутри оболочки нет input. diff --git a/content/ru/components/forms/quantity.md b/content/ru/components/forms/quantity.md index d9153826..7e7faf9a 100644 --- a/content/ru/components/forms/quantity.md +++ b/content/ru/components/forms/quantity.md @@ -193,11 +193,10 @@ Tab или нажмите на него. :::example {id="components/quantity/reset" label="Сброс формы"} ::: -```js -document.querySelector('input[name="places"]').addEventListener('change', (event) => { - updateTotal(event.target.value); -}); -``` +В примере страница пересчитывает сумму заказа по событию `change`. + +:::example {id="components/quantity/total" label="Сумма по количеству" preview=sandbox log="change" log_open=false} +::: Компонент регистрирует класс `Quantity`. `SF.Loader` появляется к событию `sf-loader-init` на `window`; `SF.Loader.ready('Quantity', callback)` передаёт diff --git a/content/ru/components/forms/range-slider.md b/content/ru/components/forms/range-slider.md index fd8bfe1a..d0a5c75c 100644 --- a/content/ru/components/forms/range-slider.md +++ b/content/ru/components/forms/range-slider.md @@ -176,10 +176,11 @@ profile: reference | `sf-range-slider-set`, `sf-range-slider-change` | значение установлено | | `change` | значение установил человек; `setValue` его не создаёт | -```js -const slider = document.querySelector('.sf-range-slider'); -slider.addEventListener('change', (event) => applyFilter(event.detail.value)); -``` +В примере страница фильтрует проекты по бюджету, когда человек отпускает +ручку. + +:::example {id="components/range-slider/change" label="Фильтр по бюджету" preview=sandbox log="change sf-range-slider-end" log_open=false} +::: `SF.RangeSlider` управляет слайдером из кода: diff --git a/content/ru/components/forms/textarea.md b/content/ru/components/forms/textarea.md index f5d43421..6f35ff38 100644 --- a/content/ru/components/forms/textarea.md +++ b/content/ru/components/forms/textarea.md @@ -250,10 +250,11 @@ profile: reference и прежний текст подсказки возвращает приложение. После изменения `value` поле получает событие `input`. -```js -const field = document.querySelector('textarea[name="comment"]'); -SF.Textarea.setState(field, {error: true, errorMessage: 'Добавьте не менее десяти символов'}); -``` +В примере страница проверяет длину комментария при отправке и снимает +ошибку, когда текста становится достаточно. + +:::example {id="components/textarea/set-state" label="Ошибка из кода" preview=sandbox} +::: Функция возвращает `false`, если внутри оболочки нет `Что важно знать курьеру +
+ +
+

+ diff --git a/examples/components/textarea/set-state/index.js b/examples/components/textarea/set-state/index.js new file mode 100644 index 00000000..8375a81f --- /dev/null +++ b/examples/components/textarea/set-state/index.js @@ -0,0 +1,23 @@ +const whenLoader = (run) => (window.SF?.Loader ? run() : window.addEventListener('sf-loader-init', run, {once: true})); + +whenLoader(() => SF.Loader.ready('Textarea', () => { + const field = document.querySelector('textarea[name="comment"]'); + const result = document.querySelector('#textarea-result'); + const hint = 'Что важно знать курьеру'; + + // The page checks the text; the component shows the error in its hint. + const check = () => { + const short = field.value.trim().length < 10; + SF.Textarea.setState(field, short + ? {error: true, errorMessage: 'Добавьте не менее десяти символов'} + : {error: false, errorMessage: hint}); + return !short; + }; + + document.querySelector('#textarea-check').addEventListener('click', () => { + result.textContent = check() ? 'Комментарий принят.' : ''; + }); + field.addEventListener('input', () => { + if (field.closest('.sf-textarea').classList.contains('error')) check(); + }); +})); diff --git a/examples/components/tree/open/index.html b/examples/components/tree/open/index.html new file mode 100644 index 00000000..930b90c3 --- /dev/null +++ b/examples/components/tree/open/index.html @@ -0,0 +1,23 @@ +
+
+
+
Документы
+
+
Договор.pdf
+
Смета.xlsx
+
+
+
+
Изображения
+
+
Обложка.png
+
+
+
README.md
+
+
+ + +
+

Выберите файл и нажмите Enter: страница откроет его.

+
diff --git a/examples/components/tree/open/index.js b/examples/components/tree/open/index.js new file mode 100644 index 00000000..63567518 --- /dev/null +++ b/examples/components/tree/open/index.js @@ -0,0 +1,16 @@ +const whenLoader = (run) => (window.SF?.Loader ? run() : window.addEventListener('sf-loader-init', run, {once: true})); + +whenLoader(() => SF.Loader.ready('Tree', () => { + const tree = document.querySelector('#tree-open-files'); + const docs = tree.querySelector('[data-value="docs"]'); + const result = document.querySelector('#tree-open-result'); + + // Enter on a file: the page opens it. + tree.addEventListener('sf-tree-open', (event) => { + result.textContent = `Открыт файл: ${event.detail.value}`; + }); + + // A branch from code, as a link elsewhere on the page would do. + document.querySelector('#tree-open-docs').addEventListener('click', () => SF.Tree.open(docs)); + document.querySelector('#tree-close-docs').addEventListener('click', () => SF.Tree.close(docs)); +})); diff --git a/examples/components/verification/complete/index.html b/examples/components/verification/complete/index.html new file mode 100644 index 00000000..e3d9c308 --- /dev/null +++ b/examples/components/verification/complete/index.html @@ -0,0 +1,10 @@ +
+
+ + + + + Введите шесть цифр. Верный код в примере — 123456 +
+

+
diff --git a/examples/components/verification/complete/index.js b/examples/components/verification/complete/index.js new file mode 100644 index 00000000..b80a5a92 --- /dev/null +++ b/examples/components/verification/complete/index.js @@ -0,0 +1,12 @@ +const result = document.querySelector('#verification-complete-result'); + +// The page checks the code; the component only says it is complete. +const checkCode = (value) => { + result.textContent = value === '123456' + ? `Код ${value} подтверждён.` + : `Код ${value} не подошёл: проверьте сообщение.`; +}; + +document.addEventListener('verification:complete', (event) => { + checkCode(event.detail.value); +}); From fcc35513e765888b7442adcb47cec82dae5fd08c Mon Sep 17 00:00:00 2001 From: Rim Zabarov Date: Sun, 22 Nov 2026 01:49:44 +0300 Subject: [PATCH 2/6] Guide and Pro: live theme, display settings, workspace and composer examples Theme: setTheme/changeTheme inside the example frame (theme_switch). Display settings: write/reset/current/subscribe by buttons. Workspace: show()/panel() with the state line and events. Chat composer: the host sends, shows the message and clears the field. Docara frame shims, commented in the scripts: the frame copies the page's root font size inline, which hides the core text scale (also fixed in the accessibility display-settings example); the frame has no allow-forms, so the composer's send button asks its form for the submit. Co-Authored-By: Claude Opus 5.5 --- content/ru/guide/functions/actions/theme.md | 12 +++- .../functions/person/display-settings.md | 10 +++ .../ru/guide/layouts/building/workspace.md | 8 +++ content/ru/pro/chat/chat-composer.md | 7 ++ .../accessibility/display-settings/index.js | 14 ++++ .../functions/display-settings/index.html | 10 +++ .../guide/functions/display-settings/index.js | 39 +++++++++++ examples/guide/functions/theme/index.html | 9 +++ examples/guide/functions/theme/index.js | 26 ++++++++ examples/guide/workspace/script/index.css | 7 ++ examples/guide/workspace/script/index.html | 23 +++++++ examples/guide/workspace/script/index.js | 22 +++++++ .../chat-composer/send/index.html | 4 ++ .../chat-composer/send/index.js | 64 +++++++++++++++++++ 14 files changed, 252 insertions(+), 3 deletions(-) create mode 100644 examples/guide/functions/display-settings/index.html create mode 100644 examples/guide/functions/display-settings/index.js create mode 100644 examples/guide/functions/theme/index.html create mode 100644 examples/guide/functions/theme/index.js create mode 100644 examples/guide/workspace/script/index.css create mode 100644 examples/guide/workspace/script/index.html create mode 100644 examples/guide/workspace/script/index.js create mode 100644 examples/smart-components/chat-composer/send/index.html create mode 100644 examples/smart-components/chat-composer/send/index.js diff --git a/content/ru/guide/functions/actions/theme.md b/content/ru/guide/functions/actions/theme.md index 17763426..62923ba8 100644 --- a/content/ru/guide/functions/actions/theme.md +++ b/content/ru/guide/functions/actions/theme.md @@ -43,9 +43,15 @@ Loader: функции темы появляются вместе с `SF.Loader` ## Пример -Тему этой документации ведёт сам сайт, поэтому в примерах Loader темой не -управляет. Переключатель на классах, который работает на любой странице с -Loader: +Тему этой документации ведёт сам сайт, а в примере ниже Loader управляет +темой своей рамки: кнопки вызывают `setTheme` и `changeTheme`, строка под +ними читает `theme` и `themePreference`, журнал показывает +`sf-theme-change`. Рамка без cookie, поэтому выбор держится до перезагрузки. + +:::example {id="guide/functions/theme" label="Тема из скрипта" theme_switch=true log_console=true} +::: + +Переключатель на классах, который работает на любой странице с Loader: ```html diff --git a/content/ru/guide/functions/person/display-settings.md b/content/ru/guide/functions/person/display-settings.md index d01b2e57..012f3617 100644 --- a/content/ru/guide/functions/person/display-settings.md +++ b/content/ru/guide/functions/person/display-settings.md @@ -52,6 +52,16 @@ SF.displaySettings.reset(); // обычная ве Ядро: сразу после выполнения `core.js`, ждать не нужно. +## Пример + +Кнопки записывают выбор через `write()`, «Обычная версия» вызывает +`reset()`, строка под текстом читает `current()`, а журнал показывает вызовы +`subscribe`. В рамке примера нет хранилища браузера, поэтому выбор держится +до перезагрузки. + +:::example {id="guide/functions/display-settings" label="Настройки отображения из скрипта" preview=sandbox log_console=true} +::: + ## Особые случаи - Ссылку «Перейти к содержимому» ядро ставит первой в `` на каждой diff --git a/content/ru/guide/layouts/building/workspace.md b/content/ru/guide/layouts/building/workspace.md index 87e08de0..c1355733 100644 --- a/content/ru/guide/layouts/building/workspace.md +++ b/content/ru/guide/layouts/building/workspace.md @@ -111,3 +111,11 @@ workspace.layout; // 'narrow', 'split' или 'wide' - `sf-workspace-view` — `detail: {view}`, когда изменился показанный вид; - `sf-workspace-panel` — `detail: {open}`, когда панель открылась или закрылась, но не когда она только перешла из колонки в положение поверх. + +В примере кнопки вызывают `show()` и `panel()`, строка под рабочей областью +читает `view`, `panelOpen` и `layout`, журнал показывает события. Сузьте +пример кнопкой размера: на узкой ширине виден один экран, а панель выезжает +поверх. + +:::example {id="guide/workspace/script" label="Рабочая область из скрипта" preview=sandbox log="sf-workspace-view sf-workspace-panel" log_open=true} +::: diff --git a/content/ru/pro/chat/chat-composer.md b/content/ru/pro/chat/chat-composer.md index 8d72c9bc..e27c0bec 100644 --- a/content/ru/pro/chat/chat-composer.md +++ b/content/ru/pro/chat/chat-composer.md @@ -92,6 +92,13 @@ composer.addEventListener('sf-chat-composer-detach', (event) => remove(event.det composer.files = [{id: 'att_1', name: 'Договор.pdf', bytes: 48213}]; ``` +В примере хост «отправляет» сообщение после короткой паузы, показывает его +над полем и вызывает `clear()`; прикреплённые файлы он так же «загружает» и +возвращает чипами. + +:::example {id="smart-components/chat-composer/send" label="Отправка и очистка" preview=sandbox log="sf-chat-composer-submit sf-chat-composer-attach sf-chat-composer-detach" log_open=true} +::: + ### Счётчик знаков После 80 % от `maxlength` под полем появляется счётчик знаков; сверх предела diff --git a/examples/guide/accessibility/display-settings/index.js b/examples/guide/accessibility/display-settings/index.js index c59ec151..1d3f8fb6 100644 --- a/examples/guide/accessibility/display-settings/index.js +++ b/examples/guide/accessibility/display-settings/index.js @@ -12,3 +12,17 @@ document.addEventListener('sf-display-settings-change', (event) => { ? 'Возвращена обычная версия' : `Изменено: ${names[setting] ?? setting}; текст ${settings?.textScale ?? 100} %`; }); + +// Only for this example: the documentation frame copies the page's root font +// size onto inline, and an inline size beats the core rule that scales +// the text. While a text scale is chosen the frame lets the core rule work; +// on a site this part is not needed. +let docaraRootSize = document.documentElement.style.fontSize; +const letTextScaleWork = () => { + const root = document.documentElement; + const scaled = root.hasAttribute('data-sf-text-scale'); + if (!scaled && root.style.fontSize) docaraRootSize = root.style.fontSize; + if (scaled && root.style.fontSize) root.style.removeProperty('font-size'); + else if (!scaled && docaraRootSize && root.style.fontSize !== docaraRootSize) root.style.fontSize = docaraRootSize; +}; +new MutationObserver(letTextScaleWork).observe(document.documentElement, {attributes: true, attributeFilter: ['data-sf-text-scale', 'style']}); diff --git a/examples/guide/functions/display-settings/index.html b/examples/guide/functions/display-settings/index.html new file mode 100644 index 00000000..e97b061a --- /dev/null +++ b/examples/guide/functions/display-settings/index.html @@ -0,0 +1,10 @@ +
+
+ + + + +
+

Заявление можно подать лично или через личный кабинет. Справку выдают в течение трёх рабочих дней.

+

Показано сейчас:

+
diff --git a/examples/guide/functions/display-settings/index.js b/examples/guide/functions/display-settings/index.js new file mode 100644 index 00000000..1a503333 --- /dev/null +++ b/examples/guide/functions/display-settings/index.js @@ -0,0 +1,39 @@ +const log = (name, data) => (window.docara?.example?.log ? window.docara.example.log(name, data) : console.log(name, data)); +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +// The example frame has no browser storage: the choice lasts until the +// page is reloaded. On a site it stays for every page. +const show = () => { + const now = SF.displaySettings.current(); + document.getElementById('display-current').textContent = `textScale ${now.textScale}, scheme «${now.scheme}», textSpacing ${now.textSpacing}`; +}; + +const start = async () => { + await sfReady(); + SF.displaySettings.subscribe((settings) => { + log('subscribe', {textScale: settings.textScale, scheme: settings.scheme, textSpacing: settings.textSpacing}); + show(); + }); + show(); + const press = (id, run) => document.getElementById(id).addEventListener('click', () => { run(); show(); }); + press('display-large', () => SF.displaySettings.write({textScale: 150})); + press('display-contrast', () => SF.displaySettings.write({scheme: 'black-on-white'})); + press('display-wide', () => SF.displaySettings.write({textSpacing: 'wide'})); + press('display-reset', () => SF.displaySettings.reset()); +}; + +start(); + +// Only for this example: the documentation frame copies the page's root font +// size onto inline, and an inline size beats the core rule that scales +// the text. While a text scale is chosen the frame lets the core rule work; +// on a site this part is not needed. +let docaraRootSize = document.documentElement.style.fontSize; +const letTextScaleWork = () => { + const root = document.documentElement; + const scaled = root.hasAttribute('data-sf-text-scale'); + if (!scaled && root.style.fontSize) docaraRootSize = root.style.fontSize; + if (scaled && root.style.fontSize) root.style.removeProperty('font-size'); + else if (!scaled && docaraRootSize && root.style.fontSize !== docaraRootSize) root.style.fontSize = docaraRootSize; +}; +new MutationObserver(letTextScaleWork).observe(document.documentElement, {attributes: true, attributeFilter: ['data-sf-text-scale', 'style']}); diff --git a/examples/guide/functions/theme/index.html b/examples/guide/functions/theme/index.html new file mode 100644 index 00000000..78f99077 --- /dev/null +++ b/examples/guide/functions/theme/index.html @@ -0,0 +1,9 @@ +
+
+ + + + +
+

Тема: , выбор:

+
diff --git a/examples/guide/functions/theme/index.js b/examples/guide/functions/theme/index.js new file mode 100644 index 00000000..c3aab27a --- /dev/null +++ b/examples/guide/functions/theme/index.js @@ -0,0 +1,26 @@ +const log = (name, data) => (window.docara?.example?.log ? window.docara.example.log(name, data) : console.log(name, data)); +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +// The theme here changes only inside this example frame; the frame has no +// cookie, so the choice lasts until the page is reloaded. +const show = () => { + document.getElementById('theme-now').textContent = SF.Loader.theme; + document.getElementById('theme-preference').textContent = SF.Loader.themePreference; +}; + +const start = async () => { + await sfReady(); + window.addEventListener('sf-theme-change', (event) => { + const {theme, preference} = event.detail; + log('sf-theme-change', {theme, preference}); + show(); + }); + show(); + const press = (id, run) => document.getElementById(id).addEventListener('click', () => log(id, {result: run()})); + press('theme-dark', () => SF.Loader.setTheme('dark')); + press('theme-light', () => SF.Loader.setTheme('light')); + press('theme-system', () => SF.Loader.setTheme('system')); + press('theme-change', () => SF.Loader.changeTheme()); +}; + +start(); diff --git a/examples/guide/workspace/script/index.css b/examples/guide/workspace/script/index.css new file mode 100644 index 00000000..d2f619c9 --- /dev/null +++ b/examples/guide/workspace/script/index.css @@ -0,0 +1,7 @@ +/* Рамка рабочей области: её высота — место под список, разговор и панель. */ +.page-workspace-frame { + block-size: var(--sf-g0); + border: var(--sf-px) solid var(--sf-outline-variant); + border-radius: var(--sf-radius--ui); + overflow: hidden; +} diff --git a/examples/guide/workspace/script/index.html b/examples/guide/workspace/script/index.html new file mode 100644 index 00000000..2a69e49a --- /dev/null +++ b/examples/guide/workspace/script/index.html @@ -0,0 +1,23 @@ +
+
+ + + +
+
+
+
+

Выпуск документации

+

Отпуск и перенос

+
+
+ +

Открытый разговор. Кнопки над рабочей областью меняют вид и панель из скрипта; на узкой ширине виден один экран.

+
+ +
+
+

+
diff --git a/examples/guide/workspace/script/index.js b/examples/guide/workspace/script/index.js new file mode 100644 index 00000000..613e3d2b --- /dev/null +++ b/examples/guide/workspace/script/index.js @@ -0,0 +1,22 @@ +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +const start = async () => { + const SF = await sfReady(); + const element = document.querySelector('#workspace-script'); + const workspace = SF.workspace(element); + const state = document.querySelector('#workspace-state'); + const show = () => { + state.textContent = `view: ${workspace.view}, panelOpen: ${workspace.panelOpen}, layout: ${workspace.layout}`; + }; + + document.querySelector('#workspace-list').addEventListener('click', () => workspace.show('list')); + document.querySelector('#workspace-main').addEventListener('click', () => workspace.show('main')); + document.querySelector('#workspace-panel').addEventListener('click', () => workspace.panel()); + + // The events come however the state changed: a call, an attribute, «Назад». + element.addEventListener('sf-workspace-view', show); + element.addEventListener('sf-workspace-panel', show); + show(); +}; + +start(); diff --git a/examples/smart-components/chat-composer/send/index.html b/examples/smart-components/chat-composer/send/index.html new file mode 100644 index 00000000..2efafcdc --- /dev/null +++ b/examples/smart-components/chat-composer/send/index.html @@ -0,0 +1,4 @@ +
+
+ +
diff --git a/examples/smart-components/chat-composer/send/index.js b/examples/smart-components/chat-composer/send/index.js new file mode 100644 index 00000000..4685456d --- /dev/null +++ b/examples/smart-components/chat-composer/send/index.js @@ -0,0 +1,64 @@ +// The host sends the message and clears the field only when it was accepted; +// here "sending" is a short pause. Files are "uploaded" the same way. +const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +const initialize = async () => { + await customElements.whenDefined('sf-chat-composer'); + const composer = document.querySelector('#chat-composer-send'); + const sent = document.querySelector('#chat-composer-sent'); + if (!composer || composer.dataset.exampleReady === 'true') return; + composer.dataset.exampleReady = 'true'; + let files = []; + let count = 0; + + const send = async (text, ids) => { + await pause(400); + // The message element is not on the page yet: ask the loader for it. + await window.SF.Loader.ensure(['sf-chat-message']); + await customElements.whenDefined('sf-chat-message'); + const message = document.createElement('sf-chat-message'); + message.setAttribute('template', 'person'); + count += 1; + message.message = {id: count, body: text, authorName: 'Вы', files: files.filter((file) => ids.includes(file.id)).map((file) => ({id: file.id, name: file.name, size: file.bytes, state: 'ready'}))}; + message.display = {own: true, first: true, last: true}; + sent.append(message); + return true; + }; + + composer.addEventListener('sf-chat-composer-submit', async (event) => { + event.preventDefault(); + if (await send(event.detail.text, event.detail['attachment-ids'])) { + files = []; + composer.clear(); + } + }); + composer.addEventListener('sf-chat-composer-attach', async (event) => { + const added = event.detail.files.map((file, index) => ({localId: `f${count}-${index}-${file.name}`, name: file.name, bytes: file.size, progress: 0.3, error: ''})); + files = [...files, ...added]; + composer.files = files; + await pause(600); + files = files.map((file) => (added.includes(file) ? {...file, id: `att_${file.localId}`, progress: null} : file)); + composer.files = files; + }); + composer.addEventListener('sf-chat-composer-detach', (event) => { + files = files.filter((file) => file.id !== event.detail.id); + composer.files = files; + }); +}; + +initialize(); + +// Only for this example: the documentation frame may not send forms, and the +// browser then does not even report the submit, so the send button would not +// reach the composer (Enter sends without the form). The button's press asks +// the form for the submit, as the browser does on a site. On a site this part +// is not needed. +const composerForSubmit = document.querySelector('#chat-composer-send'); +if (composerForSubmit && composerForSubmit.dataset.submitShim !== 'true') { + composerForSubmit.dataset.submitShim = 'true'; + composerForSubmit.addEventListener('click', (event) => { + if (!event.target.closest('button[type="submit"]')) return; + event.preventDefault(); + composerForSubmit.querySelector('form')?.dispatchEvent(new Event('submit', {cancelable: true})); + }, true); +} From 5a6212b553f5b1390a9f86c8ba9856254eb0dd82 Mon Sep 17 00:00:00 2001 From: Rim Zabarov Date: Sun, 22 Nov 2026 01:49:45 +0300 Subject: [PATCH 3/6] Smart composite and content: live examples on 7 pages Page header favourite answered by a pretend server, site header sheet filled on sf-header-site-opened, accordion open/toggle from code, file preview removed after the server confirms, gallery counter and the viewer without a gallery, slider from code, tag filter on change. The tags kinds example now sets kind="checkbox" on the tag it labels as such (the default kind is default). Co-Authored-By: Claude Opus 5.5 --- content/ru/smart/composite/page-header.md | 10 ++---- content/ru/smart/composite/site-header.md | 11 +++---- content/ru/smart/content/accordion.md | 8 +++++ content/ru/smart/content/file-preview.md | 6 ++++ content/ru/smart/content/gallery.md | 15 ++++----- content/ru/smart/content/slider.md | 9 ++---- content/ru/smart/content/tags.md | 8 ++--- .../counter/assets/place-01-16x9-label.svg | 1 + .../counter/assets/place-02-16x9-label.svg | 1 + .../counter/assets/place-03-16x9-label.svg | 1 + .../components/gallery/counter/index.html | 11 +++++++ examples/components/gallery/counter/index.js | 15 +++++++++ .../viewer/assets/place-01-16x9-label.svg | 1 + .../viewer/assets/place-02-16x9-label.svg | 1 + .../viewer/assets/place-03-16x9-label.svg | 1 + examples/components/gallery/viewer/index.html | 8 +++++ examples/components/gallery/viewer/index.js | 23 ++++++++++++++ .../accordion/from-code/index.html | 12 +++++++ .../accordion/from-code/index.js | 23 ++++++++++++++ .../file-preview/remove/index.html | 7 +++++ .../file-preview/remove/index.js | 27 ++++++++++++++++ .../page-header/favourite/index.html | 7 +++++ .../page-header/favourite/index.js | 21 +++++++++++++ .../site-header/sheet/index.css | 4 +++ .../site-header/sheet/index.html | 11 +++++++ .../site-header/sheet/index.js | 31 +++++++++++++++++++ .../slider/from-code/index.html | 12 +++++++ .../slider/from-code/index.js | 15 +++++++++ .../smart-components/tags/filter/index.html | 15 +++++++++ .../smart-components/tags/filter/index.js | 19 ++++++++++++ .../smart-components/tags/kinds/index.html | 2 +- 31 files changed, 301 insertions(+), 35 deletions(-) create mode 100644 examples/components/gallery/counter/assets/place-01-16x9-label.svg create mode 100644 examples/components/gallery/counter/assets/place-02-16x9-label.svg create mode 100644 examples/components/gallery/counter/assets/place-03-16x9-label.svg create mode 100644 examples/components/gallery/counter/index.html create mode 100644 examples/components/gallery/counter/index.js create mode 100644 examples/components/gallery/viewer/assets/place-01-16x9-label.svg create mode 100644 examples/components/gallery/viewer/assets/place-02-16x9-label.svg create mode 100644 examples/components/gallery/viewer/assets/place-03-16x9-label.svg create mode 100644 examples/components/gallery/viewer/index.html create mode 100644 examples/components/gallery/viewer/index.js create mode 100644 examples/smart-components/accordion/from-code/index.html create mode 100644 examples/smart-components/accordion/from-code/index.js create mode 100644 examples/smart-components/file-preview/remove/index.html create mode 100644 examples/smart-components/file-preview/remove/index.js create mode 100644 examples/smart-components/page-header/favourite/index.html create mode 100644 examples/smart-components/page-header/favourite/index.js create mode 100644 examples/smart-components/site-header/sheet/index.css create mode 100644 examples/smart-components/site-header/sheet/index.html create mode 100644 examples/smart-components/site-header/sheet/index.js create mode 100644 examples/smart-components/slider/from-code/index.html create mode 100644 examples/smart-components/slider/from-code/index.js create mode 100644 examples/smart-components/tags/filter/index.html create mode 100644 examples/smart-components/tags/filter/index.js diff --git a/content/ru/smart/composite/page-header.md b/content/ru/smart/composite/page-header.md index 64229a19..bd7807a4 100644 --- a/content/ru/smart/composite/page-header.md +++ b/content/ru/smart/composite/page-header.md @@ -182,14 +182,8 @@ description: "Голова рабочей страницы приложения: событие, дождитесь ответа и задайте `star` по нему: так звезда не покажет состояние, которое не сохранилось. -```js -const header = document.querySelector('sf-header-page'); -header.addEventListener('sf-header-page-toggle', async (event) => { - event.preventDefault(); - const saved = await saveFavourite(event.detail.on); - header.setAttribute('star', saved ? 'on' : 'off'); -}); -``` +:::example {id="smart-components/page-header/favourite" label="Избранное через сервер" preview=sandbox log="sf-header-page-toggle" log_open=true} +::: Если та же страница отмечена в меню администратора, после ответа сервера попросите меню перечитать избранное методом `refresh()` у ``. diff --git a/content/ru/smart/composite/site-header.md b/content/ru/smart/composite/site-header.md index 1b818833..cbfc1c39 100644 --- a/content/ru/smart/composite/site-header.md +++ b/content/ru/smart/composite/site-header.md @@ -151,12 +151,11 @@ SIMAI: каталогу эффектов, сайтам документации откроется; `sf-header-site-close` несёт причину: `close`, `escape`, `outside`, `cancelled` или `api`. -```js -const header = document.querySelector('sf-header-site'); -header.addEventListener('sf-header-site-opened', () => { - header.querySelector('[slot="sheet"]')?.replaceChildren(buildDocumentationTree()); -}); -``` +В примере страница строит дерево документации в слоте `sheet`, когда +панель открылась в первый раз. + +:::example {id="smart-components/site-header/sheet" label="Панель заполняется при открытии" preview=sandbox log="sf-header-site-open sf-header-site-opened sf-header-site-close" log_open=true} +::: Нажатие на затемнение, кнопка закрытия и выбор ссылки в панели тоже её закрывают; панель закрывается и тогда, когда окно стало шире `collapse`. diff --git a/content/ru/smart/content/accordion.md b/content/ru/smart/content/accordion.md index 5d2e30b4..3a43d9bd 100644 --- a/content/ru/smart/content/accordion.md +++ b/content/ru/smart/content/accordion.md @@ -145,6 +145,14 @@ faq.addEventListener('sf-accordion-toggle', (event) => { faq.open(location.hash.slice(1)); ``` +В примере кнопки вызывают `open()` и `toggle()`, а строка под секциями +показывает адрес открытой секции: у рамки примера своего адреса нет, и +браузер не даёт ей `replaceState`. Журнал показывает, кто открыл секцию: +`user` или `method`. + +:::example {id="smart-components/accordion/from-code" label="Секции из кода" preview=sandbox log="sf-accordion-toggle" log_open=true} +::: + ## Доступность - Шапка каждой секции — кнопка внутри заголовка уровня `heading-level` diff --git a/content/ru/smart/content/file-preview.md b/content/ru/smart/content/file-preview.md index 1352fb00..6488583b 100644 --- a/content/ru/smart/content/file-preview.md +++ b/content/ru/smart/content/file-preview.md @@ -123,6 +123,12 @@ file.onDownload((event) => { }); ``` +В примере «сервер» подтверждает удаление через полсекунды, и только тогда +строка исчезает; скачивание страница перехватывает и называет файл. + +:::example {id="smart-components/file-preview/remove" label="Удаление после ответа сервера" preview=sandbox log="sf-file-preview-download sf-file-preview-detach" log_open=true} +::: + ### Данные файла `getValue()` возвращает те же данные, что приходят в `event.detail.value`. diff --git a/content/ru/smart/content/gallery.md b/content/ru/smart/content/gallery.md index a840b781..1d894d2c 100644 --- a/content/ru/smart/content/gallery.md +++ b/content/ru/smart/content/gallery.md @@ -92,13 +92,8 @@ description: "Показывает набор материалов слайде `event.detail` приходят `current` и `total`, а у `change` ещё `previous` и `from` — откуда пришла смена: `inline`, `lightbox` или `api`. -```js -const gallery = document.querySelector('sf-gallery'); -gallery.addEventListener('change', (event) => { - counter.textContent = `${event.detail.current} из ${event.detail.total}`; -}); -gallery.open(3); -``` +:::example {id="components/gallery/counter" label="Счётчик материалов" preview=sandbox log="change sf-gallery-opened sf-gallery-closed" log_open=false} +::: Вложенные слайдеры не хранят своего положения: не исправляйте его через их API, а вызывайте методы галереи. `getInlineSlider()`, `getLightboxSlider()` @@ -120,6 +115,12 @@ const viewer = SF.Gallery.view([ viewer.next(); ``` +В примере ссылки на файлы открывают просмотр с нужного материала, а фокус +после закрытия возвращается на ссылку. + +:::example {id="components/gallery/viewer" label="Просмотр списка файлов" preview=sandbox} +::: + `SF.Gallery.view(items, options)` открывает просмотр (или показывает новые материалы в открытом) и возвращает `{close(), goTo(n), next(), prev(), current, total, open}`; `SF.Gallery.close()` закрывает его, а diff --git a/content/ru/smart/content/slider.md b/content/ru/smart/content/slider.md index 2333c337..4c88bda9 100644 --- a/content/ru/smart/content/slider.md +++ b/content/ru/smart/content/slider.md @@ -156,13 +156,8 @@ SIMAI Framework: цветовые роли, отступы и радиусы з `realIndex` — номер слайда без учёта копий, которые добавляет `loop`. `refresh()` пересчитывает раскладку после изменения размеров контейнера. -```js -const slider = document.querySelector('sf-slider'); -slider.addEventListener('change', (event) => { - counter.textContent = `${event.detail.realIndex + 1} из 3`; -}); -slider.slideNext(); -``` +:::example {id="smart-components/slider/from-code" label="Листание из кода" preview=sandbox log="change" log_open=false} +::: ## Доступность diff --git a/content/ru/smart/content/tags.md b/content/ru/smart/content/tags.md index f7ec1a71..1d4232a4 100644 --- a/content/ru/smart/content/tags.md +++ b/content/ru/smart/content/tags.md @@ -146,12 +146,8 @@ description: "Показывает короткую метку — катего отправляет всплывающее событие `change`; в `event.detail.active` — новое состояние, сам тег — `event.target`. -```js -document.querySelector('.filters').addEventListener('change', (event) => { - if (event.target.localName !== 'sf-tag') return; - applyFilter(event.target.getAttribute('text'), event.detail.active); -}); -``` +:::example {id="smart-components/tags/filter" label="Фильтр статей" preview=sandbox log="change" log_open=false} +::: ### Удаление diff --git a/examples/components/gallery/counter/assets/place-01-16x9-label.svg b/examples/components/gallery/counter/assets/place-01-16x9-label.svg new file mode 100644 index 00000000..f64d5819 --- /dev/null +++ b/examples/components/gallery/counter/assets/place-01-16x9-label.svg @@ -0,0 +1 @@ +1 · 16:9 diff --git a/examples/components/gallery/counter/assets/place-02-16x9-label.svg b/examples/components/gallery/counter/assets/place-02-16x9-label.svg new file mode 100644 index 00000000..0aff2b22 --- /dev/null +++ b/examples/components/gallery/counter/assets/place-02-16x9-label.svg @@ -0,0 +1 @@ +2 · 16:9 diff --git a/examples/components/gallery/counter/assets/place-03-16x9-label.svg b/examples/components/gallery/counter/assets/place-03-16x9-label.svg new file mode 100644 index 00000000..3c941562 --- /dev/null +++ b/examples/components/gallery/counter/assets/place-03-16x9-label.svg @@ -0,0 +1 @@ +3 · 16:9 diff --git a/examples/components/gallery/counter/index.html b/examples/components/gallery/counter/index.html new file mode 100644 index 00000000..5cb99b35 --- /dev/null +++ b/examples/components/gallery/counter/index.html @@ -0,0 +1,11 @@ +
+ +
Холмы и солнце над долиной
Долина
+
Город у подножия холмов
Город
+
Озеро между холмами
Озеро
+
+
+ + 1 из 3 +
+
diff --git a/examples/components/gallery/counter/index.js b/examples/components/gallery/counter/index.js new file mode 100644 index 00000000..c70e17f8 --- /dev/null +++ b/examples/components/gallery/counter/index.js @@ -0,0 +1,15 @@ +const initialize = async () => { + await customElements.whenDefined('sf-gallery'); + const gallery = document.querySelector('#gallery-counter'); + const counter = document.querySelector('#gallery-counter-value'); + if (!gallery || gallery.dataset.exampleReady === 'true') return; + gallery.dataset.exampleReady = 'true'; + + // The counter follows every change: arrows, dots, the full-screen view, open(). + gallery.addEventListener('change', (event) => { + counter.textContent = `${event.detail.current} из ${event.detail.total}`; + }); + document.querySelector('#gallery-counter-open').addEventListener('click', () => gallery.open(3)); +}; + +initialize(); diff --git a/examples/components/gallery/viewer/assets/place-01-16x9-label.svg b/examples/components/gallery/viewer/assets/place-01-16x9-label.svg new file mode 100644 index 00000000..f64d5819 --- /dev/null +++ b/examples/components/gallery/viewer/assets/place-01-16x9-label.svg @@ -0,0 +1 @@ +1 · 16:9 diff --git a/examples/components/gallery/viewer/assets/place-02-16x9-label.svg b/examples/components/gallery/viewer/assets/place-02-16x9-label.svg new file mode 100644 index 00000000..0aff2b22 --- /dev/null +++ b/examples/components/gallery/viewer/assets/place-02-16x9-label.svg @@ -0,0 +1 @@ +2 · 16:9 diff --git a/examples/components/gallery/viewer/assets/place-03-16x9-label.svg b/examples/components/gallery/viewer/assets/place-03-16x9-label.svg new file mode 100644 index 00000000..3c941562 --- /dev/null +++ b/examples/components/gallery/viewer/assets/place-03-16x9-label.svg @@ -0,0 +1 @@ +3 · 16:9 diff --git a/examples/components/gallery/viewer/index.html b/examples/components/gallery/viewer/index.html new file mode 100644 index 00000000..5bfd475c --- /dev/null +++ b/examples/components/gallery/viewer/index.html @@ -0,0 +1,8 @@ +
+ + +
diff --git a/examples/components/gallery/viewer/index.js b/examples/components/gallery/viewer/index.js new file mode 100644 index 00000000..a372d859 --- /dev/null +++ b/examples/components/gallery/viewer/index.js @@ -0,0 +1,23 @@ +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +const items = [ + {src: 'assets/place-01-16x9-label.svg', alt: 'Холмы и солнце над долиной', caption: 'План участка'}, + {src: 'assets/place-02-16x9-label.svg', alt: 'Город у подножия холмов', caption: 'Фасад'}, + {src: 'assets/place-03-16x9-label.svg', alt: 'Озеро между холмами', caption: 'Вид на озеро'}, +]; + +const start = async () => { + const SF = await sfReady(); + const state = document.querySelector('#gallery-viewer-state'); + document.querySelector('#gallery-viewer-files').addEventListener('click', async (event) => { + const link = event.target.closest('a[data-index]'); + if (!link) return; + event.preventDefault(); + // The viewer script comes with the gallery: ask the loader for it first. + await SF.Loader.ensure(['sf-gallery']); + const viewer = SF.Gallery.view(items, {start: Number(link.dataset.index), opener: link}); + state.textContent = `Открыт просмотр: ${viewer.current} из ${viewer.total}`; + }); +}; + +start(); diff --git a/examples/smart-components/accordion/from-code/index.html b/examples/smart-components/accordion/from-code/index.html new file mode 100644 index 00000000..53d30ccf --- /dev/null +++ b/examples/smart-components/accordion/from-code/index.html @@ -0,0 +1,12 @@ +
+
+ + +
+ +

Адрес секции: #main

+
diff --git a/examples/smart-components/accordion/from-code/index.js b/examples/smart-components/accordion/from-code/index.js new file mode 100644 index 00000000..51c164d7 --- /dev/null +++ b/examples/smart-components/accordion/from-code/index.js @@ -0,0 +1,23 @@ +// On a site the open section goes into the address with +// history.replaceState(null, '', `#${id}`). Only for this example: the +// documentation frame has no address of its own (about:srcdoc), the browser +// refuses replaceState there, so the line under the accordion shows the +// address instead. +const showAddress = (id, source) => { + document.querySelector('#accordion-from-code-state').textContent = `Адрес секции: #${id} (${source})`; +}; + +const initialize = async () => { + await customElements.whenDefined('sf-accordion'); + const faq = document.querySelector('#accordion-from-code'); + if (!faq || faq.dataset.exampleReady === 'true') return; + faq.dataset.exampleReady = 'true'; + + faq.addEventListener('sf-accordion-toggle', (event) => { + if (event.detail.open) showAddress(event.detail.id, event.detail.source); + }); + document.querySelector('#accordion-open-price').addEventListener('click', () => faq.open('price')); + document.querySelector('#accordion-toggle-stock').addEventListener('click', () => faq.toggle('stock')); +}; + +initialize(); diff --git a/examples/smart-components/file-preview/remove/index.html b/examples/smart-components/file-preview/remove/index.html new file mode 100644 index 00000000..4fd2db2f --- /dev/null +++ b/examples/smart-components/file-preview/remove/index.html @@ -0,0 +1,7 @@ +
+
+ + +
+

Удалите файл или скачайте его: «сервер» ответит через полсекунды.

+
diff --git a/examples/smart-components/file-preview/remove/index.js b/examples/smart-components/file-preview/remove/index.js new file mode 100644 index 00000000..e77eb09c --- /dev/null +++ b/examples/smart-components/file-preview/remove/index.js @@ -0,0 +1,27 @@ +// The "server" answers after a pause; the row goes only when it confirmed. +const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const api = { + deleteAttachment: async () => { await pause(500); return true; }, + downloadAttachment: (value) => `${value.fileName}, ${value.fileSize}`, +}; + +const initialize = async () => { + await customElements.whenDefined('sf-file-preview'); + const state = document.querySelector('#file-preview-remove-state'); + document.querySelectorAll('#file-preview-remove-list sf-file-preview').forEach((file) => { + file.onRemove(async (event) => { + state.textContent = `Удаляем «${event.detail.value.fileName}»…`; + if (await api.deleteAttachment(event.detail.value.href)) { + file.remove(); + state.textContent = `Файл «${event.detail.value.fileName}» удалён.`; + } + }); + // In this example the download goes nowhere: the page says what it would fetch. + file.onDownload((event) => { + event.preventDefault(); + state.textContent = `Скачали бы: ${api.downloadAttachment(event.detail.value)}`; + }); + }); +}; + +initialize(); diff --git a/examples/smart-components/page-header/favourite/index.html b/examples/smart-components/page-header/favourite/index.html new file mode 100644 index 00000000..cff05b17 --- /dev/null +++ b/examples/smart-components/page-header/favourite/index.html @@ -0,0 +1,7 @@ +
+ + + + +

Нажмите звезду: страница спросит «сервер» и покажет его ответ.

+
diff --git a/examples/smart-components/page-header/favourite/index.js b/examples/smart-components/page-header/favourite/index.js new file mode 100644 index 00000000..40f7e963 --- /dev/null +++ b/examples/smart-components/page-header/favourite/index.js @@ -0,0 +1,21 @@ +// The star shows only what the "server" saved: the page cancels the toggle, +// waits for the answer and sets star itself. Here the server is a pause. +const saveFavourite = (on) => new Promise((resolve) => setTimeout(() => resolve(on), 500)); + +const initialize = async () => { + await customElements.whenDefined('sf-header-page'); + const header = document.querySelector('#page-header-favourite'); + const state = document.querySelector('#page-header-favourite-state'); + if (!header || header.dataset.exampleReady === 'true') return; + header.dataset.exampleReady = 'true'; + + header.addEventListener('sf-header-page-toggle', async (event) => { + event.preventDefault(); + state.textContent = 'Сохраняем…'; + const saved = await saveFavourite(event.detail.on); + header.setAttribute('star', saved ? 'on' : 'off'); + state.textContent = saved ? 'Сервер сохранил: страница в избранном.' : 'Сервер сохранил: страница убрана из избранного.'; + }); +}; + +initialize(); diff --git a/examples/smart-components/site-header/sheet/index.css b/examples/smart-components/site-header/sheet/index.css new file mode 100644 index 00000000..5785eda2 --- /dev/null +++ b/examples/smart-components/site-header/sheet/index.css @@ -0,0 +1,4 @@ +/* Место под открытую панель в рамке примера. */ +.page-site-header-room { + min-block-size: var(--sf-g2); +} diff --git a/examples/smart-components/site-header/sheet/index.html b/examples/smart-components/site-header/sheet/index.html new file mode 100644 index 00000000..e9182913 --- /dev/null +++ b/examples/smart-components/site-header/sheet/index.html @@ -0,0 +1,11 @@ +
+ + SIMAI + +
+
+

Откройте меню: дерево документации появится в панели при первом открытии.

+
diff --git a/examples/smart-components/site-header/sheet/index.js b/examples/smart-components/site-header/sheet/index.js new file mode 100644 index 00000000..4de489e2 --- /dev/null +++ b/examples/smart-components/site-header/sheet/index.js @@ -0,0 +1,31 @@ +// The sheet is filled when the panel has opened, not with the page: a long +// documentation tree costs nothing until someone asks for it. +const buildDocumentationTree = () => { + const menu = document.createElement('sf-menu'); + menu.setAttribute('label', 'Документация'); + menu.setAttribute('items', JSON.stringify([ + {id: 'start', label: 'Начало работы', href: '#start'}, + {id: 'forms', label: 'Формы', href: '#forms'}, + {id: 'navigation', label: 'Навигация', href: '#navigation'}, + {id: 'overlays', label: 'Окна и панели', href: '#overlays'}, + ])); + return menu; +}; + +const initialize = async () => { + await customElements.whenDefined('sf-header-site'); + const header = document.querySelector('#site-header-sheet'); + const state = document.querySelector('#site-header-sheet-state'); + if (!header || header.dataset.exampleReady === 'true') return; + header.dataset.exampleReady = 'true'; + let opened = 0; + + header.addEventListener('sf-header-site-opened', () => { + opened += 1; + const sheet = header.querySelector('[slot="sheet"]'); + if (!sheet.childElementCount) sheet.replaceChildren(buildDocumentationTree()); + state.textContent = `Панель открыта ${opened} раз; дерево построено при первом открытии.`; + }); +}; + +initialize(); diff --git a/examples/smart-components/slider/from-code/index.html b/examples/smart-components/slider/from-code/index.html new file mode 100644 index 00000000..44e127d8 --- /dev/null +++ b/examples/smart-components/slider/from-code/index.html @@ -0,0 +1,12 @@ +
+ +

Выпуск документации

Справочник компонентов собран из манифестов выпуска.

+

Новая тема

Тёмная тема доступна во всех разделах сайта.

+

Встреча команды

Обсуждаем план работ на следующий квартал.

+
+
+ + + 1 из 3 +
+
diff --git a/examples/smart-components/slider/from-code/index.js b/examples/smart-components/slider/from-code/index.js new file mode 100644 index 00000000..d69b4503 --- /dev/null +++ b/examples/smart-components/slider/from-code/index.js @@ -0,0 +1,15 @@ +const initialize = async () => { + await customElements.whenDefined('sf-slider'); + const slider = document.querySelector('#slider-from-code'); + const counter = document.querySelector('#slider-from-code-counter'); + if (!slider || slider.dataset.exampleReady === 'true') return; + slider.dataset.exampleReady = 'true'; + + slider.addEventListener('change', (event) => { + counter.textContent = `${event.detail.realIndex + 1} из 3`; + }); + document.querySelector('#slider-from-code-next').addEventListener('click', () => slider.slideNext()); + document.querySelector('#slider-from-code-prev').addEventListener('click', () => slider.slidePrev()); +}; + +initialize(); diff --git a/examples/smart-components/tags/filter/index.html b/examples/smart-components/tags/filter/index.html new file mode 100644 index 00000000..69f1d5e6 --- /dev/null +++ b/examples/smart-components/tags/filter/index.html @@ -0,0 +1,15 @@ +
+
+ + + +
+
    +
  • Сетка и отступы в карточках
  • +
  • Подключение Framework через npm
  • +
  • Фокус в окнах и панелях
  • +
  • Цвета статусов в таблице
  • +
  • Свой шаблон смарт-компонента
  • +
+

Показаны все статьи: 5

+
diff --git a/examples/smart-components/tags/filter/index.js b/examples/smart-components/tags/filter/index.js new file mode 100644 index 00000000..7ada26b6 --- /dev/null +++ b/examples/smart-components/tags/filter/index.js @@ -0,0 +1,19 @@ +const chosen = new Set(); +const rows = [...document.querySelectorAll('#tags-filter-list li')]; +const state = document.querySelector('#tags-filter-state'); + +const applyFilter = (topic, active) => { + if (active) chosen.add(topic); else chosen.delete(topic); + let shown = 0; + rows.forEach((row) => { + row.hidden = chosen.size > 0 && !chosen.has(row.dataset.topic); + if (!row.hidden) shown += 1; + }); + state.textContent = chosen.size ? `Темы: ${[...chosen].join(', ')}; статей: ${shown}` : `Показаны все статьи: ${shown}`; +}; + +// One listener for the whole row: each tag reports its new state. +document.querySelector('.filters').addEventListener('change', (event) => { + if (event.target.localName !== 'sf-tag') return; + applyFilter(event.target.getAttribute('text'), event.detail.active); +}); diff --git a/examples/smart-components/tags/kinds/index.html b/examples/smart-components/tags/kinds/index.html index 37efede8..05e0183e 100644 --- a/examples/smart-components/tags/kinds/index.html +++ b/examples/smart-components/tags/kinds/index.html @@ -1,6 +1,6 @@
- + kind="checkbox"
From d41430e9becbbcdfe162f80f94d4a101256ea28b Mon Sep 17 00:00:00 2001 From: Rim Zabarov Date: Sun, 22 Nov 2026 01:49:45 +0300 Subject: [PATCH 4/6] Smart feedback, forms and navigation: live examples on 15 pages Alert action and close, progress bar/ring chunk() by a pretend upload, progress scale from script, skeleton replaced by content, toast undo, checkbox created from script, country code state, file upload import kept in memory (no IndexedDB in the frame), radio schedule field, switch with rollback, breadcrumbs router, contents change in a scrolling block, tabs goTo, popover focus on open. Tabs: goTo() answers an outcome and sends no sf-tabs-change (the standard's change is what a person did); the text said every switch sends it. Co-Authored-By: Claude Opus 5.5 --- content/ru/smart/feedback/alert.md | 3 + content/ru/smart/feedback/progress-bar.md | 6 ++ content/ru/smart/feedback/progress-ring.md | 3 + content/ru/smart/feedback/progress-scale.md | 6 +- content/ru/smart/feedback/skeleton.md | 6 ++ content/ru/smart/feedback/toast.md | 6 ++ content/ru/smart/forms/checkbox.md | 7 +++ content/ru/smart/forms/country-code.md | 3 + content/ru/smart/forms/file-upload.md | 7 +++ content/ru/smart/forms/radio.md | 6 ++ content/ru/smart/forms/switch.md | 6 ++ content/ru/smart/navigation/breadcrumbs.md | 6 ++ content/ru/smart/navigation/contents.md | 7 +++ content/ru/smart/navigation/tabs.md | 15 +++-- content/ru/smart/overlays/popover.md | 6 ++ .../country-code/smart-state/index.html | 8 +++ .../country-code/smart-state/index.js | 21 +++++++ .../components/tabs/smart-go-to/index.html | 11 ++++ examples/components/tabs/smart-go-to/index.js | 17 ++++++ .../smart-components/alert/actions/index.html | 4 ++ .../smart-components/alert/actions/index.js | 23 ++++++++ .../breadcrumbs/router/index.html | 7 +++ .../breadcrumbs/router/index.js | 22 +++++++ .../checkbox/from-code/index.html | 7 +++ .../checkbox/from-code/index.js | 27 +++++++++ .../contents/change/index.css | 28 +++++++++ .../contents/change/index.html | 26 +++++++++ .../smart-components/contents/change/index.js | 18 ++++++ .../file-upload/browser-import/index.html | 5 ++ .../file-upload/browser-import/index.js | 57 +++++++++++++++++++ .../popover/focus-field/index.html | 14 +++++ .../popover/focus-field/index.js | 25 ++++++++ .../progress-bar/upload/index.html | 6 ++ .../progress-bar/upload/index.js | 37 ++++++++++++ .../progress-ring/upload/index.html | 5 ++ .../progress-ring/upload/index.js | 27 +++++++++ .../progress-scale/steps/index.html | 8 +++ .../progress-scale/steps/index.js | 23 ++++++++ .../radio/schedule/index.html | 14 +++++ .../smart-components/radio/schedule/index.js | 14 +++++ .../skeleton/replace/index.html | 11 ++++ .../skeleton/replace/index.js | 28 +++++++++ .../smart-components/switch/apply/index.html | 12 ++++ .../smart-components/switch/apply/index.js | 29 ++++++++++ .../smart-components/toast/undo/index.html | 10 ++++ examples/smart-components/toast/undo/index.js | 31 ++++++++++ 46 files changed, 658 insertions(+), 10 deletions(-) create mode 100644 examples/components/country-code/smart-state/index.html create mode 100644 examples/components/country-code/smart-state/index.js create mode 100644 examples/components/tabs/smart-go-to/index.html create mode 100644 examples/components/tabs/smart-go-to/index.js create mode 100644 examples/smart-components/alert/actions/index.html create mode 100644 examples/smart-components/alert/actions/index.js create mode 100644 examples/smart-components/breadcrumbs/router/index.html create mode 100644 examples/smart-components/breadcrumbs/router/index.js create mode 100644 examples/smart-components/checkbox/from-code/index.html create mode 100644 examples/smart-components/checkbox/from-code/index.js create mode 100644 examples/smart-components/contents/change/index.css create mode 100644 examples/smart-components/contents/change/index.html create mode 100644 examples/smart-components/contents/change/index.js create mode 100644 examples/smart-components/file-upload/browser-import/index.html create mode 100644 examples/smart-components/file-upload/browser-import/index.js create mode 100644 examples/smart-components/popover/focus-field/index.html create mode 100644 examples/smart-components/popover/focus-field/index.js create mode 100644 examples/smart-components/progress-bar/upload/index.html create mode 100644 examples/smart-components/progress-bar/upload/index.js create mode 100644 examples/smart-components/progress-ring/upload/index.html create mode 100644 examples/smart-components/progress-ring/upload/index.js create mode 100644 examples/smart-components/progress-scale/steps/index.html create mode 100644 examples/smart-components/progress-scale/steps/index.js create mode 100644 examples/smart-components/radio/schedule/index.html create mode 100644 examples/smart-components/radio/schedule/index.js create mode 100644 examples/smart-components/skeleton/replace/index.html create mode 100644 examples/smart-components/skeleton/replace/index.js create mode 100644 examples/smart-components/switch/apply/index.html create mode 100644 examples/smart-components/switch/apply/index.js create mode 100644 examples/smart-components/toast/undo/index.html create mode 100644 examples/smart-components/toast/undo/index.js diff --git a/content/ru/smart/feedback/alert.md b/content/ru/smart/feedback/alert.md index 2056303a..2790e4d2 100644 --- a/content/ru/smart/feedback/alert.md +++ b/content/ru/smart/feedback/alert.md @@ -118,6 +118,9 @@ alert.onClose(() => saveDismissed('delivery-warning')); `onAction(handler)` передаёт обработчику значение действия, `detail` и само событие; `onClose(handler)` — `detail` и событие. +:::example {id="smart-components/alert/actions" label="Действие и закрытие" preview=sandbox log="sf-alert-action sf-alert-close" log_open=true} +::: + ### Создание из скрипта ```js diff --git a/content/ru/smart/feedback/progress-bar.md b/content/ru/smart/feedback/progress-bar.md index 6db256b7..5a8ee654 100644 --- a/content/ru/smart/feedback/progress-bar.md +++ b/content/ru/smart/feedback/progress-bar.md @@ -127,6 +127,12 @@ upload.addEventListener('load', () => { }); ``` +В примере загрузка ненастоящая: она так же сообщает `progress` и `load`, а +полоса получает их через `chunk()`. + +:::example {id="smart-components/progress-bar/upload" label="Ход загрузки" preview=sandbox} +::: + ## Доступность - С `meter` полоса — `role="meter"`: экранный диктор читает её как объём. diff --git a/content/ru/smart/feedback/progress-ring.md b/content/ru/smart/feedback/progress-ring.md index ddde69ad..609aa61b 100644 --- a/content/ru/smart/feedback/progress-ring.md +++ b/content/ru/smart/feedback/progress-ring.md @@ -110,6 +110,9 @@ ring.setAttribute('status', 'success'); ring.setAttribute('value-text', 'Файлы загружены'); ``` +:::example {id="smart-components/progress-ring/upload" label="Файл за файлом" preview=sandbox} +::: + ### Кольцо вокруг картинки Кольцо вокруг аватара показывает долю и оставляет картинку на месте: кольцо diff --git a/content/ru/smart/feedback/progress-scale.md b/content/ru/smart/feedback/progress-scale.md index abbbac8f..9e1a49cc 100644 --- a/content/ru/smart/feedback/progress-scale.md +++ b/content/ru/smart/feedback/progress-scale.md @@ -99,10 +99,8 @@ description: "Показывает известный ход процесса ш Меняйте `value`: шкала обновляется без перерисовки. Текущее значение читайте из `value`. -```js -const scale = document.querySelector('sf-progress-scale'); -scale.setAttribute('value', String(completedSteps * 20)); -``` +:::example {id="smart-components/progress-scale/steps" label="Шаги профиля" preview=sandbox} +::: ## Доступность diff --git a/content/ru/smart/feedback/skeleton.md b/content/ru/smart/feedback/skeleton.md index e4c91005..86806426 100644 --- a/content/ru/smart/feedback/skeleton.md +++ b/content/ru/smart/feedback/skeleton.md @@ -101,6 +101,12 @@ region.replaceChildren(renderAuthor(author)); region.removeAttribute('aria-busy'); ``` +В примере ответ приходит через полторы секунды; кнопка возвращает скелетон и +загружает карточку снова. + +:::example {id="smart-components/skeleton/replace" label="Карточка после ответа" preview=sandbox} +::: + ## Доступность - Фигуры скрыты от экранного диктора и не получают фокус: они ничего не diff --git a/content/ru/smart/feedback/toast.md b/content/ru/smart/feedback/toast.md index 1c7724c0..ea9383dc 100644 --- a/content/ru/smart/feedback/toast.md +++ b/content/ru/smart/feedback/toast.md @@ -96,6 +96,12 @@ toast.onAction((action) => { toast.onClose(() => console.log('Сообщение закрыто')); ``` +В примере «Вернуть» возвращает удалённый файл в список, пока сообщение на +экране. + +:::example {id="smart-components/toast/undo" label="Отмена удаления" preview=sandbox log="sf-toast-action sf-toast-close" log_console=true log_open=true} +::: + `closable="false"` убирает кнопку закрытия; закрыть такое сообщение может только таймер или метод `close()`. diff --git a/content/ru/smart/forms/checkbox.md b/content/ru/smart/forms/checkbox.md index 7d952924..ba3b76ff 100644 --- a/content/ru/smart/forms/checkbox.md +++ b/content/ru/smart/forms/checkbox.md @@ -154,6 +154,13 @@ await terms.whenRendered(); terms.setChecked(false); ``` +В примере флажок создан из скрипта: отметка открывает кнопку «Продолжить» +по событию `change`, а снятие отметки из кода события не отправляет, поэтому +кнопку закрывает сама страница. + +:::example {id="smart-components/checkbox/from-code" label="Флажок из скрипта" preview=sandbox log="change" log_open=false} +::: + ## Доступность - Каждому флажку нужно доступное имя: видимый `label` или, если подписи нет, diff --git a/content/ru/smart/forms/country-code.md b/content/ru/smart/forms/country-code.md index 66c4f979..aa412120 100644 --- a/content/ru/smart/forms/country-code.md +++ b/content/ru/smart/forms/country-code.md @@ -181,6 +181,9 @@ phone.addEventListener('change', () => { phone.setState({iso2: 'KZ'}); ``` +:::example {id="components/country-code/smart-state" label="Номер и страна из кода" preview=sandbox log="change" log_open=false} +::: + ## Доступность - Задайте видимую подпись в `label`: компонент связывает её с полем номера. diff --git a/content/ru/smart/forms/file-upload.md b/content/ru/smart/forms/file-upload.md index 80bbf31e..df2392e1 100644 --- a/content/ru/smart/forms/file-upload.md +++ b/content/ru/smart/forms/file-upload.md @@ -275,6 +275,13 @@ async function store(item) { повтора называет файл: человек читает, почему не получилось, и нажимает «Повторить», чтобы отправить тот же файл ещё раз. +В примере у рамки документации нет IndexedDB, поэтому `put()` держит файлы +в памяти; остальное — как в коде выше. Включите «Хранилище переполнено», +выберите файл, затем выключите переключатель и нажмите «Повторить». + +:::example {id="smart-components/file-upload/browser-import" label="Импорт без сервера" preview=sandbox log="sf-file-upload-attached sf-file-upload-retry sf-file-upload-detach" log_open=true} +::: + ## Доступность - Зона — кнопка с одной остановкой `Tab`; `Enter` или `Space` открывают diff --git a/content/ru/smart/forms/radio.md b/content/ru/smart/forms/radio.md index 3fe85c57..92d8fbc6 100644 --- a/content/ru/smart/forms/radio.md +++ b/content/ru/smart/forms/radio.md @@ -122,6 +122,12 @@ publish.addEventListener('change', (event) => { document.querySelector('sf-radio[value="draft"]').setChecked(true); ``` +В примере «По расписанию» показывает поле даты. Кнопка под группой отмечает +черновик из кода: `change` при этом нет, и поле прячет сама страница. + +:::example {id="smart-components/radio/schedule" label="Поле по выбору" preview=sandbox log="change" log_open=false} +::: + ## Доступность - Каждой радиокнопке нужно видимое название в `label`: отдельного diff --git a/content/ru/smart/forms/switch.md b/content/ru/smart/forms/switch.md index 3af2437b..1ec18aee 100644 --- a/content/ru/smart/forms/switch.md +++ b/content/ru/smart/forms/switch.md @@ -126,6 +126,12 @@ compact.addEventListener('change', async (event) => { }); ``` +В примере компактный режим сразу уплотняет список. Включите «Сервер не +отвечает»: сохранение не удастся, и переключатель со списком вернутся. + +:::example {id="smart-components/switch/apply" label="Настройка с откатом" preview=sandbox} +::: + ## Доступность - Переключателю нужно название: видимое в `label` или, если подпись выводит diff --git a/content/ru/smart/navigation/breadcrumbs.md b/content/ru/smart/navigation/breadcrumbs.md index ea62598f..2b2c46a9 100644 --- a/content/ru/smart/navigation/breadcrumbs.md +++ b/content/ru/smart/navigation/breadcrumbs.md @@ -124,6 +124,12 @@ crumbs.onItemClick((item) => { }); ``` +В примере пункты пути заданы через `value` без `href`, а маленький роутер +страницы показывает выбранный раздел без перезагрузки. + +:::example {id="smart-components/breadcrumbs/router" label="Переход без перезагрузки" preview=sandbox log="sf-breadcrumbs-press" log_open=false} +::: + ## Доступность - Корень — ориентир `nav` с доступным именем. На русской странице имя по diff --git a/content/ru/smart/navigation/contents.md b/content/ru/smart/navigation/contents.md index 95da0a6b..2ddfe183 100644 --- a/content/ru/smart/navigation/contents.md +++ b/content/ru/smart/navigation/contents.md @@ -224,6 +224,13 @@ contents.addEventListener('sf-contents-change', ({detail}) => { }); ``` +В примере разделы прокручиваются в своём блоке, а строка под ним собирает +прочитанные разделы по `sf-contents-change` — так их получила бы +аналитика. + +:::example {id="smart-components/contents/change" label="Смена раздела" preview=sandbox log="sf-contents-change" log_open=false} +::: + ### Переход к разделу и адрес Выбранная ссылка плавно прокручивает страницу к разделу (без плавности, если diff --git a/content/ru/smart/navigation/tabs.md b/content/ru/smart/navigation/tabs.md index 311a6b23..d3c89dbf 100644 --- a/content/ru/smart/navigation/tabs.md +++ b/content/ru/smart/navigation/tabs.md @@ -280,17 +280,20 @@ tabs.setItems([ ### Переключение из кода `goTo(index)` открывает вкладку по номеру в объявленном списке, считая с нуля, — и после того, как человек переставил вкладки; на недоступную вкладку он не переключает. -При переключении элемент отправляет всплывающее событие `sf-tabs-change` с +Он отвечает исходом — `{outcome: 'applied'}` или `{outcome: 'refused', reason}` +— и события не отправляет: `sf-tabs-change` сообщает о том, что сделал +человек. Когда вкладку переключает человек, элемент отправляет всплывающее +событие `sf-tabs-change` с `detail.previous`, `detail.current`, `detail.item` и `detail.items`. `previous` и `current` — номера в объявленном списке, `item` — пункт целиком, с `key`, `label` и `count`. `onTabChange(handler)` подписывается на событие и передаёт обработчику номер новой вкладки первым аргументом. -```js -const tabs = document.querySelector('sf-tabs'); -tabs.onTabChange((current) => console.log('Открыта вкладка', current)); -tabs.goTo(2); -``` +В примере кнопка вызывает `goTo(2)` и показывает его исход, а щелчок по +вкладке приходит в `onTabChange`. + +:::example {id="components/tabs/smart-go-to" label="Вкладка из кода" preview=sandbox log="sf-tabs-change" log_open=true} +::: Если вкладку нужно хранить не в `#`, а в параметре адреса, её пишут в адрес по `key` и читают обратно. Стрелки переключают вкладки на каждое diff --git a/content/ru/smart/overlays/popover.md b/content/ru/smart/overlays/popover.md index 641c86d0..165910fe 100644 --- a/content/ru/smart/overlays/popover.md +++ b/content/ru/smart/overlays/popover.md @@ -112,6 +112,12 @@ popover.addEventListener('sf-popover-closed', () => { }); ``` +В примере поле поиска получает фокус, когда поверхность открылась, а список +фильтруется, когда она закрылась. + +:::example {id="smart-components/popover/focus-field" label="Фокус в поле при открытии" preview=sandbox log="sf-popover-opened sf-popover-closed" log_open=false} +::: + ## Доступность - Поверхности нужно доступное имя: `label` на `` передаётся ей diff --git a/examples/components/country-code/smart-state/index.html b/examples/components/country-code/smart-state/index.html new file mode 100644 index 00000000..7ac647d8 --- /dev/null +++ b/examples/components/country-code/smart-state/index.html @@ -0,0 +1,8 @@ +
+ +
+ + +
+

Сохранится: номер и страна после изменения.

+
diff --git a/examples/components/country-code/smart-state/index.js b/examples/components/country-code/smart-state/index.js new file mode 100644 index 00000000..bfa16184 --- /dev/null +++ b/examples/components/country-code/smart-state/index.js @@ -0,0 +1,21 @@ +const saved = []; +const savePhone = (phone) => saved.push(phone); + +const initialize = async () => { + await customElements.whenDefined('sf-input-country'); + const phone = document.querySelector('sf-input-country[name="phone"]'); + const state = document.querySelector('#country-smart-state'); + if (!phone || phone.dataset.exampleReady === 'true') return; + phone.dataset.exampleReady = 'true'; + + // A typed number, a chosen country and setState() all end with change. + phone.addEventListener('change', () => { + const {value, iso2, dialCode} = phone.state; + savePhone({value, iso2, dialCode}); + state.textContent = `Сохранено: ${value} (${iso2}, ${dialCode})`; + }); + document.querySelector('#country-smart-de').addEventListener('click', () => phone.setState({iso2: 'DE'})); + document.querySelector('#country-smart-fr').addEventListener('click', () => phone.setState({iso2: 'FR'})); +}; + +initialize(); diff --git a/examples/components/tabs/smart-go-to/index.html b/examples/components/tabs/smart-go-to/index.html new file mode 100644 index 00000000..83356b17 --- /dev/null +++ b/examples/components/tabs/smart-go-to/index.html @@ -0,0 +1,11 @@ +
+ +

Краткая информация о проекте.

+

Участники и роли команды.

+

Последние изменения проекта.

+
+
+ + Щёлкните вкладку или нажмите кнопку +
+
diff --git a/examples/components/tabs/smart-go-to/index.js b/examples/components/tabs/smart-go-to/index.js new file mode 100644 index 00000000..a83e8d15 --- /dev/null +++ b/examples/components/tabs/smart-go-to/index.js @@ -0,0 +1,17 @@ +const initialize = async () => { + await customElements.whenDefined('sf-tabs'); + const tabs = document.querySelector('#tabs-go-to'); + const state = document.querySelector('#tabs-go-to-state'); + if (!tabs || tabs.dataset.exampleReady === 'true') return; + tabs.dataset.exampleReady = 'true'; + + // A person's switch: the handler gets the number of the new tab. + tabs.onTabChange((current) => { state.textContent = `Человек открыл вкладку ${current}`; }); + // goTo() answers with an outcome and sends no event. + document.querySelector('#tabs-go-to-history').addEventListener('click', () => { + const {outcome, reason} = tabs.goTo(2); + state.textContent = `goTo(2): ${outcome}${reason ? `, ${reason}` : ''}`; + }); +}; + +initialize(); diff --git a/examples/smart-components/alert/actions/index.html b/examples/smart-components/alert/actions/index.html new file mode 100644 index 00000000..5195bbdc --- /dev/null +++ b/examples/smart-components/alert/actions/index.html @@ -0,0 +1,4 @@ +
+ +

Нажмите «Изменить адрес» или закройте сообщение.

+
diff --git a/examples/smart-components/alert/actions/index.js b/examples/smart-components/alert/actions/index.js new file mode 100644 index 00000000..6ad1aa98 --- /dev/null +++ b/examples/smart-components/alert/actions/index.js @@ -0,0 +1,23 @@ +// The message stays where it is: the page does the action. Closing is +// remembered in memory here; a site would keep it for the person. +const dismissed = new Set(); +const saveDismissed = (key) => dismissed.add(key); + +const initialize = async () => { + await customElements.whenDefined('sf-alert'); + const alert = document.querySelector('#alert-actions'); + const state = document.querySelector('#alert-actions-state'); + if (!alert || alert.dataset.exampleReady === 'true') return; + alert.dataset.exampleReady = 'true'; + + const openAddressForm = () => { state.textContent = 'Страница открыла бы форму адреса.'; }; + alert.onAction((action) => { + if (action === 'edit-address') openAddressForm(); + }); + alert.onClose(() => { + saveDismissed('delivery-warning'); + state.textContent = `Сообщение закрыто; запомнено: ${[...dismissed].join(', ')}`; + }); +}; + +initialize(); diff --git a/examples/smart-components/breadcrumbs/router/index.html b/examples/smart-components/breadcrumbs/router/index.html new file mode 100644 index 00000000..ce9c0692 --- /dev/null +++ b/examples/smart-components/breadcrumbs/router/index.html @@ -0,0 +1,7 @@ +
+ +
+ + +
+
diff --git a/examples/smart-components/breadcrumbs/router/index.js b/examples/smart-components/breadcrumbs/router/index.js new file mode 100644 index 00000000..915e386e --- /dev/null +++ b/examples/smart-components/breadcrumbs/router/index.js @@ -0,0 +1,22 @@ +// A tiny single-page router: items with value and no href are buttons, and +// the page itself shows the section. +const sections = {home: 'Главная', catalog: 'Каталог', light: 'Освещение'}; +const router = { + navigate(value) { + document.querySelector('#breadcrumbs-router-title').textContent = sections[value] ?? value; + document.querySelector('#breadcrumbs-router-text').textContent = `Раздел «${sections[value] ?? value}» открыт роутером страницы, адрес документа не менялся.`; + }, +}; + +const initialize = async () => { + await customElements.whenDefined('sf-breadcrumbs'); + const crumbs = document.querySelector('#breadcrumbs-router'); + if (!crumbs || crumbs.dataset.exampleReady === 'true') return; + crumbs.dataset.exampleReady = 'true'; + crumbs.onItemClick((item) => { + if (item.href || item.ellipsis) return; + router.navigate(item.value); + }); +}; + +initialize(); diff --git a/examples/smart-components/checkbox/from-code/index.html b/examples/smart-components/checkbox/from-code/index.html new file mode 100644 index 00000000..f7d0c3fa --- /dev/null +++ b/examples/smart-components/checkbox/from-code/index.html @@ -0,0 +1,7 @@ +
+

Условия сервиса: оплата раз в месяц, отменить можно в любой день.

+
+ + +
+
diff --git a/examples/smart-components/checkbox/from-code/index.js b/examples/smart-components/checkbox/from-code/index.js new file mode 100644 index 00000000..7c57c1d9 --- /dev/null +++ b/examples/smart-components/checkbox/from-code/index.js @@ -0,0 +1,27 @@ +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +const start = async () => { + const SF = await sfReady(); + const form = document.querySelector('#checkbox-from-code-form'); + const submit = document.querySelector('#checkbox-from-code-submit'); + if (form.dataset.exampleReady === 'true') return; + form.dataset.exampleReady = 'true'; + + // A person's tick sends change: the button follows it. + const terms = await SF.createAsync('checkbox', { + name: 'terms', + value: 'accepted', + label: 'Принимаю условия', + onChange: (event) => submit.toggleAttribute('disabled', !event.target.checked), + }); + form.prepend(terms); + await terms.whenRendered(); + + // setChecked() sends no change, so the page updates the button itself. + document.querySelector('#checkbox-from-code-reset').addEventListener('click', () => { + terms.setChecked(false); + submit.toggleAttribute('disabled', true); + }); +}; + +start(); diff --git a/examples/smart-components/contents/change/index.css b/examples/smart-components/contents/change/index.css new file mode 100644 index 00000000..9ca4b557 --- /dev/null +++ b/examples/smart-components/contents/change/index.css @@ -0,0 +1,28 @@ +/* Разделы прокручиваются в своём блоке: в рамке документации окно примера + не прокручивается, а оглавление следит за ближайшим прокручиваемым предком. + Оглавление стоит в начале строки; на узкой ширине оно переносится над + статьёй. */ +.page-contents-box { + display: flex; + flex-wrap: wrap; + align-items: flex-start; + gap: var(--sf-space-3); + block-size: var(--sf-g0); + overflow: auto; + padding-inline: var(--sf-space-2); + border: var(--sf-px) solid var(--sf-outline-variant); + border-radius: var(--sf-radius--ui); +} +.page-contents-article { + flex: 1 1 var(--sf-g0); + min-inline-size: 0; +} +.page-contents-box > aside { + flex: 0 0 auto; +} +.page-contents-article h2 { + margin-block: var(--sf-space-2) var(--sf-space-1); +} +.page-contents-article p { + margin-block: 0 var(--sf-space-1); +} diff --git a/examples/smart-components/contents/change/index.html b/examples/smart-components/contents/change/index.html new file mode 100644 index 00000000..2794f2da --- /dev/null +++ b/examples/smart-components/contents/change/index.html @@ -0,0 +1,26 @@ +
+
+ +
+

Введение

+

Компонент берёт данные из манифеста, рисует начальный вид без кода и оживает, когда код загрузится.

+

Страница задаёт только настройки и содержимое; всё остальное компонент делает сам.

+

Прокрутите этот блок: оглавление отметит раздел, а страница узнает о смене.

+

Подключение

+

Компонент берёт данные из манифеста, рисует начальный вид без кода и оживает, когда код загрузится.

+

Страница задаёт только настройки и содержимое; всё остальное компонент делает сам.

+

Прокрутите этот блок: оглавление отметит раздел, а страница узнает о смене.

+

События

+

Компонент берёт данные из манифеста, рисует начальный вид без кода и оживает, когда код загрузится.

+

Страница задаёт только настройки и содержимое; всё остальное компонент делает сам.

+

Прокрутите этот блок: оглавление отметит раздел, а страница узнает о смене.

+

Доступность

+

Компонент берёт данные из манифеста, рисует начальный вид без кода и оживает, когда код загрузится.

+

Страница задаёт только настройки и содержимое; всё остальное компонент делает сам.

+

Прокрутите этот блок: оглавление отметит раздел, а страница узнает о смене.

+
+
+

Прочитанные разделы: —

+
diff --git a/examples/smart-components/contents/change/index.js b/examples/smart-components/contents/change/index.js new file mode 100644 index 00000000..8a8a3a07 --- /dev/null +++ b/examples/smart-components/contents/change/index.js @@ -0,0 +1,18 @@ +// What a page could send to analytics: the sections read, in order. +const read = []; +const analytics = {track: (name, id) => read.push(id)}; + +const initialize = async () => { + await customElements.whenDefined('sf-contents'); + const contents = document.querySelector('#contents-change'); + const state = document.querySelector('#contents-change-state'); + if (!contents || contents.dataset.exampleReady === 'true') return; + contents.dataset.exampleReady = 'true'; + + contents.addEventListener('sf-contents-change', ({detail}) => { + analytics.track('section', detail.id); + state.textContent = `Прочитанные разделы: ${read.map((id) => document.getElementById(id)?.textContent).join(' → ')}`; + }); +}; + +initialize(); diff --git a/examples/smart-components/file-upload/browser-import/index.html b/examples/smart-components/file-upload/browser-import/index.html new file mode 100644 index 00000000..bd378b4d --- /dev/null +++ b/examples/smart-components/file-upload/browser-import/index.html @@ -0,0 +1,5 @@ +
+ + +

+
diff --git a/examples/smart-components/file-upload/browser-import/index.js b/examples/smart-components/file-upload/browser-import/index.js new file mode 100644 index 00000000..e84ed3d9 --- /dev/null +++ b/examples/smart-components/file-upload/browser-import/index.js @@ -0,0 +1,57 @@ +// Only for this example: the documentation frame has no IndexedDB (its +// origin is opaque), so put() keeps the files in memory. On a site put() +// writes them into IndexedDB; the component part is the same. +const kept = new Map(); +const full = () => document.querySelector('sf-switch[name="full"] input')?.checked; +const put = (id, file) => new Promise((resolve, reject) => setTimeout(() => { + if (full()) reject(new Error('Хранилище переполнено')); + else { kept.set(id, file); resolve(); } +}, 500)); + +const initialize = async () => { + await customElements.whenDefined('sf-file-upload'); + const upload = document.querySelector('sf-file-upload'); + const state = document.querySelector('#file-upload-import-state'); + if (!upload || upload.dataset.exampleReady === 'true') return; + upload.dataset.exampleReady = 'true'; + const items = new Map(); // id → item + + const report = () => { + state.textContent = `Сохранено файлов: ${kept.size}`; + }; + + async function store(item) { + const next = {...item, state: 'process', progress: 10}; + items.set(item.id, next); + upload.setItems([...items.values()]); // the bar moves + try { + if (item.file.size > 5 * 1024 * 1024) throw new Error('Файл больше 5 МБ'); + await put(item.id, item.file); + items.set(item.id, {...next, state: 'done', progress: 100}); + } catch (error) { + items.set(item.id, {...next, state: 'error', errorMessage: error.message}); + } + upload.setItems([...items.values()]); + report(); + } + + upload.addEventListener('sf-file-upload-attached', async (event) => { + const item = {...event.detail.item}; + items.set(item.id, item); + await store(item); + }); + + upload.addEventListener('sf-file-upload-retry', (event) => { + const item = items.get(event.detail.item.id); + if (item) store({...item, state: 'process', progress: 0}); + }); + + upload.addEventListener('sf-file-upload-detach', (event) => { + const id = event.detail.item?.id ?? event.detail.id; + items.delete(id); + kept.delete(id); + report(); + }); +}; + +initialize(); diff --git a/examples/smart-components/popover/focus-field/index.html b/examples/smart-components/popover/focus-field/index.html new file mode 100644 index 00000000..c283ec40 --- /dev/null +++ b/examples/smart-components/popover/focus-field/index.html @@ -0,0 +1,14 @@ +
+ + +
+ +
+
+
    +
  • Подготовить договор с поставщиком
  • +
  • Согласовать макет главной страницы
  • +
  • Перенести архив заказов
  • +
  • Обновить прайс-лист
  • +
+
diff --git a/examples/smart-components/popover/focus-field/index.js b/examples/smart-components/popover/focus-field/index.js new file mode 100644 index 00000000..e9bad0ce --- /dev/null +++ b/examples/smart-components/popover/focus-field/index.js @@ -0,0 +1,25 @@ +const rows = [...document.querySelectorAll('#popover-focus-list li')]; + +const initialize = async () => { + await customElements.whenDefined('sf-popover'); + const popover = document.querySelector('#popover-focus-field'); + if (!popover || popover.dataset.exampleReady === 'true') return; + popover.dataset.exampleReady = 'true'; + const field = () => popover.querySelector('[slot="content"] input'); + + const applyFilter = () => { + const query = (field()?.value ?? '').trim().toLowerCase(); + rows.forEach((row) => { row.hidden = Boolean(query) && !row.textContent.toLowerCase().includes(query); }); + }; + + // The person opened the surface to type: the field takes the focus. + popover.addEventListener('sf-popover-opened', () => { + field()?.focus(); + }); + // The filter applies when the surface closes. + popover.addEventListener('sf-popover-closed', () => { + applyFilter(); + }); +}; + +initialize(); diff --git a/examples/smart-components/progress-bar/upload/index.html b/examples/smart-components/progress-bar/upload/index.html new file mode 100644 index 00000000..6ea82de2 --- /dev/null +++ b/examples/smart-components/progress-bar/upload/index.html @@ -0,0 +1,6 @@ +
+ +
+ +
+
diff --git a/examples/smart-components/progress-bar/upload/index.js b/examples/smart-components/progress-bar/upload/index.js new file mode 100644 index 00000000..4d2f2096 --- /dev/null +++ b/examples/smart-components/progress-bar/upload/index.js @@ -0,0 +1,37 @@ +// A pretend upload: it reports progress and load like XMLHttpRequest.upload. +const fakeUpload = () => { + const upload = new EventTarget(); + const total = 12 * 1024 * 1024; + let loaded = 0; + const step = () => { + loaded = Math.min(total, loaded + total / 8); + upload.dispatchEvent(Object.assign(new Event('progress'), {loaded, total})); + if (loaded < total) setTimeout(step, 250); else upload.dispatchEvent(new Event('load')); + }; + setTimeout(step, 250); + return upload; +}; + +const initialize = async () => { + await customElements.whenDefined('sf-progress-bar'); + const progress = document.querySelector('#progress-bar-upload'); + const start = document.querySelector('#progress-bar-upload-start'); + if (!progress || progress.dataset.exampleReady === 'true') return; + progress.dataset.exampleReady = 'true'; + + start.addEventListener('click', () => { + progress.removeAttribute('status'); + progress.removeAttribute('value-text'); + progress.setAttribute('value', '0'); + const upload = fakeUpload(); + upload.addEventListener('progress', (event) => { + progress.chunk({done: event.loaded, total: event.total}); + }); + upload.addEventListener('load', () => { + progress.setAttribute('status', 'success'); + progress.setAttribute('value-text', 'Файлы загружены'); + }); + }); +}; + +initialize(); diff --git a/examples/smart-components/progress-ring/upload/index.html b/examples/smart-components/progress-ring/upload/index.html new file mode 100644 index 00000000..40fa226c --- /dev/null +++ b/examples/smart-components/progress-ring/upload/index.html @@ -0,0 +1,5 @@ +
+ + + +
diff --git a/examples/smart-components/progress-ring/upload/index.js b/examples/smart-components/progress-ring/upload/index.js new file mode 100644 index 00000000..79ba8273 --- /dev/null +++ b/examples/smart-components/progress-ring/upload/index.js @@ -0,0 +1,27 @@ +// Each file is a pretend upload of a third of a second. +const files = ['Договор.pdf', 'Смета.xlsx', 'План.png', 'Акт.docx']; +const upload = () => new Promise((resolve) => setTimeout(resolve, 350)); + +const initialize = async () => { + await customElements.whenDefined('sf-progress-ring'); + const ring = document.querySelector('#progress-ring-upload'); + const state = document.querySelector('#progress-ring-upload-state'); + if (!ring || ring.dataset.exampleReady === 'true') return; + ring.dataset.exampleReady = 'true'; + + document.querySelector('#progress-ring-upload-start').addEventListener('click', async () => { + ring.removeAttribute('status'); + ring.removeAttribute('value-text'); + ring.setAttribute('value', '0'); + for (const [index, file] of files.entries()) { + state.textContent = `Загружается ${file}`; + await upload(file); + ring.chunk({done: index + 1, total: files.length}); + } + ring.setAttribute('status', 'success'); + ring.setAttribute('value-text', 'Файлы загружены'); + state.textContent = 'Файлы загружены'; + }); +}; + +initialize(); diff --git a/examples/smart-components/progress-scale/steps/index.html b/examples/smart-components/progress-scale/steps/index.html new file mode 100644 index 00000000..ef955218 --- /dev/null +++ b/examples/smart-components/progress-scale/steps/index.html @@ -0,0 +1,8 @@ +
+ +
+ + + Выполнено шагов: 1 из 5 +
+
diff --git a/examples/smart-components/progress-scale/steps/index.js b/examples/smart-components/progress-scale/steps/index.js new file mode 100644 index 00000000..b36a3bdd --- /dev/null +++ b/examples/smart-components/progress-scale/steps/index.js @@ -0,0 +1,23 @@ +const initialize = async () => { + await customElements.whenDefined('sf-progress-scale'); + const scale = document.querySelector('#progress-scale-steps'); + const state = document.querySelector('#progress-scale-steps-state'); + if (!scale || scale.dataset.exampleReady === 'true') return; + scale.dataset.exampleReady = 'true'; + let completedSteps = 1; + + const show = () => { + scale.setAttribute('value', String(completedSteps * 20)); + state.textContent = completedSteps === 5 ? 'Профиль заполнен' : `Выполнено шагов: ${completedSteps} из 5`; + }; + document.querySelector('#progress-scale-steps-next').addEventListener('click', () => { + completedSteps = Math.min(5, completedSteps + 1); + show(); + }); + document.querySelector('#progress-scale-steps-reset').addEventListener('click', () => { + completedSteps = 0; + show(); + }); +}; + +initialize(); diff --git a/examples/smart-components/radio/schedule/index.html b/examples/smart-components/radio/schedule/index.html new file mode 100644 index 00000000..3be2d1f4 --- /dev/null +++ b/examples/smart-components/radio/schedule/index.html @@ -0,0 +1,14 @@ +
+
+ Когда опубликовать? +
+ + + +
+
+ +
+ +
+
diff --git a/examples/smart-components/radio/schedule/index.js b/examples/smart-components/radio/schedule/index.js new file mode 100644 index 00000000..d7c2aaf0 --- /dev/null +++ b/examples/smart-components/radio/schedule/index.js @@ -0,0 +1,14 @@ +const field = document.querySelector('#radio-schedule-field'); +const showSchedule = (visible) => { field.hidden = !visible; }; + +// The person's choice sends change, heard on the fieldset. +document.querySelector('#radio-schedule-group').addEventListener('change', (event) => { + showSchedule(event.target.value === 'later'); +}); + +// setChecked() sends no change, so the page updates its own field. +document.querySelector('#radio-schedule-draft').addEventListener('click', async () => { + await customElements.whenDefined('sf-radio'); + document.querySelector('sf-radio[value="draft"]').setChecked(true); + showSchedule(false); +}); diff --git a/examples/smart-components/skeleton/replace/index.html b/examples/smart-components/skeleton/replace/index.html new file mode 100644 index 00000000..0096c97b --- /dev/null +++ b/examples/smart-components/skeleton/replace/index.html @@ -0,0 +1,11 @@ +
+
+ +
+ +
+
+
+ +
+
diff --git a/examples/smart-components/skeleton/replace/index.js b/examples/smart-components/skeleton/replace/index.js new file mode 100644 index 00000000..59bea1a3 --- /dev/null +++ b/examples/smart-components/skeleton/replace/index.js @@ -0,0 +1,28 @@ +// A pretend request answers after a second and a half; the skeleton holds +// the place of the card until then. +const api = {getAuthor: () => new Promise((resolve) => setTimeout(() => resolve({name: 'Анна Смирнова', role: 'Редактор раздела «Формы»', articles: 12}), 1500))}; + +const renderAuthor = (author) => { + const card = document.createElement('div'); + card.className = 'flex gap-3 items-cross-center'; + card.innerHTML = '
'; + card.querySelector('sf-avatar').setAttribute('text', author.name.split(' ').map((part) => part[0]).join('')); + card.querySelector('strong').textContent = author.name; + card.querySelector('span').textContent = author.role; + card.querySelectorAll('span')[1].textContent = `Статей: ${author.articles}`; + return card; +}; + +const region = document.querySelector('#skeleton-replace-author'); +const placeholder = [...region.children].map((node) => node.cloneNode(true)); + +const load = async () => { + region.replaceChildren(...placeholder.map((node) => node.cloneNode(true))); + region.setAttribute('aria-busy', 'true'); + const author = await api.getAuthor(); + region.replaceChildren(renderAuthor(author)); + region.removeAttribute('aria-busy'); +}; + +document.querySelector('#skeleton-replace-again').addEventListener('click', load); +load(); diff --git a/examples/smart-components/switch/apply/index.html b/examples/smart-components/switch/apply/index.html new file mode 100644 index 00000000..4aab4094 --- /dev/null +++ b/examples/smart-components/switch/apply/index.html @@ -0,0 +1,12 @@ +
+
+ + +
+
    +
  • Отчёт за ноябрь
  • +
  • Договор поставки
  • +
  • Смета на ремонт
  • +
+

+
diff --git a/examples/smart-components/switch/apply/index.js b/examples/smart-components/switch/apply/index.js new file mode 100644 index 00000000..d9140c29 --- /dev/null +++ b/examples/smart-components/switch/apply/index.js @@ -0,0 +1,29 @@ +const list = document.querySelector('#switch-apply-list'); +const state = document.querySelector('#switch-apply-state'); +const offline = () => document.querySelector('sf-switch[name="offline"] input').checked; + +// A pretend server: it saves after a pause or refuses while "offline". +const saveSetting = (name, enabled) => new Promise((resolve, reject) => { + setTimeout(() => (offline() ? reject(new Error('offline')) : resolve({name, enabled})), 400); +}); +const apply = (enabled) => list.classList.replace(enabled ? 'gap-2' : 'gap-1/3', enabled ? 'gap-1/3' : 'gap-2'); + +const initialize = async () => { + await customElements.whenDefined('sf-switch'); + const compact = document.querySelector('sf-switch[name="compact"]'); + compact.addEventListener('change', async (event) => { + const enabled = event.target.checked; + apply(enabled); + try { + await saveSetting('compact', enabled); + state.textContent = enabled ? 'Компактный режим сохранён.' : 'Обычный режим сохранён.'; + } catch { + // Not saved: the switch and the list go back. + compact.setChecked(!enabled); + apply(!enabled); + state.textContent = 'Не удалось сохранить: настройка возвращена.'; + } + }); +}; + +initialize(); diff --git a/examples/smart-components/toast/undo/index.html b/examples/smart-components/toast/undo/index.html new file mode 100644 index 00000000..d87c33f4 --- /dev/null +++ b/examples/smart-components/toast/undo/index.html @@ -0,0 +1,10 @@ +
+
    +
  • Договор.pdf
  • +
  • Смета.xlsx
  • +
+
+ +
+
+
diff --git a/examples/smart-components/toast/undo/index.js b/examples/smart-components/toast/undo/index.js new file mode 100644 index 00000000..8cd8a311 --- /dev/null +++ b/examples/smart-components/toast/undo/index.js @@ -0,0 +1,31 @@ +// The container is the live region; each toast removes itself when closed. +// The page keeps the deleted file until the toast is gone, so «Вернуть» +// can put it back. +const list = document.querySelector('#toast-undo-files'); +const container = document.querySelector('#toast-undo-container'); +const button = document.querySelector('#toast-undo-delete'); + +button.addEventListener('click', async () => { + const file = list.firstElementChild; + if (!file) return; + file.remove(); + await customElements.whenDefined('sf-toast'); + const toast = document.createElement('sf-toast'); + toast.setAttribute('status', 'info'); + toast.setAttribute('icon', 'delete'); + toast.setAttribute('heading', `${file.textContent} в корзине`); + toast.setAttribute('action-text', 'Вернуть'); + toast.setAttribute('action', 'undo'); + toast.setAttribute('duration', '8000'); + toast.setAttribute('close-label', 'Закрыть сообщение'); + container.append(toast); + + const restoreFile = () => { + list.prepend(file); + toast.close(); + }; + toast.onAction((action) => { + if (action === 'undo') restoreFile(); + }); + toast.onClose(() => console.log('Сообщение закрыто')); +}); From dd9b7536e779b02698c9f8710f7c7534a68b340f Mon Sep 17 00:00:00 2001 From: Rim Zabarov Date: Sun, 22 Nov 2026 02:51:32 +0300 Subject: [PATCH 5/6] Smart pages for tag-group, bulk-actions, form and display-settings; progress-ring class page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five pages the catalogue lacked, written against pair ui-9ceecc24c988 (manifests, distr, ui-source e7ea89e07): - smart/content/tag-group: layout row/wrap, filter selection, keyboard - smart/actions/bulk-actions: place, sizes, select-all under a filter, progress and result with refusals, undo - smart/forms/form: labels, view, answer, instant, field conditions - smart/navigation/display-settings: disclosure and panel, font and links - components/feedback/progress-ring: the class form, linked both ways with the Smart page Each page is enrolled in reference-pages (smart standard 3, component blocks), catalog-groups and the section indexes; Справочник sections and badges come from build-smart-reference with 58 new manifest translations. The redirect components/feedback/progress-ring -> smart is removed: the route is a page now, and the migration rewrote links to it otherwise. Live examples carry their script in the JavaScript tab; form examples that submit hand the button press to the form, since the example frame may not send forms. Co-Authored-By: Claude Opus 5.5 --- config/catalog-groups.json | 11 +- config/public-variables.ru.json | 6 +- config/reference-pages.json | 23 ++ config/smart-reference.json | 6 +- config/smart-reference.ru.json | 60 +++- content/ru/components/feedback/index.md | 1 + .../ru/components/feedback/progress-ring.md | 167 +++++++++++ .../feedback/progress-ring.page.json | 6 + content/ru/components/index.md | 1 + content/ru/guide/smart-components/names.md | 8 + content/ru/smart/actions/bulk-actions.md | 247 ++++++++++++++++ .../ru/smart/actions/bulk-actions.page.json | 6 + content/ru/smart/actions/index.md | 1 + content/ru/smart/content/index.md | 1 + content/ru/smart/content/tag-group.md | 155 ++++++++++ content/ru/smart/content/tag-group.page.json | 6 + content/ru/smart/feedback/progress-ring.md | 4 + content/ru/smart/forms/form.md | 267 ++++++++++++++++++ content/ru/smart/forms/form.page.json | 6 + content/ru/smart/forms/index.md | 1 + content/ru/smart/index.md | 4 + .../ru/smart/navigation/display-settings.md | 180 ++++++++++++ .../navigation/display-settings.page.json | 6 + content/ru/smart/navigation/index.md | 1 + .../progress-ring/avatar/index.html | 4 + .../components/progress-ring/basic/index.html | 4 + .../progress-ring/indeterminate/index.html | 4 + .../components/progress-ring/sizes/index.html | 28 ++ .../progress-ring/status/index.html | 28 ++ .../bulk-actions/all/index.html | 7 + .../bulk-actions/all/index.js | 20 ++ .../bulk-actions/overview/index.html | 10 + .../bulk-actions/overview/index.js | 53 ++++ .../bulk-actions/place/index.html | 23 ++ .../bulk-actions/result/index.html | 6 + .../bulk-actions/result/index.js | 28 ++ .../bulk-actions/sizes/index.html | 20 ++ .../display-settings/extra/index.html | 5 + .../display-settings/overview/index.html | 12 + .../display-settings/overview/index.js | 12 + .../display-settings/panel/index.html | 8 + .../smart-components/form/answer/index.html | 12 + .../smart-components/form/answer/index.js | 26 ++ .../form/conditions/index.html | 11 + .../smart-components/form/conditions/index.js | 23 ++ .../smart-components/form/instant/index.html | 9 + .../smart-components/form/instant/index.js | 12 + .../smart-components/form/labels/index.html | 24 ++ .../smart-components/form/overview/index.html | 16 ++ .../smart-components/form/overview/index.js | 29 ++ .../smart-components/form/view/index.html | 9 + examples/smart-components/form/view/index.js | 24 ++ .../tag-group/layout/index.html | 36 +++ .../tag-group/overview/index.html | 10 + .../tag-group/overview/index.js | 18 ++ .../tag-group/selection/index.html | 20 ++ .../tag-group/selection/index.js | 21 ++ redirects.json | 4 - 58 files changed, 1736 insertions(+), 14 deletions(-) create mode 100644 content/ru/components/feedback/progress-ring.md create mode 100644 content/ru/components/feedback/progress-ring.page.json create mode 100644 content/ru/smart/actions/bulk-actions.md create mode 100644 content/ru/smart/actions/bulk-actions.page.json create mode 100644 content/ru/smart/content/tag-group.md create mode 100644 content/ru/smart/content/tag-group.page.json create mode 100644 content/ru/smart/forms/form.md create mode 100644 content/ru/smart/forms/form.page.json create mode 100644 content/ru/smart/navigation/display-settings.md create mode 100644 content/ru/smart/navigation/display-settings.page.json create mode 100644 examples/components/progress-ring/avatar/index.html create mode 100644 examples/components/progress-ring/basic/index.html create mode 100644 examples/components/progress-ring/indeterminate/index.html create mode 100644 examples/components/progress-ring/sizes/index.html create mode 100644 examples/components/progress-ring/status/index.html create mode 100644 examples/smart-components/bulk-actions/all/index.html create mode 100644 examples/smart-components/bulk-actions/all/index.js create mode 100644 examples/smart-components/bulk-actions/overview/index.html create mode 100644 examples/smart-components/bulk-actions/overview/index.js create mode 100644 examples/smart-components/bulk-actions/place/index.html create mode 100644 examples/smart-components/bulk-actions/result/index.html create mode 100644 examples/smart-components/bulk-actions/result/index.js create mode 100644 examples/smart-components/bulk-actions/sizes/index.html create mode 100644 examples/smart-components/display-settings/extra/index.html create mode 100644 examples/smart-components/display-settings/overview/index.html create mode 100644 examples/smart-components/display-settings/overview/index.js create mode 100644 examples/smart-components/display-settings/panel/index.html create mode 100644 examples/smart-components/form/answer/index.html create mode 100644 examples/smart-components/form/answer/index.js create mode 100644 examples/smart-components/form/conditions/index.html create mode 100644 examples/smart-components/form/conditions/index.js create mode 100644 examples/smart-components/form/instant/index.html create mode 100644 examples/smart-components/form/instant/index.js create mode 100644 examples/smart-components/form/labels/index.html create mode 100644 examples/smart-components/form/overview/index.html create mode 100644 examples/smart-components/form/overview/index.js create mode 100644 examples/smart-components/form/view/index.html create mode 100644 examples/smart-components/form/view/index.js create mode 100644 examples/smart-components/tag-group/layout/index.html create mode 100644 examples/smart-components/tag-group/overview/index.html create mode 100644 examples/smart-components/tag-group/overview/index.js create mode 100644 examples/smart-components/tag-group/selection/index.html create mode 100644 examples/smart-components/tag-group/selection/index.js diff --git a/config/catalog-groups.json b/config/catalog-groups.json index b4c8f62e..7098ada5 100644 --- a/config/catalog-groups.json +++ b/config/catalog-groups.json @@ -51,6 +51,7 @@ "badges", "dot", "progress-bar", + "progress-ring", "progress-scale", "spinner", "skeleton", @@ -115,7 +116,8 @@ "download-file", "copy-button", "confirm", - "confirm-change" + "confirm-change", + "bulk-actions" ] }, "forms": { @@ -136,7 +138,8 @@ "code-input", "file-upload", "image-field", - "color" + "color", + "form" ] }, "navigation": { @@ -153,7 +156,8 @@ "dropdown", "context-menu", "settings", - "language" + "language", + "display-settings" ] }, "feedback": { @@ -182,6 +186,7 @@ "avatars", "icons", "tags", + "tag-group", "list-item", "list", "list-feed", diff --git a/config/public-variables.ru.json b/config/public-variables.ru.json index f3f2e5c3..c8e592fe 100644 --- a/config/public-variables.ru.json +++ b/config/public-variables.ru.json @@ -361,6 +361,10 @@ "With overflow=\"truncate\": the widest the button grows before its label is cut with an ellipsis; the max-width setting wins over it, and the container's width stays the limit.": "При `overflow=\"truncate\"` — наибольшая ширина кнопки, после которой подпись обрезается многоточием; атрибут `max-width` сильнее этой переменной, а пределом остаётся ширина контейнера.", "The border colour; seen with a border width. Its resting default is the tonal edge's graphic ink (component.badges 1.12.0, C208): drawn only where a place asks for the edge (an inverse place), invisible at the default width 0.": "Цвет рамки; виден, когда задана толщина рамки. В покое по умолчанию — графический цвет тонального края: он рисуется только там, где край просит место (инверсное место), а при толщине по умолчанию 0 не виден.", "Space between the icon and the text; on a badge with a name and a value, the space on each side of the divider, --sf-space-1/3 there (owner decision C317).": "Расстояние между значком и текстом; у значка с именем и значением — расстояние по обе стороны от разделителя, там это `--sf-space-1/3`.", - "The one-pixel divider between a name and a value in one badge («sf-wizard | 1.5.3», owner decision C317): the badge's border colour on an outline badge, --sf-outline on a fill.": "Разделитель толщиной в один пиксель между именем и значением в одном значке («sf-wizard | 1.5.3»): цвет рамки значка у значка с рамкой, `--sf-outline` у залитого." + "The one-pixel divider between a name and a value in one badge («sf-wizard | 1.5.3», owner decision C317): the badge's border colour on an outline badge, --sf-outline on a fill.": "Разделитель толщиной в один пиксель между именем и значением в одном значке («sf-wizard | 1.5.3»): цвет рамки значка у значка с рамкой, `--sf-outline` у залитого.", + "The ring's box: the control height of its size unless this is set.": "Рамка кольца: высота элемента управления его размера, если переменная не задана.", + "The width of the line; a bare 0 is valid.": "Толщина линии; можно задать и голый 0.", + "Space between the line and what stands in the middle; a bare 0 is valid.": "Зазор между линией и тем, что стоит в середине; можно задать и голый 0.", + "The percentage in the middle.": "Процент в середине." } } diff --git a/config/reference-pages.json b/config/reference-pages.json index 7465d7ea..76ec855d 100644 --- a/config/reference-pages.json +++ b/config/reference-pages.json @@ -214,6 +214,13 @@ "sf-progress-bar" ] }, + "components/feedback/progress-ring.md": { + "kind": "component", + "component": "progress-ring", + "blocks": [ + "sf-progress-ring" + ] + }, "components/feedback/progress-scale.md": { "kind": "component", "component": "progress-scale", @@ -526,6 +533,10 @@ "kind": "smart", "standard": 3 }, + "smart/content/tag-group.md": { + "kind": "smart", + "standard": 3 + }, "smart/editor/composition-overlay.md": { "kind": "smart", "standard": 3 @@ -1994,6 +2005,18 @@ "kind": "smart", "standard": 3 }, + "smart/actions/bulk-actions.md": { + "kind": "smart", + "standard": 3 + }, + "smart/forms/form.md": { + "kind": "smart", + "standard": 3 + }, + "smart/navigation/display-settings.md": { + "kind": "smart", + "standard": 3 + }, "pro/chat/chat-composer.md": { "kind": "smart", "standard": 2 diff --git a/config/smart-reference.json b/config/smart-reference.json index 4167615b..a6db2983 100644 --- a/config/smart-reference.json +++ b/config/smart-reference.json @@ -39,11 +39,7 @@ }, "skip": { "message-log": "Dated alias of sf-list-feed until 2027-01-01: the page is a short note that points to the feed (D10, register RG-S2-52); the name table lives in the «Прежние имена» guide.", - "theme-generator": "Leaving until 2027-01-01 (C84): sf-input-color variant=\"brand\" and variant=\"theme\" replace it; its page folded into smart/forms/color.md (DEV decision 2026-11-15), the old address redirects there. Its former names stay in the «Прежние имена» guide.", - "display-settings": "No page yet (repin to ui-1ed6b6c9a040): the component is in the release and not described in the documentation; its page comes with its own docs pass, not with a repin.", - "form": "No page yet (repin to ui-1ed6b6c9a040): the component is in the release and not described in the documentation; its page comes with its own docs pass, not with a repin.", - "tag-group": "No page yet (repin to ui-1ed6b6c9a040): the component is in the release and not described in the documentation; its page comes with its own docs pass, not with a repin.", - "bulk-actions": "No page yet (repin to ui-b654460cad2a): the component is in the release and not described in the documentation; its page comes with its own docs pass, not with a repin. The list and pagination pages name it where a choice of rows shows its bar." + "theme-generator": "Leaving until 2027-01-01 (C84): sf-input-color variant=\"brand\" and variant=\"theme\" replace it; its page folded into smart/forms/color.md (DEV decision 2026-11-15), the old address redirects there. Its former names stay in the «Прежние имена» guide." }, "suppress": { "popover": { diff --git a/config/smart-reference.ru.json b/config/smart-reference.ru.json index 8e54a58d..b60d8667 100644 --- a/config/smart-reference.ru.json +++ b/config/smart-reference.ru.json @@ -3693,6 +3693,64 @@ "auto: a row while the steps fit their own width on one line, else a column (label and a second line); below 30rem of the list's own width always a column, drawn by the sheet before the code measures (1.5.0); under 20rem of its own width the count line «Шаг N из M · label» over sf-progress-bar. row, column and count draw that layout always; an explicit row wider than its place scrolls inside itself.": "auto: строка, пока шаги помещаются в одну строку своей ширины, иначе колонка (подпись и вторая строка); если собственная ширина списка меньше 30rem — всегда колонка, её рисует таблица стилей ещё до того, как код измерит; если собственная ширина меньше 20rem — строка счёта «Шаг N из M · подпись» над sf-progress-bar. row, column и count рисуют свою раскладку всегда; явная строка шире своего места прокручивается внутри.", "The panel's width: three steps and the screen (owner decision C157 (2)) -- 1/2 44 characters, 1 52 (the default), 2 64 (--sf-measure-44/52/64, owner decision C396: 352, 416, 512px at text 16, following the text; 20, 24, 30rem before), full the whole screen. The step is the panel's outer width; the content stands inside the window inset (C105 H6, --sf-space-2: 20 px a side on a desktop, 16 in compact density and on a phone): 312, 376, 472px on a desktop. No other widths: a panel that needs its own width carries an sf-resizer within 1/2...2. width replaces the step.": "Ширина панели: три ступени и весь экран — `1/2` 44 знака, `1` 52 (по умолчанию), `2` 64 (`--sf-measure-44/52/64`: 352, 416, 512 px при тексте 16, следуют размеру текста), `full` — весь экран. Ступень — внешняя ширина панели; содержимое стоит внутри отступа окна (`--sf-space-2`: 20 px с каждой стороны на компьютере, 16 в компактной плотности и на телефоне): 312, 376, 472 px на компьютере. Других ширин нет: панель, которой нужна своя ширина, несёт sf-resizer в пределах `1/2`…`2`. `width` заменяет ступень.", "The panel's width, a CSS length (sets --sf-drawer-width); empty: the size step's width. A width off the ladder (44 · 52 · 64 characters since C396, the whole screen; owner decision C157 (2)) is still drawn until 2027-01-01 and said once per element in the console and in SF.deprecations.list(); take a size step, and an sf-resizer within 1/2...2 for a width of its own.": "Ширина панели, длина CSS (задаёт `--sf-drawer-width`); пусто — ширина ступени размера. Ширина вне лестницы (44 · 52 · 64 знака, весь экран) рисуется до 2027-01-01 и один раз на элемент сообщается в консоли и в `SF.deprecations.list()`; берите ступень размера, а для своей ширины — sf-resizer в пределах `1/2`…`2`.", - "An announced aside column's width (a CSS length, a system value where there is one), added on top of the size step (or width) that is the content's panel and never taken from it (A9, DEV msg-6aead3f3): size 1 with aside-width 240px is 416 + 240px wide, the step still 52 characters. The step is the panel's width, not the content's: the content stands inside the window inset (C105 H6, --sf-space-2: 20 px a side on a desktop, 16 in compact density and on a phone), 312, 376 and 472 px for the steps 352, 416 and 512 on a desktop at text 16. Sets --sf-drawer-aside-width. Never wider than the window; on a phone the panel is the whole screen and the aside adds nothing. It raises no off-ladder warning.": "Ширина объявленной боковой колонки (длина CSS, системное значение, где оно есть), прибавляется к ступени размера (или `width`) — панели содержимого — и никогда не отнимается от неё: размер `1` с `aside-width` 240px шириной 416 + 240 px, ступень по-прежнему 52 знака. Ступень — ширина панели, а не содержимого: содержимое стоит внутри отступа окна (`--sf-space-2`: 20 px с каждой стороны на компьютере, 16 в компактной плотности и на телефоне), 312, 376 и 472 px для ступеней 352, 416 и 512 на компьютере при тексте 16. Задаёт `--sf-drawer-aside-width`. Не шире окна; на телефоне панель во весь экран и колонка ничего не добавляет. Предупреждения о ширине вне лестницы не вызывает." + "An announced aside column's width (a CSS length, a system value where there is one), added on top of the size step (or width) that is the content's panel and never taken from it (A9, DEV msg-6aead3f3): size 1 with aside-width 240px is 416 + 240px wide, the step still 52 characters. The step is the panel's width, not the content's: the content stands inside the window inset (C105 H6, --sf-space-2: 20 px a side on a desktop, 16 in compact density and on a phone), 312, 376 and 472 px for the steps 352, 416 and 512 on a desktop at text 16. Sets --sf-drawer-aside-width. Never wider than the window; on a phone the panel is the whole screen and the aside adds nothing. It raises no off-ladder warning.": "Ширина объявленной боковой колонки (длина CSS, системное значение, где оно есть), прибавляется к ступени размера (или `width`) — панели содержимого — и никогда не отнимается от неё: размер `1` с `aside-width` 240px шириной 416 + 240 px, ступень по-прежнему 52 знака. Ступень — ширина панели, а не содержимого: содержимое стоит внутри отступа окна (`--sf-space-2`: 20 px с каждой стороны на компьютере, 16 в компактной плотности и на телефоне), 312, 376 и 472 px для ступеней 352, 416 и 512 на компьютере при тексте 16. Задаёт `--sf-drawer-aside-width`. Не шире окна; на телефоне панель во весь экран и колонка ничего не добавляет. Предупреждения о ширине вне лестницы не вызывает.", + "A person chose or cleared a filter tag of the row (selection one or many): ids is the whole selection, id the tag pressed and selected whether it is now chosen (vocabulary §5 select)": "Человек выбрал или снял тег-фильтр ряда (`selection` `one` или `many`): `ids` — весь выбор, `id` — нажатый тег, `selected` — выбран ли он теперь", + "Delete or Backspace removes the removable tag stood on; the focus goes to its neighbour": "Delete или Backspace убирает тег, на котором стоит фокус, если его можно убрать; фокус переходит к соседу", + "Enter or Space on «+N» opens the hidden tags; Escape closes them": "Enter или пробел на «+N» открывает скрытые теги; Escape закрывает их", + "For filter tags (kind checkbox): none leaves each tag its own; one keeps a single tag chosen (choosing one clears the others; it can be cleared); many lets each be chosen. With one or many the group reports select": "Для тегов-фильтров (`kind=\"checkbox\"`): `none` — каждый тег сам по себе; `one` — выбран один тег (выбор тега снимает выбор с остальных, выбранный можно снять); `many` — выбирается любой набор. При `one` и `many` группа сообщает выбор событием `sf-tag-group-select`", + "Tab reaches the row once; ArrowLeft and ArrowRight walk the tags and «+N», Home and End go to the ends": "Tab попадает в ряд один раз; стрелки влево и вправо ходят по тегам и «+N», Home и End — к концам ряда", + "row: one line -- filters, a table cell, a card: the tags that do not fit leave it and «+N» opens them in a popover (C58, C145 (5)); wrap: the row wraps, every tag in view (a form)": "`row` — одна строка: фильтры, ячейка таблицы, карточка; теги, которые не поместились, уходят из строки, и «+N» открывает их во всплывающей панели; `wrap` — ряд переносится, все теги на виду (форма)", + "A field's value changed by the person: its key and the new value (undefined when the field withdrew an incomplete text). Sent as sf-form-input, not input: the fields' own native input events bubble through the form unchanged": "Человек изменил значение поля: его ключ и новое значение (`undefined`, если поле отказалось от недописанного текста). Приходит как `sf-form-input`, а не `input`: собственные события `input` полей проходят через форму без изменений", + "A person changed a setting or chose «Обычная версия»: the fact, sent after the root shows it and the browser keeps it. Nothing is sent anywhere; a page that wants to know listens here": "Человек изменил настройку или выбрал «Обычную версию»: событие приходит, когда страница уже показывает выбор и браузер его запомнил. Никуда ничего не отправляется; страница, которой нужно знать, слушает это событие", + "A person chose an action (after «yes» in the question when it asks one): the host does it on the selection or on all under the filter, and says how it went with result(). Cancel it to refuse; a reversible action's notice is then not shown": "Человек выбрал действие (после «да» в вопросе, если вопрос есть): приложение выполняет его над выбранными или над всеми по фильтру и сообщает итог методом `result()`. Отменённое событие — действие не принято; уведомление обратимого действия тогда не показывается", + "A person pressed «Отменить» in the notice of a reversible action (C25): the host puts the items back": "Человек нажал «Отменить» в уведомлении обратимого действия: приложение возвращает записи", + "A person pressed × or Escape (or the page called clear()): the host drops the selection and writes count 0": "Человек нажал × или Escape (или страница вызвала `clear()`): приложение снимает выбор и пишет `count` 0", + "A person took «Выбрать все N»: every item under the filter is selected (all-selected is set)": "Человек выбрал «Выбрать все N»: выбраны все записи по фильтру (`all-selected` поставлен)", + "A person took «Только эта страница»: back to the items on screen (all-selected is off)": "Человек выбрал «Только эта страница»: выбор вернулся к записям на экране (`all-selected` снят)", + "A short run in the bar: «Выполняем: 4 из 12» (or «: 4 / 12») over a progress bar, the actions out of reach until done reaches total or result() comes. Refused {reason: long} over 100 items -- an action that long goes in the background and its result in a notice (C387); its progress is the host's sf-progress-run (C34) -- and {reason: invalid} without a total": "Короткий прогон в полосе: «Выполняем: 4 из 12» (или «<текст>: 4 / 12») над полосой прогресса; действия недоступны, пока `done` не дойдёт до `total` или не придёт `result()`. Больше чем для 100 записей — отказ `{reason: long}`: такое действие идёт в фоне, его итог — в уведомлении, а ход показывает `sf-progress-run` приложения; без `total` — отказ `{reason: invalid}`", + "A submit or check-validity found wrong fields: their keys in order. Every one shows its error at the field; from two errors a summary with a link to each stands over the form and takes the focus. A host error (set-errors) for a field its conditions hide is said in the summary by the field's label, without a link, and does not hold the next submit back (FO3-1)": "Отправка или `checkValidity()` нашли неверные поля: их ключи по порядку. У каждого поля — его ошибка; от двух ошибок над формой встаёт сводка со ссылкой на каждое поле и получает фокус. Ошибка приложения (`setErrors`) для поля, которое скрыто условием, называется в сводке подписью поля, без ссылки, и не задерживает следующую отправку", + "After a submit with two errors or more the focus is on the summary; Tab reaches its links, and Enter on a link moves the focus to that field": "После отправки с двумя ошибками и больше фокус на сводке; Tab доходит до её ссылок, Enter на ссылке переводит фокус в поле", + "All items under the filter are selected: the count says «Выбраны все 240», the offer turns to «Только эта страница (12)» and an action goes with scope all. The bar sets it on «Выбрать все N» and takes it off on «Только эта страница», on clear and when count stops being page-count": "Выбраны все записи по фильтру: счёт говорит «Выбраны все 240», предложение становится «Только эта страница (12)», действие приходит со `scope` `all`. Полоса ставит его по «Выбрать все N» и снимает по «Только эта страница», при снятии выбора и когда `count` перестаёт быть равен `page-count`", + "Checks every field it shows and shows every error, as «Сохранить» does but without submit: applied when right, refused {reason: invalid} otherwise (§17.4). Moves no focus": "Проверяет каждое показанное поле и показывает все ошибки, как «Сохранить», но без отправки: `applied`, если всё верно, иначе отказ `{reason: invalid}`. Фокус не переводит", + "Enter in a one-line field submits the form": "Enter в однострочном поле отправляет форму", + "Escape in an open disclosure panel closes it and returns the focus to the trigger": "Escape в открытой панели вида `disclosure` закрывает её и возвращает фокус на кнопку", + "Escape in the list or the bar clears the selection, unless a menu, a window or a text field holds it": "Escape в списке или в полосе снимает выбор, если фокус не занят меню, окном или полем ввода", + "Every field returns to the saved state, without events; the errors and the summary are gone (§17.4)": "Каждое поле возвращается к сохранённому состоянию, без событий; ошибки и сводка уходят", + "How an action went, failed as [{id, text, reason}] (owner decision C387, refining C295 and C331). A fast action: without refusals the bar says «Удалено: 5» (the action's done-text, else «Готово: 5») in place of the count for 4 s and goes back, the selection may drop to 0 meanwhile; with refusals «Готово 10 из 12 · 2 не удалось» with «Подробнее» (the list in a question window) and «Повторить для 2», the host keeps the failed items selected and the result goes when the selection changes. A long action (long in its action event): a notice, success or an error that stays with «Подробнее». A failure is written to «Уведомления» either way: SF.notify's sf-notification record, source sf-bulk-actions (a fast one's not shown again as a toast, the bar shows it). A reversible action's success says nothing more: its notice with «Отменить» already did": "Как прошло действие; неудачи — списком `[{id, text, reason}]`. Быстрое действие без отказов: полоса на 4 секунды говорит «Удалено: 5» (`done-text` действия, иначе «Готово: 5») на месте счёта и возвращается, выбор тем временем может стать пустым. С отказами — «Готово 10 из 12 · 2 не удалось» с «Подробнее» (список в окне-вопросе) и «Повторить для 2»; приложение оставляет не получившиеся записи выбранными, итог уходит, когда выбор меняется. Долгое действие (`long` в событии действия) — уведомление: об успехе или об ошибке, которая ждёт с «Подробнее». Неудача в любом случае записывается в «Уведомления»: запись `sf-notification` от `SF.notify` с `source` `sf-bulk-actions` (неудача быстрого действия не всплывает второй раз — её показывает полоса). Успех обратимого действия больше ничего не говорит: уведомление с «Отменить» уже сказало", + "How many items are on screen (the rows of the page). When count equals it and total is larger, the bar offers «Выбрать все N». 0: not known, no offer": "Сколько записей на экране (строк страницы). Когда `count` равен ему, а `total` больше, полоса предлагает «Выбрать все N». 0 — неизвестно, предложения нет", + "How many items are under the filter. Unset or 0: not known (a cursor list), no «Выбрать все N»": "Сколько записей по фильтру. Не задано или 0 — неизвестно (список с курсором), «Выбрать все N» нет", + "How many items the host has selected. 0 hides the bar (its live region stays and says «Выбор снят»); the host owns the selection and writes this on every change": "Сколько записей выбрано. 0 прячет полосу (её живая область остаётся и говорит «Выбор снят»); выбор держит приложение и пишет это значение при каждом изменении", + "Offer the font group: the site's font, sans serif or serif (the system's --sf-sans and --sf-serif). Off by default: the site's author turns it on": "Показывает группу «Шрифт»: шрифт сайта, без засечек или с засечками (системные `--sf-sans` и `--sf-serif`). По умолчанию выключено: включает автор сайта", + "Offer «Подчёркивать ссылки». Off by default: the site's author turns it on. Inside a colour scheme links are always underlined": "Показывает «Подчёркивать ссылки». По умолчанию выключено: включает автор сайта. В цветовой схеме ссылки подчёркнуты всегда", + "Sends clear {reason: api}, as × does": "Присылает `clear` с `{reason: api}`, как крестик", + "Tab reaches the offer, every action, «⋯» and ×; Enter or Space presses it": "Tab доходит до предложения, каждого действия, «⋯» и крестика; Enter или пробел нажимает кнопку", + "Tab reaches the trigger and every button of the panel; Enter or Space presses it": "Tab доходит до кнопки и каждой кнопки панели; Enter или пробел нажимает её", + "Tab walks the fields in order, then «Сохранить» and «Отмена» (or «Изменить» in view)": "Tab идёт по полям по порядку, затем «Сохранить» и «Отмена» (в просмотре — «Изменить»)", + "The actions on the selection: up to three labelled outline buttons (one icon button on a phone), the rest in «⋯» (the page's one menu, SF.menu.open), a dangerous one always last in «⋯»": "Действия над выбранными: до трёх кнопок с подписью и рамкой (на телефоне — одна кнопка-значок), остальные в «⋯» (общее меню страницы, `SF.menu.open`); опасное — всегда последним в «⋯»", + "The field host's answers changed -- a page of candidates, an upload's progress, a stored file -- and the fields are drawn again with what it answers now (1.7.0). The form draws again by itself when a host call answers a promise that settles. Working name (name to confirm)": "Ответы хозяина полей изменились — страница вариантов, ход загрузки, сохранённый файл — и поля рисуются заново с тем, что он отвечает сейчас. Когда вызов хозяина отвечает обещанием, форма перерисовывается сама, как только оно выполнено", + "The fields, in order: the Framework field descriptor that sf-view-properties sends -- the property registry's type, its template and its parameters (propertyType, template and templateParams -- variant is the former name of template until 2027-01-01 --, required, readonly, placeholder, options, min, max, step, unit, decimals, currency, currencies, currencyDisplay, holder (a ru.inn field: any, organization -- 10 digits -- or person -- 12), defaultCountry (a phone field: the ISO 3166 alpha-2 country an empty field starts on, else the page's) … as SF.fieldRenderers.registry lists them) plus key, label, hint, help, width and group. width short (the field width step of 20 characters, 160 px at text 16), medium (28, 224 px) or full -- s and m, the former names, read as short and medium until 2027-01-01; without it a field pairs with its neighbour from 44rem of the form's own width. A field of a type the field renderers do not draw is left out": "Поля по порядку: описание поля SIMAI Framework, то же, что передаёт `sf-view-properties`, — тип из реестра свойств, его шаблон и параметры (`propertyType`, `template` и `templateParams`, `required`, `readonly`, `placeholder`, `options`, `min`, `max`, `step`, `unit`, `decimals`, `currency`, `currencies`, `currencyDisplay`, `holder` — для поля ИНН: `any`, `organization` (10 цифр) или `person` (12), `defaultCountry` — для телефона: страна ISO 3166 alpha-2, с которой начинается пустое поле, иначе страна страницы … как их перечисляет `SF.fieldRenderers.registry`) и ключи формы `key`, `label`, `hint`, `help`, `width` и `group`. `width`: `short` (шаг ширины поля в 20 знаков, 160 px при тексте 16), `medium` (28 знаков, 224 px) или `full`; без него поле встаёт в пару с соседним от 44rem ширины самой формы. Поле типа, который модуль полей не рисует, не показывается", + "The form's accessible name (the native form's aria-label), so a screen reader announces it as a form landmark; best the heading the form stands under. Working name (name to confirm)": "Доступное имя формы (`aria-label` формы): экранный диктор называет по нему ориентир «форма»; лучше всего — заголовок, под которым стоит форма", + "The groups the fields' group keys name, in order: {key, label}. With two or more, each is a fieldset with its label as the legend, 24 apart over a line. A field without a group, or with a group not listed, stands in one group of its own after the listed ones": "Группы, которые называют ключи `group` полей, по порядку: `{key, label}`. От двух групп каждая — набор полей с подписью-заголовком, между группами 24 и линия. Поле без группы или с группой не из списка стоит в своей группе после перечисленных", + "The host's answer to a submit: {key: message} -- each named field shows the message as its error until the person changes it, from two a summary takes the focus as after «Сохранить»; an empty object clears them. A form in view opens edit. refused {reason: missing} when no key names a field it shows. Working name (name to confirm)": "Ответ приложения на отправку: `{ключ: сообщение}` — каждое названное поле показывает сообщение как свою ошибку, пока человек его не изменит; от двух ошибок сводка получает фокус, как после «Сохранить»; пустой объект снимает ошибки. Форма в просмотре открывает правку. Отказ `{reason: missing}`, если ни один ключ не называет показанное поле", + "The host's own count line in place of «Выбрано N» («Выбрано 3 · с вложенными 48» of a tree). Empty: the bar's words": "Своя строка счёта вместо «Выбрано N» («Выбрано 3 · с вложенными 48» у дерева). Пусто — слова полосы", + "The ladder rung its buttons and count take (the bar is the rung's control height and space-1/4 above and below: 42 px at 1/2, 50 at 1). Unset: the size of the nearest element around it that has one (the list that places it), else 1": "Ступень линейки для кнопок и счёта (высота полосы — высота элемента управления этой ступени и `space-1/4` сверху и снизу: 42 px у `1/2`, 50 у `1`). Не задано — размер ближайшего элемента с размером вокруг (списка, который ставит полосу), иначе `1`", + "The record host's half of the field renderers' host interface (1.7.0), a property only: getFieldOptionsPage, getFieldOptionSearch, setFieldOptionSearch and loadFieldOptions page and search a record, relation or user picker (template reference_picker); getFieldUploads, startFieldUpload and retryFieldUpload transfer a file (template upload: the upload area is drawn and says its own error); getFieldText and formatFieldValue are the host's words and formatting; renderField(field, value, host, {editing, size}) draws a type a component set draws (items, complex, ru.requisites). Each is called with the renderers' arguments and, last, the form's host for that field, whose setFieldValue writes into the form's value (a stored file the host was handed). The form keeps setFieldValue and setFieldError, so the values, their checks and the submit stay the form's. Without it a picker pages the field's own options and a file field keeps the chosen files in its value ({name, size, mime, file}: the File for the host to send with the values). Working name (name to confirm)": "Половина интерфейса хозяина полей, которую держит запись; только свойство. `getFieldOptionsPage`, `getFieldOptionSearch`, `setFieldOptionSearch` и `loadFieldOptions` листают и ищут выбор записи, связи или сотрудника (шаблон `reference_picker`); `getFieldUploads`, `startFieldUpload` и `retryFieldUpload` передают файл (шаблон `upload`: форма рисует поле загрузки, и оно само говорит свою ошибку); `getFieldText` и `formatFieldValue` — слова и формат хозяина; `renderField(field, value, host, {editing, size})` рисует тип, который рисует набор компонентов (`items`, `complex`, `ru.requisites`). Каждый вызывается с аргументами модуля полей и последним аргументом — хозяином формы для этого поля; его `setFieldValue` пишет в значение формы (например, сохранённый файл). Значения, их проверка и отправка остаются формы. Без этого свойства выбор листает собственные `options` поля, а файловое поле держит выбранные файлы в значении (`{name, size, mime, file}`: сам `File` приложение отправляет вместе со значениями)", + "The region's name. Empty: «Действия с выбранными» («Actions on the selected»)": "Имя области. Пусто — «Действия с выбранными»", + "The rung of the fields and the buttons on the size ladder: 1, or 1/2 for a form in a message (owner decision C291 (3)). The label, the hint and the error keep the 1/2 text step at both": "Ступень полей и кнопок на линейке размеров: `1` или `1/2` — для формы в сообщении. Подпись, подсказка и ошибка стоят на ступени текста `1/2` при обоих", + "The trigger's text and the panel's name. Not set: «Настройки отображения» («Display settings»). A Russian site that is asked for the button by name writes «Версия для слабовидящих»": "Подпись кнопки и имя панели. Не задано — «Настройки отображения». Российский сайт, где кнопку ищут по названию, пишет «Версия для слабовидящих»", + "The values by field key: {text: \"Подробнее\", tone: \"accent\"}. Set from code it is the saved state: the form shows it, forgets the errors and is not dirty; read, it is what the fields hold now and what a save sends: a field its conditions hide (when.visible) is left out, while the form keeps what it held so that showing the field again brings it back (FO3-1, Larena settings standard §4). A value the person never set is absent": "Значения по ключам полей: `{text: \"Подробнее\", tone: \"accent\"}`. Заданное из кода — сохранённое состояние: форма показывает его, забывает ошибки и не считается изменённой. Прочитанное — то, что сейчас в полях и что уйдёт при сохранении: поле, скрытое условием (`when.visible`), в него не входит, но форма помнит его значение, и оно вернётся, когда поле покажется снова. Значения, которое человек не задавал, нет", + "Where the bar stands (C295 (1)): dock over the list's bottom edge at its width, sticking to the bottom of the scroll; top in the toolbar's place, in the primary container; float a plate at the middle of the window's bottom edge; inline a plain row in the flow. The host places the element: after its list for dock and inline, before it for top": "Где стоит полоса: `dock` — по нижнему краю списка во всю его ширину, прилипает к низу прокрутки; `top` — на месте панели инструментов, на основном контейнере; `float` — плашка посередине нижнего края окна; `inline` — обычная строка в потоке. Элемент ставит приложение: после списка для `dock` и `inline`, перед ним для `top`", + "Whether the panel of layout disclosure is open; the button turns it, Escape closes it": "Открыта ли панель вида `disclosure`; кнопка переключает её, Escape закрывает", + "apply answer only: where the answer is, the confirm surface's words (sf-confirm). open: the fields and «Отправить», «Отмена». pending: an answer is on its way, set by a press -- the fields are locked, the pressed button waits, «Отправляем…» (or «Отменяем…»). accepted: the values sent, read-only, with «Отправлено». declined: nothing is drawn (C35: a declined answer says nothing). expired: only «Время ответа истекло». The host sets the outcome; back to open when the answer could not be delivered (with set-errors for the fields to fix)": "Только при `apply=\"answer\"`: где ответ, словами поверхности подтверждения (`sf-confirm`). `open` — поля, «Отправить» и «Отмена». `pending` — ответ в пути, ставится нажатием: поля заперты, нажатая кнопка ждёт, «Отправляем…» («Отменяем…»). `accepted` — отправленные значения текстом с «Отправлено». `declined` — ничего не рисуется: отказ ничего не говорит. `expired` — только «Время ответа истекло». Исход ставит приложение; `open` снова — если ответ не дошёл (с `setErrors` для полей, которые нужно исправить)", + "apply answer: «Отправить» found every field right (accepted true, with the value) or «Отмена» was pressed (accepted false). Sent with state pending; the host sets the outcome, in its handler or later: accepted, declined, or open again. Cancelled, the answer was not taken: the form is open again and may be answered again (the confirm surface's answer)": "`apply=\"answer\"`: «Отправить» нашла все поля верными (`accepted` true, со значением) или нажата «Отмена» (`accepted` false). Приходит в состоянии `pending`; исход ставит приложение в обработчике или позже: `accepted`, `declined` или снова `open`. Отменённое событие — ответ не принят: форма снова открыта, и на неё можно ответить ещё раз", + "apply instant only: a field's value is applied (§8, one per commit of the field). Sent as sf-form-change, not change: the fields' own native change events bubble through the form unchanged": "Только при `apply=\"instant\"`: значение поля применено. Приходит как `sf-form-change`, а не `change`: собственные события `change` полей проходят через форму без изменений", + "apply submit: «Сохранить» (or Enter in a one-line field) found every field right; value is every shown field's value by key (a field its conditions hide is not sent, FO3-1). Not cancelled, the value becomes the saved state (dirty false) and a form that was opened from view returns to view; cancelled, the form stays as it is (the host answers later, with set-errors or a new value)": "`apply=\"submit\"`: «Сохранить» (или Enter в однострочном поле) нашла все поля верными; `value` — значения всех показанных полей по ключам (поле, скрытое условием, не отправляется). Не отменённое событие делает значение сохранённым (`dirty` false), и форма, открытая из просмотра, возвращается в просмотр; отменённое — форма остаётся как есть (приложение ответит позже через `setErrors` или новым `value`)", + "disclosure: a button that opens the panel in place under it (aria-expanded), Escape closes it and the focus goes back to the button; panel: the panel stands open, with no button (a page of its own, a footer)": "`disclosure` — кнопка, которая раскрывает панель под собой (`aria-expanded`); Escape закрывает её, и фокус возвращается на кнопку. `panel` — панель стоит открытой, без кнопки (своя страница, подвал)", + "edit: the fields. view: the values as text (the field renderers' view, as a record card shows them) with «Изменить» under them; «Изменить» opens edit, and «Сохранить» or «Отмена» return to view. Working name (name to confirm)": "`edit` — поля. `view` — значения текстом (вид модуля полей для просмотра, как в карточке записи) и «Изменить» под ними; «Изменить» открывает правку, «Сохранить» и «Отмена» возвращают просмотр", + "static: the buttons under the last field, the main one first at the start. sticky: the same buttons in a bar that sticks to the bottom of the scrolling place while the form is longer than it -- a settings page (C166 (3)). The value name static is a working name (name to confirm)": "`static` — кнопки под последним полем, главная первой в начале. `sticky` — те же кнопки в полосе, которая прилипает к низу прокручиваемого места, пока форма длиннее его: страница настроек", + "submit: the form is saved with its button -- «Сохранить» and «Отмена» under the fields, a required yes/no is a checkbox (C165 (4)), «Есть несохранённые изменения» under the buttons after a change. instant: every change acts at once -- no buttons, a change event per field, a required yes/no is a switch (a settings panel, a block's parameters). answer: a form a person answers once, a questionnaire in a message or a feed entry (owner decision C291 (3)) -- «Отправить» and «Отмена» under the fields; a press puts the answer on its way (state pending, «Отправляем…»), the host sets the outcome; accepted shows the values read-only with the mark «Отправлено» and no «Изменить», nothing reopens them; mode is not read": "`submit` — форма сохраняется кнопкой: «Сохранить» и «Отмена» под полями, обязательное «да / нет» — флажок, после изменения под кнопками «Есть несохранённые изменения». `instant` — каждое изменение действует сразу: кнопок нет, событие изменения на каждое поле, обязательное «да / нет» — переключатель (панель настроек, параметры блока). `answer` — форма, на которую отвечают один раз: анкета в сообщении или записи ленты; «Отправить» и «Отмена» под полями, нажатие отправляет ответ (состояние `pending`, «Отправляем…»), исход ставит приложение; `accepted` показывает значения текстом с отметкой «Отправлено» и без «Изменить», снова их не открыть; `mode` не читается", + "top: the label above its field (the default). start: from 40rem of the form's own width the label stands beside its field in a third of the row, the field in the rest -- the row of a settings page and of an admin card; narrower, above. The value name top is a working name (name to confirm)": "`top` — подпись над полем (по умолчанию). `start` — от 40rem ширины самой формы подпись стоит слева в трети строки, поле — в остальном: строка страницы настроек и карточки в админке; уже — над полем", + "«Обычная версия»: every setting back to the site's own look, the kept choice removed; sends change with setting reset. refused {reason: unchanged} when nothing was changed": "«Обычная версия»: все настройки возвращаются к виду сайта, запомненный выбор удаляется; приходит `change` с `setting` `reset`. Отказ `{reason: unchanged}`, если ничего не меняли", + "«Отмена»: the fields went back to the saved state (value), the errors are gone; a form opened from view returns to view": "«Отмена»: поля вернулись к сохранённому состоянию (`value`), ошибки ушли; форма, открытая из просмотра, возвращается в просмотр" } } diff --git a/content/ru/components/feedback/index.md b/content/ru/components/feedback/index.md index a62e2902..2560036c 100644 --- a/content/ru/components/feedback/index.md +++ b/content/ru/components/feedback/index.md @@ -26,6 +26,7 @@ profile: reference - **[Бейджи](/ru/components/feedback/badges/)** — короткий статус, категория или счётчик рядом с объектом. - **[Точка состояния](/ru/components/feedback/dot/)** — минимальный визуальный индикатор состояния. - **[Прогресс](/ru/components/feedback/progress-bar/)** — ход операции с известной степенью завершения. +- **[Кольцо прогресса](/ru/components/feedback/progress-ring/)** — доля выполненного кольцом в габарите элемента управления. - **[Шкала прогресса](/ru/components/feedback/progress-scale/)** — прогресс, разделённый на наглядные участки. - **[Спиннер](/ru/components/feedback/spinner/)** — ожидание операции с неизвестной длительностью. - **[Скелетон](/ru/components/feedback/skeleton/)** — стабильная форма содержимого во время загрузки данных. diff --git a/content/ru/components/feedback/progress-ring.md b/content/ru/components/feedback/progress-ring.md new file mode 100644 index 00000000..c4723039 --- /dev/null +++ b/content/ru/components/feedback/progress-ring.md @@ -0,0 +1,167 @@ +--- +title: "Кольцо прогресса" +description: "Показывает долю выполненного кольцом в габарите элемента управления — классами, без скрипта." +profile: reference +--- + +# Кольцо прогресса + +:badge[sf-progress-ring]{variant=outline scheme=on-surface size=1/2} :badge[1.7.1]{variant=outline scheme=on-surface size=1/2} + +Кольцо прогресса показывает значение от 0 до 100 кольцом размером с +элемент управления: в панели инструментов, в строке списка, вокруг аватара. +Компонент — только стили: значение задаёт переменная на блоке, скрипт не +нужен. Кольцо, значение которого меняется по ходу работы, проще взять +смарт-компонентом [Кольцо прогресса](/ru/smart/feedback/progress-ring/): он +пишет эту же разметку и сам держит значение, роль и имя. Длинной задаче в +теле страницы подходит [Прогресс](/ru/components/feedback/progress-bar/). + +## Пример + +:::example {id="components/progress-ring/basic" label="Кольцо с процентом"} +::: + +## Разметка + +```html +
+ + +
+``` + +- `sf-progress-ring` — рамка кольца. Значение — переменная + `--sf-progress-ring--value`, число от 0 до 100. +- `sf-progress-ring-indicator` — само кольцо: дорожка и заполненная часть. + На нём роль, значение и имя для экранного диктора. +- `sf-progress-ring-content` — середина: процент или картинка. Процент + скрыт от диктора: значение уже говорит кольцо. Число пишут с неразрывным + пробелом перед «%»: «62 %». +- Четырёхзначное значение («100 %») отметьте + `sf-progress-ring-content--long`: оно берёт ступень текста на одну меньше. +- Значение меняет страница: и переменную, и `aria-valuenow`. + +## Варианты + +### Размер + +`sf-progress-ring--size-1/4` … `sf-progress-ring--size-3` • [справочник](#классы) + +Ступени лестницы аватара: на каждой кольцо занимает рамку аватара того же +размера, поэтому стоит в одной строке с ним и с кнопкой со значком. +Процент в середине виден с размера `2`; на меньших ступенях середина +остаётся пустой, а значение говорит имя кольца. + +:::example {id="components/progress-ring/sizes" label="Шесть ступеней размера"} +::: + +### Статус + +`sf-progress-ring--neutral`, `--info`, `--success`, `--warning`, `--error` • [справочник](#классы) + +Статус красит заполненную часть цветом из общего словаря статусов; без +статуса она основного цвета темы. Кольцо не выводит статус из значения: +порог «с 80 % — предупреждение» ставит страница. + +:::example {id="components/progress-ring/status" label="Без статуса и пять статусов"} +::: + +## Состояния + +### Значение неизвестно + +`sf-progress-ring--indeterminate` • [справочник](#классы) + +Пока доля неизвестна, по дорожке бежит дуга спиннера. Уберите +`aria-valuenow` и процент из середины. При системной настройке уменьшения +движения дуга не бежит: кольцо стоит ровной подкрашенной дорожкой. + +:::example {id="components/progress-ring/indeterminate" label="Готовим отчёт"} +::: + +## Применение + +### Аватар в середине + +Кольцо вокруг аватара показывает занятую квоту или заполненный профиль, не +сдвигая картинку. Аватар на ступень меньше кольца (`sf-avatar--size-1` в +кольце `2`) заполняет середину точно, с зазором 2 px до линии. Величину в +известных границах — занятое место, а не ход задачи — называйте ролью +`meter` вместо `progressbar`. + +:::example {id="components/progress-ring/avatar" label="Аватар и занятое место"} +::: + +## Доступность + +- На `sf-progress-ring-indicator` — роль `progressbar` (ход задачи) или + `meter` (величина в границах), `aria-valuemin="0"`, `aria-valuemax="100"` + и текущее `aria-valuenow`. Пока значение неизвестно, `aria-valuenow` нет. +- Имя — ваша часть: `aria-label` («Загрузка файлов») или `aria-labelledby` + на видимую подпись. Значение словами («3 из 5 файлов») задаёт + `aria-valuetext`. +- Процент в середине скрыт от диктора (`aria-hidden="true"`), чтобы + значение не звучало дважды. +- Об окончании или ошибке сообщите отдельно, текстом с `role="status"`: + диктор не объявляет каждое изменение значения. + +## Классы + +| Что | Классы | +|:---|:---| +| Блок | `sf-progress-ring` | +| Части | `sf-progress-ring-content`, `sf-progress-ring-content--long`, `sf-progress-ring-indicator` | +| Модификаторы | `sf-progress-ring--error`, `sf-progress-ring--indeterminate`, `sf-progress-ring--info`, `sf-progress-ring--neutral`, `sf-progress-ring--success`, `sf-progress-ring--warning` | +| Размеры | `sf-progress-ring--size-1`, `sf-progress-ring--size-1/2`, `sf-progress-ring--size-1/3`, `sf-progress-ring--size-1/4`, `sf-progress-ring--size-2`, `sf-progress-ring--size-3` | + +Классы и переменные собраны из CSS выпуска и обновляются вместе с ним. + +## Переменные + +### Настройка + +Эти переменные — поверхность настройки компонента. Их имена стабильны: переименовать или убрать такую переменную можно только через журнал изменений, с предупреждением, как атрибут. Framework их не задаёт, поэтому значение можно поставить на сам компонент (`.sf-progress-ring`) или на любого предка. Переменные действуют на спокойный вид; наведение, фокус, нажатие, недоступность и ошибка рисуются поверх, поэтому состояния остаются видны. + +| Переменная | Что задаёт | По умолчанию | +|:---|:---|:---| +| `--sf-progress-ring-size` | Рамка кольца: высота элемента управления его размера, если переменная не задана. | `var(--sf-ui-1--control-height)`; зависит от размера | +| `--sf-progress-ring-line-width` | Толщина линии; можно задать и голый 0. | `var(--sf-a2)` | +| `--sf-progress-ring-gap` | Зазор между линией и тем, что стоит в середине; можно задать и голый 0. | `var(--sf-a2)` | +| `--sf-progress-ring-fill-color` | Заполненная часть; статус задаёт свой цвет, если эта переменная не задана. | `var(--sf-primary)`; зависит от статуса | +| `--sf-progress-ring-track-color` | Дорожка под заполненной частью. | `var(--sf-surface-container)` | +| `--sf-progress-ring-color` | Процент в середине. | `var(--sf-on-surface)` | + +```css +.sf-progress-ring { + --sf-progress-ring-size: var(--sf-ui-1--control-height); +} +``` + +### Устройство + +Остальные переменные — внутренняя проводка компонента: модификаторы задают им значения, а части их читают. Их имена и устройство могут меняться в любом выпуске, поэтому проект их не задаёт. Значение по умолчанию — из базового правила блока (`.sf-progress-ring`); переменную без него задают только модификаторы. + +| Переменная | По умолчанию | Задаёт | +|:---|:---|:---| +| `--sf-progress-ring--content-size` | не задана; задают модификаторы, например `.sf-progress-ring .sf-progress-ring-content`: `calc(var(--sf-progress-ring--size) - 2 * (var(--sf-progress-ring--line-width) + var(--sf-progress-ring--gap)))` | `width`, `inline-size`, `height`, `block-size`, `font-size`, `line-height`, `max-width`, `max-inline-size` | +| `--sf-progress-ring--fill` | `var(--sf-progress-ring-fill-color, var(--sf-primary))` | `background` | +| `--sf-progress-ring--font-size` | `var(--sf-text-size-1/3)` | `font-size` | +| `--sf-progress-ring--gap` | `var(--sf-progress-ring-gap, var(--sf-a2))` | `--sf-progress-ring--content-size`, `--sf-progress-ring--point-inset` | +| `--sf-progress-ring--line-width` | `var(--sf-progress-ring-line-width, var(--sf-progress-ring--step-line-width))` | `mask`, `--sf-progress-ring--content-size`, `--sf-progress-ring--point-inset` | +| `--sf-progress-ring--point-inset` | не задана; задают модификаторы, например `.sf-progress-ring .sf-progress-ring-content > sf-avatar .sf-online-indicator`: `calc( + (var(--sf-progress-ring--size) / 2 - var(--sf-progress-ring--line-width) - var(--sf-progress-ring--gap)) + - (var(--sf-progress-ring--size) / 2 - var(--sf-progress-ring--line-width) / 2) * sin(45deg) + - var(--sf-online-indicator--width) / 2 + )` | `bottom`, `inset-block-end`, `inset-inline-end` | +| `--sf-progress-ring--size` | `var(--sf-progress-ring-size, var(--sf-progress-ring--step-size))` | `width`, `inline-size`, `height`, `block-size`, `--sf-progress-ring--content-size`, `--sf-progress-ring--point-inset` | +| `--sf-progress-ring--step-line-width` | `var(--sf-a2)` | `--sf-progress-ring--line-width` | +| `--sf-progress-ring--step-size` | `var(--sf-ui-1--control-height)` | `--sf-progress-ring--size` | +| `--sf-progress-ring--track` | `var(--sf-progress-ring-track-color, var(--sf-surface-container))` | `background` | + +## См. также + +- [Кольцо прогресса — смарт-компонент](/ru/smart/feedback/progress-ring/) +- [Прогресс](/ru/components/feedback/progress-bar/) +- [Спиннер](/ru/components/feedback/spinner/) +- [Аватары](/ru/components/content/avatars/) diff --git a/content/ru/components/feedback/progress-ring.page.json b/content/ru/components/feedback/progress-ring.page.json new file mode 100644 index 00000000..92b4e591 --- /dev/null +++ b/content/ru/components/feedback/progress-ring.page.json @@ -0,0 +1,6 @@ +{ + "schema": "docara.page.v1", + "navigation": { + "order": 55 + } +} diff --git a/content/ru/components/index.md b/content/ru/components/index.md index 51897084..90d19898 100644 --- a/content/ru/components/index.md +++ b/content/ru/components/index.md @@ -61,6 +61,7 @@ profile: reference - **[Бейджи](/ru/components/feedback/badges/)** — короткий статус, категория или счётчик рядом с объектом. - **[Точка состояния](/ru/components/feedback/dot/)** — минимальный визуальный индикатор состояния. - **[Прогресс](/ru/components/feedback/progress-bar/)** — ход операции с известной степенью завершения. +- **[Кольцо прогресса](/ru/components/feedback/progress-ring/)** — доля выполненного кольцом в габарите элемента управления. - **[Шкала прогресса](/ru/components/feedback/progress-scale/)** — прогресс, разделённый на наглядные участки. - **[Спиннер](/ru/components/feedback/spinner/)** — ожидание операции с неизвестной длительностью. - **[Скелетон](/ru/components/feedback/skeleton/)** — стабильная форма содержимого во время загрузки данных. diff --git a/content/ru/guide/smart-components/names.md b/content/ru/guide/smart-components/names.md index f516cf8b..4dc84099 100644 --- a/content/ru/guide/smart-components/names.md +++ b/content/ru/guide/smart-components/names.md @@ -678,6 +678,14 @@ id?}` значит «перестать ждать», а `wait` принимае | событие `sf-file-upload-retry` | `sf-file-upload:retry` | работает, отмечается в `SF.deprecations` | 2026-12-01 | | событие `sf-file-upload-attach` | `sf-file-upload:select` | работает, отмечается в `SF.deprecations` | 2026-12-01 | +#### `` + +| Имя | Прежнее имя | Состояние | Убирается после | +|:---|:---|:---|:---| +| `groups="layout"` | `groups="structure"` | работает, отмечается в `SF.deprecations` | 2027-01-01 | +| `fields[].width="short"` | `fields[].width="s"` | работает, отмечается в `SF.deprecations` | 2027-01-01 | +| `fields[].width="medium"` | `fields[].width="m"` | работает, отмечается в `SF.deprecations` | 2027-01-01 | + #### `` | Имя | Прежнее имя | Состояние | Убирается после | diff --git a/content/ru/smart/actions/bulk-actions.md b/content/ru/smart/actions/bulk-actions.md new file mode 100644 index 00000000..7cf970b5 --- /dev/null +++ b/content/ru/smart/actions/bulk-actions.md @@ -0,0 +1,247 @@ +--- +title: "Групповые действия" +description: "Полоса у списка, пока в нём что-то выбрано: «Выбрано N», действия над выбранными, «Выбрать все N», вопрос перед опасным действием и итог." +--- + +# Групповые действия + +:badge[sf-bulk-actions]{variant=outline scheme=on-surface size=1/2} :badge[1.2.1]{variant=outline scheme=on-surface size=1/2} + +Полоса групповых действий появляется у списка, пока в нём что-то выбрано: +«Выбрано N», до трёх действий кнопками, остальные в «⋯» и крестик «Снять +выбор». Одна полоса служит таблице, карточкам, галерее, дереву и простому +списку. Что выбрано и как выполнить действие, решает список; полоса +показывает выбор, спрашивает перед опасным действием и сообщает итог. + +## Пример + +Отметьте несколько заказов и выберите действие. «В архив» можно отменить в +уведомлении, «Удалить» в меню «⋯» сначала спрашивает. Код — на вкладке +JavaScript. + +:::example {id="smart-components/bulk-actions/overview" label="Заказы: выбор и действия" preview=sandbox log="sf-bulk-actions-action sf-bulk-actions-undo sf-bulk-actions-clear" log_console=true log_open=false} +::: + +## Разметка + +Список ставит полосу после себя и пишет в неё, сколько выбрано: + +```html + +``` + +- `count` — сколько выбрано сейчас. Пока он `0`, полосы нет. Список пишет + его при каждом изменении выбора. +- `page-count` — сколько записей на экране, `total` — сколько всего по + фильтру. Когда выбрана вся страница, а записей по фильтру больше, полоса + предлагает «Выбрать все 240». +- `count-text` — своя строка счёта вместо «Выбрано N» («Выбрано 3 · с + вложенными 48»). +- `actions` — действия. Свойство задают из скрипта или в блоке настроек + ` + +``` + +Описание поля — тип и параметры из реестра полей (`propertyType`, +`template`, `templateParams`, `required`, `readonly`, `placeholder`, +`options`, `min`, `max`, `step`, `unit`, `decimals`, деньги — `currency`, +`currencies`, `currencyDisplay`) и ключи формы: + +| Ключ | Что задаёт | +|:---|:---| +| `key` | Имя значения в `value`. | +| `label` | Подпись над полем; ею же назван элемент управления. | +| `hint` | Подсказка под полем; ошибка встаёт на её место. Экранный диктор читает её вместе с полем. | +| `help` | Пояснение за знаком «?» после подписи. | +| `width` | `short` — не шире 20 знаков, `medium` — 28 знаков, `full` — во всю строку. Без него поле встаёт в пару с соседним. | +| `group` | Ключ группы из `groups`. | +| `when` | Когда поле показано, обязательно и доступно — см. [Условия полей](#условия-полей). | + +`groups` — группы `{key, label}` по порядку. От двух групп каждая — набор +полей с заголовком, между группами линия. Короткий выбор, до пяти +вариантов, форма рисует группой радиокнопок или флажков; длинный — +выпадающим списком. `readonly: true` показывает значение текстом, а не +выключенным полем. Поле типа, который модуль полей не рисует, не +показывается. + +## Варианты + +### Подписи + +`labels` • по умолчанию `top` • [справочник](#атрибуты) + +| Значение | Когда брать | +|:---|:---| +| `top` | Подпись над полем: заявка, правка записи, форма в окне. | +| `start` | Подпись слева, в трети строки, поле — в остальном: страница настроек, карточка в админке. Работает с 40rem ширины самой формы; уже — подпись снова над полем. | + +Раскладку форма выбирает по своей ширине, а не по ширине окна: от 44rem +поля без `width` встают по два в строку, уже — в одну колонку. + +:::example {id="smart-components/form/labels" label="Подпись над полем и слева"} +::: + +## Состояния + +### Просмотр + +`mode` • по умолчанию `edit` • [справочник](#атрибуты) + +`mode="view"` показывает значения текстом, как карточка записи, и кнопку +«Изменить» под ними. «Изменить» открывает поля; «Сохранить» и «Отмена» +возвращают просмотр. Пустое значение — тихое «Не указан». + +:::example {id="smart-components/form/view" label="Контакт: просмотр и правка" preview=sandbox log="sf-form-submit sf-form-cancel" log_console=true log_open=false} +::: + +### Ответ отправлен + +`apply="answer"`, `state` • [справочник](#атрибуты) + +Анкета, на которую отвечают один раз: сообщение в чате, запись в ленте. +Кнопки — «Отправить» и «Отмена». Нажатие проверяет поля и переводит форму в +`pending`: поля заперты, строка «Отправляем…», приходит `sf-form-answer`. +Исход ставит страница атрибутом `state`: `accepted` — значения текстом с +отметкой «Отправлено», `declined` — ничего, `expired` — «Время ответа +истекло», `open` — снова поля, если ответ не дошёл. `size="1/2"` делает +поля и кнопки на ступень меньше — для формы в сообщении. + +:::example {id="smart-components/form/answer" label="Оценка ответа в чате" preview=sandbox log="sf-form-answer" log_console=true log_open=false} +::: + +## Поведение + +### Сохранение и ошибки + +«Сохранить» всегда доступна: форма сама говорит, что не так. Нажатие (и +`Enter` в однострочном поле) проверяет поля. Если всё верно, приходит +`sf-form-submit` с `{value}` — значения всех показанных полей. Не +отменённое событие делает значения сохранёнными; отменённое оставляет форму +как есть, пока сервер не ответит. Ответ сервера с ошибками у полей — +метод `setErrors`: + +```js +form.addEventListener('sf-form-submit', async (event) => { + event.preventDefault(); // ждём ответа сервера + const answer = await save(event.detail.value); + if (answer.errors) form.setErrors({errors: answer.errors}); + else form.value = answer.value; // новое сохранённое состояние +}); +``` + +Ошибка встаёт у неверного поля после «Сохранить», потом — у поля, которое +изменили и покинули, и уходит, как только значение верно. От двух ошибок +над формой встаёт сводка «Исправьте 2 поля» со ссылкой на каждое поле, и +фокус переходит на неё; одна ошибка — фокус сразу в поле. После первого +изменения под кнопками появляется «Есть несохранённые изменения». «Отмена» +возвращает сохранённые значения и присылает `sf-form-cancel`. + +### Изменения сразу + +`apply="instant"` — каждое изменение действует сразу, кнопок нет: панель +настроек, параметры блока в редакторе. Изменение поля приходит событием +`sf-form-change` с `{key, value}`; «да / нет» по умолчанию — +переключатель. + +:::example {id="smart-components/form/instant" label="Параметры блока" log="sf-form-change" log_console=true log_open=false} +::: + +### Условия полей + +`when` в описании поля говорит, когда поле показано (`visible`), +обязательно (`required`) и доступно (`enabled`). Условие читает значения +других полей такими, какие они на экране сейчас: + +| Условие | Когда верно | +|:---|:---| +| `{"field": "k", "op": "eq", "value": v}` | значение поля `k` равно `v`; `ne` — не равно | +| `{"field": "k", "op": "in", "value": [v1, v2]}` | одно из перечисленных; `not_in` — ни одно | +| `{"field": "k", "op": "empty"}` | поле пустое; `not_empty` — заполнено | +| `{"field": "k", "op": "gt", "value": 1000}` | число или дата больше; `gte`, `lt`, `lte` — больше или равно, меньше, меньше или равно | +| `{"all": […]}`, `{"any": […]}`, `{"not": {…}}` | все условия, хотя бы одно, условие неверно | + +Скрытое поле не проверяется и не отправляется, но форма помнит его +значение: если поле покажется снова, значение вернётся. Недоступное поле +показано текстом, как `readonly`. + +:::example {id="smart-components/form/conditions" label="Адрес только для курьера" preview=sandbox log="sf-form-submit sf-form-invalid" log_console=true log_open=false} +::: + +### Значения из скрипта + +- `value` — значения по ключам. Заданное из скрипта — сохранённое + состояние: форма показывает его, забывает ошибки и не считается + изменённой. Прочитанное — то, что в полях сейчас. +- `valid` — все поля сейчас верны, `dirty` — есть несохранённые изменения; + оба только читаются. +- `checkValidity()` проверяет поля и показывает ошибки без отправки; + `reset()` возвращает сохранённые значения без событий. +- `fieldHost` — свойство для записи, которая сама листает выбор записей и + загружает файлы (карточка записи передаёт его форме при правке группы). + +### Внешний вид + +Открытые переменные: `--sf-form-field-gap`, `--sf-form-group-gap`, +`--sf-form-label-color`, `--sf-form-summary-background-color` и +`--sf-form-footer-background-color`. `footer="sticky"` ставит кнопки в +полосу, которая прилипает к низу прокручиваемого места, пока форма длиннее +его: длинная страница настроек. + +## Доступность + +- Форма — ориентир «форма» с именем из `label`; лучше всего — заголовок, + под которым она стоит. +- Подпись называет поле, подсказка и ошибка связаны с полем и читаются + вместе с ним; группы — наборы полей с заголовком. +- `Tab` идёт по полям по порядку, затем «Сохранить» и «Отмена» (в просмотре + — «Изменить»). +- После отправки с одной ошибкой фокус в поле, с двумя и больше — на + сводке (`role="alert"`); ссылка сводки переводит фокус в своё поле. +- «Изменить» переводит фокус в первое поле, возврат в просмотр — на + «Изменить». + +## Справочник + +### Атрибуты + +| Атрибут | Тип | По умолчанию | Значения | Что делает | +|:---|:---|:---|:---|:---| +| `apply` | строка | `submit` | `submit`, `instant`, `answer` | `submit` — форма сохраняется кнопкой: «Сохранить» и «Отмена» под полями, обязательное «да / нет» — флажок, после изменения под кнопками «Есть несохранённые изменения». `instant` — каждое изменение действует сразу: кнопок нет, событие изменения на каждое поле, обязательное «да / нет» — переключатель (панель настроек, параметры блока). `answer` — форма, на которую отвечают один раз: анкета в сообщении или записи ленты; «Отправить» и «Отмена» под полями, нажатие отправляет ответ (состояние `pending`, «Отправляем…»), исход ставит приложение; `accepted` показывает значения текстом с отметкой «Отправлено» и без «Изменить», снова их не открыть; `mode` не читается. | +| `size` | строка | `1` | `1`, `1/2` | Ступень полей и кнопок на линейке размеров: `1` или `1/2` — для формы в сообщении. Подпись, подсказка и ошибка стоят на ступени текста `1/2` при обоих. | +| `state` | строка | `open` | `open`, `pending`, `accepted`, `declined`, `expired` | Только при `apply="answer"`: где ответ, словами поверхности подтверждения (`sf-confirm`). `open` — поля, «Отправить» и «Отмена». `pending` — ответ в пути, ставится нажатием: поля заперты, нажатая кнопка ждёт, «Отправляем…» («Отменяем…»). `accepted` — отправленные значения текстом с «Отправлено». `declined` — ничего не рисуется: отказ ничего не говорит. `expired` — только «Время ответа истекло». Исход ставит приложение; `open` снова — если ответ не дошёл (с `setErrors` для полей, которые нужно исправить). | +| `labels` | строка | `top` | `top`, `start` | `top` — подпись над полем (по умолчанию). `start` — от 40rem ширины самой формы подпись стоит слева в трети строки, поле — в остальном: строка страницы настроек и карточки в админке; уже — над полем. | +| `footer` | строка | `static` | `static`, `sticky` | `static` — кнопки под последним полем, главная первой в начале. `sticky` — те же кнопки в полосе, которая прилипает к низу прокручиваемого места, пока форма длиннее его: страница настроек. | +| `label` | строка | пусто | — | Доступное имя формы (`aria-label` формы): экранный диктор называет по нему ориентир «форма»; лучше всего — заголовок, под которым стоит форма. | +| `mode` | строка | `edit` | `edit`, `view` | `edit` — поля. `view` — значения текстом (вид модуля полей для просмотра, как в карточке записи) и «Изменить» под ними; «Изменить» открывает правку, «Сохранить» и «Отмена» возвращают просмотр. | +| `fields` | список | `[]` | — | Поля по порядку: описание поля SIMAI Framework, то же, что передаёт `sf-view-properties`, — тип из реестра свойств, его шаблон и параметры (`propertyType`, `template` и `templateParams`, `required`, `readonly`, `placeholder`, `options`, `min`, `max`, `step`, `unit`, `decimals`, `currency`, `currencies`, `currencyDisplay`, `holder` — для поля ИНН: `any`, `organization` (10 цифр) или `person` (12), `defaultCountry` — для телефона: страна ISO 3166 alpha-2, с которой начинается пустое поле, иначе страна страницы … как их перечисляет `SF.fieldRenderers.registry`) и ключи формы `key`, `label`, `hint`, `help`, `width` и `group`. `width`: `short` (шаг ширины поля в 20 знаков, 160 px при тексте 16), `medium` (28 знаков, 224 px) или `full`; без него поле встаёт в пару с соседним от 44rem ширины самой формы. Поле типа, который модуль полей не рисует, не показывается. | +| `groups` | список | `[]` | — | Группы, которые называют ключи `group` полей, по порядку: `{key, label}`. От двух групп каждая — набор полей с подписью-заголовком, между группами 24 и линия. Поле без группы или с группой не из списка стоит в своей группе после перечисленных. | +| `field-host` | объект | `null` | — | Половина интерфейса хозяина полей, которую держит запись; только свойство. `getFieldOptionsPage`, `getFieldOptionSearch`, `setFieldOptionSearch` и `loadFieldOptions` листают и ищут выбор записи, связи или сотрудника (шаблон `reference_picker`); `getFieldUploads`, `startFieldUpload` и `retryFieldUpload` передают файл (шаблон `upload`: форма рисует поле загрузки, и оно само говорит свою ошибку); `getFieldText` и `formatFieldValue` — слова и формат хозяина; `renderField(field, value, host, {editing, size})` рисует тип, который рисует набор компонентов (`items`, `complex`, `ru.requisites`). Каждый вызывается с аргументами модуля полей и последним аргументом — хозяином формы для этого поля; его `setFieldValue` пишет в значение формы (например, сохранённый файл). Значения, их проверка и отправка остаются формы. Без этого свойства выбор листает собственные `options` поля, а файловое поле держит выбранные файлы в значении (`{name, size, mime, file}`: сам `File` приложение отправляет вместе со значениями). | +| `value` | объект | `{}` | — | Значения по ключам полей: `{text: "Подробнее", tone: "accent"}`. Заданное из кода — сохранённое состояние: форма показывает его, забывает ошибки и не считается изменённой. Прочитанное — то, что сейчас в полях и что уйдёт при сохранении: поле, скрытое условием (`when.visible`), в него не входит, но форма помнит его значение, и оно вернётся, когда поле покажется снова. Значения, которое человек не задавал, нет. | + +#### Общие для всех компонентов + +| Атрибут | Тип | По умолчанию | Значения | Что делает | +|:---|:---|:---|:---|:---| +| `template` | строка | `default` | — | Имя шаблона отрисовки; `default` — встроенный. | +| `root-class` | строка | пусто | — | Свои CSS-классы для нарисованного элемента. | +| `root-style` | строка | пусто | — | Свои стили для нарисованного элемента, например `max-width: 20rem`. | + +Каждому атрибуту соответствует свойство элемента с тем же именем в camelCase: `icon-start` — `iconStart`. Свойство атрибута `template` называется `templateName`. + +### Методы + +| Метод | Возвращает | Что делает | +|:---|:---|:---| +| `checkValidity()` | объект | Проверяет каждое показанное поле и показывает все ошибки, как «Сохранить», но без отправки: `applied`, если всё верно, иначе отказ `{reason: invalid}`. Фокус не переводит. | +| `reset()` | объект | Каждое поле возвращается к сохранённому состоянию, без событий; ошибки и сводка уходят. | +| `refreshFields()` | объект | Ответы хозяина полей изменились — страница вариантов, ход загрузки, сохранённый файл — и поля рисуются заново с тем, что он отвечает сейчас. Когда вызов хозяина отвечает обещанием, форма перерисовывается сама, как только оно выполнено. | +| `setErrors(args: object)` | объект | Ответ приложения на отправку: `{ключ: сообщение}` — каждое названное поле показывает сообщение как свою ошибку, пока человек его не изменит; от двух ошибок сводка получает фокус, как после «Сохранить»; пустой объект снимает ошибки. Форма в просмотре открывает правку. Отказ `{reason: missing}`, если ни один ключ не называет показанное поле. | + +### События + +События приходят на сам элемент и всплывают; глаголы в именах — из [общего словаря](/ru/guide/smart-components/names/). Общие события базового элемента — в главе [Модель компонента](/ru/guide/smart-components/model/#базовый-интерфейс). + +| Событие | `detail` | Когда приходит | +|:---|:---|:---| +| `sf-form-input` | `{ key: string, value: string }` | Человек изменил значение поля: его ключ и новое значение (`undefined`, если поле отказалось от недописанного текста). Приходит как `sf-form-input`, а не `input`: собственные события `input` полей проходят через форму без изменений. | +| `sf-form-change` | `{ key: string, value: string }` | Только при `apply="instant"`: значение поля применено. Приходит как `sf-form-change`, а не `change`: собственные события `change` полей проходят через форму без изменений. | +| `sf-form-submit` | `{ value: object }` | `apply="submit"`: «Сохранить» (или Enter в однострочном поле) нашла все поля верными; `value` — значения всех показанных полей по ключам (поле, скрытое условием, не отправляется). Не отменённое событие делает значение сохранённым (`dirty` false), и форма, открытая из просмотра, возвращается в просмотр; отменённое — форма остаётся как есть (приложение ответит позже через `setErrors` или новым `value`). | +| `sf-form-answer` | `{ accepted: boolean, value?: object }` | `apply="answer"`: «Отправить» нашла все поля верными (`accepted` true, со значением) или нажата «Отмена» (`accepted` false). Приходит в состоянии `pending`; исход ставит приложение в обработчике или позже: `accepted`, `declined` или снова `open`. Отменённое событие — ответ не принят: форма снова открыта, и на неё можно ответить ещё раз. | +| `sf-form-invalid` | `{ fields: array }` | Отправка или `checkValidity()` нашли неверные поля: их ключи по порядку. У каждого поля — его ошибка; от двух ошибок над формой встаёт сводка со ссылкой на каждое поле и получает фокус. Ошибка приложения (`setErrors`) для поля, которое скрыто условием, называется в сводке подписью поля, без ссылки, и не задерживает следующую отправку. | +| `sf-form-cancel` | `{ value: object }` | «Отмена»: поля вернулись к сохранённому состоянию (`value`), ошибки ушли; форма, открытая из просмотра, возвращается в просмотр. | + +### О компоненте + +| | | +|:---|:---| +| Тег | ``, контракт `smart.form` версии `1.13.0` | +| Поставка | выпуск Framework `ui-9ceecc24c988` | +| [Готовность](/ru/guide/smart-components/quality/#готовность-компонента-к-использованию) | Пробный: может измениться в следующих выпусках; описан и проверен своим сценарием, в продуктах ещё не проверен. | +| До прихода кода | Заготовки нет. Подробнее — [Коробка до кода](/ru/guide/smart-components/first-paint/#коробка-до-кода). | +| Доступность | Роль `form`; желательна подпись или `aria-label`; с клавиатуры: Tab идёт по полям по порядку, затем «Сохранить» и «Отмена» (в просмотре — «Изменить»); Enter в однострочном поле отправляет форму; После отправки с двумя ошибками и больше фокус на сводке; Tab доходит до её ссылок, Enter на ссылке переводит фокус в поле. | +| Источник | `simai/ui@9ceecc24c988209abc7d09e22522eeb7b73f485e:distr/smart/form` | +| Правило классов | `simai/ui@9ceecc24c988209abc7d09e22522eeb7b73f485e:distr/rule/rule.json#name=cl-form` | + +## См. также + +- [Настройки](/ru/smart/navigation/settings/) — строки меню настроек вместо формы. +- [Поля формы](/ru/guide/components/form-fields/) — форма, свёрстанная полями вручную. +- [Текстовое поле](/ru/smart/forms/inputs/) — поле, которое форма рисует для строки. +- [Подтверждение](/ru/smart/actions/confirm/) — вопрос с ответом на месте, без полей. diff --git a/content/ru/smart/forms/form.page.json b/content/ru/smart/forms/form.page.json new file mode 100644 index 00000000..42278c0a --- /dev/null +++ b/content/ru/smart/forms/form.page.json @@ -0,0 +1,6 @@ +{ + "schema": "docara.page.v1", + "navigation": { + "order": 120 + } +} diff --git a/content/ru/smart/forms/index.md b/content/ru/smart/forms/index.md index ba950ec6..de0df1f5 100644 --- a/content/ru/smart/forms/index.md +++ b/content/ru/smart/forms/index.md @@ -43,3 +43,4 @@ profile: reference - [Цвет](/ru/smart/forms/color/) — Выбирает цвет из палитры SIMAI Framework, из цветов продукта или свой, возвращает к унаследованному цвету и строит тему сайта из фирменного цвета. - [Загрузка файлов](/ru/smart/forms/file-upload/) — Даёт выбрать или перетащить файлы и показывает их список, прогресс и ошибки передачи. - [Поле изображения](/ru/smart/forms/image-field/) — Даёт выбрать одно изображение: миниатюра, имя и размер файла, замена, удаление и перетаскивание. +- [Форма](/ru/smart/forms/form/) — Форма из описаний полей: подписи, ошибки, группы, кнопки, просмотр и ответ. diff --git a/content/ru/smart/index.md b/content/ru/smart/index.md index 6a990f1c..e1e959c8 100644 --- a/content/ru/smart/index.md +++ b/content/ru/smart/index.md @@ -17,6 +17,7 @@ description: "Смарт-компоненты по задачам интерфе - [Кнопка копирования](/ru/smart/actions/copy-button/) - [Подтверждение](/ru/smart/actions/confirm/) - [Подтверждение изменения](/ru/smart/actions/confirm-change/) +- [Групповые действия](/ru/smart/actions/bulk-actions/) — Полоса у списка, пока в нём что-то выбрано: «Выбрано N», действия над выбранными и итог. ## Формы и ввод @@ -36,6 +37,7 @@ description: "Смарт-компоненты по задачам интерфе - [Цвет](/ru/smart/forms/color/) - [Загрузка файлов](/ru/smart/forms/file-upload/) - [Поле изображения](/ru/smart/forms/image-field/) +- [Форма](/ru/smart/forms/form/) — Форма из описаний полей: подписи, ошибки, группы, кнопки, просмотр и ответ. ## Навигация @@ -51,6 +53,7 @@ description: "Смарт-компоненты по задачам интерфе - [Контекстное меню](/ru/smart/navigation/context-menu/) - [Настройки](/ru/smart/navigation/settings/) - [Выбор языка](/ru/smart/navigation/language/) +- [Настройки отображения](/ru/smart/navigation/display-settings/) — Размер текста, цветовая схема, интервалы, картинки и движение для всего сайта. ## Уведомления и состояния @@ -75,6 +78,7 @@ description: "Смарт-компоненты по задачам интерфе - [Аватары](/ru/smart/content/avatars/) - [Иконки](/ru/smart/content/icons/) - [Теги](/ru/smart/content/tags/) +- [Группа тегов](/ru/smart/content/tag-group/) — Ряд тегов с одним шагом Tab, «+N» в одну строку и выбором фильтров. - [Строка списка](/ru/smart/content/list-item/) - [Список](/ru/smart/content/list/) - [Лента](/ru/smart/content/list-feed/) diff --git a/content/ru/smart/navigation/display-settings.md b/content/ru/smart/navigation/display-settings.md new file mode 100644 index 00000000..36242bae --- /dev/null +++ b/content/ru/smart/navigation/display-settings.md @@ -0,0 +1,180 @@ +--- +title: "Настройки отображения" +description: "Кнопка и панель, в которой человек выбирает размер текста, цветовую схему, интервалы, картинки и движение для всего сайта." +--- + +# Настройки отображения + +:badge[sf-display-settings]{variant=outline scheme=on-surface size=1/2} :badge[1.1.5]{variant=outline scheme=on-surface size=1/2} + +Настройки отображения дают посетителю сайта крупнее текст, другую цветовую +схему, шире интервалы, картинки серыми или скрытыми и остановку движения — +то, чего он не нашёл в настройках своего устройства. Панель только +записывает выбор; показывает его ядро SIMAI Framework на каждой странице +сайта, в том числе там, где панели нет. Берите её для сайта школы, +библиотеки, ведомства, где просят «версию для слабовидящих», и для любого +сайта, который хочет дать людям размер текста и контраст. Зачем это и где +граница с настоящей доступностью — в главе +[Настройки отображения](/ru/guide/accessibility/display-settings/). + +## Пример + +Откройте «Версию для слабовидящих» и нажмите «А+» или «Жёлтый на чёрном»: +меняется весь пример. `Escape` закрывает панель. Код — на вкладке +JavaScript. + +:::example {id="smart-components/display-settings/overview" label="Кнопка в шапке сайта" preview=sandbox log="sf-display-settings-change" log_console=true log_open=false} +::: + +## Разметка + +```html + +``` + +- `label` — подпись кнопки и имя панели. Без него — «Настройки + отображения». На российских сайтах, где кнопку ищут по старому имени, + пишут «Версия для слабовидящих». +- Больше ничего не нужно: панель сама хранит выбор в браузере человека, а + ядро применяет его на каждой странице. + +## Варианты + +### Кнопка или панель + +`layout` • по умолчанию `disclosure` • [справочник](#атрибуты) + +| Значение | Когда брать | +|:---|:---| +| `disclosure` | Кнопка в шапке или подвале; панель раскрывается под ней. | +| `panel` | Панель стоит открытой, без кнопки: своя страница настроек, подвал. | + +:::example {id="smart-components/display-settings/panel" label="Панель на странице" preview=sandbox} +::: + +### Шрифт и ссылки + +`show-font`, `show-links` • по умолчанию выключены • [справочник](#атрибуты) + +Две группы включает автор сайта: «Шрифт» — шрифт сайта, без засечек или с +засечками; «Ссылки» — подчёркивать ссылки. В цветовой схеме ссылки +подчёркнуты всегда. + +:::example {id="smart-components/display-settings/extra" label="Со шрифтом и ссылками" preview=sandbox} +::: + +## Поведение + +### Что в панели + +| Группа | Варианты | +|:---|:---| +| Текст | 100, 125, 150, 175 и 200 %: доля размера текста браузера, а не замена его | +| Цвет | Как на сайте; чёрный на белом, белый на чёрном, жёлтый на чёрном, синий на голубом, коричневый на кремовом | +| Интервалы | Обычные или шире: строка, абзацы, буквы и слова по WCAG 1.4.12 | +| Картинки | Цветные, чёрно-белые или скрытые; на месте скрытой картинки — её описание `alt` | +| Движение | Как в системе или остановить: анимации и переходы стоят | +| Обычная версия | Всё как на сайте, выбор забыт | + +Если в системе включены контрастные цвета (`forced-colors`), группа «Цвет» +выключена и говорит «Цвета задаёт система». Если устройство уже уменьшает +движение, группа «Движение» говорит об этом. + +### Где хранится выбор + +Только в браузере человека: в `localStorage`, без cookie, ничего не уходит +на сервер. Ядро пишет выбор на `` атрибутами `data-sf-scheme`, +`data-sf-text-scale`, `data-sf-text-spacing`, `data-sf-images`, +`data-sf-motion`, `data-sf-font` и `data-sf-links`; сайт может поставить их +и сам. Из скрипта выбор читает и пишет +[`SF.displaySettings`](/ru/guide/functions/person/display-settings/). + +### Событие и сброс + +Человек изменил настройку — приходит `sf-display-settings-change` с +`{settings, previous, setting}`: `setting` — что изменилось (`scheme`, +`textScale`, `textSpacing`, `images`, `motion`, `font`, `links`) или +`reset`. Событие приходит после того, как страница уже показывает выбор. +Свойство `settings` — выбор сейчас, только для чтения. Метод `reset()` — то +же, что «Обычная версия». + +```js +const panel = document.querySelector('sf-display-settings'); +panel.addEventListener('sf-display-settings-change', (event) => { + console.log(event.detail.setting, event.detail.settings); +}); +``` + +### Внешний вид + +Открытые переменные: `--sf-display-settings-background` (поверхность +панели), `--sf-display-settings-border-color` (край), +`--sf-display-settings-label-color` (подписи групп), +`--sf-display-settings-gap` (между группами) и +`--sf-display-settings-group-gap` (внутри группы). + +## Доступность + +- Кнопка — обычная кнопка с `aria-expanded`; `Escape` закрывает панель и + возвращает фокус на кнопку. +- Панель — группа с именем из `label`; каждая настройка — группа с + подписью, выбор — кнопки-переключатели с `aria-pressed`. «А−» и «А+» + названы словами: «Текст меньше», «Текст больше». +- Панель — удобство, а не заявление о доступности: ни подпись, ни текст + рядом не обещают, что сайт соответствует стандарту. Основной сайт + отвечает WCAG сам. + +## Справочник + +### Атрибуты + +| Атрибут | Тип | По умолчанию | Значения | Что делает | +|:---|:---|:---|:---|:---| +| `label` | строка | — | — | Подпись кнопки и имя панели. Не задано — «Настройки отображения». Российский сайт, где кнопку ищут по названию, пишет «Версия для слабовидящих». | +| `layout` | строка | `disclosure` | `disclosure`, `panel` | `disclosure` — кнопка, которая раскрывает панель под собой (`aria-expanded`); Escape закрывает её, и фокус возвращается на кнопку. `panel` — панель стоит открытой, без кнопки (своя страница, подвал). | +| `open` | да/нет | нет | — | Открыта ли панель вида `disclosure`; кнопка переключает её, Escape закрывает. | +| `show-font` | да/нет | нет | — | Показывает группу «Шрифт»: шрифт сайта, без засечек или с засечками (системные `--sf-sans` и `--sf-serif`). По умолчанию выключено: включает автор сайта. | +| `show-links` | да/нет | нет | — | Показывает «Подчёркивать ссылки». По умолчанию выключено: включает автор сайта. В цветовой схеме ссылки подчёркнуты всегда. | + +#### Общие для всех компонентов + +| Атрибут | Тип | По умолчанию | Значения | Что делает | +|:---|:---|:---|:---|:---| +| `template` | строка | `default` | — | Имя шаблона отрисовки; `default` — встроенный. | +| `root-class` | строка | пусто | — | Свои CSS-классы для нарисованного элемента. | +| `root-style` | строка | пусто | — | Свои стили для нарисованного элемента, например `max-width: 20rem`. | + +Каждому атрибуту соответствует свойство элемента с тем же именем в camelCase: `icon-start` — `iconStart`. Свойство атрибута `template` называется `templateName`. + +### Методы + +| Метод | Возвращает | Что делает | +|:---|:---|:---| +| `reset()` | объект | «Обычная версия»: все настройки возвращаются к виду сайта, запомненный выбор удаляется; приходит `change` с `setting` `reset`. Отказ `{reason: unchanged}`, если ничего не меняли. | + +### События + +События приходят на сам элемент и всплывают; глаголы в именах — из [общего словаря](/ru/guide/smart-components/names/). Общие события базового элемента — в главе [Модель компонента](/ru/guide/smart-components/model/#базовый-интерфейс). + +| Событие | `detail` | Когда приходит | +|:---|:---|:---| +| `sf-display-settings-change` | `{ settings: object, previous: object, setting: string }` | Человек изменил настройку или выбрал «Обычную версию»: событие приходит, когда страница уже показывает выбор и браузер его запомнил. Никуда ничего не отправляется; страница, которой нужно знать, слушает это событие. | + +### О компоненте + +| | | +|:---|:---| +| Тег | ``, контракт `smart.display-settings` версии `1.1.5` | +| Поставка | выпуск Framework `ui-9ceecc24c988` | +| [Готовность](/ru/guide/smart-components/quality/#готовность-компонента-к-использованию) | Пробный: может измениться в следующих выпусках; описан и проверен своим сценарием, в продуктах ещё не проверен. | +| До прихода кода | Заготовки нет. Подробнее — [Коробка до кода](/ru/guide/smart-components/first-paint/#коробка-до-кода). | +| Доступность | Читается как группа; нужна подпись или `aria-label`; с клавиатуры: Tab доходит до кнопки и каждой кнопки панели; Enter или пробел нажимает её; Escape в открытой панели вида `disclosure` закрывает её и возвращает фокус на кнопку. | +| Источник | `simai/ui@9ceecc24c988209abc7d09e22522eeb7b73f485e:distr/smart/display-settings` | +| Правило классов | `simai/ui@9ceecc24c988209abc7d09e22522eeb7b73f485e:distr/rule/rule.json#name=cl-display-settings` | + +## См. также + +- [Настройки отображения](/ru/guide/accessibility/display-settings/) — зачем панель и чего она не делает. +- [`SF.displaySettings`](/ru/guide/functions/person/display-settings/) — выбор из скрипта. +- [Настройки](/ru/smart/navigation/settings/) — меню настроек продукта: тема, язык, размер текста. +- [Выбор языка](/ru/smart/navigation/language/) diff --git a/content/ru/smart/navigation/display-settings.page.json b/content/ru/smart/navigation/display-settings.page.json new file mode 100644 index 00000000..4e60fb95 --- /dev/null +++ b/content/ru/smart/navigation/display-settings.page.json @@ -0,0 +1,6 @@ +{ + "schema": "docara.page.v1", + "navigation": { + "order": 95 + } +} diff --git a/content/ru/smart/navigation/index.md b/content/ru/smart/navigation/index.md index 9ee8b7f2..6df2490b 100644 --- a/content/ru/smart/navigation/index.md +++ b/content/ru/smart/navigation/index.md @@ -36,3 +36,4 @@ profile: reference - [Контекстное меню](/ru/smart/navigation/context-menu/) — Показывает короткий список действий над объектом с клавиатурной моделью меню. - [Настройки](/ru/smart/navigation/settings/) — Компактная панель настроек: переключатели, варианты и ползунки, которые человек меняет на месте, у кнопки или в потоке страницы. - [Выбор языка](/ru/smart/navigation/language/) — Переключает язык сайта: одна кнопка с кодом языка открывает меню языков, от восьми языков в меню есть поиск. +- [Настройки отображения](/ru/smart/navigation/display-settings/) — Размер текста, цветовая схема, интервалы, картинки и движение для всего сайта. diff --git a/examples/components/progress-ring/avatar/index.html b/examples/components/progress-ring/avatar/index.html new file mode 100644 index 00000000..75428e73 --- /dev/null +++ b/examples/components/progress-ring/avatar/index.html @@ -0,0 +1,4 @@ +
+
+ Анна Ким · занято 85 % места +
diff --git a/examples/components/progress-ring/basic/index.html b/examples/components/progress-ring/basic/index.html new file mode 100644 index 00000000..9a239547 --- /dev/null +++ b/examples/components/progress-ring/basic/index.html @@ -0,0 +1,4 @@ +
+
+ Загрузка файлов: 62 % +
diff --git a/examples/components/progress-ring/indeterminate/index.html b/examples/components/progress-ring/indeterminate/index.html new file mode 100644 index 00000000..f6939335 --- /dev/null +++ b/examples/components/progress-ring/indeterminate/index.html @@ -0,0 +1,4 @@ +
+
+ Готовим отчёт +
diff --git a/examples/components/progress-ring/sizes/index.html b/examples/components/progress-ring/sizes/index.html new file mode 100644 index 00000000..67c1dfd3 --- /dev/null +++ b/examples/components/progress-ring/sizes/index.html @@ -0,0 +1,28 @@ +
+
+
+
+ 1/4 +
+
+
+ 1/3 +
+
+
+ 1/2 +
+
+
+ 1 +
+
+
+ 2 +
+
+
+ 3 +
+
+
diff --git a/examples/components/progress-ring/status/index.html b/examples/components/progress-ring/status/index.html new file mode 100644 index 00000000..6d2ab84b --- /dev/null +++ b/examples/components/progress-ring/status/index.html @@ -0,0 +1,28 @@ +
+
+
+
+ без статуса +
+
+
+ neutral +
+
+
+ info +
+
+
+ success +
+
+
+ warning +
+
+
+ error +
+
+
diff --git a/examples/smart-components/bulk-actions/all/index.html b/examples/smart-components/bulk-actions/all/index.html new file mode 100644 index 00000000..0dc6440c --- /dev/null +++ b/examples/smart-components/bulk-actions/all/index.html @@ -0,0 +1,7 @@ +
+
На странице 12 заказов из 240 по фильтру «Ждут оплаты»; выбраны все 12.
+ + + +

+
diff --git a/examples/smart-components/bulk-actions/all/index.js b/examples/smart-components/bulk-actions/all/index.js new file mode 100644 index 00000000..f5665d2b --- /dev/null +++ b/examples/smart-components/bulk-actions/all/index.js @@ -0,0 +1,20 @@ +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +const start = async () => { + const SF = await sfReady(); + await SF.whenDefined(['bulk-actions']); + const bar = document.querySelector('#bulk-all'); + const said = document.querySelector('#bulk-all-said'); + + // scope says what the action goes to: the rows on screen or all under the filter. + bar.addEventListener('sf-bulk-actions-action', (event) => { + const {id, scope, count} = event.detail; + said.textContent = `Действие ${id}: ${scope === 'all' ? 'все по фильтру' : 'выбранные на странице'}, ${count}.`; + bar.result({id, ok: count, failed: []}); + }); + bar.addEventListener('sf-bulk-actions-clear', () => { + bar.count = 12; // the example keeps its page selected + }); +}; + +start(); diff --git a/examples/smart-components/bulk-actions/overview/index.html b/examples/smart-components/bulk-actions/overview/index.html new file mode 100644 index 00000000..be1a62ef --- /dev/null +++ b/examples/smart-components/bulk-actions/overview/index.html @@ -0,0 +1,10 @@ +
+
    +
  • +
  • +
  • +
  • +
  • +
+ +
diff --git a/examples/smart-components/bulk-actions/overview/index.js b/examples/smart-components/bulk-actions/overview/index.js new file mode 100644 index 00000000..91511031 --- /dev/null +++ b/examples/smart-components/bulk-actions/overview/index.js @@ -0,0 +1,53 @@ +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +const start = async () => { + const SF = await sfReady(); + await SF.whenDefined(['bulk-actions', 'checkbox']); + const bar = document.querySelector('#bulk-bar'); + const list = document.querySelector('#bulk-orders'); + let archived = []; + + bar.actions = [ + {id: 'paid', text: 'Отметить оплаченными', icon: 'payments', 'done-text': 'Отмечено'}, + {id: 'export', text: 'Экспорт', icon: 'download', 'done-text': 'Выгружено'}, + {id: 'archive', text: 'В архив', icon: 'archive', undo: true}, + {id: 'delete', text: 'Удалить', icon: 'delete', status: 'danger', 'done-text': 'Удалено'}, + ]; + + // The list owns the selection: it writes count on every change. + const boxes = () => [...list.querySelectorAll('sf-checkbox')]; + const selected = () => boxes().filter((box) => box.checked); + const update = () => { + bar.count = selected().length; + bar.pageCount = boxes().length; + }; + list.addEventListener('change', update); + + // The bar asks (and asks again before a dangerous action); the list does the work. + bar.addEventListener('sf-bulk-actions-action', (event) => { + const {id} = event.detail; + const rows = selected().map((box) => box.closest('li')); + if (id === 'archive') archived = rows; + if (id === 'archive' || id === 'delete') rows.forEach((row) => row.remove()); + else selected().forEach((box) => { box.checked = false; }); + bar.result({id, ok: rows.length, failed: []}); + update(); + }); + + // «Отменить» in the notice of a reversible action: the list puts the rows back. + bar.addEventListener('sf-bulk-actions-undo', () => { + archived.forEach((row) => { row.querySelector('sf-checkbox').checked = false; }); + const order = (row) => Number(row.querySelector('sf-checkbox').dataset.id); + list.append(...[...list.children, ...archived].sort((a, b) => order(a) - order(b))); + archived = []; + update(); + }); + + // × and Escape: the list drops its selection. + bar.addEventListener('sf-bulk-actions-clear', () => { + boxes().forEach((box) => { box.checked = false; }); + update(); + }); +}; + +start(); diff --git a/examples/smart-components/bulk-actions/place/index.html b/examples/smart-components/bulk-actions/place/index.html new file mode 100644 index 00000000..1d31d431 --- /dev/null +++ b/examples/smart-components/bulk-actions/place/index.html @@ -0,0 +1,23 @@ +
+
+ top + + + +
Список
+
+
+ dock +
Список
+ + + +
+
+ inline +
Список
+ + + +
+
diff --git a/examples/smart-components/bulk-actions/result/index.html b/examples/smart-components/bulk-actions/result/index.html new file mode 100644 index 00000000..ea278cef --- /dev/null +++ b/examples/smart-components/bulk-actions/result/index.html @@ -0,0 +1,6 @@ +
+
Выбрано 12 страниц сайта. Две из них опубликовать нельзя.
+ + + +
diff --git a/examples/smart-components/bulk-actions/result/index.js b/examples/smart-components/bulk-actions/result/index.js new file mode 100644 index 00000000..f07157d7 --- /dev/null +++ b/examples/smart-components/bulk-actions/result/index.js @@ -0,0 +1,28 @@ +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +const start = async () => { + const SF = await sfReady(); + await SF.whenDefined(['bulk-actions']); + const bar = document.querySelector('#bulk-run'); + + bar.addEventListener('sf-bulk-actions-action', async (event) => { + const {id, count} = event.detail; + // A short run shows its progress in the bar. + for (let done = 1; done <= count; done += 1) { + bar.progress({done, total: count}); + await wait(150); + } + // Failed items stay selected; the bar offers «Подробнее» and «Повторить». + bar.result({id, ok: count - 2, failed: [ + {id: 'p3', text: 'Склад', reason: 'Нет главной страницы'}, + {id: 'p5', text: 'Блог', reason: 'Нет прав на раздел'}, + ]}); + bar.count = 2; + }); + bar.addEventListener('sf-bulk-actions-clear', () => { + bar.count = 12; // the example keeps its rows selected + }); +}; + +start(); diff --git a/examples/smart-components/bulk-actions/sizes/index.html b/examples/smart-components/bulk-actions/sizes/index.html new file mode 100644 index 00000000..5c581e67 --- /dev/null +++ b/examples/smart-components/bulk-actions/sizes/index.html @@ -0,0 +1,20 @@ +
+
+ + + + 1/2 +
+
+ + + + 1 +
+
+ + + + 2 +
+
diff --git a/examples/smart-components/display-settings/extra/index.html b/examples/smart-components/display-settings/extra/index.html new file mode 100644 index 00000000..80c59912 --- /dev/null +++ b/examples/smart-components/display-settings/extra/index.html @@ -0,0 +1,5 @@ +
+ +

Подробнее о сроках — в разделе «Сроки и порядок».

+

Заявку рассматривают десять рабочих дней.

+
diff --git a/examples/smart-components/display-settings/overview/index.html b/examples/smart-components/display-settings/overview/index.html new file mode 100644 index 00000000..d12b5ff3 --- /dev/null +++ b/examples/smart-components/display-settings/overview/index.html @@ -0,0 +1,12 @@ +
+
+ Городская библиотека + +
+
+

Часы работы

+

Читальный зал открыт по будням с 10 до 20 часов, в субботу — с 11 до 17. Книги выдают по читательскому билету.

+

Билет оформляют за пять минут по паспорту.

+

+
+
diff --git a/examples/smart-components/display-settings/overview/index.js b/examples/smart-components/display-settings/overview/index.js new file mode 100644 index 00000000..7e77ce35 --- /dev/null +++ b/examples/smart-components/display-settings/overview/index.js @@ -0,0 +1,12 @@ +// The panel writes the choice on ; the core styles of the site show it +// on every page. The page only listens to say what changed. In this example +// frame the browser keeps nothing: the choice lasts until the page reloads. +const names = {scheme: 'цветовая схема', textScale: 'размер текста', textSpacing: 'интервалы', images: 'картинки', motion: 'движение', font: 'шрифт', links: 'ссылки'}; +const said = document.querySelector('#display-settings-said'); + +document.addEventListener('sf-display-settings-change', (event) => { + const {setting, settings} = event.detail; + said.textContent = setting === 'reset' + ? 'Возвращена обычная версия.' + : `Изменено: ${names[setting] ?? setting}. Текст ${settings.textScale} %.`; +}); diff --git a/examples/smart-components/display-settings/panel/index.html b/examples/smart-components/display-settings/panel/index.html new file mode 100644 index 00000000..2a781b63 --- /dev/null +++ b/examples/smart-components/display-settings/panel/index.html @@ -0,0 +1,8 @@ +
+ +
+

Приём документов

+

Документы принимают по будням с 9 до 18 часов. Заявление можно подать лично или через личный кабинет.

+

Справку выдают в течение трёх рабочих дней.

+
+
diff --git a/examples/smart-components/form/answer/index.html b/examples/smart-components/form/answer/index.html new file mode 100644 index 00000000..f8da57a5 --- /dev/null +++ b/examples/smart-components/form/answer/index.html @@ -0,0 +1,12 @@ +
+

Сообщение от бота поддержки

+

Оцените, пожалуйста, ответ оператора.

+ + + +
diff --git a/examples/smart-components/form/answer/index.js b/examples/smart-components/form/answer/index.js new file mode 100644 index 00000000..6e763ba6 --- /dev/null +++ b/examples/smart-components/form/answer/index.js @@ -0,0 +1,26 @@ +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +const start = async () => { + const SF = await sfReady(); + await SF.whenDefined(['form']); + const form = document.querySelector('#form-survey'); + // The form is pending; the host sets the outcome when the answer is delivered. + form.addEventListener('sf-form-answer', (event) => { + setTimeout(() => { + form.setAttribute('state', event.detail.accepted ? 'accepted' : 'declined'); + }, 800); + }); +}; + +start(); + +// Only for this example: the documentation frame may not send forms, and the +// browser then does not even report the submit. The press of a submit button +// hands the form its submit, as the browser does on a site. A site does not +// need this part. +document.addEventListener('click', (event) => { + const button = event.target.closest?.('sf-form [type="submit"]'); + if (!button) return; + event.preventDefault(); + button.form?.dispatchEvent(new Event('submit', {cancelable: true, bubbles: true})); +}, true); diff --git a/examples/smart-components/form/conditions/index.html b/examples/smart-components/form/conditions/index.html new file mode 100644 index 00000000..2ab6404b --- /dev/null +++ b/examples/smart-components/form/conditions/index.html @@ -0,0 +1,11 @@ + + + diff --git a/examples/smart-components/form/conditions/index.js b/examples/smart-components/form/conditions/index.js new file mode 100644 index 00000000..39f90d12 --- /dev/null +++ b/examples/smart-components/form/conditions/index.js @@ -0,0 +1,23 @@ +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +const start = async () => { + const SF = await sfReady(); + await SF.whenDefined(['form']); + // A field its conditions hide is not sent. + document.querySelector('#form-delivery').addEventListener('sf-form-submit', (event) => { + console.log('Отправить:', event.detail.value); + }); +}; + +start(); + +// Only for this example: the documentation frame may not send forms, and the +// browser then does not even report the submit. The press of a submit button +// hands the form its submit, as the browser does on a site. A site does not +// need this part. +document.addEventListener('click', (event) => { + const button = event.target.closest?.('sf-form [type="submit"]'); + if (!button) return; + event.preventDefault(); + button.form?.dispatchEvent(new Event('submit', {cancelable: true, bubbles: true})); +}, true); diff --git a/examples/smart-components/form/instant/index.html b/examples/smart-components/form/instant/index.html new file mode 100644 index 00000000..8c4c9063 --- /dev/null +++ b/examples/smart-components/form/instant/index.html @@ -0,0 +1,9 @@ + + + diff --git a/examples/smart-components/form/instant/index.js b/examples/smart-components/form/instant/index.js new file mode 100644 index 00000000..aca8d5b3 --- /dev/null +++ b/examples/smart-components/form/instant/index.js @@ -0,0 +1,12 @@ +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +const start = async () => { + const SF = await sfReady(); + await SF.whenDefined(['form']); + // apply="instant": every change acts at once, one event per field. + document.querySelector('#form-block').addEventListener('sf-form-change', (event) => { + console.log(`Поле ${event.detail.key}:`, event.detail.value); + }); +}; + +start(); diff --git a/examples/smart-components/form/labels/index.html b/examples/smart-components/form/labels/index.html new file mode 100644 index 00000000..248ed830 --- /dev/null +++ b/examples/smart-components/form/labels/index.html @@ -0,0 +1,24 @@ +
+
+ top + + + +
+
+ start + + + +
+
diff --git a/examples/smart-components/form/overview/index.html b/examples/smart-components/form/overview/index.html new file mode 100644 index 00000000..f35ec02d --- /dev/null +++ b/examples/smart-components/form/overview/index.html @@ -0,0 +1,16 @@ +
+ + + +

+
diff --git a/examples/smart-components/form/overview/index.js b/examples/smart-components/form/overview/index.js new file mode 100644 index 00000000..914a6e62 --- /dev/null +++ b/examples/smart-components/form/overview/index.js @@ -0,0 +1,29 @@ +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +const start = async () => { + const SF = await sfReady(); + await SF.whenDefined(['form']); + const form = document.querySelector('#form-button'); + const saved = document.querySelector('#form-button-saved'); + + // «Сохранить» found every field right: value is what the form would send. + form.addEventListener('sf-form-submit', (event) => { + saved.textContent = `Сохранено: ${JSON.stringify(event.detail.value)}`; + }); + form.addEventListener('sf-form-invalid', (event) => { + saved.textContent = `Исправьте поля: ${event.detail.fields.join(', ')}.`; + }); +}; + +start(); + +// Only for this example: the documentation frame may not send forms, and the +// browser then does not even report the submit. The press of a submit button +// hands the form its submit, as the browser does on a site. A site does not +// need this part. +document.addEventListener('click', (event) => { + const button = event.target.closest?.('sf-form [type="submit"]'); + if (!button) return; + event.preventDefault(); + button.form?.dispatchEvent(new Event('submit', {cancelable: true, bubbles: true})); +}, true); diff --git a/examples/smart-components/form/view/index.html b/examples/smart-components/form/view/index.html new file mode 100644 index 00000000..99c233a1 --- /dev/null +++ b/examples/smart-components/form/view/index.html @@ -0,0 +1,9 @@ + + + diff --git a/examples/smart-components/form/view/index.js b/examples/smart-components/form/view/index.js new file mode 100644 index 00000000..ab823544 --- /dev/null +++ b/examples/smart-components/form/view/index.js @@ -0,0 +1,24 @@ +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +const start = async () => { + const SF = await sfReady(); + await SF.whenDefined(['form']); + const form = document.querySelector('#form-contact'); + // «Изменить» opens the fields; a submit that is not cancelled returns to view. + form.addEventListener('sf-form-submit', (event) => { + console.log('Сохранить на сервере:', event.detail.value); + }); +}; + +start(); + +// Only for this example: the documentation frame may not send forms, and the +// browser then does not even report the submit. The press of a submit button +// hands the form its submit, as the browser does on a site. A site does not +// need this part. +document.addEventListener('click', (event) => { + const button = event.target.closest?.('sf-form [type="submit"]'); + if (!button) return; + event.preventDefault(); + button.form?.dispatchEvent(new Event('submit', {cancelable: true, bubbles: true})); +}, true); diff --git a/examples/smart-components/tag-group/layout/index.html b/examples/smart-components/tag-group/layout/index.html new file mode 100644 index 00000000..fec47a9e --- /dev/null +++ b/examples/smart-components/tag-group/layout/index.html @@ -0,0 +1,36 @@ +
+
+
+
+ + + + + + + + + + + +
+ row +
+
+
+ + + + + + + + + + + +
+ wrap +
+
+
diff --git a/examples/smart-components/tag-group/overview/index.html b/examples/smart-components/tag-group/overview/index.html new file mode 100644 index 00000000..1ceaac81 --- /dev/null +++ b/examples/smart-components/tag-group/overview/index.html @@ -0,0 +1,10 @@ +
+ + + + + + + +

Выбрано городов: 5.

+
diff --git a/examples/smart-components/tag-group/overview/index.js b/examples/smart-components/tag-group/overview/index.js new file mode 100644 index 00000000..a53d1cae --- /dev/null +++ b/examples/smart-components/tag-group/overview/index.js @@ -0,0 +1,18 @@ +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +const start = async () => { + const SF = await sfReady(); + await SF.whenDefined(['tag-group', 'tag']); + const group = document.querySelector('#tag-group-cities'); + const left = document.querySelector('#tag-group-cities-left'); + + // The cross and Delete only ask: the page removes the tag itself. + group.addEventListener('sf-tag-close', (event) => { + event.target.remove(); + // Only the group's own tags: the copies in «+N» belong to its popup. + const count = group.querySelectorAll(':scope > sf-tag').length; + left.textContent = count ? `Выбрано городов: ${count}.` : 'Ни одного города не выбрано.'; + }); +}; + +start(); diff --git a/examples/smart-components/tag-group/selection/index.html b/examples/smart-components/tag-group/selection/index.html new file mode 100644 index 00000000..b6484c07 --- /dev/null +++ b/examples/smart-components/tag-group/selection/index.html @@ -0,0 +1,20 @@ +
+
+ selection="one" + + + + + +
+
+ selection="many" + + + + + + +
+

+
diff --git a/examples/smart-components/tag-group/selection/index.js b/examples/smart-components/tag-group/selection/index.js new file mode 100644 index 00000000..38659ed2 --- /dev/null +++ b/examples/smart-components/tag-group/selection/index.js @@ -0,0 +1,21 @@ +const sfReady = () => (window.SF?.ready ? Promise.resolve(window.SF.ready) : new Promise((resolve) => window.addEventListener('sf-loader-init', () => resolve(window.SF), {once: true}))); + +const start = async () => { + const SF = await sfReady(); + await SF.whenDefined(['tag-group', 'tag']); + const chosen = document.querySelector('#tag-group-chosen'); + const show = document.querySelector('#tag-group-show'); + const status = document.querySelector('#tag-group-status'); + const say = () => { + const many = status.selectedIds ?? []; + chosen.textContent = `Показать: ${show.selected || 'ничего'}. Статус: ${many.length ? many.join(', ') : 'любой'}.`; + }; + + // The group reports the whole choice: ids, the tag pressed and whether it is chosen now. + for (const group of [show, status]) { + group.addEventListener('sf-tag-group-select', say); + } + say(); +}; + +start(); diff --git a/redirects.json b/redirects.json index 9138b89e..cdce3f2e 100644 --- a/redirects.json +++ b/redirects.json @@ -3894,10 +3894,6 @@ "from": "ru/components/overlays-media/swiper", "to": "ru/components/tools/swiper" }, - { - "from": "ru/components/feedback/progress-ring", - "to": "ru/smart/feedback/progress-ring" - }, { "from": "ru/pro/chat/thread-list", "to": "ru/pro/chat/chat-threads" From c0c320c5813e2cf8cb093824ada148b909ed561e Mon Sep 17 00:00:00 2001 From: Rim Zabarov Date: Sun, 22 Nov 2026 03:54:55 +0300 Subject: [PATCH 6/6] Display settings: the overview example is a library site page (header, news, alerts, cards, table, form, code) with the panel above the header; a line says colour schemes show wrong in the docs frame (Docara copies the docs colours over the scheme) Co-Authored-By: Claude Opus 5.5 --- .../ru/smart/navigation/display-settings.md | 14 +- .../display-settings/overview/index.html | 122 ++++++++++++++++-- 2 files changed, 124 insertions(+), 12 deletions(-) diff --git a/content/ru/smart/navigation/display-settings.md b/content/ru/smart/navigation/display-settings.md index 36242bae..98c6044f 100644 --- a/content/ru/smart/navigation/display-settings.md +++ b/content/ru/smart/navigation/display-settings.md @@ -19,13 +19,19 @@ description: "Кнопка и панель, в которой человек в ## Пример -Откройте «Версию для слабовидящих» и нажмите «А+» или «Жёлтый на чёрном»: -меняется весь пример. `Escape` закрывает панель. Код — на вкладке -JavaScript. +Страница библиотеки: шапка, новости, сообщения, карточки, таблица, форма +и код. Откройте «Версию для слабовидящих» над шапкой и нажмите «А+», +«Шире» или «Скрыть» картинки — меняется вся страница. `Escape` закрывает +панель. Код — на вкладке JavaScript. -:::example {id="smart-components/display-settings/overview" label="Кнопка в шапке сайта" preview=sandbox log="sf-display-settings-change" log_console=true log_open=false} +:::example {id="smart-components/display-settings/overview" label="Страница сайта с панелью над шапкой" preview=sandbox log="sf-display-settings-change" log_console=true log_open=false} ::: +Цветовые схемы в рамке этого примера показываются неверно: рамка +документации переносит в пример цвета самой документации, и они +перекрывают схему. На странице сайта схема перекрашивает всё: текст, края, +кнопки, отметки и ссылки. + ## Разметка ```html diff --git a/examples/smart-components/display-settings/overview/index.html b/examples/smart-components/display-settings/overview/index.html index d12b5ff3..022fb426 100644 --- a/examples/smart-components/display-settings/overview/index.html +++ b/examples/smart-components/display-settings/overview/index.html @@ -1,12 +1,118 @@ -
-
- Городская библиотека +
+
-
-

Часы работы

-

Читальный зал открыт по будням с 10 до 20 часов, в субботу — с 11 до 17. Книги выдают по читательскому билету.

-

Билет оформляют за пять минут по паспорту.

-

+ + + Библиотека на Садовой + + + + + +
+
+

Весенняя программа библиотеки

+

Лекции, клубы и мастерские для взрослых и детей. Вход свободный, на мастерские — по записи.

+
+ + + + + +
+
+ Читальный зал: стеллажи с книгами и лампа
+ + + +
+
+

Клуб «Читаем вслух» набирает вторую группу

+

12 марта · 3 минуты чтения

+

Встречи проходят по субботам в 12:00 в малом зале; книги на сезон выбирают вместе. Расписание — в разделе «Мероприятия».

+
    +
  • до 12 человек в группе;
  • +
  • книги выдаём на весь сезон;
  • +
  • для детей от 10 лет — с родителями.
  • +
+
«Библиотека — место, где тишину охраняют вместе». — из книги отзывов
+
+ + + + + + +
+
+
+ + + +
+ + + + +
+
+
+ +
+ + +
+ +
+ + + + + + + + + +
ОтделБудниСуббота
Абонемент10:00–20:0011:00–17:00
Читальный зал10:00–21:0011:00–18:00
Архивпо записизакрыт
+
+ +
+ + + + + + + +
+ + +
+
+ + +
+
+ +
<script src="https://library.example/afisha.js"></script>
+ +