diff --git a/config/catalog-groups.json b/config/catalog-groups.json index b4c8f62e0..7098ada56 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 f3f2e5c34..c8e592fe7 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 7465d7ea9..76ec855da 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 4167615bf..a6db29830 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 8e54a58d5..b60d86674 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/actions/clipboard.md b/content/ru/components/actions/clipboard.md index 58a3e63c3..a871c288a 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/feedback/index.md b/content/ru/components/feedback/index.md index a62e2902a..2560036c6 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 000000000..c4723039b --- /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 000000000..92b4e5917 --- /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/forms/country-code.md b/content/ru/components/forms/country-code.md index f9c7bb624..720b9c74a 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 72344591b..f678e3fa7 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 d9153826e..7e7faf9ad 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 fd8bfe1a3..d0a5c75ce 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 f5d434211..6f35ff38d 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 000000000..8375a81fa --- /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 000000000..930b90c31 --- /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 000000000..635675185 --- /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 000000000..e3d9c3081 --- /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 000000000..b80a5a920 --- /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); +}); diff --git a/examples/guide/accessibility/display-settings/index.js b/examples/guide/accessibility/display-settings/index.js index c59ec1518..1d3f8fb60 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 000000000..e97b061a5 --- /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 000000000..1a5033337 --- /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 000000000..78f99077c --- /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 000000000..c3aab27aa --- /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 000000000..d2f619c91 --- /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 000000000..2a69e49a5 --- /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 000000000..613e3d2bb --- /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/accordion/from-code/index.html b/examples/smart-components/accordion/from-code/index.html new file mode 100644 index 000000000..53d30ccf1 --- /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 000000000..51c164d73 --- /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/alert/actions/index.html b/examples/smart-components/alert/actions/index.html new file mode 100644 index 000000000..5195bbdc0 --- /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 000000000..6ad1aa986 --- /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 000000000..ce9c0692e --- /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 000000000..915e386ec --- /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/bulk-actions/all/index.html b/examples/smart-components/bulk-actions/all/index.html new file mode 100644 index 000000000..0dc6440cc --- /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 000000000..f5665d2b7 --- /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 000000000..be1a62efd --- /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 000000000..915110319 --- /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 000000000..1d31d431e --- /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 000000000..ea278ceff --- /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 000000000..f07157d70 --- /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 000000000..5c581e679 --- /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/chat-composer/send/index.html b/examples/smart-components/chat-composer/send/index.html new file mode 100644 index 000000000..2efafcdc5 --- /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 000000000..4685456de --- /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); +} 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 000000000..f7d0c3fa0 --- /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 000000000..7c57c1d9d --- /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 000000000..9ca4b5570 --- /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 000000000..2794f2da6 --- /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 000000000..8a8a3a070 --- /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/display-settings/extra/index.html b/examples/smart-components/display-settings/extra/index.html new file mode 100644 index 000000000..80c59912e --- /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 000000000..022fb426c --- /dev/null +++ b/examples/smart-components/display-settings/overview/index.html @@ -0,0 +1,118 @@ +
+
+ +
+ + + Библиотека на Садовой + + + + + +
+
+

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

+

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

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

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

+

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>
+ +
+

Библиотека на Садовой · ул. Садовая, 12 · +7 (495) 000-00-00

+

+
+
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 000000000..7e77ce35d --- /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 000000000..2a781b63e --- /dev/null +++ b/examples/smart-components/display-settings/panel/index.html @@ -0,0 +1,8 @@ +
+ +
+

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

+

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

+

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

+
+
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 000000000..4fd2db2f8 --- /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 000000000..e77eb09ca --- /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/file-upload/browser-import/index.html b/examples/smart-components/file-upload/browser-import/index.html new file mode 100644 index 000000000..bd378b4db --- /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 000000000..e84ed3d92 --- /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/form/answer/index.html b/examples/smart-components/form/answer/index.html new file mode 100644 index 000000000..f8da57a52 --- /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 000000000..6e763ba66 --- /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 000000000..2ab6404b1 --- /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 000000000..39f90d120 --- /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 000000000..8c4c90630 --- /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 000000000..aca8d5b3c --- /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 000000000..248ed830c --- /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 000000000..f35ec02d9 --- /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 000000000..914a6e625 --- /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 000000000..99c233a1c --- /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 000000000..ab8235440 --- /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/page-header/favourite/index.html b/examples/smart-components/page-header/favourite/index.html new file mode 100644 index 000000000..cff05b174 --- /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 000000000..40f7e963d --- /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/popover/focus-field/index.html b/examples/smart-components/popover/focus-field/index.html new file mode 100644 index 000000000..c283ec409 --- /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 000000000..e9bad0ce4 --- /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 000000000..6ea82de20 --- /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 000000000..4d2f2096b --- /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 000000000..40fa226c4 --- /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 000000000..79ba82736 --- /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 000000000..ef955218c --- /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 000000000..b36a3bdde --- /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 000000000..3be2d1f41 --- /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 000000000..d7c2aaf00 --- /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/site-header/sheet/index.css b/examples/smart-components/site-header/sheet/index.css new file mode 100644 index 000000000..5785eda22 --- /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 000000000..e91829139 --- /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 000000000..4de489e29 --- /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/skeleton/replace/index.html b/examples/smart-components/skeleton/replace/index.html new file mode 100644 index 000000000..0096c97b4 --- /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 000000000..59bea1a35 --- /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/slider/from-code/index.html b/examples/smart-components/slider/from-code/index.html new file mode 100644 index 000000000..44e127d81 --- /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 000000000..d69b45034 --- /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/switch/apply/index.html b/examples/smart-components/switch/apply/index.html new file mode 100644 index 000000000..4aab40942 --- /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 000000000..d9140c299 --- /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/tag-group/layout/index.html b/examples/smart-components/tag-group/layout/index.html new file mode 100644 index 000000000..fec47a9e3 --- /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 000000000..1ceaac810 --- /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 000000000..a53d1cae4 --- /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 000000000..b6484c076 --- /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 000000000..38659ed2c --- /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/examples/smart-components/tags/filter/index.html b/examples/smart-components/tags/filter/index.html new file mode 100644 index 000000000..69f1d5e61 --- /dev/null +++ b/examples/smart-components/tags/filter/index.html @@ -0,0 +1,15 @@ +
+
+ + + +
+ +

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

+
diff --git a/examples/smart-components/tags/filter/index.js b/examples/smart-components/tags/filter/index.js new file mode 100644 index 000000000..7ada26b61 --- /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 37efede82..05e0183e4 100644 --- a/examples/smart-components/tags/kinds/index.html +++ b/examples/smart-components/tags/kinds/index.html @@ -1,6 +1,6 @@
- + kind="checkbox"
diff --git a/examples/smart-components/toast/undo/index.html b/examples/smart-components/toast/undo/index.html new file mode 100644 index 000000000..d87c33f42 --- /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 000000000..8cd8a311a --- /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('Сообщение закрыто')); +}); diff --git a/redirects.json b/redirects.json index 9138b89e4..cdce3f2e6 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"