# @smartsoft001-mobilems/angular

Shared Angular building blocks — components, services, directives, guards, state and models.

Related packages:
[models](../models/README.md) ·
[objects](../../objects/README.md) ·
[articles](../../articles/README.md) ·
[public-collections](../../public-collections/README.md)

## Install / import

```typescript
import { MasonryGridComponent, FiltersBaseComponent, FileUrlService } from '@smartsoft001-mobilems/angular';
```

Root wiring lives in `app.config.ts` via `SharedModule.forRoot(config)`; feature libraries use
`SharedModule` (or `SharedModule.forFeature(config)`) in their module `imports`.

## Contents

- [Components](#components)
- [Base components (extend these)](#base-components-extend-these)
- [Services](#services)
- [State](#state)
- [Directives](#directives)
- [Pipes](#pipes)
- [Guards](#guards)
- [Interceptors](#interceptors)
- [Models, interfaces and tokens](#models-interfaces-and-tokens)
- [Tailwind (`@smartsoft001-mobilems/angular/tailwind`)](#tailwind-smartsoft001-mobilemsangulartailwind)
- [CLI (`bin`)](#cli-bin)
- [Module & config](#module--config)
- [App setup (`provideMobilemsCore`, `provideMobilemsApp`)](#app-setup-providemobilemscore-providemobilemsapp)
- [Static page, search page, resolvers](#static-page-search-page-resolvers)
- [Bootstrap entry points](#bootstrap-entry-points)
- [SSR server (`ssr`)](#ssr-server-ssr)
- [Translations](#translations)

## Components

Ready-to-use components. Selectors are prefixed `smart-mobilems-`.

| Component               | Selector                       | Purpose                                                                    |
| ----------------------- | ------------------------------ | -------------------------------------------------------------------------- |
| `MasonryGridComponent`  | `smart-mobilems-masonry-grid`  | Masonry layout with image-load awaiting, responsive gutter and re-layout    |
| `AppComponent`          | `smart-mobilems-app`           | App shell: skip links, `<header>`/`<footer>` slots (hidden via `GlobalService`), `<main id="main-content" tabindex="-1">`, default slot for extras; `options` is optional (see **App setup**). Host directives `InPageAnchorsDirective` + `ExternalLinksDirective`, inert unless `contentLinks` is set. With `contentLinks` off, SSR still carries a transient `jsaction` attribute on `<smart-mobilems-app>` (event replay of the host listeners); it has no behavioural effect |
| `SkipLinksComponent`    | `smart-mobilems-skip-links`    | Keyboard skip links from `MOBILEMS_APP_OPTIONS.skipLinks` (home vs subpage); the nav/footer links are added while `GlobalService` shows the header/footer. Visually hidden until focused through inline styles (no app CSS needed); focus colours from `--mobilems-skip-link-bg` / `--mobilems-skip-link-color` (default white / `--primary-color`) |
| `NotFoundContentComponent` | `smart-mobilems-not-found-content` | 404 panel (inputs `fullHeight`, `messageKey`, `backRoute`, `backLabelKey`) for the `**` route and API-404 pages |
| `HeaderComponent`       | `smart-mobilems-header`        | Header state: WCAG toggle, search panel, user, local-collection counter (deprecated, see `HeaderBaseComponent`) |
| `FooterComponent`       | `smart-mobilems-footer`        | Footer state driven by config + CMS static pages (deprecated, see `FooterBaseComponent`) |
| `MenuComponent`         | `smart-mobilems-menu`          | Config-driven main menu                                                     |
| `PageComponent`         | —                              | CMS page renderer (extends `PageBaseComponent`)                             |
| `ScrollTopComponent`    | —                              | Back-to-top button (`windowScrolled`, `scrollToTop`); no-op on the server   |
| `WidgetComponent`       | `smart-widget`                 | Renders an `ArticleWidget` by mapping `ArticleWidgetType` → component       |
| `WidgetTextComponent`   | `smart-widget-text`            | Text widget                                                                 |
| `PageSectionsComponent` | `smart-mobilems-page-sections` | Dynamic CMS page sections: `type/theme` → component, `portal_slot` slot    |
| `SectionLinkComponent`  | `smart-mobilems-section-link`  | Wraps content in a router link / external link / `<span>` for a CMS target  |
| `GridContainerSectionComponent` | `smart-mobilems-page-section-grid-container` | Default `grid_container` section: title + children on a 12-column grid |
| `ModalContainerComponent` | `smart-mobilems-modal-container` | Host for `ModalService.open()`                                          |

Page bases shipped for reuse: `HomeBaseComponent`, `PageStaticComponent`, `SearchBaseComponent`, `NotFoundComponent` (+ `NotFoundContentComponent`).

### `PageSectionsComponent`

Renders the `sections` of a CMS page in `position` order. Like `WidgetComponent`, it maps each
section to a component — `{ ...baseMap, ...PAGE_SECTION_COMPONENTS_TOKEN }`, where the framework
`baseMap` is **empty**: visual variants are per museum. Keys are `` `${type}/${theme}` `` (one
variant) or bare `type` (every theme of that type); `type/theme` wins
(`pageSectionComponent(section, map)` does the lookup). Section components extend
`PageSectionBaseComponent` (`section` input).

```typescript
@Component({
  selector: 'app-home',
  imports: [PageSectionsComponent],
  providers: [
    {
      provide: PAGE_SECTION_COMPONENTS_TOKEN,
      useValue: {
        'slider/carousel': CarouselSectionComponent,
        tile_collection: TilesSectionComponent,
      },
    },
  ],
  template: `
    <smart-mobilems-page-sections
      [page]="'slug/strona-glowna'"
      (pageLoaded)="setSeo($event)"
    >
      <app-object-of-the-day />
    </smart-mobilems-page-sections>
  `,
})
export class HomePage {
  setSeo(page: Page | null): void {
    // page?.seo?.title, page?.seo?.description …
  }
}

@Component({
  selector: 'app-carousel-section',
  template: `<h2 [innerHTML]="section().content?.title"></h2>`,
})
export class CarouselSectionComponent extends PageSectionBaseComponent {}
```

| Input / output | Type                                 | Notes                                                                    |
| -------------- | ------------------------------------ | ------------------------------------------------------------------------ |
| `page`         | `PageRef \| null`                    | Fetched via `ConfigsFacade.getPage`; re-fetched on change, stale responses ignored |
| `sections`     | `PageSectionRaw[] \| null \| undefined` | When not `undefined` it is rendered (after normalization) and **no fetch** happens (SSR/resolver) |
| `slotFallback` | `boolean` (default `true`)           | Without a `portal_slot` the projected content goes after the sections; `false` → only at a placeholder |
| `expandDictionaries` | `boolean` (default `true`)     | Expand whole-dictionary blocks into one block per entry (see **Dictionary targets**); `false` → passed on as they are (not clickable) |
| `pageLoaded`   | output `Page \| null`                | After every fetch; `null` on API error (no sections rendered, nothing thrown) |

`loadedPage` is a readonly signal with the last fetched page. The fetch is registered with
`PendingTasks`, so SSR waits for the sections.

**Normalization.** Before dispatch the sections go through `normalizePageSections(raw)` (pure,
exported): `null`/missing `blocks`, `cta`, `children` (of a `grid_container`), `widget.search`,
`widget.counter` become `[]`, `null` items are dropped, and sections, blocks, CTAs, children and
widgets are sorted **stably** by `position` (ties keep the API order; a missing/`null` position goes
last and is replaced by the item's index in the sorted list, so `position` is always a number). `content`, `appearance` and `widget` may still be `null` — variants must cope. A variant
always receives a normalized `PageSection`; the API shape is `PageSectionRaw`.

Each section is wrapped in `<section data-testid="page-section">` with an `id` (`section-<position>`
when the position is unique among the rendered sections, `section-<position>-<index>` for ties —
`index` = place in the normalized list — or the anchor of the previous section's `#anchor` CTA), `data-section-type`/`data-section-theme`,
`data-section-bg="color|image|none"`, the hook class `PAGE_SECTION_HOOK_CLASS`
(`smart-mobilems-page-section`) and the appearance as custom properties
(`pageSectionAppearance(appearance, multimediaUrl)` → `PageSectionAppearanceStyle`):

| Variable                                     | From                                     | Value                                              |
| -------------------------------------------- | ---------------------------------------- | -------------------------------------------------- |
| `--page-section-bg`                          | `background.color`                       | the colour — only `#rgb` / `#rrggbb` / `#rrggbbaa` |
| `--page-section-bg-image`                    | `background.file` (not `type: 'video' \| 'audio' \| 'other'`) | `url("<multimediaUrl + filePath>")` (`pageSectionFileUrl`) |
| `--page-section-mt` / `-mr` / `-mb` / `-ml`  | `margin.top/right/bottom/left`           | `calc(var(--page-section-space-unit, 0.5rem) * N)` |
| `--page-section-pt` / `-pr` / `-pb` / `-pl`  | `padding.top/right/bottom/left`          | same                                               |

A side that is `null` sets **no** variable, so the museum fallback applies; `N` is clamped to
0–`PAGE_SECTION_SPACE_MAX` (12, the CMS scale).

**Colour whitelist.** `background.color` is trimmed and used only when it is `#rgb`, `#rrggbb` or
`#rrggbbaa` (hex digits, any case). Anything else — `red; background:url(…)`, `url(…)`, `var(…)`,
`rgb(…)`, colour names — is skipped (no `--page-section-bg`; `data-section-bg="none"` when there is no
image) with a `console.warn` in dev mode only. The image URL is percent-encoded (`\ ' " ( )` and
whitespace) by `pageSectionFileUrl`, so a file name like `Muzeum Ogińskich's.jpg` cannot break out of
`url("…")`; an absolute `filePath` (`http(s)://…`, `//…` — e.g. an image borrowed from an object) is
used without the `multimediaUrl` prefix.

The framework paints nothing — the museum applies the
variables in its own CSS (Tailwind does not scan `node_modules`), plus its dark / high-contrast
override:

```css
.smart-mobilems-page-section {
  --page-section-space-unit: 0.5rem;
  margin: var(--page-section-mt, 0) var(--page-section-mr, 0) var(--page-section-mb, 0)
    var(--page-section-ml, 0);
  padding: var(--page-section-pt, 2rem) var(--page-section-pr, 1rem) var(--page-section-pb, 2rem)
    var(--page-section-pl, 1rem);
  background-color: var(--page-section-bg, transparent);
}
.smart-mobilems-page-section[data-section-bg='image'] {
  background-image: var(--page-section-bg-image);
  background-size: cover;
  background-position: center;
}
```

Sections without a component are skipped with a `console.warn` in dev mode only.

**`grid_container`.** The only type with a framework default: `GridContainerSectionComponent`
(`smart-mobilems-page-section-grid-container`, key `PAGE_SECTION_GRID_CONTAINER_TYPE`; register
`grid_container` or `grid_container/<theme>` to replace it). Inside the container `<section>` it
renders the optional `content.title` as `<h2 class="smart-mobilems-page-section__title">` and the
`children` through the same `type/theme` dispatch, each in a
`<section class="smart-mobilems-page-section smart-mobilems-page-grid__item" data-testid="page-section-child">`
with its own appearance variables. From 768px `.smart-mobilems-page-grid` is a 12-column CSS grid
(`repeat(12, minmax(0, 1fr))`) and each child sits at `gridArea(child.grid)` (a child without `grid`
spans the full row); below that the children stack in `position` order. The layout CSS is added once
per document as `<style id="smart-mobilems-page-grid-style">` in `<head>` (SSR too, `CSP_NONCE`
honoured) — the museum may override it. Gap:
`--page-section-grid-gap` (default `0`). A nested `grid_container` (the CMS does not allow one) or a
child without a component is skipped with a dev-mode warning.

**Slot (`portal_slot`).** The first section of type `PAGE_SECTION_PLACEHOLDER_TYPE` (`'portal_slot'`
— the CMS v3 name: theme `default`, `content: null`, no `blocks`/`cta`; matched by `type` whatever the
theme) renders the content projected into the component at its position, inside a fixed
`<div class="smart-mobilems-page-slot" data-testid="page-slot">` (`PAGE_SECTION_SLOT_CLASS`; no
`<section>` — the host content brings its own semantics). When the `portal_slot` sets a background or
spacing, the wrapper also gets `PAGE_SECTION_HOOK_CLASS` (`smart-mobilems-page-section`), its
appearance variables and `data-section-bg` like a section. Otherwise (no appearance, while loading,
without a placeholder) it is `display: contents` without the hook class: it paints nothing and the
projected elements stay flex/grid items of the host (e.g. `smart-flex-1` filling a
`smart-flex smart-flex-col` host keeps working). This is how a CMS page wraps an existing module
(e.g. the object list): sections above and below it, the module in place of `portal_slot`.
Further placeholders are ignored.

Without a `portal_slot` — also while the page is loading, after a failed fetch (404, network) and for
a page with empty/missing `sections` — the projected content falls back to **after** all sections
(alone on error) when `slotFallback` is `true` (default). With `slotFallback = false` it renders only
at a `portal_slot` (not while loading; Angular still instantiates it, so keep it light).

The slot wrapper is one fixed container between two loops — sections before the `portal_slot`, then the
slot, then sections after it (without a placeholder every section goes "before"). Loading the
sections only inserts siblings around it, so the projected module renders immediately (no waiting
for the CMS, no SSR flicker) and is never moved or re-created — it keeps its state (only its class
and style change when the appearance arrives).

**Target links.** `smart-mobilems-section-link` (`target`, `label`, `linkClass`, `testId`) renders a
`routerLink`, an external `<a>` (web links with `target="_blank" rel="noopener noreferrer"`,
`mailto:`/`tel:` in place) or a plain `<span>`, using `resolveSectionTarget(target, label?, routes)`.
Routes come from `PAGE_SECTION_ROUTES_TOKEN` (default `DEFAULT_PAGE_SECTION_ROUTES`:
`objectsPath: '/obiekty'`, `pagePath: '/strona'`, `dictionaryFilters: { creator: 'creators',
department: 'department', cycle: 'cycles' }`, `dictionarySources`, `dictionaryLimit: 50`, no
`cardTypeFilter`, no `creatorsPath`):

- `museum_object` → `[objectsPath, id]`
- `page` → `[pagePath, id]` (`/strona/:id`; `pagePath` is optional, default `/strona`)
- `dictionary` → `[objectsPath]` with `?filter=[{"name":<filter>,"data":[{"id","value"}]}]`, the
  filter being the target's `objectFilter` (CMS v3 sends it on every dictionary target — it wins) or,
  without one, what `dictionaryFilters` maps its `dictionaryType` to (defaults: `creator` → `creators`, `department` →
  `department`, `cycle` → `cycles` — the `FiltersContext` filters); otherwise not clickable; a
  whole dictionary (`dictionary: null`, not expanded) is not clickable. **`tag` has no default** —
  the object search has no tag filter (`keywords` is a different dictionary); map it once one exists.
  With `creatorsPath` set (e.g. `'/artysci'`), a `creator` entry goes to the creator page
  `[creatorsPath, id]` instead; unset (default) keeps the objects filter
- `dictionary_filter` (a whole dictionary, not expanded) → not clickable
- `card_type_code` → `[objectsPath]` with one `?filter=` entry per code (any matches) when
  `cardTypeFilter` is set. **TODO:** the framework object search has no card-type filter yet, so by
  default these targets are not clickable
- `link` → `http(s)://`, `//`, `mailto:`, `tel:` external (`newTab: true` for the web ones, checked
  on the control-character-stripped URL like the scheme); `#x` fragment; other schemes
  (`javascript:`, `data:`, …) and an empty URL not clickable; anything else router commands + query +
  fragment
- `module` → the path `routes.modules` maps its `module` id to (resolved like a `link`, query and
  hash kept), e.g. `modules: { 10: '/artysci' }`; ids are instance data, so there is no default —
  unmapped modules are not clickable
- unknown types, `null` → not clickable

```typescript
providers: [
  {
    provide: PAGE_SECTION_ROUTES_TOKEN,
    useValue: { ...DEFAULT_PAGE_SECTION_ROUTES, objectsPath: '/zbiory' },
  },
];
```

**Dictionary targets — two modes.** In the CMS a block with link type "dictionary record" either
picks **selected records** or a **whole dictionary**:

- **A — selected records** (unchanged): `target = { targetType: 'dictionary', dictionaryType,
  dictionary: <id> }` — one block per record, resolved as above.
- **B — whole dictionary** (`isWholeDictionaryTarget(target)`, type
  `PageSectionWholeDictionaryTarget`), two accepted shapes:
  - **canonical** (backend contract of 2026-10-02):
    `target = { targetType: 'dictionary_filter', targetLabel: null, dictionaryType: 'cycle' }` —
    no `dictionary` field; the block's `content` is usually `null`;
  - **legacy** (still supported): `target = { targetType: 'dictionary', dictionaryType,
    dictionary: null }` (a missing `dictionary` too).

  `smart-mobilems-page-sections` replaces such a block, **before dispatch** (top-level sections and
  `grid_container` children alike — variants only ever see ordinary mode-A blocks), with one block
  per dictionary entry: `target = { targetType: 'dictionary', dictionaryType, dictionary: <entry
  id>, targetLabel: <entry name> }`, `content.title` = entry name (also when the source `content` is
  `null`), every other field (background, lead, grid…) copied from the source block. Entries keep
  the **API order** (no client sorting — the editor's order of the CMS dictionary) and are inserted
  at the source block's place; the section's blocks get `position` renumbered `0…n-1`. Entries
  already selected in the same section (same `dictionaryType` + id — the selected block stays) or
  produced by an earlier whole-dictionary block are skipped. While loading, after a failed request,
  and for a type without a source, the block is left out — the rest of the section renders.

`dictionary_filter` fields (`PageSectionDictionaryFilterTarget`) — the backend announced a filter
configuration (sorting, limit…); every such field is optional, unknown ones are ignored:

| Field            | Type                        | Handling                                                                  |
| ---------------- | --------------------------- | ------------------------------------------------------------------------- |
| `targetType`     | `'dictionary_filter'`       | Required                                                                  |
| `dictionaryType` | `PageSectionDictionaryType` | Required, non-empty (`creator`, `department`, `tag`, `cycle`, …)          |
| `targetLabel`    | `string \| null`            | Optional; replaced by the entry name in the expanded blocks               |
| `limit`          | `number \| null`            | Optional; an integer `> 0` caps the blocks of this block (skipped duplicates do not count), otherwise ignored |
| `sort`           | `string \| null`            | Optional, **future** (e.g. newest/oldest) — ignored, the API order is kept |

Dictionaries are loaded by `PageSectionDictionaryExpander` (root service, needs `HttpClient`):
`GET {apiUrl}dictionary/<source>/search/page/1?maxPerPage=<limit>&_type=query` → `data.items[{ id,
name }]`. One request per `dictionaryType` for the whole app (on the server: per request), shared
by every section and renderer; a failed request resolves to `null` and is retried by the next
renderer. The renderer tracks it with `PendingTasks`, so SSR waits; a cached / HTTP-transfer-cached
response arrives synchronously, so hydration renders the same blocks.

| `dictionaryType` | `dictionarySources` (API dictionary) | `dictionaryFilters` (object search filter) |
| ---------------- | ------------------------------------ | ------------------------------------------ |
| `creator`        | `Creator`                            | `creators`                                 |
| `department`     | `Department`                         | `department`                               |
| `tag`            | `Tag`                                | — (no tag filter: expanded, not clickable) |
| `cycle`          | `Cycle`                              | `cycles` (`FiltersContext.cycles`)          |
| any other        | — (add it to both maps)              | —                                          |

`PageSectionRoutes.dictionarySources` (default `DEFAULT_PAGE_SECTION_DICTIONARY_SOURCES`, also used
when a museum's routes omit it) maps a type to an API dictionary name or, with a `/`, a path relative
to `apiUrl` (e.g. `article/authors`); `dictionaryLimit` caps the entries per block (default
`DEFAULT_PAGE_SECTION_DICTIONARY_LIMIT`, 50). A museum providing its own `dictionaryFilters` without
`cycle` gets non-clickable cycle pills — spread `DEFAULT_PAGE_SECTION_ROUTES` and override.

Outside the renderer (resolver, own component): `await expander.expand(sections)` (normalized
sections → expanded), `expander.entries(type)` / `entries$(type)` (`PageSectionDictionaryEntry[]`
or `null`), or the pure `wholeDictionaryTypes(sections)` + `expandDictionaryBlocks(sections,
entries)` (`PageSectionDictionaryEntries` — `type → entries | null`; `toEntriesMap(pairs)` builds it
from `[type, entries]` pairs). A whole-dictionary target
that was not expanded (e.g. `expandDictionaries = false`) resolves to `null` in
`resolveSectionTarget` — never a filter with an `undefined` id.

**Content, media, widgets — helpers for variants** (the framework gives data, the museum the look):

| Helper                                       | Returns                                                                                       |
| -------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `pageSectionHtml(html)`                      | the CMS HTML, or `null` when it renders nothing (`null`, blanks, `<p><br></p>`, `&nbsp;`)      |
| `smartMobilemsSectionHtml` pipe (`PageSectionHtmlPipe`) | `DomSanitizer`-sanitized HTML (or `null`) for `[innerHTML]` — scripts/handlers stripped, `javascript:` neutralized; same in SSR |
| `pageSectionLeadLines(html)`                 | `string[]` — each paragraph and soft line break (`<br>`) of a CMS HTML field as one line (inline markup kept, empty lines dropped), e.g. the strips of `banner/title_slide` |
| `pageSectionCtaLabel(cta)`                   | trimmed `targetLabel` or `null` — fallback texts per target type are the museum's translations |
| `pageSectionMedia(media, multimediaUrl?)`    | `PageSectionMediaInfo` `{ url, type: 'image' \| 'video' \| 'audio', alt, isDecorative }` or `null` without a file or for `type: 'other'` |
| `pageSectionMediaUrl(media, multimediaUrl?)` | just the URL, or `null`                                                                        |
| `pageSectionFileUrl(filePath, multimediaUrl?)` | absolute URLs (`http(s)://`, `//`) without the prefix, others joined with `SharedConfig.multimediaUrl` (like `FileUrlService` `noCache`); `\ ' " ( )` and whitespace percent-encoded |
| `gridArea(grid)`                             | `PageSectionGridArea` `{ 'grid-column': 'x+1 / span w', 'grid-row': 'y+1 / span h' }` clamped to `PAGE_SECTION_GRID_COLUMNS` (12), or `null` — for mosaics |
| `pageSectionCounterValue(counter, locale)`   | banner counter `value` via `Intl.NumberFormat(locale)` (empty/invalid locale → `PAGE_SECTION_FALLBACK_LOCALE` `'pl-PL'`, never the runtime default), or `null` |
| `smartMobilemsSectionCounter` pipe (`PageSectionCounterPipe`) | the same for the app `LOCALE_ID` — identical in SSR and the browser |

Media kind (`PageSectionMediaKind`): the API `type` (`image|video|audio`) first; `type: 'other'` →
`null` (never rendered as an image/video); only without `type` (missing/`null`) the extension decides:
`mp3|wav|m4a|ogg` → `audio`, `webm|mp4` → `video`, else `image`. No/blank `altText` → decorative
(`alt: ''`). The counter locale is explicit so SSR and hydration format the same text:
`{{ counter | smartMobilemsSectionCounter }}` (`LOCALE_ID`) or
`pageSectionCounterValue(counter, inject(TranslationService).currentLanguage())`. The banner search
box (`widget.search[].placeholder`) is rendered by the museum variant.

```typescript
@Component({
  selector: 'app-tiles-section',
  imports: [SectionLinkComponent, PageSectionHtmlPipe],
  template: `
    @if (section().content?.lead | smartMobilemsSectionHtml; as lead) {
      <div [innerHTML]="lead"></div>
    }
    @for (tile of tiles(); track $index) {
      <smart-mobilems-section-link [target]="tile.block.target" [label]="tile.block.content?.title ?? null">
        @if (tile.media; as media) {
          <img [src]="media.url" [alt]="media.alt" />
        }
      </smart-mobilems-section-link>
    }
  `,
})
export class TilesSectionComponent extends PageSectionBaseComponent {
  private readonly multimediaUrl = inject(SharedConfig).multimediaUrl;
  readonly tiles = computed(() =>
    this.section().blocks.map((block) => ({
      block,
      media: pageSectionMedia(block.media?.background, this.multimediaUrl),
    })),
  );
}
```

**Test fixture.** `TEST_SECTIONS` (`PageSectionRaw[]`) and `TEST_SECTIONS_PAGE` (`Page`): positions
0–21 are a verbatim copy of `GET page/slug/test-sekcje` (11 `tile_collection` themes, 4 `slider`, 5
`banner` incl. widgets, a `grid_container` with 3 children, `portal_slot`); positions 22–30 add the
Live Edit v3 themes of the MSL skin (`collage`, `roster`, `showcase`, `accordion`, `title_slide`,
`picture`, `heading`, `quote`, `video`) with `objectFilter` and a `module` target — together every
`PAGE_SECTION_KEYS` entry. Use them in museum tests to check that every registered variant copes
with the real data.

**Key coverage.** `PAGE_SECTION_THEMES` / `PAGE_SECTION_KEYS` (`@smartsoft001-mobilems/models`) list
every CMS `type/theme`; `missingPageSectionComponents(map)` returns the keys a museum map has no
component for (`portal_slot` and `grid_container` count as covered — the framework renders them):

```typescript
expect(missingPageSectionComponents(PAGE_SECTION_COMPONENTS)).toEqual([]);
```

### `MasonryGridComponent`

Owns the whole masonry lifecycle: it creates the `@thisissoon/angular-masonry` instance, waits for
the grid images to load, re-layouts when `list` changes, destroys the instance, and fades the grid in
once the layout settles. The host only supplies the items template and (once) the `Masonry` factory.

```html
<smart-mobilems-masonry-grid [list]="list()" [options]="{ gutter: 24 }" classes="smart-my-4">
  <ng-template #masonryContentTpl>
    <div class="masonry-grid-sizer"></div>
    @for (item of list(); track item.id) {
      <smart-objects-grid-item [item]="item" />
    }
  </ng-template>
</smart-mobilems-masonry-grid>
```

The grid item carries `masonry-item` on its own root element (host class). **Never wrap a card
in an extra `<div class="masonry-item">`** — masonry itemizes matching descendants too, so the
card would be laid out twice, collapse to a fraction of the column width and overlap its
neighbours. The component defensively strips the item class from nested matches (with a
console warning), but the wrapper markup is still wrong — don't write it.

| Input     | Type                 | Default          | Notes                                                       |
| --------- | -------------------- | ---------------- | ----------------------------------------------------------- |
| `list`    | `Array<unknown>`     | —                | Triggers destroy + re-init + re-layout when it changes       |
| `options` | `MasonryOptions`     | `{}`             | Merged over `itemSelector: .masonry-item`, `columnWidth: .masonry-grid-sizer`, `gutter: 24` |
| `classes` | `string \| string[]` | `'smart-my-4'`   | Applied to the grid container                                |

Content child: `#masonryContentTpl` (required). Public methods: `initMasonry()`, `destroyMasonry()`;
`masonryReady` signal gates the opacity transition. Gutter drops to `0` below 768 px.

SSR provider (once per lazy route or module that renders a grid):

```typescript
providers: [provideBrowserMasonry()];
```

Server: no timers, no layout. Missing or `null` provider: items are shown without masonry layout.

`stripNestedMasonryItems(container, itemSelector)` is the helper the component runs before layout: it
removes the item class from elements nested inside another item, so a card can never be laid out
twice. Exported for tests and custom grids; only simple `.class` selectors are handled.

### `FiltersBaseComponent` / `FiltersContext`

`FiltersContext<T>` translates filter UI state into a `CrudFilter` on the `CrudFacade<T>`: each
accessor reads the current filter and writes it back through a debounced (500 ms), change-checked
refresh, so bound controls never rebuild the `query` array themselves.

```typescript
@Component({ selector: 'smart-mobilems-objects-filters', templateUrl: './filters.component.html' })
export class FiltersComponent extends FiltersBaseComponent<MsObject> {}
```

```html
<ng-template #contentTpl>
  <input [(ngModel)]="context.searchText" />
  <smart-filter-dictionary-input [(value)]="context.keywords" dictionaryKey="keywords" />
</ng-template>
```

`FiltersBaseComponent<T>` (selector `smart-mobilems-filters`) injects `CrudFacade<T>`, builds
`context` in `ngAfterContentInit`, and exposes the `#contentTpl` content child.

`FiltersContext<T>` accessors — each reads/writes the facade filter and refreshes it:

- paging/sorting: `searchText`, `page`, `limit`, `sortBy`, `sortDesc`, `sort`, `query`, `totalCount`
- flags: `onlyImage`, `exposure`
- dictionary/query filters: `creators`, `authors`, `keywords`, `cycles`, `techniques`, `materials`,
  `category`, `department`, `location`, `locationType`, `createPlaces`, `formFeature`,
  `targetGroups`, `template`, `types`, `extraNumbersValue`, `inventoryNumber`
- date ranges: `createDatesFrom`, `createDatesTo`, `publicationDateFrom`, `publicationDateTo`
- bulk: `filters` — set several `{ val, key, type }` entries in one refresh

`FilterType = string | string[] | MenuItem | MenuItem[] | undefined`.

## Base components (extend these)

| Base class                             | Extend for                                                          |
| -------------------------------------- | ------------------------------------------------------------------- |
| `FiltersBaseComponent<T>`              | A module's filters component                                        |
| `SearchBaseComponent<SEARCH_PATH>`     | The search results page — see **Search page** below                 |
| `HomeBaseComponent`                    | CMS-sections home page: `page: PageRef` (`slug/<homePage.slug>`), `path`, `applySeo(page)` (CMS `seo` fields, else `MODEL.mainTitle` / `HOME.title`) |
| `NotFoundComponent`                    | 404 page: sets the museum title, exposes `url` (the unknown address) for the breadcrumb |
| `SliderBaseComponent` / `ISliderOptions` | Home and detail sliders/carousels (`slides: PageSlide[]` input, `#swiperContainer` ref, `slideImages`, `getImage`, `toggleAutoplay`/`autoplayEnabled`); Swiper only in the browser. Override `sliderOptions: ISliderOptions` to opt in to `keyboard`, `orientationChange`, `keepPausedOnRecreate` and `noImageUrl` (default `/gfx/no-image.png`) |
| `PageStaticComponent`                  | CMS static page — see **Static page** below                         |
| `GalleryFullscreenBaseComponent`       | **Deprecated** — use `GalleryFullscreenDialogBaseComponent`. Kept for apps on ^2.x (e.g. Rabka): fullscreen gallery dialogs (`closeChange` output) |
| `GalleryBaseComponent` / `IGalleryItem` | Object/article gallery: `items`, `alt`, `id` inputs, `selectedIndex` model, `selectedItem` (null out of range), fullscreen state (`isFullscreen`, `fullscreenIndex`, `zoomLevel`, `imageTransform`, `transform`, `isFullscreenLoading`), `openFullscreen`, `closeFullscreen`, `stopLoading` |
| `GalleryFullscreenDialogBaseComponent` | Fullscreen gallery in a native `<dialog>` (`#fullscreenDialog` ref, `[id]="osdContainerId()"` OpenSeadragon container, navigator on, no rotation): keyboard/mouse host listeners (do not redeclare them), `closeChange`, prev/next, zoom, `thumbnailsVisible` / `toggleThumbnails` (follows `isLandscape()` until toggled), `downloadImage` (`photoFileName`, numbered among photos only); `galleryOrientation` for class computeds, override `galleryDialogStyle` for the dialog inline styles (the override replaces the whole object - spread `GALLERY_DIALOG_STYLE` to keep the other defaults); the dialog, OpenSeadragon and the DOM work are guarded in `ngAfterViewInit` (browser only) |
| `GALLERY_DIALOG_STYLE`                 | Default inline styles of the fullscreen gallery dialog (readonly); spread it in a `galleryDialogStyle` override: `{ ...GALLERY_DIALOG_STYLE, background: 'red' }` |
| `ShareLinkBaseComponent`, `SHARE_LINK_COPIED_TIMEOUT` | A "share link" button (template in the app): implement `protected shareLinkUrl(): string` (read `defaultView` from the protected `shareLinkDocument`); bind `(click)="share()"` and `copied()`. Browser only: `defaultView.navigator.share({ title: document.title, url })` (a rejection such as `AbortError` is swallowed) or `clipboard.writeText(url)` + `copied` for the protected `shareLinkCopiedTimeout` getter (default `3000` ms, override the getter, read inside `share`) on a safe timer that dies with the component. Extended by `CollectionShareButtonBaseComponent` and `ObjectsShareResultsBaseComponent` |
| `ConfirmationModalBaseComponent`       | Global confirmation dialog on `ConfirmationModalService`: `modalService`, `onBackdropClick`, `handleCancel`, `handleConfirm`, Escape host listener (do not redeclare it); returns focus to `returnFocusTo` after render when still connected |
| `NewsletterModalBaseComponent` / `IMailerliteEmbed` | Newsletter modal with a Mailerlite embed: `email`, `closeOnBackdrop` inputs, `closed` output, `isModalOpen`, `handleOpen` / `handleClose`, Escape host listener (do not redeclare it); the subclass provides `protected readonly mailerlite: IMailerliteEmbed` (read lazily; `formId` getter); script injected in the browser only, email prefilled when the embed renders |
| `MAILERLITE_UNIVERSAL_SCRIPT_URL`      | Default Mailerlite script URL (`IMailerliteEmbed.scriptUrl` overrides it) |
| `MediaTabBaseComponent<MediaType>`     | Object media tabs (`item`, `formFeatureTypes` inputs). Deprecated, Rabka only: new tabs extend `ObjectMediaTabBaseComponent` from `@smartsoft001-mobilems/objects-shell-angular` |
| `WidgetBaseComponent<T>`               | A content widget (`item` input)                                     |
| `WidgetImageBaseComponent`             | Image widget logic on `WidgetBaseComponent` (keeps the `item` input the outlet sets): `alt` input, `items`, `isModalOpen`, `openFullscreen` / `closeFullscreen`, `getImageUrl(file, mode?: FileUrlMode)` (a big PNG stays a PNG; placeholder from the overridable `widgetImagePlaceholder`, default `WIDGET_IMAGE_PLACEHOLDER`), `getAltText(item, fallback?)` (`altText` / `description` HTML-stripped, then the fallback, then `alt()` - both as given; an explicit `''` fallback wins over `alt()`, unlike gallery-image), `stripHtml`, `normalizeUrl`, `trackByIndex`. Here `alt` is an **input**; on `WidgetGalleryImageBaseComponent` it is a derived computed, so a widget outlet should bind inputs per widget type (Podlasie's per-type `inputs` map) rather than pass `alt` to every widget. No template |
| `WidgetMediaBaseComponent` / `IWidgetMediaFile` / `WidgetMediaItem` | Article attachment widget logic (MOB-1805) on `WidgetBaseComponent` (keeps the `item` input the outlet sets): computeds `file` (`IWidgetMediaFile \| null`, first of `file` / `media` with a `filePath`), `url` (`noCache`), `name` (title, `fileName`, description, decoded path name), `isPdf`, `details` (`PDF · 1,2 MB`, size only when the API gives `size` / `fileSize`). No template |
| `WidgetGalleryImageBaseComponent` / `IWidgetGalleryImageEntry` | Article image gallery widget logic on `WidgetBaseComponent` (keeps the `item` input the outlet sets): `items` (`gallery.items`), `alt` (gallery name - a derived computed, **not** an input like on `WidgetImageBaseComponent`), `trackId` (`widgetDomId`, stable in SSR), views `showListSlider` / `showGridView` (2+ items, `gridMode`) / `showSingleMedia` (1 item), `selectedIndex` (two-way bindable) / `currentItem`, `toggleGridMode(force?)`, `nextImage` / `prevImage` / `goToImage(index)` (wire the museum's slider controls and swipe to them), `openFullscreen(index)` / `closeFullscreen`, `getImageUrl(file, mode?: FileUrlMode)` (a big PNG stays a PNG; overridable `widgetGalleryImagePlaceholder`, default `WIDGET_IMAGE_PLACEHOLDER`), `getAltText(entry, fallback?)` (`altText` / `description` / caption HTML-stripped, then the fallback as given; an empty caption or `''` fallback falls through to `''`), `stripHtml`, `normalizeUrl`, `trackByIndex`. Template contract of the grid: the element carries `#masonryGrid` and contains one `.masonry-grid-sizer` element (column width), one `.masonry-gutter-sizer` element (gutter; give both their widths in CSS) and the `.masonry-item` tiles. A sizer the template lacks falls back - gutter `0`, column width from the first tile - with one dev-mode `console.warn` (without the fallback masonry-layout would stack every tile). Masonry starts 150 ms after grid mode turns on (a restart within 150 ms replaces the pending start, so there is one instance), `masonryReady` turns true 250 ms after the images load and the grid re-lays out when a breakpoint (overridable `widgetGalleryImageBreakpoints`) is crossed. Provide `Masonry` with `provideBrowserMasonry()` (`null` on the server: no layout). No template |
| `WIDGET_GALLERY_IMAGE_BREAKPOINTS` / `WIDGET_GALLERY_IMAGE_MASONRY_OPTIONS` | Defaults of `WidgetGalleryImageBaseComponent`: grid column breakpoints `(min-width: 768px)`, `(min-width: 1024px)` (MOB-1852) and masonry options (CSS sizer column and gutter, no transition - MOB-1854; frozen - spread it, `{ ...WIDGET_GALLERY_IMAGE_MASONRY_OPTIONS, … }`); override `widgetGalleryImageBreakpoints` / `widgetGalleryImageMasonryOptions` |
| `WidgetAudioBaseComponent` / `WidgetAudioItem` / `WidgetAudioSource` | Audio widget logic on `WidgetBaseComponent` (keeps the `item` input the outlet sets) for the custom "cms Player" (Figma 2275:5525, MOB-1805): `source` (`file`, then `audio`, then a trimmed `url`), `src` (`noCache`), `title` / `description` (HTML stripped), `label` / `ariaLabel` (re-translated on a language change), `trackName` input + `withTrack(label)`, `playing` / `currentTime` / `duration` (reset with `src`), `progressPercent` (0-100, for the museum's own bar colours), `toggle(player)`, `seek(player, event)`, `onMetadata(player)`, `resetPlayback()`, `formatTime`, `getAudioUrl` / `getAudioTitle` / `getAudioAriaLabel`. Keyboard map of `onSeekKeydown(player, event)`: arrows ±5 s, Page Up/Down ±10 %, Home/End, clamped. Template contract: an `<audio #player>` bound to `loadedmetadata` / `durationchange` (`onMetadata`), `timeupdate`, `play` / `pause` / `ended` (`playing.set`) and `emptied` (`resetPlayback`). The first render re-reads metadata the element loaded before hydration; on destroy (browser only) the element is paused, loses `src` and is reloaded. Overridable `widgetAudioLabelKey`. No template |
| `WidgetGalleryObjectBaseComponent` | Article object gallery widget logic on `WidgetBaseComponent` (keeps the `item` input the outlet sets) for "CMS galeria" (Figma 2284:14833, MOB-1805): `items` (`gallery.items` sorted by `position`, mapped to `.object`, empty entries dropped), `columnsPerPage` input (3; the article column passes 2), `isMobile`, `perPage` (1 on a phone), `pages`, `page` (kept in range when `pages` changes), `trackId` (`widgetDomId`, stable in SSR), `trackStyle` (`--gallery-cols` plus the `translateX` shift by a full page - feed it to the museum's CSS via `[attr.style]`), `isOnPage(index)` (bind `[attr.inert]` / `aria-hidden` on cards outside the page), `goTo(page)` (wraps; wire slider controls and swipe to it). Every card stays in the DOM, so the server and the first client render match; `isMobile` turns on only after hydration (`afterNextRender`, `BreakpointObserver`, browser only, unsubscribed on destroy). Overridable `widgetGalleryObjectGap` and `widgetGalleryObjectSingleQuery`. No template |
| `WIDGET_GALLERY_OBJECT_GAP` / `WIDGET_GALLERY_OBJECT_SINGLE_QUERY` | Defaults of `WidgetGalleryObjectBaseComponent`: the gap between cards (24 px, counted into the track shift) and the one-card media query `(max-width: 767.98px)` - keep both in sync with the museum's CSS (MOB-1805) |
| `CalendarBaseComponent` / `ICalendarDay` / `IMonthChangeEvent` / `ICalendarLabelKeys` | Available-dates month picker (`availableDates`, `selectedDate`, `monthChange`, 42-day Monday-first `calendarDays`); override `calendarLabelKeys` for other aria keys |
| `CarouselBaseComponent<T>`             | Paged carousel (`items`, `columnsPerPage`, `rowsPerPage`, `autoplayInterval`, `loop` inputs, `mainNavigation`, `contentTemplate`; `pages`, `currentPage`, `next`, `previous`, `goToPage`, autoplay via `isAutoplayActive`, browser only) |
| `PaginationDotsBaseComponent`          | Dots: minimal pager (`limit`, `totalCount`, `page` inputs, `pageChange`, `items`, `changePage`) |
| `PaginationBaseComponent`              | Full pager with go-to field and `context` sync (`goToPageValue`, `goToPage`, `getTotalPages`, `navLabelKey`, `svgId`) |
| `PartnersCarouselBaseComponent`        | Home partners carousel: `items` input, `columnsPerPage` (2 Handset / 3 Tablet / 4 Web), `getImage`, `$Partner`, `navigateToMainRoute` (override `partnersRoute`, `/partnerzy`); on the server preloads the first `columnsPerPage()` logos as `Link` headers |
| `NewObjectsCarouselBaseComponent`      | Home "new objects" carousel: `items` input, `isMobile` / `isTablet` signals, `getImage` (cache extension); on the server preloads the first `(isMobile() ? 1 : 3) × 3` images. `$Object` stays in the museum (domain type) |
| `ArticlesCarouselBaseComponent`        | Home articles carousel: `items` input, `isMobile` / `isTablet` signals, `getImage`, `$Article`, `navigateToMainRoute` (override `articlesRoute`, `/artykuly`), `navigateToArticlesItem(commands)`; on the server preloads the first `isMobile() ? 1 : 4` images |
| `FilterInputBaseComponent`             | Single phrase filter field: `id`, `label`, `placeholder` (`OBJECTS.filters.typePhrase`), `filter`, `filterKey`, `disabled` inputs, `searchText` model following the `filterKey` query item, `filterChange` / `clearEvent` outputs, `onFilterChange`, `clear` (no-ops while disabled) |
| `FilterDateInputBaseComponent` / `IFilterDateRange` / `FILTER_DATE_INPUT_DEBOUNCE_MS` | Year range with 500 ms debounce and MOB-1866 echo handling: `searchFromText` / `searchToText` models, `yearMaxLength`, `boundaries`, `onYearInput(event, boundary)` (digits only, max 4), `clearYear(boundary)` (emits at once), `filterChange` emits `IFilterDateRange`; the museum keeps its own `layout` input; no emit after destroy |
| `FilterCustomDictionaryInputBaseComponent` | Static dictionary dropdown with keyboard navigation: `dictionary`, `dictionaryKey`, `filter` inputs, `selected`, `isOpen`, `activeIndex`, `toggleDropdown`, `isSelected`, `isActive`, `handleKeyDown` (ArrowDown/Up, Enter, Escape), `onClick`, `filterChange` / `clearAll`; options are the `#dropdownItem` refs, scrolled into view in the browser only |
| `FilterDictionaryInputBaseComponent` / `IFilterDictionaryRow` / `FilterDictionarySource` / `FilterDictionaryAppearance` | Dictionary combobox with an inline list (MOB-1802): `id`, `label`, `placeholder` (`OBJECTS.filters.choose`), `dictionaryKey`, `filterKey`, `filter`, `mode` (`'default'` / `'tree'`), `appearance` (`'dictionary'` / `'dropdown'`, not typeable), `disabled`, `source` (own page source, wins over `DataService.loadFilterDictionary`; neither = empty list + dev warning) inputs; `filterChange` / `clearAll`; pages append via the `#loadMoreSentinel` `IntersectionObserver` (browser only) and `loadMore`, a failed page rewinds for retry; `tree` mode loads levels from `DictionaryService.getNode` on open / `toggleNode` (one request per node, dropped on destroy), a phrase switches to flat search; `rows`, `optionId(n)` (`<id>-option-<n>`), `errorId` (`<id>-error`), `activeDescendantId`, `handleKeyDown` (arrows incl. tree Left/Right, Enter, Escape, Tab), `onFocusOut`, `onToggleButton`, `retryLoadDictionary`, `rowIndent`; template refs `#host`, `#field`, `#dropdownItem`, `#loadMoreSentinel`. Override (read lazily) `filterDictionaryQueryKeys`, `filterDictionaryIndents`, `filterDictionaryLabelKeys` |
| `FILTER_DICTIONARY_QUERY_KEYS`         | Default map of `filterKey ?? dictionaryKey` -> filter query key for `FilterDictionaryInputBaseComponent.selected` (`Creator` -> `creators`, `Material`, `Technique`, `CreatePlace`, `Keyword`); unmapped keys are used as is |
| `FILTER_DICTIONARY_INDENTS` / `IFilterDictionaryIndents` | Default tree row indents (mockup 2193:3460): with chevron 12/46/80, without 34/72/96, +24 px per deeper level |
| `IFilterDictionaryLabelKeys`           | Selection announcement keys (`itemSelected`, `itemDeselected`; defaults `OBJECTS.filters.item…`) for a `filterDictionaryLabelKeys` override |
| `ThemeTagsFilterBaseComponent` | Theme tags bar logic: `items` (required), `selectedIds`, `selectedKeys` (`${source}:${id}`, wins over ids), `visibleLimit` (`THEME_TAGS_VISIBLE_LIMIT`), `expanded` (model) inputs, `toggled` output; `isEmpty`, `visibleItems`, `hasMore` and protected `layout`, `totalCount`, `tagKey`, `isSelected`, `toggle(item, index)`, `toggleExpanded()`. The `[hidden]` host binding (`isEmpty()`) is in the base `@Directive({ host })` - do not redeclare it. After a toggle or a reveal focus returns to the chip (WCAG 2.4.3); chips are found by `themeTagsChipSelector` (default `[data-testid="theme-tags-filter-chip"]`, read lazily - override to change) and matched by their `data-tag-key` attribute (`tagKey(tag)`), so the template must set both |
| `CatalogFilterBarBaseComponent` / `ICatalogCategory` | Catalog filter strip logic: `searchPlaceholder` (required), `tagsLabel` (`COLLECTIONS.themeTags`), `tagSearchPlaceholder` (`COLLECTIONS.searchTags`), `phrase`, `categories`, `selectedCategoryId`, `tags`, `selectedTagIds`, `selectedTagKeys`, `remoteTagSearch` inputs; `categorySelect`, `tagToggle`, `searchPhrase`, `tagQueryChange` outputs; protected `tagQuery`, `searchText` (follows `phrase`), `tagsExpanded`, `filtersOpen`, `filteredTags` (local query ignores diacritics and never hides selected tags), `showTagsSection`, `noTagsFound`, `onTagQuery`, `toggleFilters`, `submitSearch` (trimmed phrase only when it differs from `phrase()`, empty clears) |
| `CatalogToolbarBaseComponent` / `ICatalogOption` / `CATALOG_SORT_OPTIONS` / `CATALOG_LIMIT_OPTIONS` | Catalog list toolbar logic: `idPrefix` (`catalog`), `totalCount`, `listMode` (`ListMode.masonryGrid`), `limit` (12), `page` (1), `sortBy`, `sortOptions` (`CATALOG_SORT_OPTIONS`: `name-asc`, `name-desc`, `publication-date-desc`), `limitOptions` (`CATALOG_LIMIT_OPTIONS`: 6/12/24/48) inputs; `limitChange`, `pageChange`, `sortChange` (the existing `ICatalogSort` `{ by, desc }` of `createCatalog`), `listModeChange` outputs; `ListMode`, `camelIdPrefix`, `selectedSort`, `selectedLimit` (both fall back to the first option) and `onSortChange`, `onLimitChange` (emits a number), `onListMode`. `ListMode` comes from `@smartsoft001/angular`, not this package's own `ListMode`. `ICatalogOption` is structurally an `IKeyValue`; `CATALOG_SORT_OPTIONS` / `CATALOG_LIMIT_OPTIONS` are frozen `readonly ICatalogOption[]`, so the option inputs take `readonly ICatalogOption[]` |
| `SearchbarBaseComponent` | Search bar logic: `searchText` (model), `disabled` inputs; `cleared`, `closed` outputs; `close()`, `clear()`, `search()` (no-op when disabled or blank; navigates to `[searchbarRoute, text]`, then closes) and a focus on init (browser only, after a tick, dropped on destroy). The Escape listener (`keydown.escape` -> `close()`, MOB-966) is in the base `@Directive({ host })` - do not redeclare it or one Escape emits `closed` twice. Override `searchbarRoute` (default `/wyszukaj`) and `searchbarFocusSelector` (default `input`, resolved document-wide, not scoped to the host; a selector matching nothing is ignored); both are read lazily |
| `SelectCheckboxBaseComponent` / `ISelectableRef` / `ISelectionHooks` | Card selection checkbox logic (MOB-1661): `item` (required `ISelectableRef`) input, `checked` computed and `onChange(event)` toggling `{ id, title }` with the checkbox state. The museum provides the abstract `selectCheckboxSelection` (an `ISelectionHooks`: `isSelected(id)`, `toggle(ref, checked?)`), e.g. `protected readonly selectCheckboxSelection = inject(SelectionStore)` |
| `FavoriteButtonBaseComponent` / `IFavoriteRef` / `IFavoriteHooks` / `IFavoriteButtonLabels` / `FAVORITE_BUTTON_LABELS` | Favourite button logic (MOB-1661, MOB-1867): `item` (required `IFavoriteRef`, an `ISelectableRef` plus the API `collected` hint) input, `pressed`, `busy`, `isLoggedIn` and `label` computeds, and `toggle(event)` (stops the click, then `toggle({ id, title }, collected, trigger)`). The museum provides the abstract `favoriteButtonFavorites` (an `IFavoriteHooks`: `isLoggedIn()`, `isFavorite(id, hint?)`, `isPending(id)`, `toggle(ref, hint?, trigger?)`), e.g. `inject(FavoritesStore)`; `favoriteButtonLabels` (default `FAVORITE_BUTTON_LABELS`: guest/add/remove keys) can be overridden. The guest gets a login action, so the template omits `aria-pressed` when `!isLoggedIn()` |
| `FavoritesNoticeBaseComponent` / `IFavoritesNotice` / `IFavoritesNoticeHooks` / `FavoritesNoticeKind` / `FAVORITES_NOTICE_TIMEOUT` | Favourites message logic (MOB-1566): `notice` computed, `dismiss(id)` and an auto-dismiss timer per kind (success 6000, error 10000, progress 30000 ms; override `favoritesNoticeDurations`), cancelled on destroy. The museum provides the abstract `favoritesNoticeStore` (an `IFavoritesNoticeHooks`: `notice()`, `dismissNotice(id?)`), e.g. `inject(FavoritesStore)`; the template keeps both live regions (`status` / `alert`) in the DOM |
| `ObjectCardBaseComponent<T>` / `IObjectCardItem` / `ICardSelectionState` | Object card logic shared by the grid and list cards (MOB-1588): `item` (`T \| undefined`; pass the museum's own item type as `T`, default `IObjectCardItem`, an `IObjectCardSource` plus `id`, `title`, `name`, `slug`, `image`, `multimedium`, `collected`, `description`, `publicDescriptions`) input; `favoriteRef` (`{ id, title, collected }`, an `IFavoriteRef` that feeds the favourite button and the select checkbox), `meta` (`objectCardMeta`), `hasMeta`, `seriesVisible` (first `objectCardTagsLimit` series tags), `seriesHiddenCount`, `exhibition` (`objectCardExhibition`) computeds, `seriesFilter` (`SERIES_TITLES_FILTER`) and `tagParams(tag)` (`catalogEntryFilterParams` for the cycles filter). `selection` (`ICardSelectionState \| null`: `enabled()`, `mode()`) is a template hook the base never reads, default `null`; a museum with a selection store overrides it (e.g. `override readonly selection = inject(SelectionStore, { optional: true })`). Override (read lazily) `objectCardTagsLimit` (3), `objectCardPlaceholder` (`/gfx/no-image.png`) and the `objectCardFavoriteTitle(item)` hook (`title ?? ''`) |
| `ObjectsGridItemBaseComponent<T>` | Grid (masonry) object card: the common card plus `imageSrc` (`FileUrlService.get(image ?? multimedium, 'cache', objectCardPlaceholder)` through `replaceExtension`, `''` without an item), `place` (`{ labelKey, entries }` or `null`; keys from the overridable `objectsGridItemPlaceKeys`: `archaeological` `OBJECTS.archaeologicalSite`, `place` `OBJECTS.createOrFindPlace`) and `actionsStyle` (`--img-top: <top>px; --img-bottom: <bottom>px` for positioning the heart against the image, or `null`). The template marks the image with `#img`; its `offsetTop` / `offsetTop + offsetHeight` are measured after the first render and followed by a `ResizeObserver` disconnected on destroy - browser only, so `actionsStyle` is `null` on the server and without `ResizeObserver`. The favourite title falls back to `name`. Tags limit 3 |
| `ObjectsListItemBaseComponent<T>` / `IObjectsListItemField` | List-row object card: the common card with 5 series tags (`objectCardTagsLimit` override) plus `imageSrc` (`FileUrlService.get(image, 'cache')`; the framework `assets/no-image.svg` placeholder becomes `objectCardPlaceholder`, anything else goes through `replaceExtension`), `description` (first non-blank `publicDescriptions[].text`, else `description`, tags replaced by spaces, whitespace collapsed) and `fields` (`IObjectsListItemField`: `key`, `labelKey`, `entries`, `separator`; place `'; '`, types / techniques / materials `', '`, inventory `''`, in that order, empty fields dropped). Override (read lazily) `objectsListItemFieldKeys` (`archaeological`, `place`, `types`, `techniques`, `materials`, `inventory`; defaults `OBJECTS.*` / `DETAILS_PAGE.detail.*`) |
| `CollectionCardBaseComponent<T>` / `ICollectionCardItem` | Collection card logic; the list row extends it directly (it has no logic of its own). `item` (`T \| undefined`, default `ICollectionCardItem`: `id`, `title`, `description`, `itemCount`, `image`, `cycles`) input; tag hooks `tags` (`[]`), `tagsInteractive` (`false`), `selectedTagIds` (`[]`) inputs and `tagSelect` output; `cardTags` (the given `tags`, else the item's `cycles` when an array, else `[]`, MOB-1600), `isTagSelected(tag)` (compares `normalizeCycleId` values), `imageSrc` (`FileUrlService.get(image)`; the `assets/no-image.svg` result becomes the placeholder, `''` without an item), `onImageError(img)` (MOB-1564: retries once with the `noCache` url, remembered in `dataset.originalTried`, then the placeholder) and `description` (tags and entities turned into spaces, whitespace collapsed). Override (read lazily) `collectionCardPlaceholder` (`/gfx/no-image.png`) |
| `CollectionsGridItemBaseComponent<T>` / `COLLECTIONS_GRID_SINGLE_ROW_QUERY` | Grid collection card: the common card plus `hiddenTagIds` (`ReadonlySet` of the pills that do not fit one row from md, MOB-1808: `overflowingTags` against `(min-width: 768px)`; the template hides them and shows "+N"). The template marks the pill list with `#tagsList`; the list and every pill are observed with a `ResizeObserver`, disconnected on cleanup and on destroy. Browser only: on the server (or without `ResizeObserver` / `matchMedia` from the injected `DOCUMENT`'s `defaultView`) the set stays empty, so every tag is visible. Override (read lazily) `collectionsGridItemSingleRowQuery` |
| `SelectionActionsBaseComponent<T>` / `ISelectionActionsSelection` / `ISelectionActionsFavorites<T>` / `ISelectionActionsResult` / `ISelectionActionsChoice` | Logic of the actions on a list selection (MOB-1661): "Add selected to favourites" opens a non-modal dialog with the target collection choice. `menuOpen`, `saving` signals and `canAdd` computed (`count() > 0` and not saving); `toggleMenu()` (a guest gets `requireLogin()`; else opens, `reload()`s collections whose `status()` is not `'ready'` and focuses `#choice` (`focusFirst()`) after a tick, or closes with focus back on the button), `closeMenu(restoreFocus?)`, `addTo(target: T)` (`addMany(selected, target)`, the dialog stays open with `aria-busy` while saving, the selection is cleared only without `failed` / `refreshFailed`; then focus moves after render to the first enabled of `#addButton` (only when not cleared), `#selectAll`, `#countMessage` if it was inside the dialog or lost), `createAndAdd(title)` (`createCollection` then `addTo(id)`), `onFocusOut(event)` (closes when focus leaves `#menuWrapper`, but not for an ancestor - Safari), `onEscape()` (returns focus only from inside) and `onDocumentClick(event)` (closes on a click outside the host). The museum provides the public `selection` (`count()`, `selected()`, `clear()`) and `favorites` (`isLoggedIn()`, `requireLogin()`, `status()`, `reload()`, `addMany(refs, target)`, `createCollection(title)`) hooks, e.g. `inject(SelectionStore)` / `inject(FavoritesStore)`; `T` is the collection target. Template refs: `#addButton`, `#menuWrapper`, `#selectAll`, `#countMessage`, `#choice`. The `document:click` and `document:keydown.escape` listeners live in the base `host` - do not redeclare them |
| `DownloadCardsBaseComponent` / `IDownloadCardsResult` / `IDownloadCardsProgress` / `IDownloadCardsExportOptions` / `IDownloadCardsMessage` / `IDownloadCardsLimits` / `IDownloadCardsKeys` / `DownloadCardsStatus` / `DownloadCardsPhase` / `DownloadCardsErrorCode` / `DOWNLOAD_CARDS_LIMITS` / `DOWNLOAD_CARDS_FORMATS` / `DOWNLOAD_CARDS_FORMAT_LABELS` / `DOWNLOAD_CARDS_KEYS` / `DOWNLOAD_CARDS_ERROR_CODES` | "Download cards of the selected objects" logic (MOB-1663), a WAI-ARIA menu button: `ids` (required) and `fileName` inputs; `formats` (`pdf-full`, `pdf-brief`, `docx-brief`) and `formatLabels` (label / hint keys); `open`, `status` signals; `working`, `empty`, `overLimit`, `unavailable` and `messages` (`aria-live` keys and params: progress per phase, done, skipped, oversized with the MB limit, without thumbnail, cancelled, errors with `{ count, limit }`) computeds; `toggle()`, `onTriggerKeydown(event)` (ArrowDown / ArrowUp open at the first / last format), `onMenuKeydown(event)` (arrows wrap, Home / End, Escape closes and refocuses the trigger, Tab closes), `onDocumentClick(event)`, `choose(format)` (over the limit: an error without exporting; else `working` with progress, then `done`, `cancelled` or `error`) and `cancel()`; a running export is aborted on destroy. The museum implements the `downloadCardsExport(format, ids, options)` hook (e.g. lazily `injector.get(DownloadService).export(...)`); `downloadCardsErrorCode(error)` maps an `Error` with a known string `code` and anything else to `failed`. Override (read lazily) `downloadCardsLimits` (50 cards, 20 MiB per response, 150 MiB total) and `downloadCardsKeys`. Template refs: `#trigger`, `#item` (in `formats` order). The `document:click` listener lives in the base `host` - do not redeclare it |
| `RecommendedBaseComponent<O, C, A>` / `IRecommendedSources<O, C, A>` / `IRecommendedCard` / `RecommendedTabId` / `RECOMMENDED_TAB_LABELS` / `recommendedPerPage(width)` | Logic of the "recommended" module on the object and article pages (Figma 2289:23952, MOB-1801 / MOB-1805): tabs with counters and cards in pages. `sources` (required `IRecommendedSources`: `objects`, `collections`, `articles`; items without an `id` are skipped, empty tabs disappear), `idPrefix` (`recommended`) inputs; `trackId` (`<idPrefix>-recommended-track`), `tabs` (`ITab[]` with the full `count`, labels via `instant` and re-translated on a language change; ready for `TabsBaseComponent`), `activeTab` (writable `linkedSignal`, bind it two-way; keeps the tab while it exists, else the first), `perPage` (4 on the server), `pages`, `page` (resets to 0 on a tab change, clamped otherwise), `visibleObjects` / `visibleCollections` / `visibleArticles` (only the current page is rendered, even for 100 related objects) and `goTo(page)` (wraps). The template marks the strip with `#track`: a `ResizeObserver` on it (browser only, disconnected on destroy) sets `perPage` from `recommendedPerPage(width)` (>= 960 -> 4, >= 560 -> 2, else 1; a zero width is ignored). Override (read lazily) `recommendedTabLabels` (`RECOMMENDED_TAB_LABELS`) and `recommendedCardsPerPage(width)`. The museum keeps the template, the max-bars input and the card type aliases |
| `MapBaseComponent` / `IMapIconUrls`    | Single-marker OpenStreetMap map: `latitude`, `longitude`, `zoom` (17) inputs, `#map` view child; the app owns the `leaflet` dependency and implements `loadLeaflet()` (`return import('leaflet')`); override `mapIconUrls` / `mapMarkerHtml`; nothing runs on the server |
| `MenuItemBaseComponent` | One first-level CMS menu entry (`MenuComponent` is unrelated and unchanged): `item` (required `ConfigMenuItem`) input, `navigated` output; `routeCommands`, `routeQueryParams`, `routeFragment` (route), `externalHref` (another site), `nativeHref` (`mailto:`, `tel:`, `#fragment`) computeds - each `null` (`routeFragment`: `undefined`) when the entry is of another kind; `newTabText`, `externalLabel` (capitalised title + the new-tab note, follows the language). Override the protected `menuItemResolveTarget(item)` hook (default `resolveMenuItemTarget(item)`, read lazily) to pass the museum's `siteUrl` |
| `BreadcrumbsBaseComponent` | Page breadcrumbs declaration only (renders nothing; the museum keeps its selector and `template: ''`): `links` (`IBreadcrumbLink[]`, `[]`), `disabled` (`false`, article preview) inputs, registered with `BreadcrumbsService.set(this, links, disabled)` in a constructor `effect` and cleared on destroy. The effect runs on the server too, so the trail is serialized to TransferState and the SSR bar survives hydration |
| `BreadcrumbsBarBaseComponent` / `IBreadcrumbsBarItem` / `IBreadcrumbsBarHint` | Header breadcrumbs bar logic (MOB-1803): `items` (home item first, then the registered links; `text` = `label ?? translationKey`, `translate` when there is no `label`, `html` from `innerHtml`, only the last link `current`; home is `current` on the home page with no links), `hasCurrent`, `disabled` (from the current entry), `hint` (`{ index, text }` of a truncated label, MOB-1799), `hintFor(event)`, `hideHint()`. The five host listeners (`mouseover`/`focusin` -> `hintFor`, `mouseleave`/`focusout`/`keydown.escape` -> `hideHint`) are in the base `@Directive({ host })` - do not redeclare them or each event runs twice. Override (read lazily) `breadcrumbsBarHomeRoute` (`/strona-glowna`), `breadcrumbsBarHomeKey` (`HOME.homeIndex`), `breadcrumbsBarItemSelector` (`[data-testid="breadcrumbs-item"]`), `breadcrumbsBarLabelSelector` (`a, span:not([aria-hidden])`) |
| `DropdownBaseComponent` | Single-choice dropdown as an ARIA listbox (catalog sort / page size): `dropdownId` (`sortDropdownId`; not `id`, which would duplicate on the host), `label`, `selected` (`ICatalogOption`), `options` (`readonly ICatalogOption[]`), `disabled` inputs, `optionChange` output (key), `isOpen` signal; `toggleDropdown(force?)`, `selectOption(key)`, `onTriggerKeydown(event)`, `onListKeydown(event)`. Keyboard: on the trigger ArrowDown / ArrowUp open and focus the selected option (none selected: first / last); in the list ArrowDown / ArrowUp wrap, Home / End, Enter / Space emit the focused option, Escape closes and refocuses the trigger, Tab closes. Template refs: `#triggerRef` (button), `#optionRef` (each option). The delayed option focus runs only in the browser and is cancelled on destroy. Markup, classes and the compact mobile label are the museum's |
| `TabsBaseComponent<T extends ITab>` / `TABS_GENERATED_ID_PREFIX` | ARIA tab list logic: `tabs` (required `T[]`), `activeTabId` (required model), `idPrefix` (`null`) inputs, `prefix` computed (`idPrefix` or a per-instance `app-tabs-…-` id from `_IdGenerator`; pass `idPrefix` for tabs rendered in SSR so ids stay stable through hydration); `handleKeydown(event)` roving focus (ArrowRight / ArrowLeft wrap, Home, End; prevents default, sets `activeTabId`, focuses the tab); `ensureActiveTabVisible()` scrolls only the overflowing tab row (`scrollLeft`, never `scrollIntoView` or the page) to reveal the active tab after tab changes, row resizes (`ResizeObserver`) and web-font loading; browser only. Template ref: `#tabButton` on each tab, directly inside the scrolled row. Override (read lazily) `tabsListSelector` (`[role="tablist"]`, the observed row). Variants and classes are the museum's |
| `WcagBaseComponent` | Accessibility (WCAG) settings logic for the desktop dropdown and the `mobile-panel` mode (header panel, no trigger): `buttonId` (`dropdownButton`), `mode` (`WcagMode`, `'dropdown'`) inputs; `isPanel`, `isOpen`, `lineHeight` (from `LineHeightService`, restored on construction), `isHighContrastOn`, `isGrayscaleOn` (both read from `WcagService`), `panelId` (`<buttonId>Panel`), `titleId` (`<buttonId>Title`), `labelId(key)` (`<buttonId><key>Label`), `optionId(id)` (`mobile` + capitalised id in `mobile-panel` mode, so the two instances never share ids); `optionGroups` (one `IWcagOptionGroup` per definition: option `id` = `idPrefix` + capitalised value, `selected` from `WcagService` / `LineHeightService`, `icon` from `wcagOptionIcons`); `toggleDropdown()`, `toggleHighContrast(force?)` / `toggleGrayscale(force?)` (mutually exclusive through the service setters in one call, MOB-966), `selectOption(kind, value)` (the matching `WcagService` setter or `LineHeightService`; the `setContrast` and `setGrayscale` kinds are display-only inside option groups - contrast and grayscale switch through `toggleHighContrast` and `toggleGrayscale`), `setLineHeight`, `toggleOption`, `closeAndFocusTrigger()` (focuses `#<buttonId>` in the browser only), `closeDropdown()`; every change calls `WcagChangesService.notifyWcagSettingsChanged()`. Groups are `aria-pressed` buttons in a `role="group"` - no arrow-key radio model. The Escape listener (`keydown.escape` -> `onEscape()`, closes and refocuses the trigger while open) is in the base `@Directive({ host })` - do not redeclare it or each Escape runs twice. Override (read lazily) `wcagOptionGroupDefinitions` (`WCAG_OPTION_GROUPS`) and `wcagOptionIcons` (group key -> value -> 16×16 SVG path, default `{}`). Markup, classes and icons are the museum's |
| `WCAG_OPTION_GROUPS` / `WcagMode` / `WcagOptionKind` / `IWcagOption` / `IWcagOptionGroup` / `IWcagOptionDefinition` / `IWcagOptionGroupDefinition` | Frozen default WCAG option groups in mockup order: `textSize` (`HOME.accessibility.textSize`, `setText`, `textSizeButton`; small / normal / large with screen reader labels `WCAG.smallText` / `normalText` / `largeText`), `lineHeight` (`WCAG.lineHeight`, `lineHeightButton`; normal / medium / large), `wordSpacing` (`setWordSpacing`), `letterSpacing` (`setLetterSpacing`), the size options labelled `HOME.accessibility.small` / `normal` / `large`. `WcagMode` = `'dropdown' \| 'mobile-panel'`, `WcagOptionKind` = `WcagChangeType \| 'lineHeight'`; a definition is `{ key, labelKey, kind, idPrefix, options: { value, labelKey, srLabelKey? }[] }` |
| `LanguageSwitchBaseComponent` / `injectLanguageSwitch(options?)` / `ILanguageSwitch` / `ILanguageSwitchOption` / `LANGUAGE_SWITCH_NAME_KEY_PREFIX` | Language switch logic (sztuki-2 `app-language-switch`, the template's `switchLanguage`, Podlasie's language list). `injectLanguageSwitch({ nameKeyPrefix?: () => string })` (injection context; use it inside a header, which can extend one base only) returns `ILanguageSwitch`: `languages` (`ILanguageSwitchOption[]` from `MOBILEMS_APP_OPTIONS.languages.available`, else the current language only; `label` = upper-case code, `nameKey` = prefix + code, prefix `LANGUAGE_SWITCH_NAME_KEY_PREFIX` = `HOME.languages.`), `current` (`TranslationService.currentLanguage`), `target` (the next available language after the current one, cyclic; `null` with fewer than two), `hasChoice` (more than one language - hide the list otherwise, Podlasie, Emil 2026-10-02), `switchTo(code = target())` (no-op for `null` or the current language; `TranslationService.setLanguage(code)`, then `location.reload()` in the browser only). The base exposes the same `languages`, `current`, `target`, `hasChoice` and `switchLanguage(code?)`; override (read lazily) `languageSwitchNameKeyPrefix`. Markup is the museum's: show the target's code with `lang` on it and start the accessible name with that visible code (WCAG 2.5.3, sztuki MOB-1617) |
| `HeaderBaseComponent<TPanel>` | Header logic (Podlasie `app-header`): `isHomePage` (route url through `isHomePath`; default `headerBaseHomePaths` = `MOBILEMS_APP_OPTIONS.homePaths ?? DEFAULT_HOME_PATHS`, default `headerBaseHomePathOptions` = `{ strict: true }`, Podlasie's rule; override with `{}` for the lenient one), `isHighContrast` (`WcagContrastService`), mobile panels: `openPanel`, `togglePanel(panel)` (one open at a time), `closePanel(restoreFocus = true)`, `onEscape()`. Escape is in the base host (`document:keydown.escape`) - do not redeclare it. Trigger ids are a subclass map (`protected readonly headerBasePanelTriggerIds: Record<TPanel, string>`); focus returns to the trigger synchronously in the browser only (override `headerBaseFocusTrigger(id)` for another timing). Every `NavigationEnd` closes the panel without moving focus, except the navigation already in flight when the panel opened (the initial lazy navigation). `protected headerBaseCurrentUrl` = url after redirects, seeded from `Location.path()` before the first navigation. Search, menus, breadcrumbs, the a11y bar and the language list stay in the museum (`injectLanguageSwitch()` for the list) |
| `FooterBaseComponent` | Footer logic (Podlasie `app-footer`): `data` (`Signal<Config \| null>`, set by `ngOnInit` from `ConfigsFacade.init()`; a failed request is logged with `console.error` and `data` stays `null`, so the static parts still render), `isHighContrast` (`WcagContrastService`, for the monochrome logo variants), `currentYear`. Menus, columns, logos, newsletter and the social links (`footerSocialLinks`) stay in the museum |
| `PageSectionBaseComponent`             | A CMS page section variant (`section` input, required)              |

A base that releases resources in `ngOnDestroy` (sliders, maps, carousels, the newsletter modal, the
fullscreen gallery) relies on it running. A subclass that overrides `ngOnDestroy` must call
`super.ngOnDestroy()`, or timers, listeners and the map stay alive after the view is gone.

## Services

All are `providedIn: 'root'` unless noted; `SERVICES` exports the array for module providers.

| Service                | Key API                                                                                          |
| ---------------------- | ------------------------------------------------------------------------------------------------ |
| `ConfigsService`       | `get()`, `getPage(ref: PageRef)` — CMS config + page fetch (`page/<id>`, `page/home`, `page/slug/<slug>`) |
| `DictionaryService<T>` | `get(...)`, `getNode(...)` — filter dictionaries (**lowercase keys**, e.g. `authors`)             |
| `CrudBaseService<T>`   | abstract: `getById(id)`, `downloadPdf(name, id)` — extend for a module service                    |
| `SearchService`        | `search(txt, data)`, `setCurrentSearchText(txt)`, `getFilterQuery(...)` (needs `SEARCH_CONFIG_TOKEN`); the standalone `getSearchFilterQuery(type, txt, data)` builds the same query string outside DI. Counts `objects`, `publicCollections`, `articles`; `ISearchConfig.creators: true` (default `false`) adds `creators` (`dictionary/Creator/search/page/1?maxPerPage=1&q=…`, `ISearchResults.creators`; an empty phrase omits `q`, like the other counts; a whitespace-only one sends `q=%20`, which the API answers with 404, counted as 0); `searchMap` still overrides any url |
| `FileUrlService`       | `get(...)` with `FileUrlMode = 'cache' \| 'big' \| 'noCache'` — builds multimedia URLs            |
| `SettingsService`      | `getMediaUrl()`, `getBaseTitle()`, `getCanLink()`, `getMainLogo()`                                 |
| `TranslationService`   | `init(defaultLang, availableLangs)` resolves `?lang=` → stored preference (localStorage / SSR cookie `SELECTED_LANGUAGE`) → default and sets `<html lang>`; `get(key, params)`, `setLanguage(lang)` persists to localStorage + cookie (`ITranslationConfig`) |
| `SeoService`           | `updateTitle`, `updateDescription`, `updateMetaTags`, `updateOgTags`                              |
| `MuseumSeoService`     | `apply(metadata: ISeoMetadata)` — title, description (≤170 chars), OG + Twitter tags, canonical + `hreflang` links (`?lang=` for non-default languages), site-wide JSON-LD (`WebSite` + optional `Organization`, `<` escaped); `applyForSsr(fetcher)` applies fetched metadata inside an SSR pending task (4.5 s cap); `currentLanguage()`. Constants from `MOBILEMS_SEO_OPTIONS` (`IMuseumSeoConfig` = `IMobilemsSeoOptions` + `languages`/`defaultLanguage`); neutral defaults without the token. `SeoMetadataType` = `'article' \| 'website'`. `ISeoMetadata.resolveRelativeUrl` (opt-in, default off): a root-relative `url` (not `//`) is resolved against the site origin (`siteUrl()`, else the document origin) and becomes the canonical / `og:url` instead of the request URL; absolute urls and no `url` behave as before |
| `MetaService`          | `keepUpdatingPageTitle`, `setPageMetadata`, `setObjectMetadata`, `setImageMetadata`, `resetMetadata`, `setTitle`, `setDescription`, `updateTag`, `destroy` |
| `WcagService`          | `init()`, `setContrast/setText/setLetterSpacing/setWordSpacing/setGrayscale`, `reset()`            |
| `ContrastService`      | `changeTheme(active)`, `toggle()`                                                                  |
| `StyleService`         | `init(elementRef, customVariables?)` — applies theme CSS variables                                 |
| `ModalService`         | `open(templateRef): ModalRef`, `closeAll()`; `ModalRef.close()`                                    |
| `AuthStorageService`   | `setUser`, `getUser`, `removeUser`, `hasUser`                                                      |
| `GlobalService`        | `setHeaderVisibility`, `setFooterVisibility`, `hexToRgb`, `rgbToHex`                               |
| `QueryFilterService`   | Query-string ⇄ filter helpers                                                                      |
| `ConfirmationModalService` | `open(config: IConfirmationModalConfig): Promise<boolean>` (single flight: a second `open()` while open resolves `false`), `confirm()`, `cancel()`, signals `isOpen()` / `config()`, `takeReturnFocusTarget()` (once). The modal markup stays in the app and reads this service |
| `ExternalLinkConfirmationService` | `handleLinkActivation(event, anchor)` — internal links via Router, external ones after the "Opuszczasz stronę" modal (`COMMON.externalLinkTitle`, `externalLinkWarning`, `stay`, `continue`, Polish fallbacks), `mailto:`/`tel:`/`#` untouched; `confirm(returnFocusTo?)`, `confirmAndOpen(href, newTab)`, `classify(href)` (`classifyLink` with `MOBILEMS_ENVIRONMENT.siteUrl`). `opensInNewTab(event, anchor)` — `target=_blank`, Ctrl/Cmd/Shift or middle button |
| `FilterPersistenceService` | `saveFilter(key, filter)` (memory + base64 URL hash), `loadFilter(key)` (hash first, then memory), `clearFilter(key)`; no-op on the server |
| `OrientationService`   | Signals `isLandscape()`, `isCompactHeight()` (≤ 600 px) from `BreakpointObserver` (`@angular/cdk` peer); `false` on the server |
| `LineHeightService`    | `lineHeight()` signal (`WcagLineHeight` = `'normal' \| 'medium' \| 'large'`, default `'normal'`), `set(value)` (persists to localStorage under `LINE_HEIGHT_STORAGE_KEY` = `WCAG_LINE_HEIGHT`), `init()` restores the stored value, `applyToDom()` sets the `line-height-<value>` body class — re-applied after every WCAG config change because `WcagService` wipes `body.className`; no-op on the server |
| `BreadcrumbsService`   | Breadcrumb trail registry (MOB-1803): `set(owner, links: IBreadcrumbLink[], disabled = false)`, `clear(owner)`; signals `current()` (`{ owner, links, disabled, path }` of the last registered owner, or `null`), `path()` (router path without query/hash, seeded from `Location`), `isHomePage()` (path in `MOBILEMS_APP_OPTIONS.homePaths`, default `/` and `/strona-glowna`). A cleared top entry stays until the path changes; on the server the entry is serialized to TransferState key `mob-breadcrumbs` and restored in the browser for the same path. `IBreadcrumbLink` = `{ route, translationKey?, label?, innerHtml? }`; `IBreadcrumbsEntry` = the type of `current()` |
| `WcagChangesService`   | `notifyWcagSettingsChanged()`; signal `wcagSettingsChanged()` fires on every call                  |
| `WcagContrastService`  | High contrast and grayscale, mutually exclusive (MOB-966): signals `isHighContrastOn()` (`WcagService.config().contrast === 'high'`) / `isGrayscaleOn()` (`grayscale === 'true'`); `setHighContrast(on)` / `setGrayscale(on)` set the mode through the `WcagService` setter and switch the other one off when turning on; `toggleHighContrast(force?)` / `toggleGrayscale(force?)` (`force ?? !current`). Every change calls `WcagChangesService.notifyWcagSettingsChanged()`. `WcagBaseComponent` delegates to it |
| `ContactService`       | `submitContactForm(data: IContactFormData): Observable<IContactFormResponse>` — `POST api/contact/submit` with `domain` = `MOBILEMS_ENVIRONMENT.siteUrl` |
| `DataService`          | `loadPromotedObjectsForHome(): Signal<IObject[]>`, `loadFilterDictionary(dictionary, page?, query?): Observable<IDictionaryPage>` (`DICTIONARY_PAGE_SIZE` = 500; `authors` → `api/article/…`), `loadCycleTags(query?)` — every page of the `Cycle` dictionary (`CYCLE_TAGS_PAGE_SIZE` = 100, at most `CYCLE_TAGS_MAX_PAGES` = 20), cached without a query, `[]` on error. `normalizeDictionaryItems(items)` keeps entries with a numeric id and a name, without duplicates. `IDictionaryResponse` is the raw API envelope |

```ts
private readonly breadcrumbs = inject(BreadcrumbsService);
private readonly lineHeightService = inject(LineHeightService);

constructor() {
  this.breadcrumbs.set(this, [{ route: '/obiekty', translationKey: 'OBJECTS.title' }]);
  inject(DestroyRef).onDestroy(() => this.breadcrumbs.clear(this));
}

setLargeText(): void {
  this.lineHeightService.set('large'); // persisted, body class line-height-large
}
```

The breadcrumbs `owner` is any object (usually the component, `this`) and is compared by identity:
`clear(owner)` only removes the entry that same object registered.

`DataService` and `ContactService` take the API URL from `SharedConfig.apiUrl`, falling back to
`MOBILEMS_ENVIRONMENT.apiUrl`.

## State

| Export          | Purpose                                                             |
| --------------- | ------------------------------------------------------------------- |
| `ConfigsFacade` | `init(): Promise<Config>` (in-flight promise shared between callers, retried after a rejection), `getPage(ref: PageRef)`, config signals |

Feature state (`ObjectsFacade`, `ArticlesFacade`, `PublicCollectionsFacade`) lives in the feature
packages and extends `CrudFacade` from `@smartsoft001/crud-shell-angular`.

## Directives

All are **standalone**. `SharedModule` does **not** re-export them — the exported `DIRECTIVES`
array is empty, so importing `SharedModule` gives you no directives. Add the ones you need to the
`imports` of the standalone component that uses them:

```typescript
import { ScrollableDirective, HoverDirective } from '@smartsoft001-mobilems/angular';

@Component({ imports: [ScrollableDirective, HoverDirective], /* … */ })
```

| Directive               | Selector              | Purpose                                        |
| ----------------------- | --------------------- | ---------------------------------------------- |
| `ClickOutsideDirective` | `[smartClickOutside]` | Emits `ClickOutsideEvent` on an outside click   |
| `HoverDirective`        | `[smartHover]`        | Hover state without component boilerplate       |
| `ScrollableDirective`   | `[smartScrollable]`   | Programmatic scrolling + overflow detection     |
| `ExternalLinkDirective` | `a[smartExternalLink]` | Confirmation modal before leaving the site     |
| `ExternalLinksDirective` | `[smartExternalLinks]` | The same for every link inside CMS HTML        |
| `FocusTrapDirective`    | `[smartFocusTrap]`    | Modal focus trap + `inert` on the rest of the page |
| `TruncatedTitleDirective` | `[smartTruncatedTitle]` | `title` only when the text is cut by an ellipsis |
| `InPageAnchorsDirective` | `[smartInPageAnchors]` | `href="#id"` links in CMS content scroll to and focus their target and change only the hash, instead of jumping to `/#id` (MOB-1828) |

**`ClickOutsideDirective`** — input `isActive: boolean` (default `true`; when `false` nothing is
emitted), output `smartClickOutside: ClickOutsideEvent`. The output shares the selector's name, so the
element carries both: `<div smartClickOutside [isActive]="open()" (smartClickOutside)="close()">`.
Clicks on descendants count as inside. `ClickOutsideEvent` is `{ event: MouseEvent; target: EventTarget | null }`.

**`HoverDirective`** — no inputs or outputs. Adds/removes the `hover` class on the host element on
`mouseenter` / `mouseleave`; style it from CSS.

**`ScrollableDirective`** — `exportAs: 'smartScrollable'`, so grab it with a template reference
variable. Required input `scrollUnit: number` (pixels per scroll unit). Methods
`scrollHorizontal(units)` / `scrollVertical(units)` (negative units scroll back). Read-only **signals**
— call them: `canScrollStartHorizontal()`, `canScrollEndHorizontal()`, `canScrollStartVertical()`,
`canScrollEndVertical()`, `scrollLeftPosition()`, `scrollTopPosition()`. They refresh on `scroll`,
on window `resize`, and when `scrollUnit` changes.

```html
<div smartScrollable [scrollUnit]="200" #scroll="smartScrollable">…</div>
<button (click)="scroll.scrollHorizontal(1)" [disabled]="!scroll.canScrollEndHorizontal()">→</button>
```

**`ExternalLinkDirective`** — input `skipConfirmation` (default `false`), output `linkActivated`
(navigation started: Router or "Kontynuuj"; nothing on "Zostań na stronie"). Handles `click` and
middle-button `auxclick` through `ExternalLinkConfirmationService`.

**`ExternalLinksDirective`** — for hosts with `[innerHTML]`. Delegated clicks (skipped when an inner
`smartExternalLink` already handled them, so one click opens one dialog; `download` links untouched).
In the browser, after render and on every content, link attribute or language change, external links
get `rel="noopener noreferrer"` and `target="_blank"` ones a hidden "(otwiera się w nowej karcie)"
note (`smart-sr-only`; via `aria-describedby` when the link has `aria-label`; skipped when a
`[data-new-tab-hint]` already announces it). SSR output is unchanged.

**`FocusTrapDirective`** — focuses `[data-focus-initial]` (or the first focusable), keeps Tab /
Shift+Tab and stray focus inside, sets `inert` on the rest of the page (except `[data-focus-trap-ignore]`)
and returns focus on destroy.

**`TruncatedTitleDirective`** — `[smartTruncatedTitle]="text"`: sets `title` only while
`scrollWidth > clientWidth`; re-measures on resize and after web fonts load.

**`InPageAnchorsDirective`** — delegated `click` on `a[href^="#"]` inside the host (with at least one
character after `#`; modifier, non-primary and already prevented clicks are skipped). The default is
always prevented; the target is found by `id`, then `a[name]` (the fragment is URI-decoded, so
`#%5B12%5D` finds `id="[12]"`), scrolled into view, given `tabindex="-1"` if missing, focused, and
the address becomes `pathname + search + #fragment` via `history.replaceState` (no router
navigation). Usable as a `hostDirectives` entry on the app root.

**Content links on the app shell (FRA-415, opt-in).** `AppComponent` carries `InPageAnchorsDirective`
and `ExternalLinksDirective` (in that order) as host directives. They are **off by default**: without
`provideMobilemsApp({ contentLinks })` the shell renders and handles clicks as before this release (no
`rel`, no new-tab notes, no prevented clicks). With `contentLinks: true` (or an object) they cover
everything inside `<smart-mobilems-app>`, CMS `[innerHTML]` included, so a museum no longer has to
add `smartExternalLinks` to each CMS host. One click is still handled once: an inner
`a[smartExternalLink]` or `[smartExternalLinks]` handles it first (and the shell sees it as
prevented), and a `#id` click prevented by the shell is skipped by an `InPageAnchorsDirective` on an
ancestor.

- `IContentLinksOptions` — `{ externalLinks?: boolean; inPageAnchors?: boolean }`; a key left out of an
  object is on.
- `MOBILEMS_CONTENT_LINKS` — `InjectionToken<Required<IContentLinksOptions>>` that `AppComponent`
  provides on its own element. Both directives read it with `{ self: true, optional: true }`, so only
  the shell instances are switched; a `[smartExternalLinks]` / `[smartInPageAnchors]` anywhere else
  keeps working whatever the option says. Disabled, a directive returns from its click handler at once
  and `ExternalLinksDirective` sets up neither its effect nor its `MutationObserver`.
- `resolveContentLinks(option: IContentLinksOptions | boolean | undefined)` — `undefined` / `false` →
  both off, `true` → both on, an object → each key on unless it is `false`.

Apps that opt in and attach `InPageAnchorsDirective` to their own root can drop it (keeping it is
harmless: the click is handled once). With `externalLinks` on, the shell leaves two kinds of links to
the browser: a same-site link whose path has a file extension (`/upload/x.pdf`, checked with
`urlExtension`) is not sent through the Router (which would show not-found), and a link to the
multimedia host (`multimediaUrl` of `MOBILEMS_ENVIRONMENT`, else `SharedConfig`; `www.` and
http/https ignored) gets no "Opuszczasz stronę" modal — those are the museum's own files. A
`[smartExternalLinks]` outside the shell keeps the old behaviour (file links routed, multimedia links
confirmed).

```html
<a href="https://example.org" smartExternalLink>Example</a>
<div smartExternalLinks [innerHTML]="content"></div>
<div role="dialog" smartFocusTrap>…</div>
<span class="smart-truncate" [smartTruncatedTitle]="tag.name">{{ tag.name }}</span>
```

## Pipes

| Pipe                       | Class                 | Purpose                                                      |
| -------------------------- | --------------------- | ------------------------------------------------------------ |
| `smartMobilemsSectionHtml` | `PageSectionHtmlPipe` | Sanitized CMS section HTML or `null` (see page sections)     |
| `smartMobilemsSectionCounter` | `PageSectionCounterPipe` | Banner counter value for the app `LOCALE_ID` (see page sections) |
| `capitalize`               | `CapitalizePipe`      | First letter upper-cased, `''` for `null`/`undefined`                    |
| `altText`                  | `AltTextPipe`         | `file \| altText: baseAlt` — `MsFile.altTextEn` for English, else `altText`, else `baseAlt`; tags stripped |
| `fileUrl`                  | `FileUrlPipe`         | `file \| fileUrl: mode` — multimedia URL via `FileUrlService` (`FileUrlMode`, default `cache`) |
| `backgroundUrl`            | `BackgroundUrlPipe`   | Sanitized `url(…)` style for `[style.background-image]`                  |
| `plainText`                | `PlainTextPipe`       | HTML → plain text: script/style dropped, block tags become spaces, entities decoded, whitespace collapsed (`toPlainText(value)` outside templates) |
| `stripAnchors`             | `StripAnchorsPipe`    | Removes `<a>` tags, keeps their content                                   |

`replaceExtension(path, mode)` — for `media/dictionaries` files: `cache` → `.jpg`, `big` turns `.png` into `.jpg` (used by both URL pipes).

If a museum app needs another pipe, add it to that app's `libs/shared/angular` (and its README) —
never per-module.

## Guards

| Guard                  | Purpose                                     |
| ---------------------- | ------------------------------------------- |
| `authenticationGuard`  | `CanActivateFn` — requires a stored user    |
| `unauthorizedGuard`    | `CanActivateFn` — only for anonymous users  |

## Interceptors

Class interceptors (`HTTP_INTERCEPTORS`, `withInterceptorsFromDi()`), registered by
`provideMobilemsCore()` in this order — or by hand in apps that do not use it:

| Interceptor                | What it does                                                                                     |
| -------------------------- | ------------------------------------------------------------------------------------------------ |
| `LanguageInterceptor`      | `Accept-Language: PL` for a `pl*` UI language, else `EN` (current → default → `pl`)               |
| `PreviewAuthInterceptor`   | `withCredentials` for CMS preview requests (`/admin…/json-preview`)                              |
| `SsrTimeoutInterceptor`    | On the server, answers `{ data: null }` (200) after 5 s instead of hanging the render             |
| `DedupeRequestInterceptor` | Shares one in-flight response between identical GETs (and the read-only `object-of-the-week` POST) keyed by method, url, `Accept-Language` and body; last in the chain |

## Models, interfaces and tokens

- Config/UI: `ListMode`, `IQuickMenu`, `ITab`, `IImages`, `ImageBox`, `IAudio`, `IVideo`,
  `IErrorMessages`, `IObjectGallery`, `IObjectGalleryItem`, `IObjectGallerySingleObject`,
  `ISingleObjectMultimedia`
- Games: `IGame`, `GameType`, `IGameQuestion`, `IGameAnswer`, `IGameMemoConfig`, `IGamePuzzleConfig`,
  `IGameQuizConfig`
- Component contracts: `IHeaderUser`, `IHeaderConfig`, `IFooterStaticPage`, `IFooterConfig`,
  `IMenuItem`, `IMenuConfig`, `ClickOutsideEvent`, `IDictionaryItem`, `PageSlide` (slider input)
- Search: `ISearchConfig`, `ISearchData`, `ISearchResults`, `SearchSource`, `SEARCH_CONFIG_TOKEN`,
  `SearchQuery`, and the saved-query shapes `IUserQuery`, `IUserQueryList`, `IFilterItem`,
  `IFilterOne`
- Account flows (used by apps that enable the user module): `IUser`, `IUserInfo`, `IUserRegister`,
  `IUserModify`, `ILoginResponse`, and the form error messages `ChangePasswordErrorMessage`,
  `ForgotPasswordErrorMessage`, `ModifyUserErrorMessage`, `RegisterErrorMessage`

  > **Name collision.** [`@smartsoft001-mobilems/models`](../models/README.md) declares its own
  > `IUser`, `IUserInfo`, `IUserRegister`, `IUserModify` and `ILoginResponse`, and the shapes are
  > **not** identical — e.g. this package's `IUserInfo` is `{ email, userID, avatar?, newsletterAcceptance }`
  > while the models one is `{ username?, email, [key: string]: any }`, and `IUser.refreshToken` is
  > optional here but required there. They are not interchangeable. Use the ones from **this** package
  > in Angular UI code (the components and services are typed against them), and import the models
  > variants only when working with API payloads. Never mix the two in one type position.
- Widgets: `ArticlesWidgetComponentsToken`, `ARTICLES_WIDGET_COMPONENTS_TOKEN`
- Page sections (see [`PageSectionsComponent`](#pagesectionscomponent)):
  `PAGE_SECTION_COMPONENTS_TOKEN`, `PageSectionComponentsToken`, `pageSectionComponent`,
  `missingPageSectionComponents`, `pageSectionLeadLines`,
  `PAGE_SECTION_PLACEHOLDER_TYPE`, `PAGE_SECTION_GRID_CONTAINER_TYPE`, `PAGE_SECTION_HOOK_CLASS`,
  `PAGE_SECTION_SLOT_CLASS`, `PAGE_SECTION_ROUTES_TOKEN`, `PageSectionRoutes`,
  `DEFAULT_PAGE_SECTION_ROUTES`, `resolveSectionTarget`, `ResolvedSectionTarget`,
  `DEFAULT_PAGE_SECTION_DICTIONARY_SOURCES`, `DEFAULT_PAGE_SECTION_DICTIONARY_LIMIT`,
  `PageSectionDictionaryExpander`, `PageSectionDictionaryEntry`, `PageSectionDictionaryEntries`,
  `PageSectionWholeDictionaryTarget`, `isWholeDictionaryTarget`, `wholeDictionaryTypes`,
  `expandDictionaryBlocks`, `toEntriesMap`,
  `normalizePageSections`, `pageSectionAppearance`, `PageSectionAppearanceStyle`,
  `PageSectionBackgroundKind`, `PAGE_SECTION_SPACE_MAX`, `pageSectionFileUrl`, `pageSectionHtml`,
  `pageSectionCtaLabel`, `pageSectionCounterValue`, `PageSectionCounterPipe`,
  `PAGE_SECTION_FALLBACK_LOCALE`, `pageSectionMedia`, `pageSectionMediaUrl`,
  `PageSectionMediaInfo`, `PageSectionMediaKind`, `gridArea`, `PageSectionGridArea`,
  `PAGE_SECTION_GRID_COLUMNS`, the fixtures `TEST_SECTIONS` / `TEST_SECTIONS_PAGE`, and
  `PageRef` (`` number | 'home' | `slug/${string}` ``, the `getPage` argument)
- WCAG: `IWcagConfig`, `WcagContrast`, `WcagText`, `WcagLetterSpacing`, `WcagWordSpacing`,
  `WcagGrayscale`, `WcagChangeType`
- Environment: `environment` (only the base build is exported from the package entry point;
  `environment.prod.ts` is not reachable through the barrel)

Entities (`Config`, `Page`, `PageSection*`, `MsFile`, `IUser`, the `IArticle*` widget interfaces, `MenuItem`, …) come
from [`@smartsoft001-mobilems/models`](../models/README.md).

### Museum API models

API list-item shapes shared by the museum apps: `IObject`, `IImage`, `IDictionary`,
`IDictionaryEntry` (`id: number | null`, `extraData`), `IArticleListItem`, `IAuthorDetails`, `IPartner`,
`ICreateDate`, `ICreatePlace`, `IMaterial`, `ITechnique`, `IType`, `ISeriesTitle`, `IExtraNumber`;
home page: `IHomePage`, `IHomePageSlide`; `PARENT_TITLE_TOKEN` (`WritableSignal<string>`) — the parent page
title (e.g. the article name) for child components, used as the download file-name fallback.

Renamed when moved from the museum libs (the framework already had different types under the old
names): `IDictionaryItem` → `IDictionaryEntry`, `IArticle` → `IArticleListItem`, `IAuthor` → `IAuthorDetails`.

## Runtime environment

```ts
// libs/shared/angular/src/lib/environments/environment.ts
export const environment = createMobilemsEnvironment<{ adobeFontsKitId: string }>({
  adobeFontsKitId: { env: 'ADOBE_FONTS_KIT_ID' },
});

// env-init.ts (server, before the app modules load)
EnvironmentService.initFromProcessEnv(environment);

// app.config.ts
provideMobilemsApp({ environment, /* … */ }); // `version` defaults to environment.version
```

- `IMobilemsEnvironment` — `production` (`!isDevMode()`), `version`, `apiUrl`, `siteUrl`,
  `multimediaUrl`, `useLocalTranslations`.
- `createMobilemsEnvironment<E>(extra?)` — fills the object once from `window.env` (browser) or
  `process.env` (server) and never throws (missing → `''`). Extra keys: `IMobilemsEnvKey<T>` =
  `{ env: string | string[]; parse?(raw) }` (the first non-empty variable wins). `parse` runs in the
  browser too (on the `window.env` value), so it must not touch `process`. Without `window.env`
  (jsdom, a server polyfilling `window`) values come from `process.env`.
  `mobilemsEnvKeys()` lists the core keys (`version` ← `APP_VERSION`, then `VERSION`);
  `readProcessEnv(source)` reads the first non-empty `process.env` variable; `envValue(definition, raw)`
  applies `parse` (or `raw ?? ''`).
- `MOBILEMS_ENVIRONMENT` — the token `provideMobilemsApp({ environment })` provides.
- `EnvironmentService` — `initFromProcessEnv(env)` (static, server) re-reads `process.env`; `init()`
  (call it from an app initializer: `provideAppInitializer(() => inject(EnvironmentService).init())`) passes the values to the browser via `TransferState`, falling back to
  `window.env`, and throws when neither has `apiUrl`. No-op without the token.

## Tailwind (`@smartsoft001-mobilems/angular/tailwind`)

The framework component templates use the app's `smart-` Tailwind classes, but they live in
`node_modules`, which an app's own `content` globs do not scan. Spread `mobilemsContent` into the
app's `tailwind.config.js` so its theme generates them:

```js
const { mobilemsContent } = require('@smartsoft001-mobilems/angular/tailwind');

module.exports = {
  content: ['./apps/web/src/**/*.{html,ts}', './libs/**/*.{html,ts}', ...mobilemsContent],
  // …
};
```

`mobilemsContent` is the glob of the `fesm2022` bundles of every installed `@smartsoft001-mobilems/*`
package. Structural styles that must never depend on it (skip links, the shell's `main` min-height)
are inline in the components.

`mobilemsPreset` is an opt-in Tailwind 3 preset with the settings every portal shares. Nothing in the
framework applies it; add it next to `content`:

```js
const { mobilemsContent, mobilemsPreset } = require('@smartsoft001-mobilems/angular/tailwind');

module.exports = {
  presets: [mobilemsPreset],
  content: ['./apps/web/src/**/*.{html,ts}', ...mobilemsContent],
  // theme: brand tokens stay per museum
};
```

`IMobilemsTailwindPreset` is the type of `mobilemsPreset` (`prefix`, `darkMode`,
`future.hoverOnlyWhenSupported`); import it to type a spread or override of the preset.

- `prefix: 'smart-'` - the framework templates use `smart-` classes.
- `darkMode: ['class', '[class~="contrast-high"]']` - the high-contrast toggle drives dark variants.
- `future.hoverOnlyWhenSupported: true` - `hover:` applies only with a pointer, so touch screens get no
  sticky hover (MOB-1843, MOB-1894).

It has no `content` and no `theme`. Tailwind 3 config only: under Tailwind 4, `hover:` is already
pointer-only and the prefix is set in CSS.

## CLI (`bin`)

The package ships two guard scripts. They are tools: nothing runs them for you, so wire them into the
portal's CI yourself. Run both from the portal root.

### `mobilems-check-translations`

```bash
npx mobilems-check-translations [--reference <path>] [--groups "A B C"]
```

Checks the translations of the whole portal: every key used in code exists in both `pl` and `en`, `pl`
and `en` define the same keys, and (with `--reference`) the groups are complete against a reference
project. Exit `0` = clean, `1` = findings.

### `mobilems-check-portal`

```bash
npx mobilems-check-portal [--root <dir>] [--only <rule,...>] [--skip <rule,...>]
```

Static guard for the bugs that keep coming back in portals (MOB-1889..1895). It scans `libs/` and
`apps/web/src/` (`.html` and `.ts`, inline templates included) plus `apps/web/public/translations.json`,
and skips `*.spec.ts`, `*.stories.ts`, `__mocks__`, `node_modules`, `dist`, `.nx`, `coverage` and `e2e`.
It prints one `  FAIL: <file>:<line> [<rule>] <message>` line per finding and a summary.

| Rule                       | Flags                                                                                                           |
| -------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `object-cover`             | `<img>` with `object-cover` under an object, collection, gallery or slider path: it crops museum photos         |
| `innerhtml-external-links` | a `[innerHTML]` element without `smartExternalLink(s)` on the same element or `smartExternalLinks` on an ancestor in the same template: its links skip the "leaving the site" modal (MOB-1891) |
| `natural-size-binding`     | `[width]`/`[height]`/`[attr.width]`/`[attr.height]` bound to `naturalWidth`/`naturalHeight`: layout shift (CLS) |
| `template-emoji`           | an emoji, arrow or cross glyph in a template (HTML comments are ignored): use an icon component                                             |
| `contact-placeholder`      | `Przykładowa`, `Przykladowa` or `00 000 00 00` left from the template                                            |
| `static-online-3d-viewer`  | a static `import` of `online-3d-viewer`: it lands in the main bundle; use `createLazyLoader`                     |
| `masonry-stub`             | an anonymous class next to `provide: Masonry`: use `provideBrowserMasonry()`                                     |

`innerhtml-external-links` is skipped (the summary prints `SKIP: innerhtml-external-links (AppComponent
handles content links)`) only when the shell is `<smart-mobilems-app>`, the app opts in with
`contentLinks: true` or an options object, and nothing sets `contentLinks: false`. `contentLinks` is
opt-in, so leaving it unset keeps the rule on. `contentLinks: { externalLinks: false }` and a
commented-out `contentLinks` do not count as handled.

The rule looks at the same element and at ancestors in the same template only. It does not follow a
`smartExternalLinks` set on a parent component's host in another file; accept such a finding with
`check-portal-ignore innerhtml-external-links`.

**Adopting it in an existing portal.** An existing portal usually has many `[innerHTML]` findings
(Podlasie 35, sztuki-2 18, before it opts into `contentLinks`). Start with
`npx mobilems-check-portal --skip innerhtml-external-links` (or `check-portal-ignore` comments on the
deliberate ones) so the other rules gate CI from day one. Once the portal opts into
`contentLinks: true`, drop the `--skip`: the rule then skips itself.

To accept a finding on purpose, put a comment containing `check-portal-ignore <rule>` (optionally
followed by `: reason`) on the same line or the line directly above. It silences that rule only:

```html
<!-- check-portal-ignore object-cover: decorative crop -->
<img class="smart-object-cover" src="..." alt="" />
```

```ts
// check-portal-ignore masonry-stub: deliberate SSR Masonry fallback
```

Use the same comment for a deliberate SSR `Masonry` fallback that really needs an anonymous class.

Exit codes: `0` clean, `1` findings, `2` unknown rule id. CI snippet:

```yaml
- run: npx mobilems-check-portal
```

## Module & config

- `SharedModule.forRoot(config)` — root: registers the components. It no longer loads the global
  `Config`; that is `provideMobilemsApp()`'s job (a dev-mode warning reminds you when it is
  missing). It exports no directives — import those standalone (see [Directives](#directives)).
- `SharedModule.forFeature(config)` / `SharedModule` — feature libraries.
- `SharedConfig` — `apiUrl`, `multimediaUrl`, `mainLogoPath`, `styleVariables`.
- `provideInheritedSharedConfig(apiUrl)` — factory provider for `SharedConfig` that keeps the parent's
  values and overrides only `apiUrl`. Feature `forFeature` modules (`ObjectsModule`, `ObjectsSharedModule`,
  `ArticlesModule`, `ArticlesSharedModule`, `PublicCollectionsModule`, `PublicCollectionsSharedModule`)
  use it, so they inherit `multimediaUrl`/`mainLogoPath` from the root `SharedConfig` (FRA-416).

## App setup (`provideMobilemsCore`, `provideMobilemsApp`)

Two calls in `app.config.ts` replace the provider boilerplate and the root-component plumbing every
museum app used to copy:

```typescript
import { provideMobilemsApp, provideMobilemsCore } from '@smartsoft001-mobilems/angular';

export const appConfig: ApplicationConfig = {
  providers: [
    provideMobilemsCore({
      routes: appRoutes,
      shared: { apiUrl: environment.apiUrl, multimediaUrl: environment.multimediaUrl, mainLogoPath: 'logo.png', styleVariables: {} },
      // interceptors: [JwtInterceptor],          // museum class interceptors, before the dedupe one
      // routerFeatures: [withViewTransitions()], // after the built-in in-memory scrolling
    }),
    provideMobilemsApp({
      version: environment.version,
      languages: { available: ['pl', 'en'], default: 'pl' },
      skipLinks: {
        home: [{ targetId: 'main-new-objects', translationKey: 'HOME.accessibility.skipToNewObjects' }],
        subpage: [{ targetId: 'main-content', translationKey: 'HOME.accessibility.skipToContent' }],
      },
      translations: {
        url: environment.production && !environment.useLocalTranslations
          ? environment.apiUrl + 'setting/theme'
          : '/api/translations',
      },
      seo: {
        siteNameFallback: { pl: 'Nazwa Muzeum', en: 'Museum Name' },
        defaultOgImage: { url: '/gfx/og-default.jpg', width: 1200, height: 630 },
        organization: { name: 'Muzeum …', url: 'https://muzeum.pl/' },
        siteUrl: () => environment.siteUrl,
      },
      // homePage: { slug: 'strona-glowna', path: '/strona-glowna' },  // defaults
      // homePaths: ['/', '/strona-glowna'],                            // skip-links home detection
      // app: { logo: 'logo.png' },                                     // Partial<IAppOptions> over the shell defaults
      // contentLinks: true,                                            // opt-in: shell handles external and #id links
    }),
    provideEnvironmentInitializer(() => inject(EnvironmentService).init()),   // museum runtime env
    provideStoreDevtools({ maxAge: 25, logOnly: !isDevMode() }),              // optional, app dependency
    { provide: SEARCH_CONFIG_TOKEN, useValue: { apiUrl: environment.apiUrl, searchMap: … } },
  ],
};
```

### `provideMobilemsCore(options: IMobilemsCoreOptions)`

`routes`, `routerFeatures?`, `shared: SharedConfig`, `interceptors?: Type<HttpInterceptor>[]`.
Registers: `provideClientHydration(withEventReplay(), withI18nSupport(), withNoIncrementalHydration())`,
`provideBrowserGlobalErrorListeners()`, `provideZonelessChangeDetection()`, `provideRouter(routes,
withInMemoryScrolling({ scrollPositionRestoration: 'top', anchorScrolling: 'enabled' }), …routerFeatures)`,
`provideHttpClient(withFetch(), withInterceptorsFromDi())` with the [interceptors](#interceptors)
(museum `interceptors` go before the dedupe one), `provideStore()` (state/action immutability runtime checks off) / `provideEffects()`, `MasonryModule.forRoot()`, `TranslateModule.forRoot()`,
`NgrxSharedModule`, `SharedModule.forRoot(shared)`, `StyleService`, `AppService` → `NoOpAppService`
(its `initTitle()` is a no-op so `SeoService.updateTitle()` wins) and an `ErrorService` that logs to
`console.error`. NgRx devtools are not included (not a framework dependency).

### `provideMobilemsApp(options: IMobilemsAppOptions)`

- `MOBILEMS_APP_OPTIONS` (`version`, `languages: ILanguagesOptions`, `skipLinks: ISkipLinksOptions` of
  `ISkipLink`, `homePaths?`, `app?`, `translations?: ITranslationsOptions`, `seo?: IMobilemsSeoOptions`,
  `homePage?: { slug?, path? }`, `contentLinks?: IContentLinksOptions | boolean`).
- `contentLinks` (opt-in, default off) switches the shell's delegated link handling — the external-link
  modal and in-page `#id` anchors over all app content, see
  [Content links on the app shell](#directives). `provideMobilemsApp({ …, contentLinks: true })` turns
  both on; `{ …, contentLinks: { inPageAnchors: false } }` keeps only the external links. Leaving it out
  (or `false`) keeps the behaviour from before this release.
- an app initialiser: `TranslationService.init(default, available)`, then — when `translations` is set —
  `loadTranslations(http, translate, options, languages)` (GET `url`, `data.translations.<lang>` →
  `setTranslation` for every available language present; timeout 5 s; a missing/malformed payload only
  warns), then `ConfigsFacade.init()` (started, not awaited — a failing config request is logged, never
  blocks bootstrap).
- `MOBILEMS_SEO_OPTIONS` when `seo` is set (merged with `languages`), consumed by `MuseumSeoService`.
- an environment initialiser: the `app-version` meta tag and, in the browser, focus on `#skip-links`
  after every `NavigationEnd` (`setupRouteFocus(router, document, destroyRef)`). Navigations that must
  keep focus (tabs, pagination) pass `state: KEEP_FOCUS_STATE`.

`validateMobilemsAppOptions(options)` throws at construction for an empty `languages.available`, a
`languages.default` outside it, a missing `skipLinks` list, or an empty `version`. `NAV_SKIP_LINK` /
`FOOTER_SKIP_LINK` are the fixed outer links, `DEFAULT_HOME_PATHS` the default home detection.

**Skip-link targets are a contract with the museum templates.** The framework renders only
`<main id="main-content" tabindex="-1">`; the app's header must carry `id="main-nav" tabindex="-1"` on
its main navigation and the footer `id="main-footer" tabindex="-1"`, and every `targetId` in
`skipLinks.home` / `skipLinks.subpage` must exist on the page it is listed for (the links no-op on a
missing id, so a wrong id is a silent accessibility regression). `buildDefaultAppOptions(logo, overrides?)`
is what the shell uses when no `options` input is bound.

The resulting museum root component:

```typescript
@Component({
  imports: [AppComponent, HeaderComponent, FooterComponent],
  selector: 'app-root',
  template: `
    <smart-mobilems-app>
      <header tabindex="-1"><app-header /></header>
      <footer><app-footer /></footer>
    </smart-mobilems-app>
  `,
})
export class App {}
```

### Upgrading from 2.106 without adopting the new providers

What changes for an app that only bumps the package:

- `SharedModule.forRoot()` no longer loads the global `Config` (dev-mode warning only) — adopt
  `provideMobilemsApp()` or call `ConfigsFacade.init()` yourself.
- `TranslationService.init()` resolves `?lang=` → stored preference (localStorage, SSR cookie) →
  default and no longer falls back to the browser language; `setLanguage()` persists to
  `SELECTED_LANGUAGE` (localStorage + cookie) instead of `TRANSLATION_CONFIG` (read once as a fallback).
- `ConfigsFacade.init()` shares one in-flight promise per injector.
- `AppComponent` (`smart-mobilems-app`) renders `<nav id="skip-links">` and `<main id="main-content">`
  itself and no longer requires the `options` input — remove an app-level `app-skip-links`, otherwise
  the id is duplicated and `setupRouteFocus` focuses the wrong one.
- `SearchBaseComponent` has a new API (`tabDefinitions`), the abstract `HomeComponent` became
  `HomeBaseComponent`, and `provideMobilemsCore()` already registers `TranslateModule.forRoot()` —
  drop a second one from the app.

## Static page, search page, resolvers

### Static page (`PageStaticComponent`)

Extend it for `/strona/:id`, `/kontakt`, … and keep the template in the museum app. Data comes from a
route resolver when there is one, otherwise it is fetched by the `id` param:

- `pageResolver` — `resolve: { pageData: pageResolver }` on `strona/:id`.
- `createSlugPageResolver(slug, { emptyTitleKey })` — a fixed-address page backed by the CMS page with
  that slug: the page, an empty page titled with the translated key on 404 / no data, or `PAGE_LOAD_FAILED`
  (frozen sentinel) for every other error. Use `runGuardsAndResolvers: 'always'` so `retry()` re-runs it.
  `PageResolved` = `Page | typeof PAGE_LOAD_FAILED | null`.

Members: `data` / `page` (signal), `loading`, `loadFailed` (resolver returned `PAGE_LOAD_FAILED`),
`retry()` (`navigateByUrl(url, { onSameUrlNavigation: 'reload' })`), `pageRoute` (`route.data.pageRoute`
for breadcrumbs), `contentHtml` (`SafeHtml | null`; CMS `<h1>` demoted to `<h2>` so the page keeps one
`h1`; `demoteContentHeading(content)` is public), `sectionsHaveH1` (`rendersPageHeading(sections,
PAGE_SECTION_COMPONENTS_TOKEN)` — a mapped heading variant among the sections, also inside
`grid_container`), `loadData(id)`, `setTitle()`.

`PageHeadingOwner` (provide it in the page component) hands the `h1` to the first section variant that
`claim()`s it; `PAGE_HEADING_VARIANT` (`banner/archive`) is the default heading variant of
`rendersPageHeading(sections, components, variant?)`.

### Search page (`SearchBaseComponent<SEARCH_PATH>`)

```typescript
@Component({ selector: 'app-search-page', imports: [RouterModule, TabsComponent, TranslatePipe], templateUrl: '…' })
export class SearchComponent extends SearchBaseComponent<'obiekty' | 'artykuly' | 'kolekcje'> {
  protected override readonly tabDefinitions: ReadonlyArray<ISearchTabDefinition<'obiekty' | 'artykuly' | 'kolekcje'>> = [
    { id: 'obiekty', labelKey: 'SEARCH.tabs.objects', count: (d) => d.objects },
    { id: 'artykuly', labelKey: 'SEARCH.tabs.articles', count: (d) => d.articles },
    { id: 'kolekcje', labelKey: 'SEARCH.tabs.collections', count: (d) => d.publicCollections },
  ];
}
```

Signals: `text`, `data` (`SearchCounts` — the module counts, every key optional), `tabs` (`ITab[]` with
`count`, always every definition in order), `activeTab`. Behaviour: phrase from `/wyszukaj/:text`
(distinct; empty → `homeRoute`), `SearchService.setCurrentSearchText` before the request, `switchMap`
race protection, default tab = deep-linked segment (only when the url still carries the phrase) → first
tab with results → first definition, back/forward keeps `activeTab` in step with the url, tab changes
navigate with `KEEP_FOCUS_STATE`, SEO re-applied on phrase/tab change via `MuseumSeoService`
(`seoKeys: ISearchSeoKeys` = `PAGE_TITLES.search`, `SEARCH.ogDescription`, `MODEL.mainTitle`;
`applySeo(text, tab)` is overridable), `SearchService.setEnabled` on init/destroy. Overridable:
`searchRoute` (`/wyszukaj`), `homeRoute` (`/strona-glowna`).

### Tools

`decodeHtmlEntities(text)` — named (`HTML_NAMED_ENTITIES`), decimal and hex entities to characters,
identical on server and browser; `normalizeMetaText(text)` — decoded and whitespace-collapsed text for
meta tags.

| Tool | Purpose |
| --- | --- |
| `stripHtml(html)` | Tags removed (no entity decoding — see `toPlainText`), `''` for empty input |
| `normalizeUrl(url)` | `https://` prepended unless the URL starts with `http` or `/`; `''` for empty input |
| `isHomePath(url, homePaths = DEFAULT_HOME_PATHS, options?: IHomePathOptions)` | Whether `url` is a home path. Lenient (default): query (`?…`) and fragment (`#…`) ignored, `''` is `/`, one trailing slash dropped (except for `/`), home paths normalised the same way. `{ strict: true }` - Podlasie's header rule, the `HeaderBaseComponent` default: the url equals a home path or continues with `?` (not for `/`), so `/strona-glowna?x=1` is home but `/strona-glowna#main`, `/?lang=en`, `/strona-glowna/` and `''` are not. In both modes sub-pages and prefixes (`/strona-glowna-2`, `/strona-glowna/x`) are not home |
| `classifyLink(href, options?: IClassifyLinkOptions)` | `LinkClassification`: `internal` (`path` = pathname + search + hash), `external` (`href`) or `ignore` (non-http(s) such as `mailto:`/`tel:`, `#…`, empty or invalid). Same origin or `siteUrl` (option, else `window.env.siteUrl`, on the server `SITE_URL`; `www.` ignored) is internal. Options: `base`, `origin`, `siteUrl` |
| `isInternalLink(url, currentOrigin?)` | `classifyLink(url, { origin }).kind === 'internal'` |
| `formatNamedEntries(entries)` / `namedEntryParts(entries)` | `name [role] (comment)` text / parts (`INamedEntryParts`) from API entries (`INamedEntrySource`, `INamedEntry`) |
| `normalizeSearchText(text)` | Lower-case, diacritics removed (`ł` → `l`) — for client-side matching |
| `translationChanges(translate)` | `Signal<number>` that ticks on language / translation changes |
| `newTabText(translate)` / `newTabTextSignal(translate)` | "otwiera się w nowej karcie" from `NEW_TAB_KEY` (`HOME.sections.opensInNewTab`), else `NEW_TAB_FALLBACK.pl` / `.en` by language |
| `pageToOffset(page, limit)` / `offsetToPage(offset, limit)` | 1-based page ⇄ CRUD `offset` (page N → `N × limit`, page 1 → 0) |
| `normalizeCycleId(id)` | Number or numeric string → number, otherwise `null` |
| `ElementIdSequence` | Root service; `next()` returns 0, 1, 2… per injector, so ids for `aria-*` / `<label for>` match between SSR and the browser (MOB-1850) |
| `photoFileName(title, extension, index?, total?)` / `urlExtension(url)` | Download name of an object photo from its title (HTML and forbidden characters stripped, max 120 chars, `(N)` only when several, fallback `zdjecie.jpg`) / extension from the URL path (no query or fragment) |
| `objectCardMeta(item)` / `objectCardExhibition(item)` / `exhibitionText(info)` / `objectCardPlace(item)` / `SERIES_TITLES_FILTER` / `IObjectCardSource` / `IObjectCardArcheologicalDetails` / `ObjectCardExhibitionInformation` | Object card fields from a `search/Object` item (MOB-1588): `{ authors, dates }` as `INamedEntryParts[]` with the role dropped; the "on display" eye `{ text }` only for `isExhibited === true` (`exhibitionText` reads a string or an entry `name`, blank gives `null`); the place `{ archeological, entries }`: archaeological objects use `archeologicalDetails.town`, then `name` (MOB-1820, API 12037), others `createPlaces`; `SERIES_TITLES_FILTER` is `'cycles'` (MOB-1856) |
| `widgetDomId(type, item)` | Stable SSR-safe id of widget elements: `widget-<type>-<gallery id cleaned of [^\w-] or x>-<position ?? 0>` (no module counter, review MOB-1805) |
| `cleanWidgetText(text)` | Article text widget HTML: decodes `\uXXXX` sequences and drops empty CKEditor paragraphs (MOB-1805); `''` for missing text |
| `formatFileSize(bytes)` / `safeDecode(value)` | File size in Polish units (`'512 B'`, `'820 kB'`, `'1,2 MB'`; `''` for missing, non-finite or <= 0) / `decodeURIComponent` that returns the raw value on a `URIError` |
| `catalogEntryFilterParams(filter, id, name)` | `{ filter }` for the `?filter=` of a list link: with an `id` (anything but `undefined`, `null`, `''`, so `0` counts) a dictionary item `{ id, value: name \|\| String(id) }`; without one the phrase `searchText` (the API filters dictionaries by `id` only) |
| `widgetImageUrl(fileUrlService, file, mode, placeholder)` | `FileUrlService.get` that keeps `.png` in `big` mode; use it when the CDN stores big PNG widget images only under the original extension (no `.jpg` twin); query and fragment preserved |
| `WIDGET_IMAGE_PLACEHOLDER` | `/gfx/no-image.png` - default placeholder of `WidgetImageBaseComponent` and `WidgetGalleryImageBaseComponent` (`widgetImagePlaceholder` / `widgetGalleryImagePlaceholder`) |
| `overflowingTags(list, tags, singleRow)` / `MORE_PILL_ESTIMATE` | Browser only (call after render, reads layout): set of tags that do not fit one row next to the "+N" pill (MOB-1808); `MORE_PILL_ESTIMATE` (44 px) is used until "+N" is rendered |
| `createSafeTimeouts(destroyRef?)` / `ISafeTimeouts` | `later(callback, delay)` timeouts cancelled on destroy (later calls become no-ops, MOB-1805); `clear()` cancels pending ones without destroying; needs an injection context unless `destroyRef` is passed |
| `resolveMenuItemTarget(item, slug?, options?: IMenuItemTargetOptions)` / `isNavigableMenuItem(item)` / `MenuItemTarget` / `MENU_ITEM_STATIC_PAGE_ROUTE` | Where a CMS menu entry leads: `MenuItemTarget` is `route` (`commands`, optional `queryParams`, `fragment`), `external` (`href`), `native` (`mailto:`, `tel:`, `#fragment`) or `null` (empty, invalid, `javascript:`, `dynamic` containers). A static page is `[staticPageRoute, page.id, slug?]` (`options.staticPageRoute`, default `/strona`); links go through `classifyLink`. Site address: `window.env.siteUrl` wins over `options.siteUrl`. `isNavigableMenuItem` has exactly one parameter, so `items.filter(isNavigableMenuItem)` is safe. It always uses the default resolver, never a subclass `menuItemResolveTarget`; that is fine because only null versus non-null matters |
| `createCycleTagSearch(options?: ICycleTagSearchOptions)` / `ICycleTagSearch` | Tag search of a catalog tag bar (MOB-1815; injection context, injects `DataService`): `query` (writable phrase) and `tags` (`Signal<IDictionaryEntry[]>`, `[]` until the first answer). An empty phrase calls `DataService.loadCycleTags()` at once, a phrase calls `loadCycleTags(phrase)` after `debounceMs` (default `0`: at once); a changed phrase drops the pending request. Merge the result with the selection via `mergeSelectedTags` |
| `themeTagKey(tag)` / `themeTagsLayout(items, isSelected, limit, expanded)` / `THEME_TAGS_VISIBLE_LIMIT` / `ThemeTag` / `ThemeTagSource` / `IThemeTagsLayout` | Theme tag bar rules: key `${source ?? 'cycles'}:${id}` (`'7'` and `7` match), layout with selected first, key duplicates counted once, `limit` tags collapsed (every selected one stays visible) or all expanded -> `{ tags, visibleCount }` |
| `injectServerResponseInit()` / `appendPreloadLinks(responseInit, urls, placeholder?)` | SSR image preload: the optional `RESPONSE_INIT` on the server (`null` in the browser; injection context) / appends `Link: <url>; rel=preload; as=image` per url in order, skipping empty urls and the placeholder (`/gfx/no-image.png`); no-op when nothing is left, creates `headers` when missing |
| `footerSocialLinks(sources, labelKeyPrefix = FOOTER_SOCIAL_LABEL_KEY_PREFIX)` / `IFooterSocialLink<TId>` / `IFooterSocialSource<TId>` / `FooterSocialId` / `FOOTER_SOCIAL_LABEL_KEY_PREFIX` | Footer (and mobile menu) social links. They are static or runtime-env data, not CMS data (the CMS config has none). Source order kept, `url` trimmed, a blank, `null` or missing `url` drops the profile (no address, no icon), `labelKey` = the given one or the prefix (`HOME.footer.social.`) + `id`, `iconPath` copied when present; returns a frozen array of frozen entries. `TId` defaults to `FooterSocialId` (`facebook`, `x`, `tiktok`, `instagram`, `youtube`, `linkedin`) |
| `createLazyLoader(lazyLoaderImport)` / `ILazyLoader` | Generic single-flight lazy loader for a dynamic import: concurrent `load()` calls share one import, the module is cached (`loaded` is `null` until then), a rejection reaches every waiting caller and is not cached, so the next `load()` retries (chunk-load error after a deploy). The framework does not import the library; the portal passes its own, e.g. `export const loadOnlineViewer = createLazyLoader(() => import('online-3d-viewer'));` (MOB-1850, MOB-1895). A stale-call guard (an init token) stays in the component |

```ts
private readonly ids = inject(ElementIdSequence);
private readonly timeouts = createSafeTimeouts(); // injection context
readonly labelId = `filter-label-${this.ids.next()}`;
// ...
this.timeouts.later(() => this.focusInput(), 100); // no-op after destroy
```

## Catalog lists (`createCatalog`)

The list behaviour of a catalog page (articles, later objects and collections) — taken from Muzeum
Podlasia's articles list. Call in an injection context (a constructor or a field); the page keeps its
template. `ArticlesCatalogBaseComponent` (articles shell) wraps it for articles.

```ts
readonly catalog = createCatalog({
  facade: this.facade, // ICatalogFacade: filter, loading, error, totalCount, read
  defaults: { paginationMode: PaginationMode.singlePage, offset: 0, limit: 12, sortBy: 'title', sortDesc: false },
  persistKey: 'MUSEUM_ARTICLES_FILTER',
  listPath: '/artykuly',
  searchTab: 'artykuly',
  listModeKey: 'MUSEUM_ARTICLES_LIST_MODE_KEY',
});
```

`ICatalogOptions`:

| Option | Meaning |
| --- | --- |
| `defaults` | Filter defaults; `defaults.query` is the base query (e.g. `template`) kept by every read and by `clearAll` |
| `persistKey` | `FilterPersistenceService` key |
| `listPath` / `searchTab` | The list route; the `/wyszukaj/:text/<searchTab>` segment for a new phrase |
| `ssrRead` (`CatalogSsrRead`) | `route` (default) — read in SSR only when the route carries the filter (search tab, `?filter=`), the persisted filter lives in the browser; `always` — also the defaults |
| `searchNavigatesToList` | Default `true`: in a search tab a filter change opens `listPath` with the whole filter (`catalogListQueryParams`); `false` reads in place |
| `restoreSaved(saved)` | Cleans a persisted filter (dropped keys) before it is restored |
| `listModeKey` | `StorageService` key of the grid/list mode (restored after hydration) |
| `readGuard` | Default `true`: `createCrudReadGuard` guards the shared NgRx CRUD slice. `false` — for a facade that is not an NgRx CRUD slice: no store listener (a foreign `CrudConfig` in the injector is ignored), the response is always fresh |
| `mobileListModeBelow` | Off by default. Below this `innerWidth` (browser only) the first render and every later read force `mobileListMode` instead of restoring `listModeKey` (at or above it they restore the stored mode), and `setListMode` is ignored |
| `mobileListMode` | The mode forced below `mobileListModeBelow`; default `ListMode.masonryGrid`. Read only with `mobileListModeBelow` |
| `layoutQueryParams` | Off by default. Query params that only switch the layout (e.g. `['widok']`): the read ignores them and a change to them alone does not re-read |

First read: `?filter=` (+ `?sort=`, `?limit=`), else the persisted filter (not in a search context), else
the defaults; the phrase comes from the parent `:text`, `?search=` or `SearchService`. Every later change
is persisted, except in a search context.

`ICatalog`: signals `filter`, `isLoading` (also while the shared CRUD slice holds a response to another
filter), `hasError`, `totalCount`, `sortKey` (`title-desc`), `selectedPage`, `barPhrase`, `searchEnabled`,
`isSearchContext`, `routeList`, `isBrowser`, `listMode`; methods `update(patch)` (back to page 1),
`setSort(ICatalogSort)`, `setSortKey('title-asc' | 'random')`, `setLimit`, `setPage`, `search(phrase)`,
`retry`, `clearAll`, `setListMode`, `openInList(filter)` (opens `listPath` with the whole filter,
`catalogListQueryParams`), `queryItems(key)`, `toggleQueryItem(key, entry)` (`'7'` = `7`, an
empty key is dropped), `setQueryItem(key, value, type?)`, `removeQueryKey(key)`,
`setRange(key, { from, to }, format?)`. `yearRangeValue(year, 'from' | 'to')` formats a year bound for
the API (`1` → `0001-01-01`), `yearRangeLabel(value)` shows it back (`0001-01-01` → `1`).

Building blocks (also usable alone):

| Export | Purpose |
| --- | --- |
| `parseCatalogFilterParam(raw)` → `IParsedCatalogFilterParam` | `?filter=` JSON (`ICatalogFilterParamItem[]`: `{ name, data, type? }`, dictionary data as `{ id, value }`); invalid items are skipped, broken JSON gives `null`; `SEARCH_TEXT_PARAM_NAME` item carries the phrase |
| `serializeCatalogFilter(filter)` | The inverse; `null` for an empty filter |
| `catalogListQueryParams(filter)` → `ICatalogListQueryParams` | `{ filter, sort, limit }` of the list url (`sort=random` for an empty `sortBy`) |
| `parseCatalogListParams(params)` → `ICatalogListParams` | `?sort=` / `?limit=` back to `sortBy`, `sortDesc`, `limit` |
| `createCatalogLoadMore(ICatalogLoadMoreSource)` → `ICatalogLoadMore` | Mobile "load more": `items` (previous pages + current), `hasMore`, `isAppending`, `loadMore()`; `onAppended(added, firstIndex)` for the screen-reader status and focus |
| `createCrudReadGuard(ICrudReadGuardFacade)` → `ICrudReadGuard` | `fresh` — the store's list belongs to the current filter (two routes on one CRUD slice); re-reads when a stale answer overwrote a fresh one. `crudFilterKey(filter)` — order-independent key |
| `isDictionaryEntry`, `dictionaryEntries(value)`, `dictionaryEntryKey(id)`, `dictionaryFilterItems(value)` → `IDictionaryFilterItem[]`, `mergeSelectedTags(selected, tags)`, `toggleDictionaryFilterItem(value, entry)` | Dictionary values of a filter (ids normalised, duplicates dropped) |

`provideBrowserMasonry()` — the `Masonry` provider for `MasonryGridComponent`: `window.Masonry` in the
browser, `null` in SSR (the grid then skips the layout).

## Bootstrap entry points

Two secondary entry points replace the boilerplate of `main.ts` / `main.server.ts`. They are
split on purpose: `masonry-layout` touches `window` at import time and would crash SSR, so the
server entry never imports it.

- `bootstrapApplication(rootComponent, options?)` from `@smartsoft001-mobilems/angular/bootstrap`
  — browser only. Registers `masonry-layout` on `window.Masonry` (consumed by the `Masonry` token
  factories of `@thisissoon/angular-masonry`) and returns Angular's `Promise<ApplicationRef>`.
  Requires `masonry-layout` (peer dependency) and `allowedCommonJsDependencies: ["masonry-layout"]`
  in the app's build options.
- `bootstrapServerApplication(rootComponent, options)` from
  `@smartsoft001-mobilems/angular/bootstrap/server` — returns the `ServerBootstrap` factory
  (`(context: BootstrapContext) => Promise<ApplicationRef>`) that `main.server.ts` exports as
  default. Anything that must run before the app modules are evaluated (environment init from
  `process.env`) still has to be imported first in `main.server.ts`.

```typescript
// main.ts
import { bootstrapApplication } from '@smartsoft001-mobilems/angular/bootstrap';
bootstrapApplication(App, appConfig).catch((err) => console.error(err));

// main.server.ts
import './env-init';
import { bootstrapServerApplication } from '@smartsoft001-mobilems/angular/bootstrap/server';
export default bootstrapServerApplication(App, config);
```

## SSR server (`ssr`)

`@smartsoft001-mobilems/angular/ssr` (Node only) replaces the hand-written Express `server.ts`.
Peers: `@angular/ssr`, `express` (4 or 5), `dotenv`, `compression`.

- `createMobilemsServer(options)` — assembles dotenv, the SSRF allow-list (hosts of `SITE_URL` /
  `MULTIMEDIA_URL` / `API_URL` + `localhost` outside production), `GET /env.js`,
  `GET /api/translations`, `GET /robots.txt`, `GET /sitemap.xml`, your `configure(app)` routes,
  static files and the Angular request handler; listens when the module is the entry point. Returns
  `{ app, angularApp, reqHandler, browserDistFolder }` — export `reqHandler` from `server.ts`.
- `MobilemsServerOptions` — `moduleUrl` (`import.meta.url`), `sitemap` (`SitemapOptions`:
  `routes: SitemapRoute[]`, `languages`, `defaultLanguage`, `langQueryParam`), `robots`
  (`RobotsOptions`: `disallow`; `false` disables), `env` (`EnvMap`: extra `window.env` keys →
  env var name, list of names (first set wins) or resolver, see `EnvValueSource`), `translations` (`TranslationsOptions`: candidate
  `paths`; `false` disables), `allowedHosts`, `allowedHostsEnvVars`, `trustProxyHeaders`
  (default `DEFAULT_TRUST_PROXY_HEADERS`), `dotenv`, `compression` (`ICompressionOptions`: `threshold`, `level`, `filter`; default on, first
  middleware; `false` disables), `configure`, `autoListen`, `port`.
  `SitemapChangefreq` lists the accepted `changefreq` values; `MobilemsServer` is the return type.
  Apps that already add `compression()` in `configure` can drop it; leaving it is harmless (a
  response is encoded once). An ingress that compresses too sees `Content-Encoding` and leaves the
  response alone. Existing portals add `compression` to their dependencies when bumping to this release (it is a peer dependency; `compression: false` keeps the old server).
- Building blocks, for a custom server: `buildAllowedHosts` (`BuildAllowedHostsOptions`,
  `DEFAULT_ALLOWED_HOSTS_ENV_VARS`), `createEnvScriptHandler` / `resolveEnvValues` /
  `renderEnvScript` (`DEFAULT_ENV_MAP` = `apiUrl`, `siteUrl`, `multimediaUrl`, `version`
  (`APP_VERSION`, else `VERSION` — the museum Dockerfiles set `VERSION`), `useLocalTranslations`;
  values are JSON-encoded), `createSitemapHandler` / `buildSitemapXml` /
  `localizedUrl` (`DEFAULT_SITEMAP_LANGUAGES`, `DEFAULT_SITEMAP_LANGUAGE`), `createRobotsHandler` /
  `buildRobotsTxt` (`BuildRobotsTxtOptions`), `createTranslationsHandler` /
  `defaultTranslationPaths`, `resolveSiteUrl` / `withProtocol` / `hostnameOf` (`SiteUrlRequest`).

```typescript
// server.ts
import { createMobilemsServer } from '@smartsoft001-mobilems/angular/ssr';

export const { reqHandler } = createMobilemsServer({
  moduleUrl: import.meta.url,
  sitemap: {
    routes: [
      { path: '/strona-glowna', changefreq: 'daily', priority: 1 },
      { path: '/obiekty', changefreq: 'daily', priority: 0.9 },
    ],
  },
  robots: { disallow: ['/article-preview', '/wyszukaj'] },
  env: { gtmId: 'GTM_ID' },
});
```

## Translations

`setTranslationsAndLang(translateService)` seeds the bundled PL strings shipped with the package
(`TRANSLATE_DATA_PL`, typed by `ITranslateData`) into an `ngx-translate` `TranslateService` and sets
the active language.
