@acropole/skills 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +180 -2
  2. package/agents/revisor-deploy.md +73 -0
  3. package/agents/revisor-documentacao.md +78 -0
  4. package/agents/revisor-orfeu.md +80 -0
  5. package/agents/revisor-trismegisto.md +81 -0
  6. package/bin/install.js +252 -0
  7. package/package.json +15 -4
  8. package/skills/acropole/SKILL.md +75 -0
  9. package/skills/acropole/references/fluxos/doctor.md +55 -0
  10. package/skills/acropole/references/fluxos/endpoint-novo.md +22 -0
  11. package/skills/acropole/references/fluxos/revisar.md +56 -0
  12. package/skills/acropole/references/fluxos/tela-nova.md +27 -0
  13. package/skills/acropole/scripts/doctor.mjs +439 -0
  14. package/skills/angular/SKILL.md +152 -0
  15. package/skills/angular/references/armadilhas.md +95 -0
  16. package/skills/angular/references/dados.md +251 -0
  17. package/skills/angular/references/estrutura.md +260 -0
  18. package/skills/angular/references/features.md +219 -0
  19. package/skills/angular/references/testes-build.md +230 -0
  20. package/skills/angular/scripts/checar.mjs +182 -0
  21. package/skills/angular/scripts/nucleo.mjs +227 -0
  22. package/skills/apollo/SKILL.md +222 -0
  23. package/skills/apollo/references/armadilhas.md +95 -0
  24. package/skills/apollo/references/envelope-erros.md +120 -0
  25. package/skills/apollo/references/estrutura-bootstrap.md +299 -0
  26. package/skills/apollo/references/schema-resolvers.md +183 -0
  27. package/skills/apollo/references/subscriptions.md +224 -0
  28. package/skills/apollo/references/testes-build.md +180 -0
  29. package/skills/apollo/scripts/checar.mjs +160 -0
  30. package/skills/apollo/scripts/nucleo.mjs +227 -0
  31. package/skills/docker/SKILL.md +102 -0
  32. package/skills/docker/references/modelos.md +251 -0
  33. package/skills/docker/references/porques.md +282 -0
  34. package/skills/documentacao/SKILL.md +146 -0
  35. package/skills/documentacao/references/checklist-coerencia.md +59 -0
  36. package/skills/documentacao/references/ligar-app-novo.md +107 -0
  37. package/skills/documentacao/references/modelo-especificacao.md +51 -0
  38. package/skills/documentacao/references/modelo-readme.md +75 -0
  39. package/skills/documentacao/scripts/checar.mjs +454 -0
  40. package/skills/documentacao/scripts/nucleo.mjs +227 -0
  41. package/skills/express/SKILL.md +154 -0
  42. package/skills/express/references/dados.md +180 -0
  43. package/skills/express/references/estrutura.md +154 -0
  44. package/skills/express/references/middlewares.md +227 -0
  45. package/skills/express/references/rotas-erros.md +274 -0
  46. package/skills/express/references/testes-deploy.md +150 -0
  47. package/skills/express/scripts/checar.mjs +115 -0
  48. package/skills/express/scripts/nucleo.mjs +227 -0
  49. package/skills/fastapi/SKILL.md +129 -0
  50. package/skills/fastapi/references/banco.md +185 -0
  51. package/skills/fastapi/references/estrutura.md +281 -0
  52. package/skills/fastapi/references/integracoes.md +145 -0
  53. package/skills/fastapi/references/rotas-erros.md +140 -0
  54. package/skills/fastapi/references/testes-deploy.md +190 -0
  55. package/skills/fastapi/scripts/checar.mjs +108 -0
  56. package/skills/fastapi/scripts/nucleo.mjs +227 -0
  57. package/skills/hefesto/SKILL.md +119 -0
  58. package/skills/hefesto/references/conceitos.md +131 -0
  59. package/skills/hefesto/references/diagnostico.md +70 -0
  60. package/skills/hefesto/references/fluxo.md +122 -0
  61. package/skills/hefesto/references/preparar-app.md +105 -0
  62. package/skills/orfeu/SKILL.md +162 -0
  63. package/skills/orfeu/references/angular-api.md +201 -0
  64. package/skills/orfeu/references/angular-armadilhas.md +116 -0
  65. package/skills/orfeu/references/angular-recipes.md +474 -0
  66. package/skills/orfeu/references/angular.md +212 -0
  67. package/skills/orfeu/references/diferencas.md +56 -0
  68. package/skills/orfeu/references/node-api.md +348 -0
  69. package/skills/orfeu/references/node-armadilhas.md +158 -0
  70. package/skills/orfeu/references/node-recipes.md +534 -0
  71. package/skills/orfeu/references/node.md +204 -0
  72. package/skills/orfeu/references/python-api.md +346 -0
  73. package/skills/orfeu/references/python-recipes.md +479 -0
  74. package/skills/orfeu/references/python.md +234 -0
  75. package/skills/orfeu/scripts/checar.mjs +126 -0
  76. package/skills/orfeu/scripts/nucleo.mjs +227 -0
  77. package/skills/trismegisto/SKILL.md +194 -0
  78. package/skills/trismegisto/references/angular-api.md +2788 -0
  79. package/skills/trismegisto/references/angular-exports.md +4020 -0
  80. package/skills/trismegisto/references/angular-recipes.md +1883 -0
  81. package/skills/trismegisto/references/angular-types.md +492 -0
  82. package/skills/trismegisto/references/angular.md +390 -0
  83. package/skills/trismegisto/references/catalogo/icones.json +912 -0
  84. package/skills/trismegisto/references/catalogo/seletores.json +7013 -0
  85. package/skills/trismegisto/references/catalogo/tokens.json +240 -0
  86. package/skills/trismegisto/references/spine-api.md +1530 -0
  87. package/skills/trismegisto/references/spine-recipes.md +581 -0
  88. package/skills/trismegisto/references/spine.md +343 -0
  89. package/skills/trismegisto/scripts/checar.mjs +216 -0
  90. package/skills/trismegisto/scripts/nucleo.mjs +227 -0
@@ -0,0 +1,1883 @@
1
+ # Receitas — @trismegisto/angular 1.0
2
+
3
+ Padrões prontos, baseados nos demos do site de docs. Todos os componentes são standalone: importe as classes
4
+ usadas no `imports` do componente. Eventos de botão são `(clicked)`, **não** `(click)`.
5
+ Nomes exatos de inputs/outputs: `angular-api.md`; de funções, tipos e serviços: `angular-exports.md`. Tipos/funções que não saem de `@trismegisto/angular` vêm de
6
+ `@trismegisto/primitives` (marcados nos imports); harnesses, de `@trismegisto/angular/testing`.
7
+
8
+ ## 1. Shell da aplicação
9
+
10
+ Se o app usa `@trismegisto/spine`, o layout pronto dele já faz isto. Sem spine:
11
+
12
+ ```html
13
+ <div class="shell" hermesTheme>
14
+ <hm-header>
15
+ <span shortcuts><!-- atalhos à esquerda das ações --></span>
16
+ <span actions>
17
+ <hm-theme-picker [families]="theme.families" [family]="theme.family()" [theme]="theme.theme()"
18
+ (familyChosen)="theme.setFamily($event)" (themeChosen)="theme.setTheme($event)" />
19
+ </span>
20
+ </hm-header>
21
+
22
+ <div class="shell__body">
23
+ <hm-sidebar label="Navegação principal">
24
+ <hm-sidebar-link route="/" label="Início" icon="home" />
25
+ <hm-sidebar-group id="servidores" label="Servidores" icon="rack-server">
26
+ <hm-sidebar-link route="/servidores" label="Lista" icon="list" />
27
+ </hm-sidebar-group>
28
+ </hm-sidebar>
29
+ <main class="shell__content" tabindex="0">
30
+ <router-outlet />
31
+ </main>
32
+ </div>
33
+
34
+ <hm-toast-stack />
35
+ </div>
36
+ ```
37
+
38
+ ```scss
39
+ .shell { min-height: 100dvh; background: var(--hm-surface); color: var(--hm-text); }
40
+ .shell__body { display: grid; grid-template-columns: auto minmax(0, 1fr); }
41
+ .shell__content { padding: var(--hm-space-lg); min-width: 0; overflow: auto; }
42
+ ```
43
+
44
+ No componente do shell: `protected readonly theme = inject(HermesThemeService);`. Para menus montados a
45
+ partir de dados, troque os links por `@for (item of nav; track item.id) { <hm-sidebar-node [node]="item" /> }`
46
+ com uma árvore de `SidebarNode`.
47
+
48
+ `main` com `tabindex="0"` permite rolar só pelo teclado. `minmax(0, 1fr)` evita que conteúdo largo
49
+ (tabela, código) estoure a página no celular.
50
+
51
+ ## 2. Listagem com data grid
52
+
53
+ ```ts
54
+ import { Component, inject, signal } from '@angular/core';
55
+ import {
56
+ DataGridActionTriggered, DataGridCellDirective, DataGridColumn, DataGridComponent,
57
+ DataGridRowAction, HermesToastService, TagComponent,
58
+ } from '@trismegisto/angular';
59
+
60
+ interface Server { id: string; name: string; status: 'Online' | 'Offline'; cpu: number; }
61
+
62
+ @Component({
63
+ selector: 'app-servers',
64
+ imports: [DataGridComponent, DataGridCellDirective, TagComponent],
65
+ templateUrl: './servers.html',
66
+ })
67
+ export class Servers {
68
+ private readonly toast = inject(HermesToastService);
69
+
70
+ protected readonly rows = signal<readonly Server[]>([]);
71
+ protected readonly loading = signal(true);
72
+ protected readonly page = signal({ page: 1, size: 10 });
73
+ protected readonly rowId = (row: Server) => row.id;
74
+
75
+ protected readonly columns: readonly DataGridColumn<Server>[] = [
76
+ { key: 'name', title: 'Servidor', value: (r) => r.name, sortable: true },
77
+ { key: 'status', title: 'Status', value: (r) => r.status, sortable: true },
78
+ { key: 'cpu', title: 'CPU', value: (r) => `${r.cpu}%`, raw: (r) => r.cpu, type: 'number', align: 'end', sortable: true },
79
+ ];
80
+
81
+ protected readonly actions: readonly DataGridRowAction<Server>[] = [
82
+ { id: 'restart', icon: 'refresh', label: 'Reiniciar' },
83
+ { id: 'remove', icon: 'trash', label: 'Remover', danger: true, separatorAbove: true },
84
+ ];
85
+
86
+ protected onAction({ action, row }: DataGridActionTriggered<Server>): void {
87
+ if (action === 'restart') this.toast.success(`${row.name} reiniciado.`);
88
+ }
89
+ }
90
+ ```
91
+
92
+ ```html
93
+ <hm-data-grid
94
+ caption="Servidores"
95
+ [columns]="columns"
96
+ [rows]="rows()"
97
+ [rowId]="rowId"
98
+ [rowActions]="actions"
99
+ [loading]="loading()"
100
+ [(pageState)]="page"
101
+ itemsLabel="servidores"
102
+ (actionTriggered)="onAction($event)"
103
+ >
104
+ <ng-template hmCell="status" let-row>
105
+ <hm-tag [name]="row.status" [color]="row.status === 'Online' ? 'success' : 'danger'" />
106
+ </ng-template>
107
+
108
+ <div dataGridActions>
109
+ <!-- botões da barra acima da grade (ex.: "Novo servidor") -->
110
+ </div>
111
+ </hm-data-grid>
112
+ ```
113
+
114
+ - `caption` é obrigatório: é o nome acessível da tabela.
115
+ - Busca, filtro por coluna, ordenação e paginação já vêm prontos no modo cliente. Para paginação no servidor,
116
+ passe `[totalItems]` e busque a página ao mudar `pageState`.
117
+ - Detalhe da linha: `<ng-template #detailPane let-row>…</ng-template>` dentro da grade.
118
+
119
+ ## 3. Formulário reativo
120
+
121
+ ```ts
122
+ import { Component, inject, signal } from '@angular/core';
123
+ import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
124
+ import { ButtonComponent, CheckboxComponent, DatePickerComponent, InputComponent, SelectComponent } from '@trismegisto/angular';
125
+
126
+ @Component({
127
+ selector: 'app-account-form',
128
+ imports: [ReactiveFormsModule, InputComponent, SelectComponent, DatePickerComponent, CheckboxComponent, ButtonComponent],
129
+ templateUrl: './account-form.html',
130
+ })
131
+ export class AccountForm {
132
+ protected readonly form = inject(FormBuilder).nonNullable.group({
133
+ name: ['', Validators.required],
134
+ email: ['', [Validators.required, Validators.email]],
135
+ environment: ['', Validators.required],
136
+ expiresAt: [''],
137
+ notify: [false],
138
+ });
139
+ protected readonly saving = signal(false);
140
+
141
+ protected save(): void {
142
+ if (this.form.invalid) { this.form.markAllAsTouched(); return; }
143
+ this.saving.set(true);
144
+ // chamada ao backend…
145
+ }
146
+ }
147
+ ```
148
+
149
+ ```html
150
+ <form class="form" [formGroup]="form" (ngSubmit)="save()">
151
+ <hm-input label="Nome" formControlName="name" />
152
+ <hm-input label="E-mail" formControlName="email"
153
+ [messages]="{ email: 'Informe um e-mail válido.' }" hint="Usado para notificações." />
154
+ <hm-select label="Ambiente" formControlName="environment">
155
+ <option value="" disabled>Selecione…</option>
156
+ <option value="dev">Desenvolvimento</option>
157
+ <option value="prod">Produção</option>
158
+ </hm-select>
159
+ <hm-date-picker label="Expira em" formControlName="expiresAt" />
160
+ <hm-checkbox label="Receber notificações" formControlName="notify" />
161
+
162
+ <div class="form__actions">
163
+ <hm-button emphasis="minimal" type="button">Cancelar</hm-button>
164
+ <hm-button type="submit" [loading]="saving()">Salvar</hm-button>
165
+ </div>
166
+ </form>
167
+ ```
168
+
169
+ ```scss
170
+ .form { display: grid; gap: var(--hm-space-md); max-width: 40rem; }
171
+ .form__actions { display: flex; justify-content: flex-end; gap: var(--hm-space-sm); }
172
+ ```
173
+
174
+ - O mesmo formulário funciona com `[(ngModel)]` (template-driven) ou `[(value)]` sem formulário — `angular.md` §3.
175
+ - `loading` já desabilita o botão e anuncia o carregamento; não combine com `disabled`.
176
+ - O asterisco de obrigatório vem de `Validators.required`.
177
+
178
+ ## 4. Confirmação
179
+
180
+ ```ts
181
+ private readonly dialogs = inject(HermesDialogService);
182
+
183
+ protected async remove(server: Server): Promise<void> {
184
+ const ok = await this.dialogs.confirm({
185
+ heading: 'Remover servidor?',
186
+ message: `${server.name} será removido. Essa ação não pode ser desfeita.`,
187
+ danger: true,
188
+ });
189
+ if (ok) await this.api.remove(server.id);
190
+ }
191
+ ```
192
+
193
+ Diálogo com conteúdo próprio: `const ref = this.dialogs.open<Result>(EditServer, { heading: 'Editar', data: server });`
194
+ e `await ref.closed`. Dentro do componente: `inject(HERMES_DIALOG_DATA)` e `inject(HermesDialogRef).close(result)`.
195
+ Fechar no X ou no Esc resolve com `undefined` (no `confirm`, com `false`).
196
+
197
+ Modal fixo no template (quando o conteúdo mora na própria tela):
198
+
199
+ ```html
200
+ <hm-modal heading="Detalhes" [(open)]="detailsOpen">
201
+ <p>…</p>
202
+ <div footer><hm-button (clicked)="detailsOpen.set(false)">Fechar</hm-button></div>
203
+ </hm-modal>
204
+ ```
205
+
206
+ ## 5. Estados de carregamento, vazio e erro
207
+
208
+ ```html
209
+ @if (loading()) {
210
+ <hm-skeleton shape="cards" [count]="3" label="Painéis" />
211
+ } @else if (error()) {
212
+ <hm-state-screen situation="error" heading="Não foi possível carregar"
213
+ [description]="error()" action="Tentar de novo" actionIcon="refresh"
214
+ (actionTriggered)="reload()" />
215
+ } @else if (items().length === 0) {
216
+ <hm-state-screen situation="empty" heading="Nenhum painel ainda"
217
+ description="Crie o primeiro painel para começar." />
218
+ } @else {
219
+ <!-- conteúdo -->
220
+ }
221
+ ```
222
+
223
+ ## 6. Menu de ações e feedback
224
+
225
+ ```ts
226
+ protected readonly menu: readonly MenuItem[] = [
227
+ { id: 'edit', label: 'Editar', icon: 'pencil' },
228
+ { id: 'duplicate', label: 'Duplicar', icon: 'copy' },
229
+ { id: 'delete', label: 'Excluir', icon: 'trash', danger: true, separatorAbove: true },
230
+ ];
231
+ ```
232
+
233
+ ```html
234
+ <hm-menu-button label="Ações" icon="ellipsis-vertical" shape="circle" [items]="menu" (chosen)="run($event)" />
235
+ ```
236
+
237
+ `(chosen)` emite o `id`. Para resultado de uma ação, prefira `HermesToastService` a um `hm-alert` temporário.
238
+
239
+ ## 7. Idioma
240
+
241
+ ```ts
242
+ // app.config.ts — idioma inicial (pt-BR se omitido)
243
+ providers: [provideHermesI18n({ locale: savedLocale })];
244
+
245
+ // quando a pessoa troca o idioma no app
246
+ private readonly hermesI18n = inject(HermesI18nService);
247
+ changeLanguage(locale: string) {
248
+ this.appTranslations.use(locale); // o i18n do próprio app
249
+ this.hermesI18n.setLocale(locale); // textos da lib, formato de data e plurais, sem recarregar
250
+ }
251
+ ```
252
+
253
+ Texto da lib diferente do padrão: `provideHermesI18n({ override: { modal: { close: 'Dispensar' } } })`.
254
+ Idioma que a lib não traz: `registerCatalog('fr', catalogoCompleto)`.
255
+ Com `@trismegisto/spine`, o shell segue o mesmo `setLocale`; textos dele: `provideSpineMessages({ override })`.
256
+ Catálogo do próprio app no mesmo idioma: `liveCatalog(() => i18n.pick({ 'pt-BR': PT, en: EN }, PT))`.
257
+
258
+ Pipes standalone que seguem o `setLocale` ao vivo (impuros com memória; funcionam em OnPush/zoneless):
259
+
260
+ ```html
261
+ {{ 'modal.close' | hmTranslate }} <!-- chave seção.chave do catálogo -->
262
+ {{ 'alert.groupLabel' | hmTranslate: { count: n } }} <!-- plural pelo idioma -->
263
+ {{ pedido.criadoEm | hmDate }} <!-- 'short' (padrão) | 'medium' | 'long' | 'full' -->
264
+ {{ pedido.criadoEm | hmDate: { month: 'long', year: 'numeric' } }}
265
+ {{ evento.em | hmDateTime: 'short' : { timeZone: 'UTC' } }}
266
+ ```
267
+
268
+ Importe `HermesTranslatePipe`, `HermesDatePipe`, `HermesDateTimePipe`. Aceita `Date`, ms ou ISO (`'AAAA-MM-DD'` = dia
269
+ local); vazio/inválido → `''`. Em TS: `formatHermesDate(valor, i18n.messages().meta.locale, 'date', 'long')` num `computed`.
270
+
271
+ ## 8. Cadastro com máscara e número
272
+
273
+ ```ts
274
+ import { Component, inject } from '@angular/core';
275
+ import { AbstractControl, FormBuilder, ReactiveFormsModule, ValidationErrors, Validators } from '@angular/forms';
276
+ import { ButtonComponent, InputComponent } from '@trismegisto/angular';
277
+ import { isMaskComplete } from '@trismegisto/primitives';
278
+
279
+ /** "CPF completo": a máscara só formata; quem exige os 11 dígitos é o validator. */
280
+ const completeCpf = (c: AbstractControl): ValidationErrors | null =>
281
+ !c.value || isMaskComplete(c.value, 'cpf') ? null : { pattern: true };
282
+
283
+ @Component({
284
+ selector: 'app-member-form',
285
+ imports: [ReactiveFormsModule, InputComponent, ButtonComponent],
286
+ templateUrl: './member-form.html',
287
+ })
288
+ export class MemberForm {
289
+ protected readonly form = inject(FormBuilder).group({
290
+ cpf: ['', [Validators.required, completeCpf]], // guarda '12345678901' (maskValue raw, padrão)
291
+ phone: [''],
292
+ email: ['', Validators.email],
293
+ quota: [null as number | null, Validators.required], // type="number": o valor é number, vazio = null
294
+ });
295
+ }
296
+ ```
297
+
298
+ ```html
299
+ <form class="form" [formGroup]="form">
300
+ <hm-input label="CPF" formControlName="cpf" mask="cpf" />
301
+ <hm-input label="Telefone" formControlName="phone" mask="phone" type="tel" autocomplete="tel" />
302
+ <hm-input label="E-mail" formControlName="email" type="email" autocomplete="email" />
303
+ <hm-input label="Cota mensal" formControlName="quota" type="number" prefix="R$"
304
+ [min]="0" [max]="10000" [step]="0.01" hint="Até R$ 10.000,00." />
305
+ </form>
306
+ ```
307
+
308
+ - `min`/`max`/`step` do `type="number"` já validam (erros `min`, `max`, `number`, com texto do catálogo):
309
+ não repita `Validators.min/max`. Os botões −/+ vêm junto (`[stepButtons]="false"` tira).
310
+ - `prefix`/`suffix` em texto são lidos pelo leitor de tela junto do rótulo; `prefixIcon` é decorativo.
311
+ - Com `mask`, `maxLength` é ignorado; sem máscara, `[maxLength]="120"` mostra o contador.
312
+ - Backend que quer a pontuação: `maskValue="masked"`.
313
+
314
+ ## 9. Cabeçalho de página e barra de ferramentas
315
+
316
+ ```html
317
+ <hm-page-header
318
+ heading="Organizações"
319
+ description="Cadastro das organizações atendidas."
320
+ [summary]="countText()"
321
+ [breadcrumb]="[{ label: 'Início', routerLink: '/' }, { label: 'Organizações' }]"
322
+ >
323
+ <hm-tag meta name="Sincronizado" color="success" />
324
+ <hm-button actions (clicked)="create()">Nova organização</hm-button>
325
+ </hm-page-header>
326
+
327
+ <hm-toolbar label="Filtros da listagem">
328
+ <hm-search-field start label="Buscar organização" labelHidden [landmark]="false"
329
+ [debounce]="300" [(value)]="term" (search)="load($event)" />
330
+ <hm-segmented-control start label="Situação" [options]="situations" [(value)]="situation" />
331
+ <hm-copy-button end label="Copiar link da busca" [value]="shareUrl()" />
332
+ </hm-toolbar>
333
+ ```
334
+
335
+ - `hm-page-header` é o `<h1>` da página; se o shell já tem um, use `[level]="2"`. `summary` é anunciado a
336
+ cada mudança — texto fixo vai em `description`. No máximo duas ou três ações no slot `actions`.
337
+ - `countText()` vem do i18n do app (com plural: "1 de 40 organizações"), não de concatenação no template.
338
+ - `hm-toolbar` é uma parada de Tab só: as setas andam entre os controles (no campo de busca, as setas movem
339
+ o cursor — saia com Tab). Dentro dela, `hm-search-field` vai com `[landmark]="false"`.
340
+ - `(search)` já vem com `debounce`; `Enter` e limpar publicam na hora. Filtro em memória: `debounce` 0.
341
+
342
+ ## 10. Wizard com validação por etapa e confirmação de cancelar
343
+
344
+ ```ts
345
+ import { Component, inject, signal } from '@angular/core';
346
+ import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
347
+ import { ButtonComponent, HermesStepGuard, HermesToastService, InputComponent, StepComponent, WizardComponent } from '@trismegisto/angular';
348
+
349
+ @Component({
350
+ selector: 'app-new-organization',
351
+ imports: [ReactiveFormsModule, WizardComponent, StepComponent, InputComponent, ButtonComponent],
352
+ templateUrl: './new-organization.html',
353
+ })
354
+ export class NewOrganization {
355
+ private readonly fb = inject(FormBuilder).nonNullable;
356
+ private readonly toast = inject(HermesToastService);
357
+
358
+ protected readonly open = signal(false);
359
+ protected readonly saving = signal(false);
360
+ protected readonly data = this.fb.group({ name: ['', Validators.required], cnpj: ['', Validators.required] });
361
+ protected readonly address = this.fb.group({ city: ['', Validators.required] });
362
+
363
+ /** Regra que não cabe no formulário: consulta o servidor antes de sair da etapa. */
364
+ protected readonly cnpjFree: HermesStepGuard = () => this.api.isCnpjFree(this.data.getRawValue().cnpj);
365
+
366
+ protected async save(): Promise<void> {
367
+ this.saving.set(true);
368
+ try {
369
+ await this.api.create({ ...this.data.getRawValue(), ...this.address.getRawValue() });
370
+ this.open.set(false); // o wizard não fecha sozinho: só depois de salvar
371
+ this.toast.success(this.texts.created);
372
+ } finally {
373
+ this.saving.set(false); // se falhou, a pessoa continua com tudo preenchido
374
+ }
375
+ }
376
+
377
+ protected discard(): void {
378
+ this.data.reset();
379
+ this.address.reset();
380
+ }
381
+ }
382
+ ```
383
+
384
+ ```html
385
+ <hm-button (clicked)="open.set(true)">Nova organização</hm-button>
386
+
387
+ <hm-wizard heading="Nova organização" [(open)]="open" [loading]="saving()"
388
+ [confirmCancel]="{ message: 'Os dados preenchidos serão perdidos.' }"
389
+ (completed)="save()" (cancelled)="discard()">
390
+ <hm-step label="Dados" [stepControl]="data" [canAdvance]="cnpjFree">
391
+ <form class="form" [formGroup]="data">
392
+ <hm-input label="Nome" formControlName="name" />
393
+ <hm-input label="CNPJ" formControlName="cnpj" mask="cnpj" />
394
+ </form>
395
+ </hm-step>
396
+ <hm-step label="Endereço" [stepControl]="address">
397
+ <form class="form" [formGroup]="address">
398
+ <hm-input label="Cidade" formControlName="city" />
399
+ </form>
400
+ </hm-step>
401
+ <!-- Revisão final: não escreva uma etapa à mão — use [summary]="true" no wizard (receita 21). -->
402
+ </hm-wizard>
403
+ ```
404
+
405
+ - `linear` vem ligado: Avançar valida `stepControl` (inválido marca tudo como tocado e a etapa fica com erro)
406
+ e depois `canAdvance` (enquanto a `Promise` não resolve, o Avançar carrega). Etapa `optional` não bloqueia.
407
+ - `confirmCancel`: `true` usa os textos do catálogo; um objeto troca só o que vier (`heading`, `message`,
408
+ `confirmLabel`, `cancelLabel`, `danger` — padrão `true`). Vale para o botão Cancelar, o X e o Esc.
409
+ - `loading` trava o fluxo e o X; ao reabrir, volta à primeira etapa (`resetOnOpen`). Os formulários são do app.
410
+ - Mesmo fluxo no corpo da página: `mode="page"`. Só o indicador com conteúdo, sem rodapé pronto: `hm-stepper`
411
+ com `[(selectedIndex)]` e `next()`/`previous()` chamados pelos seus botões.
412
+ - Modal comum com "descartar alterações?": `<hm-modal [beforeClose]="confirmDiscard">`, com
413
+ `confirmDiscard = () => this.form.pristine || this.dialogs.confirm({ heading, message, danger: true })`.
414
+
415
+ ## 11. Upload com envio e progresso
416
+
417
+ ```ts
418
+ import { HttpClient, HttpEventType } from '@angular/common/http';
419
+ import { Component, inject } from '@angular/core';
420
+ import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
421
+ import { FileUploadComponent, FileUploader, UploadFile } from '@trismegisto/angular';
422
+
423
+ @Component({
424
+ selector: 'app-attachments',
425
+ imports: [ReactiveFormsModule, FileUploadComponent],
426
+ templateUrl: './attachments.html',
427
+ })
428
+ export class Attachments {
429
+ private readonly http = inject(HttpClient);
430
+ protected readonly form = inject(FormBuilder).nonNullable.group({
431
+ files: [[] as readonly UploadFile[], Validators.required],
432
+ });
433
+
434
+ /** Cada arquivo aceito é enviado na hora; remover durante o envio aborta o `signal`. */
435
+ protected readonly upload: FileUploader = (file, report, signal) =>
436
+ new Promise((resolve, reject) => {
437
+ const body = new FormData();
438
+ body.append('file', file);
439
+ const sub = this.http.post('/api/attachments', body, { reportProgress: true, observe: 'events' }).subscribe({
440
+ next: (event) => {
441
+ if (event.type === HttpEventType.UploadProgress && event.total) report(Math.round((100 * event.loaded) / event.total));
442
+ if (event.type === HttpEventType.Response) resolve(event.body);
443
+ },
444
+ error: () => reject(new Error(this.texts.uploadFailed(file.name))), // texto do i18n do app
445
+ });
446
+ signal.addEventListener('abort', () => sub.unsubscribe());
447
+ });
448
+ }
449
+ ```
450
+
451
+ ```html
452
+ <form [formGroup]="form">
453
+ <hm-file-upload label="Anexos" formControlName="files" [uploader]="upload"
454
+ accept=".pdf,.xlsx,image/*" [multiple]="true" [maxFiles]="5" [maxSize]="5 * 1024 * 1024"
455
+ hint="Contrato assinado e comprovantes." />
456
+ </form>
457
+ ```
458
+
459
+ - Formatos e limites aparecem sozinhos embaixo da área e são validados **antes** de o arquivo entrar na
460
+ lista; recusas são anunciadas com o motivo e saem em `(rejected)`.
461
+ - Com `uploader`: progresso, erro (a `message` do `Error` vira o texto), "tentar de novo" e cancelamento ao
462
+ remover já vêm prontos. Antes de salvar o formulário, confira que todos estão com `status === 'done'`.
463
+ - Envio por conta do app (lote no submit, por exemplo): sem `uploader`, pegue a instância
464
+ (`viewChild.required(FileUploadComponent)`) e informe com `update(id, { status: 'uploading', progress })`,
465
+ `update(id, { status: 'done' })` ou `update(id, { status: 'error', error: texto })`; "tentar de novo" emite
466
+ `(retried)` com o item já em `pending`.
467
+ - Soltar arquivos é só atalho de mouse: o botão "Escolher arquivos" (input nativo) é o caminho acessível.
468
+
469
+ ## 12. Data grid com exportação, filtro composto e persistência
470
+
471
+ ```ts
472
+ import { Component, signal } from '@angular/core';
473
+ import { DataGridColumn, DataGridComponent, SelectComponent } from '@trismegisto/angular';
474
+ import { EMPTY_GRID_QUERY, GridAggregateFormatter, GridFilterQuery } from '@trismegisto/primitives';
475
+
476
+ interface Invoice { id: string; customer: string; status: string; issuedAt: string; total: number; }
477
+
478
+ @Component({
479
+ selector: 'app-invoices',
480
+ imports: [DataGridComponent, SelectComponent],
481
+ templateUrl: './invoices.html',
482
+ })
483
+ export class Invoices {
484
+ protected readonly rows = signal<readonly Invoice[]>([]);
485
+ protected readonly rowId = (row: Invoice) => row.id;
486
+ protected readonly query = signal<GridFilterQuery>(EMPTY_GRID_QUERY);
487
+ protected readonly group = signal(''); // '' = sem agrupamento
488
+
489
+ private readonly money = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' });
490
+ protected readonly columns: readonly DataGridColumn<Invoice>[] = [
491
+ { key: 'customer', title: 'Cliente', value: (r) => r.customer, sortable: true },
492
+ { key: 'status', title: 'Situação', value: (r) => r.status, sortable: true },
493
+ { key: 'issuedAt', title: 'Emissão', value: (r) => r.issuedAt.split('-').reverse().join('/'), raw: (r) => r.issuedAt, type: 'date', sortable: true },
494
+ { key: 'total', title: 'Total', value: (r) => this.money.format(r.total), raw: (r) => r.total, type: 'number', align: 'end', sortable: true },
495
+ ];
496
+ protected readonly formatAggregate: GridAggregateFormatter = (value, fn) => (fn === 'count' ? String(value) : this.money.format(value));
497
+ }
498
+ ```
499
+
500
+ ```html
501
+ <hm-select label="Agrupar por" [(value)]="group">
502
+ <option value="">Sem agrupamento</option>
503
+ <option value="status">Situação</option>
504
+ <option value="customer">Cliente</option>
505
+ </hm-select>
506
+
507
+ <hm-data-grid
508
+ caption="Notas fiscais"
509
+ [columns]="columns" [rows]="rows()" [rowId]="rowId"
510
+ [exportable]="true" exportFileName="notas-fiscais"
511
+ [advancedFilter]="true" [(filterQuery)]="query"
512
+ [columnManager]="true"
513
+ [groupBy]="group() || null"
514
+ [aggregates]="{ total: 'sum' }" [aggregateFormatter]="formatAggregate"
515
+ persistKey="invoices"
516
+ />
517
+ ```
518
+
519
+ - **Exportar**: botão na barra (CSV ou Excel). Sai o que a pessoa vê: linhas filtradas e ordenadas de todas
520
+ as páginas, colunas visíveis na ordem da tela, texto formatado (`value`). Coluna só visual: `exportable: false`.
521
+ Por código: `grid.exportCsv({ format: 'excel', download: false })` devolve o texto.
522
+ - **Filtro composto**: popover com condições coluna + operador (pelo `type` da coluna) + valor, E/OU, e chips
523
+ das condições ativas. `[(filterQuery)]` é serializável — para filtrar no servidor, leia `query()`.
524
+ - **Persistência**: ordenação, filtros, colunas (visibilidade, largura, ordem) e itens por página ficam em
525
+ `localStorage` com a chave `<storagePrefix>_grid_invoices` (`persistStorage="session"` para durar só na aba).
526
+ Uma chave por tela; `grid.clearPersistedState()` para um "restaurar padrão" do app.
527
+ - **Gerenciador de colunas**: mostrar/ocultar, reordenar (arrasto e teclado), restaurar; `[(columnOrder)]` se
528
+ o app precisar saber a ordem. Fixar coluna: `pinned` na coluna ou `[(pinnedColumns)]` (receita 20).
529
+ - **Agrupar**: cada grupo vira um bloco recolhível com o rótulo e os agregados do grupo; `aggregates` também
530
+ põe a linha de totais no rodapé. O seletor de agrupamento é do app (aqui, `hm-select`).
531
+
532
+ ## 13. Atalhos de teclado com painel
533
+
534
+ ```ts
535
+ import { Component, DestroyRef, inject, signal } from '@angular/core';
536
+ import { HermesShortcutItem, HermesShortcutService, ModalComponent, ShortcutListComponent } from '@trismegisto/angular';
537
+
538
+ // no shell (imports: ModalComponent, ShortcutListComponent)
539
+ export class Shell {
540
+ protected readonly helpOpen = signal(false);
541
+ protected readonly declared: readonly HermesShortcutItem[] = [
542
+ { keys: 'Esc', description: 'Fechar o diálogo aberto', group: 'general' }, // tratado pelo próprio diálogo
543
+ ];
544
+
545
+ constructor() {
546
+ const remove = inject(HermesShortcutService).register({
547
+ keys: '?', description: 'Mostrar os atalhos', group: 'general',
548
+ handler: () => this.helpOpen.set(true),
549
+ });
550
+ inject(DestroyRef).onDestroy(remove);
551
+ }
552
+ }
553
+ ```
554
+
555
+ ```html
556
+ <!-- shell -->
557
+ <hm-modal heading="Atalhos de teclado" [(open)]="helpOpen">
558
+ <hm-shortcut-list [items]="declared" [searchable]="true" [characterKeysToggle]="true" />
559
+ </hm-modal>
560
+
561
+ <!-- numa tela (imports: ShortcutDirective): o atalho vale enquanto o elemento existe -->
562
+ <hm-search-field label="Buscar servidor" hmShortcut="/" hmShortcutDescription="Ir para a busca" hmShortcutGroup="navigation" />
563
+ <hm-button hmShortcut="Mod+S" hmShortcutDescription="Salvar" hmShortcutGroup="actions" (clicked)="save()">Salvar</hm-button>
564
+ ```
565
+
566
+ - `Mod` = Ctrl no Windows/Linux e ⌘ no macOS (o painel mostra o símbolo certo). Sequência: `'G H'`.
567
+ - `[hmShortcut]` age no alvo: foca campo editável, clica no resto (`hmShortcutAction`); botão desabilitado não
568
+ reage. Também põe `aria-keyshortcuts`. Com foco num campo, o atalho não dispara (salvo `hmShortcutAllowInInputs`).
569
+ - Atalho de tecla única (`/`, `?`, `G H`) precisa poder ser desligado (WCAG 2.1.4): `characterKeysToggle` mostra o
570
+ interruptor; guardar a escolha entre sessões é do app (`setCharacterKeys` ao iniciar).
571
+ - Mesma tecla registrada duas vezes: vale a mais recente (o atalho do diálogo por cima do global).
572
+ - Não tome atalhos do navegador ou do leitor de tela (Ctrl+L, Ctrl+T, Insert+…).
573
+ - `MenuItem.shortcut` continua só exibição: registre a tecla com o serviço ou a diretiva.
574
+
575
+ ## 14. Faixa de filtros ligada ao data grid, com filtros salvos
576
+
577
+ ```ts
578
+ import { Component, computed, signal } from '@angular/core';
579
+ import {
580
+ DataGridColumn, DataGridComponent, FilterBarComponent, FilterBarField, FilterBarValue,
581
+ applyFilterBar, filterBarGridUnsupported, filterBarToGridQuery,
582
+ } from '@trismegisto/angular';
583
+
584
+ interface Account { id: string; name: string; status: 'A' | 'I'; region: string; opened: string; vip: boolean; }
585
+
586
+ @Component({
587
+ selector: 'app-accounts',
588
+ imports: [FilterBarComponent, DataGridComponent],
589
+ templateUrl: './accounts.html',
590
+ })
591
+ export class Accounts {
592
+ protected readonly accounts = signal<readonly Account[]>([]);
593
+ protected readonly rowId = (row: Account) => row.id;
594
+
595
+ /** `key` = propriedade da linha (applyFilterBar) = `key` da coluna (filterBarToGridQuery). */
596
+ protected readonly filters: readonly FilterBarField[] = [
597
+ { key: 'name', label: 'Nome', type: 'text' },
598
+ { key: 'status', label: 'Situação', type: 'select', options: [{ value: 'A', label: 'Ativa' }, { value: 'I', label: 'Inativa' }] },
599
+ { key: 'region', label: 'UF', type: 'multiselect', options: [{ value: 'MG', label: 'MG' }, { value: 'SP', label: 'SP' }] },
600
+ { key: 'opened', label: 'Abertura', type: 'date-range' },
601
+ { key: 'vip', label: 'VIP', type: 'boolean' },
602
+ ];
603
+ protected readonly filterValue = signal<FilterBarValue>({}); // só campos ativos: { status: 'A', region: ['MG'] }
604
+
605
+ protected readonly columns: readonly DataGridColumn<Account>[] = [
606
+ { key: 'name', title: 'Nome', value: (r) => r.name, sortable: true },
607
+ // `raw` devolve o mesmo valor das `options` ('A'), não o texto exibido: o filtro compara pelo bruto
608
+ { key: 'status', title: 'Situação', value: (r) => (r.status === 'A' ? 'Ativa' : 'Inativa'), raw: (r) => r.status },
609
+ { key: 'region', title: 'UF', value: (r) => r.region },
610
+ { key: 'opened', title: 'Abertura', value: (r) => r.opened.split('-').reverse().join('/'), raw: (r) => r.opened, type: 'date' },
611
+ { key: 'vip', title: 'VIP', value: (r) => (r.vip ? 'Sim' : 'Não'), raw: (r) => r.vip, type: 'boolean' },
612
+ ];
613
+
614
+ /** Caminho A — filtrar no app: a grade recebe as linhas já recortadas. Sempre funciona. */
615
+ protected readonly rows = computed(() => applyFilterBar(this.accounts(), this.filters, this.filterValue()));
616
+
617
+ /** Caminho B — a grade filtra: vira o filtro composto dela (chips e persistência junto). */
618
+ protected readonly query = computed(() => filterBarToGridQuery(this.filters, this.filterValue()));
619
+ protected readonly gridCanFilter = computed(() => filterBarGridUnsupported(this.filters, this.filterValue()).length === 0);
620
+ }
621
+ ```
622
+
623
+ ```html
624
+ <hm-filter-bar label="Filtros de contas" [filters]="filters" [(value)]="filterValue"
625
+ [savedFilters]="true" storageKey="contas" />
626
+
627
+ <!-- A: linhas recortadas no app -->
628
+ <hm-data-grid caption="Contas" [columns]="columns" [rows]="rows()" [rowId]="rowId" />
629
+
630
+ <!-- B: no lugar do A, quando gridCanFilter() — a grade aplica o filtro composto
631
+ <hm-data-grid caption="Contas" [columns]="columns" [rows]="accounts()" [rowId]="rowId" [filterQuery]="query()" /> -->
632
+ ```
633
+
634
+ - `filterBarToGridQuery` não exprime `multiselect` com 2+ escolhas (`filterBarGridUnsupported` lista quais):
635
+ nesse caso use o caminho A ou mande `filterValue()` ao servidor. Na dúvida, fique no A.
636
+ - Lista no servidor: reaja a `filterValue()` (num `effect` ou `toObservable`) e busque; `serializeFilterBarValue`
637
+ / `parseFilterBarValue` levam o filtro para a URL e de volta.
638
+ - O popover é rascunho até Aplicar: `value` só muda quando a pessoa confirma — pode disparar a consulta direto.
639
+ - Salvos no servidor: `[storage]="{ get: (key) => api.load(key), set: (key, list) => api.save(key, list) }"`
640
+ (`FilterBarStorage`, síncrono ou `Promise`). Um padrão marcado é aplicado ao carregar se não houver filtro
641
+ (`[applyDefault]="false"` desliga); `(savedApplied)` avisa quando a pessoa aplica um salvo.
642
+ - Campo com sugestões mas texto livre (datalist): `hm-combobox` com `[allowCustomValue]="true"`.
643
+
644
+ ## 15. Kanban com regra de movimento (`canMove`)
645
+
646
+ ```ts
647
+ import { Component, inject, signal } from '@angular/core';
648
+ import { HERMES_KANBAN, HermesToastService, IconButtonComponent, KanbanCanMove, KanbanColumn, KanbanMoveEvent, TagComponent } from '@trismegisto/angular';
649
+
650
+ interface Ticket { id: string; title: string; assignee: string | null; urgent: boolean; }
651
+
652
+ @Component({
653
+ selector: 'app-ticket-board',
654
+ imports: [HERMES_KANBAN, IconButtonComponent, TagComponent],
655
+ templateUrl: './ticket-board.html',
656
+ })
657
+ export class TicketBoard {
658
+ private readonly api = inject(TicketsApi); // serviço do app
659
+ private readonly toast = inject(HermesToastService);
660
+
661
+ protected readonly columns = signal<readonly KanbanColumn<Ticket>[]>([
662
+ { id: 'todo', title: 'A fazer', items: [] },
663
+ { id: 'doing', title: 'Em andamento', items: [], limit: 3 }, // WIP: só avisa acima de 3
664
+ { id: 'review', title: 'Revisão', items: [] },
665
+ { id: 'done', title: 'Concluído', items: [] },
666
+ ]);
667
+ protected readonly collapsed = signal<readonly string[]>([]);
668
+ protected readonly ticketLabel = (t: Ticket) => t.title;
669
+ protected readonly ticketKey = (t: Ticket) => t.id;
670
+
671
+ /** Concluído não volta; "Em andamento" e "Revisão" exigem responsável. Reordenar na coluna é livre. */
672
+ protected readonly canMove: KanbanCanMove<Ticket> = (ticket, from, to) =>
673
+ from.id !== 'done' && (ticket.assignee !== null || !['doing', 'review'].includes(to.id));
674
+
675
+ /** `[(columns)]` já está atualizado; aqui só persiste. */
676
+ protected async onMoved(event: KanbanMoveEvent<Ticket>): Promise<void> {
677
+ try {
678
+ await this.api.move(event.item.id, event.to, event.toIndex);
679
+ } catch {
680
+ this.toast.error('Não foi possível mover o chamado.');
681
+ this.columns.set(await this.api.board()); // volta ao que o servidor tem
682
+ }
683
+ }
684
+
685
+ protected create(column: KanbanColumn<Ticket>): void { /* abre o formulário do app */ }
686
+ }
687
+ ```
688
+
689
+ ```html
690
+ <hm-kanban label="Chamados" [(columns)]="columns" [(collapsed)]="collapsed"
691
+ [canMove]="canMove" [itemLabel]="ticketLabel" [itemKey]="ticketKey" (moved)="onMoved($event)">
692
+ <ng-template hmKanbanCard let-ticket>
693
+ <strong>{{ ticket.title }}</strong>
694
+ @if (ticket.urgent) { <hm-tag name="Urgente" color="danger" [compact]="true" /> }
695
+ <span>{{ ticket.assignee ?? 'Sem responsável' }}</span>
696
+ </ng-template>
697
+
698
+ <ng-template hmKanbanColumnActions let-column>
699
+ <hm-icon-button icon="plus" [label]="'Novo chamado em ' + column.title" (clicked)="create(column)" />
700
+ </ng-template>
701
+
702
+ <div hmKanbanToolbar><!-- filtros/ações do quadro --></div>
703
+ </hm-kanban>
704
+ ```
705
+
706
+ - `canMove(item, from, to)` só vale entre colunas: a coluna recusada nem aparece como destino (ponteiro e
707
+ teclado). `limit` só avisa (borda + texto "Acima do limite"); para barrar, recuse em `canMove`.
708
+ - `moved` traz `item`, `from`/`to` (ids), `fromIndex`/`toIndex`, `via` e o quadro novo (`columns`). Sem two-way,
709
+ use `[columns]` + `(moved)` e aplique `event.columns` você mesmo.
710
+ - Teclado pronto: Espaço/Enter pega, setas escolhem posição e coluna (←/→), Espaço/Enter solta, Esc cancela —
711
+ cada passo anunciado. `itemLabel` é o nome falado; sem ele, o leitor lê o texto todo do cartão.
712
+ - Arrastar não é o único caminho (WCAG 2.5.7): ofereça "Mover para…" num menu do cartão ou no detalhe.
713
+ - Botões dentro do cartão continuam clicáveis (pressionar neles não arrasta). Não ponha `(click)` no cartão.
714
+ - Animação dos cartões ao reordenar: `[hmFlip]` (§29).
715
+
716
+ ## 16. Arrastar e soltar genérico
717
+
718
+ ```ts
719
+ import { Component, signal } from '@angular/core';
720
+ import { HERMES_DRAG_DROP, HermesDropEvent, HermesSortEvent, IconButtonComponent } from '@trismegisto/angular';
721
+
722
+ interface Doc { id: string; name: string; }
723
+ interface Step { id: string; title: string; }
724
+
725
+ @Component({
726
+ selector: 'app-documents',
727
+ imports: [HERMES_DRAG_DROP, IconButtonComponent],
728
+ templateUrl: './documents.html',
729
+ styleUrl: './documents.scss',
730
+ })
731
+ export class Documents {
732
+ protected readonly docs = signal<readonly Doc[]>([]);
733
+ protected readonly steps = signal<readonly Step[]>([]);
734
+ protected readonly selected = signal<readonly Doc[]>([]);
735
+
736
+ protected onSorted(event: HermesSortEvent<Doc>): void {
737
+ // [(hmSortable)] já trocou a lista; aqui só persiste a ordem (event.previousIndex → event.index)
738
+ }
739
+
740
+ protected attach(event: HermesDropEvent<Doc>): void {
741
+ if (!this.selected().includes(event.data)) this.selected.update((list) => [...list, event.data]);
742
+ }
743
+
744
+ protected remove(doc: Doc): void {
745
+ this.docs.update((list) => list.filter((d) => d !== doc));
746
+ }
747
+ }
748
+ ```
749
+
750
+ ```html
751
+ <!-- 1. Lista que reordena; os itens também podem ir para a zona "Anexar" -->
752
+ <ul class="docs" [(hmSortable)]="docs" hmSortableLabel="Documentos" (sorted)="onSorted($event)">
753
+ @for (doc of docs(); track doc.id) {
754
+ <li class="docs__item" [hmDraggable]="doc" hmDragType="doc" [hmDragLabel]="doc.name">
755
+ {{ doc.name }}
756
+ <hm-icon-button icon="trash" [label]="'Excluir ' + doc.name" (clicked)="remove(doc)" />
757
+ </li>
758
+ }
759
+ </ul>
760
+
761
+ <!-- 2. Zona simples: recebe e o app decide -->
762
+ <div class="drop" hmDropZone="Anexar ao pedido" hmDropZoneAccepts="doc" (dropped)="attach($event)">
763
+ Solte aqui para anexar ({{ selected().length }})
764
+ </div>
765
+
766
+ <!-- 3. Lista fechada: só reordena, pela alça; nada sai dela -->
767
+ <ol class="docs" [(hmSortable)]="steps" hmSortableLabel="Etapas do processo">
768
+ @for (step of steps(); track step.id) {
769
+ <li class="docs__item" [hmDraggable]="step" [hmDragContained]="true">
770
+ <button type="button" hmDragHandle [attr.aria-label]="'Mover ' + step.title">⠿</button>
771
+ {{ step.title }}
772
+ </li>
773
+ }
774
+ </ol>
775
+ ```
776
+
777
+ ```scss
778
+ .docs { display: grid; gap: var(--hm-space-xs); padding: 0; list-style: none; }
779
+ .docs__item { display: flex; align-items: center; gap: var(--hm-space-sm); padding: var(--hm-space-xs) var(--hm-space-sm);
780
+ border: var(--hm-border-hairline) solid var(--hm-border); border-radius: var(--hm-radius); background: var(--hm-surface-raised); }
781
+ .drop { padding: var(--hm-space-lg); border: var(--hm-border-thin) dashed var(--hm-border); border-radius: var(--hm-radius); }
782
+ .drop.hm-drop-zone--active { border-color: var(--hm-accent); }
783
+ .drop.hm-drop-zone--over { background: var(--hm-accent-subtle); }
784
+ @media (forced-colors: active) { .drop.hm-drop-zone--over { border-color: Highlight; } }
785
+ ```
786
+
787
+ - `[(hmSortable)]` recebe a lista nova **ao soltar**; o `@for` tem de percorrer a mesma lista, na mesma ordem.
788
+ Listas com o mesmo `hmSortableGroup` trocam itens entre si (a base do kanban).
789
+ - `hmDragContained` prende o item à própria lista: nem zonas sem filtro nem listas do grupo o recebem.
790
+ - Com `[hmDragHandle]`, só a alça pega (e é ela que recebe foco e ARIA); sem alça, o item inteiro vira botão
791
+ focável e o toque precisa de toque longo (`hmDragTouchDelay`, 250 ms) para não brigar com a rolagem.
792
+ - `hmDropZone` é o nome da zona nos anúncios ("Contrato.pdf sobre Anexar ao pedido"); `hmSortableLabel`, o da
793
+ lista. Sem nome, o leitor anuncia algo genérico.
794
+ - Destino que depende de onde o ponteiro está (metade esquerda/direita, borda): `(overPoint)` na zona traz
795
+ `offset` e `rect` (`offset.x / rect.width`). Só ponteiro — pelo teclado não há ponto.
796
+ - Prévia e marcador próprios: `<ng-template hmDragPreview let-data>` dentro do item e
797
+ `<ng-template hmDragPlaceholder let-data>` dentro da lista.
798
+ - Para "a pessoa define a ordem" num formulário, prefira o pronto `hm-reorder-list`. Toda ação de arrastar
799
+ precisa de um caminho por clique simples também (botão Excluir acima, "Mover para…") — WCAG 2.5.7.
800
+
801
+ ## 17. Árvore: mover nó, menu por nó e "carregar mais"
802
+
803
+ ```ts
804
+ import { HttpClient } from '@angular/common/http';
805
+ import { Component, inject, signal } from '@angular/core';
806
+ import {
807
+ HermesToastService, MenuItem, TreeCanDrop, TreeChildrenLoader, TreeComponent, TreeMoveEvent, TreeNode,
808
+ TreeNodeActionEvent, TreeNodeActions,
809
+ } from '@trismegisto/angular';
810
+ import { moveTreeNode, treeAcceptsChildren } from '@trismegisto/primitives';
811
+
812
+ @Component({
813
+ selector: 'app-folders',
814
+ imports: [TreeComponent],
815
+ templateUrl: './folders.html',
816
+ })
817
+ export class Folders {
818
+ private readonly http = inject(HttpClient);
819
+ private readonly api = inject(FoldersApi); // serviço do app
820
+ private readonly toast = inject(HermesToastService);
821
+
822
+ // ── A. árvore inteira no app: arrastar para reorganizar + menu por nó
823
+ protected readonly nodes = signal<readonly TreeNode[]>([]);
824
+ protected readonly expanded = signal<ReadonlySet<string>>(new Set());
825
+
826
+ /** Substitui a regra padrão: repita o "dentro só em pasta" (treeAcceptsChildren) e some a sua. */
827
+ protected readonly canDrop: TreeCanDrop = (node, target, position) =>
828
+ (position !== 'inside' || treeAcceptsChildren(target)) && !(target.data as { locked?: boolean })?.locked;
829
+
830
+ protected onMoved(event: TreeMoveEvent): void {
831
+ const before = this.nodes();
832
+ this.nodes.set(moveTreeNode(before, event.node.id, event.target.id, event.position)); // a árvore não muda sozinha
833
+ this.api.move(event.node.id, event.to.parentId, event.to.index).catch(() => {
834
+ this.nodes.set(before);
835
+ this.toast.error(`Não foi possível mover ${event.node.label}.`);
836
+ });
837
+ }
838
+
839
+ private readonly folderActions: readonly MenuItem[] = [
840
+ { id: 'rename', label: 'Renomear', icon: 'pencil' },
841
+ { id: 'new', label: 'Nova subpasta', icon: 'plus' },
842
+ { id: 'delete', label: 'Excluir', icon: 'trash', danger: true, separatorAbove: true },
843
+ ];
844
+ /** Por nó: pasta tem "Nova subpasta"; arquivo não. */
845
+ protected readonly actions: TreeNodeActions = (node) =>
846
+ treeAcceptsChildren(node) ? this.folderActions : this.folderActions.filter((a) => a.id !== 'new');
847
+
848
+ protected onNodeAction({ id, node }: TreeNodeActionEvent): void { /* abre o fluxo do app */ }
849
+
850
+ // ── B. filhos sob demanda, paginados: "Carregar mais" e "Tentar de novo" vêm prontos
851
+ protected readonly roots = signal<readonly TreeNode[]>([{ id: 'srv', label: 'Servidores', expandable: true }]);
852
+
853
+ protected readonly loadChildren: TreeChildrenLoader = (node, { offset }) =>
854
+ this.http.get<{ children: TreeNode[]; hasMore: boolean }>(`/api/tree/${node.id}/children`, {
855
+ params: { offset, limit: 50 },
856
+ }); // erro do Observable = erro no nó com "Tentar de novo"
857
+ }
858
+ ```
859
+
860
+ ```html
861
+ <hm-tree label="Pastas" [nodes]="nodes()" [selectable]="false" [(expanded)]="expanded"
862
+ [draggable]="true" [canDrop]="canDrop" (moved)="onMoved($event)"
863
+ [nodeActions]="actions" (nodeAction)="onNodeAction($event)" />
864
+
865
+ <hm-tree label="Inventário" [nodes]="roots()" selectionMode="single" [loadChildren]="loadChildren" />
866
+ ```
867
+
868
+ - `moved` traz `node`, `target`, `position` (`before`/`inside`/`after`), `from`/`to` (`{ parentId, index }`) e
869
+ `via`. O hm-tree **não** muda `nodes`: aplique com `moveTreeNode` (ou recarregue do servidor).
870
+ - `canDrop` próprio **substitui** a regra padrão: sem `treeAcceptsChildren`, a pessoa consegue soltar "dentro"
871
+ de um arquivo.
872
+ - Filhos vindos de `loadChildren` moram dentro da árvore, não no seu `nodes`: `moveTreeNode` não os acha.
873
+ Árvore paginada que também move nó: persista no servidor e recarregue o ramo.
874
+ - Teclado do arrasto: Espaço pega (Ctrl+Espaço quando o Espaço já seleciona), ↑/↓ destino, ←/→ nível,
875
+ Enter solta, Esc cancela. Menu do nó: botão direito, Shift+F10 ou tecla Menu.
876
+ - Menu de contexto é atalho: as mesmas ações precisam existir num caminho visível (barra acima da árvore
877
+ agindo no nó ativo, painel de detalhe).
878
+ - Página do carregador: `{ children, hasMore }`; `context.offset` = quantos já chegaram. Lista inteira (array)
879
+ também vale. O foco vai para o primeiro item novo e a chegada é anunciada.
880
+
881
+ ## 18. Agenda buscando por período no servidor
882
+
883
+ ```ts
884
+ import { HttpClient } from '@angular/common/http';
885
+ import { Component, inject, signal } from '@angular/core';
886
+ import { toSignal } from '@angular/core/rxjs-interop';
887
+ import { Subject, catchError, of, switchMap } from 'rxjs';
888
+ import {
889
+ CalendarEvent, EventCalendarComponent, EventCalendarDateClick, EventCalendarRangeChange, EventCalendarView,
890
+ HermesToastService, IsoDate,
891
+ } from '@trismegisto/angular';
892
+
893
+ @Component({
894
+ selector: 'app-maintenance-calendar',
895
+ imports: [EventCalendarComponent],
896
+ templateUrl: './maintenance-calendar.html',
897
+ })
898
+ export class MaintenanceCalendar {
899
+ private readonly http = inject(HttpClient);
900
+ private readonly toast = inject(HermesToastService);
901
+
902
+ protected readonly view = signal<EventCalendarView>('month');
903
+ protected readonly date = signal<IsoDate>('2026-10-03'); // ou omita: começa em hoje
904
+ private readonly range$ = new Subject<EventCalendarRangeChange>();
905
+
906
+ /** Cada troca de período/visão cancela a busca anterior (switchMap). */
907
+ protected readonly events = toSignal(
908
+ this.range$.pipe(
909
+ switchMap(({ start, end }) =>
910
+ this.http.get<CalendarEvent[]>('/api/maintenances', { params: { start, end } }).pipe( // end é exclusivo
911
+ catchError(() => {
912
+ this.toast.error('Não foi possível carregar a agenda.');
913
+ return of([] as CalendarEvent[]);
914
+ }),
915
+ ),
916
+ ),
917
+ ),
918
+ { initialValue: [] as CalendarEvent[] },
919
+ );
920
+
921
+ protected onRange(range: EventCalendarRangeChange): void { this.range$.next(range); }
922
+ protected open(event: CalendarEvent): void { /* detalhe no drawer/modal do app */ }
923
+ protected create({ date, time }: EventCalendarDateClick): void { /* novo evento em date, às time (ou dia inteiro) */ }
924
+ }
925
+ ```
926
+
927
+ ```html
928
+ <hm-event-calendar label="Janelas de manutenção" [events]="events()" [(view)]="view" [(date)]="date"
929
+ timeZone="America/Sao_Paulo"
930
+ (rangeChange)="onRange($event)" (eventClick)="open($event)" (dateClick)="create($event)" />
931
+ ```
932
+
933
+ ```ts
934
+ // formato de CalendarEvent que o backend devolve
935
+ { id: '42', title: 'Troca de switch', start: '2026-10-12T22:00:00Z', end: '2026-10-13T02:00:00Z', color: 3 }
936
+ { id: '43', title: 'Congelamento de mudanças', start: '2026-10-20', end: '2026-10-24' } // dia inteiro, fim inclusivo
937
+ ```
938
+
939
+ - `rangeChange` sai também na primeira pintura: não busque no `ngOnInit` em paralelo. O fim do intervalo é
940
+ **exclusivo** (`{ start: '2026-10-01', end: '2026-11-01' }` = outubro).
941
+ - `start`/`end`: ISO com offset é instante (convertido para `timeZone`); sem offset é hora de parede; só data =
942
+ dia inteiro, e aí o `end` é a **última data, inclusiva**. Evento com hora sem `end` dura 1 h.
943
+ - `color` é 1–8 da paleta categórica (`--hm-data-categorical-*`), nunca hex. Se a cor quer dizer algo
944
+ (tipo de manutenção), ponha a legenda ao lado (`hm-legend`) e a informação no título — cor sozinha não basta.
945
+ - `view="list"` é a alternativa acessível (dias com lista de botões); deixe-a nas `views`. Abaixo de
946
+ `compactBelow` px de largura, semana vira lista e mês fica compacto sozinho.
947
+ - `dateClick.time` vem `'HH:mm'` quando o clique foi na grade de horas, `null` no mês.
948
+
949
+ ## 19. Entrada em lote validando IP ou CPF
950
+
951
+ ```ts
952
+ import { Component, computed, signal } from '@angular/core';
953
+ import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
954
+ import { BulkInputComponent, BulkParseResult, BulkValidator, ButtonComponent } from '@trismegisto/angular';
955
+
956
+ const IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
957
+
958
+ /** Dígitos verificadores do CPF (aceita com ou sem pontuação). */
959
+ function isCpf(text: string): boolean {
960
+ const d = text.replace(/\D/g, '');
961
+ if (d.length !== 11 || /^(\d)\1{10}$/.test(d)) return false;
962
+ const digit = (len: number) => {
963
+ const sum = [...d.slice(0, len)].reduce((acc, n, i) => acc + Number(n) * (len + 1 - i), 0);
964
+ return ((sum * 10) % 11) % 10;
965
+ };
966
+ return digit(9) === Number(d[9]) && digit(10) === Number(d[10]);
967
+ }
968
+
969
+ @Component({
970
+ selector: 'app-bulk-lookup',
971
+ imports: [ReactiveFormsModule, BulkInputComponent, ButtonComponent],
972
+ templateUrl: './bulk-lookup.html',
973
+ })
974
+ export class BulkLookup {
975
+ /** Regex: inválido com o motivo padrão do catálogo. */
976
+ protected readonly ipValidator: BulkValidator = IPV4;
977
+ /** Função: string = inválido com ESTE motivo (texto do app, já no idioma dele). */
978
+ protected readonly cpfValidator: BulkValidator = (item) => isCpf(item) || 'Dígito verificador não confere.';
979
+
980
+ protected readonly ips = new FormControl<string[]>([], { nonNullable: true, validators: Validators.required });
981
+ protected readonly cpfs = signal<string[]>([]);
982
+ protected readonly result = signal<BulkParseResult | null>(null);
983
+ protected readonly blocked = computed(() => (this.result()?.invalid.length ?? 0) > 0);
984
+
985
+ protected lookup(): void {
986
+ const digits = this.cpfs().map((cpf) => cpf.replace(/\D/g, '')); // normalize antes de mandar
987
+ // chamada ao backend com this.ips.value e digits…
988
+ }
989
+ }
990
+ ```
991
+
992
+ ```html
993
+ <hm-bulk-input label="Endereços IP" [formControl]="ips" [validate]="ipValidator" [max]="500"
994
+ hint="Cole da planilha: um por linha, ou separados por vírgula ou ponto e vírgula." />
995
+
996
+ <hm-bulk-input label="CPFs" [(value)]="cpfs" [validate]="cpfValidator" [max]="200"
997
+ (parsed)="result.set($event)" />
998
+
999
+ <hm-button [disabled]="blocked()" (clicked)="lookup()">Consultar {{ cpfs().length }}</hm-button>
1000
+ ```
1001
+
1002
+ - O valor é só o `string[]` dos **válidos, sem repetição**; inválidos aparecem listados com o motivo (e saem no
1003
+ ×), repetidos são contados. `(parsed)` traz `{ valid, invalid, duplicates }` para o app decidir se bloqueia.
1004
+ - Repetido compara o texto como foi digitado: `123.456.789-09` e `12345678909` contam como dois. Se importa,
1005
+ normalize no `validate`/no envio. `textCase="lower"` + `ignoreCaseDuplicates` para e-mails e hostnames.
1006
+ - `separators` padrão: quebra de linha, vírgula, ponto e vírgula e tab; acrescente `'space'` se precisar.
1007
+ - O resumo é anunciado só depois de uma pausa na digitação (`announceDelay`), nunca a cada tecla.
1008
+ - Não procura nada na base: quem consulta é o app. Para escolher entre opções conhecidas, `hm-combobox-multi`.
1009
+
1010
+ ## 20. Data grid com rolagem virtual, coluna fixa e seleção única
1011
+
1012
+ ```ts
1013
+ import { Component, computed, signal } from '@angular/core';
1014
+ import { DataGridColumn, DataGridComponent, GridSelection } from '@trismegisto/angular';
1015
+
1016
+ interface Host { id: string; hostname: string; ip: string; site: string; os: string; owner: string; status: string; }
1017
+
1018
+ @Component({
1019
+ selector: 'app-hosts',
1020
+ imports: [DataGridComponent],
1021
+ templateUrl: './hosts.html',
1022
+ })
1023
+ export class Hosts {
1024
+ protected readonly rows = signal<readonly Host[]>([]); // milhares de linhas
1025
+ protected readonly rowId = (row: Host) => row.id;
1026
+ protected readonly selection = signal<GridSelection>(new Set());
1027
+ protected readonly chosen = computed(() => this.rows().find((r) => this.selection().has(r.id)) ?? null);
1028
+
1029
+ protected readonly columns: readonly DataGridColumn<Host>[] = [
1030
+ { key: 'hostname', title: 'Hostname', value: (r) => r.hostname, sortable: true, pinned: 'start', initialWidth: '14rem' },
1031
+ { key: 'ip', title: 'IP', value: (r) => r.ip },
1032
+ { key: 'site', title: 'Site', value: (r) => r.site, sortable: true },
1033
+ { key: 'os', title: 'Sistema', value: (r) => r.os },
1034
+ { key: 'owner', title: 'Responsável', value: (r) => r.owner },
1035
+ { key: 'status', title: 'Situação', value: (r) => r.status, pinned: 'end' },
1036
+ ];
1037
+
1038
+ protected readonly decommissioned = (row: Host) => row.status !== 'Desativado';
1039
+ protected readonly whyLocked = () => 'Host desativado não pode ser escolhido.';
1040
+ }
1041
+ ```
1042
+
1043
+ ```html
1044
+ <hm-data-grid caption="Hosts" [columns]="columns" [rows]="rows()" [rowId]="rowId"
1045
+ [virtual]="true" [paginated]="false" [rowHeight]="40" maxHeight="32rem"
1046
+ selectionMode="single" [(selection)]="selection"
1047
+ [rowSelectable]="decommissioned" [rowSelectableReason]="whyLocked"
1048
+ [columnManager]="true" persistKey="hosts" />
1049
+
1050
+ <p>Escolhido: {{ chosen()?.hostname ?? 'nenhum' }}</p>
1051
+ ```
1052
+
1053
+ - `virtual` desenha só as linhas visíveis; use com `[paginated]="false"`. `rowHeight` é estimativa (as linhas
1054
+ reais são medidas). Sem `maxHeight` nem `fillHeight`, a área tem 32rem.
1055
+ - `pinned: 'start' | 'end'` na coluna fixa ao rolar de lado; a pessoa também fixa/desafixa pelo
1056
+ `columnManager`, e o estado vai em `[(pinnedColumns)]` (persiste com `persistKey`). Fixe só a coluna-chave:
1057
+ colunas fixas demais comem a área rolável no celular.
1058
+ - `selectionMode="single"`: rádio por linha com nome comum, setas trocam a linha marcada (inclusive fora da
1059
+ janela virtual), clique na linha seleciona. `selection` continua sendo um `Set` (com um id no máximo).
1060
+ - `rowSelectable` trava linhas (controle desativado, fora do Tab); o motivo de `rowSelectableReason` vira
1061
+ descrição do controle.
1062
+ - A área rolável já é `role="region"` focável e a grade tem `aria-rowcount`/`aria-rowindex`: não envolva em
1063
+ outro contêiner com `overflow` próprio.
1064
+
1065
+ ## 21. Wizard com página de revisão automática
1066
+
1067
+ ```ts
1068
+ import { Component, inject, signal } from '@angular/core';
1069
+ import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
1070
+ import { ButtonComponent, HermesStepSummaryEntry, InputComponent, StepComponent, WizardComponent } from '@trismegisto/angular';
1071
+
1072
+ @Component({
1073
+ selector: 'app-new-server',
1074
+ imports: [ReactiveFormsModule, WizardComponent, StepComponent, InputComponent, ButtonComponent],
1075
+ templateUrl: './new-server.html',
1076
+ })
1077
+ export class NewServer {
1078
+ private readonly fb = inject(FormBuilder).nonNullable;
1079
+ protected readonly open = signal(false);
1080
+ protected readonly saving = signal(false);
1081
+ protected readonly identity = this.fb.group({ hostname: ['', Validators.required], ip: ['', Validators.required] });
1082
+ protected readonly placement = this.fb.group({ site: ['', Validators.required], rack: [''] });
1083
+
1084
+ /** Função: lida na hora em que a revisão aparece (valor atual) e vira um hm-description-list. */
1085
+ protected readonly identitySummary = (): HermesStepSummaryEntry[] => [
1086
+ { term: 'Hostname', value: this.identity.getRawValue().hostname },
1087
+ { term: 'IP', value: this.identity.getRawValue().ip },
1088
+ ];
1089
+
1090
+ protected async save(): Promise<void> { /* igual à §10: saving, api, open.set(false) só no sucesso */ }
1091
+ }
1092
+ ```
1093
+
1094
+ ```html
1095
+ <hm-wizard heading="Novo servidor" [(open)]="open" [loading]="saving()" [confirmCancel]="true"
1096
+ [summary]="true" summaryDescription="Confira antes de cadastrar." finishLabel="Cadastrar"
1097
+ (completed)="save()">
1098
+ <hm-step label="Identificação" [stepControl]="identity" [summary]="identitySummary">
1099
+ <form class="form" [formGroup]="identity">
1100
+ <hm-input label="Hostname" formControlName="hostname" />
1101
+ <hm-input label="IP" formControlName="ip" />
1102
+ </form>
1103
+ </hm-step>
1104
+ <hm-step label="Localização" [stepControl]="placement" [summary]="placementSummary">
1105
+ <form class="form" [formGroup]="placement">
1106
+ <hm-input label="Site" formControlName="site" />
1107
+ <hm-input label="Rack (opcional)" formControlName="rack" />
1108
+ </form>
1109
+ </hm-step>
1110
+ <!-- Template: conteúdo livre na revisão -->
1111
+ <ng-template #placementSummary>{{ placement.value.site }}{{ placement.value.rack ? ', rack ' + placement.value.rack : '' }}</ng-template>
1112
+ </hm-wizard>
1113
+ ```
1114
+
1115
+ - `[summary]="true"` acrescenta a etapa final "Revisão" com uma seção por `hm-step` que tenha `summary` e um
1116
+ "Editar {etapa}" que volta a ela. **Não** escreva uma etapa "Revisão" à mão (como a da §10): vira duplicada.
1117
+ - `summary` aceita função (`HermesStepSummaryEntry[]` → lista termo/valor) ou `TemplateRef` (livre).
1118
+ Sem nenhuma etapa com `summary`, a página de revisão não aparece.
1119
+ - `(completed)` só sai do Concluir da revisão; o resto (validação por etapa, `confirmCancel`, `loading`) é como
1120
+ na §10.
1121
+
1122
+ ## 22. Diálogo de configurações com validação e salvamento assíncrono
1123
+
1124
+ ```ts
1125
+ import { Component, inject, signal } from '@angular/core';
1126
+ import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
1127
+ import { firstValueFrom } from 'rxjs';
1128
+ import {
1129
+ ButtonComponent, HermesSettingsCloseHandler, HermesToastService, InputComponent, SettingsDialogComponent,
1130
+ SettingsRowComponent, SettingsSectionComponent, SwitchComponent,
1131
+ } from '@trismegisto/angular';
1132
+
1133
+ @Component({
1134
+ selector: 'app-account-settings',
1135
+ imports: [ReactiveFormsModule, ButtonComponent, InputComponent, SwitchComponent, SettingsDialogComponent, SettingsSectionComponent, SettingsRowComponent],
1136
+ templateUrl: './account-settings.html',
1137
+ })
1138
+ export class AccountSettings {
1139
+ private readonly api = inject(AccountApi); // serviço do app (HttpClient)
1140
+ private readonly toast = inject(HermesToastService);
1141
+
1142
+ protected readonly open = signal(false);
1143
+ protected readonly profile = new FormGroup({ name: new FormControl('', { nonNullable: true, validators: Validators.required }) });
1144
+ protected readonly alerts = new FormGroup({
1145
+ email: new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.email] }),
1146
+ weekly: new FormControl(false, { nonNullable: true }),
1147
+ });
1148
+
1149
+ protected readonly handler: HermesSettingsCloseHandler = {
1150
+ // Só é chamado com TODAS as seções válidas. true fecha; rejeição mostra a falha no rodapé e fica aberto.
1151
+ onSubmit: async () => {
1152
+ await firstValueFrom(this.api.save({ ...this.profile.getRawValue(), ...this.alerts.getRawValue() }));
1153
+ this.toast.success('Configurações salvas.');
1154
+ return true;
1155
+ },
1156
+ // Cancelar, X e Esc. Devolver false mantém aberto.
1157
+ onCancel: () => {
1158
+ this.profile.reset();
1159
+ this.alerts.reset();
1160
+ return true;
1161
+ },
1162
+ };
1163
+ }
1164
+ ```
1165
+
1166
+ ```html
1167
+ <hm-button icon="cog" (clicked)="open.set(true)">Configurações</hm-button>
1168
+
1169
+ <hm-settings-dialog heading="Conta" [(open)]="open" [closeHandler]="handler">
1170
+ <hm-settings-section key="profile" label="Perfil" icon="user" [control]="profile">
1171
+ <form [formGroup]="profile">
1172
+ <hm-settings-row label="Nome de exibição" description="Aparece no cabeçalho e nos comentários." [stacked]="true">
1173
+ <hm-input label="Nome de exibição" [labelHidden]="true" formControlName="name" />
1174
+ </hm-settings-row>
1175
+ </form>
1176
+ </hm-settings-section>
1177
+
1178
+ <hm-settings-section key="alerts" label="Notificações" icon="bell" [control]="alerts">
1179
+ <form [formGroup]="alerts">
1180
+ <hm-settings-row label="E-mail para avisos" [stacked]="true">
1181
+ <hm-input label="E-mail para avisos" [labelHidden]="true" type="email" formControlName="email" />
1182
+ </hm-settings-row>
1183
+ <hm-settings-row label="Resumo semanal">
1184
+ <hm-switch label="Resumo semanal" formControlName="weekly" />
1185
+ </hm-settings-row>
1186
+ </form>
1187
+ </hm-settings-section>
1188
+ </hm-settings-dialog>
1189
+ ```
1190
+
1191
+ - Com `closeHandler` (ou `actions`) o diálogo entra no **modo formulário**: rodapé Cancelar/Salvar
1192
+ (`submitLabel`/`cancelLabel`) e clicar fora não fecha. Sem ele, cada mudança vale na hora e clicar fora fecha.
1193
+ - `[control]` (um `FormGroup` por seção) ou `[invalid]`: seção inválida ganha marca e "Com erro" na navegação;
1194
+ o Salvar abre a primeira inválida e foca o campo. **Não valide dentro do `onSubmit`**.
1195
+ - Enquanto `onSubmit` espera, Salvar carrega e Cancelar/X/Esc travam. `(submitted)` sai depois de fechar.
1196
+ - `hm-settings-row` já dá o rótulo visível da linha: no controle dentro dela, `labelHidden` (o rótulo continua
1197
+ para o leitor de tela). `keywords` na linha/seção alimenta a busca da navegação.
1198
+
1199
+ ## 23. Drawer fixado com formulário, legenda de obrigatório e barra de ações fixa
1200
+
1201
+ ```ts
1202
+ import { Component, inject, signal } from '@angular/core';
1203
+ import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
1204
+ import { ButtonComponent, DrawerComponent, FormRequiredHintComponent, HermesDialogService, InputComponent, TextareaComponent } from '@trismegisto/angular';
1205
+
1206
+ @Component({
1207
+ selector: 'app-server-editor',
1208
+ imports: [ReactiveFormsModule, DrawerComponent, FormRequiredHintComponent, InputComponent, TextareaComponent, ButtonComponent],
1209
+ templateUrl: './server-editor.html',
1210
+ styleUrl: './server-editor.scss',
1211
+ })
1212
+ export class ServerEditor {
1213
+ private readonly dialogs = inject(HermesDialogService);
1214
+ protected readonly editing = signal(false);
1215
+ protected readonly saving = signal(false);
1216
+ protected readonly form = inject(FormBuilder).nonNullable.group({
1217
+ hostname: ['', Validators.required],
1218
+ ip: ['', Validators.required],
1219
+ notes: [''],
1220
+ });
1221
+
1222
+ /** X/Esc com alteração pendente pergunta antes. */
1223
+ protected readonly confirmDiscard = () =>
1224
+ this.form.pristine ||
1225
+ this.dialogs.confirm({ heading: 'Descartar alterações?', message: 'O que foi editado será perdido.', danger: true });
1226
+
1227
+ protected async save(): Promise<void> {
1228
+ if (this.form.invalid) { this.form.markAllAsTouched(); return; }
1229
+ this.saving.set(true);
1230
+ try { /* api… */ this.form.markAsPristine(); this.editing.set(false); } finally { this.saving.set(false); }
1231
+ }
1232
+ }
1233
+ ```
1234
+
1235
+ ```html
1236
+ <div class="editor">
1237
+ <section class="editor__list"><!-- grade/lista; o botão "Editar" faz editing.set(true) --></section>
1238
+
1239
+ <hm-drawer heading="Editar servidor" [(open)]="editing" [pinned]="true" [beforeClose]="confirmDiscard">
1240
+ <form class="hm-form" [formGroup]="form" (ngSubmit)="save()">
1241
+ <hm-form-required-hint />
1242
+ <hm-input label="Hostname" formControlName="hostname" />
1243
+ <hm-input label="IP" formControlName="ip" />
1244
+ <hm-textarea label="Observações" formControlName="notes" />
1245
+
1246
+ <div class="hm-form-actions hm-form-actions--sticky">
1247
+ <hm-button emphasis="minimal" type="button" (clicked)="editing.set(false)">Cancelar</hm-button>
1248
+ <hm-button type="submit" [loading]="saving()">Salvar</hm-button>
1249
+ </div>
1250
+ </form>
1251
+ </hm-drawer>
1252
+ </div>
1253
+ ```
1254
+
1255
+ ```scss
1256
+ .editor { display: flex; gap: var(--hm-space-md); min-block-size: 0; }
1257
+ .editor__list { flex: 1; min-inline-size: 0; }
1258
+ ```
1259
+
1260
+ - `pinned`: o painel entra no layout (empurra o conteúdo, sem véu), vira `role="complementary"` nomeado pelo
1261
+ `heading` e não prende o foco. A ordem no DOM é a ordem de leitura: ponha-o depois da lista, num contêiner
1262
+ flex. No celular, prefira o modal (`[pinned]="false"`, ou `position="bottom"`) escolhido por breakpoint
1263
+ (`hermesMediaQuery('md', 'down')`).
1264
+ - O botão Cancelar com `editing.set(false)` muda `[(open)]` por código, e isso **não** passa pelo `beforeClose`
1265
+ (só X/Esc/fundo passam): se precisar perguntar, chame `confirmDiscard()` antes.
1266
+ - `.hm-form-actions--sticky` prende os botões no rodapé do que rola, dentro do `<form>` (o submit continua
1267
+ funcionando com Enter) e já dá `scroll-margin` aos campos para o foco não ficar por baixo da barra (WCAG
1268
+ 2.4.11). `--spread` separa um "Excluir" à esquerda.
1269
+ - `hm-form-required-hint` vai antes do primeiro campo e cita a mesma marca que os campos mostram; não substitui o
1270
+ `Validators.required` de cada um. Use `.hm-form--horizontal` para rótulo ao lado (por largura do próprio form).
1271
+
1272
+ ## 24. Paleta de comandos e busca global
1273
+
1274
+ ```ts
1275
+ import { HttpClient } from '@angular/common/http';
1276
+ import { Component, inject, signal } from '@angular/core';
1277
+ import { Router } from '@angular/router';
1278
+ import { firstValueFrom, fromEvent, takeUntil } from 'rxjs';
1279
+ import {
1280
+ CommandPaletteComponent, GlobalSearchComponent, HeaderComponent, HermesCommand, HermesSearchFn,
1281
+ HermesSearchGroup, HermesSearchSelection, HermesThemeService,
1282
+ } from '@trismegisto/angular';
1283
+
1284
+ // no shell
1285
+ @Component({
1286
+ selector: 'app-shell',
1287
+ imports: [HeaderComponent, CommandPaletteComponent, GlobalSearchComponent],
1288
+ templateUrl: './shell.html',
1289
+ })
1290
+ export class Shell {
1291
+ private readonly router = inject(Router);
1292
+ private readonly http = inject(HttpClient);
1293
+ private readonly theme = inject(HermesThemeService);
1294
+
1295
+ protected readonly paletteOpen = signal(false);
1296
+ protected readonly searchOpen = signal(false);
1297
+ protected readonly recent = signal<readonly string[]>([]); // guarde entre sessões se quiser
1298
+
1299
+ protected readonly commands: readonly HermesCommand[] = [
1300
+ { id: 'go-servers', label: 'Ir para Servidores', group: 'Navegação', icon: 'rack-server', run: () => this.router.navigate(['/servidores']) },
1301
+ { id: 'new-server', label: 'Novo servidor', group: 'Ações', icon: 'plus', keywords: ['cadastrar', 'host'], run: () => this.router.navigate(['/servidores/novo']) },
1302
+ { id: 'export', label: 'Exportar inventário', group: 'Ações', keywords: ['csv', 'excel'],
1303
+ run: () => firstValueFrom(this.http.post('/api/inventory/export', {})) }, // Promise: carrega no item; rejeição anuncia
1304
+ { id: 'theme', label: 'Alternar tema claro/escuro', group: 'Preferências', run: () => this.theme.toggle() },
1305
+ ];
1306
+
1307
+ /** Várias fontes num pedido só; o `signal` aborta quando o termo muda. */
1308
+ protected readonly search: HermesSearchFn = (term, signal) =>
1309
+ firstValueFrom(
1310
+ this.http.get<HermesSearchGroup[]>('/api/search', { params: { q: term } }).pipe(takeUntil(fromEvent(signal, 'abort'))),
1311
+ );
1312
+
1313
+ protected go({ result }: HermesSearchSelection): void {
1314
+ this.router.navigateByUrl(result.data as string); // `data` é livre: aqui, a rota do resultado
1315
+ }
1316
+ }
1317
+ ```
1318
+
1319
+ ```html
1320
+ <hm-header (searchRequested)="paletteOpen.set(true)">
1321
+ <span actions><!-- … --></span>
1322
+ </hm-header>
1323
+
1324
+ <!-- Ctrl/⌘ K já vem do hm-header (searchRequested): não repita shortcut="Mod+K" aqui -->
1325
+ <hm-command-palette [(open)]="paletteOpen" [commands]="commands" [recentLimit]="5" [(recentIds)]="recent" />
1326
+
1327
+ <hm-global-search [(open)]="searchOpen" [search]="search" shortcut="Mod+Shift+F" [minLength]="2" (selected)="go($event)" />
1328
+ ```
1329
+
1330
+ - O `hm-header` já escuta Ctrl/⌘ K e emite `(searchRequested)`. Sem `hm-header`, dê `shortcut="Mod+K"` à paleta.
1331
+ O mesmo atalho nos dois alterna abrir/fechar duas vezes.
1332
+ - `HermesCommand.shortcut` é só exibição: a tecla é registrada por quem executa (`hmShortcut`/serviço, §13).
1333
+ - `run` com `Promise`: o item mostra carregando e a paleta só fecha depois; se rejeitar, fica aberta e anuncia.
1334
+ - Busca global: espera `debounce` (250 ms), aborta a consulta anterior e ignora resposta atrasada; carregando,
1335
+ vazio e erro com "Tentar de novo" já vêm prontos. Devolva grupos (`{ id, label, results }`) por fonte.
1336
+ - As duas são combobox em diálogo modal: `Esc` fecha e devolve o foco a quem abriu. Não abra uma de dentro do
1337
+ `run` da outra (o fechamento devolve o foco por cima da que abriu).
1338
+
1339
+ ## 25. Alertas do sistema (banner) e toast com "Desfazer"
1340
+
1341
+ ```html
1342
+ <!-- no topo do shell, antes do conteúdo -->
1343
+ <hm-alert-group label="Avisos do sistema">
1344
+ <hm-alert appearance="banner" variant="warning" heading="Manutenção programada"
1345
+ [closable]="true" dismissKey="manutencao-2026-10-12">
1346
+ O sistema fica fora do ar no domingo, das 2h às 4h.
1347
+ <hm-button actions emphasis="minimal" size="small" (clicked)="openDetails()">Ver detalhes</hm-button>
1348
+ </hm-alert>
1349
+ <hm-alert appearance="banner" variant="info" [closable]="true" dismissKey="versao-0-2"
1350
+ link="/novidades" linkLabel="Ver novidades">
1351
+ Nova versão disponível.
1352
+ </hm-alert>
1353
+ </hm-alert-group>
1354
+ ```
1355
+
1356
+ ```ts
1357
+ import { inject, signal } from '@angular/core';
1358
+ import { HermesToastService } from '@trismegisto/angular';
1359
+
1360
+ const UNDO_MS = 10_000;
1361
+
1362
+ // numa tela de listagem
1363
+ private readonly toast = inject(HermesToastService);
1364
+ protected readonly rows = signal<readonly Server[]>([]);
1365
+
1366
+ protected remove(server: Server): void {
1367
+ const before = this.rows();
1368
+ this.rows.update((list) => list.filter((s) => s.id !== server.id)); // some da tela na hora
1369
+ const commit = setTimeout(() => this.api.remove(server.id), UNDO_MS); // grava depois
1370
+ this.toast.success(`${server.name} removido.`, {
1371
+ duration: UNDO_MS,
1372
+ action: { label: 'Desfazer', run: () => { clearTimeout(commit); this.rows.set(before); } },
1373
+ });
1374
+ }
1375
+ ```
1376
+
1377
+ - `hm-alert-group` mostra um alerta por vez com "1 de 3" e anterior/próximo; conta só os abertos (fechar ou um
1378
+ `dismissKey` já lembrado tira da conta). Com um só, o paginador some; sem nenhum, a faixa some.
1379
+ - Escreva os `hm-alert` direto dentro do grupo (filhos diretos do template): é assim que o grupo os encontra.
1380
+ - `dismissKey` lembra o fechamento em `localStorage`; troque a chave quando o aviso mudar (data no nome).
1381
+ - Papel ARIA: `variant="error"` é `role="alert"` (interrompe); os demais, `role="status"`. O banner não ganha
1382
+ `role="banner"`. `heading` não é `<h*>` — não entra no sumário de títulos.
1383
+ - Toast com `action`: sem `duration`, fica pelo menos 10 s e pausa com foco/ponteiro na pilha. Desfazer é
1384
+ conveniência, não proteção: ação irreversível de verdade pede confirmação antes (§4).
1385
+ - Resultado de uma ação vai no toast; aviso que precisa ficar na tela (do sistema, de um formulário) vai no `hm-alert`.
1386
+
1387
+ ## 26. Visualizador de certificado
1388
+
1389
+ ```ts
1390
+ import { Component, computed, input, signal } from '@angular/core';
1391
+ import { CertificateInfo, CertificateViewerComponent, TagComponent, certificateValidity } from '@trismegisto/angular';
1392
+
1393
+ @Component({
1394
+ selector: 'app-tls-detail',
1395
+ imports: [CertificateViewerComponent, TagComponent],
1396
+ templateUrl: './tls-detail.html',
1397
+ })
1398
+ export class TlsDetail {
1399
+ /** Já interpretado pelo servidor (ou por pkijs no app): o componente não lê PEM/DER. Final em [0], raiz no fim. */
1400
+ readonly chain = input.required<readonly CertificateInfo[]>();
1401
+ protected readonly selected = signal(0);
1402
+
1403
+ /** A mesma regra de validade do componente, para uma coluna de listagem ou um alerta. */
1404
+ protected readonly leafState = computed(() => {
1405
+ const leaf = this.chain()[0];
1406
+ return leaf ? certificateValidity(leaf.notBefore, leaf.notAfter, { warningDays: 60 }).state : null;
1407
+ });
1408
+ }
1409
+ ```
1410
+
1411
+ ```html
1412
+ @if (leafState() === 'expiring') {
1413
+ <hm-tag name="Vence em breve" color="warning" />
1414
+ }
1415
+ <hm-certificate-viewer [chain]="chain()" [(selectedIndex)]="selected" [headingLevel]="2" [warningDays]="60" />
1416
+ ```
1417
+
1418
+ ```ts
1419
+ // formato esperado (CertificateInfo)
1420
+ {
1421
+ subject: { commonName: 'api.exemplo.org.br', organization: 'Organização Exemplo' },
1422
+ issuer: { commonName: 'AC Intermediária' },
1423
+ serialNumber: '0A:1B:2C:3D', notBefore: '2026-01-10T00:00:00Z', notAfter: '2026-12-10T23:59:59Z',
1424
+ signatureAlgorithm: 'SHA256withRSA', publicKeyAlgorithm: 'RSA 2048 bits',
1425
+ fingerprints: { sha256: 'AB:CD:…' },
1426
+ subjectAltNames: [{ type: 'dns', value: 'api.exemplo.org.br' }],
1427
+ }
1428
+ ```
1429
+
1430
+ - Um certificado só: `[certificate]`. Cadeia: `[chain]` do final (`[0]`) até a raiz; a lista aparece da raiz
1431
+ para o final e o escolhido tem `aria-current`.
1432
+ - `headingLevel` encaixa o título na hierarquia da página (as seções usam o nível seguinte). Dois
1433
+ visualizadores na mesma tela funcionam (seções são `group`, não `region`).
1434
+ - A situação (válido, vence em N dias, vencido, ainda não válido) sai numa etiqueta com **texto**, não só cor;
1435
+ `referenceDate` fixa a data de referência (útil em teste). Datas seguem o idioma do `HermesI18nService`.
1436
+ - `certificateValidity` devolve `{ state, days }` com a mesma regra — use-a em vez de recalcular a validade.
1437
+
1438
+ ## 27. Página de login (local e SSO)
1439
+
1440
+ Não é componente: classes `.hm-login` do `@trismegisto/core` com `hm-input`/`hm-button`.
1441
+
1442
+ ```ts
1443
+ import { Component, ElementRef, Injector, afterNextRender, inject, signal, viewChild } from '@angular/core';
1444
+ import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
1445
+ import { ButtonComponent, CheckboxComponent, IconComponent, InputComponent } from '@trismegisto/angular';
1446
+
1447
+ @Component({
1448
+ selector: 'app-login',
1449
+ imports: [ReactiveFormsModule, ButtonComponent, CheckboxComponent, IconComponent, InputComponent],
1450
+ templateUrl: './login.html',
1451
+ })
1452
+ export class Login {
1453
+ private readonly injector = inject(Injector);
1454
+ private readonly auth = inject(AuthService); // serviço do app
1455
+ private readonly errorBox = viewChild<ElementRef<HTMLElement>>('loginError');
1456
+ private readonly formEl = viewChild<ElementRef<HTMLFormElement>>('loginForm');
1457
+
1458
+ protected readonly form = inject(FormBuilder).nonNullable.group({
1459
+ username: ['', Validators.required],
1460
+ password: ['', Validators.required],
1461
+ remember: [false],
1462
+ });
1463
+ protected readonly sending = signal(false);
1464
+ protected readonly failed = signal(false);
1465
+
1466
+ protected async submit(): Promise<void> {
1467
+ this.failed.set(false);
1468
+ if (this.form.invalid) {
1469
+ this.form.markAllAsTouched(); // erro em cada campo
1470
+ afterNextRender(() => this.formEl()?.nativeElement.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus(), { injector: this.injector });
1471
+ return;
1472
+ }
1473
+ this.sending.set(true);
1474
+ try {
1475
+ await this.auth.login(this.form.getRawValue());
1476
+ } catch {
1477
+ this.failed.set(true);
1478
+ this.form.controls.password.reset();
1479
+ afterNextRender(() => this.errorBox()?.nativeElement.focus(), { injector: this.injector }); // leitor anuncia, teclado parte dali
1480
+ } finally {
1481
+ this.sending.set(false);
1482
+ }
1483
+ }
1484
+ }
1485
+ ```
1486
+
1487
+ ```html
1488
+ <main class="hm-login">
1489
+ <section class="hm-login__panel" aria-labelledby="login-title">
1490
+ <div class="hm-login__brand"><img src="logo.svg" alt="" /> Integrações</div>
1491
+ <header class="hm-login__header">
1492
+ <h1 id="login-title" class="hm-login__title">Entrar</h1>
1493
+ <p class="hm-login__subtitle">Use sua conta da organização.</p>
1494
+ </header>
1495
+
1496
+ @if (failed()) {
1497
+ <div #loginError class="hm-login__error" role="alert" tabindex="-1">
1498
+ <hm-icon shape="exclamation-circle" />
1499
+ <p>Usuário ou senha incorretos. Confira e tente de novo.</p>
1500
+ </div>
1501
+ }
1502
+
1503
+ <form #loginForm class="hm-login__form" novalidate [formGroup]="form" (ngSubmit)="submit()">
1504
+ <hm-input label="Usuário" autocomplete="username" formControlName="username" [messages]="{ required: 'Informe seu usuário.' }" />
1505
+ <hm-input label="Senha" type="password" autocomplete="current-password" formControlName="password"
1506
+ [messages]="{ required: 'Informe sua senha.' }" />
1507
+ <div class="hm-login__options">
1508
+ <hm-checkbox label="Manter conectado" formControlName="remember" />
1509
+ <a href="/recuperar-senha">Esqueci minha senha</a>
1510
+ </div>
1511
+ <div class="hm-login__actions">
1512
+ <hm-button type="submit" [loading]="sending()">Entrar</hm-button>
1513
+ </div>
1514
+ </form>
1515
+
1516
+ <footer class="hm-login__footer"><a href="/ajuda">Ajuda</a> <span>© Organização Exemplo</span></footer>
1517
+ </section>
1518
+ </main>
1519
+ ```
1520
+
1521
+ SSO (só redireciona) — o mesmo cartão, com um botão; login local junto: `<div class="hm-login__divider">ou</div>`
1522
+ entre os dois.
1523
+
1524
+ ```html
1525
+ <main class="hm-login">
1526
+ <section class="hm-login__panel" aria-labelledby="sso-title">
1527
+ <div class="hm-login__brand"><img src="logo.svg" alt="" /> Integrações</div>
1528
+ <header class="hm-login__header">
1529
+ <h1 id="sso-title" class="hm-login__title">Entrar</h1>
1530
+ <p class="hm-login__subtitle">Você será levado ao login da organização.</p>
1531
+ </header>
1532
+ <div class="hm-login__actions">
1533
+ <hm-button [loading]="redirecting()" (clicked)="sso()">Entrar com SSO</hm-button> <!-- sso(): redirecting.set(true); location.assign(url) -->
1534
+ </div>
1535
+ </section>
1536
+ </main>
1537
+ ```
1538
+
1539
+ - Marca numa coluna à parte em tela larga: `.hm-login--split` com `.hm-login__aside` (some no estreito) e
1540
+ `.hm-login__main` envolvendo o cartão.
1541
+ - `autocomplete="username"` / `"current-password"` (gerenciador de senhas, WCAG 1.3.5) e rótulo visível, nunca
1542
+ só placeholder. Botão Entrar sempre habilitado: a validação acontece no envio.
1543
+ - Erro genérico ("usuário ou senha incorretos"), sem dizer qual dos dois errou. O resumo do erro recebe o foco.
1544
+ - Segundo fator: `hm-code-input`; nada de captcha em imagem.
1545
+
1546
+ ## 28. Editor de família de cor (theme builder)
1547
+
1548
+ ```ts
1549
+ import { Component, computed, signal } from '@angular/core';
1550
+ import { ButtonComponent, ThemeBuilderComponent } from '@trismegisto/angular';
1551
+ import { FamilyDraft, draftContrastInput, familyContrastChecks } from '@trismegisto/primitives';
1552
+
1553
+ @Component({
1554
+ selector: 'app-brand-colors',
1555
+ imports: [ThemeBuilderComponent, ButtonComponent],
1556
+ templateUrl: './brand-colors.html',
1557
+ })
1558
+ export class BrandColors {
1559
+ protected readonly draft = signal<FamilyDraft | null>(null);
1560
+
1561
+ /** A mesma regra AA que reprova o build dos tokens; aqui barra o "Salvar" do app. */
1562
+ protected readonly failures = computed(() => {
1563
+ const draft = this.draft();
1564
+ return draft ? familyContrastChecks(draftContrastInput(draft)).filter((c) => !c.pass) : [];
1565
+ });
1566
+
1567
+ protected save(): void { /* manda this.draft() ao servidor do app */ }
1568
+ }
1569
+ ```
1570
+
1571
+ ```html
1572
+ <hm-theme-builder baseFamily="poseidon" [exportFormats]="['typescript', 'css']" [headingLevel]="2"
1573
+ (draftChange)="draft.set($event)" />
1574
+
1575
+ <hm-button [disabled]="!draft() || failures().length > 0" (clicked)="save()">Salvar família</hm-button>
1576
+ ```
1577
+
1578
+ - O builder parte de uma família existente (`baseFamily`), valida contraste ao vivo (tabela com "Passa"/"Falha" em
1579
+ texto) e exporta. Falha não bloqueia a edição; bloquear o salvar é decisão do app (acima).
1580
+ - Para usar a família criada: o export **TypeScript** traz a `HermesFamily` e o trecho do
1581
+ `HERMES_THEME_CONFIG` (`families: [...HERMES_FAMILIES, minhaFamilia]`); o export **CSS** traz as superfícies do
1582
+ tema escuro — vai no SCSS global do app. Hex aqui é aceitável: é a definição da família, não CSS de tela.
1583
+ - Só para escolher entre famílias prontas, `hm-theme-picker` (§1). O builder é ferramenta de admin/design.
1584
+
1585
+ ## 29. Movimento: número animado, reordenação suave e revelação ao rolar
1586
+
1587
+ ```html
1588
+ <!-- Número de destaque (cartão de painel, página de resultados) -->
1589
+ <p class="hm-heading-2"><hm-animated-number [value]="total()" [format]="{ style: 'currency', currency: 'BRL' }" /></p>
1590
+ <p><hm-animated-number [value]="uptime()" [format]="{ style: 'percent', maximumFractionDigits: 1 }" [duration]="600" /></p>
1591
+
1592
+ <!-- Itens que deslizam ao mudar de ordem: o valor muda → anima -->
1593
+ <ul class="hm-list hm-list--unstyled" role="list" [hmFlip]="ranking()">
1594
+ @for (item of ranking(); track item.id) { <li>{{ item.name }}</li> }
1595
+ </ul>
1596
+
1597
+ <!-- Itens mais fundos (cartões dentro das colunas do kanban) -->
1598
+ <hm-kanban label="Chamados" [(columns)]="columns" [hmFlip]="columns()" hmFlipItems=".hm-kanban-card">…</hm-kanban>
1599
+
1600
+ <!-- Disparo manual: capture() ANTES de mexer no estado -->
1601
+ <div #flip="hmFlip" hmFlip>
1602
+ @for (card of cards(); track card.id) { <article>{{ card.title }}</article> }
1603
+ </div>
1604
+ <hm-button (clicked)="flip.capture(); shuffle()">Embaralhar</hm-button>
1605
+
1606
+ <!-- Conteúdo editorial que aparece ao rolar, escalonado -->
1607
+ @for (feature of features; track feature.id; let i = $index) {
1608
+ <section hmReveal [hmRevealDelay]="i * 60">…</section>
1609
+ }
1610
+ ```
1611
+
1612
+ Imports: `AnimatedNumberComponent`, `FlipDirective`, `RevealDirective`.
1613
+
1614
+ - Tudo respeita `prefers-reduced-motion` sozinho (o número aparece direto no valor, os itens vão direto ao lugar,
1615
+ o bloco já nasce visível). Não repita a checagem no app.
1616
+ - `hm-animated-number`: a contagem é `aria-hidden` e o valor final vai para o leitor; ele **não** é região viva —
1617
+ se a mudança precisa ser anunciada, a tela anuncia. Não use em tabela nem em valor que se atualiza sozinho.
1618
+ - `[hmFlip]` não mexe em foco, ordem do DOM nem ARIA: quem anuncia a reordenação é quem reordena. `.hm-kanban-card` é a
1619
+ moldura que o quadro desenha em volta do seu template.
1620
+ - `hmReveal` nunca tira o conteúdo da árvore de acessibilidade e revela na hora quando o foco entra. Não use em
1621
+ formulário, mensagem de erro nem conteúdo de trabalho (listagem, grade): só em página de apresentação.
1622
+
1623
+ ## 30. Idiomas sob demanda e pipes no template
1624
+
1625
+ ```ts
1626
+ // app.config.ts
1627
+ import { ApplicationConfig, provideAppInitializer } from '@angular/core';
1628
+ import { preloadHermesCatalog, provideHermesI18n } from '@trismegisto/angular';
1629
+
1630
+ const saved = localStorage.getItem('locale') ?? 'pt-BR';
1631
+
1632
+ export const appConfig: ApplicationConfig = {
1633
+ providers: [
1634
+ provideHermesI18n({
1635
+ locale: saved,
1636
+ catalogs: {
1637
+ // idioma que a lib não traz: carregador vira um chunk à parte, baixado no 1º setLocale('fr')
1638
+ fr: () => import('./i18n/hermes-fr').then((m) => m.HERMES_MESSAGES_FR),
1639
+ },
1640
+ }),
1641
+ // en/es já têm carregador próprio; pré-carregar evita a espera na primeira troca (e o piscar no início)
1642
+ provideAppInitializer(() => preloadHermesCatalog(saved)),
1643
+ ],
1644
+ };
1645
+ ```
1646
+
1647
+ ```ts
1648
+ // troca de idioma no app
1649
+ private readonly hermesI18n = inject(HermesI18nService);
1650
+
1651
+ protected async changeLanguage(locale: string): Promise<void> {
1652
+ this.appTranslations.use(locale);
1653
+ await this.hermesI18n.setLocale(locale); // resolve quando o catálogo chegou e o idioma mudou
1654
+ localStorage.setItem('locale', locale);
1655
+ }
1656
+ ```
1657
+
1658
+ ```html
1659
+ <!-- imports: HermesTranslatePipe, HermesDatePipe, HermesDateTimePipe -->
1660
+ <hm-button>{{ 'modal.close' | hmTranslate }}</hm-button>
1661
+ <span>{{ 'alert.position' | hmTranslate: { current: 2, count: 5 } }}</span>
1662
+ <td>{{ server.createdAt | hmDate }}</td> <!-- curto: 03/10/2026 -->
1663
+ <td>{{ server.createdAt | hmDate: 'long' }}</td>
1664
+ <td>{{ log.at | hmDateTime: 'short' : { timeZone: 'America/Sao_Paulo' } }}</td>
1665
+ ```
1666
+
1667
+ - Só o pt-BR vem embutido. `setLocale('en' | 'es')` baixa o catálogo na primeira troca e só então muda (sem piscar
1668
+ pt-BR); chamadas seguidas: vale a última. Falha de rede troca mesmo assim, com texto do pt-BR.
1669
+ - Embutir en/es (sem chunk): `catalogs: { en: HERMES_MESSAGES_EN }` com
1670
+ `import { HERMES_MESSAGES_EN } from '@trismegisto/primitives/messages/en'`. Em spec que troca de idioma:
1671
+ `beforeAll(() => preloadHermesCatalog('en'))`.
1672
+ - O catálogo de um idioma novo precisa ser **completo** (`HermesMessages`); só ajustar alguns textos é `override`.
1673
+ - Os pipes são impuros com memória: seguem o `setLocale` em OnPush/zoneless. Chave inexistente aparece na tela
1674
+ (e avisa no console em dev). Eles são para texto **da lib** e datas; texto do app continua no i18n do app.
1675
+ - `hmDate` aceita `Date`, ms ou ISO (`'2026-12-31'` é dia local); vazio/inválido vira `''`.
1676
+
1677
+ ## 31. Testes de tela com harnesses
1678
+
1679
+ ```ts
1680
+ // servers.spec.ts — @angular/cdk como devDependency
1681
+ import { TestBed } from '@angular/core/testing';
1682
+ import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
1683
+ import { HarnessLoader } from '@angular/cdk/testing';
1684
+ import {
1685
+ HermesButtonHarness, HermesDataGridHarness, HermesInputHarness, HermesMenuButtonHarness, HermesModalHarness,
1686
+ } from '@trismegisto/angular/testing';
1687
+ import { Servers } from './servers';
1688
+ import { ServersApi } from './servers-api';
1689
+
1690
+ describe('Servers', () => {
1691
+ let loader: HarnessLoader;
1692
+ let root: HarnessLoader;
1693
+ // dublê do serviço do app (jasmine.createSpy no Karma; vi.fn() no Vitest); SERVERS = linhas de teste
1694
+ const apiFake = { list: () => Promise.resolve(SERVERS), remove: jasmine.createSpy('remove').and.resolveTo() };
1695
+
1696
+ beforeEach(async () => {
1697
+ await TestBed.configureTestingModule({ imports: [Servers], providers: [{ provide: ServersApi, useValue: apiFake }] }).compileComponents();
1698
+ const fixture = TestBed.createComponent(Servers);
1699
+ loader = TestbedHarnessEnvironment.loader(fixture);
1700
+ root = TestbedHarnessEnvironment.documentRootLoader(fixture); // diálogos do HermesDialogService vão para o <body>
1701
+ });
1702
+
1703
+ it('filtra, ordena e lê a grade pelo que está na tela', async () => {
1704
+ const grid = await loader.getHarness(HermesDataGridHarness.with({ caption: 'Servidores' }));
1705
+ await grid.search('web');
1706
+ await grid.sortBy('CPU', 'descending');
1707
+ expect(await grid.getColumnTexts('Servidor')).toEqual(['web-02', 'web-01']);
1708
+ const [first] = await grid.getRows({ cellText: 'web-02' });
1709
+ expect((await first.getCellTextByColumnTitle())['Status']).toBe('Online');
1710
+ });
1711
+
1712
+ it('valida o formulário', async () => {
1713
+ const name = await loader.getHarness(HermesInputHarness.with({ label: 'Hostname' }));
1714
+ await name.setValue('');
1715
+ await name.blur(); // marca como tocado
1716
+ expect(await name.getErrorText()).not.toBe('');
1717
+ await name.setValue('web-03');
1718
+ expect(await name.isInvalid()).toBe(false);
1719
+ });
1720
+
1721
+ it('confirma a remoção', async () => {
1722
+ const actions = await loader.getHarness(HermesMenuButtonHarness.with({ label: 'Ações' }));
1723
+ await actions.clickItem({ text: 'Remover' });
1724
+ const dialog = await root.getHarness(HermesModalHarness.with({ heading: 'Remover servidor?' }));
1725
+ await (await dialog.getFooterButton({ text: 'Remover' })).click();
1726
+ expect(apiFake.remove).toHaveBeenCalledWith('2'); // apiFake: o dublê do serviço passado nos providers
1727
+ });
1728
+ });
1729
+ ```
1730
+
1731
+ - Ache pelo que a pessoa vê: `with({ label })` nos campos, `with({ text })` nos botões (no `hm-icon-button`, o
1732
+ rótulo acessível), `with({ heading })` no modal, `with({ caption })` na grade. **Nunca** por classe interna
1733
+ (`.hm-field__control`): o DOM da lib muda, o harness não.
1734
+ - Harnesses disponíveis: input, textarea, select, checkbox, radio, switch, segmented control, combobox (e multi),
1735
+ date picker, button, modal, tabs, menu/menu-button e data grid. Sem harness (kanban, árvore, agenda…): teste
1736
+ pelo papel ARIA e pelo texto (`getByRole` da Testing Library ou `querySelector('[role="tree"]')`), não por classe.
1737
+ - Combobox, menu-button e filtro de coluna da grade já procuram no `<body>` sozinhos; diálogo aberto por serviço
1738
+ pede o `documentRootLoader`.
1739
+ - Date picker recebe a data no padrão do idioma (`'15/03/2026'`) e já faz o blur. Em spec que troca de idioma,
1740
+ `beforeAll(() => preloadHermesCatalog('en'))`.
1741
+
1742
+ ## 32. Barra de editor com grupos de alternância
1743
+
1744
+ ```html
1745
+ <hm-toolbar label="Formatação">
1746
+ <hm-toggle-group label="Estilo do texto" multiple [(value)]="estilos">
1747
+ <hm-toggle-group-item value="bold" icon="bold" label="Negrito" />
1748
+ <hm-toggle-group-item value="italic" icon="italic" label="Itálico" />
1749
+ </hm-toggle-group>
1750
+ <hm-toggle-group label="Alinhamento" [(value)]="alinhamento">
1751
+ <hm-toggle-group-item value="left" icon="align-left-text" label="Alinhar à esquerda" />
1752
+ <hm-toggle-group-item value="right" icon="align-right-text" label="Alinhar à direita" />
1753
+ </hm-toggle-group>
1754
+ <hm-icon-button toggle [(pressed)]="fixado" icon="pin" label="Fixar" />
1755
+ </hm-toolbar>
1756
+ ```
1757
+ ```ts
1758
+ protected readonly estilos = signal<readonly string[]>([]); // multiple → lista
1759
+ protected readonly alinhamento = signal('left'); // único → texto
1760
+ protected readonly fixado = signal(false);
1761
+ ```
1762
+ O grupo múltiplo cede Tab e setas à barra; o único (radiogroup) mantém o próprio teclado. O rótulo de um
1763
+ botão `toggle` não muda com o estado — quem diz "pressionado" é o `aria-pressed`.
1764
+
1765
+ ## 33. Menu com itens marcáveis e barra de menus
1766
+
1767
+ ```ts
1768
+ protected readonly exibir = signal<readonly MenuItem[]>([
1769
+ { id: 'grade', label: 'Mostrar grade', type: 'checkbox', checked: true },
1770
+ { id: 'lista', label: 'Lista', type: 'radio', group: 'vista', checked: true, separatorAbove: true },
1771
+ { id: 'cartoes', label: 'Cartões', type: 'radio', group: 'vista' },
1772
+ ]);
1773
+ protected aplicar(change: MenuItemChange): void {
1774
+ this.exibir.update((items) => applyMenuItemChange(items, change)); // de @trismegisto/angular
1775
+ }
1776
+ ```
1777
+ ```html
1778
+ <hm-menu-button label="Exibir" icon="eye" [items]="exibir()" (checkedChange)="aplicar($event)" />
1779
+ <hm-menubar label="Editor" [menus]="[{ id: 'exibir', label: 'Exibir', items: exibir() }]"
1780
+ (chosen)="executar($event)" (checkedChange)="aplicar($event)" />
1781
+ ```
1782
+ O menu não muda `items` sozinho: o app aplica a mudança. `menuRadioValue(items, 'vista')` lê o rádio marcado.
1783
+
1784
+ ## 34. Conversa
1785
+
1786
+ ```html
1787
+ <hm-message-scroller label="Conversa com Ana" [hasMoreHistory]="temMais()" [loadingHistory]="carregando()"
1788
+ (loadHistory)="carregarAnteriores()">
1789
+ @for (m of mensagens(); track m.id; let i = $index) {
1790
+ <hm-message [author]="m.author" [time]="m.time" [align]="m.minha ? 'end' : 'start'"
1791
+ [grouped]="continua(i)" [status]="m.status ?? null" (retry)="reenviar(m)">
1792
+ <hm-bubble>{{ m.texto }}</hm-bubble>
1793
+ </hm-message>
1794
+ }
1795
+ @if (digitando()) {
1796
+ <hm-message author="Ana" [announce]="false"><hm-bubble typing /></hm-message>
1797
+ }
1798
+ </hm-message-scroller>
1799
+ ```
1800
+ ```ts
1801
+ import { isMessageContinuation } from '@trismegisto/primitives';
1802
+ private readonly scroller = viewChild.required(MessageScrollerComponent);
1803
+ protected continua(i: number): boolean {
1804
+ const lista = this.mensagens(); // itens com `author` e `time`
1805
+ return isMessageContinuation(lista[i - 1], lista[i]);
1806
+ }
1807
+ protected enviar(texto: string): void {
1808
+ this.mensagens.update((l) => [...l, { id: crypto.randomUUID(), author: 'Eu', minha: true, texto, time: Date.now(), status: 'sending' }]);
1809
+ this.scroller().scrollToEnd('smooth'); // quem envia sempre vai ao fim
1810
+ }
1811
+ ```
1812
+ `hm-message-divider` separa dias (`label`) ou marca eventos (`variant="inline"`). O indicador de digitação vai
1813
+ com `[announce]="false"` para não ser lido como mensagem.
1814
+
1815
+ ## 35. Campo de prompt com anexos
1816
+
1817
+ ```html
1818
+ <hm-textarea label="Mensagem" labelHidden [(value)]="texto" [rows]="1" autoGrow [maxRows]="6"
1819
+ submitKey="enter" (submitted)="enviar()">
1820
+ <hm-icon-button hmTextareaActions icon="paperclip" emphasis="subtle" size="small" label="Anexar arquivo"
1821
+ (clicked)="seletor.click()" />
1822
+ @if (anexos().length) {
1823
+ <hm-attachment-group hmTextareaActions label="Anexos da mensagem" layout="inline">
1824
+ @for (a of anexos(); track a.id) {
1825
+ <hm-attachment [name]="a.file.name" [size]="a.file.size" [type]="a.file.type"
1826
+ [status]="a.status" [progress]="a.progress" removable (removed)="remover(a.id)" />
1827
+ }
1828
+ </hm-attachment-group>
1829
+ }
1830
+ <hm-button hmTextareaActionsEnd size="small" icon="send-arrow" (clicked)="enviar()">Enviar</hm-button>
1831
+ </hm-textarea>
1832
+ <input #seletor type="file" multiple hidden (change)="anexar(seletor)" />
1833
+ ```
1834
+ `submitKey="enter"`: Enter envia e Shift+Enter quebra linha; `mod-enter` exige Ctrl/⌘. Os anexos usam os
1835
+ mesmos textos de estado do `hm-file-upload` (`UploadFile` serve de modelo).
1836
+
1837
+ ## 36. Mapa com marcadores e GeoJSON (`@trismegisto/maps`)
1838
+
1839
+ ```ts
1840
+ import { HM_MAP_COMPONENTS } from '@trismegisto/maps';
1841
+ ```
1842
+ ```html
1843
+ <hm-map
1844
+ label="Lojas no Recife"
1845
+ [center]="[-8.06, -34.87]"
1846
+ [zoom]="13"
1847
+ tileUrl="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
1848
+ attribution="&copy; <a href='https://www.openstreetmap.org/copyright'>OpenStreetMap</a>"
1849
+ [scrollWheelZoom]="false"
1850
+ >
1851
+ @for (loja of lojas(); track loja.id) {
1852
+ <hm-map-marker [position]="loja.posicao" [label]="loja.nome">
1853
+ <hm-map-popup [label]="loja.nome">{{ loja.endereco }}</hm-map-popup>
1854
+ </hm-map-marker>
1855
+ }
1856
+ <hm-map-geojson [data]="bairros()" colorProperty="zona" />
1857
+ </hm-map>
1858
+ ```
1859
+ Tiles raster por `tileUrl` com a `attribution` exigida pelo provedor (OpenStreetMap, servidor próprio ou
1860
+ contratado); sem `tileUrl`, um mapa base embutido (`<hm-map-basemap layer="br/ufs" />`); valor por região é
1861
+ `hm-map-choropleth`. Textos do mapa seguem
1862
+ `setLocale`; para sobrescrever, `provideMapsMessages({ override })`.
1863
+
1864
+ ## 37. Gráficos (`@trismegisto/charts`)
1865
+
1866
+ ```ts
1867
+ import { HmBarChartComponent, HmLineChartComponent, type ChartSeries } from '@trismegisto/charts';
1868
+ ```
1869
+ ```html
1870
+ <hm-bar-chart label="Receita por trimestre" description="O 4º trimestre puxou o ano."
1871
+ [categories]="['T1', 'T2', 'T3', 'T4']" [series]="receita()"
1872
+ [numberFormat]="{ style: 'currency', currency: 'BRL', notation: 'compact' }" />
1873
+
1874
+ <hm-line-chart label="Usuários ativos" [categories]="meses" [series]="ativos()" [area]="true" [stacked]="true" />
1875
+ ```
1876
+ Comece pelo tipado do caso (barras para categorias, linhas para sequência ordenada, pizza/rosca para partes de
1877
+ um todo com até seis fatias, mapa de calor/calendário para intensidade, dispersão para relação entre medidas).
1878
+ Cada um já traz: cores de `--hm-data-*`, resumo automático no idioma ativo ligado por `aria-describedby`, botão
1879
+ "Ver como tabela" (`[(showTable)]` para controlar pelo app), tabela de dados equivalente e navegação por setas.
1880
+ `null` em `data` é lacuna (a linha interrompe, a tabela mostra traço). `hm-chart` recebe a opção crua do motor
1881
+ (`HmChartOption`) e `points` para teclado/tabela: use só quando nenhum tipado servir. O pacote é grande
1882
+ (~215 kB gzip): carregue a tela de gráficos com `@defer` ou rota lazy. Textos seguem `setLocale`; para
1883
+ sobrescrever, `provideChartsMessages({ override })`.