@llmnative/react 1.47.0 → 1.48.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.
package/llms-full.txt CHANGED
@@ -1,1485 +1,1487 @@
1
- # @llmnative/react — Riferimento completo
2
-
3
- Framework React AI-first per generazione deterministica di UI. Data-driven di default, schema-driven opzionale.
4
- Versione 1.0.0 — Apache-2.0
5
-
6
- ```bash
7
- npm install @llmnative/react
8
- import '@llmnative/react/dist/index.css'
9
- ```
10
-
11
- ---
12
-
13
- ## Regole fondamentali
14
-
15
- - Tutti gli import da `'@llmnative/react'` — mai da sottodirectory
16
- - I provider sono iniettati via `<App providers={...}>` — mai importati direttamente nei componenti
17
- - Usare `useDataProvider()`, `useAuthProvider()`, ecc. nei componenti, non istanze dirette
18
- - TypeScript strict: no `any` — usare `unknown`, `Record<string, unknown>`, tipi specifici
19
- - Naming props: `view` (presentazione contenuto), `appearance` (guscio visuale), `layout` (disposizione spaziale), `mode` (comportamento operativo), `variant` (tono semantico), `position` (ancoraggio), `size` (scala)
20
-
21
- ---
22
-
23
- ## App — Entry point
24
-
25
- ```tsx
26
- <App
27
- providers={{
28
- firebase: { // FirebaseConfig — tutte le chiavi flat
29
- apiKey, authDomain, databaseURL, projectId,
30
- storageBucket, messagingSenderId, appId,
31
- },
32
- supabase: { url, anonKey },
33
- google: { clientId, scope }, // flat — NON { oAuth2: { clientId } }
34
- dropbox: { clientId }, // DropboxConfig
35
- mock: { data: mockData },
36
- ai: { // AIConfig — NON una prop separata di <App>
37
- openaiApiKey, geminiApiKey, anthropicApiKey,
38
- deepSeekApiKey, mistralApiKey, openRouterApiKey,
39
- groqApiKey,
40
- cloudflare: { apiToken, accountId }, // Cloudflare Workers AI
41
- },
42
- proxy: { enable: true, route: '/api/proxy' },
43
- custom: { data: { myAdapter: new MyDataProvider() } },
44
- services: {
45
- data: 'dbRealtime', // DataDriverName
46
- storage: 'firestorage', // StorageDriverName | null
47
- auth: 'googleAuth', // AuthDriverName | null
48
- email: 'gmail', // EmailDriverName | null
49
- ai: 'openai', // AIDriverName | null
50
- credentials: 'googleServiceAccount',
51
- },
52
- }}
53
- iconProvider="lucide" // 'lucide' | 'phosphor' | AppIconProviderConfig
54
- themeProvider="default" // 'default' | 'flat' | 'cyber' | AppThemeProviderConfig
55
- menuConfig={menuConfig}
56
- importPage={(path) => import(path)}
57
- LayoutDefault={MyLayout} // layout wrapper custom (opzionale)
58
- appName="MyApp" // nome app (opzionale)
59
- i18n={{ locale: 'it', translations: { ... } }}
60
- contextProviders={MyContextProvider}
61
- errorReportUrl="/api/errors"
62
- debug={import.meta.env.DEV}
63
- />
64
- ```
65
-
66
- ### Testi dei componenti (i18n)
67
-
68
- I testi fissi dei componenti vengono da `I18nDict` e seguono `i18n.locale` (en, it, de, ru, ar, zh
69
- inclusi): un testo si cambia con `i18n.translations`, non nel codice. Namespace dei componenti:
70
- `notifications` (`markAllRead`, `empty`, `emptyHint`), `errorBoundary` (schermata d'errore; fuori da
71
- `<I18nProvider>`, come l'`ErrorBoundary` radice di `<App>`, resta in inglese), `themeSwitcher`,
72
- `imageField` (anche i dialoghi immagine di `RichText`), `richText`, `tabDynamic` (`addTab`),
73
- `breadcrumbs` (`label`, l'`aria-label` del `nav`), `grid` (`tableView`, `galleryView`, `columns`,
74
- `fields`), `prompt` (anche `Chatbot`: `role`, `language`, `voice`, `style`, `temperature`, `stop`),
75
- `chat` (`ChatReasoning` e `ChatQuestions`: `reasoning`, `reasoningFor`, `other`, `review`, `submit`, …;
76
- il codice di `ChatMarkdown` usa `code`).
77
-
78
- ```tsx
79
- <App i18n={{ locale: 'it', translations: { it: { notifications: { emptyHint: 'Niente di nuovo' } } } }} />
80
- ```
81
-
82
- ### AppThemeProviderConfig
83
- ```ts
84
- {
85
- mode?: 'light' | 'dark' | 'system';
86
- theme: string;
87
- themes?: Record<string, {
88
- preset?: { colors?: ColorScale; radius?: number; font?: string };
89
- motion?: MotionRegistry;
90
- components?: Record<string, Partial<ThemeComponent>>;
91
- }>;
92
- themeOverride?: Record<string, Partial<ThemeComponent>>;
93
- }
94
- ```
95
-
96
- Built-in themes: `default`, `flat`, `cyber`, `vscode-dark-modern`, `vscode-light-modern`, `vscode-dark-plus`, `vscode-light-plus`, `tokyo-night`, `tokyo-night-light`.
97
- The VS Code and Tokyo Night themes are compiled from the original VS Code theme JSON (`scripts/themes/vscode`), filling the keys a theme does not list with VS Code's color registry defaults; each one has both modes (`vscode-dark-*` starts dark, `vscode-light-*` light). Status colors (destructive/success/warning/info) stay the framework's.
98
-
99
- `ColorScale` tokens: `background`, `foreground`, `canvas` (page floor behind cards and panels, `bg-canvas`; falls back to `background`), `card`, `popover`, `primary`, `secondary`, `muted`, `accent`, `destructive`, `success`, `warning`, `info` (each with its `*Foreground`), `border`, `input` (border of form fields), `ring`. A consumer bridging the tokens in its own `@theme inline` adds `--color-canvas: hsl(var(--rf-canvas, var(--rf-background)));`.
100
-
101
- ---
102
-
103
- ## Provider System
104
-
105
- ### Matrix completa
106
-
107
- | Servizio | Interfaccia | Driver | Config key | Obbligatorio |
108
- |---|---|---|---|---|
109
- | data | `DataProviderAdapter` | `mock`, `dbRealtime`, `firestoreDb`, `supabaseDb` | `providers.mock/firebase/supabase` | sì (fallback: mock) |
110
- | storage | `StorageProviderAdapter` | `firestorage`, `supabaseStorage` | `providers.firebase/supabase` | no |
111
- | auth | `AuthProviderAdapter` | `googleAuth`, `firebaseAuth`, `supabaseAuth`, `dropboxAuth`, `githubAuth` | `providers.google/firebase/supabase/dropbox/github` | sì (fallback: googleAuth) |
112
- | email | `EmailProviderAdapter` | `gmail` | `providers.google` | no |
113
- | ai | `AIProviderAdapter` | `openai`, `gemini`, `anthropic`, `deepseek`, `mistral`, `openrouter`, `opencode`, `opencode-go`, `cloudflare`, `groq` | `Config.tsx AIConfig` | no |
114
- | credentials | `CredentialsAdapter` | `googleServiceAccount` | `providers.google.serviceAccount` | no |
115
-
116
- ### Hooks
117
-
118
- ```ts
119
- const data = useDataProvider() // DataProviderAdapter | null
120
- const storage = useStorageProvider() // StorageProviderAdapter | null
121
- const auth = useAuthProvider() // AuthProviderAdapter | null
122
- const email = useEmailProvider() // EmailProviderAdapter | null
123
- const ai = useAIProvider() // AIProviderAdapter | null
124
- const creds = useCredentialsProvider() // CredentialsAdapter | null
125
-
126
- // Named provider (multi-provider setup)
127
- const supabase = useDataProvider('supabase')
128
- ```
129
-
130
- ### GitHub (`githubAuth`, sessione sul server dell'app)
131
-
132
- GitHub richiede il client secret per scambiare il codice: scambio, token e sessione stanno sul server
133
- dell'app, il browser vede solo il profilo. Config `providers.github = { sessionUrl: '/api/auth/github' }`,
134
- driver `auth: 'githubAuth'`; funziona con `AuthButton` (pulsante e `aspect="avatar"`) e
135
- `useAuthProvider('githubAuth')`. Il server espone sotto `sessionUrl`:
136
-
137
- | Rotta | Risposta |
138
- |---|---|
139
- | `GET /login?returnTo=<path>[&scope=…]` | redirect a GitHub, poi di nuovo a `<path>` |
140
- | `GET /me` | `{ login, name, avatarUrl, email }`, 401 senza sessione |
141
- | `POST /logout` | chiude la sessione |
142
-
143
- Lato server, da `@llmnative/react/server`:
144
-
145
- ```ts
146
- const oauth = createGitHubOAuth({ clientId, clientSecret, scopes: ['read:org'] })
147
- oauth.authorizeUrl({ state, redirectUri, codeChallenge }) // PKCE S256
148
- const { accessToken } = await oauth.exchangeCode({ code, redirectUri, codeVerifier }) // GitHubOAuthError se rifiutato
149
- await oauth.getUser(accessToken) // { login, name, avatarUrl, email }
150
- await oauth.getOrganizations(accessToken) // [{ login, avatarUrl, role: 'admin' | 'member' }]
151
- ```
152
-
153
- ### Interfacce principali
154
-
155
- ```ts
156
- // DataProviderAdapter
157
- read(path, options?) / set(path, data) / update(path, data) / remove(path)
158
- subscribe(path, callback: (records: RecordArray) => void): () => void
159
- count?(path, where?): Promise<number>
160
-
161
- // StorageProviderAdapter
162
- upload(file, path): Promise<string|undefined>
163
- getURL(path) / download(path): Promise<Blob|undefined> / delete(path): Promise<boolean>
164
-
165
- // AuthProviderAdapter
166
- signIn(intent?, options?) / signOut() / getUser(): UserProfile|null
167
- onAuthChange(callback) / getAccessToken(): Promise<string|null>
168
- ```
169
-
170
- ### Auth sign-in methods
171
-
172
- | method | Firebase | Supabase | Google |
173
- |---|---|---|---|
174
- | `password` | ✅ | ✅ | — |
175
- | `anonymous` | ✅ | ✅ | — |
176
- | `magic_link` | — | ✅ | — |
177
- | `oauth` (github, apple…) | ✅ | ✅ | — |
178
- | GIS + scoped token | — | — | ✅ |
179
-
180
- ```ts
181
- await auth.signIn({ method: 'password', email: '...', password: '...' })
182
- await auth.signIn({ method: 'oauth', provider: 'github' })
183
- // Google: token per API scope
184
- const token = await auth.getAccessToken('https://www.googleapis.com/auth/gmail.send')
185
- ```
186
-
187
- ### CredentialsAdapter (Google Service Account)
188
- ```tsx
189
- // Chiama Google APIs lato browser senza Node.js
190
- <App providers={{ google: { serviceAccount: { clientEmail, privateKey } }, services: { credentials: 'googleServiceAccount' } }} />
191
-
192
- const creds = useCredentialsProvider()
193
- const token = await creds.getToken('https://www.googleapis.com/auth/solar')
194
- ```
195
-
196
- ### Provider custom
197
- ```ts
198
- import { DataProviderAdapter, RecordArray } from '@llmnative/react'
199
-
200
- export class RestDataProvider implements DataProviderAdapter {
201
- async read(path: string): Promise<unknown> { ... }
202
- async set(path: string, data: object): Promise<void> { ... }
203
- async update(path: string, data: object): Promise<void> { ... }
204
- async remove(path: string): Promise<void> { ... }
205
- subscribe(path: string | undefined, callback: (records: RecordArray) => void): () => void {
206
- return () => undefined
207
- }
208
- }
209
- ```
210
-
211
- ---
212
-
213
- ## Grid — CRUD table/gallery
214
-
215
- ```tsx
216
- <Grid
217
- path="/users" // DataProvider-backed — oppure records={array} per in-memory
218
- columns={[
219
- { key: 'name', label: 'Nome', sortable: true },
220
- { key: 'email', label: 'Email' },
221
- { key: 'role', label: 'Ruolo', render: ({ value }) => <Badge>{value}</Badge> },
222
- { key: 'date', label: 'Data', render: 'date' },
223
- ]}
224
- actions={['add', 'edit', 'delete']} // oppure Record<string, GridAction>
225
- view="table" // 'table' | 'gallery'
226
- pagination={{ limit: 20 }}
227
- groupBy="status"
228
- sortable={{ field: 'name', dir: 'asc' }}
229
- form={<FormFields />}
230
- onSave={async ({ record, action }) => record._key}
231
- onComplete={async ({ record, action }) => true}
232
- selection={{ mode: 'multiple', onChange: (sel) => {} }}
233
- reorderable
234
- onReorder={(records, meta) => {}}
235
- header={(ctx) => <div>{ctx.title}</div>}
236
- footer={(ctx) => <div>{ctx.records.length} records</div>}
237
- />
238
- ```
239
-
240
- | Prop | Tipo | Note |
241
- |---|---|---|---|
242
- | `path` | `string \| "fromUrl"` | Path provider-backed |
243
- | `records` | `RecordArray` | Dati in memoria (alternativa a path) |
244
- | `columns` | `GridColumn[]` | `{ key, label, sortable?, render?, className? }` |
245
- | `actions` | `Array<'add'\|'edit'\|'delete'> \| Record<string, GridAction>` | |
246
- | `view` | `'table' \| 'gallery'` | |
247
- | `groupBy` | `string \| string[]` | |
248
- | `pagination` | `PaginationParams` | `{ limit, page?, maxPageButtons?, align?, sticky? }` |
249
- | `sortable` | `boolean \| OrderConfig` | |
250
- | `selection` | `false \| 'single' \| 'multiple' \| GridSelectionConfig` | |
251
- | `form` | `ReactElement \| ((ctx) => ReactNode)` | Form condiviso per CRUD |
252
- | `onSave` | `GridMutationSaveHandler` | `async ({ record, action }) => string` |
253
- | `onDelete` | `GridMutationDeleteHandler` | `async ({ record }) => string` |
254
- | `onComplete` | `GridAfterActionHandler` | `async ({ record, action }) => boolean` |
255
- | `onRowClick` | `(record) => void` | |
256
- | `reorderable` | `boolean` | Abilita drag & drop righe |
257
- | `onReorder` | `GridReorderHandler` | `(records, meta) => void` |
258
- | `onLoad` | `(records) => TRecord[]` | Trasforma records dopo il fetch |
259
- | `editDeepLink` | `boolean` | Sincronizza modal edit con URL |
260
- | `audit` | `boolean` | Logga mutazioni |
261
- | `sticky` | `'top' \| 'bottom'` | Header/footer sticky |
262
- | `wrapperClassName` | `string` | CSS wrapper esterno |
263
- | `loading` | `boolean` | Stato loading override |
264
- | `title` | `ReactNode` | Titolo header grid |
265
- | `before` / `after` | `ReactNode` | Slot prima/dopo il contenuto |
266
- | `header` / `footer` | `ReactNode \| ((ctx) => ReactNode)` | Header/footer custom |
267
- | `searchable` | `boolean \| GridSearchConfig` | Search box nell'header default — `{ fields?, placeholder? }` |
268
- | `filters` | `GridFilterConfig[]` | Checkbox toggle nell'header default, applicati PRIMA di `searchable` — `{ key, label, defaultValue?, predicate(record, value) }` |
269
-
270
- **GridAction kind:** `'modal'` (default), `'route'`, `'external'`, `'inline'`, `'delete'`
271
-
272
- ---
273
-
274
- ## Form — form CRUD con lifecycle
275
-
276
- ```tsx
277
- <Form
278
- path="/products"
279
- appearance="card" // 'card' | 'empty'
280
- showBack
281
- defaultValues={{ status: 'draft' }}
282
- keyGenerator={() => `prod_${Date.now()}`}
283
- onLoad={(data) => { /* side-effect hook, non trasforma */ }}
284
- onSave={async ({ record, action }) => { /* return storagePath or undefined */ }}
285
- onDelete={async ({ record }) => { /* confirm */ }}
286
- onComplete={async ({ action }) => { if (action === 'save') navigate('/products') }}
287
- >
288
- <Input name="title" label="Titolo" required />
289
- <Input name="price" label="Prezzo" type="number" />
290
- <Input name="address.city" label="Città" /> {/* oggetto annidato */}
291
- <Repeat name="tags" defaultLength={1}>
292
- {(i) => <Input name={`tags.${i}`} label={`Tag ${i+1}`} />}
293
- </Repeat>
294
- </Form>
295
- ```
296
-
297
- | Prop | Tipo | Note |
298
- |---|---|---|---|
299
- | `path` | `string` | Path provider-backed |
300
- | `appearance` | `'card' \| 'empty'` | Guscio visuale |
301
- | `controller` | `FormController` | Controller condiviso per bottoni custom esterni |
302
- | `showBack` | `boolean` | Pulsante Back nel footer |
303
- | `defaultValues` | `RecordProps` | Valori iniziali per nuovo record |
304
- | `keyGenerator` | `(record) => string` | Generatore chiave primaria custom |
305
- | `draftBucket` | `string` | Bucket stabile che isola la bozza locale; omettilo per disabilitare la persistenza |
306
- | `noticeAnchorRef` | `React.RefObject<HTMLElement>` | Ancoraggio sticky per notifiche |
307
- | `showNotice` | `boolean` | Mostra notifiche save/delete (default `true`) |
308
- | `requireChanges` | `boolean` | Default `true`: senza un campo cambiato il salvataggio dice "No changes to save" ed è disabilitato. `false` = form d'azione (CR-117): i valori iniziali sono già un invio valido (es. avviare una release con la versione proposta), `save()` valida e chiama `onSave` anche senza modifiche; `isDirty` dice comunque se qualcosa è cambiato |
309
- | `children` | `ReactNode \| ((fields) => ReactNode) \| (({ record }) => ReactNode)` | Contenuto form |
310
- | `header` | `ReactNode` | Contenuto header custom |
311
- | `footer` | `ReactNode` | Contenuto footer custom |
312
- | `wrapperClassName` | `string` | CSS wrapper esterno |
313
- | `headerClassName` | `string` | CSS header |
314
- | `className` | `string` | CSS body form |
315
- | `footerClassName` | `string` | CSS footer |
316
- | `log` | `boolean` | Logga ogni modifica su console |
317
- | `onLoad` | `(record) => void` | Side-effect dopo il caricamento (non trasforma) |
318
- | `onRecordChange` | `(record) => void` | Cambio campo in tempo reale |
319
- | `onSave` | `FormSaveHandler` | `async ({ record, prevRecord?, storagePath?, action }) => string \| undefined` |
320
- | `onDelete` | `FormDeleteHandler` | `async ({ record }) => string \| undefined` |
321
- | `onComplete` | `FormFinallyHandler` | `async ({ record, action }) => boolean` |
322
-
323
- **Form controller** — stato e azioni native del form accessibili da qualsiasi punto della pagina.
324
-
325
- Due hook:
326
-
327
- | Hook | Dove usarlo | Cosa restituisce |
328
- |---|---|---|
329
- | `useFormController(controller?)` | Ovunque (anche fuori dal form) | Crea o si aggancia a un `FormController`. Senza argomenti ne crea uno locale stabile. Con un `controller` esistente ci si aggancia. |
330
- | `useFormActions()` | Solo dentro `<Form>` (legge dal context) | Restituisce lo stesso `FormController` del form genitore. Lancia errore se usato fuori. |
331
-
332
- Esempio — bottone custom fuori dal form:
333
- ```tsx
334
- const form = useFormController();
335
-
336
- <ActionButton disabled={form.saveDisabled} onClick={() => { void form.save(); }} />
337
- <Form controller={form} draftBucket="workspace/acme" onSave={...} />
338
- ```
339
-
340
- Esempio — form d'azione, i valori proposti si inviano anche senza modificarli (CR-117):
341
- ```tsx
342
- const form = useFormController();
343
-
344
- <LoadingButton label="Avvia la release" onClick={() => form.save()} />
345
- <Form controller={form} appearance="empty" requireChanges={false} defaultValues={{ version: '1.4.0', notes }} onSave={async ({ record }) => { await start(record); return undefined; }}>
346
- <Input name="version" label="Versione" required />
347
- </Form>
348
- ```
349
-
350
- Esempio — uso dentro il form (senza passare controller):
351
- ```tsx
352
- function MySaveButton() {
353
- const form = useFormActions();
354
- return <LoadingButton disabled={form.saveDisabled} loading={form.isSaving} onClick={form.save} />;
355
- }
356
- ```
357
-
358
- Stato esposto dal controller: `record`, `isNewRecord`, `isDirty`, `canSave`, `canDelete`, `isSaving`, `isDeleting`, `saveDisabled`, `deleteDisabled`, `hasDraft`, `draftStatus`, `errors`, `hasErrors`.
359
-
360
- Azioni: `save()`, `delete()`, `reset()`, `restoreDraft()`, `discardDraft()`.
361
-
362
- ---
363
-
364
- ## Campi form
365
-
366
- ### Input
367
- ```tsx
368
- <Input name="x" label="..." required /> // text (default)
369
- <Input name="price" type="number" min={0} max={100} step={0.01} />
370
- <Input name="email" type="email" />
371
- <Input name="pwd" type="password" />
372
- <Input name="date" type="date" />
373
- <Input name="color" type="color" />
374
- <TextArea name="bio" minHeight={96} />
375
- <Checkbox name="active" valueChecked="yes" />
376
- <Switch name="gate" label="Passa dalla CI" disabled title="L'agente non committa" /> // CR-116: disabled (non cambia né con il clic né da tastiera), title anche sull'etichetta: il motivo al passaggio del mouse
377
- ```
378
- `Input` props: `name`(req) `label` `type` `required` `disabled` `placeholder` `min` `max` `step` `validator:(v)=>string|undefined`
379
- `type`: `'text' | 'number' | 'email' | 'password' | 'color' | 'date' | 'time' | 'datetime-local' | 'week' | 'month' | 'range' | 'checkbox' | 'radio' | 'url'`
380
-
381
- **NOTA**: il tipo HTML si passa con `type`. `inputType` e i sotto-componenti `Input.Number`/`Input.Email`/`Input.Date` non esistono.
382
-
383
- **Label come nodo**: `label` di tutti i campi di inserimento (`Input`, `TextArea`, `Checkbox`, `Select`, `Autocomplete`, `Checklist`, `Upload*`, `ImageField`, `CodeEditor`, `RichText`, `AddressAutocomplete`, `UploadCSV`, `Prompt`) accetta una stringa o un nodo React (tipo `FieldLabel`), disegnato dentro la `<label>` prima dell'asterisco di obbligatorio. Dove serve un testo (messaggio "obbligatorio", `aria-label`) si usa il testo del nodo, ricavabile anche con `labelText(node)`.
384
- ```tsx
385
- <Select name="skill" required options={skills} label={<>Skill <ActionButton icon="info" ariaLabel="Apri la skill" variant="link" onClick={openSkill} /></>} />
386
- ```
387
-
388
- ### Select / Autocomplete / Checklist
389
- ```tsx
390
- <Select name="role" options={[{ label: 'Admin', value: 'admin' }]} />
391
- <Select name="categoryId" optionsSource={{ path: '/categories', labelField: 'name', valueField: '_key' }} />
392
- <Autocomplete name="userId" optionsSource={{ path: '/users', labelField: 'email' }} maxItems={1} />
393
- <Checklist name="tags" options={['a', 'b', 'c']} />
394
- ```
395
-
396
- | Prop | Tipo | Note |
397
- |---|---|---|
398
- | `options` | `Option[] \| string[] \| number[]` | |
399
- | `optionsSource` | `{ path, labelField, valueField?, where?, order?, fieldMap?, onLoad? }` | Carica da provider |
400
- | `order` | `{ field: 'label' \| 'value', dir: 'asc' \| 'desc' }` | |
401
- | `placeholderOption` | `Option` | Solo Select |
402
- | `placeholder` | `string` | Solo Autocomplete |
403
- | `creatable` | `boolean` | Solo Autocomplete — crea nuovi valori |
404
- | `onCreate` | `(value) => void \| boolean \| Promise<void \| boolean>` | Solo Autocomplete — restituire `false` per non selezionare il valore creato (es. aprire un modulo di creazione) |
405
- | `listClassName` / `optionClassName` | `string` | Solo Autocomplete — classi della lista e delle voci (anche da tema `Autocomplete.listClassName` / `optionClassName`) |
406
- | `minItems` / `maxItems` | `number` | Solo Autocomplete |
407
- | `itemClassName` | `string` | Solo Checklist |
408
- | `validator` | `(value) => string \| undefined` | Tutte le varianti |
409
- | `readOnlyAfterSet` | `boolean` | readonly dopo primo valore |
410
- | `disabled` | `boolean` | |
411
- | `title` | `string` | |
412
- | `feedback` | `string` | Messaggio di errore/suggerimento |
413
-
414
- `Autocomplete` è una combobox accessibile: la lista (in un portal, larga quanto il campo, stile popover del tema) mostra solo le label e filtra per label/value senza distinzione di maiuscole e accenti; i chip mostrano la label; tastiera: frecce, Invio, Esc (chiude solo la lista, non il `Modal`), Tab, Backspace su campo vuoto rimuove l'ultimo valore. Con `creatable` compare la voce "Crea «testo»". Il valore salvato è sempre l'array dei `value`. `Autocomplete` e `Checklist` sono export nominati: `Select.Autocomplete`/`Select.Checklist` non esistono.
415
-
416
- ### UploadImage / UploadDocument / UploadCSV
417
- ```tsx
418
- <UploadImage name="cover" label="Copertina" /> {/* con crop editor */}
419
- <UploadDocument name="pdf" label="PDF" />
420
- <UploadCSV name="data" label="Importa CSV" /> {/* con preview tabellare */}
421
- ```
422
-
423
- **UploadImageProps** (eredita FormFieldProps):
424
- | Prop | Tipo | Note |
425
- |---|---|---|
426
- | `name` | `string` (required) | |
427
- | `uploadPath` | `string` | Path storage per upload automatico |
428
- | `accept` | `string` | MIME types accettati |
429
- | `editable` | `boolean` | Abilita crop editor |
430
- | `multiple` | `boolean` | Multipla selezione |
431
- | `max` | `number` | Numero massimo file |
432
- | `feedback` | `string` | Testo placeholder drop zone |
433
- | `srcsetWidths` | `number[]` | Larghezze varianti responsive |
434
- | `previewHeight` / `previewWidth` | `number` | Dimensioni preview |
435
-
436
- **UploadDocumentProps** (eredita FormFieldProps): `name`, `uploadPath`, `accept`, `editable`, `multiple`, `max`
437
-
438
- ### UploadCSV
439
- ```tsx
440
- <UploadCSV name="data" label="Importa CSV" />
441
- ```
442
- | Prop | Tipo |
443
- |---|---|
444
- | `name` | `string` (required) |
445
- | `onDataLoaded` | `(data: UploadCSVData) => void` |
446
- | `onParseField` | `([key, value]) => [key, value] \| undefined` |
447
- | `normalizeKeys` | `boolean` |
448
- | `removeEmptyFields` | `boolean` |
449
- | `delimiter` | `string` |
450
- | `label` / `icon` | Opzionali |
451
-
452
- ### ImageField
453
- ```tsx
454
- <ImageField
455
- name="hero"
456
- label="Hero image"
457
- defaultValue={{ src: 'https://example.com/hero.jpg', alt: 'Hero shot' }}
458
- srcsetWidths={[400, 800]}
459
- uploadPath="/content/images"
460
- />
461
- ```
462
-
463
- Gestisce un oggetto `{ src, alt, srcset?, sizes? }`, preview inline, crop editor e generazione opzionale di varianti responsive.
464
-
465
- ### CropImage
466
- ```tsx
467
- <CropImage img={imageObj} title="Ritaglia" scales={{ '1:1': 1, '4:3': 1.33 }} />
468
- ```
469
- Componente di ritaglio indipendente. `img` ha tipo `{ fileName, variants }` dove ogni variante è `{ fileName, type, scale, top, left, width, height, base64? }`. Usato internamente da `UploadImage` e `ImageField`, ma esportato pubblicamente per uso standalone.
470
-
471
- ### CodeEditor
472
- ```tsx
473
- <CodeEditor
474
- name="code"
475
- label="Template"
476
- language="html"
477
- placeholder="Scrivi HTML..."
478
- minHeight={200}
479
- maxHeight={600}
480
- disabled={false}
481
- required
482
- validateSyntax
483
- commands={[{ name: 'wrap-section', handler: ({ value }) => `<section>\n${value}\n</section>` }]}
484
- commandsTrigger="/"
485
- />
486
- ```
487
- Editor basato su CodeMirror con syntax highlighting e validazione. Linguaggi: `liquid`, `html`, `json`, `js`, `ts`, `css`.
488
- Quando `commands` e presente, `CodeEditor` apre internamente `ContextMenu` sul trigger configurato.
489
-
490
- | Prop extra | Tipo |
491
- |---|---|
492
- | `language` | `CodeEditorLanguage` |
493
- | `placeholder` | `string` |
494
- | `minHeight` / `maxHeight` | `number` |
495
- | `validateSyntax` | `boolean` |
496
- | `validator` | `(value) => string \| undefined \| Promise<string \| undefined>` |
497
- | `extensions` | `unknown[]` |
498
-
499
- ### RichText
500
- ```tsx
501
- <RichText
502
- name="body"
503
- label="Article body"
504
- placeholder="Scrivi..."
505
- toolbar="fixed" // 'fixed' | 'floating' | false
506
- toolbarCommands={['bold', 'italic', 'heading1', '|', 'bulletList', 'link']}
507
- outputFormat="html" // 'html' | 'json' | 'text'
508
- statusBar={{ tagBreadcrumb: true, wordCount: true }}
509
- minHeight={200}
510
- maxHeight={800}
511
- imageUpload={{ path: '/content/images', srcsetWidths: [400, 800] }}
512
- commands={[{ name: 'summary', icon: 'sparkles' }]}
513
- commandsTrigger="/"
514
- />
515
- ```
516
-
517
- | Prop extra | Tipo |
518
- |---|---|
519
- | `placeholder` | `string` |
520
- | `disabled` | `boolean` |
521
- | `feedback` | `string` |
522
- | `toolbar` | `'fixed' \| 'floating' \| false` |
523
- | `toolbarCommands` | `ToolbarCommand[]` |
524
- | `outputFormat` | `'html' \| 'json' \| 'text'` |
525
- | `statusBar` | `boolean \| StatusBarConfig` |
526
- | `minHeight` / `maxHeight` | `number` |
527
- | `imageUpload` | `RichTextImageUploadConfig` |
528
- | `documentUpload` | `RichTextDocumentUploadConfig` |
529
- | `validator` | `(value) => string \| undefined` |
530
-
531
- ### Repeat — array dinamici
532
- ```tsx
533
- <Repeat name="items" defaultLength={3} minItems={1} maxItems={10} label="Elementi" layout="vertical" readOnly>
534
- {({ index, record, records, remove }) => (
535
- <>
536
- <Input name={`items.${index}.name`} label="Nome" />
537
- <UploadImage name={`items.${index}.photo`} label="Foto" />
538
- </>
539
- )}
540
- </Repeat>
541
- ```
542
-
543
- | Prop | Tipo | Note |
544
- |---|---|---|
545
- | `name` | `string` (required) | |
546
- | `children` | `ReactNode \| ((args) => ReactNode)` | Render prop con `{ index, record, records, remove }` |
547
- | `defaultLength` | `number` | Righe iniziali |
548
- | `minItems` / `maxItems` | `number` | Min/max righe |
549
- | `layout` | `'vertical' \| 'horizontal' \| 'inline'` | |
550
- | `label` | `string` | Etichetta gruppo |
551
- | `labelPosition` | `'top' \| 'bottom'` | |
552
- | `hideRemoveButton` | `boolean` | Nascondi rimozione |
553
- | `readOnly` | `boolean` | Sola lettura |
554
- | `onChange` | `FieldOnChange` | |
555
- | `onAdd` / `onRemove` | `(records) => void` | Callback aggiunta/rimozione |
556
-
557
- ### Prompt — campo AI-potenziato
558
- ```tsx
559
- <Prompt
560
- name="summary"
561
- mode="run" // 'edit' | 'run'
562
- onRunPrompt={async (prompt, options) => AI.fetch(prompt)}
563
- commands={[{ name: 'translate', icon: 'languages', handler: (v) => `Translate:\n${v}` }]}
564
- commandsTrigger="/" // default automatico quando commands e presente
565
- attachments
566
- statusItems={['tokensIn', 'tokensOut', 'contextPercent', 'duration']}
567
- />
568
- ```
569
-
570
- Quando `commands` e presente in `mode="run"`, `Prompt` monta internamente `ContextMenu` sulla textarea del risultato. Il trigger di default e `"/"`; `commandsTrigger` permette di cambiarlo. Il menu diventa searchable automaticamente sopra una soglia interna di comandi.
571
-
572
- `renderFallback`: quando l'AI non e configurata, `Prompt` monta un fallback testuale; passa `renderFallback` per personalizzarlo (riceve `{ name, label, required, onChange }`).
573
-
574
- ---
575
-
576
- ## UI Primitives
577
-
578
- ### Alert
579
- ```tsx
580
- <Alert variant="success">Salvato!</Alert>
581
- <Alert variant="warning" icon placement="fixed" timeout={3000}>Attenzione</Alert>
582
- ```
583
- `variant`: `'info' | 'success' | 'warning' | 'danger' | 'primary' | 'secondary' | 'light' | 'dark'`
584
- `appearance`: `'default' | 'text'`
585
- `placement`: `'inline' | 'fixed'`
586
-
587
- ### Badge
588
- ```tsx
589
- <Badge variant="success">Attivo</Badge>
590
- ```
591
- `variant`: stessi valori di Alert
592
-
593
- ### Button variants
594
- ```tsx
595
- <ActionButton variant="primary" label="Salva" icon="save" onClick={handleSave} />
596
- <LoadingButton variant="primary" label="Invia" onClick={async (e, setMsg) => { await save(); setMsg('Salvato!') }} />
597
- <BackLink label="Indietro" />
598
- <GoSite href="https://..." label="Visita" />
599
- ```
600
-
601
- **IButton props:** `variant`, `label`, `icon`, `badge`, `disabled`, `ariaLabel`, `title`, `iconClassName`, `onClick`
602
- **LoadingButton aggiunge:** `loading`, `loadingLabel` — `onClick` riceve `(e, setMessage?) => Promise<unknown>`
603
-
604
- ### Card
605
- ```tsx
606
- <Card title="Titolo" header={<Actions />} footer={<Pagination />} loading={isLoading}>
607
- {children}
608
- </Card>
609
- ```
610
-
611
- ### Modal
612
- ```tsx
613
- <Modal title="Conferma" size="md" position="center" onClose={() => {}} onSave={handleSave} onDelete={handleDelete} motion="fade" allowFullscreen stackedBehind>
614
- {content}
615
- </Modal>
616
- <ModalYesNo title="Sicuro?" onClose={() => {}} onYes={async () => true}>Eliminare il record?</ModalYesNo>
617
- <ModalOk title="Completato!" onClose={() => {}}>Salvato.</ModalOk>
618
- ```
619
- `size`: `'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'fullscreen'`
620
- `position`: `'center' | 'top' | 'left' | 'right' | 'bottom'`
621
- `ModalYesNo` e `ModalOk` sono export separati: `Modal.YesNo` e `Modal.Ok` non esistono.
622
- Tastiera: Esc chiude il modal in cima alla pila (`closeOnEscape`, default `true`).
623
- Accessibilità: il dialog ha `role="dialog"`, `aria-modal="true"` (non con `stackedBehind`) e `aria-labelledby` verso `title` (o `header` stringa) — nei test si trova con `getByRole('dialog', { name })`.
624
-
625
- | Prop | Tipo | Note |
626
- |---|---|---|
627
- | `children` | `ReactNode` (required) | |
628
- | `title` | `ReactNode` | |
629
- | `header` / `footer` | `ReactNode \| false` | Custom header/footer |
630
- | `size` / `position` | Come sopra | |
631
- | `onClose` | `() => void` | |
632
- | `onSave` / `onDelete` | `(e) => Promise<boolean>` | |
633
- | `allowFullscreen` | `boolean` | Toggle fullscreen |
634
- | `showCancel` | `boolean` | Default `true` |
635
- | `stackedBehind` | `boolean` | Modale sotto un'altra (stile Google Tag Manager): un velo la scurisce, il suo backdrop resta com'è (quello della modale sopra entra sopra, così la pagina si scurisce di un gradino per modale) e non riceve il puntatore. I pannelli laterali aperti sullo stesso lato si impilano da soli: quello in cima prende la larghezza con cui si è aperto il primo, ognuno sotto è largo il 10% in più di quello sopra (100%, 110%, 121%…), così ne sporge una striscia. Solo la larghezza cambia, con la transizione dello slide, in entrata e in uscita |
636
- | `closeOnBackdrop` | `boolean` | Default `true` |
637
- | `closeOnEscape` | `boolean` | Default `true` — solo il modal in cima reagisce |
638
- | `zIndex` | `number` | |
639
- | `motion` | `MotionReference` | Preset animazione |
640
- | Classi CSS header/title/subtitle/body/footer | `string` | |
641
-
642
- ### Table
643
- ```tsx
644
- <Table
645
- columns={[{ key: 'name', label: 'Nome', sort: true }]}
646
- records={records}
647
- onRowClick={(record) => {}}
648
- selection="multiple"
649
- sortable={{ field: 'name', dir: 'asc' }}
650
- pagination={{ limit: 20 }}
651
- onReorder={(records, meta) => {}}
652
- onSelectionChange={(sel) => {}}
653
- groupBy="status"
654
- renderCell={(record, key, index) => <CustomCell />}
655
- />
656
- ```
657
-
658
- | Prop | Tipo |
659
- |---|---|
660
- | `columns` | `TableHeaderProp[]` |
661
- | `records` | `RecordArray` |
662
- | `sortable` | `boolean \| OrderConfig` |
663
- | `pagination` | `PaginationParams` |
664
- | `selection` | `'single' \| 'multiple'` |
665
- | `onRowClick` | `(record) => void` |
666
- | `onReorder` | `(records, meta) => void` |
667
- | `onSelectionChange` | `(selection) => void` |
668
- | `renderCell` | `(record, key, index) => ReactNode` |
669
- | `groupBy` | `string \| string[]` |
670
- | `activeKey` | `string \| null` |
671
- | `selectedKeys` | `string[]` |
672
- | `header` / `footer` | `ReactNode` |
673
- | `headerClassName` / `bodyClassName` / `footerClassName` / `scrollClassName` / `selectedClassName` / `heightClassName` | `string` |
674
-
675
- ### Gallery
676
- ```tsx
677
- <Gallery
678
- records={records}
679
- overlays={[{ position: 'topRight', badge: { variant: 'success', children: 'New' } }]}
680
- columns={3}
681
- gap={2}
682
- sortable={{ field: 'name', dir: 'asc' }}
683
- pagination={{ limit: 20 }}
684
- onRowClick={(record) => {}}
685
- onSelectionChange={(sel) => {}}
686
- header="Titolo"
687
- groupBy="status"
688
- />
689
- ```
690
-
691
- `position`: `'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight' | 'middleLeft' | 'middleRight'`
692
-
693
- | Prop | Tipo |
694
- |---|---|
695
- | `records` | `GalleryRecord[]` (`{ img?, thumbnail?, name?, width?, height? }`) |
696
- | `columns` | `1 \| 2 \| 3 \| 4 \| 6` |
697
- | `gap` | `0 \| 1 \| 2 \| 3 \| 4 \| 5` |
698
- | `overlays` | `GalleryOverlay[]` |
699
- | `sortable` | `boolean \| OrderConfig` |
700
- | `pagination` | `PaginationParams` |
701
- | `onRowClick` | `(record) => void` |
702
- | `onSelectionChange` | `(selection) => void` |
703
- | `groupBy` | `string \| string[]` |
704
- | `selectedKeys` | `string[]` |
705
- | `header` / `footer` | `ReactNode` |
706
- | Classi CSS: `headerClassName`, `bodyClassName`, `footerClassName`, `scrollClassName`, `selectedClassName` | `string` |
707
-
708
- ### Tab
709
- ```tsx
710
- import { Tab, TabItem } from '@llmnative/react'
711
-
712
- <Tab defaultIndex={0} layout="top">
713
- <TabItem label="Generale">{content1}</TabItem>
714
- <TabItem label="SEO">{content2}</TabItem>
715
- </Tab>
716
- ```
717
- `layout`: `'default' | 'top' | 'left' | 'right' | 'bottom'`
718
- Le schede sono `<TabItem>`, export separato: `Tab.Item` non esiste.
719
-
720
- ### Image
721
- ```tsx
722
- <Image src="..." fit="cover" position="center" width={400} height={300} />
723
- ```
724
- `fit`: `'cover' | 'contain' | 'fill' | 'scale-down' | 'none'`
725
-
726
- ### Pagination (standalone)
727
- ```tsx
728
- <Pagination records={items} limit={20}>
729
- {(pageRecords, offset) => pageRecords.map(r => <Row key={r._key} record={r} />)}
730
- </Pagination>
731
- ```
732
-
733
- ### Percentage
734
- ```tsx
735
- <Percentage value={75} appearance="bar" variant="success" showText />
736
- <Percentage value={0.75} appearance="circle" size={60} />
737
- ```
738
-
739
- | Prop | Tipo | Default |
740
- |---|---|---|
741
- | `value` | `number` | — |
742
- | `max` | `number` | `100` |
743
- | `min` | `number` | — |
744
- | `appearance` | `'bar' \| 'circle'` | `'bar'` |
745
- | `variant` | `ColorType` | — |
746
- | `trackVariant` | `ColorType` | — |
747
- | `thickness` | `number` | — (px) |
748
- | `showText` | `boolean` | — |
749
- | `size` | `number` | Diametro in modalità `'circle'` (px) |
750
- | `fontSize` | `number` | — |
751
- | `label` | `string` | — |
752
-
753
- ### DescriptionList
754
- Coppie etichetta → valore in sola lettura (profilo, dati di un record, riepiloghi), rese come `<dl>`/`<dt>`/`<dd>`. Da usare al posto di markup `<dl>` scritto a mano; per dati modificabili usare i campi di `<Form>`, per molti record `<Table>`/`<Grid>`.
755
- ```tsx
756
- <DescriptionList items={[{ label: 'Email', value: 'a@b.it' }, { label: 'Telefono', value: null }]} />
757
- <DescriptionList layout="stacked" columns={4} truncate items={[{ label: 'Stato', value: <Badge variant="success">Spedito</Badge> }]} />
758
- ```
759
-
760
- | Prop | Tipo | Default |
761
- |---|---|---|
762
- | `items` | `DescriptionListItem[]` — `{ key?, label, value?, title? }` | — |
763
- | `layout` | `'horizontal' \| 'stacked'` | `'horizontal'` (etichette a sinistra, impilate su mobile) |
764
- | `columns` | `1 \| 2 \| 3 \| 4 \| 5 \| 6` | `1` (solo `stacked`, dal breakpoint `lg`) |
765
- | `labelWidth` | `string` (lunghezza CSS) | `'12rem'` (solo `horizontal`) |
766
- | `emptyValue` | `ReactNode` | `'—'` per `null` / `undefined` / `''` (lo `0` resta) |
767
- | `truncate` | `boolean` | `false`; un valore testuale diventa il suo `title` |
768
- | Classi | `wrapperClassName`, `className`, `itemClassName`, `labelClassName`, `valueClassName` | tema `DescriptionList` |
769
-
770
- ### Tree
771
- Albero accessibile di nodi (cartelle e file, gerarchie): pattern WAI-ARIA tree, un solo tab stop, frecce per muoversi, → / ← per aprire e chiudere, Invio o Spazio per selezionare. Le cartelle si aprono al click, le foglie si selezionano.
772
- ```tsx
773
- <Tree nodes={treeFromPaths(paths)} defaultExpanded selectedId={path} onSelect={(node) => setPath(node.id)} ariaLabel="File" />
774
- <Tree nodes={[{ id: 'a', label: 'Docs', children: [{ id: 'a/1', label: 'README.md', badge: <Badge>new</Badge> }] }]} />
775
- ```
776
- | Prop | Tipo | Note |
777
- |---|---|---|
778
- | `nodes` | `TreeNode[]` — `{ id, label, icon?, badge?, description?, children?, disabled? }` | `id` unico; con `children` è una cartella |
779
- | `selectedId` + `onSelect` / `defaultSelectedId` | `string \| null` | selezione controllata o no |
780
- | `expanded` + `onExpandedChange` / `defaultExpanded` | `string[]`; `defaultExpanded` anche `true` (tutto aperto) | apertura controllata o no |
781
- | `selectableBranches` | `boolean` (default `false`) | anche le cartelle si selezionano |
782
- | `ariaLabel` | `string` | nome accessibile |
783
- | Classi | `wrapperClassName`, `className`, `itemClassName`, `selectedClassName` | tema `Tree` |
784
-
785
- `treeFromPaths(paths, leaf?)` costruisce l'albero da percorsi `a/b/c`: cartelle prima dei file, ordinati; l'id di un file è il percorso, quello di una cartella `percorso/`; `leaf(path)` decora le foglie (label, icona, descrizione…).
786
-
787
- ### Dropdown
788
- ```tsx
789
- <Dropdown trigger={<Icon name="menu" />} position="end">
790
- <DropdownItem label="Modifica" icon="edit" onClick={() => {}} />
791
- <DropdownItem label="Elimina" icon="trash" variant="danger" />
792
- <DropdownDivider />
793
- <DropdownHeader label="Azioni rapide" />
794
- </Dropdown>
795
- ```
796
-
797
- Azioni secondarie di una voce (CR-107): `actions` mostra icone in fondo alla riga, al passaggio
798
- del mouse o al focus (sempre sui dispositivi touch). Non selezionano la voce e lasciano il menu aperto
799
- salvo `closeOnClick`.
800
-
801
- ```tsx
802
- <DropdownItem icon="messages-square" onClick={() => open(chat)}
803
- actions={[{ icon: 'archive', label: 'Archivia', onClick: () => archive(chat) }]}>
804
- {chat.title}
805
- </DropdownItem>
806
- ```
807
-
808
- Per elenchi caricati dinamicamente usare `AsyncDropdown`: gestisce ricerca con debounce,
809
- cancellazione delle richieste precedenti tramite `AbortSignal` e stati loading/empty/error.
810
-
811
- ```tsx
812
- <AsyncDropdown
813
- trigger={<ActionButton label="Select user" />}
814
- loadItems={(query, signal) => users.search(query, { signal })}
815
- getItemId={user => user.id}
816
- renderItem={user => user.name}
817
- onSelect={user => setUser(user)}
818
- selectedId={user?.id}
819
- />
820
- ```
821
-
822
- ### ContextMenu
823
- ```tsx
824
- <ContextMenu trigger="/" searchable>
825
- <ContextMenu.Heading>Comandi</ContextMenu.Heading>
826
- <ContextMenu.Item label="Titolo" value="# " icon="heading" />
827
- <ContextMenu.Separator />
828
- <ContextMenu.Item label="Bold" value="**bold**" icon="bold" />
829
- </ContextMenu>
830
- ```
831
- Funziona su qualsiasi `<textarea>` / `<input>` figlio. Trigger custom (`/`, `@`, `{`), filtro searchable, navigazione tastiera, floating positioning.
832
- `ContextMenu.Item` accetta `description` (opzionale): seconda riga attenuata (`text-muted-foreground`)
833
- sotto la label, troncata; il menu è largo al massimo 28rem e il testo completo resta nel `title`
834
- della voce. Il filtro cerca nel testo digitato dopo il trigger su label, value e description (CR-111).
835
-
836
- ```tsx
837
- <ContextMenu.Item label="/plan" value="plan" icon="list" description="Scrive il piano della release" />
838
- ```
839
-
840
- | Prop | Tipo | Note |
841
- |---|---|---|
842
- | `trigger` | `string` (required) | Es. `"/"`, `"@"`, `"{"` |
843
- | `searchable` | `boolean` | Filtro testuale |
844
- | `controlled` | `ContextMenuControlledState` | Stato controllato esterno |
845
- | `onSelect` | `(item, context) => void` | |
846
-
847
- **EditorCommand** (usato da `commands` prop su `Chatbot`, `Prompt`, `RichText`, `CodeEditor`):
848
- ```ts
849
- {
850
- name: string;
851
- description?: string;
852
- icon?: string;
853
- group?: string;
854
- consumeSuffix?: string;
855
- handler?: (context: TextCommandContext) => string | Promise<string>;
856
- }
857
- ```
858
-
859
- `description` compare sotto `/name` nel menu dei comandi di tutti e quattro i consumer e il filtro
860
- la usa (digitare `/release` trova un comando descritto come "…release…"). Un comando senza `handler`
861
- sostituisce il trigger con `/name ` (spazio finale) e il testo resta tale: in `Chatbot`/`Prompt` il
862
- messaggio inviato è letteralmente `"/name …"`, da interpretare a cura di chi lo riceve.
863
-
864
- `consumeSuffix` elimina una chiusura automatica adiacente durante la sostituzione del trigger,
865
- utile quando un comando cambia famiglia sintattica (per esempio da `{{ ... }}` a `{% ... %}`).
866
-
867
- ### Altre primitive
868
- ```tsx
869
- <Icon name="user" size={20} /> // usa provider icone configurato
870
- <ImageAvatar src="..." title="Mario" alt="Mario" width={40} height={40} />
871
- <Identicon value="acme/app" size={32} title="acme/app" /> // icona generata dal valore, stile GitHub
872
- <Loader show={isLoading}>{content}</Loader> // indicatore al posto dei figli finché show è true
873
- <Loader show>{null}</Loader> // solo indicatore (es. pagina in caricamento)
874
- <Code language="tsx">{snippet}</Code> // syntax highlight
875
- <GridSystem.Row><GridSystem.Col xs={12} md={6}>...</GridSystem.Col></GridSystem.Row>
876
- <LocaleSwitcher locales={[{ code: 'it', label: 'Italiano' }]} />
877
- <ThemeSwitcher />
878
- <ProviderSwitcher />
879
- <LayoutBuilder components={...} />
880
- ```
881
-
882
- ### Charts (CR-112)
883
- Grafici SVG senza dipendenze, dal modulo `charts`. Colori come token del tema: `color` è uno slot della
884
- palette categoriale (`1…8` → `--rf-chart-N`, definiti in `globals.css` con la variante scura e
885
- sovrascrivibili dal consumer) o un token (`'--rf-success'`); le serie senza colore prendono lo slot
886
- della loro posizione. Larghezza dal contenitore (ResizeObserver), animazioni spente con
887
- `prefers-reduced-motion`, tooltip che segue il puntatore e la tastiera (le aree prendono il focus
888
- finché sono al massimo 40), tabella dei dati `sr-only` con `ariaLabel` come didascalia, stato vuoto
889
- `charts.noData`. `format` è facoltativo: di default il numero nella locale dell'app.
890
-
891
- ```tsx
892
- <ColumnChart ariaLabel="CR chiuse al giorno" columns={[{ label: 'lun', value: 4 }]} markers={[{ position: 3.5, label: 'mediana', dashed: true }]} onColumnClick={(column) => {}} />
893
- <StackedColumnChart ariaLabel="Ore per agente" labels={days} labelEvery={2} format={(v) => `${v} h`}
894
- series={[{ id: 'dev', label: 'Developer', values: dev }, { id: 'qa', label: 'Tester', values: qa, color: 3 }]}
895
- comparison={previousTotals} comparisonLabel="periodo precedente" />
896
- <MeasureBarList ariaLabel="Agenti" // CR-115: barre raggruppate, ogni agente una volta, una barra per misura (colore in legenda), ognuna sulla sua scala
897
- columns={[{ id: 'time', label: 'Ore', format: (v) => `${v} h` }, { id: 'cost', label: 'Costo' },
898
- { id: 'tokens', label: 'Token', parts: [{ id: 'in', label: 'Input' }, { id: 'out', label: 'Output' }] }]} // parts: la barra divisa in proporzione
899
- rows={[{ id: 'dev', label: 'Developer', values: { time: 18, cost: 4.27, tokens: [2400000, 190000] }, trailing: { text: '18 back', tone: 'bad' } }]} />
900
- <SequenceColumnChart ariaLabel="Turni per CR" format={(v) => `${v} min`} // CR-114: ogni colonna nel suo ordine, una serie può tornare
901
- series={[{ id: 'dev', label: 'Developer' }, { id: 'rev', label: 'Reviewer' }]}
902
- columns={[{ label: '#34', title: 'CR #34', segments: [{ series: 'dev', value: 18 }, { series: 'rev', value: 6 }, { series: 'dev', value: 11 }] }]}
903
- onColumnClick={(column) => {}} />
904
- <LineChart ariaLabel="Lead time" labels={days} threshold={{ value: 6.5, label: 'obiettivo' }} baseline={0} domain={[0, 10]}
905
- series={[{ id: 'now', label: 'Ora', values: [3, null, 5], area: true, band: { min, max } }, { id: 'before', label: 'Prima', values: prev, dashed: true }]} />
906
- <AreaChart ariaLabel="Flusso cumulativo" labels={days} stacked series={[{ id: 'closed', label: 'Chiuse', values: closed }]} />
907
- <ScatterChart ariaLabel="Costo contro rework" xLabel="Costo" yLabel="Rework" sizeLabel="Turni"
908
- series={[{ id: 'sonnet', label: 'Sonnet' }]} points={[{ id: '1', label: 'Developer', x: 0.04, y: 0.3, size: 30, series: 'sonnet' }]} onPointClick={(point) => {}} />
909
- <DivergingBarChart ariaLabel="Valore e costo" upLabel="Valore" downLabel="Costo" bars={[{ label: 'lun', up: 120, down: null }]} />
910
- <BarList ariaLabel="Costo per agente" rows={[{ id: 'dev', label: 'Developer', value: 1.84, trailing: { text: '+12%', tone: 'bad' } }]} />
911
- <Heatmap ariaLabel="Turni per ora" rowLabels={agents} columnLabels={hours} columnLabelEvery={2} values={matrix} />
912
- <CalendarHeatmap ariaLabel="Turni per giorno" days={[{ date: '2026-11-02', value: 4 }, { date: '2026-11-03', value: null }]} />
913
- <Sparkline values={[1, 3, null, 2]} ariaLabel="Andamento" /> // senza ariaLabel è decorativa
914
- <AnimatedNumber value={3.85} format={(v) => `$${v.toFixed(2)}`} />
915
- ```
916
-
917
- Parti comuni per grafici propri: `useChartTooltip()` (`show`, `showAt`, `hide`, `element`), `ChartLegend`,
918
- `ChartDataTable`, `useChartWidth(fallback)`, `useAnimatedValues(values)`, `useReveal(key)`,
919
- `useChartFormat(format?)`, `chartToken(color)`, `chartFill(token, alpha?)`, `niceMax`, `ticks`.
920
-
921
- ---
922
-
923
- ## Blocks
924
-
925
- ```tsx
926
- <Breadcrumbs trail={[{ label: 'Home', href: '/' }, { label: 'Utenti' }]} separator="/" jsonLd />
927
- <Brand url="/" label="MyApp" logo="/logo.svg" width={120} />
928
- <Search onQueryChange={(e) => setQ(e.target.value)} />
929
- <Notifications items={[...]} seeAllUrl="/notifications" onMarkAllRead={() => {}} onItemClick={(item) => markRead(item.id)} />
930
- <Notifications items={[{ id: 'a', title: 'Fonte senza Action', description: 'crm · sources/notes/a.md', url: '/projects/crm', time: 'ora', icon: 'file', actions: [{ label: "Apri l'Action", icon: 'play', onClick: openAction, variant: 'primary' }] }]} />
931
- <Carousel images={[...]} />
932
- <Toolbar items={[...]}>
933
- {children}
934
- </Toolbar>
935
- <SideNav />
936
- <ListCard records={records} onRowClick={(r) => {}} />
937
- ```
938
-
939
- **Brand:**
940
- | Prop | Tipo |
941
- |---|---|
942
- | `url` | `string` |
943
- | `label` | `string` |
944
- | `logo` | `string` |
945
- | `width` / `height` | `number` |
946
- | `wrapperClassName` / `className` / `logoClassName` / `labelClassName` | `string` |
947
-
948
- **SideNav:**
949
- | Prop | Tipo |
950
- |---|---|
951
- | `items` | `SideNavItemDef[]` (in alternativa a `menuKey`) |
952
- | `menuKey` | `string` — voci dal menu registrato in `<App>` |
953
- | `bottomItems` | `SideNavItemDef[]` — voci fissate in fondo, sopra il footer e fuori dalla lista scorrevole (es. Impostazioni) |
954
- | `header` / `footer` | `ReactNode` |
955
- | `collapsed` + `onCollapsedChange` / `defaultCollapsed` | `boolean` — compressione controllata o no |
956
- | `showIcons` / `showCollapseButton` | `boolean` (default `true`) |
957
- | `embedded` | `boolean` — solo le voci, senza guscio (drawer, pannelli); `bottomItems` seguono le voci principali |
958
-
959
- `SideNavItemDef`: `{ path, title?, icon?, group?, end?, badge?, children? }`. La voce attiva ha
960
- `aria-current="page"`.
961
-
962
- ```tsx
963
- <SideNav
964
- items={[{ path: '/dashboard', title: 'Dashboard', icon: 'home' }]}
965
- bottomItems={[{ path: '/settings', title: 'Impostazioni', icon: 'settings' }]}
966
- />
967
- ```
968
-
969
- **ImageAvatar:**
970
- | Prop | Tipo |
971
- |---|---|
972
- | `src` | `string` (obbligatoria) |
973
- | `width` / `height` | `number` |
974
- | `title` / `alt` | `string` |
975
- | `fit` | `AvatarFit` |
976
- | `badge` | `BadgeDescriptor` |
977
- | `feedback` | `ReactNode` |
978
-
979
- **Identicon:** l'icona di un'entità senza immagine (repository, tenant, utente senza foto), come quelle di
980
- GitHub: griglia 5×5 simmetrica, celle e tinta da un hash di `value`. Lo stesso valore dà sempre la stessa
981
- icona; niente rete né storage. Default: `rounded-md bg-muted` (tema `Identicon.className`).
982
- `identiconPattern(value)` restituisce celle e tinta, per chi la disegna altrove.
983
- | Prop | Tipo |
984
- |---|---|
985
- | `value` | `string` (obbligatoria) |
986
- | `size` | `number` (px, default 40) |
987
- | `title` | `string`: nome accessibile (`role="img"`); senza, `aria-hidden` |
988
- | `before` / `after` / `className` / `wrapperClassName` | come le altre primitive |
989
-
990
- **Search:**
991
- | Prop | Tipo |
992
- |---|---|
993
- | `onQueryChange` | `(e: React.ChangeEvent<HTMLInputElement>) => void` |
994
-
995
- **Notifications:**
996
- | Prop | Tipo |
997
- |---|---|
998
- | `items` | `NotificationItem[]` |
999
- | `badge` | `BadgeProps` |
1000
- | `seeAllUrl` | `string` |
1001
- | `onMarkAllRead` | `() => void` |
1002
- | `onItemClick` | `(item, index) => void` — una voce aperta (es. per segnarla letta); il menu si chiude |
1003
- | `motion` | `MotionReference` |
1004
-
1005
- `NotificationItem`: `{ id?, title, description?, url?, external?, time, icon, read?, actions? }`. `description` è la
1006
- riga sotto il titolo; senza `url` la voce si mostra e basta; con `external` l'`url` è un indirizzo aperto
1007
- in una nuova scheda (`<a target="_blank">`), altrimenti una rotta (`Link`). `actions`
1008
- (`NotificationAction[]`: `{ label, icon?, onClick, variant?: 'primary' | 'default', closeOnClick? }`) sono
1009
- pulsanti sotto la voce: non la aprono, mostrano il caricamento finché la promessa di `onClick` è in corso
1010
- e lasciano il menu aperto salvo `closeOnClick`.
1011
-
1012
- **ListCard:**
1013
- | Prop | Tipo |
1014
- |---|---|
1015
- | `title` / `description` / `meta` | `ReactNode` |
1016
- | `badge` | `ReactNode` |
1017
- | `icon` | `string \| ReactNode` |
1018
- | `trailing` / `footer` / `children` | `ReactNode` |
1019
- | `href` | `string` |
1020
- | `external` / `active` / `disabled` / `dashed` / `compact` | `boolean` |
1021
- | `align` | `'start' \| 'center'` |
1022
- | `onClick` | `(e) => void` |
1023
- | Classi CSS: `titleClassName`, `descriptionClassName`, `metaClassName`, `badgeClassName`, `leadingClassName`, `bodyClassName`, `headerClassName`, `trailingClassName`, `footerClassName` | `string` |
1024
-
1025
- **SortableList (CR-120):** card compatte (ListCard) in un ordine che la persona sceglie: le trascina per la
1026
- maniglia, o con le frecce su/giù sulla maniglia; l'annuncio della nuova posizione va agli screen reader.
1027
- ```tsx
1028
- <SortableList
1029
- items={accounts}
1030
- getKey={(a) => a.id}
1031
- label="Account"
1032
- numbered
1033
- onReorder={(next, { fromIndex, toIndex, item }) => setAccounts(next)}
1034
- renderItem={(a) => ({ title: a.email, meta: a.added, badge: <Badge variant="success">Disponibile</Badge>, trailing: <ActionButton icon="trash-2" … /> })}
1035
- emptyState={<p>Nessun account</p>}
1036
- />
1037
- moveItem(['a', 'b', 'c'], 0, 2) // ['b', 'c', 'a']
1038
- ```
1039
- | Prop | Tipo |
1040
- |---|---|
1041
- | `items` / `getKey` | `TItem[]` / `(item) => string` |
1042
- | `renderItem` | `(item, index) => SortableListCard` (`title`, `description`, `meta`, `badge`, `icon`, `trailing`, `active`, `disabled` di ListCard) |
1043
- | `onReorder` | `(items, { fromIndex, toIndex, item }) => void`; senza, nessuna maniglia |
1044
- | `label` / `numbered` / `disabled` / `emptyState` | `string` / `boolean` / `boolean` / `ReactNode` |
1045
- | Classi CSS: `className`, `itemClassName`, `cardClassName` | `string` |
1046
-
1047
- **Dropdown:**
1048
- | Prop | Tipo |
1049
- |---|---|
1050
- | `trigger` | `string \| ReactNode \| DropdownTogglerProps` |
1051
- | `badge` | `BadgeProps` |
1052
- | `header` / `footer` | `ReactNode` |
1053
- | `defaultOpen` / `open` | `boolean` |
1054
- | `onOpenChange` | `(open) => void` |
1055
- | `position` | `'start' \| 'end'` |
1056
- | `placement` | `'auto' \| 'top' \| 'bottom'` |
1057
- | `strategy` | `'fixed' \| 'absolute'` |
1058
-
1059
- // Menu — renderizza una sezione del menuConfig passato ad <App>
1060
- <Menu menuKey="main" /> // 'main' o qualsiasi chiave definita in MenuConfig
1061
- <Menu menuKey="topbar" className="nav flex-row gap-2" />
1062
- // NON usare context= — la prop si chiama menuKey
1063
-
1064
- // AuthButton — login/logout con il provider auth configurato
1065
- <AuthButton />
1066
- ```
1067
-
1068
- ---
1069
-
1070
- ## Widgets
1071
-
1072
- ### MarkdownReader
1073
- ```tsx
1074
- <MarkdownReader
1075
- content={markdownString}
1076
- onInternalLinkClick={(href, e) => { e.preventDefault(); navigate(href) }}
1077
- wrapperClassName="prose"
1078
- />
1079
- ```
1080
-
1081
- ### Messaggi di chat: ChatMarkdown, ChatReasoning, ChatQuestions (CR-109), ChatActivity (CR-123)
1082
-
1083
- Parti di un messaggio di un modello, da comporre nel proprio thread (anche accanto a `Chatbot`).
1084
-
1085
- ```tsx
1086
- // Markdown GFM del messaggio: tabelle (scorrono dentro di sé in un pannello stretto), elenchi,
1087
- // titoli, citazioni, task list, codice con evidenziazione (Prism, lazy) e pulsante Copia, link a
1088
- // indirizzi in una nuova scheda (noopener). Sanitizzato: niente HTML grezzo, niente javascript:.
1089
- // streaming: chiude ciò che la fine del testo lascia aperto (fence, intestazione di tabella,
1090
- // **grassetto**, `codice`, link) così il layout non salta mentre arriva. Off per un messaggio finito.
1091
- <ChatMarkdown content={text} streaming={running} onLinkClick={(href) => navigate(href)} />
1092
- // tone="muted", highlight={false}, components (come react-markdown), className,
1093
- // classNames={{ root, paragraph, heading, list, blockquote, tableWrapper, table, th, td, codeBlock, codeHeader, code, inlineCode, link }}
1094
- // repairStreamingMarkdown(text) è la stessa riparazione, pura.
1095
-
1096
- // Ragionamento: chiuso dietro "Ragionamento" / "Ha ragionato per 12 s"; aperto mentre arriva
1097
- // (se l'utente non lo chiude) e richiuso alla fine. Contenuto con ChatMarkdown, tono attenuato.
1098
- <ChatReasoning content={reasoning} streaming={thinking} duration={12} />
1099
- // defaultOpen, open + onOpenChange (controllato), label, icon ('brain'), className, classNames={{ root, trigger, content }}
1100
-
1101
- // Domande interattive (formato dello strumento `question` di opencode / elicitation MCP):
1102
- <ChatQuestions
1103
- questions={[
1104
- { id: 'db', header: 'Database', question: 'Quale database?', recommended: 0,
1105
- options: [{ label: 'Postgres', description: 'Relazionale' }, { label: 'SQLite' }] },
1106
- { id: 'features', header: 'Funzioni', question: 'Quali funzioni?', multiple: true,
1107
- options: [{ label: 'Auth' }, { label: 'Ricerca' }] },
1108
- ]}
1109
- onSubmit={async (answers) => send(answers)} // [{ id, header, values: string[] }] in ordine
1110
- />
1111
- // Una scheda per domanda (header) + Riepilogo e un solo Invia; opzioni numerate 1-2-3 o A-B-C
1112
- // (numbering, altrimenti dedotto da etichette "A) …" / "1. …", che vengono tolte); consigliata
1113
- // (recommended: indice da 0 o etichetta; anche il suffisso "(Recommended)"); multiple; "Altro" con
1114
- // testo libero (allowOther, default true; per domanda `custom`); senza options è a testo libero.
1115
- // Il testo libero è una textarea (CR-110) di 2 righe che cresce col testo fino a ~160px e poi
1116
- // scorre; ridimensionabile in verticale. Lì Invio va a capo, Ctrl/Cmd+Invio prosegue o invia
1117
- // (suggerimento `chat.textKeyboardHint` nel piè mentre si scrive).
1118
- // Tastiera: numeri (o lettere con A-B-C) scelgono, frecce sinistra/destra tra le schede, su/giù tra
1119
- // le opzioni, Spazio seleziona, Invio prosegue o invia (su una scelta singola prima la sceglie;
1120
- // nel testo libero serve Ctrl/Cmd+Invio).
1121
- // Ruoli tablist/tab/tabpanel, radiogroup/radio o group/checkbox.
1122
- // Scelta singola: il click sceglie e passa alla domanda dopo. onSubmit che rifiuta lascia il form.
1123
- // answers={[…]} mostra un insieme già risposto (sola lettura); disabled, autoFocus, submitLabel,
1124
- // classNames={{ root, tabs, tab, panel, question, option, optionSelected, footer, summary }}
1125
-
1126
- // Il lavoro di un agente (CR-123), come negli assistenti AI: gruppi di passi (icona, label, quanti,
1127
- // dettagli brevi: query, file, comandi; quanti falliti) con le righe sotto aperte da "Comandi";
1128
- // le parole dell'agente in Markdown; come è finito; i file cambiati con "Vedi le modifiche";
1129
- // il registro grezzo a un clic. Il consumer traduce il suo log negli item.
1130
- <ChatActivity
1131
- items={[
1132
- { type: 'steps', icon: 'search', label: 'Esplora il repository', count: 3, detail: ['git status'], lines: ['git status --short'] },
1133
- { type: 'text', text: 'Aggiungo il comando e il suo test.' },
1134
- { type: 'end', ok: true, text: 'success · 9 steps' },
1135
- ]}
1136
- files={['functions/src/catalog/index.js']} onShowChanges={() => openDiff()} log={rawLines}
1137
- />
1138
- // className, classNames={{ root, step, text, files, log }}
1139
- ```
1140
-
1141
- ### ImageEditor
1142
- ```tsx
1143
- <ImageEditor src="..." onSave={(dataUrl) => save(dataUrl)} />
1144
- ```
1145
-
1146
- `ImageEditor` e un singolo componente pubblico. La libreria pesante `tui-image-editor` viene importata lazy a runtime dentro il componente, quindi non viene scaricata finche l'editor non viene effettivamente montato.
1147
-
1148
- ### TabDynamic
1149
- Tab con lazy loading dei contenuti — gestione dinamica aggiunta/rimozione tab.
1150
-
1151
- ---
1152
-
1153
- ## AI Integration
1154
-
1155
- ```ts
1156
- import { useAIProvider, getAIModelCatalog, createAIProviderRegistry } from '@llmnative/react'
1157
-
1158
- // Hooks
1159
- const provider = useAIProvider() // provider di default
1160
- const registry = useAIProviderRegistry() // tutti i provider AI registrati
1161
- const catalog = getAIModelCatalog() // modelli disponibili
1162
- // ogni modello: { id, provider, model, label, pricing? } — pricing in USD per 1M token
1163
- // { input, output, currency: 'USD', source: 'provider' | 'models.dev' }; assente = prezzo
1164
- // non trovato (il modello resta in lista). isFreeAIModel(m) → input e output a 0.
1165
- // Il model picker di Prompt/Chatbot mostra "$in / $out", evidenzia i free, segnala i mancanti,
1166
- // e raggruppa per provider (ChatbotModelOption.group = providerLabel) con header sticky.
1167
- // CR-121: il pulsante mostra la `label` del modello scelto (non il suo valore); `groupBadge: { label, variant? }`
1168
- // su un'opzione mette un Badge a destra nell'header del suo gruppo (es. Abbonamento / A consumo).
1169
-
1170
- // Provider adapter restituito da useAIProvider()
1171
- const text = await provider.fetch("Scrivi un titolo per: {keyword}", { keyword: "React" })
1172
- const json = await provider.json("Lista di 5 categorie per blog tech")
1173
- const arr = await provider.array("5 tag per: machine learning")
1174
-
1175
- // Provider custom
1176
- class MyAIProvider implements AIProviderAdapter {
1177
- async fetch(prompt: string, options?: AIRequestOptions): Promise<string> { ... }
1178
- async json<T>(prompt: string, options?: AIRequestOptions): Promise<T> { ... }
1179
- async array(prompt: string, options?: AIRequestOptions): Promise<string[]> { ... }
1180
- }
1181
-
1182
- // Quanto ragiona il modello (CR-122): `reasoning: 'low' | 'medium' | 'high' | 'max'` (AIReasoningLevel) su
1183
- // una richiesta. Anthropic: `output_config.effort` sui Claude 4.6 e successivi (+ thinking adaptive su Opus
1184
- // 4.6-4.8 e Sonnet 4.6); OpenAI e compatibili (OpenCode, DeepSeek, Groq…): `reasoning_effort` solo sui modelli
1185
- // di ragionamento di OpenAI (serie o, GPT-5; max = high); OpenRouter: `reasoning.effort` su ogni modello.
1186
- // Altrove (modelli più vecchi, Gemini) non si manda nulla: il default del modello.
1187
- await ai.complete({ prompt: 'Rivedi questo piano', model: 'claude-opus-5-5', reasoning: 'high' })
1188
-
1189
- // Factory per registri esterni
1190
- const registry = createAIProviderRegistry(definitions)
1191
- // Azioni di Chatbot (CR-107): con `content` aprono un menu; senza, sono pulsanti con `onClick`.
1192
- // <Chatbot actions={[{ key: 'finish', icon: 'git-pull-request', label: 'Concludi', showLabel: true,
1193
- // disabled: running, onClick: finish }]} … />
1194
- // Comandi "/" di Chatbot: `commands` (EditorCommand[]) + `commandsTrigger` (default "/").
1195
- // Il menu mostra `/name` e sotto la `description`; il filtro cerca in entrambi (CR-111).
1196
- // Senza `handler` la scelta inserisce "/name " e l'invio manda il testo così com'è.
1197
- // Tastiera: Invio invia a menu chiuso e sceglie il comando evidenziato a menu aperto;
1198
- // Maiusc+Invio (e Invio durante la composizione IME) va a capo.
1199
- // <Chatbot commands={[{ name: 'plan', icon: 'list', description: 'Scrive il piano' }]} … />
1200
- ```
1201
-
1202
- ### Identità dei modelli indipendente dal provider (CR-103)
1203
-
1204
- ```ts
1205
- const index = await loadModelIdentityIndex() // models.dev, un fetch per sessione
1206
- canonicalModelName('DeepSeek V4.1 Flash (Alibaba Cloud)') // 'deepseek v4.1 flash'
1207
- index.models['deepseek v4.1 flash'] // { key, name, family?, providers: { openrouter: [{ id, name }], … } }
1208
- resolveModel(index, 'DeepSeek V4.1 Flash', ['openrouter', 'deepseek'])
1209
- // → { provider: 'openrouter', model: 'deepseek/deepseek-v4.1-flash', ref: 'openrouter/deepseek/deepseek-v4.1-flash' }
1210
- modelOffers(index, 'DeepSeek V4.1 Flash', ['openrouter', 'deepseek']) // CR-119: tutti quelli che lo servono
1211
- // → [{ provider: 'openrouter', model, ref, cost: { input: 0.15, output: 0.3 } }, { provider: 'deepseek', … }]
1212
- // senza `providers`: tutto il catalogo, per chiave del provider. `cost` in USD per 1M token, assente se models.dev non lo dà
1213
- ```
1214
-
1215
- Il nome canonico toglie data, Free, Latest e host o regione tra parentesi; una modalità
1216
- ("(Thinking)", "(Reasoning)", "(Fast)") resta. Per ogni provider l'id preferito è quello stabile (non
1217
- alias `~`, non free tier, non datato). I provider sono le chiavi di models.dev, le stesse di opencode.
1218
- Puro: anche da `@llmnative/react/server`.
1219
-
1220
- ### Chiavi tenute dal server (CR-102)
1221
-
1222
- Per un'app che non mette mai le chiavi dei provider nel browser. Il browser conosce solo quali
1223
- provider sono collegati; il proxy dell'app mette la chiave.
1224
-
1225
- ```ts
1226
- // Browser: gli stessi adapter, con un segnaposto dove andrebbe la chiave. Serve il proxy attivo.
1227
- const registry = createServerCredentialAIRegistry(
1228
- [{ id: 'anthropic' }, { id: 'cloudflare', accountId }, { id: 'openai-compatible', baseUrl }],
1229
- { scope: companyId }, // lettere, cifre, - e _
1230
- )
1231
- Object.entries(registry).forEach(([id, adapter]) => setProvider('ai', id, adapter))
1232
-
1233
- // Server (Node, nessuna dipendenza da React): nel proxy, prima di inoltrare.
1234
- import { resolveServerCredentials } from '@llmnative/react/server'
1235
- const resolved = await resolveServerCredentials({ url: target, headers },
1236
- (scope, provider) => keysOf(scope)[provider]) // { id, apiKey, accountId?, baseUrl? } | undefined
1237
- if (!resolved.ok) return reply(resolved.status, resolved.error) // 404 non collegato, 403 host estraneo
1238
- await fetch(resolved.url, { headers: resolved.headers, ... })
1239
- ```
1240
-
1241
- La chiave va solo agli host del provider (`AI_PROVIDER_HOSTS`, il `baseUrl` di openai-compatible,
1242
- l'account di Cloudflare): una destinazione diversa è rifiutata. `createProxyPlugin(route, log,
1243
- lookup)` fa lo stesso nel proxy di sviluppo di Vite. Senza proxy, `proxyFetch` rifiuta di inviare
1244
- un segnaposto. `createAIProviderRegistry` (chiavi nel browser) resta com'è.
1245
-
1246
- Configurazione API key in `Config.tsx`: `geminiApiKey`, `openaiApiKey`, `anthropicApiKey`, `deepSeekApiKey`, `mistralApiKey`, `openRouterApiKey`, `groqApiKey`, `cloudflare: { apiToken, accountId }` (Cloudflare Workers AI: l'account id fa parte dell'URL; discovery via `ai/models/search`, modelli Workers Paid esclusi salvo `includePaidModels`).
1247
-
1248
- ---
1249
-
1250
- ## Theme e icone
1251
-
1252
- ```tsx
1253
- const theme = useThemeController()
1254
- theme.applyTheme('flat') // BuiltInThemeId ('default' | 'flat' | 'cyber' | 'vscode-dark-modern' | …) | custom
1255
- theme.setMode('dark') // 'light' | 'dark' | 'system'
1256
-
1257
- const icons = useIconController()
1258
- icons.setProvider('phosphor') // 'lucide' | 'phosphor' | custom
1259
- ```
1260
-
1261
- ---
1262
-
1263
- ## Head (SEO)
1264
-
1265
- ```ts
1266
- useHead({
1267
- title: 'Pagina',
1268
- description: '...',
1269
- robots: 'noindex',
1270
- canonical: 'https://...',
1271
- og: { title: '...', image: '...' }
1272
- })
1273
- ```
1274
-
1275
- ---
1276
-
1277
- ## Global state (localStorage)
1278
-
1279
- ```ts
1280
- const vars = useGlobalVars()
1281
- getGlobalVars('key')
1282
- setGlobalVars({ key: 'value' })
1283
- removeGlobalVars('key')
1284
- ```
1285
-
1286
- ---
1287
-
1288
- ## Hooks completi
1289
-
1290
- | Hook | Ritorna |
1291
- |---|---|
1292
- | `useDataProvider(name?)` | `DataProviderAdapter \| null` |
1293
- | `useStorageProvider(name?)` | `StorageProviderAdapter \| null` |
1294
- | `useAuthProvider(name?)` | `AuthProviderAdapter \| null` |
1295
- | `useEmailProvider(name?)` | `EmailProviderAdapter \| null` |
1296
- | `useAIProvider(name?)` | `AIProviderAdapter \| null` |
1297
- | `useAIProviderRegistry()` | `Record<string, AIProviderAdapter>` |
1298
- | `useCredentialsProvider()` | `CredentialsAdapter \| null` |
1299
- | `useTheme()` | `Theme \| undefined` |
1300
- | `useThemeController()` | `ThemeController` |
1301
- | `useIconController()` | `IconController` |
1302
- | `useAccessToken(clientID, renew?)` | `boolean` | Ottiene token per servizio esterno (true = ok) |
1303
- | `useGlobalVars()` | `Record<string, unknown>` |
1304
- | `useHead()` | `HeadController` |
1305
- | `useDocumentHead()` | `HeadController` |
1306
- | `useAssetsHead(title?)` | `void` |
1307
- | `useLanguageHead(lang?)` | `void` |
1308
- | `useSocialHead(config)` | `void` |
1309
- | `usePaginationHead(config)` | `void` |
1310
- | `usePwaHead(config)` | `void` |
1311
- | `useSchemaOrgHead(config)` | `void` |
1312
- | `useHeadLinks(links)` | `void` |
1313
- | `useProxy()` | `(url, init?) => Promise<Response>` |
1314
- | `useImage()` | `UseImageResult` |
1315
- | `useI18n()` | `I18nController` |
1316
- | `useMenu()` | Menu hook |
1317
- | `useFormController(controller?)` | `FormController` |
1318
- | `useFormActions()` | `FormController` |
1319
- | `useApiProvider(pathname?)` | `ApiProviderAdapter \| null` |
1320
- | `useSetProvider(service, driver?)` | `void` |
1321
- | `useProvider(name)` | `ProviderConfigurationState` |
1322
- | `useProviderSession()` | `ProviderSession` |
1323
- | `useDropBoxConnect(config?)` | `DropBoxConnectResult` |
1324
- | `useEnterMotion(baseStyle?, ref?, fallback?)` | `CSSProperties` |
1325
- | `useMotionState(active, ref?, fallback?, baseStyle?)` | `CSSProperties` |
1326
- | `useMotionEffect(ref?, fallback?)` | `ResolvedMotionEffect` |
1327
- | `usePressMotion(hovered, baseStyle?, ref?, fallback?)` | `{ style, pressHandlers }` |
1328
- | `useIconProvider()` | `IconProvider` |
1329
-
1330
- ---
1331
-
1332
- ## Tipi chiave
1333
-
1334
- ```ts
1335
- type RecordProps = Record<string, FieldValue>
1336
- type FieldValue = string | number | boolean | null | undefined | Record<string, unknown> | unknown[]
1337
- type RecordArray = RecordProps[]
1338
-
1339
- type OrderConfig = { field: string; dir: 'asc' | 'desc' }
1340
- type WhereClause = { field: string; op: '==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any'; value: unknown }
1341
-
1342
- interface UIProps {
1343
- before?: React.ReactNode
1344
- after?: React.ReactNode
1345
- wrapperClassName?: string
1346
- className?: string
1347
- }
1348
-
1349
- type UserProfile = { uid?: string; email?: string; displayName?: string; photoURL?: string; [key: string]: unknown }
1350
- ```
1351
-
1352
- ---
1353
-
1354
- ## Utilities
1355
-
1356
- ```ts
1357
- import { cn, converter, Sanitizer, Order, path, fetchJson, fetchRest, fetchWithRetry } from '@llmnative/react'
1358
- import { getKeywordIdeas, getGoogleTrendsData, getGoogleTrendsRelated } from '@llmnative/react'
1359
-
1360
- cn('base', condition && 'extra', className) // tailwind-merge classname
1361
- new Sanitizer().sanitize(html) // XSS sanitizer (non usare dangerouslySetInnerHTML)
1362
- new Order().order(records, { field: 'name', dir: 'asc' }) // ordina record array
1363
- fetchJson(url, init?) // fetch + JSON parse + error handling
1364
- fetchRest(path, init?) // fetch REST con auth
1365
- getKeywordIdeas(keyword) // Google Ads Keyword Ideas
1366
- getGoogleTrendsData(keyword) // Google Trends interest over time
1367
- getGoogleTrendsRelated(keyword) // Google Trends related queries
1368
- ```
1369
-
1370
- ---
1371
-
1372
- ## Scaffold (npx create)
1373
-
1374
- ```bash
1375
- npx @llmnative/react create
1376
- npx @llmnative/react create --yes --provider=mock --template=admin
1377
- ```
1378
-
1379
- Flag disponibili: `--name` `--provider=firebase|supabase|mock|custom` `--ai-provider` `--icon-provider` `--theme` `--template=blank|admin|crm|inventory|project`
1380
-
1381
- **5 template disponibili:**
1382
- | Template | Pagine incluse | Uso tipico |
1383
- |---|---|---|
1384
- | `blank` | home | App vuota — massima libertà |
1385
- | `admin` | home, users, roles, settings | Dashboard admin/backoffice |
1386
- | `crm` | home, companies, contacts, deals | CRM |
1387
- | `inventory` | home + gestione inventario | Magazzino |
1388
- | `project` | home + gestione progetti | PM tool |
1389
-
1390
- **Struttura generata in-place nella current directory:**
1391
- ```
1392
- src/
1393
- index.tsx ← App entry
1394
- vite-env.d.ts
1395
- conf/
1396
- app.ts ← providers config letta da .env (VITE_PROVIDER, VITE_AI_PROVIDER...)
1397
- menu.ts ← MenuConfig con path, title, icon, page (layout opzionale: c'è LayoutDefault)
1398
- data/
1399
- mockData.ts ← dati fake per MockDataProvider
1400
- layouts/
1401
- Default.tsx ← layout wrapper (header + sidebar + main + footer)
1402
- sections/
1403
- Header.tsx / Sidebar.tsx / PageHeader.tsx / Footer.tsx ← solo componenti pubblici (SideNav, AuthButton, ActionButton, Brand, Breadcrumbs)
1404
- pages/
1405
- home/HomePage.tsx
1406
- [altre pagine dal template scelto]
1407
- styles/
1408
- globals.css ← @import '@llmnative/react/dist/index.css' + Tailwind override
1409
- .env ← VITE_PROVIDER, VITE_THEME, chiavi API (non committare)
1410
- .env.example ← stessa struttura, valori vuoti (committare)
1411
- vite.config.ts / tsconfig.json / postcss.config.js / index.html
1412
- ```
1413
-
1414
- **Pattern conf/app.ts** (auto-generato, leggere per capire come funziona):
1415
- ```ts
1416
- import type { AppProvidersConfig } from '@llmnative/react'
1417
- import { mockData } from '../data/mockData'
1418
- const env = import.meta.env
1419
-
1420
- export const providers: AppProvidersConfig = {
1421
- mock: { data: mockData },
1422
- ai: { openaiApiKey: env.VITE_OPENAI_API_KEY ?? '' }, // AI dentro providers, non prop <App>
1423
- services: { data: 'mock', auth: 'googleAuth' },
1424
- }
1425
- ```
1426
-
1427
- Driver per `VITE_PROVIDER`: `firebase` → `firestoreDb` + `firestorage` + `firebaseAuth`; `supabase` → `supabaseDb` + `supabaseStorage` + `supabaseAuth`; `mock` → `mock` + `googleAuth`. `index.tsx` passa `LayoutDefault={Default}` ad `<App>`.
1428
-
1429
- ---
1430
-
1431
- ## Gotchas — pitfall frequenti
1432
-
1433
- | Errore | Causa | Fix |
1434
- |---|---|---|
1435
- | `aiConfig` prop non esiste su `<App>` | La config AI va dentro `providers.ai`, NON come prop separata | `providers={{ ai: { openaiApiKey } }}` |
1436
- | `inputType` o `Input.Number`/`Input.Email` non esistono | Il tipo HTML è la prop `type` | `<Input type="number">`, `<Input type="email">`, `<Input type="date">` |
1437
- | `Menu context=` non esiste | La prop si chiama `menuKey` | `<Menu menuKey="main" />` |
1438
- | `SignInButton` non esiste | Rinominato | `<AuthButton />` |
1439
- | `firebase: { config: ... }` errato | FirebaseConfig è flat | `firebase: { apiKey, authDomain, databaseURL, ... }` |
1440
- | `google: { oAuth2: { clientId } }` errato | GoogleProviderConfig è flat | `google: { clientId, scope }` |
1441
- | `children` su `Grid` | Grid non accetta children | Usa `form={<Fields />}` per il form inline |
1442
- | `recordId` su `Form` | Prop non esiste | La chiave del record viene da URL automaticamente |
1443
- | `MenuConfig` non importabile | Era type interno | Ora esportato: `import type { MenuConfig } from '@llmnative/react'` |
1444
- | `GridCellContext` non importabile | Mancava dall'index | Ora esportato: `import type { GridCellContext } from '@llmnative/react'` |
1445
-
1446
- ---
1447
-
1448
- ## Dove cercare nel codice sorgente
1449
-
1450
- | Cosa | File |
1451
- |---|---|
1452
- | Form | `src/components/widgets/Form.tsx` |
1453
- | Grid | `src/components/widgets/Grid.tsx` |
1454
- | Prompt | `src/components/widgets/Prompt.tsx` |
1455
- | Campi form | `src/components/ui/fields/` |
1456
- | Blocks (Menu, Toolbar, Notifications, Dropdown…) | `src/components/blocks/` |
1457
- | Provider data Firebase (RTDB) | `src/providers/data/firebase.ts` |
1458
- | Provider data Firestore | `src/providers/data/firestore.ts` |
1459
- | Provider data Supabase | `src/providers/data/supabase.ts` |
1460
- | Provider storage Firebase | `src/providers/storage/firebase.ts` |
1461
- | Provider storage Supabase | `src/providers/storage/supabase.ts` |
1462
- | Provider auth Firebase | `src/providers/auth/firebase/FirebaseAuthProvider.ts` |
1463
- | Provider auth Supabase | `src/providers/auth/supabase/` |
1464
- | Provider auth Google | `src/providers/auth/google/` |
1465
- | Provider auth Dropbox | `src/providers/auth/dropbox/` |
1466
- | Provider email Gmail | `src/providers/email/google/GmailEmailProvider.ts` |
1467
- | Provider AI definitions | `src/providers/ai/` |
1468
- | Provider credenziali | `src/providers/credentials/` |
1469
- | Provider session | `src/providers/ProviderSession.ts` |
1470
- | Proxy CORS | `src/providers/proxy.ts` |
1471
- | Motion system | `src/motion.ts` |
1472
- | I18n | `src/I18n.tsx` |
1473
- | Dropbox integration | `src/providers/dropbox/` |
1474
- | Interfaccia DataProvider | `src/providers/data/DataProvider.ts` |
1475
- | Interfaccia StorageProvider | `src/providers/storage/StorageProvider.ts` |
1476
- | Interfaccia AuthProvider | `src/providers/auth/AuthProvider.ts` |
1477
- | Interfaccia EmailProvider | `src/providers/email/EmailProvider.ts` |
1478
- | Interfaccia AIProvider | `src/providers/ai/AIProvider.ts` |
1479
- | Registry provider | `src/providers/manifest.ts` |
1480
- | Config provider | `src/providers/ProviderConfiguration.ts` |
1481
- | SEO / Google Trends | `src/providers/seo/google/` |
1482
- | Sistema tema | `src/Theme.tsx` |
1483
- | Config runtime | `src/Config.tsx` |
1484
- | Tipi TypeScript | `src/types/` |
1485
- | Utilities pure | `src/libs/` |
1
+ # @llmnative/react — Riferimento completo
2
+
3
+ Framework React AI-first per generazione deterministica di UI. Data-driven di default, schema-driven opzionale.
4
+ Versione 1.0.0 — Apache-2.0
5
+
6
+ ```bash
7
+ npm install @llmnative/react
8
+ import '@llmnative/react/dist/index.css'
9
+ ```
10
+
11
+ ---
12
+
13
+ ## Regole fondamentali
14
+
15
+ - Tutti gli import da `'@llmnative/react'` — mai da sottodirectory
16
+ - I provider sono iniettati via `<App providers={...}>` — mai importati direttamente nei componenti
17
+ - Usare `useDataProvider()`, `useAuthProvider()`, ecc. nei componenti, non istanze dirette
18
+ - TypeScript strict: no `any` — usare `unknown`, `Record<string, unknown>`, tipi specifici
19
+ - Naming props: `view` (presentazione contenuto), `appearance` (guscio visuale), `layout` (disposizione spaziale), `mode` (comportamento operativo), `variant` (tono semantico), `position` (ancoraggio), `size` (scala)
20
+
21
+ ---
22
+
23
+ ## App — Entry point
24
+
25
+ ```tsx
26
+ <App
27
+ providers={{
28
+ firebase: { // FirebaseConfig — tutte le chiavi flat
29
+ apiKey, authDomain, databaseURL, projectId,
30
+ storageBucket, messagingSenderId, appId,
31
+ },
32
+ supabase: { url, anonKey },
33
+ google: { clientId, scope }, // flat — NON { oAuth2: { clientId } }
34
+ dropbox: { clientId }, // DropboxConfig
35
+ mock: { data: mockData },
36
+ ai: { // AIConfig — NON una prop separata di <App>
37
+ openaiApiKey, geminiApiKey, anthropicApiKey,
38
+ deepSeekApiKey, mistralApiKey, openRouterApiKey,
39
+ groqApiKey,
40
+ cloudflare: { apiToken, accountId }, // Cloudflare Workers AI
41
+ },
42
+ proxy: { enable: true, route: '/api/proxy' },
43
+ custom: { data: { myAdapter: new MyDataProvider() } },
44
+ services: {
45
+ data: 'dbRealtime', // DataDriverName
46
+ storage: 'firestorage', // StorageDriverName | null
47
+ auth: 'googleAuth', // AuthDriverName | null
48
+ email: 'gmail', // EmailDriverName | null
49
+ ai: 'openai', // AIDriverName | null
50
+ credentials: 'googleServiceAccount',
51
+ },
52
+ }}
53
+ iconProvider="lucide" // 'lucide' | 'phosphor' | AppIconProviderConfig
54
+ themeProvider="default" // 'default' | 'flat' | 'cyber' | AppThemeProviderConfig
55
+ menuConfig={menuConfig}
56
+ importPage={(path) => import(path)}
57
+ LayoutDefault={MyLayout} // layout wrapper custom (opzionale)
58
+ appName="MyApp" // nome app (opzionale)
59
+ i18n={{ locale: 'it', translations: { ... } }}
60
+ contextProviders={MyContextProvider}
61
+ errorReportUrl="/api/errors"
62
+ debug={import.meta.env.DEV}
63
+ />
64
+ ```
65
+
66
+ ### Testi dei componenti (i18n)
67
+
68
+ I testi fissi dei componenti vengono da `I18nDict` e seguono `i18n.locale` (en, it, de, ru, ar, zh
69
+ inclusi): un testo si cambia con `i18n.translations`, non nel codice. Namespace dei componenti:
70
+ `notifications` (`markAllRead`, `empty`, `emptyHint`), `errorBoundary` (schermata d'errore; fuori da
71
+ `<I18nProvider>`, come l'`ErrorBoundary` radice di `<App>`, resta in inglese), `themeSwitcher`,
72
+ `imageField` (anche i dialoghi immagine di `RichText`), `richText`, `tabDynamic` (`addTab`),
73
+ `breadcrumbs` (`label`, l'`aria-label` del `nav`), `grid` (`tableView`, `galleryView`, `columns`,
74
+ `fields`), `prompt` (anche `Chatbot`: `role`, `language`, `voice`, `style`, `temperature`, `stop`),
75
+ `chat` (`ChatReasoning` e `ChatQuestions`: `reasoning`, `reasoningFor`, `other`, `review`, `submit`, …;
76
+ il codice di `ChatMarkdown` usa `code`).
77
+
78
+ ```tsx
79
+ <App i18n={{ locale: 'it', translations: { it: { notifications: { emptyHint: 'Niente di nuovo' } } } }} />
80
+ ```
81
+
82
+ ### AppThemeProviderConfig
83
+ ```ts
84
+ {
85
+ mode?: 'light' | 'dark' | 'system';
86
+ theme: string;
87
+ themes?: Record<string, {
88
+ preset?: { colors?: ColorScale; radius?: number; font?: string };
89
+ motion?: MotionRegistry;
90
+ components?: Record<string, Partial<ThemeComponent>>;
91
+ }>;
92
+ themeOverride?: Record<string, Partial<ThemeComponent>>;
93
+ }
94
+ ```
95
+
96
+ Built-in themes: `default`, `flat`, `cyber`, `vscode-dark-modern`, `vscode-light-modern`, `vscode-dark-plus`, `vscode-light-plus`, `tokyo-night`, `tokyo-night-light`.
97
+ The VS Code and Tokyo Night themes are compiled from the original VS Code theme JSON (`scripts/themes/vscode`), filling the keys a theme does not list with VS Code's color registry defaults; each one has both modes (`vscode-dark-*` starts dark, `vscode-light-*` light). Status colors (destructive/success/warning/info) stay the framework's.
98
+
99
+ `ColorScale` tokens: `background`, `foreground`, `canvas` (page floor behind cards and panels, `bg-canvas`; falls back to `background`), `card`, `popover`, `primary`, `secondary`, `muted`, `accent`, `destructive`, `success`, `warning`, `info` (each with its `*Foreground`), `border`, `input` (border of form fields), `ring`. A consumer bridging the tokens in its own `@theme inline` adds `--color-canvas: hsl(var(--rf-canvas, var(--rf-background)));`.
100
+
101
+ ---
102
+
103
+ ## Provider System
104
+
105
+ ### Matrix completa
106
+
107
+ | Servizio | Interfaccia | Driver | Config key | Obbligatorio |
108
+ |---|---|---|---|---|
109
+ | data | `DataProviderAdapter` | `mock`, `dbRealtime`, `firestoreDb`, `supabaseDb` | `providers.mock/firebase/supabase` | sì (fallback: mock) |
110
+ | storage | `StorageProviderAdapter` | `firestorage`, `supabaseStorage` | `providers.firebase/supabase` | no |
111
+ | auth | `AuthProviderAdapter` | `googleAuth`, `firebaseAuth`, `supabaseAuth`, `dropboxAuth`, `githubAuth` | `providers.google/firebase/supabase/dropbox/github` | sì (fallback: googleAuth) |
112
+ | email | `EmailProviderAdapter` | `gmail` | `providers.google` | no |
113
+ | ai | `AIProviderAdapter` | `openai`, `gemini`, `anthropic`, `deepseek`, `mistral`, `openrouter`, `opencode`, `opencode-go`, `cloudflare`, `groq` | `Config.tsx AIConfig` | no |
114
+ | credentials | `CredentialsAdapter` | `googleServiceAccount` | `providers.google.serviceAccount` | no |
115
+
116
+ ### Hooks
117
+
118
+ ```ts
119
+ const data = useDataProvider() // DataProviderAdapter | null
120
+ const storage = useStorageProvider() // StorageProviderAdapter | null
121
+ const auth = useAuthProvider() // AuthProviderAdapter | null
122
+ const email = useEmailProvider() // EmailProviderAdapter | null
123
+ const ai = useAIProvider() // AIProviderAdapter | null
124
+ const creds = useCredentialsProvider() // CredentialsAdapter | null
125
+
126
+ // Named provider (multi-provider setup)
127
+ const supabase = useDataProvider('supabase')
128
+ ```
129
+
130
+ ### GitHub (`githubAuth`, sessione sul server dell'app)
131
+
132
+ GitHub richiede il client secret per scambiare il codice: scambio, token e sessione stanno sul server
133
+ dell'app, il browser vede solo il profilo. Config `providers.github = { sessionUrl: '/api/auth/github' }`,
134
+ driver `auth: 'githubAuth'`; funziona con `AuthButton` (pulsante e `aspect="avatar"`) e
135
+ `useAuthProvider('githubAuth')`. Il server espone sotto `sessionUrl`:
136
+
137
+ | Rotta | Risposta |
138
+ |---|---|
139
+ | `GET /login?returnTo=<path>[&scope=…]` | redirect a GitHub, poi di nuovo a `<path>` |
140
+ | `GET /me` | `{ login, name, avatarUrl, email }`, 401 senza sessione |
141
+ | `POST /logout` | chiude la sessione |
142
+
143
+ Lato server, da `@llmnative/react/server`:
144
+
145
+ ```ts
146
+ const oauth = createGitHubOAuth({ clientId, clientSecret, scopes: ['read:org'] })
147
+ oauth.authorizeUrl({ state, redirectUri, codeChallenge }) // PKCE S256
148
+ const { accessToken } = await oauth.exchangeCode({ code, redirectUri, codeVerifier }) // GitHubOAuthError se rifiutato
149
+ await oauth.getUser(accessToken) // { login, name, avatarUrl, email }
150
+ await oauth.getOrganizations(accessToken) // [{ login, avatarUrl, role: 'admin' | 'member' }]
151
+ ```
152
+
153
+ ### Interfacce principali
154
+
155
+ ```ts
156
+ // DataProviderAdapter
157
+ read(path, options?) / set(path, data) / update(path, data) / remove(path)
158
+ subscribe(path, callback: (records: RecordArray) => void): () => void
159
+ count?(path, where?): Promise<number>
160
+
161
+ // StorageProviderAdapter
162
+ upload(file, path): Promise<string|undefined>
163
+ getURL(path) / download(path): Promise<Blob|undefined> / delete(path): Promise<boolean>
164
+
165
+ // AuthProviderAdapter
166
+ signIn(intent?, options?) / signOut() / getUser(): UserProfile|null
167
+ onAuthChange(callback) / getAccessToken(): Promise<string|null>
168
+ ```
169
+
170
+ ### Auth sign-in methods
171
+
172
+ | method | Firebase | Supabase | Google |
173
+ |---|---|---|---|
174
+ | `password` | ✅ | ✅ | — |
175
+ | `anonymous` | ✅ | ✅ | — |
176
+ | `magic_link` | — | ✅ | — |
177
+ | `oauth` (github, apple…) | ✅ | ✅ | — |
178
+ | GIS + scoped token | — | — | ✅ |
179
+
180
+ ```ts
181
+ await auth.signIn({ method: 'password', email: '...', password: '...' })
182
+ await auth.signIn({ method: 'oauth', provider: 'github' })
183
+ // Google: token per API scope
184
+ const token = await auth.getAccessToken('https://www.googleapis.com/auth/gmail.send')
185
+ ```
186
+
187
+ ### CredentialsAdapter (Google Service Account)
188
+ ```tsx
189
+ // Chiama Google APIs lato browser senza Node.js
190
+ <App providers={{ google: { serviceAccount: { clientEmail, privateKey } }, services: { credentials: 'googleServiceAccount' } }} />
191
+
192
+ const creds = useCredentialsProvider()
193
+ const token = await creds.getToken('https://www.googleapis.com/auth/solar')
194
+ ```
195
+
196
+ ### Provider custom
197
+ ```ts
198
+ import { DataProviderAdapter, RecordArray } from '@llmnative/react'
199
+
200
+ export class RestDataProvider implements DataProviderAdapter {
201
+ async read(path: string): Promise<unknown> { ... }
202
+ async set(path: string, data: object): Promise<void> { ... }
203
+ async update(path: string, data: object): Promise<void> { ... }
204
+ async remove(path: string): Promise<void> { ... }
205
+ subscribe(path: string | undefined, callback: (records: RecordArray) => void): () => void {
206
+ return () => undefined
207
+ }
208
+ }
209
+ ```
210
+
211
+ ---
212
+
213
+ ## Grid — CRUD table/gallery
214
+
215
+ ```tsx
216
+ <Grid
217
+ path="/users" // DataProvider-backed — oppure records={array} per in-memory
218
+ columns={[
219
+ { key: 'name', label: 'Nome', sortable: true },
220
+ { key: 'email', label: 'Email' },
221
+ { key: 'role', label: 'Ruolo', render: ({ value }) => <Badge>{value}</Badge> },
222
+ { key: 'date', label: 'Data', render: 'date' },
223
+ ]}
224
+ actions={['add', 'edit', 'delete']} // oppure Record<string, GridAction>
225
+ view="table" // 'table' | 'gallery'
226
+ pagination={{ limit: 20 }}
227
+ groupBy="status"
228
+ sortable={{ field: 'name', dir: 'asc' }}
229
+ form={<FormFields />}
230
+ onSave={async ({ record, action }) => record._key}
231
+ onComplete={async ({ record, action }) => true}
232
+ selection={{ mode: 'multiple', onChange: (sel) => {} }}
233
+ reorderable
234
+ onReorder={(records, meta) => {}}
235
+ header={(ctx) => <div>{ctx.title}</div>}
236
+ footer={(ctx) => <div>{ctx.records.length} records</div>}
237
+ />
238
+ ```
239
+
240
+ | Prop | Tipo | Note |
241
+ |---|---|---|---|
242
+ | `path` | `string \| "fromUrl"` | Path provider-backed |
243
+ | `records` | `RecordArray` | Dati in memoria (alternativa a path) |
244
+ | `columns` | `GridColumn[]` | `{ key, label, sortable?, render?, className? }` |
245
+ | `actions` | `Array<'add'\|'edit'\|'delete'> \| Record<string, GridAction>` | |
246
+ | `view` | `'table' \| 'gallery'` | |
247
+ | `groupBy` | `string \| string[]` | |
248
+ | `pagination` | `PaginationParams` | `{ limit, page?, maxPageButtons?, align?, sticky? }` |
249
+ | `sortable` | `boolean \| OrderConfig` | |
250
+ | `selection` | `false \| 'single' \| 'multiple' \| GridSelectionConfig` | |
251
+ | `form` | `ReactElement \| ((ctx) => ReactNode)` | Form condiviso per CRUD |
252
+ | `onSave` | `GridMutationSaveHandler` | `async ({ record, action }) => string` |
253
+ | `onDelete` | `GridMutationDeleteHandler` | `async ({ record }) => string` |
254
+ | `onComplete` | `GridAfterActionHandler` | `async ({ record, action }) => boolean` |
255
+ | `onRowClick` | `(record) => void` | |
256
+ | `reorderable` | `boolean` | Abilita drag & drop righe |
257
+ | `onReorder` | `GridReorderHandler` | `(records, meta) => void` |
258
+ | `onLoad` | `(records) => TRecord[]` | Trasforma records dopo il fetch |
259
+ | `editDeepLink` | `boolean` | Sincronizza modal edit con URL |
260
+ | `audit` | `boolean` | Logga mutazioni |
261
+ | `sticky` | `'top' \| 'bottom'` | Header/footer sticky |
262
+ | `wrapperClassName` | `string` | CSS wrapper esterno |
263
+ | `loading` | `boolean` | Stato loading override |
264
+ | `title` | `ReactNode` | Titolo header grid |
265
+ | `before` / `after` | `ReactNode` | Slot prima/dopo il contenuto |
266
+ | `header` / `footer` | `ReactNode \| ((ctx) => ReactNode)` | Header/footer custom |
267
+ | `searchable` | `boolean \| GridSearchConfig` | Search box nell'header default — `{ fields?, placeholder? }` |
268
+ | `filters` | `GridFilterConfig[]` | Checkbox toggle nell'header default, applicati PRIMA di `searchable` — `{ key, label, defaultValue?, predicate(record, value) }` |
269
+
270
+ **GridAction kind:** `'modal'` (default), `'route'`, `'external'`, `'inline'`, `'delete'`
271
+
272
+ ---
273
+
274
+ ## Form — form CRUD con lifecycle
275
+
276
+ ```tsx
277
+ <Form
278
+ path="/products"
279
+ appearance="card" // 'card' | 'empty'
280
+ showBack
281
+ defaultValues={{ status: 'draft' }}
282
+ keyGenerator={() => `prod_${Date.now()}`}
283
+ onLoad={(data) => { /* side-effect hook, non trasforma */ }}
284
+ onSave={async ({ record, action }) => { /* return storagePath or undefined */ }}
285
+ onDelete={async ({ record }) => { /* confirm */ }}
286
+ onComplete={async ({ action }) => { if (action === 'save') navigate('/products') }}
287
+ >
288
+ <Input name="title" label="Titolo" required />
289
+ <Input name="price" label="Prezzo" type="number" />
290
+ <Input name="address.city" label="Città" /> {/* oggetto annidato */}
291
+ <Repeat name="tags" defaultLength={1}>
292
+ {(i) => <Input name={`tags.${i}`} label={`Tag ${i+1}`} />}
293
+ </Repeat>
294
+ </Form>
295
+ ```
296
+
297
+ | Prop | Tipo | Note |
298
+ |---|---|---|---|
299
+ | `path` | `string` | Path provider-backed |
300
+ | `appearance` | `'card' \| 'empty'` | Guscio visuale |
301
+ | `controller` | `FormController` | Controller condiviso per bottoni custom esterni |
302
+ | `showBack` | `boolean` | Pulsante Back nel footer |
303
+ | `defaultValues` | `RecordProps` | Valori iniziali per nuovo record |
304
+ | `keyGenerator` | `(record) => string` | Generatore chiave primaria custom |
305
+ | `draftBucket` | `string` | Bucket stabile che isola la bozza locale; omettilo per disabilitare la persistenza |
306
+ | `noticeAnchorRef` | `React.RefObject<HTMLElement>` | Ancoraggio sticky per notifiche |
307
+ | `showNotice` | `boolean` | Mostra notifiche save/delete (default `true`) |
308
+ | `requireChanges` | `boolean` | Default `true`: senza un campo cambiato il salvataggio dice "No changes to save" ed è disabilitato. `false` = form d'azione (CR-117): i valori iniziali sono già un invio valido (es. avviare una release con la versione proposta), `save()` valida e chiama `onSave` anche senza modifiche; `isDirty` dice comunque se qualcosa è cambiato |
309
+ | `children` | `ReactNode \| ((fields) => ReactNode) \| (({ record }) => ReactNode)` | Contenuto form |
310
+ | `header` | `ReactNode` | Contenuto header custom |
311
+ | `footer` | `ReactNode` | Contenuto footer custom |
312
+ | `wrapperClassName` | `string` | CSS wrapper esterno |
313
+ | `headerClassName` | `string` | CSS header |
314
+ | `className` | `string` | CSS body form |
315
+ | `footerClassName` | `string` | CSS footer |
316
+ | `log` | `boolean` | Logga ogni modifica su console |
317
+ | `onLoad` | `(record) => void` | Side-effect dopo il caricamento (non trasforma) |
318
+ | `onRecordChange` | `(record) => void` | Cambio campo in tempo reale |
319
+ | `onSave` | `FormSaveHandler` | `async ({ record, prevRecord?, storagePath?, action }) => string \| undefined` |
320
+ | `onDelete` | `FormDeleteHandler` | `async ({ record }) => string \| undefined` |
321
+ | `onComplete` | `FormFinallyHandler` | `async ({ record, action }) => boolean` |
322
+
323
+ **Form controller** — stato e azioni native del form accessibili da qualsiasi punto della pagina.
324
+
325
+ Due hook:
326
+
327
+ | Hook | Dove usarlo | Cosa restituisce |
328
+ |---|---|---|
329
+ | `useFormController(controller?)` | Ovunque (anche fuori dal form) | Crea o si aggancia a un `FormController`. Senza argomenti ne crea uno locale stabile. Con un `controller` esistente ci si aggancia. |
330
+ | `useFormActions()` | Solo dentro `<Form>` (legge dal context) | Restituisce lo stesso `FormController` del form genitore. Lancia errore se usato fuori. |
331
+
332
+ Esempio — bottone custom fuori dal form:
333
+ ```tsx
334
+ const form = useFormController();
335
+
336
+ <ActionButton disabled={form.saveDisabled} onClick={() => { void form.save(); }} />
337
+ <Form controller={form} draftBucket="workspace/acme" onSave={...} />
338
+ ```
339
+
340
+ Esempio — form d'azione, i valori proposti si inviano anche senza modificarli (CR-117):
341
+ ```tsx
342
+ const form = useFormController();
343
+
344
+ <LoadingButton label="Avvia la release" onClick={() => form.save()} />
345
+ <Form controller={form} appearance="empty" requireChanges={false} defaultValues={{ version: '1.4.0', notes }} onSave={async ({ record }) => { await start(record); return undefined; }}>
346
+ <Input name="version" label="Versione" required />
347
+ </Form>
348
+ ```
349
+
350
+ Esempio — uso dentro il form (senza passare controller):
351
+ ```tsx
352
+ function MySaveButton() {
353
+ const form = useFormActions();
354
+ return <LoadingButton disabled={form.saveDisabled} loading={form.isSaving} onClick={form.save} />;
355
+ }
356
+ ```
357
+
358
+ Stato esposto dal controller: `record`, `isNewRecord`, `isDirty`, `canSave`, `canDelete`, `isSaving`, `isDeleting`, `saveDisabled`, `deleteDisabled`, `hasDraft`, `draftStatus`, `errors`, `hasErrors`.
359
+
360
+ Azioni: `save()`, `delete()`, `reset()`, `restoreDraft()`, `discardDraft()`.
361
+
362
+ ---
363
+
364
+ ## Campi form
365
+
366
+ ### Input
367
+ ```tsx
368
+ <Input name="x" label="..." required /> // text (default)
369
+ <Input name="price" type="number" min={0} max={100} step={0.01} />
370
+ <Input name="email" type="email" />
371
+ <Input name="pwd" type="password" />
372
+ <Input name="date" type="date" />
373
+ <Input name="color" type="color" />
374
+ <TextArea name="bio" minHeight={96} />
375
+ <Checkbox name="active" valueChecked="yes" />
376
+ <Switch name="gate" label="Passa dalla CI" disabled title="L'agente non committa" /> // CR-116: disabled (non cambia né con il clic né da tastiera), title anche sull'etichetta: il motivo al passaggio del mouse
377
+ ```
378
+ `Input` props: `name`(req) `label` `type` `required` `disabled` `placeholder` `min` `max` `step` `validator:(v)=>string|undefined`
379
+ `type`: `'text' | 'number' | 'email' | 'password' | 'color' | 'date' | 'time' | 'datetime-local' | 'week' | 'month' | 'range' | 'checkbox' | 'radio' | 'url'`
380
+
381
+ **NOTA**: il tipo HTML si passa con `type`. `inputType` e i sotto-componenti `Input.Number`/`Input.Email`/`Input.Date` non esistono.
382
+
383
+ **Label come nodo**: `label` di tutti i campi di inserimento (`Input`, `TextArea`, `Checkbox`, `Select`, `Autocomplete`, `Checklist`, `Upload*`, `ImageField`, `CodeEditor`, `RichText`, `AddressAutocomplete`, `UploadCSV`, `Prompt`) accetta una stringa o un nodo React (tipo `FieldLabel`), disegnato dentro la `<label>` prima dell'asterisco di obbligatorio. Dove serve un testo (messaggio "obbligatorio", `aria-label`) si usa il testo del nodo, ricavabile anche con `labelText(node)`.
384
+ ```tsx
385
+ <Select name="skill" required options={skills} label={<>Skill <ActionButton icon="info" ariaLabel="Apri la skill" variant="link" onClick={openSkill} /></>} />
386
+ ```
387
+
388
+ ### Select / Autocomplete / Checklist
389
+ ```tsx
390
+ <Select name="role" options={[{ label: 'Admin', value: 'admin' }]} />
391
+ <Select name="categoryId" optionsSource={{ path: '/categories', labelField: 'name', valueField: '_key' }} />
392
+ <Autocomplete name="userId" optionsSource={{ path: '/users', labelField: 'email' }} maxItems={1} />
393
+ <Checklist name="tags" options={['a', 'b', 'c']} />
394
+ ```
395
+
396
+ | Prop | Tipo | Note |
397
+ |---|---|---|
398
+ | `options` | `Option[] \| string[] \| number[]` | |
399
+ | `optionsSource` | `{ path, labelField, valueField?, where?, order?, fieldMap?, onLoad? }` | Carica da provider |
400
+ | `order` | `{ field: 'label' \| 'value', dir: 'asc' \| 'desc' }` | |
401
+ | `placeholderOption` | `Option` | Solo Select |
402
+ | `placeholder` | `string` | Solo Autocomplete |
403
+ | `creatable` | `boolean` | Solo Autocomplete — crea nuovi valori |
404
+ | `onCreate` | `(value) => void \| boolean \| Promise<void \| boolean>` | Solo Autocomplete — restituire `false` per non selezionare il valore creato (es. aprire un modulo di creazione) |
405
+ | `listClassName` / `optionClassName` | `string` | Solo Autocomplete — classi della lista e delle voci (anche da tema `Autocomplete.listClassName` / `optionClassName`) |
406
+ | `minItems` / `maxItems` | `number` | Solo Autocomplete |
407
+ | `itemClassName` | `string` | Solo Checklist |
408
+ | `validator` | `(value) => string \| undefined` | Tutte le varianti |
409
+ | `readOnlyAfterSet` | `boolean` | readonly dopo primo valore |
410
+ | `disabled` | `boolean` | |
411
+ | `title` | `string` | |
412
+ | `feedback` | `string` | Messaggio di errore/suggerimento |
413
+
414
+ `Autocomplete` è una combobox accessibile: la lista (in un portal, larga quanto il campo, stile popover del tema) mostra solo le label e filtra per label/value senza distinzione di maiuscole e accenti; i chip mostrano la label; tastiera: frecce, Invio, Esc (chiude solo la lista, non il `Modal`), Tab, Backspace su campo vuoto rimuove l'ultimo valore. Con `creatable` compare la voce "Crea «testo»". Il valore salvato è sempre l'array dei `value`. `Autocomplete` e `Checklist` sono export nominati: `Select.Autocomplete`/`Select.Checklist` non esistono.
415
+
416
+ ### UploadImage / UploadDocument / UploadCSV
417
+ ```tsx
418
+ <UploadImage name="cover" label="Copertina" /> {/* con crop editor */}
419
+ <UploadDocument name="pdf" label="PDF" />
420
+ <UploadCSV name="data" label="Importa CSV" /> {/* con preview tabellare */}
421
+ ```
422
+
423
+ **UploadImageProps** (eredita FormFieldProps):
424
+ | Prop | Tipo | Note |
425
+ |---|---|---|
426
+ | `name` | `string` (required) | |
427
+ | `uploadPath` | `string` | Path storage per upload automatico |
428
+ | `accept` | `string` | MIME types accettati |
429
+ | `editable` | `boolean` | Abilita crop editor |
430
+ | `multiple` | `boolean` | Multipla selezione |
431
+ | `max` | `number` | Numero massimo file |
432
+ | `feedback` | `string` | Testo placeholder drop zone |
433
+ | `srcsetWidths` | `number[]` | Larghezze varianti responsive |
434
+ | `previewHeight` / `previewWidth` | `number` | Dimensioni preview |
435
+
436
+ **UploadDocumentProps** (eredita FormFieldProps): `name`, `uploadPath`, `accept`, `editable`, `multiple`, `max`
437
+
438
+ ### UploadCSV
439
+ ```tsx
440
+ <UploadCSV name="data" label="Importa CSV" />
441
+ ```
442
+ | Prop | Tipo |
443
+ |---|---|
444
+ | `name` | `string` (required) |
445
+ | `onDataLoaded` | `(data: UploadCSVData) => void` |
446
+ | `onParseField` | `([key, value]) => [key, value] \| undefined` |
447
+ | `normalizeKeys` | `boolean` |
448
+ | `removeEmptyFields` | `boolean` |
449
+ | `delimiter` | `string` |
450
+ | `label` / `icon` | Opzionali |
451
+
452
+ ### ImageField
453
+ ```tsx
454
+ <ImageField
455
+ name="hero"
456
+ label="Hero image"
457
+ defaultValue={{ src: 'https://example.com/hero.jpg', alt: 'Hero shot' }}
458
+ srcsetWidths={[400, 800]}
459
+ uploadPath="/content/images"
460
+ />
461
+ ```
462
+
463
+ Gestisce un oggetto `{ src, alt, srcset?, sizes? }`, preview inline, crop editor e generazione opzionale di varianti responsive.
464
+
465
+ ### CropImage
466
+ ```tsx
467
+ <CropImage img={imageObj} title="Ritaglia" scales={{ '1:1': 1, '4:3': 1.33 }} />
468
+ ```
469
+ Componente di ritaglio indipendente. `img` ha tipo `{ fileName, variants }` dove ogni variante è `{ fileName, type, scale, top, left, width, height, base64? }`. Usato internamente da `UploadImage` e `ImageField`, ma esportato pubblicamente per uso standalone.
470
+
471
+ ### CodeEditor
472
+ ```tsx
473
+ <CodeEditor
474
+ name="code"
475
+ label="Template"
476
+ language="html"
477
+ placeholder="Scrivi HTML..."
478
+ minHeight={200}
479
+ maxHeight={600}
480
+ disabled={false}
481
+ required
482
+ validateSyntax
483
+ commands={[{ name: 'wrap-section', handler: ({ value }) => `<section>\n${value}\n</section>` }]}
484
+ commandsTrigger="/"
485
+ />
486
+ ```
487
+ Editor basato su CodeMirror con syntax highlighting e validazione. Linguaggi: `liquid`, `html`, `json`, `js`, `ts`, `css`.
488
+ Quando `commands` e presente, `CodeEditor` apre internamente `ContextMenu` sul trigger configurato.
489
+
490
+ | Prop extra | Tipo |
491
+ |---|---|
492
+ | `language` | `CodeEditorLanguage` |
493
+ | `placeholder` | `string` |
494
+ | `minHeight` / `maxHeight` | `number` |
495
+ | `validateSyntax` | `boolean` |
496
+ | `validator` | `(value) => string \| undefined \| Promise<string \| undefined>` |
497
+ | `extensions` | `unknown[]` |
498
+
499
+ ### RichText
500
+ ```tsx
501
+ <RichText
502
+ name="body"
503
+ label="Article body"
504
+ placeholder="Scrivi..."
505
+ toolbar="fixed" // 'fixed' | 'floating' | false
506
+ toolbarCommands={['bold', 'italic', 'heading1', '|', 'bulletList', 'link']}
507
+ outputFormat="html" // 'html' | 'json' | 'text'
508
+ statusBar={{ tagBreadcrumb: true, wordCount: true }}
509
+ minHeight={200}
510
+ maxHeight={800}
511
+ imageUpload={{ path: '/content/images', srcsetWidths: [400, 800] }}
512
+ commands={[{ name: 'summary', icon: 'sparkles' }]}
513
+ commandsTrigger="/"
514
+ />
515
+ ```
516
+
517
+ | Prop extra | Tipo |
518
+ |---|---|
519
+ | `placeholder` | `string` |
520
+ | `disabled` | `boolean` |
521
+ | `feedback` | `string` |
522
+ | `toolbar` | `'fixed' \| 'floating' \| false` |
523
+ | `toolbarCommands` | `ToolbarCommand[]` |
524
+ | `outputFormat` | `'html' \| 'json' \| 'text'` |
525
+ | `statusBar` | `boolean \| StatusBarConfig` |
526
+ | `minHeight` / `maxHeight` | `number` |
527
+ | `imageUpload` | `RichTextImageUploadConfig` |
528
+ | `documentUpload` | `RichTextDocumentUploadConfig` |
529
+ | `validator` | `(value) => string \| undefined` |
530
+
531
+ ### Repeat — array dinamici
532
+ ```tsx
533
+ <Repeat name="items" defaultLength={3} minItems={1} maxItems={10} label="Elementi" layout="vertical" readOnly>
534
+ {({ index, record, records, remove }) => (
535
+ <>
536
+ <Input name={`items.${index}.name`} label="Nome" />
537
+ <UploadImage name={`items.${index}.photo`} label="Foto" />
538
+ </>
539
+ )}
540
+ </Repeat>
541
+ ```
542
+
543
+ | Prop | Tipo | Note |
544
+ |---|---|---|
545
+ | `name` | `string` (required) | |
546
+ | `children` | `ReactNode \| ((args) => ReactNode)` | Render prop con `{ index, record, records, remove }` |
547
+ | `defaultLength` | `number` | Righe iniziali |
548
+ | `minItems` / `maxItems` | `number` | Min/max righe |
549
+ | `layout` | `'vertical' \| 'horizontal' \| 'inline'` | |
550
+ | `label` | `string` | Etichetta gruppo |
551
+ | `labelPosition` | `'top' \| 'bottom'` | |
552
+ | `hideRemoveButton` | `boolean` | Nascondi rimozione |
553
+ | `readOnly` | `boolean` | Sola lettura |
554
+ | `onChange` | `FieldOnChange` | |
555
+ | `onAdd` / `onRemove` | `(records) => void` | Callback aggiunta/rimozione |
556
+
557
+ ### Prompt — campo AI-potenziato
558
+ ```tsx
559
+ <Prompt
560
+ name="summary"
561
+ mode="run" // 'edit' | 'run'
562
+ onRunPrompt={async (prompt, options) => AI.fetch(prompt)}
563
+ commands={[{ name: 'translate', icon: 'languages', handler: (v) => `Translate:\n${v}` }]}
564
+ commandsTrigger="/" // default automatico quando commands e presente
565
+ attachments
566
+ statusItems={['tokensIn', 'tokensOut', 'contextPercent', 'duration']}
567
+ />
568
+ ```
569
+
570
+ Quando `commands` e presente in `mode="run"`, `Prompt` monta internamente `ContextMenu` sulla textarea del risultato. Il trigger di default e `"/"`; `commandsTrigger` permette di cambiarlo. Il menu diventa searchable automaticamente sopra una soglia interna di comandi.
571
+
572
+ `renderFallback`: quando l'AI non e configurata, `Prompt` monta un fallback testuale; passa `renderFallback` per personalizzarlo (riceve `{ name, label, required, onChange }`).
573
+
574
+ ---
575
+
576
+ ## UI Primitives
577
+
578
+ ### Alert
579
+ ```tsx
580
+ <Alert variant="success">Salvato!</Alert>
581
+ <Alert variant="warning" icon placement="fixed" timeout={3000}>Attenzione</Alert>
582
+ ```
583
+ `variant`: `'info' | 'success' | 'warning' | 'danger' | 'primary' | 'secondary' | 'light' | 'dark'`
584
+ `appearance`: `'default' | 'text'`
585
+ `placement`: `'inline' | 'fixed'`
586
+
587
+ ### Badge
588
+ ```tsx
589
+ <Badge variant="success">Attivo</Badge>
590
+ ```
591
+ `variant`: stessi valori di Alert
592
+
593
+ ### Button variants
594
+ ```tsx
595
+ <ActionButton variant="primary" label="Salva" icon="save" onClick={handleSave} />
596
+ <LoadingButton variant="primary" label="Invia" onClick={async (e, setMsg) => { await save(); setMsg('Salvato!') }} />
597
+ <BackLink label="Indietro" />
598
+ <GoSite href="https://..." label="Visita" />
599
+ ```
600
+
601
+ **IButton props:** `variant`, `label`, `icon`, `badge`, `disabled`, `ariaLabel`, `title`, `iconClassName`, `onClick`
602
+ **LoadingButton aggiunge:** `loading`, `loadingLabel` — `onClick` riceve `(e, setMessage?) => Promise<unknown>`
603
+
604
+ ### Card
605
+ ```tsx
606
+ <Card title="Titolo" header={<Actions />} footer={<Pagination />} loading={isLoading}>
607
+ {children}
608
+ </Card>
609
+ ```
610
+
611
+ ### Modal
612
+ ```tsx
613
+ <Modal title="Conferma" size="md" position="center" onClose={() => {}} onSave={handleSave} onDelete={handleDelete} motion="fade" allowFullscreen stackedBehind>
614
+ {content}
615
+ </Modal>
616
+ <ModalYesNo title="Sicuro?" onClose={() => {}} onYes={async () => true}>Eliminare il record?</ModalYesNo>
617
+ <ModalOk title="Completato!" onClose={() => {}}>Salvato.</ModalOk>
618
+ ```
619
+ `size`: `'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'fullscreen'`
620
+ `position`: `'center' | 'top' | 'left' | 'right' | 'bottom'`
621
+ `ModalYesNo` e `ModalOk` sono export separati: `Modal.YesNo` e `Modal.Ok` non esistono.
622
+ Tastiera: Esc chiude il modal in cima alla pila (`closeOnEscape`, default `true`).
623
+ Accessibilità: il dialog ha `role="dialog"`, `aria-modal="true"` (non con `stackedBehind`) e `aria-labelledby` verso `title` (o `header` stringa) — nei test si trova con `getByRole('dialog', { name })`.
624
+
625
+ | Prop | Tipo | Note |
626
+ |---|---|---|
627
+ | `children` | `ReactNode` (required) | |
628
+ | `title` | `ReactNode` | |
629
+ | `header` / `footer` | `ReactNode \| false` | Custom header/footer |
630
+ | `size` / `position` | Come sopra | |
631
+ | `onClose` | `() => void` | |
632
+ | `onSave` / `onDelete` | `(e) => Promise<boolean>` | |
633
+ | `allowFullscreen` | `boolean` | Toggle fullscreen |
634
+ | `showCancel` | `boolean` | Default `true` |
635
+ | `stackedBehind` | `boolean` | Modale sotto un'altra (stile Google Tag Manager): un velo la scurisce, il suo backdrop resta com'è (quello della modale sopra entra sopra, così la pagina si scurisce di un gradino per modale) e non riceve il puntatore. I pannelli laterali aperti sullo stesso lato si impilano da soli: quello in cima prende la larghezza con cui si è aperto il primo, ognuno sotto è largo il 10% in più di quello sopra (100%, 110%, 121%…), così ne sporge una striscia. Solo la larghezza cambia, con la transizione dello slide, in entrata e in uscita |
636
+ | `closeOnBackdrop` | `boolean` | Default `true` |
637
+ | `closeOnEscape` | `boolean` | Default `true` — solo il modal in cima reagisce |
638
+ | `zIndex` | `number` | |
639
+ | `motion` | `MotionReference` | Preset animazione |
640
+ | Classi CSS header/title/subtitle/body/footer | `string` | |
641
+
642
+ ### Table
643
+ ```tsx
644
+ <Table
645
+ columns={[{ key: 'name', label: 'Nome', sort: true }]}
646
+ records={records}
647
+ onRowClick={(record) => {}}
648
+ selection="multiple"
649
+ sortable={{ field: 'name', dir: 'asc' }}
650
+ pagination={{ limit: 20 }}
651
+ onReorder={(records, meta) => {}}
652
+ onSelectionChange={(sel) => {}}
653
+ groupBy="status"
654
+ renderCell={(record, key, index) => <CustomCell />}
655
+ />
656
+ ```
657
+
658
+ | Prop | Tipo |
659
+ |---|---|
660
+ | `columns` | `TableHeaderProp[]` |
661
+ | `records` | `RecordArray` |
662
+ | `sortable` | `boolean \| OrderConfig` |
663
+ | `pagination` | `PaginationParams` |
664
+ | `selection` | `'single' \| 'multiple'` |
665
+ | `onRowClick` | `(record) => void` |
666
+ | `onReorder` | `(records, meta) => void` |
667
+ | `onSelectionChange` | `(selection) => void` |
668
+ | `renderCell` | `(record, key, index) => ReactNode` |
669
+ | `groupBy` | `string \| string[]` |
670
+ | `activeKey` | `string \| null` |
671
+ | `selectedKeys` | `string[]` |
672
+ | `header` / `footer` | `ReactNode` |
673
+ | `headerClassName` / `bodyClassName` / `footerClassName` / `scrollClassName` / `selectedClassName` / `heightClassName` | `string` |
674
+
675
+ ### Gallery
676
+ ```tsx
677
+ <Gallery
678
+ records={records}
679
+ overlays={[{ position: 'topRight', badge: { variant: 'success', children: 'New' } }]}
680
+ columns={3}
681
+ gap={2}
682
+ sortable={{ field: 'name', dir: 'asc' }}
683
+ pagination={{ limit: 20 }}
684
+ onRowClick={(record) => {}}
685
+ onSelectionChange={(sel) => {}}
686
+ header="Titolo"
687
+ groupBy="status"
688
+ />
689
+ ```
690
+
691
+ `position`: `'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight' | 'middleLeft' | 'middleRight'`
692
+
693
+ | Prop | Tipo |
694
+ |---|---|
695
+ | `records` | `GalleryRecord[]` (`{ img?, thumbnail?, name?, width?, height? }`) |
696
+ | `columns` | `1 \| 2 \| 3 \| 4 \| 6` |
697
+ | `gap` | `0 \| 1 \| 2 \| 3 \| 4 \| 5` |
698
+ | `overlays` | `GalleryOverlay[]` |
699
+ | `sortable` | `boolean \| OrderConfig` |
700
+ | `pagination` | `PaginationParams` |
701
+ | `onRowClick` | `(record) => void` |
702
+ | `onSelectionChange` | `(selection) => void` |
703
+ | `groupBy` | `string \| string[]` |
704
+ | `selectedKeys` | `string[]` |
705
+ | `header` / `footer` | `ReactNode` |
706
+ | Classi CSS: `headerClassName`, `bodyClassName`, `footerClassName`, `scrollClassName`, `selectedClassName` | `string` |
707
+
708
+ ### Tab
709
+ ```tsx
710
+ import { Tab, TabItem } from '@llmnative/react'
711
+
712
+ <Tab defaultIndex={0} layout="top">
713
+ <TabItem label="Generale">{content1}</TabItem>
714
+ <TabItem label="SEO">{content2}</TabItem>
715
+ </Tab>
716
+ ```
717
+ `layout`: `'default' | 'top' | 'left' | 'right' | 'bottom'`
718
+ Le schede sono `<TabItem>`, export separato: `Tab.Item` non esiste.
719
+
720
+ ### Image
721
+ ```tsx
722
+ <Image src="..." fit="cover" position="center" width={400} height={300} />
723
+ ```
724
+ `fit`: `'cover' | 'contain' | 'fill' | 'scale-down' | 'none'`
725
+
726
+ ### Pagination (standalone)
727
+ ```tsx
728
+ <Pagination records={items} limit={20}>
729
+ {(pageRecords, offset) => pageRecords.map(r => <Row key={r._key} record={r} />)}
730
+ </Pagination>
731
+ ```
732
+
733
+ ### Percentage
734
+ ```tsx
735
+ <Percentage value={75} appearance="bar" variant="success" showText />
736
+ <Percentage value={0.75} appearance="circle" size={60} />
737
+ ```
738
+
739
+ | Prop | Tipo | Default |
740
+ |---|---|---|
741
+ | `value` | `number` | — |
742
+ | `max` | `number` | `100` |
743
+ | `min` | `number` | — |
744
+ | `appearance` | `'bar' \| 'circle'` | `'bar'` |
745
+ | `variant` | `ColorType` | — |
746
+ | `trackVariant` | `ColorType` | — |
747
+ | `thickness` | `number` | — (px) |
748
+ | `showText` | `boolean` | — |
749
+ | `size` | `number` | Diametro in modalità `'circle'` (px) |
750
+ | `fontSize` | `number` | — |
751
+ | `label` | `string` | — |
752
+
753
+ ### DescriptionList
754
+ Coppie etichetta → valore in sola lettura (profilo, dati di un record, riepiloghi), rese come `<dl>`/`<dt>`/`<dd>`. Da usare al posto di markup `<dl>` scritto a mano; per dati modificabili usare i campi di `<Form>`, per molti record `<Table>`/`<Grid>`.
755
+ ```tsx
756
+ <DescriptionList items={[{ label: 'Email', value: 'a@b.it' }, { label: 'Telefono', value: null }]} />
757
+ <DescriptionList layout="stacked" columns={4} truncate items={[{ label: 'Stato', value: <Badge variant="success">Spedito</Badge> }]} />
758
+ ```
759
+
760
+ | Prop | Tipo | Default |
761
+ |---|---|---|
762
+ | `items` | `DescriptionListItem[]` — `{ key?, label, value?, title? }` | — |
763
+ | `layout` | `'horizontal' \| 'stacked'` | `'horizontal'` (etichette a sinistra, impilate su mobile) |
764
+ | `columns` | `1 \| 2 \| 3 \| 4 \| 5 \| 6` | `1` (solo `stacked`, dal breakpoint `lg`) |
765
+ | `labelWidth` | `string` (lunghezza CSS) | `'12rem'` (solo `horizontal`) |
766
+ | `emptyValue` | `ReactNode` | `'—'` per `null` / `undefined` / `''` (lo `0` resta) |
767
+ | `truncate` | `boolean` | `false`; un valore testuale diventa il suo `title` |
768
+ | Classi | `wrapperClassName`, `className`, `itemClassName`, `labelClassName`, `valueClassName` | tema `DescriptionList` |
769
+
770
+ ### Tree
771
+ Albero accessibile di nodi (cartelle e file, gerarchie): pattern WAI-ARIA tree, un solo tab stop, frecce per muoversi, → / ← per aprire e chiudere, Invio o Spazio per selezionare. Le cartelle si aprono al click, le foglie si selezionano.
772
+ ```tsx
773
+ <Tree nodes={treeFromPaths(paths)} defaultExpanded selectedId={path} onSelect={(node) => setPath(node.id)} ariaLabel="File" />
774
+ <Tree nodes={[{ id: 'a', label: 'Docs', children: [{ id: 'a/1', label: 'README.md', badge: <Badge>new</Badge> }] }]} />
775
+ ```
776
+ | Prop | Tipo | Note |
777
+ |---|---|---|
778
+ | `nodes` | `TreeNode[]` — `{ id, label, icon?, badge?, description?, children?, disabled? }` | `id` unico; con `children` è una cartella |
779
+ | `selectedId` + `onSelect` / `defaultSelectedId` | `string \| null` | selezione controllata o no |
780
+ | `expanded` + `onExpandedChange` / `defaultExpanded` | `string[]`; `defaultExpanded` anche `true` (tutto aperto) | apertura controllata o no |
781
+ | `selectableBranches` | `boolean` (default `false`) | anche le cartelle si selezionano |
782
+ | `ariaLabel` | `string` | nome accessibile |
783
+ | Classi | `wrapperClassName`, `className`, `itemClassName`, `selectedClassName` | tema `Tree` |
784
+
785
+ `treeFromPaths(paths, leaf?)` costruisce l'albero da percorsi `a/b/c`: cartelle prima dei file, ordinati; l'id di un file è il percorso, quello di una cartella `percorso/`; `leaf(path)` decora le foglie (label, icona, descrizione…).
786
+
787
+ ### Dropdown
788
+ ```tsx
789
+ <Dropdown trigger={<Icon name="menu" />} position="end">
790
+ <DropdownItem label="Modifica" icon="edit" onClick={() => {}} />
791
+ <DropdownItem label="Elimina" icon="trash" variant="danger" />
792
+ <DropdownDivider />
793
+ <DropdownHeader label="Azioni rapide" />
794
+ </Dropdown>
795
+ ```
796
+
797
+ Azioni secondarie di una voce (CR-107): `actions` mostra icone in fondo alla riga, al passaggio
798
+ del mouse o al focus (sempre sui dispositivi touch). Non selezionano la voce e lasciano il menu aperto
799
+ salvo `closeOnClick`.
800
+
801
+ ```tsx
802
+ <DropdownItem icon="messages-square" onClick={() => open(chat)}
803
+ actions={[{ icon: 'archive', label: 'Archivia', onClick: () => archive(chat) }]}>
804
+ {chat.title}
805
+ </DropdownItem>
806
+ ```
807
+
808
+ Per elenchi caricati dinamicamente usare `AsyncDropdown`: gestisce ricerca con debounce,
809
+ cancellazione delle richieste precedenti tramite `AbortSignal` e stati loading/empty/error.
810
+
811
+ ```tsx
812
+ <AsyncDropdown
813
+ trigger={<ActionButton label="Select user" />}
814
+ loadItems={(query, signal) => users.search(query, { signal })}
815
+ getItemId={user => user.id}
816
+ renderItem={user => user.name}
817
+ onSelect={user => setUser(user)}
818
+ selectedId={user?.id}
819
+ />
820
+ ```
821
+
822
+ ### ContextMenu
823
+ ```tsx
824
+ <ContextMenu trigger="/" searchable>
825
+ <ContextMenu.Heading>Comandi</ContextMenu.Heading>
826
+ <ContextMenu.Item label="Titolo" value="# " icon="heading" />
827
+ <ContextMenu.Separator />
828
+ <ContextMenu.Item label="Bold" value="**bold**" icon="bold" />
829
+ </ContextMenu>
830
+ ```
831
+ Funziona su qualsiasi `<textarea>` / `<input>` figlio. Trigger custom (`/`, `@`, `{`), filtro searchable, navigazione tastiera, floating positioning.
832
+ `ContextMenu.Item` accetta `description` (opzionale): seconda riga attenuata (`text-muted-foreground`)
833
+ sotto la label, troncata; il menu è largo al massimo 28rem e il testo completo resta nel `title`
834
+ della voce. Il filtro cerca nel testo digitato dopo il trigger su label, value e description (CR-111).
835
+
836
+ ```tsx
837
+ <ContextMenu.Item label="/plan" value="plan" icon="list" description="Scrive il piano della release" />
838
+ ```
839
+
840
+ | Prop | Tipo | Note |
841
+ |---|---|---|
842
+ | `trigger` | `string` (required) | Es. `"/"`, `"@"`, `"{"` |
843
+ | `searchable` | `boolean` | Filtro testuale |
844
+ | `controlled` | `ContextMenuControlledState` | Stato controllato esterno |
845
+ | `onSelect` | `(item, context) => void` | |
846
+
847
+ **EditorCommand** (usato da `commands` prop su `Chatbot`, `Prompt`, `RichText`, `CodeEditor`):
848
+ ```ts
849
+ {
850
+ name: string;
851
+ description?: string;
852
+ icon?: string;
853
+ group?: string;
854
+ consumeSuffix?: string;
855
+ handler?: (context: TextCommandContext) => string | Promise<string>;
856
+ }
857
+ ```
858
+
859
+ `description` compare sotto `/name` nel menu dei comandi di tutti e quattro i consumer e il filtro
860
+ la usa (digitare `/release` trova un comando descritto come "…release…"). Un comando senza `handler`
861
+ sostituisce il trigger con `/name ` (spazio finale) e il testo resta tale: in `Chatbot`/`Prompt` il
862
+ messaggio inviato è letteralmente `"/name …"`, da interpretare a cura di chi lo riceve.
863
+
864
+ `consumeSuffix` elimina una chiusura automatica adiacente durante la sostituzione del trigger,
865
+ utile quando un comando cambia famiglia sintattica (per esempio da `{{ ... }}` a `{% ... %}`).
866
+
867
+ ### Altre primitive
868
+ ```tsx
869
+ <Icon name="user" size={20} /> // usa provider icone configurato
870
+ <ImageAvatar src="..." title="Mario" alt="Mario" width={40} height={40} />
871
+ <Identicon value="acme/app" size={32} title="acme/app" /> // icona generata dal valore, stile GitHub
872
+ <Loader show={isLoading}>{content}</Loader> // indicatore al posto dei figli finché show è true
873
+ <Loader show>{null}</Loader> // solo indicatore (es. pagina in caricamento)
874
+ <Code language="tsx">{snippet}</Code> // syntax highlight
875
+ <GridSystem.Row><GridSystem.Col xs={12} md={6}>...</GridSystem.Col></GridSystem.Row>
876
+ <LocaleSwitcher locales={[{ code: 'it', label: 'Italiano' }]} />
877
+ <ThemeSwitcher />
878
+ <ProviderSwitcher />
879
+ <LayoutBuilder components={...} />
880
+ ```
881
+
882
+ ### Charts (CR-112)
883
+ Grafici SVG senza dipendenze, dal modulo `charts`. Colori come token del tema: `color` è uno slot della
884
+ palette categoriale (`1…8` → `--rf-chart-N`, definiti in `globals.css` con la variante scura e
885
+ sovrascrivibili dal consumer) o un token (`'--rf-success'`); le serie senza colore prendono lo slot
886
+ della loro posizione. Larghezza dal contenitore (ResizeObserver), animazioni spente con
887
+ `prefers-reduced-motion`, tooltip che segue il puntatore e la tastiera (le aree prendono il focus
888
+ finché sono al massimo 40), tabella dei dati `sr-only` con `ariaLabel` come didascalia, stato vuoto
889
+ `charts.noData`. `format` è facoltativo: di default il numero nella locale dell'app.
890
+
891
+ ```tsx
892
+ <ColumnChart ariaLabel="CR chiuse al giorno" columns={[{ label: 'lun', value: 4 }]} markers={[{ position: 3.5, label: 'mediana', dashed: true }]} onColumnClick={(column) => {}} />
893
+ <StackedColumnChart ariaLabel="Ore per agente" labels={days} labelEvery={2} format={(v) => `${v} h`}
894
+ series={[{ id: 'dev', label: 'Developer', values: dev }, { id: 'qa', label: 'Tester', values: qa, color: 3 }]}
895
+ comparison={previousTotals} comparisonLabel="periodo precedente" />
896
+ <MeasureBarList ariaLabel="Agenti" // CR-115: barre raggruppate, ogni agente una volta, una barra per misura (colore in legenda), ognuna sulla sua scala
897
+ columns={[{ id: 'time', label: 'Ore', format: (v) => `${v} h` }, { id: 'cost', label: 'Costo' },
898
+ { id: 'tokens', label: 'Token', parts: [{ id: 'in', label: 'Input' }, { id: 'out', label: 'Output' }] }]} // parts: la barra divisa in proporzione
899
+ rows={[{ id: 'dev', label: 'Developer', values: { time: 18, cost: 4.27, tokens: [2400000, 190000] }, trailing: { text: '18 back', tone: 'bad' } }]} />
900
+ <SequenceColumnChart ariaLabel="Turni per CR" format={(v) => `${v} min`} // CR-114: ogni colonna nel suo ordine, una serie può tornare
901
+ series={[{ id: 'dev', label: 'Developer' }, { id: 'rev', label: 'Reviewer' }]}
902
+ columns={[{ label: '#34', title: 'CR #34', segments: [{ series: 'dev', value: 18 }, { series: 'rev', value: 6 }, { series: 'dev', value: 11 }] }]}
903
+ onColumnClick={(column) => {}} />
904
+ <LineChart ariaLabel="Lead time" labels={days} threshold={{ value: 6.5, label: 'obiettivo' }} baseline={0} domain={[0, 10]}
905
+ series={[{ id: 'now', label: 'Ora', values: [3, null, 5], area: true, band: { min, max } }, { id: 'before', label: 'Prima', values: prev, dashed: true }]} />
906
+ <AreaChart ariaLabel="Flusso cumulativo" labels={days} stacked series={[{ id: 'closed', label: 'Chiuse', values: closed }]} />
907
+ <ScatterChart ariaLabel="Costo contro rework" xLabel="Costo" yLabel="Rework" sizeLabel="Turni"
908
+ series={[{ id: 'sonnet', label: 'Sonnet' }]} points={[{ id: '1', label: 'Developer', x: 0.04, y: 0.3, size: 30, series: 'sonnet' }]} onPointClick={(point) => {}} />
909
+ <DivergingBarChart ariaLabel="Valore e costo" upLabel="Valore" downLabel="Costo" bars={[{ label: 'lun', up: 120, down: null }]} />
910
+ <BarList ariaLabel="Costo per agente" rows={[{ id: 'dev', label: 'Developer', value: 1.84, trailing: { text: '+12%', tone: 'bad' } }]} />
911
+ <Heatmap ariaLabel="Turni per ora" rowLabels={agents} columnLabels={hours} columnLabelEvery={2} values={matrix} />
912
+ <CalendarHeatmap ariaLabel="Turni per giorno" days={[{ date: '2026-11-02', value: 4 }, { date: '2026-11-03', value: null }]} />
913
+ <Sparkline values={[1, 3, null, 2]} ariaLabel="Andamento" /> // senza ariaLabel è decorativa
914
+ <AnimatedNumber value={3.85} format={(v) => `$${v.toFixed(2)}`} />
915
+ ```
916
+
917
+ Parti comuni per grafici propri: `useChartTooltip()` (`show`, `showAt`, `hide`, `element`), `ChartLegend`,
918
+ `ChartDataTable`, `useChartWidth(fallback)`, `useAnimatedValues(values)`, `useReveal(key)`,
919
+ `useChartFormat(format?)`, `chartToken(color)`, `chartFill(token, alpha?)`, `niceMax`, `ticks`.
920
+
921
+ ---
922
+
923
+ ## Blocks
924
+
925
+ ```tsx
926
+ <Breadcrumbs trail={[{ label: 'Home', href: '/' }, { label: 'Utenti' }]} separator="/" jsonLd />
927
+ <Brand url="/" label="MyApp" logo="/logo.svg" width={120} />
928
+ <Search onQueryChange={(e) => setQ(e.target.value)} />
929
+ <Notifications items={[...]} seeAllUrl="/notifications" onMarkAllRead={() => {}} onItemClick={(item) => markRead(item.id)} />
930
+ <Notifications items={[{ id: 'a', title: 'Fonte senza Action', description: 'crm · sources/notes/a.md', url: '/projects/crm', time: 'ora', icon: 'file', actions: [{ label: "Apri l'Action", icon: 'play', onClick: openAction, variant: 'primary' }] }]} />
931
+ <Carousel images={[...]} />
932
+ <Toolbar items={[...]}>
933
+ {children}
934
+ </Toolbar>
935
+ <SideNav />
936
+ <ListCard records={records} onRowClick={(r) => {}} />
937
+ ```
938
+
939
+ **Brand:**
940
+ | Prop | Tipo |
941
+ |---|---|
942
+ | `url` | `string` |
943
+ | `label` | `string` |
944
+ | `logo` | `string` |
945
+ | `width` / `height` | `number` |
946
+ | `wrapperClassName` / `className` / `logoClassName` / `labelClassName` | `string` |
947
+
948
+ **SideNav:**
949
+ | Prop | Tipo |
950
+ |---|---|
951
+ | `items` | `SideNavItemDef[]` (in alternativa a `menuKey`) |
952
+ | `menuKey` | `string` — voci dal menu registrato in `<App>` |
953
+ | `bottomItems` | `SideNavItemDef[]` — voci fissate in fondo, sopra il footer e fuori dalla lista scorrevole (es. Impostazioni) |
954
+ | `header` / `footer` | `ReactNode` |
955
+ | `collapsed` + `onCollapsedChange` / `defaultCollapsed` | `boolean` — compressione controllata o no |
956
+ | `showIcons` / `showCollapseButton` | `boolean` (default `true`) |
957
+ | `embedded` | `boolean` — solo le voci, senza guscio (drawer, pannelli); `bottomItems` seguono le voci principali |
958
+
959
+ `SideNavItemDef`: `{ path, title?, icon?, group?, end?, badge?, children? }`. La voce attiva ha
960
+ `aria-current="page"`.
961
+
962
+ ```tsx
963
+ <SideNav
964
+ items={[{ path: '/dashboard', title: 'Dashboard', icon: 'home' }]}
965
+ bottomItems={[{ path: '/settings', title: 'Impostazioni', icon: 'settings' }]}
966
+ />
967
+ ```
968
+
969
+ **ImageAvatar:**
970
+ | Prop | Tipo |
971
+ |---|---|
972
+ | `src` | `string` (obbligatoria) |
973
+ | `width` / `height` | `number` |
974
+ | `title` / `alt` | `string` |
975
+ | `fit` | `AvatarFit` |
976
+ | `badge` | `BadgeDescriptor` |
977
+ | `feedback` | `ReactNode` |
978
+
979
+ **Identicon:** l'icona di un'entità senza immagine (repository, tenant, utente senza foto), come quelle di
980
+ GitHub: griglia 5×5 simmetrica, celle e tinta da un hash di `value`. Lo stesso valore dà sempre la stessa
981
+ icona; niente rete né storage. Default: `rounded-md bg-muted` (tema `Identicon.className`).
982
+ `identiconPattern(value)` restituisce celle e tinta, per chi la disegna altrove.
983
+ | Prop | Tipo |
984
+ |---|---|
985
+ | `value` | `string` (obbligatoria) |
986
+ | `size` | `number` (px, default 40) |
987
+ | `title` | `string`: nome accessibile (`role="img"`); senza, `aria-hidden` |
988
+ | `before` / `after` / `className` / `wrapperClassName` | come le altre primitive |
989
+
990
+ **Search:**
991
+ | Prop | Tipo |
992
+ |---|---|
993
+ | `onQueryChange` | `(e: React.ChangeEvent<HTMLInputElement>) => void` |
994
+
995
+ **Notifications:**
996
+ | Prop | Tipo |
997
+ |---|---|
998
+ | `items` | `NotificationItem[]` |
999
+ | `badge` | `BadgeProps` |
1000
+ | `seeAllUrl` | `string` |
1001
+ | `onMarkAllRead` | `() => void` |
1002
+ | `onItemClick` | `(item, index) => void` — una voce aperta (es. per segnarla letta); il menu si chiude |
1003
+ | `motion` | `MotionReference` |
1004
+
1005
+ `NotificationItem`: `{ id?, title, description?, url?, external?, time, icon, read?, actions? }`. `description` è la
1006
+ riga sotto il titolo; senza `url` la voce si mostra e basta; con `external` l'`url` è un indirizzo aperto
1007
+ in una nuova scheda (`<a target="_blank">`), altrimenti una rotta (`Link`). `actions`
1008
+ (`NotificationAction[]`: `{ label, icon?, onClick, variant?: 'primary' | 'default', closeOnClick? }`) sono
1009
+ pulsanti sotto la voce: non la aprono, mostrano il caricamento finché la promessa di `onClick` è in corso
1010
+ e lasciano il menu aperto salvo `closeOnClick`.
1011
+
1012
+ **ListCard:**
1013
+ | Prop | Tipo |
1014
+ |---|---|
1015
+ | `title` / `description` / `meta` | `ReactNode` |
1016
+ | `badge` | `ReactNode` |
1017
+ | `icon` | `string \| ReactNode` |
1018
+ | `trailing` / `footer` / `children` | `ReactNode` |
1019
+ | `href` | `string` |
1020
+ | `external` / `active` / `disabled` / `dashed` / `compact` | `boolean` |
1021
+ | `align` | `'start' \| 'center'` |
1022
+ | `onClick` | `(e) => void` |
1023
+ | Classi CSS: `titleClassName`, `descriptionClassName`, `metaClassName`, `badgeClassName`, `leadingClassName`, `bodyClassName`, `headerClassName`, `trailingClassName`, `footerClassName` | `string` |
1024
+
1025
+ **SortableList (CR-120):** card compatte (ListCard) in un ordine che la persona sceglie: le trascina per la
1026
+ maniglia, o con le frecce su/giù sulla maniglia; l'annuncio della nuova posizione va agli screen reader.
1027
+ ```tsx
1028
+ <SortableList
1029
+ items={accounts}
1030
+ getKey={(a) => a.id}
1031
+ label="Account"
1032
+ numbered
1033
+ onReorder={(next, { fromIndex, toIndex, item }) => setAccounts(next)}
1034
+ renderItem={(a) => ({ title: a.email, meta: a.added, badge: <Badge variant="success">Disponibile</Badge>, trailing: <ActionButton icon="trash-2" … /> })}
1035
+ emptyState={<p>Nessun account</p>}
1036
+ />
1037
+ moveItem(['a', 'b', 'c'], 0, 2) // ['b', 'c', 'a']
1038
+ ```
1039
+ | Prop | Tipo |
1040
+ |---|---|
1041
+ | `items` / `getKey` | `TItem[]` / `(item) => string` |
1042
+ | `renderItem` | `(item, index) => SortableListCard` (`title`, `description`, `meta`, `badge`, `icon`, `trailing`, `active`, `disabled` di ListCard) |
1043
+ | `onReorder` | `(items, { fromIndex, toIndex, item }) => void`; senza, nessuna maniglia |
1044
+ | `label` / `numbered` / `disabled` / `emptyState` | `string` / `boolean` / `boolean` / `ReactNode` |
1045
+ | Classi CSS: `className`, `itemClassName`, `cardClassName` | `string` |
1046
+
1047
+ **Dropdown:**
1048
+ | Prop | Tipo |
1049
+ |---|---|
1050
+ | `trigger` | `string \| ReactNode \| DropdownTogglerProps` |
1051
+ | `badge` | `BadgeProps` |
1052
+ | `header` / `footer` | `ReactNode` |
1053
+ | `defaultOpen` / `open` | `boolean` |
1054
+ | `onOpenChange` | `(open) => void` |
1055
+ | `position` | `'start' \| 'end'` |
1056
+ | `placement` | `'auto' \| 'top' \| 'bottom'` |
1057
+ | `strategy` | `'fixed' \| 'absolute'` |
1058
+
1059
+ // Menu — renderizza una sezione del menuConfig passato ad <App>
1060
+ <Menu menuKey="main" /> // 'main' o qualsiasi chiave definita in MenuConfig
1061
+ <Menu menuKey="topbar" className="nav flex-row gap-2" />
1062
+ // NON usare context= — la prop si chiama menuKey
1063
+
1064
+ // AuthButton — login/logout con il provider auth configurato
1065
+ <AuthButton />
1066
+ ```
1067
+
1068
+ ---
1069
+
1070
+ ## Widgets
1071
+
1072
+ ### MarkdownReader
1073
+ ```tsx
1074
+ <MarkdownReader
1075
+ content={markdownString}
1076
+ onInternalLinkClick={(href, e) => { e.preventDefault(); navigate(href) }}
1077
+ wrapperClassName="prose"
1078
+ />
1079
+ ```
1080
+
1081
+ ### Messaggi di chat: ChatMarkdown, ChatReasoning, ChatQuestions (CR-109), ChatActivity (CR-123)
1082
+
1083
+ Parti di un messaggio di un modello, da comporre nel proprio thread (anche accanto a `Chatbot`).
1084
+
1085
+ ```tsx
1086
+ // Markdown GFM del messaggio: tabelle (scorrono dentro di sé in un pannello stretto), elenchi,
1087
+ // titoli, citazioni, task list, codice con evidenziazione (Prism, lazy) e pulsante Copia, link a
1088
+ // indirizzi in una nuova scheda (noopener). Sanitizzato: niente HTML grezzo, niente javascript:.
1089
+ // streaming: chiude ciò che la fine del testo lascia aperto (fence, intestazione di tabella,
1090
+ // **grassetto**, `codice`, link) così il layout non salta mentre arriva. Off per un messaggio finito.
1091
+ <ChatMarkdown content={text} streaming={running} onLinkClick={(href) => navigate(href)} />
1092
+ // tone="muted", highlight={false}, components (come react-markdown), className,
1093
+ // classNames={{ root, paragraph, heading, list, blockquote, tableWrapper, table, th, td, codeBlock, codeHeader, code, inlineCode, link }}
1094
+ // repairStreamingMarkdown(text) è la stessa riparazione, pura.
1095
+
1096
+ // Ragionamento: chiuso dietro "Ragionamento" / "Ha ragionato per 12 s"; aperto mentre arriva
1097
+ // (se l'utente non lo chiude) e richiuso alla fine. Contenuto con ChatMarkdown, tono attenuato.
1098
+ <ChatReasoning content={reasoning} streaming={thinking} duration={12} />
1099
+ // defaultOpen, open + onOpenChange (controllato), label, icon ('brain'), className, classNames={{ root, trigger, content }}
1100
+
1101
+ // Domande interattive (formato dello strumento `question` di opencode / elicitation MCP):
1102
+ <ChatQuestions
1103
+ questions={[
1104
+ { id: 'db', header: 'Database', question: 'Quale database?', recommended: 0,
1105
+ options: [{ label: 'Postgres', description: 'Relazionale' }, { label: 'SQLite' }] },
1106
+ { id: 'features', header: 'Funzioni', question: 'Quali funzioni?', multiple: true,
1107
+ options: [{ label: 'Auth' }, { label: 'Ricerca' }] },
1108
+ ]}
1109
+ onSubmit={async (answers) => send(answers)} // [{ id, header, values: string[] }] in ordine
1110
+ />
1111
+ // Una scheda per domanda (header) + Riepilogo e un solo Invia; opzioni numerate 1-2-3 o A-B-C
1112
+ // (numbering, altrimenti dedotto da etichette "A) …" / "1. …", che vengono tolte); consigliata
1113
+ // (recommended: indice da 0 o etichetta; anche il suffisso "(Recommended)"); multiple; "Altro" con
1114
+ // testo libero (allowOther, default true; per domanda `custom`); senza options è a testo libero.
1115
+ // Il testo libero è una textarea (CR-110) di 2 righe che cresce col testo fino a ~160px e poi
1116
+ // scorre; ridimensionabile in verticale. Lì Invio va a capo, Ctrl/Cmd+Invio prosegue o invia
1117
+ // (suggerimento `chat.textKeyboardHint` nel piè mentre si scrive).
1118
+ // Tastiera: numeri (o lettere con A-B-C) scelgono, frecce sinistra/destra tra le schede, su/giù tra
1119
+ // le opzioni, Spazio seleziona, Invio prosegue o invia (su una scelta singola prima la sceglie;
1120
+ // nel testo libero serve Ctrl/Cmd+Invio).
1121
+ // Ruoli tablist/tab/tabpanel, radiogroup/radio o group/checkbox.
1122
+ // Scelta singola: il click sceglie e passa alla domanda dopo. onSubmit che rifiuta lascia il form.
1123
+ // answers={[…]} mostra un insieme già risposto (sola lettura); disabled, autoFocus, submitLabel,
1124
+ // classNames={{ root, tabs, tab, panel, question, option, optionSelected, footer, summary }}
1125
+
1126
+ // Il lavoro di un agente (CR-123), come negli assistenti AI: gruppi di passi (icona, label, quanti,
1127
+ // dettagli brevi: query, file, comandi; quanti falliti) con le righe sotto aperte da "Comandi";
1128
+ // le parole dell'agente in Markdown; come è finito; i file cambiati con "Vedi le modifiche";
1129
+ // il registro grezzo a un clic. Il consumer traduce il suo log negli item.
1130
+ <ChatActivity
1131
+ items={[
1132
+ { type: 'steps', icon: 'search', label: 'Esplora il repository', count: 3, detail: ['git status'], lines: ['git status --short'] },
1133
+ { type: 'text', text: 'Aggiungo il comando e il suo test.' },
1134
+ { type: 'end', ok: true, text: 'success · 9 steps' },
1135
+ ]}
1136
+ files={['functions/src/catalog/index.js']} onShowChanges={() => openDiff()} log={rawLines}
1137
+ />
1138
+ // className, classNames={{ root, step, text, files, log }}
1139
+ ```
1140
+
1141
+ ### ImageEditor
1142
+ ```tsx
1143
+ <ImageEditor src="..." onSave={(dataUrl) => save(dataUrl)} />
1144
+ ```
1145
+
1146
+ `ImageEditor` e un singolo componente pubblico. La libreria pesante `tui-image-editor` viene importata lazy a runtime dentro il componente, quindi non viene scaricata finche l'editor non viene effettivamente montato.
1147
+
1148
+ ### TabDynamic
1149
+ Tab con lazy loading dei contenuti — gestione dinamica aggiunta/rimozione tab.
1150
+
1151
+ ---
1152
+
1153
+ ## AI Integration
1154
+
1155
+ ```ts
1156
+ import { useAIProvider, getAIModelCatalog, createAIProviderRegistry } from '@llmnative/react'
1157
+
1158
+ // Hooks
1159
+ const provider = useAIProvider() // provider di default
1160
+ const registry = useAIProviderRegistry() // tutti i provider AI registrati
1161
+ const catalog = getAIModelCatalog() // modelli disponibili
1162
+ // ogni modello: { id, provider, model, label, pricing? } — pricing in USD per 1M token
1163
+ // { input, output, currency: 'USD', source: 'provider' | 'models.dev' }; assente = prezzo
1164
+ // non trovato (il modello resta in lista). isFreeAIModel(m) → input e output a 0.
1165
+ // Il model picker di Prompt/Chatbot mostra "$in / $out", evidenzia i free, segnala i mancanti,
1166
+ // e raggruppa per provider (ChatbotModelOption.group = providerLabel) con header sticky.
1167
+ // CR-121: il pulsante mostra la `label` del modello scelto (non il suo valore); `groupBadge: { label, variant? }`
1168
+ // su un'opzione mette un Badge a destra nell'header del suo gruppo (es. Abbonamento / A consumo).
1169
+
1170
+ // Provider adapter restituito da useAIProvider()
1171
+ const text = await provider.fetch("Scrivi un titolo per: {keyword}", { keyword: "React" })
1172
+ const json = await provider.json("Lista di 5 categorie per blog tech")
1173
+ const arr = await provider.array("5 tag per: machine learning")
1174
+
1175
+ // Provider custom
1176
+ class MyAIProvider implements AIProviderAdapter {
1177
+ async fetch(prompt: string, options?: AIRequestOptions): Promise<string> { ... }
1178
+ async json<T>(prompt: string, options?: AIRequestOptions): Promise<T> { ... }
1179
+ async array(prompt: string, options?: AIRequestOptions): Promise<string[]> { ... }
1180
+ }
1181
+
1182
+ // Quanto ragiona il modello (CR-122): `reasoning: 'low' | 'medium' | 'high' | 'max'` (AIReasoningLevel) su
1183
+ // una richiesta. Anthropic: `output_config.effort` sui Claude 4.6 e successivi (+ thinking adaptive su Opus
1184
+ // 4.6-4.8 e Sonnet 4.6); OpenAI e compatibili (OpenCode, DeepSeek, Groq…): `reasoning_effort` solo sui modelli
1185
+ // di ragionamento di OpenAI (serie o, GPT-5; max = high); OpenRouter: `reasoning.effort` su ogni modello.
1186
+ // Altrove (modelli più vecchi, Gemini) non si manda nulla: il default del modello.
1187
+ await ai.complete({ prompt: 'Rivedi questo piano', model: 'claude-opus-5-5', reasoning: 'high' })
1188
+
1189
+ // Factory per registri esterni
1190
+ const registry = createAIProviderRegistry(definitions)
1191
+ // Azioni di Chatbot (CR-107): con `content` aprono un menu; senza, sono pulsanti con `onClick`.
1192
+ // <Chatbot actions={[{ key: 'finish', icon: 'git-pull-request', label: 'Concludi', showLabel: true,
1193
+ // disabled: running, onClick: finish }]} … />
1194
+ // Allegati di Chatbot (`attachments`): file scelti, trascinati o incollati con Ctrl+V (uno screenshot diventa
1195
+ // `pasted-<data>.png`, CR-124); il testo incollato resta testo. Arrivano in `onSubmit` come `files`.
1196
+ // Comandi "/" di Chatbot: `commands` (EditorCommand[]) + `commandsTrigger` (default "/").
1197
+ // Il menu mostra `/name` e sotto la `description`; il filtro cerca in entrambi (CR-111).
1198
+ // Senza `handler` la scelta inserisce "/name " e l'invio manda il testo così com'è.
1199
+ // Tastiera: Invio invia a menu chiuso e sceglie il comando evidenziato a menu aperto;
1200
+ // Maiusc+Invio (e Invio durante la composizione IME) va a capo.
1201
+ // <Chatbot commands={[{ name: 'plan', icon: 'list', description: 'Scrive il piano' }]} … />
1202
+ ```
1203
+
1204
+ ### Identità dei modelli indipendente dal provider (CR-103)
1205
+
1206
+ ```ts
1207
+ const index = await loadModelIdentityIndex() // models.dev, un fetch per sessione
1208
+ canonicalModelName('DeepSeek V4.1 Flash (Alibaba Cloud)') // 'deepseek v4.1 flash'
1209
+ index.models['deepseek v4.1 flash'] // { key, name, family?, providers: { openrouter: [{ id, name }], … } }
1210
+ resolveModel(index, 'DeepSeek V4.1 Flash', ['openrouter', 'deepseek'])
1211
+ // → { provider: 'openrouter', model: 'deepseek/deepseek-v4.1-flash', ref: 'openrouter/deepseek/deepseek-v4.1-flash' }
1212
+ modelOffers(index, 'DeepSeek V4.1 Flash', ['openrouter', 'deepseek']) // CR-119: tutti quelli che lo servono
1213
+ // → [{ provider: 'openrouter', model, ref, cost: { input: 0.15, output: 0.3 } }, { provider: 'deepseek', … }]
1214
+ // senza `providers`: tutto il catalogo, per chiave del provider. `cost` in USD per 1M token, assente se models.dev non lo dà
1215
+ ```
1216
+
1217
+ Il nome canonico toglie data, Free, Latest e host o regione tra parentesi; una modalità
1218
+ ("(Thinking)", "(Reasoning)", "(Fast)") resta. Per ogni provider l'id preferito è quello stabile (non
1219
+ alias `~`, non free tier, non datato). I provider sono le chiavi di models.dev, le stesse di opencode.
1220
+ Puro: anche da `@llmnative/react/server`.
1221
+
1222
+ ### Chiavi tenute dal server (CR-102)
1223
+
1224
+ Per un'app che non mette mai le chiavi dei provider nel browser. Il browser conosce solo quali
1225
+ provider sono collegati; il proxy dell'app mette la chiave.
1226
+
1227
+ ```ts
1228
+ // Browser: gli stessi adapter, con un segnaposto dove andrebbe la chiave. Serve il proxy attivo.
1229
+ const registry = createServerCredentialAIRegistry(
1230
+ [{ id: 'anthropic' }, { id: 'cloudflare', accountId }, { id: 'openai-compatible', baseUrl }],
1231
+ { scope: companyId }, // lettere, cifre, - e _
1232
+ )
1233
+ Object.entries(registry).forEach(([id, adapter]) => setProvider('ai', id, adapter))
1234
+
1235
+ // Server (Node, nessuna dipendenza da React): nel proxy, prima di inoltrare.
1236
+ import { resolveServerCredentials } from '@llmnative/react/server'
1237
+ const resolved = await resolveServerCredentials({ url: target, headers },
1238
+ (scope, provider) => keysOf(scope)[provider]) // { id, apiKey, accountId?, baseUrl? } | undefined
1239
+ if (!resolved.ok) return reply(resolved.status, resolved.error) // 404 non collegato, 403 host estraneo
1240
+ await fetch(resolved.url, { headers: resolved.headers, ... })
1241
+ ```
1242
+
1243
+ La chiave va solo agli host del provider (`AI_PROVIDER_HOSTS`, il `baseUrl` di openai-compatible,
1244
+ l'account di Cloudflare): una destinazione diversa è rifiutata. `createProxyPlugin(route, log,
1245
+ lookup)` fa lo stesso nel proxy di sviluppo di Vite. Senza proxy, `proxyFetch` rifiuta di inviare
1246
+ un segnaposto. `createAIProviderRegistry` (chiavi nel browser) resta com'è.
1247
+
1248
+ Configurazione API key in `Config.tsx`: `geminiApiKey`, `openaiApiKey`, `anthropicApiKey`, `deepSeekApiKey`, `mistralApiKey`, `openRouterApiKey`, `groqApiKey`, `cloudflare: { apiToken, accountId }` (Cloudflare Workers AI: l'account id fa parte dell'URL; discovery via `ai/models/search`, modelli Workers Paid esclusi salvo `includePaidModels`).
1249
+
1250
+ ---
1251
+
1252
+ ## Theme e icone
1253
+
1254
+ ```tsx
1255
+ const theme = useThemeController()
1256
+ theme.applyTheme('flat') // BuiltInThemeId ('default' | 'flat' | 'cyber' | 'vscode-dark-modern' | …) | custom
1257
+ theme.setMode('dark') // 'light' | 'dark' | 'system'
1258
+
1259
+ const icons = useIconController()
1260
+ icons.setProvider('phosphor') // 'lucide' | 'phosphor' | custom
1261
+ ```
1262
+
1263
+ ---
1264
+
1265
+ ## Head (SEO)
1266
+
1267
+ ```ts
1268
+ useHead({
1269
+ title: 'Pagina',
1270
+ description: '...',
1271
+ robots: 'noindex',
1272
+ canonical: 'https://...',
1273
+ og: { title: '...', image: '...' }
1274
+ })
1275
+ ```
1276
+
1277
+ ---
1278
+
1279
+ ## Global state (localStorage)
1280
+
1281
+ ```ts
1282
+ const vars = useGlobalVars()
1283
+ getGlobalVars('key')
1284
+ setGlobalVars({ key: 'value' })
1285
+ removeGlobalVars('key')
1286
+ ```
1287
+
1288
+ ---
1289
+
1290
+ ## Hooks completi
1291
+
1292
+ | Hook | Ritorna |
1293
+ |---|---|
1294
+ | `useDataProvider(name?)` | `DataProviderAdapter \| null` |
1295
+ | `useStorageProvider(name?)` | `StorageProviderAdapter \| null` |
1296
+ | `useAuthProvider(name?)` | `AuthProviderAdapter \| null` |
1297
+ | `useEmailProvider(name?)` | `EmailProviderAdapter \| null` |
1298
+ | `useAIProvider(name?)` | `AIProviderAdapter \| null` |
1299
+ | `useAIProviderRegistry()` | `Record<string, AIProviderAdapter>` |
1300
+ | `useCredentialsProvider()` | `CredentialsAdapter \| null` |
1301
+ | `useTheme()` | `Theme \| undefined` |
1302
+ | `useThemeController()` | `ThemeController` |
1303
+ | `useIconController()` | `IconController` |
1304
+ | `useAccessToken(clientID, renew?)` | `boolean` | Ottiene token per servizio esterno (true = ok) |
1305
+ | `useGlobalVars()` | `Record<string, unknown>` |
1306
+ | `useHead()` | `HeadController` |
1307
+ | `useDocumentHead()` | `HeadController` |
1308
+ | `useAssetsHead(title?)` | `void` |
1309
+ | `useLanguageHead(lang?)` | `void` |
1310
+ | `useSocialHead(config)` | `void` |
1311
+ | `usePaginationHead(config)` | `void` |
1312
+ | `usePwaHead(config)` | `void` |
1313
+ | `useSchemaOrgHead(config)` | `void` |
1314
+ | `useHeadLinks(links)` | `void` |
1315
+ | `useProxy()` | `(url, init?) => Promise<Response>` |
1316
+ | `useImage()` | `UseImageResult` |
1317
+ | `useI18n()` | `I18nController` |
1318
+ | `useMenu()` | Menu hook |
1319
+ | `useFormController(controller?)` | `FormController` |
1320
+ | `useFormActions()` | `FormController` |
1321
+ | `useApiProvider(pathname?)` | `ApiProviderAdapter \| null` |
1322
+ | `useSetProvider(service, driver?)` | `void` |
1323
+ | `useProvider(name)` | `ProviderConfigurationState` |
1324
+ | `useProviderSession()` | `ProviderSession` |
1325
+ | `useDropBoxConnect(config?)` | `DropBoxConnectResult` |
1326
+ | `useEnterMotion(baseStyle?, ref?, fallback?)` | `CSSProperties` |
1327
+ | `useMotionState(active, ref?, fallback?, baseStyle?)` | `CSSProperties` |
1328
+ | `useMotionEffect(ref?, fallback?)` | `ResolvedMotionEffect` |
1329
+ | `usePressMotion(hovered, baseStyle?, ref?, fallback?)` | `{ style, pressHandlers }` |
1330
+ | `useIconProvider()` | `IconProvider` |
1331
+
1332
+ ---
1333
+
1334
+ ## Tipi chiave
1335
+
1336
+ ```ts
1337
+ type RecordProps = Record<string, FieldValue>
1338
+ type FieldValue = string | number | boolean | null | undefined | Record<string, unknown> | unknown[]
1339
+ type RecordArray = RecordProps[]
1340
+
1341
+ type OrderConfig = { field: string; dir: 'asc' | 'desc' }
1342
+ type WhereClause = { field: string; op: '==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any'; value: unknown }
1343
+
1344
+ interface UIProps {
1345
+ before?: React.ReactNode
1346
+ after?: React.ReactNode
1347
+ wrapperClassName?: string
1348
+ className?: string
1349
+ }
1350
+
1351
+ type UserProfile = { uid?: string; email?: string; displayName?: string; photoURL?: string; [key: string]: unknown }
1352
+ ```
1353
+
1354
+ ---
1355
+
1356
+ ## Utilities
1357
+
1358
+ ```ts
1359
+ import { cn, converter, Sanitizer, Order, path, fetchJson, fetchRest, fetchWithRetry } from '@llmnative/react'
1360
+ import { getKeywordIdeas, getGoogleTrendsData, getGoogleTrendsRelated } from '@llmnative/react'
1361
+
1362
+ cn('base', condition && 'extra', className) // tailwind-merge classname
1363
+ new Sanitizer().sanitize(html) // XSS sanitizer (non usare dangerouslySetInnerHTML)
1364
+ new Order().order(records, { field: 'name', dir: 'asc' }) // ordina record array
1365
+ fetchJson(url, init?) // fetch + JSON parse + error handling
1366
+ fetchRest(path, init?) // fetch REST con auth
1367
+ getKeywordIdeas(keyword) // Google Ads Keyword Ideas
1368
+ getGoogleTrendsData(keyword) // Google Trends interest over time
1369
+ getGoogleTrendsRelated(keyword) // Google Trends related queries
1370
+ ```
1371
+
1372
+ ---
1373
+
1374
+ ## Scaffold (npx create)
1375
+
1376
+ ```bash
1377
+ npx @llmnative/react create
1378
+ npx @llmnative/react create --yes --provider=mock --template=admin
1379
+ ```
1380
+
1381
+ Flag disponibili: `--name` `--provider=firebase|supabase|mock|custom` `--ai-provider` `--icon-provider` `--theme` `--template=blank|admin|crm|inventory|project`
1382
+
1383
+ **5 template disponibili:**
1384
+ | Template | Pagine incluse | Uso tipico |
1385
+ |---|---|---|
1386
+ | `blank` | home | App vuota — massima libertà |
1387
+ | `admin` | home, users, roles, settings | Dashboard admin/backoffice |
1388
+ | `crm` | home, companies, contacts, deals | CRM |
1389
+ | `inventory` | home + gestione inventario | Magazzino |
1390
+ | `project` | home + gestione progetti | PM tool |
1391
+
1392
+ **Struttura generata in-place nella current directory:**
1393
+ ```
1394
+ src/
1395
+ index.tsx ← App entry
1396
+ vite-env.d.ts
1397
+ conf/
1398
+ app.ts ← providers config letta da .env (VITE_PROVIDER, VITE_AI_PROVIDER...)
1399
+ menu.ts ← MenuConfig con path, title, icon, page (layout opzionale: c'è LayoutDefault)
1400
+ data/
1401
+ mockData.ts ← dati fake per MockDataProvider
1402
+ layouts/
1403
+ Default.tsx ← layout wrapper (header + sidebar + main + footer)
1404
+ sections/
1405
+ Header.tsx / Sidebar.tsx / PageHeader.tsx / Footer.tsx ← solo componenti pubblici (SideNav, AuthButton, ActionButton, Brand, Breadcrumbs)
1406
+ pages/
1407
+ home/HomePage.tsx
1408
+ [altre pagine dal template scelto]
1409
+ styles/
1410
+ globals.css ← @import '@llmnative/react/dist/index.css' + Tailwind override
1411
+ .env ← VITE_PROVIDER, VITE_THEME, chiavi API (non committare)
1412
+ .env.example ← stessa struttura, valori vuoti (committare)
1413
+ vite.config.ts / tsconfig.json / postcss.config.js / index.html
1414
+ ```
1415
+
1416
+ **Pattern conf/app.ts** (auto-generato, leggere per capire come funziona):
1417
+ ```ts
1418
+ import type { AppProvidersConfig } from '@llmnative/react'
1419
+ import { mockData } from '../data/mockData'
1420
+ const env = import.meta.env
1421
+
1422
+ export const providers: AppProvidersConfig = {
1423
+ mock: { data: mockData },
1424
+ ai: { openaiApiKey: env.VITE_OPENAI_API_KEY ?? '' }, // AI dentro providers, non prop <App>
1425
+ services: { data: 'mock', auth: 'googleAuth' },
1426
+ }
1427
+ ```
1428
+
1429
+ Driver per `VITE_PROVIDER`: `firebase` → `firestoreDb` + `firestorage` + `firebaseAuth`; `supabase` → `supabaseDb` + `supabaseStorage` + `supabaseAuth`; `mock` → `mock` + `googleAuth`. `index.tsx` passa `LayoutDefault={Default}` ad `<App>`.
1430
+
1431
+ ---
1432
+
1433
+ ## Gotchas — pitfall frequenti
1434
+
1435
+ | Errore | Causa | Fix |
1436
+ |---|---|---|
1437
+ | `aiConfig` prop non esiste su `<App>` | La config AI va dentro `providers.ai`, NON come prop separata | `providers={{ ai: { openaiApiKey } }}` |
1438
+ | `inputType` o `Input.Number`/`Input.Email` non esistono | Il tipo HTML è la prop `type` | `<Input type="number">`, `<Input type="email">`, `<Input type="date">` |
1439
+ | `Menu context=` non esiste | La prop si chiama `menuKey` | `<Menu menuKey="main" />` |
1440
+ | `SignInButton` non esiste | Rinominato | `<AuthButton />` |
1441
+ | `firebase: { config: ... }` errato | FirebaseConfig è flat | `firebase: { apiKey, authDomain, databaseURL, ... }` |
1442
+ | `google: { oAuth2: { clientId } }` errato | GoogleProviderConfig è flat | `google: { clientId, scope }` |
1443
+ | `children` su `Grid` | Grid non accetta children | Usa `form={<Fields />}` per il form inline |
1444
+ | `recordId` su `Form` | Prop non esiste | La chiave del record viene da URL automaticamente |
1445
+ | `MenuConfig` non importabile | Era type interno | Ora esportato: `import type { MenuConfig } from '@llmnative/react'` |
1446
+ | `GridCellContext` non importabile | Mancava dall'index | Ora esportato: `import type { GridCellContext } from '@llmnative/react'` |
1447
+
1448
+ ---
1449
+
1450
+ ## Dove cercare nel codice sorgente
1451
+
1452
+ | Cosa | File |
1453
+ |---|---|
1454
+ | Form | `src/components/widgets/Form.tsx` |
1455
+ | Grid | `src/components/widgets/Grid.tsx` |
1456
+ | Prompt | `src/components/widgets/Prompt.tsx` |
1457
+ | Campi form | `src/components/ui/fields/` |
1458
+ | Blocks (Menu, Toolbar, Notifications, Dropdown…) | `src/components/blocks/` |
1459
+ | Provider data Firebase (RTDB) | `src/providers/data/firebase.ts` |
1460
+ | Provider data Firestore | `src/providers/data/firestore.ts` |
1461
+ | Provider data Supabase | `src/providers/data/supabase.ts` |
1462
+ | Provider storage Firebase | `src/providers/storage/firebase.ts` |
1463
+ | Provider storage Supabase | `src/providers/storage/supabase.ts` |
1464
+ | Provider auth Firebase | `src/providers/auth/firebase/FirebaseAuthProvider.ts` |
1465
+ | Provider auth Supabase | `src/providers/auth/supabase/` |
1466
+ | Provider auth Google | `src/providers/auth/google/` |
1467
+ | Provider auth Dropbox | `src/providers/auth/dropbox/` |
1468
+ | Provider email Gmail | `src/providers/email/google/GmailEmailProvider.ts` |
1469
+ | Provider AI definitions | `src/providers/ai/` |
1470
+ | Provider credenziali | `src/providers/credentials/` |
1471
+ | Provider session | `src/providers/ProviderSession.ts` |
1472
+ | Proxy CORS | `src/providers/proxy.ts` |
1473
+ | Motion system | `src/motion.ts` |
1474
+ | I18n | `src/I18n.tsx` |
1475
+ | Dropbox integration | `src/providers/dropbox/` |
1476
+ | Interfaccia DataProvider | `src/providers/data/DataProvider.ts` |
1477
+ | Interfaccia StorageProvider | `src/providers/storage/StorageProvider.ts` |
1478
+ | Interfaccia AuthProvider | `src/providers/auth/AuthProvider.ts` |
1479
+ | Interfaccia EmailProvider | `src/providers/email/EmailProvider.ts` |
1480
+ | Interfaccia AIProvider | `src/providers/ai/AIProvider.ts` |
1481
+ | Registry provider | `src/providers/manifest.ts` |
1482
+ | Config provider | `src/providers/ProviderConfiguration.ts` |
1483
+ | SEO / Google Trends | `src/providers/seo/google/` |
1484
+ | Sistema tema | `src/Theme.tsx` |
1485
+ | Config runtime | `src/Config.tsx` |
1486
+ | Tipi TypeScript | `src/types/` |
1487
+ | Utilities pure | `src/libs/` |