Компонент Skeleton Loader для Angular | ng-hub-ui-skeleton

Skeleton-заглушки загрузки для Angular с переиспользуемыми пресетами, инлайн-шаблонами DSL, адаптивными значениями и CSS-переменными для состояний shimmer.

Последнее обновление 16 сент. 2026 г.

Обзор

Почему команды ищут эту библиотеку

Выбирайте эту библиотеку skeleton для Angular, когда состояния загрузки должны оставаться системными, переиспользуемыми и готовыми к продукту, а не вырождаться в разовую shimmer-разметку.

Установка

npm install ng-hub-ui-skeleton

Перейти к

Идеально для

  • карточки и ленты
  • таблицы данных
  • формы
  • дашборды

О библиотеке skeleton

ng-hub-ui-skeleton даёт командам Angular структурированный способ проектировать заглушки загрузки: встроенные пресеты для распространённых UI-паттернов, компактную DSL для пользовательских форм и адаптивные значения, которые адаптируют один и тот же skeleton к разным компоновкам.

Руководства по возможностям

Каталог presets

Встроенный каталог намеренно сделан широким, потому что состояния загрузки обычно представляют собой повторяющийся бизнес-UI, а не изолированные заглушки. Он включает card, list-item, table-row, detail-view, form-section, dashboard-widget, stat-card, chart-panel, profile-summary, master-detail, kanban-card, feed-item, search-result, table-toolbar, filter-bar и empty-state-skeleton. Идея в том, чтобы команды начинали с ориентированного на продакшен словаря загрузки, а не пересобирали одни и те же shimmer-блоки в каждой функции. На практике это значит, что экраны с большим количеством таблиц могут начинаться с `table-toolbar` плюс повторяющийся `table-row`, экраны dashboard могут сочетать `stat-card`, `chart-panel` и `dashboard-widget`, а контентные потоки могут обращаться к `card`, `feed-item` или `search-result`, не создавая новую разметку раскладки с нуля.

Примеры:
Галерея каталога presets

Показывает встроенные presets рядом, чтобы команда выбрала ближайшую отправную точку до написания собственных шаблонов.

card

Content card with media, title and body lines.

list-item

Compact row with avatar and text.

table-row

Tabular data row placeholder.

detail-view

Detail screen with media and metadata.

form-section

Form group with responsive fields.

dashboard-widget

Panel with chart or metric content.

stat-card

Quick KPI summary card.

chart-panel

Large chart region with legend rows.

profile-summary

Profile hero with avatar and stats.

master-detail

List and detail layout together.

kanban-card

Small board card loading state.

feed-item

Activity or timeline row.

search-result

Search result with metadata lines.

table-toolbar

Toolbar with title, filters and actions.

filter-bar

Row of filter controls.

empty-state-skeleton

Illustrative empty or onboarding state.

card

Dense card variant for tighter layouts.

Код
Import:
Template:
Component:
Встроенный preset card

Отрисовывает встроенный skeleton card со стандартным shimmer.

Код
Import:
Template:
Component:
Композиция dashboard

Собирает несколько presets, чтобы во время загрузки показать аналитический dashboard.

Код
Import:
Template:
Component:

Написание на компактном DSL

Inline-шаблоны используют компактный синтаксис в стиле Emmet, потому что библиотека оптимизирована для быстрой итерации внутри кодовых баз Angular. Композиция соседних элементов использует `+`, вложенность — `>`, модификаторы находятся внутри скобок, повторы используют `*N`, а параметры интерполируются через `{{param}}`. Это даёт командам компактную поверхность для написания, которая по-прежнему хорошо читается в pull request и позволяет вносить небольшие изменения без переписывания целого дерева объектов. Важна не изощрённость синтаксиса, а то, что замысел раскладки остаётся близко к использованию компонента и его легко сравнивать, рефакторить и проверять.

Примеры:
Паттерны компактного DSL

Разбирает базовые элементы DSL с наглядным результатом для структуры, params и адаптивных токенов.

Structure

`+` creates siblings and `>` nests children.

Params & repeats

Use {{param}} placeholders and *N repeaters to scale rows quickly.

Responsive values

Switch spacing or columns inline with compact breakpoint tokens.

Код
Import:
Template:
Component:
Inline-шаблон в стиле Emmet

Определяет собственную форму skeleton прямо в шаблоне, с интерполяцией params.

Код
Import:
Template:
Component:

Варианты и адаптивные раскладки

Состояния загрузки не должны игнорировать плотность раскладки или breakpoints, потому что пользователи замечают, когда skeleton не имеет отношения к реальному UI. Presets могут предоставлять варианты, такие как `compact`, а отдельные значения модификаторов могут переключаться между breakpoints с помощью компактных адаптивных токенов. Это позволяет сохранять одно семантическое определение skeleton, адаптируя ширину, количество столбцов, отступы и размеры в контекстах mobile, tablet и desktop. Практический результат — меньше дублирующихся шаблонов и гораздо лучшее соответствие между фазой заглушки и реально отрисованным интерфейсом.

Примеры:
Компактный вариант

Сравнивает стандартный preset card с его компактным вариантом для более плотных интерфейсов.

Код
Import:
Template:
Component:
Адаптивная раскладка таблицы

Использует адаптивные значения внутри встроенных presets, чтобы перейти от компактной раскладки к широкой.

Код
Import:
Template:
Component:

Программная регистрация и темизация

Встроенные пресеты — это отправная точка, а не потолок. Команды могут регистрировать собственные пресеты проекта через внедрение зависимостей Angular и затем использовать их по имени точно так же, как встроенный каталог, что критично, когда у продукта есть собственный повторяющийся язык skeleton-ов. Визуальная настройка остаётся в CSS-переменных, поэтому интенсивность shimmer, базовый цвет, цвет подсветки, отступы и радиусы можно согласовать с design system, не допуская утечки жёстко заданных значений в компоненты функциональности. Это разделение важно: структура относится к пресетам и DSL, а визуальная политика — к темизации.

Примеры:
Программный пользовательский preset

Регистрирует локальный preset и использует его по имени так же, как из встроенного каталога.

Код
Import:
Template:
Component:
Композиция dashboard

Собирает несколько presets, чтобы во время загрузки показать аналитический dashboard.

Код
Import:
Template:
Component:

Ключевые возможности

Последние изменения

Version 22.3.2 - 9/16/26, 12:00 AM

changed: Repository, issue and README links follow the move to the hub-env organization. Issues for every Hub UI package are now gathered in hub-env/hub-ui, and the repository and bugs fields of the manifest point at the new addresses. No code, types or styles change.

Version 22.3.1 - 9/7/26, 12:00 AM

fixed: Both READMEs stop presenting six internal DSL helpers as part of the API. They listed parseHubSkeletonDsl, interpolateHubSkeletonParams, resolveTemplateDsl, resolveResponsiveToken, resolveBreakpointFromWidth and resolveHubSkeletonNodes as exported, and public-api.ts has never re-exported the module that declares them, so a reader who followed the documentation and imported one got a build error. They stay internal: a layout is written as a template string and handed to the component or registered as a preset, so nothing outside the package has to call them.

Version 22.3.0 - 9/6/26, 12:00 AM

added: FUNCTIONALITIES.md now ships with the library, the same coverage table the rest of the family provides: which parts of the component, the DSL, the preset catalogue, the registry and the styling surface a live example actually demonstrates, and which are only prose. Nothing stated it before, so a reader had to open the documentation site and infer it.

changed: One preset registry is shared again instead of one per placeholder. The component listed HubSkeletonPresetRegistryService in its own providers, so every <hub-skeleton> on screen built a private instance and merged the sixteen bundled presets into a fresh Map, twenty times over on a screen with twenty placeholders, while the README described the service as the providedIn: 'root' singleton a consumer who injects it actually gets. The component now resolves the root instance, which changes where custom presets are read from: see BREAKING_CHANGES.md.

changed: Both READMEs teach the canonical ng-hub-ui-skeleton/styles entry for the theming mixin. They still reached for the deep path ng-hub-ui-skeleton/styles/mixins/skeleton-theme, which resolves but is not the entry 22.2.0 introduced and not what BREAKING_CHANGES.md, the mixin's own header and the generated mixin reference all show, so a reader comparing two sources had to guess which one was current.

fixed: The ariaLabel input is finally reachable by assistive technology. The container carried role="presentation" and aria-label at once, a conflict that costs the name whichever way a user agent resolves it, while every placeholder shape inside is aria-hidden, so nothing was left to carry the name either. A consumer setting the input, or relying on its non-empty default, got silence and had to announce the loading state from an outer element of their own. The container is now a polite role="status" region with aria-busy="true", matching ng-hub-ui-loading, and keeps the label as its accessible name.

fixed: The styles subpath the docs prescribe is now declared in the manifest exports. Since 22.2.0 the stylesheets have shipped at styles/, and both the README and BREAKING_CHANGES.md tell consumers to reach them with @use ng-hub-ui-skeleton/styles. The generated exports map declared only . and ./package.json, so anything that enforces the map, from Node subpath resolution to the Sass pkg: importer and bundlers that honour exports, refused the very import the documentation teaches. An Angular CLI build happened to survive because it resolves bare Sass specifiers through loadPaths instead, which is why the block went unnoticed. The theming entry and the skeleton-theme mixin are now declared explicitly, as the sibling libraries already do.

deprecated: HubSkeletonModule is deprecated and will be removed in 23.0.0. It imports and exports HubSkeletonComponent and provides nothing of its own, so importing the component directly is the whole migration; custom presets go through provideHubSkeletonPresets(), which never travelled through the module either. The class described itself as kept for compatibility with module-based apps but carried no @deprecated tag, so neither an editor nor the build warned anyone. See BREAKING_CHANGES.md.

Version 22.2.4 - 9/1/26, 12:00 AM

changed: The homepage in the manifest points at this library's own documentation page rather than at the site root. It is the link a registry shows beside the package and the one a reader clicks from it, and landing on a front page they then have to search is a worse answer than landing on the reference for the package they were already looking at. Metadata only — no code, no types, no styles change, and nothing a consumer imports is affected.

Version 22.2.3 - 8/17/26, 12:00 AM

fixed: The package shipped without its licence notice. package.json declared MIT, but no LICENSE file travelled in the tarball — and MIT itself requires the copyright notice to be included in distributions. The notice ships now.

Version 22.2.2 - 8/8/26, 12:00 AM

fixed: Documentation links now point at the canonical localized URLs. The README linked to https://hubui.dev/<path> with no locale prefix and no trailing slash, and both forms are 301-redirected, so every reader arriving from npm or GitHub landed on a redirect instead of the canonical page.

Version 22.2.1 - 7/28/26, 12:00 AM

added: Comprehensive test suite for the skeleton DSL parser and preset registry: full grammar coverage (node types, nesting, siblings, props, variants, multipliers, responsive tokens), every parser error path with its exact message, preset expansion/override/variant resolution, and component render round-trips. No runtime changes.

Version 22.2.0 - 7/7/26, 12:00 AM

changed: BREAKING (packaging) — SCSS ships at ng-hub-ui-skeleton/styles. The theme mixin now builds to dist/skeleton/styles/... (was dist/skeleton/src/lib/styles/...), so @use 'ng-hub-ui-skeleton/styles' resolves. Update any @use that reached into src/lib/styles.

Version 22.1.0 - 6/24/26, 12:00 AM

added: New hub-skeleton-theme() Sass mixin (styles/mixins/skeleton-theme) — theme the loading placeholders in one call: base / highlight surfaces (the shimmer gradient), corner radius, node gap and shimmer speed. Every parameter is optional and defaults to null, so only the ones you pass are emitted as --hub-skeleton-* overrides. Token-based, no Bootstrap dependency. (A skeleton is a neutral placeholder — there is no semantic colour variant; per-node sizes still come from the template DSL / presets.) The five theming tokens (--hub-skeleton-bg / -highlight / -radius / -gap / -animation-duration) are now documented in the design-token reference.

Version 22.0.0 - 6/17/26, 12:00 AM

changed: Aligned with Angular 22.

changed: README documentation standardized.

Version 0.1.1 - 6/14/26, 12:00 AM

changed: Replaced the deprecated ngStyle directive with the native [style] binding (Angular soft-deprecated ngStyle/ngClass in November 2024 in favour of native bindings, for better performance and smaller bundles).

Version 0.1.0 - 4/14/26, 12:00 AM

added: Added the initial dynamic skeleton component for Angular.

added: Added a compact Emmet-like DSL with preset composition and repeat support.

added: Added responsive property values, variants, and programmatic preset registration.

added: Added the first preset catalogue for cards, lists, tables, forms, dashboards, and empty states.

Связанные библиотеки

Часто задаваемые вопросы

Как показать скелетные заглушки загрузки в Angular?

Установите ng-hub-ui-skeleton и отображайте HubSkeletonComponent, пока данные в пути. Вы описываете форму заглушки — линии, блоки, круги — и она анимирует мерцание, пока настоящее содержимое её не заменит, благодаря чему вёрстка не прыгает при получении данных.

Можно ли переиспользовать одну и ту же форму скелета в разных компонентах?

Да. HubSkeletonPreset один раз регистрирует именованную форму и переиспользует её везде, где встречается эта раскладка, поэтому заглушка карточки описана в одном месте, а не скопирована в каждый список и каждую страницу, где рисуется карточка.

Как изменить цвет или скорость мерцания скелета?

Каждый цвет, радиус и анимация ng-hub-ui-skeleton — это пользовательское свойство CSS, поэтому вы перекрашиваете его из собственной таблицы стилей во время выполнения, и он следует тёмной теме без пересборки. HubSkeletonAppearance переключает встроенное мерцание и обычную статичную заглушку.

Что использовать во время загрузки — скелет или спиннер?

Берите скелет, когда знаете форму будущего содержимого: он резервирует место и избавляет от скачка вёрстки, который оставляет спиннер. Спиннер лучше подходит для коротких неопределённых ожиданий, когда итоговая раскладка неизвестна.