TypographyТекст

Текст для статей и интерфейсов: заголовки, абзацы, строчный текст и ссылки с оформлением, копированием, правкой на месте и обрезкой длинного текста.

Импорт
import { Typography, TypographyTitle, TypographyParagraph, TypographyText, TypographyLink } from 'svelte-ant-design';
Ссылки
src/lib/Typography Сообщить о проблеме README компонента

Когда использовать

  • Используйте для читаемого текста единого вида: статьи, заметки, блог.
  • copyable и editable подходят для коротких значений, которые копируют или меняют: идентификаторов, имён.
  • ellipsis — там, где мало места; оставляйте способ прочитать весь текст: подсказку или expandable.

Примеры

A design system

Many projects need the same design rules and the same parts. A design system keeps them in one place, so the work does not start again in every application.

How to start

Run npm install svelte-ant-design and press Enter.
Decide first, then build. The API table lists every property.

Статья

Typography — это <article> с базовым текстом. Заголовки, абзацы, строчный текст и ссылки внутри него пишутся четырьмя компонентами.

Release notes

Read the table of properties before you start.

  • Run npm install and press Enter
  • Decide first, then build
Consistency is a feature that every page gets for free.
npm install svelte-ant-design

Готовый HTML

Для готового HTML из Markdown или CMS, где компоненты не расставить. Внутри Typography оформляются обычные заголовки, абзацы, ссылки, списки, цитата, pre, code, kbd, mark и strong; компоненты библиотеки внутри него сохраняют свой вид. Вставляйте только HTML, которому доверяете или который очищен.

level 2 to 5 (level 1 is the default and is the h1 of a page)

h2. Ant Design

h3. Ant Design

h4. Ant Design

h5. Ant Design

Заголовки

level от 1 до 5 даёт h1–h5; размер зависит от уровня. Пример начинается со 2: на странице один h1, это уровень по умолчанию.

type Ant Design (default) Ant Design (secondary) Ant Design (success) Ant Design (warning) Ant Design (danger) Ant Design (disabled)
decorations Ant Design (mark) Ant Design (code) Ant Design (keyboard) Ant Design (underline) Ant Design (delete) Ant Design (strong) Ant Design (italic)
combined Not for production

Оформление текста

type, disabled и флаги strong, italic, underline, delete, mark, code и keyboard. Флаги сочетаются.

copyable
This is a copyable text.
Nothing copied yet
text: the copy is not the shown text
Copy something else.
text: a function that returns a promise
Ask the server for the text.
Not requested yet
icon, tooltips
Own icon and tips.
tooltips: false
No tip, the button keeps its name.
a Text with only the button

Копирование

copyable добавляет кнопку копирования. Текст, значок, подсказки и колбэк задаются объектом; текст может быть функцией или promise: пока он ожидается, на кнопке крутится спиннер.

bind:content, with the events
This is an editable text.
No events yet
icon, tooltip
Custom icon and tip.
triggerType: ['icon', 'text']
Click the text or the icon.
maxLength, autoSize, no enter mark
No more than 20 chars
bind:editing
reading
Open me from outside.

Правка

editable открывает поле на месте текста. Enter, Tab и клик в сторону сохраняют, Escape отменяет. bind:content записывает новый текст обратно.

one row, with a tooltip
Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers. Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers.
rows=3
Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers. Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers.
onellipsis
Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers. Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers.
The text is shown whole
a Text in a narrow box
Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers. Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers.

Многоточие

ellipsis обрезает текст до одной строки или до rows строк. С tooltip полный текст виден при наведении, только пока текст обрезан.

expandable
Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers. Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers.
expandable: 'collapsible', onexpand
Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers. Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers.
Nothing pressed yet
symbol as a snippet
Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers. Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers.

Разворачивание

expandable ставит кнопку в конце последней строки; 'collapsible' добавляет обратную. symbol — её содержимое: текст или snippet.

bind:expanded
cut
Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers. Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers.
rows, with a slider
Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers. Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers.

Управляемый

bind:expanded хранит состояние; число строк можно менять в любой момент, и текст обрезается заново.

suffix, rows and expandable
To be, or not to be, that is the question: whether it is nobler in the mind to suffer the slings and arrows of outrageous fortune, or to take arms against a sea of troubles, and by opposing end them. To die, to sleep; no more. To be, or not to be, that is the question: whether it is nobler in the mind to suffer the slings and arrows of outrageous fortune, or to take arms against a sea of troubles, and by opposing end them. To die, to sleep; no more. To be, or not to be, that is the question: whether it is nobler in the mind to suffer the slings and arrows of outrageous fortune, or to take arms against a sea of troubles, and by opposing end them. To die, to sleep; no more.
suffix with a text that fits
To be, or not to be, that is the question: whether it is nobler in the mind to suffer the slings and arrows of outrageous fortune, or to take arms against a sea of troubles, and by opposing end them. To die, to sleep; no more.

Суффикс

suffix идёт после обрезанного текста и остаётся, даже когда текст помещается.

actions.placement: 'end'
Buttons after the text.
actions.placement: 'start'
Buttons before the text.
expand, edit and copy together
Ant Design, a design language for background applications, is refined by Ant UED Team. It aims to make the interface specifications of internal projects uniform, to lower the cost of design differences and of implementation, and to free the time of designers and front-end developers.

Панель кнопок

actions.placement ставит кнопки после текста или перед ним. Порядок: развернуть, изменить, копировать.

shimmer
Thinking...
duration: 3 A slow sweep, then one second of rest
duration: [1, 0] A sweep without a pause

Мерцание

shimmer пускает по тексту полосу света, пока что-то готовится. duration — время движения или пара «движение и пауза».

classNames: a class for each part (the CSS is in this example)
Styled by part.
styles: inline styles, custom properties included
Purple buttons, further from the text.
class and style
A note with a bar.

Стили частей

classNames и styles адресуют корень, панель кнопок, каждую кнопку и поле правки.

API

СвойствоОписаниеТипПо умолчанию
typeЦвет текста.'secondary' | 'success' | 'warning' | 'danger'—
disabledЦвет и курсор отключённого. Кнопки работают; ссылка теряет href.booleanfalse
codeВид code.booleanfalse
markВыделенный маркером текст.booleanfalse
underlineПодчёркнутый.booleanfalse
deleteЗачёркнутый.booleanfalse
strongЖирный. Не для заголовка.booleanfalse
italicКурсив.booleanfalse
keyboardВид kbd. Для Text и Link.booleanfalse
contentТекст как значение для правки, копирования и обрезки; важнее дочернего содержимого. bind:content записывает изменённый текст обратно.string—
copyableКнопка копирования (таблица ниже).boolean | TypographyCopyablefalse
editableКнопка правки и поле (таблица ниже).boolean | TypographyEditablefalse
editingОткрыто ли поле. bind:editing для двусторонней связи; обычное значение — начальное.booleanfalse
ellipsisОбрезает текст (таблица ниже). Text и Link — одна строка: без rows, expandable и onexpand.boolean | TypographyEllipsisfalse
expandedРазвёрнут ли обрезанный текст. bind:expanded для двусторонней связи. Title и Paragraph.booleanfalse
actionsГде стоит панель кнопок.{ placement?: 'start' | 'end' }{ placement: 'end' }
shimmerАнимированный текст. duration — секунды или [движение, пауза].boolean | { duration?: number | [number, number] }false
childrenТекст и строчное содержимое.Snippet—
onclickКлик по компоненту, включая кнопки.(event: MouseEvent) => void—
classNamesДополнительные классы частей.Partial<Record<'root' | 'actions' | 'action' | 'textarea', string>>—
stylesИнлайновые стили частей, после собственных.Partial<Record<'root' | 'actions' | 'action' | 'textarea', Record<string, string | number>>>—
classКласс корня.string—
styleИнлайновый стиль корня.string—
levelТолько TypographyTitle: 1–5 даёт h1–h5.1 | 2 | 3 | 4 | 51
native attributesОстальное идёт на элемент: id, data-*, aria-*; у ссылки также href, target, rel.HTMLAttributes—

Объект copyable

СвойствоОписаниеТипПо умолчанию
textЧто копировать, иначе content, иначе видимый текст. Пока промис ожидается, на кнопке крутится спиннер, а повторные нажатия ничего не делают. Долгий промис тоже копируется; по обычному HTTP и в Firefox старше 127 промис дольше нескольких секунд не скопируется.string | (() => string | Promise<string>)—
oncopyВызывается один раз за успешное копирование, не вызывается после неудачи.(event: MouseEvent | KeyboardEvent) => void—
iconЗаменяет значки копирования и галочки; получает copied.Snippet<[boolean]>—
tooltipsПодсказки до и после копирования; false прячет их. Строка становится и именем кнопки.false | [string | Snippet, string | Snippet]['Copy', 'Copied']
tabIndextabindex кнопки.number—

Объект editable

СвойствоОписаниеТипПо умолчанию
textНачальный текст поля.string—
maxLengthmaxlength поля.number—
autoSizeПоле растёт вместе с текстом.boolean | { minRows?: number; maxRows?: number }true
iconЗаменяет карандаш.Snippet—
tooltipПодсказка кнопки правки; false прячет. Строка становится и её именем.string | Snippet | false'Edit'
enterIconЗначок в поле; null убирает его.Snippet | null—
triggerTypeЧем начинается правка. Без 'icon' карандаша нет; текст-триггер не получает фокус.Array<'icon' | 'text'>['icon']
tabIndextabindex кнопки правки.number—
onstartПользователь открыл поле.() => void—
onchangeПравка завершена с другим текстом.(text: string) => void—
onendПравка завершена Enter или уходом из поля.() => void—
oncancelОтменено клавишей Escape.() => void—

Объект ellipsis

СвойствоОписаниеТипПо умолчанию
rowsСколько строк показывать.number1
expandableКнопка разворачивания; 'collapsible' и сворачивает.boolean | 'collapsible'false
suffixТекст после обрезанного, виден всегда.string—
symbolСодержимое кнопки. Строка — текст разворачивания; snippet получает expanded.string | Snippet<[boolean]>'Expand', 'Collapse'
tooltipПолный текст в подсказке, пока текст обрезан.boolean | string | Snippet | TooltipProps—
onexpandПользователь нажал «развернуть» или «свернуть».(event: MouseEvent, info: { expanded: boolean }) => void—
onellipsisТекст стал или перестал быть обрезанным.(ellipsis: boolean) => void—
Отличия от Ant Design: текст для правки и обрезки задаётся через content с bind:, а editing и expanded — связываемые пропсы, а не поля объектов. copyable.icon — один snippet с параметром copied, classNames и styles принимают объекты, а format: 'text/html' и стили таблиц отложены на v1.1. Подписи на английском до ConfigProvider (v1.1).

Части компонента

ЧастьОписание
rootСам элемент компонента с оформлением внутри.
actionsПанель с кнопками.
actionКаждая кнопка: копирование, правка, разворот, сворачивание.
textarea<textarea> поля правки.

Дизайн-токены

ТокенОписаниеПо умолчанию
--ads-typography-font-sizeРазмер текста абзаца и статьи.var(--ads-font-size)
--ads-typography-line-heightВысота строки абзаца и статьи.22px
--ads-typography-colorЦвет текста.var(--ads-color-text)
--ads-typography-paragraph-margin-bottomОтступ под абзацем, списком и цитатой.1em
--ads-typography-title-weightНачертание заголовков.600
--ads-typography-title-margin-topОтступ над заголовком (нет у первого).1.2em
--ads-typography-title-margin-bottomОтступ под заголовком.0.5em
--ads-typography-h1-font-sizeРазмер заголовка уровня 1.38px
--ads-typography-h1-line-heightВысота строки заголовка уровня 1.46px
--ads-typography-h2-font-sizeРазмер заголовка уровня 2.30px
--ads-typography-h2-line-heightВысота строки заголовка уровня 2.38px
--ads-typography-h3-font-sizeРазмер заголовка уровня 3.24px
--ads-typography-h3-line-heightВысота строки заголовка уровня 3.32px
--ads-typography-h4-font-sizeРазмер заголовка уровня 4.20px
--ads-typography-h4-line-heightВысота строки заголовка уровня 4.28px
--ads-typography-h5-font-sizeРазмер заголовка уровня 5.16px
--ads-typography-h5-line-heightВысота строки заголовка уровня 5.24px
--ads-typography-secondary-colorЦвет типа secondary. tokens-accessible.css затемняет его.var(--ads-color-text-tertiary)
--ads-typography-success-colorЦвет типа success. tokens-accessible.css затемняет его.#52c41a
--ads-typography-warning-colorЦвет типа warning. tokens-accessible.css затемняет его.#faad14
--ads-typography-danger-colorЦвет типа danger. tokens-accessible.css затемняет его.var(--ads-color-danger)
--ads-typography-disabled-colorЦвет отключённого текста.var(--ads-color-text-disabled)
--ads-typography-link-colorЦвет ссылки; tokens-accessible.css затемняет его.var(--ads-color-link)
--ads-typography-link-hover-colorЦвет ссылки при наведении.var(--ads-color-link-hover)
--ads-typography-link-active-colorЦвет нажатой ссылки.var(--ads-color-link-active)
--ads-typography-link-decorationЧерта под ссылкой; в тёмной теме ссылки подчёркнуты, там их цвет слишком близок к цвету текста.none
--ads-typography-action-colorЦвет кнопок.var(--ads-color-link)
--ads-typography-action-hover-colorЦвет кнопки при наведении.var(--ads-color-link-hover)
--ads-typography-action-active-colorЦвет нажатой кнопки.var(--ads-color-link-active)
--ads-typography-actions-gapОтступ между текстом и кнопками.4px
--ads-typography-mark-bgЗаливка выделенного текста.#ffe58f
--ads-typography-mark-colorЦвет выделенного текста.#000000
--ads-typography-code-bgЗаливка code и pre.rgba(150, 150, 150, 0.1)
--ads-typography-code-borderГраница code, kbd и pre.rgba(100, 100, 100, 0.2)
--ads-typography-kbd-bgЗаливка kbd.rgba(150, 150, 150, 0.06)
--ads-typography-code-font-familyШрифт code, kbd и pre.SFMono-Regular, Consolas, 'Liberation Mono', Menlo, Courier, monospace
--ads-typography-blockquote-borderПолоса в начале цитаты.rgba(100, 100, 100, 0.2)
--ads-typography-edit-offset-inlineНа сколько поле правки выступает в начале строки.12px
--ads-typography-edit-offset-blockНа сколько поле правки выступает над и под строкой.5px
--ads-typography-enter-colorЦвет значка Enter в поле.var(--ads-color-text-tertiary)
--ads-typography-shimmer-motionВремя движения мерцания в секундах.1
--ads-typography-shimmer-waitПауза мерцания в секундах.1
--ads-typography-shimmer-highlightЦвет движущейся полосы мерцания.var(--ads-color-bg-container)
--ads-typography-transitionВремя смены цвета ссылок и кнопок.0.3s

Доступность

  • Копирование, правка и разворачивание — настоящие кнопки в порядке Tab с именами Copy, Edit и видимым текстом кнопки разворачивания; она же сообщает через aria-expanded, раскрыт ли текст. Успешное копирование объявляется вежливым статусом, неудачное — молча.
  • Текст, обрезанный скриптом, целиком остаётся на странице для вспомогательных технологий; видимые куски и многоточие от них скрыты.
  • У поля правки есть имя; Enter, Tab и клик в сторону сохраняют текст, Escape отбрасывает его, а Enter во время набора через IME ничего не делает.
  • Два ограничения: текст, с которого начинается правка без карандаша, и текст с подсказкой не получают фокус. Оставляйте 'icon' в triggerType и давайте клавиатурный путь к полному тексту через expandable.
  • type меняет только цвет: где он несёт смысл, добавьте слово или значок.
  • По умолчанию цвета — собственные цвета Ant Design, и часть не достигает 4.5:1; с tokens-accessible.css и в тёмной теме — достигает. При уменьшении движения мерцание останавливается, а в режимах принудительных цветов выделение рисуется системными цветами.
  • Проверено в Orca (Firefox): кнопки, статус копирования, поле правки, развёрнутое состояние, полный обрезанный текст, уровень заголовка и обычные ссылки. Orca говорит expanded, но молчит, когда кнопка снова сворачивает — как и у любой кнопки с aria-expanded. Не проверено: Copied у обещанного текста, который идёт несколько секунд (тестовый стенд не озвучивает такое позднее изменение), NVDA, JAWS, VoiceOver и телефоны.