@llmnative/react 1.29.0 → 1.31.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,1271 +1,1297 @@
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
- ### AppThemeProviderConfig
67
- ```ts
68
- {
69
- mode?: 'light' | 'dark' | 'system';
70
- theme: string;
71
- themes?: Record<string, {
72
- preset?: { colors?: ColorScale; radius?: number; font?: string };
73
- motion?: MotionRegistry;
74
- components?: Record<string, Partial<ThemeComponent>>;
75
- }>;
76
- themeOverride?: Record<string, Partial<ThemeComponent>>;
77
- }
78
- ```
79
-
80
- Built-in themes: `default`, `flat`, `cyber`, `vscode-dark-modern`, `vscode-light-modern`, `vscode-dark-plus`, `vscode-light-plus`, `tokyo-night`, `tokyo-night-light`.
81
- 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.
82
-
83
- `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)));`.
84
-
85
- ---
86
-
87
- ## Provider System
88
-
89
- ### Matrix completa
90
-
91
- | Servizio | Interfaccia | Driver | Config key | Obbligatorio |
92
- |---|---|---|---|---|
93
- | data | `DataProviderAdapter` | `mock`, `dbRealtime`, `firestoreDb`, `supabaseDb` | `providers.mock/firebase/supabase` | sì (fallback: mock) |
94
- | storage | `StorageProviderAdapter` | `firestorage`, `supabaseStorage` | `providers.firebase/supabase` | no |
95
- | auth | `AuthProviderAdapter` | `googleAuth`, `firebaseAuth`, `supabaseAuth`, `dropboxAuth`, `githubAuth` | `providers.google/firebase/supabase/dropbox/github` | sì (fallback: googleAuth) |
96
- | email | `EmailProviderAdapter` | `gmail` | `providers.google` | no |
97
- | ai | `AIProviderAdapter` | `openai`, `gemini`, `anthropic`, `deepseek`, `mistral`, `openrouter`, `opencode`, `cloudflare`, `groq` | `Config.tsx AIConfig` | no |
98
- | credentials | `CredentialsAdapter` | `googleServiceAccount` | `providers.google.serviceAccount` | no |
99
-
100
- ### Hooks
101
-
102
- ```ts
103
- const data = useDataProvider() // DataProviderAdapter | null
104
- const storage = useStorageProvider() // StorageProviderAdapter | null
105
- const auth = useAuthProvider() // AuthProviderAdapter | null
106
- const email = useEmailProvider() // EmailProviderAdapter | null
107
- const ai = useAIProvider() // AIProviderAdapter | null
108
- const creds = useCredentialsProvider() // CredentialsAdapter | null
109
-
110
- // Named provider (multi-provider setup)
111
- const supabase = useDataProvider('supabase')
112
- ```
113
-
114
- ### GitHub (`githubAuth`, sessione sul server dell'app)
115
-
116
- GitHub richiede il client secret per scambiare il codice: scambio, token e sessione stanno sul server
117
- dell'app, il browser vede solo il profilo. Config `providers.github = { sessionUrl: '/api/auth/github' }`,
118
- driver `auth: 'githubAuth'`; funziona con `AuthButton` (pulsante e `aspect="avatar"`) e
119
- `useAuthProvider('githubAuth')`. Il server espone sotto `sessionUrl`:
120
-
121
- | Rotta | Risposta |
122
- |---|---|
123
- | `GET /login?returnTo=<path>[&scope=…]` | redirect a GitHub, poi di nuovo a `<path>` |
124
- | `GET /me` | `{ login, name, avatarUrl, email }`, 401 senza sessione |
125
- | `POST /logout` | chiude la sessione |
126
-
127
- Lato server, da `@llmnative/react/server`:
128
-
129
- ```ts
130
- const oauth = createGitHubOAuth({ clientId, clientSecret, scopes: ['read:org'] })
131
- oauth.authorizeUrl({ state, redirectUri, codeChallenge }) // PKCE S256
132
- const { accessToken } = await oauth.exchangeCode({ code, redirectUri, codeVerifier }) // GitHubOAuthError se rifiutato
133
- await oauth.getUser(accessToken) // { login, name, avatarUrl, email }
134
- await oauth.getOrganizations(accessToken) // [{ login, avatarUrl, role: 'admin' | 'member' }]
135
- ```
136
-
137
- ### Interfacce principali
138
-
139
- ```ts
140
- // DataProviderAdapter
141
- read(path, options?) / set(path, data) / update(path, data) / remove(path)
142
- subscribe(path, callback: (records: RecordArray) => void): () => void
143
- count?(path, where?): Promise<number>
144
-
145
- // StorageProviderAdapter
146
- upload(file, path): Promise<string|undefined>
147
- getURL(path) / download(path): Promise<Blob|undefined> / delete(path): Promise<boolean>
148
-
149
- // AuthProviderAdapter
150
- signIn(intent?, options?) / signOut() / getUser(): UserProfile|null
151
- onAuthChange(callback) / getAccessToken(): Promise<string|null>
152
- ```
153
-
154
- ### Auth sign-in methods
155
-
156
- | method | Firebase | Supabase | Google |
157
- |---|---|---|---|
158
- | `password` | ✅ | ✅ | — |
159
- | `anonymous` | ✅ | ✅ | — |
160
- | `magic_link` | — | ✅ | — |
161
- | `oauth` (github, apple…) | ✅ | ✅ | — |
162
- | GIS + scoped token | — | — | ✅ |
163
-
164
- ```ts
165
- await auth.signIn({ method: 'password', email: '...', password: '...' })
166
- await auth.signIn({ method: 'oauth', provider: 'github' })
167
- // Google: token per API scope
168
- const token = await auth.getAccessToken('https://www.googleapis.com/auth/gmail.send')
169
- ```
170
-
171
- ### CredentialsAdapter (Google Service Account)
172
- ```tsx
173
- // Chiama Google APIs lato browser senza Node.js
174
- <App providers={{ google: { serviceAccount: { clientEmail, privateKey } }, services: { credentials: 'googleServiceAccount' } }} />
175
-
176
- const creds = useCredentialsProvider()
177
- const token = await creds.getToken('https://www.googleapis.com/auth/solar')
178
- ```
179
-
180
- ### Provider custom
181
- ```ts
182
- import { DataProviderAdapter, RecordArray } from '@llmnative/react'
183
-
184
- export class RestDataProvider implements DataProviderAdapter {
185
- async read(path: string): Promise<unknown> { ... }
186
- async set(path: string, data: object): Promise<void> { ... }
187
- async update(path: string, data: object): Promise<void> { ... }
188
- async remove(path: string): Promise<void> { ... }
189
- subscribe(path: string | undefined, callback: (records: RecordArray) => void): () => void {
190
- return () => undefined
191
- }
192
- }
193
- ```
194
-
195
- ---
196
-
197
- ## Grid — CRUD table/gallery
198
-
199
- ```tsx
200
- <Grid
201
- path="/users" // DataProvider-backed — oppure records={array} per in-memory
202
- columns={[
203
- { key: 'name', label: 'Nome', sortable: true },
204
- { key: 'email', label: 'Email' },
205
- { key: 'role', label: 'Ruolo', render: ({ value }) => <Badge>{value}</Badge> },
206
- { key: 'date', label: 'Data', render: 'date' },
207
- ]}
208
- actions={['add', 'edit', 'delete']} // oppure Record<string, GridAction>
209
- view="table" // 'table' | 'gallery'
210
- pagination={{ limit: 20 }}
211
- groupBy="status"
212
- sortable={{ field: 'name', dir: 'asc' }}
213
- form={<FormFields />}
214
- onSave={async ({ record, action }) => record._key}
215
- onComplete={async ({ record, action }) => true}
216
- selection={{ mode: 'multiple', onChange: (sel) => {} }}
217
- reorderable
218
- onReorder={(records, meta) => {}}
219
- header={(ctx) => <div>{ctx.title}</div>}
220
- footer={(ctx) => <div>{ctx.records.length} records</div>}
221
- />
222
- ```
223
-
224
- | Prop | Tipo | Note |
225
- |---|---|---|---|
226
- | `path` | `string \| "fromUrl"` | Path provider-backed |
227
- | `records` | `RecordArray` | Dati in memoria (alternativa a path) |
228
- | `columns` | `GridColumn[]` | `{ key, label, sortable?, render?, className? }` |
229
- | `actions` | `Array<'add'\|'edit'\|'delete'> \| Record<string, GridAction>` | |
230
- | `view` | `'table' \| 'gallery'` | |
231
- | `groupBy` | `string \| string[]` | |
232
- | `pagination` | `PaginationParams` | `{ limit, page?, maxPageButtons?, align?, sticky? }` |
233
- | `sortable` | `boolean \| OrderConfig` | |
234
- | `selection` | `false \| 'single' \| 'multiple' \| GridSelectionConfig` | |
235
- | `form` | `ReactElement \| ((ctx) => ReactNode)` | Form condiviso per CRUD |
236
- | `onSave` | `GridMutationSaveHandler` | `async ({ record, action }) => string` |
237
- | `onDelete` | `GridMutationDeleteHandler` | `async ({ record }) => string` |
238
- | `onComplete` | `GridAfterActionHandler` | `async ({ record, action }) => boolean` |
239
- | `onRowClick` | `(record) => void` | |
240
- | `reorderable` | `boolean` | Abilita drag & drop righe |
241
- | `onReorder` | `GridReorderHandler` | `(records, meta) => void` |
242
- | `onLoad` | `(records) => TRecord[]` | Trasforma records dopo il fetch |
243
- | `editDeepLink` | `boolean` | Sincronizza modal edit con URL |
244
- | `audit` | `boolean` | Logga mutazioni |
245
- | `sticky` | `'top' \| 'bottom'` | Header/footer sticky |
246
- | `wrapperClassName` | `string` | CSS wrapper esterno |
247
- | `loading` | `boolean` | Stato loading override |
248
- | `title` | `ReactNode` | Titolo header grid |
249
- | `before` / `after` | `ReactNode` | Slot prima/dopo il contenuto |
250
- | `header` / `footer` | `ReactNode \| ((ctx) => ReactNode)` | Header/footer custom |
251
- | `searchable` | `boolean \| GridSearchConfig` | Search box nell'header default — `{ fields?, placeholder? }` |
252
- | `filters` | `GridFilterConfig[]` | Checkbox toggle nell'header default, applicati PRIMA di `searchable` — `{ key, label, defaultValue?, predicate(record, value) }` |
253
-
254
- **GridAction kind:** `'modal'` (default), `'route'`, `'external'`, `'inline'`, `'delete'`
255
-
256
- ---
257
-
258
- ## Form — form CRUD con lifecycle
259
-
260
- ```tsx
261
- <Form
262
- path="/products"
263
- appearance="card" // 'card' | 'empty'
264
- showBack
265
- defaultValues={{ status: 'draft' }}
266
- keyGenerator={() => `prod_${Date.now()}`}
267
- onLoad={(data) => { /* side-effect hook, non trasforma */ }}
268
- onSave={async ({ record, action }) => { /* return storagePath or undefined */ }}
269
- onDelete={async ({ record }) => { /* confirm */ }}
270
- onComplete={async ({ action }) => { if (action === 'save') navigate('/products') }}
271
- >
272
- <Input name="title" label="Titolo" required />
273
- <Input name="price" label="Prezzo" type="number" />
274
- <Input name="address.city" label="Città" /> {/* oggetto annidato */}
275
- <Repeat name="tags" defaultLength={1}>
276
- {(i) => <Input name={`tags.${i}`} label={`Tag ${i+1}`} />}
277
- </Repeat>
278
- </Form>
279
- ```
280
-
281
- | Prop | Tipo | Note |
282
- |---|---|---|---|
283
- | `path` | `string` | Path provider-backed |
284
- | `appearance` | `'card' \| 'empty'` | Guscio visuale |
285
- | `controller` | `FormController` | Controller condiviso per bottoni custom esterni |
286
- | `showBack` | `boolean` | Pulsante Back nel footer |
287
- | `defaultValues` | `RecordProps` | Valori iniziali per nuovo record |
288
- | `keyGenerator` | `(record) => string` | Generatore chiave primaria custom |
289
- | `draftBucket` | `string` | Bucket stabile che isola la bozza locale; omettilo per disabilitare la persistenza |
290
- | `noticeAnchorRef` | `React.RefObject<HTMLElement>` | Ancoraggio sticky per notifiche |
291
- | `showNotice` | `boolean` | Mostra notifiche save/delete (default `true`) |
292
- | `children` | `ReactNode \| ((fields) => ReactNode) \| (({ record }) => ReactNode)` | Contenuto form |
293
- | `header` | `ReactNode` | Contenuto header custom |
294
- | `footer` | `ReactNode` | Contenuto footer custom |
295
- | `wrapperClassName` | `string` | CSS wrapper esterno |
296
- | `headerClassName` | `string` | CSS header |
297
- | `className` | `string` | CSS body form |
298
- | `footerClassName` | `string` | CSS footer |
299
- | `log` | `boolean` | Logga ogni modifica su console |
300
- | `onLoad` | `(record) => void` | Side-effect dopo il caricamento (non trasforma) |
301
- | `onRecordChange` | `(record) => void` | Cambio campo in tempo reale |
302
- | `onSave` | `FormSaveHandler` | `async ({ record, prevRecord?, storagePath?, action }) => string \| undefined` |
303
- | `onDelete` | `FormDeleteHandler` | `async ({ record }) => string \| undefined` |
304
- | `onComplete` | `FormFinallyHandler` | `async ({ record, action }) => boolean` |
305
-
306
- **Form controller** — stato e azioni native del form accessibili da qualsiasi punto della pagina.
307
-
308
- Due hook:
309
-
310
- | Hook | Dove usarlo | Cosa restituisce |
311
- |---|---|---|
312
- | `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. |
313
- | `useFormActions()` | Solo dentro `<Form>` (legge dal context) | Restituisce lo stesso `FormController` del form genitore. Lancia errore se usato fuori. |
314
-
315
- Esempio — bottone custom fuori dal form:
316
- ```tsx
317
- const form = useFormController();
318
-
319
- <ActionButton disabled={form.saveDisabled} onClick={() => { void form.save(); }} />
320
- <Form controller={form} draftBucket="workspace/acme" onSave={...} />
321
- ```
322
-
323
- Esempio — uso dentro il form (senza passare controller):
324
- ```tsx
325
- function MySaveButton() {
326
- const form = useFormActions();
327
- return <LoadingButton disabled={form.saveDisabled} loading={form.isSaving} onClick={form.save} />;
328
- }
329
- ```
330
-
331
- Stato esposto dal controller: `record`, `isNewRecord`, `isDirty`, `canSave`, `canDelete`, `isSaving`, `isDeleting`, `saveDisabled`, `deleteDisabled`, `hasDraft`, `draftStatus`, `errors`, `hasErrors`.
332
-
333
- Azioni: `save()`, `delete()`, `reset()`, `restoreDraft()`, `discardDraft()`.
334
-
335
- ---
336
-
337
- ## Campi form
338
-
339
- ### Input
340
- ```tsx
341
- <Input name="x" label="..." required /> // text (default)
342
- <Input name="price" type="number" min={0} max={100} step={0.01} />
343
- <Input name="email" type="email" />
344
- <Input name="pwd" type="password" />
345
- <Input name="date" type="date" />
346
- <Input name="color" type="color" />
347
- <TextArea name="bio" minHeight={96} />
348
- <Checkbox name="active" valueChecked="yes" />
349
- ```
350
- `Input` props: `name`(req) `label` `type` `required` `disabled` `placeholder` `min` `max` `step` `validator:(v)=>string|undefined`
351
- `type`: `'text' | 'number' | 'email' | 'password' | 'color' | 'date' | 'time' | 'datetime-local' | 'week' | 'month' | 'range' | 'checkbox' | 'radio' | 'url'`
352
-
353
- **NOTA**: il tipo HTML si passa con `type`. `inputType` e i sotto-componenti `Input.Number`/`Input.Email`/`Input.Date` non esistono.
354
-
355
- **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)`.
356
- ```tsx
357
- <Select name="skill" required options={skills} label={<>Skill <ActionButton icon="info" ariaLabel="Apri la skill" variant="link" onClick={openSkill} /></>} />
358
- ```
359
-
360
- ### Select / Autocomplete / Checklist
361
- ```tsx
362
- <Select name="role" options={[{ label: 'Admin', value: 'admin' }]} />
363
- <Select name="categoryId" optionsSource={{ path: '/categories', labelField: 'name', valueField: '_key' }} />
364
- <Autocomplete name="userId" optionsSource={{ path: '/users', labelField: 'email' }} maxItems={1} />
365
- <Checklist name="tags" options={['a', 'b', 'c']} />
366
- ```
367
-
368
- | Prop | Tipo | Note |
369
- |---|---|---|
370
- | `options` | `Option[] \| string[] \| number[]` | |
371
- | `optionsSource` | `{ path, labelField, valueField?, where?, order?, fieldMap?, onLoad? }` | Carica da provider |
372
- | `order` | `{ field: 'label' \| 'value', dir: 'asc' \| 'desc' }` | |
373
- | `placeholderOption` | `Option` | Solo Select |
374
- | `placeholder` | `string` | Solo Autocomplete |
375
- | `creatable` | `boolean` | Solo Autocomplete — crea nuovi valori |
376
- | `onCreate` | `(value) => void \| boolean \| Promise<void \| boolean>` | Solo Autocomplete — restituire `false` per non selezionare il valore creato (es. aprire un modulo di creazione) |
377
- | `listClassName` / `optionClassName` | `string` | Solo Autocomplete — classi della lista e delle voci (anche da tema `Autocomplete.listClassName` / `optionClassName`) |
378
- | `minItems` / `maxItems` | `number` | Solo Autocomplete |
379
- | `itemClassName` | `string` | Solo Checklist |
380
- | `validator` | `(value) => string \| undefined` | Tutte le varianti |
381
- | `readOnlyAfterSet` | `boolean` | readonly dopo primo valore |
382
- | `disabled` | `boolean` | |
383
- | `title` | `string` | |
384
- | `feedback` | `string` | Messaggio di errore/suggerimento |
385
-
386
- `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.
387
-
388
- ### UploadImage / UploadDocument / UploadCSV
389
- ```tsx
390
- <UploadImage name="cover" label="Copertina" /> {/* con crop editor */}
391
- <UploadDocument name="pdf" label="PDF" />
392
- <UploadCSV name="data" label="Importa CSV" /> {/* con preview tabellare */}
393
- ```
394
-
395
- **UploadImageProps** (eredita FormFieldProps):
396
- | Prop | Tipo | Note |
397
- |---|---|---|
398
- | `name` | `string` (required) | |
399
- | `uploadPath` | `string` | Path storage per upload automatico |
400
- | `accept` | `string` | MIME types accettati |
401
- | `editable` | `boolean` | Abilita crop editor |
402
- | `multiple` | `boolean` | Multipla selezione |
403
- | `max` | `number` | Numero massimo file |
404
- | `feedback` | `string` | Testo placeholder drop zone |
405
- | `srcsetWidths` | `number[]` | Larghezze varianti responsive |
406
- | `previewHeight` / `previewWidth` | `number` | Dimensioni preview |
407
-
408
- **UploadDocumentProps** (eredita FormFieldProps): `name`, `uploadPath`, `accept`, `editable`, `multiple`, `max`
409
-
410
- ### UploadCSV
411
- ```tsx
412
- <UploadCSV name="data" label="Importa CSV" />
413
- ```
414
- | Prop | Tipo |
415
- |---|---|
416
- | `name` | `string` (required) |
417
- | `onDataLoaded` | `(data: UploadCSVData) => void` |
418
- | `onParseField` | `([key, value]) => [key, value] \| undefined` |
419
- | `normalizeKeys` | `boolean` |
420
- | `removeEmptyFields` | `boolean` |
421
- | `delimiter` | `string` |
422
- | `label` / `icon` | Opzionali |
423
-
424
- ### ImageField
425
- ```tsx
426
- <ImageField
427
- name="hero"
428
- label="Hero image"
429
- defaultValue={{ src: 'https://example.com/hero.jpg', alt: 'Hero shot' }}
430
- srcsetWidths={[400, 800]}
431
- uploadPath="/content/images"
432
- />
433
- ```
434
-
435
- Gestisce un oggetto `{ src, alt, srcset?, sizes? }`, preview inline, crop editor e generazione opzionale di varianti responsive.
436
-
437
- ### CropImage
438
- ```tsx
439
- <CropImage img={imageObj} title="Ritaglia" scales={{ '1:1': 1, '4:3': 1.33 }} />
440
- ```
441
- 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.
442
-
443
- ### CodeEditor
444
- ```tsx
445
- <CodeEditor
446
- name="code"
447
- label="Template"
448
- language="html"
449
- placeholder="Scrivi HTML..."
450
- minHeight={200}
451
- maxHeight={600}
452
- disabled={false}
453
- required
454
- validateSyntax
455
- commands={[{ name: 'wrap-section', handler: ({ value }) => `<section>\n${value}\n</section>` }]}
456
- commandsTrigger="/"
457
- />
458
- ```
459
- Editor basato su CodeMirror con syntax highlighting e validazione. Linguaggi: `liquid`, `html`, `json`, `js`, `ts`, `css`.
460
- Quando `commands` e presente, `CodeEditor` apre internamente `ContextMenu` sul trigger configurato.
461
-
462
- | Prop extra | Tipo |
463
- |---|---|
464
- | `language` | `CodeEditorLanguage` |
465
- | `placeholder` | `string` |
466
- | `minHeight` / `maxHeight` | `number` |
467
- | `validateSyntax` | `boolean` |
468
- | `validator` | `(value) => string \| undefined \| Promise<string \| undefined>` |
469
- | `extensions` | `unknown[]` |
470
-
471
- ### RichText
472
- ```tsx
473
- <RichText
474
- name="body"
475
- label="Article body"
476
- placeholder="Scrivi..."
477
- toolbar="fixed" // 'fixed' | 'floating' | false
478
- toolbarCommands={['bold', 'italic', 'heading1', '|', 'bulletList', 'link']}
479
- outputFormat="html" // 'html' | 'json' | 'text'
480
- statusBar={{ tagBreadcrumb: true, wordCount: true }}
481
- minHeight={200}
482
- maxHeight={800}
483
- imageUpload={{ path: '/content/images', srcsetWidths: [400, 800] }}
484
- commands={[{ name: 'summary', icon: 'sparkles' }]}
485
- commandsTrigger="/"
486
- />
487
- ```
488
-
489
- | Prop extra | Tipo |
490
- |---|---|
491
- | `placeholder` | `string` |
492
- | `disabled` | `boolean` |
493
- | `feedback` | `string` |
494
- | `toolbar` | `'fixed' \| 'floating' \| false` |
495
- | `toolbarCommands` | `ToolbarCommand[]` |
496
- | `outputFormat` | `'html' \| 'json' \| 'text'` |
497
- | `statusBar` | `boolean \| StatusBarConfig` |
498
- | `minHeight` / `maxHeight` | `number` |
499
- | `imageUpload` | `RichTextImageUploadConfig` |
500
- | `documentUpload` | `RichTextDocumentUploadConfig` |
501
- | `validator` | `(value) => string \| undefined` |
502
-
503
- ### Repeat — array dinamici
504
- ```tsx
505
- <Repeat name="items" defaultLength={3} minItems={1} maxItems={10} label="Elementi" layout="vertical" readOnly>
506
- {({ index, record, records, remove }) => (
507
- <>
508
- <Input name={`items.${index}.name`} label="Nome" />
509
- <UploadImage name={`items.${index}.photo`} label="Foto" />
510
- </>
511
- )}
512
- </Repeat>
513
- ```
514
-
515
- | Prop | Tipo | Note |
516
- |---|---|---|
517
- | `name` | `string` (required) | |
518
- | `children` | `ReactNode \| ((args) => ReactNode)` | Render prop con `{ index, record, records, remove }` |
519
- | `defaultLength` | `number` | Righe iniziali |
520
- | `minItems` / `maxItems` | `number` | Min/max righe |
521
- | `layout` | `'vertical' \| 'horizontal' \| 'inline'` | |
522
- | `label` | `string` | Etichetta gruppo |
523
- | `labelPosition` | `'top' \| 'bottom'` | |
524
- | `hideRemoveButton` | `boolean` | Nascondi rimozione |
525
- | `readOnly` | `boolean` | Sola lettura |
526
- | `onChange` | `FieldOnChange` | |
527
- | `onAdd` / `onRemove` | `(records) => void` | Callback aggiunta/rimozione |
528
-
529
- ### Prompt — campo AI-potenziato
530
- ```tsx
531
- <Prompt
532
- name="summary"
533
- mode="run" // 'edit' | 'run'
534
- onRunPrompt={async (prompt, options) => AI.fetch(prompt)}
535
- commands={[{ name: 'translate', icon: 'languages', handler: (v) => `Translate:\n${v}` }]}
536
- commandsTrigger="/" // default automatico quando commands e presente
537
- attachments
538
- statusItems={['tokensIn', 'tokensOut', 'contextPercent', 'duration']}
539
- />
540
- ```
541
-
542
- 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.
543
-
544
- `renderFallback`: quando l'AI non e configurata, `Prompt` monta un fallback testuale; passa `renderFallback` per personalizzarlo (riceve `{ name, label, required, onChange }`).
545
-
546
- ---
547
-
548
- ## UI Primitives
549
-
550
- ### Alert
551
- ```tsx
552
- <Alert variant="success">Salvato!</Alert>
553
- <Alert variant="warning" icon placement="fixed" timeout={3000}>Attenzione</Alert>
554
- ```
555
- `variant`: `'info' | 'success' | 'warning' | 'danger' | 'primary' | 'secondary' | 'light' | 'dark'`
556
- `appearance`: `'default' | 'text'`
557
- `placement`: `'inline' | 'fixed'`
558
-
559
- ### Badge
560
- ```tsx
561
- <Badge variant="success">Attivo</Badge>
562
- ```
563
- `variant`: stessi valori di Alert
564
-
565
- ### Button variants
566
- ```tsx
567
- <ActionButton variant="primary" label="Salva" icon="save" onClick={handleSave} />
568
- <LoadingButton variant="primary" label="Invia" onClick={async (e, setMsg) => { await save(); setMsg('Salvato!') }} />
569
- <BackLink label="Indietro" />
570
- <GoSite href="https://..." label="Visita" />
571
- ```
572
-
573
- **IButton props:** `variant`, `label`, `icon`, `badge`, `disabled`, `ariaLabel`, `title`, `iconClassName`, `onClick`
574
- **LoadingButton aggiunge:** `loading`, `loadingLabel` — `onClick` riceve `(e, setMessage?) => Promise<unknown>`
575
-
576
- ### Card
577
- ```tsx
578
- <Card title="Titolo" header={<Actions />} footer={<Pagination />} loading={isLoading}>
579
- {children}
580
- </Card>
581
- ```
582
-
583
- ### Modal
584
- ```tsx
585
- <Modal title="Conferma" size="md" position="center" onClose={() => {}} onSave={handleSave} onDelete={handleDelete} motion="fade" allowFullscreen stackedBehind>
586
- {content}
587
- </Modal>
588
- <ModalYesNo title="Sicuro?" onClose={() => {}} onYes={async () => true}>Eliminare il record?</ModalYesNo>
589
- <ModalOk title="Completato!" onClose={() => {}}>Salvato.</ModalOk>
590
- ```
591
- `size`: `'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'fullscreen'`
592
- `position`: `'center' | 'top' | 'left' | 'right' | 'bottom'`
593
- `ModalYesNo` e `ModalOk` sono export separati: `Modal.YesNo` e `Modal.Ok` non esistono.
594
- Tastiera: Esc chiude il modal in cima alla pila (`closeOnEscape`, default `true`).
595
- 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 })`.
596
-
597
- | Prop | Tipo | Note |
598
- |---|---|---|
599
- | `children` | `ReactNode` (required) | |
600
- | `title` | `ReactNode` | |
601
- | `header` / `footer` | `ReactNode \| false` | Custom header/footer |
602
- | `size` / `position` | Come sopra | |
603
- | `onClose` | `() => void` | |
604
- | `onSave` / `onDelete` | `(e) => Promise<boolean>` | |
605
- | `allowFullscreen` | `boolean` | Toggle fullscreen |
606
- | `showCancel` | `boolean` | Default `true` |
607
- | `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 |
608
- | `closeOnBackdrop` | `boolean` | Default `true` |
609
- | `closeOnEscape` | `boolean` | Default `true` — solo il modal in cima reagisce |
610
- | `zIndex` | `number` | |
611
- | `motion` | `MotionReference` | Preset animazione |
612
- | Classi CSS header/title/subtitle/body/footer | `string` | |
613
-
614
- ### Table
615
- ```tsx
616
- <Table
617
- columns={[{ key: 'name', label: 'Nome', sort: true }]}
618
- records={records}
619
- onRowClick={(record) => {}}
620
- selection="multiple"
621
- sortable={{ field: 'name', dir: 'asc' }}
622
- pagination={{ limit: 20 }}
623
- onReorder={(records, meta) => {}}
624
- onSelectionChange={(sel) => {}}
625
- groupBy="status"
626
- renderCell={(record, key, index) => <CustomCell />}
627
- />
628
- ```
629
-
630
- | Prop | Tipo |
631
- |---|---|
632
- | `columns` | `TableHeaderProp[]` |
633
- | `records` | `RecordArray` |
634
- | `sortable` | `boolean \| OrderConfig` |
635
- | `pagination` | `PaginationParams` |
636
- | `selection` | `'single' \| 'multiple'` |
637
- | `onRowClick` | `(record) => void` |
638
- | `onReorder` | `(records, meta) => void` |
639
- | `onSelectionChange` | `(selection) => void` |
640
- | `renderCell` | `(record, key, index) => ReactNode` |
641
- | `groupBy` | `string \| string[]` |
642
- | `activeKey` | `string \| null` |
643
- | `selectedKeys` | `string[]` |
644
- | `header` / `footer` | `ReactNode` |
645
- | `headerClassName` / `bodyClassName` / `footerClassName` / `scrollClassName` / `selectedClassName` / `heightClassName` | `string` |
646
-
647
- ### Gallery
648
- ```tsx
649
- <Gallery
650
- records={records}
651
- overlays={[{ position: 'topRight', badge: { variant: 'success', children: 'New' } }]}
652
- columns={3}
653
- gap={2}
654
- sortable={{ field: 'name', dir: 'asc' }}
655
- pagination={{ limit: 20 }}
656
- onRowClick={(record) => {}}
657
- onSelectionChange={(sel) => {}}
658
- header="Titolo"
659
- groupBy="status"
660
- />
661
- ```
662
-
663
- `position`: `'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight' | 'middleLeft' | 'middleRight'`
664
-
665
- | Prop | Tipo |
666
- |---|---|
667
- | `records` | `GalleryRecord[]` (`{ img?, thumbnail?, name?, width?, height? }`) |
668
- | `columns` | `1 \| 2 \| 3 \| 4 \| 6` |
669
- | `gap` | `0 \| 1 \| 2 \| 3 \| 4 \| 5` |
670
- | `overlays` | `GalleryOverlay[]` |
671
- | `sortable` | `boolean \| OrderConfig` |
672
- | `pagination` | `PaginationParams` |
673
- | `onRowClick` | `(record) => void` |
674
- | `onSelectionChange` | `(selection) => void` |
675
- | `groupBy` | `string \| string[]` |
676
- | `selectedKeys` | `string[]` |
677
- | `header` / `footer` | `ReactNode` |
678
- | Classi CSS: `headerClassName`, `bodyClassName`, `footerClassName`, `scrollClassName`, `selectedClassName` | `string` |
679
-
680
- ### Tab
681
- ```tsx
682
- import { Tab, TabItem } from '@llmnative/react'
683
-
684
- <Tab defaultIndex={0} layout="top">
685
- <TabItem label="Generale">{content1}</TabItem>
686
- <TabItem label="SEO">{content2}</TabItem>
687
- </Tab>
688
- ```
689
- `layout`: `'default' | 'top' | 'left' | 'right' | 'bottom'`
690
- Le schede sono `<TabItem>`, export separato: `Tab.Item` non esiste.
691
-
692
- ### Image
693
- ```tsx
694
- <Image src="..." fit="cover" position="center" width={400} height={300} />
695
- ```
696
- `fit`: `'cover' | 'contain' | 'fill' | 'scale-down' | 'none'`
697
-
698
- ### Pagination (standalone)
699
- ```tsx
700
- <Pagination records={items} limit={20}>
701
- {(pageRecords, offset) => pageRecords.map(r => <Row key={r._key} record={r} />)}
702
- </Pagination>
703
- ```
704
-
705
- ### Percentage
706
- ```tsx
707
- <Percentage value={75} appearance="bar" variant="success" showText />
708
- <Percentage value={0.75} appearance="circle" size={60} />
709
- ```
710
-
711
- | Prop | Tipo | Default |
712
- |---|---|---|
713
- | `value` | `number` | — |
714
- | `max` | `number` | `100` |
715
- | `min` | `number` | — |
716
- | `appearance` | `'bar' \| 'circle'` | `'bar'` |
717
- | `variant` | `ColorType` | — |
718
- | `trackVariant` | `ColorType` | — |
719
- | `thickness` | `number` | — (px) |
720
- | `showText` | `boolean` | — |
721
- | `size` | `number` | Diametro in modalità `'circle'` (px) |
722
- | `fontSize` | `number` | — |
723
- | `label` | `string` | — |
724
-
725
- ### DescriptionList
726
- 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>`.
727
- ```tsx
728
- <DescriptionList items={[{ label: 'Email', value: 'a@b.it' }, { label: 'Telefono', value: null }]} />
729
- <DescriptionList layout="stacked" columns={4} truncate items={[{ label: 'Stato', value: <Badge variant="success">Spedito</Badge> }]} />
730
- ```
731
-
732
- | Prop | Tipo | Default |
733
- |---|---|---|
734
- | `items` | `DescriptionListItem[]` — `{ key?, label, value?, title? }` | — |
735
- | `layout` | `'horizontal' \| 'stacked'` | `'horizontal'` (etichette a sinistra, impilate su mobile) |
736
- | `columns` | `1 \| 2 \| 3 \| 4 \| 5 \| 6` | `1` (solo `stacked`, dal breakpoint `lg`) |
737
- | `labelWidth` | `string` (lunghezza CSS) | `'12rem'` (solo `horizontal`) |
738
- | `emptyValue` | `ReactNode` | `'—'` per `null` / `undefined` / `''` (lo `0` resta) |
739
- | `truncate` | `boolean` | `false`; un valore testuale diventa il suo `title` |
740
- | Classi | `wrapperClassName`, `className`, `itemClassName`, `labelClassName`, `valueClassName` | tema `DescriptionList` |
741
-
742
- ### Tree
743
- 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.
744
- ```tsx
745
- <Tree nodes={treeFromPaths(paths)} defaultExpanded selectedId={path} onSelect={(node) => setPath(node.id)} ariaLabel="File" />
746
- <Tree nodes={[{ id: 'a', label: 'Docs', children: [{ id: 'a/1', label: 'README.md', badge: <Badge>new</Badge> }] }]} />
747
- ```
748
- | Prop | Tipo | Note |
749
- |---|---|---|
750
- | `nodes` | `TreeNode[]` — `{ id, label, icon?, badge?, description?, children?, disabled? }` | `id` unico; con `children` è una cartella |
751
- | `selectedId` + `onSelect` / `defaultSelectedId` | `string \| null` | selezione controllata o no |
752
- | `expanded` + `onExpandedChange` / `defaultExpanded` | `string[]`; `defaultExpanded` anche `true` (tutto aperto) | apertura controllata o no |
753
- | `selectableBranches` | `boolean` (default `false`) | anche le cartelle si selezionano |
754
- | `ariaLabel` | `string` | nome accessibile |
755
- | Classi | `wrapperClassName`, `className`, `itemClassName`, `selectedClassName` | tema `Tree` |
756
-
757
- `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…).
758
-
759
- ### Dropdown
760
- ```tsx
761
- <Dropdown trigger={<Icon name="menu" />} position="end">
762
- <DropdownItem label="Modifica" icon="edit" onClick={() => {}} />
763
- <DropdownItem label="Elimina" icon="trash" variant="danger" />
764
- <DropdownDivider />
765
- <DropdownHeader label="Azioni rapide" />
766
- </Dropdown>
767
- ```
768
-
769
- Per elenchi caricati dinamicamente usare `AsyncDropdown`: gestisce ricerca con debounce,
770
- cancellazione delle richieste precedenti tramite `AbortSignal` e stati loading/empty/error.
771
-
772
- ```tsx
773
- <AsyncDropdown
774
- trigger={<ActionButton label="Select user" />}
775
- loadItems={(query, signal) => users.search(query, { signal })}
776
- getItemId={user => user.id}
777
- renderItem={user => user.name}
778
- onSelect={user => setUser(user)}
779
- selectedId={user?.id}
780
- />
781
- ```
782
-
783
- ### ContextMenu
784
- ```tsx
785
- <ContextMenu trigger="/" searchable>
786
- <ContextMenu.Heading>Comandi</ContextMenu.Heading>
787
- <ContextMenu.Item label="Titolo" value="# " icon="heading" />
788
- <ContextMenu.Separator />
789
- <ContextMenu.Item label="Bold" value="**bold**" icon="bold" />
790
- </ContextMenu>
791
- ```
792
- Funziona su qualsiasi `<textarea>` / `<input>` figlio. Trigger custom (`/`, `@`, `{`), filtro searchable, navigazione tastiera, floating positioning.
793
-
794
- | Prop | Tipo | Note |
795
- |---|---|---|
796
- | `trigger` | `string` (required) | Es. `"/"`, `"@"`, `"{"` |
797
- | `searchable` | `boolean` | Filtro testuale |
798
- | `controlled` | `ContextMenuControlledState` | Stato controllato esterno |
799
- | `onSelect` | `(item, context) => void` | |
800
-
801
- **EditorCommand** (usato da `commands` prop su `RichText`, `CodeEditor`, `Prompt`):
802
- ```ts
803
- {
804
- name: string;
805
- description?: string;
806
- icon?: string;
807
- group?: string;
808
- consumeSuffix?: string;
809
- handler?: (context: TextCommandContext) => string | Promise<string>;
810
- }
811
- ```
812
-
813
- `consumeSuffix` elimina una chiusura automatica adiacente durante la sostituzione del trigger,
814
- utile quando un comando cambia famiglia sintattica (per esempio da `{{ ... }}` a `{% ... %}`).
815
-
816
- ### Altre primitive
817
- ```tsx
818
- <Icon name="user" size={20} /> // usa provider icone configurato
819
- <ImageAvatar src="..." title="Mario" alt="Mario" width={40} height={40} />
820
- <Loader show={isLoading}>{content}</Loader> // indicatore al posto dei figli finché show è true
821
- <Loader show>{null}</Loader> // solo indicatore (es. pagina in caricamento)
822
- <Code language="tsx">{snippet}</Code> // syntax highlight
823
- <GridSystem.Row><GridSystem.Col xs={12} md={6}>...</GridSystem.Col></GridSystem.Row>
824
- <LocaleSwitcher locales={[{ code: 'it', label: 'Italiano' }]} />
825
- <ThemeSwitcher />
826
- <ProviderSwitcher />
827
- <LayoutBuilder components={...} />
828
- ```
829
-
830
- ---
831
-
832
- ## Blocks
833
-
834
- ```tsx
835
- <Breadcrumbs trail={[{ label: 'Home', href: '/' }, { label: 'Utenti' }]} separator="/" jsonLd />
836
- <Brand url="/" label="MyApp" logo="/logo.svg" width={120} />
837
- <Search onQueryChange={(e) => setQ(e.target.value)} />
838
- <Notifications items={[...]} seeAllUrl="/notifications" onMarkAllRead={() => {}} />
839
- <Carousel images={[...]} />
840
- <Toolbar items={[...]}>
841
- {children}
842
- </Toolbar>
843
- <SideNav />
844
- <ListCard records={records} onRowClick={(r) => {}} />
845
- ```
846
-
847
- **Brand:**
848
- | Prop | Tipo |
849
- |---|---|
850
- | `url` | `string` |
851
- | `label` | `string` |
852
- | `logo` | `string` |
853
- | `width` / `height` | `number` |
854
- | `wrapperClassName` / `className` / `logoClassName` / `labelClassName` | `string` |
855
-
856
- **SideNav:**
857
- | Prop | Tipo |
858
- |---|---|
859
- | `items` | `SideNavItemDef[]` (in alternativa a `menuKey`) |
860
- | `menuKey` | `string` — voci dal menu registrato in `<App>` |
861
- | `bottomItems` | `SideNavItemDef[]` — voci fissate in fondo, sopra il footer e fuori dalla lista scorrevole (es. Impostazioni) |
862
- | `header` / `footer` | `ReactNode` |
863
- | `collapsed` + `onCollapsedChange` / `defaultCollapsed` | `boolean` — compressione controllata o no |
864
- | `showIcons` / `showCollapseButton` | `boolean` (default `true`) |
865
- | `embedded` | `boolean` — solo le voci, senza guscio (drawer, pannelli); `bottomItems` seguono le voci principali |
866
-
867
- `SideNavItemDef`: `{ path, title?, icon?, group?, end?, badge?, children? }`. La voce attiva ha
868
- `aria-current="page"`.
869
-
870
- ```tsx
871
- <SideNav
872
- items={[{ path: '/dashboard', title: 'Dashboard', icon: 'home' }]}
873
- bottomItems={[{ path: '/settings', title: 'Impostazioni', icon: 'settings' }]}
874
- />
875
- ```
876
-
877
- **ImageAvatar:**
878
- | Prop | Tipo |
879
- |---|---|
880
- | `src` | `string` (obbligatoria) |
881
- | `width` / `height` | `number` |
882
- | `title` / `alt` | `string` |
883
- | `fit` | `AvatarFit` |
884
- | `badge` | `BadgeDescriptor` |
885
- | `feedback` | `ReactNode` |
886
-
887
- **Search:**
888
- | Prop | Tipo |
889
- |---|---|
890
- | `onQueryChange` | `(e: React.ChangeEvent<HTMLInputElement>) => void` |
891
-
892
- **Notifications:**
893
- | Prop | Tipo |
894
- |---|---|
895
- | `items` | `NotificationItem[]` |
896
- | `badge` | `BadgeProps` |
897
- | `seeAllUrl` | `string` |
898
- | `onMarkAllRead` | `() => void` |
899
- | `motion` | `MotionReference` |
900
-
901
- **ListCard:**
902
- | Prop | Tipo |
903
- |---|---|
904
- | `title` / `description` / `meta` | `ReactNode` |
905
- | `badge` | `ReactNode` |
906
- | `icon` | `string \| ReactNode` |
907
- | `trailing` / `footer` / `children` | `ReactNode` |
908
- | `href` | `string` |
909
- | `external` / `active` / `disabled` / `dashed` / `compact` | `boolean` |
910
- | `align` | `'start' \| 'center'` |
911
- | `onClick` | `(e) => void` |
912
- | Classi CSS: `titleClassName`, `descriptionClassName`, `metaClassName`, `badgeClassName`, `leadingClassName`, `bodyClassName`, `headerClassName`, `trailingClassName`, `footerClassName` | `string` |
913
-
914
- **Dropdown:**
915
- | Prop | Tipo |
916
- |---|---|
917
- | `trigger` | `string \| ReactNode \| DropdownTogglerProps` |
918
- | `badge` | `BadgeProps` |
919
- | `header` / `footer` | `ReactNode` |
920
- | `defaultOpen` / `open` | `boolean` |
921
- | `onOpenChange` | `(open) => void` |
922
- | `position` | `'start' \| 'end'` |
923
- | `placement` | `'auto' \| 'top' \| 'bottom'` |
924
- | `strategy` | `'fixed' \| 'absolute'` |
925
-
926
- // Menu — renderizza una sezione del menuConfig passato ad <App>
927
- <Menu menuKey="main" /> // 'main' o qualsiasi chiave definita in MenuConfig
928
- <Menu menuKey="topbar" className="nav flex-row gap-2" />
929
- // NON usare context= — la prop si chiama menuKey
930
-
931
- // AuthButton — login/logout con il provider auth configurato
932
- <AuthButton />
933
- ```
934
-
935
- ---
936
-
937
- ## Widgets
938
-
939
- ### MarkdownReader
940
- ```tsx
941
- <MarkdownReader
942
- content={markdownString}
943
- onInternalLinkClick={(href, e) => { e.preventDefault(); navigate(href) }}
944
- wrapperClassName="prose"
945
- />
946
- ```
947
-
948
- ### ImageEditor
949
- ```tsx
950
- <ImageEditor src="..." onSave={(dataUrl) => save(dataUrl)} />
951
- ```
952
-
953
- `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.
954
-
955
- ### TabDynamic
956
- Tab con lazy loading dei contenuti — gestione dinamica aggiunta/rimozione tab.
957
-
958
- ---
959
-
960
- ## AI Integration
961
-
962
- ```ts
963
- import { useAIProvider, getAIModelCatalog, createAIProviderRegistry } from '@llmnative/react'
964
-
965
- // Hooks
966
- const provider = useAIProvider() // provider di default
967
- const registry = useAIProviderRegistry() // tutti i provider AI registrati
968
- const catalog = getAIModelCatalog() // modelli disponibili
969
- // ogni modello: { id, provider, model, label, pricing? } — pricing in USD per 1M token
970
- // { input, output, currency: 'USD', source: 'provider' | 'models.dev' }; assente = prezzo
971
- // non trovato (il modello resta in lista). isFreeAIModel(m) → input e output a 0.
972
- // Il model picker di Prompt/Chatbot mostra "$in / $out", evidenzia i free, segnala i mancanti,
973
- // e raggruppa per provider (ChatbotModelOption.group = providerLabel) con header sticky.
974
-
975
- // Provider adapter restituito da useAIProvider()
976
- const text = await provider.fetch("Scrivi un titolo per: {keyword}", { keyword: "React" })
977
- const json = await provider.json("Lista di 5 categorie per blog tech")
978
- const arr = await provider.array("5 tag per: machine learning")
979
-
980
- // Provider custom
981
- class MyAIProvider implements AIProviderAdapter {
982
- async fetch(prompt: string, options?: AIRequestOptions): Promise<string> { ... }
983
- async json<T>(prompt: string, options?: AIRequestOptions): Promise<T> { ... }
984
- async array(prompt: string, options?: AIRequestOptions): Promise<string[]> { ... }
985
- }
986
-
987
- // Factory per registri esterni
988
- const registry = createAIProviderRegistry(definitions)
989
- ```
990
-
991
- ### Identità dei modelli indipendente dal provider (CR-103)
992
-
993
- ```ts
994
- const index = await loadModelIdentityIndex() // models.dev, un fetch per sessione
995
- canonicalModelName('DeepSeek V4.1 Flash (Alibaba Cloud)') // 'deepseek v4.1 flash'
996
- index.models['deepseek v4.1 flash'] // { key, name, family?, providers: { openrouter: [{ id, name }], … } }
997
- resolveModel(index, 'DeepSeek V4.1 Flash', ['openrouter', 'deepseek'])
998
- // → { provider: 'openrouter', model: 'deepseek/deepseek-v4.1-flash', ref: 'openrouter/deepseek/deepseek-v4.1-flash' }
999
- ```
1000
-
1001
- Il nome canonico toglie data, Free, Latest e host o regione tra parentesi; una modalità
1002
- ("(Thinking)", "(Reasoning)", "(Fast)") resta. Per ogni provider l'id preferito è quello stabile (non
1003
- alias `~`, non free tier, non datato). I provider sono le chiavi di models.dev, le stesse di opencode.
1004
- Puro: anche da `@llmnative/react/server`.
1005
-
1006
- ### Chiavi tenute dal server (CR-102)
1007
-
1008
- Per un'app che non mette mai le chiavi dei provider nel browser. Il browser conosce solo quali
1009
- provider sono collegati; il proxy dell'app mette la chiave.
1010
-
1011
- ```ts
1012
- // Browser: gli stessi adapter, con un segnaposto dove andrebbe la chiave. Serve il proxy attivo.
1013
- const registry = createServerCredentialAIRegistry(
1014
- [{ id: 'anthropic' }, { id: 'cloudflare', accountId }, { id: 'openai-compatible', baseUrl }],
1015
- { scope: companyId }, // lettere, cifre, - e _
1016
- )
1017
- Object.entries(registry).forEach(([id, adapter]) => setProvider('ai', id, adapter))
1018
-
1019
- // Server (Node, nessuna dipendenza da React): nel proxy, prima di inoltrare.
1020
- import { resolveServerCredentials } from '@llmnative/react/server'
1021
- const resolved = await resolveServerCredentials({ url: target, headers },
1022
- (scope, provider) => keysOf(scope)[provider]) // { id, apiKey, accountId?, baseUrl? } | undefined
1023
- if (!resolved.ok) return reply(resolved.status, resolved.error) // 404 non collegato, 403 host estraneo
1024
- await fetch(resolved.url, { headers: resolved.headers, ... })
1025
- ```
1026
-
1027
- La chiave va solo agli host del provider (`AI_PROVIDER_HOSTS`, il `baseUrl` di openai-compatible,
1028
- l'account di Cloudflare): una destinazione diversa è rifiutata. `createProxyPlugin(route, log,
1029
- lookup)` fa lo stesso nel proxy di sviluppo di Vite. Senza proxy, `proxyFetch` rifiuta di inviare
1030
- un segnaposto. `createAIProviderRegistry` (chiavi nel browser) resta com'è.
1031
-
1032
- 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`).
1033
-
1034
- ---
1035
-
1036
- ## Theme e icone
1037
-
1038
- ```tsx
1039
- const theme = useThemeController()
1040
- theme.applyTheme('flat') // BuiltInThemeId ('default' | 'flat' | 'cyber' | 'vscode-dark-modern' | …) | custom
1041
- theme.setMode('dark') // 'light' | 'dark' | 'system'
1042
-
1043
- const icons = useIconController()
1044
- icons.setProvider('phosphor') // 'lucide' | 'phosphor' | custom
1045
- ```
1046
-
1047
- ---
1048
-
1049
- ## Head (SEO)
1050
-
1051
- ```ts
1052
- useHead({
1053
- title: 'Pagina',
1054
- description: '...',
1055
- robots: 'noindex',
1056
- canonical: 'https://...',
1057
- og: { title: '...', image: '...' }
1058
- })
1059
- ```
1060
-
1061
- ---
1062
-
1063
- ## Global state (localStorage)
1064
-
1065
- ```ts
1066
- const vars = useGlobalVars()
1067
- getGlobalVars('key')
1068
- setGlobalVars({ key: 'value' })
1069
- removeGlobalVars('key')
1070
- ```
1071
-
1072
- ---
1073
-
1074
- ## Hooks completi
1075
-
1076
- | Hook | Ritorna |
1077
- |---|---|
1078
- | `useDataProvider(name?)` | `DataProviderAdapter \| null` |
1079
- | `useStorageProvider(name?)` | `StorageProviderAdapter \| null` |
1080
- | `useAuthProvider(name?)` | `AuthProviderAdapter \| null` |
1081
- | `useEmailProvider(name?)` | `EmailProviderAdapter \| null` |
1082
- | `useAIProvider(name?)` | `AIProviderAdapter \| null` |
1083
- | `useAIProviderRegistry()` | `Record<string, AIProviderAdapter>` |
1084
- | `useCredentialsProvider()` | `CredentialsAdapter \| null` |
1085
- | `useTheme()` | `Theme \| undefined` |
1086
- | `useThemeController()` | `ThemeController` |
1087
- | `useIconController()` | `IconController` |
1088
- | `useAccessToken(clientID, renew?)` | `boolean` | Ottiene token per servizio esterno (true = ok) |
1089
- | `useGlobalVars()` | `Record<string, unknown>` |
1090
- | `useHead()` | `HeadController` |
1091
- | `useDocumentHead()` | `HeadController` |
1092
- | `useAssetsHead(title?)` | `void` |
1093
- | `useLanguageHead(lang?)` | `void` |
1094
- | `useSocialHead(config)` | `void` |
1095
- | `usePaginationHead(config)` | `void` |
1096
- | `usePwaHead(config)` | `void` |
1097
- | `useSchemaOrgHead(config)` | `void` |
1098
- | `useHeadLinks(links)` | `void` |
1099
- | `useProxy()` | `(url, init?) => Promise<Response>` |
1100
- | `useImage()` | `UseImageResult` |
1101
- | `useI18n()` | `I18nController` |
1102
- | `useMenu()` | Menu hook |
1103
- | `useFormController(controller?)` | `FormController` |
1104
- | `useFormActions()` | `FormController` |
1105
- | `useApiProvider(pathname?)` | `ApiProviderAdapter \| null` |
1106
- | `useSetProvider(service, driver?)` | `void` |
1107
- | `useProvider(name)` | `ProviderConfigurationState` |
1108
- | `useProviderSession()` | `ProviderSession` |
1109
- | `useDropBoxConnect(config?)` | `DropBoxConnectResult` |
1110
- | `useEnterMotion(baseStyle?, ref?, fallback?)` | `CSSProperties` |
1111
- | `useMotionState(active, ref?, fallback?, baseStyle?)` | `CSSProperties` |
1112
- | `useMotionEffect(ref?, fallback?)` | `ResolvedMotionEffect` |
1113
- | `usePressMotion(hovered, baseStyle?, ref?, fallback?)` | `{ style, pressHandlers }` |
1114
- | `useIconProvider()` | `IconProvider` |
1115
-
1116
- ---
1117
-
1118
- ## Tipi chiave
1119
-
1120
- ```ts
1121
- type RecordProps = Record<string, FieldValue>
1122
- type FieldValue = string | number | boolean | null | undefined | Record<string, unknown> | unknown[]
1123
- type RecordArray = RecordProps[]
1124
-
1125
- type OrderConfig = { field: string; dir: 'asc' | 'desc' }
1126
- type WhereClause = { field: string; op: '==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any'; value: unknown }
1127
-
1128
- interface UIProps {
1129
- before?: React.ReactNode
1130
- after?: React.ReactNode
1131
- wrapperClassName?: string
1132
- className?: string
1133
- }
1134
-
1135
- type UserProfile = { uid?: string; email?: string; displayName?: string; photoURL?: string; [key: string]: unknown }
1136
- ```
1137
-
1138
- ---
1139
-
1140
- ## Utilities
1141
-
1142
- ```ts
1143
- import { cn, converter, Sanitizer, Order, path, fetchJson, fetchRest, fetchWithRetry } from '@llmnative/react'
1144
- import { getKeywordIdeas, getGoogleTrendsData, getGoogleTrendsRelated } from '@llmnative/react'
1145
-
1146
- cn('base', condition && 'extra', className) // tailwind-merge classname
1147
- new Sanitizer().sanitize(html) // XSS sanitizer (non usare dangerouslySetInnerHTML)
1148
- new Order().order(records, { field: 'name', dir: 'asc' }) // ordina record array
1149
- fetchJson(url, init?) // fetch + JSON parse + error handling
1150
- fetchRest(path, init?) // fetch REST con auth
1151
- getKeywordIdeas(keyword) // Google Ads Keyword Ideas
1152
- getGoogleTrendsData(keyword) // Google Trends interest over time
1153
- getGoogleTrendsRelated(keyword) // Google Trends related queries
1154
- ```
1155
-
1156
- ---
1157
-
1158
- ## Scaffold (npx create)
1159
-
1160
- ```bash
1161
- npx @llmnative/react create
1162
- npx @llmnative/react create --yes --provider=mock --template=admin
1163
- ```
1164
-
1165
- Flag disponibili: `--name` `--provider=firebase|supabase|mock|custom` `--ai-provider` `--icon-provider` `--theme` `--template=blank|admin|crm|inventory|project`
1166
-
1167
- **5 template disponibili:**
1168
- | Template | Pagine incluse | Uso tipico |
1169
- |---|---|---|
1170
- | `blank` | home | App vuota — massima libertà |
1171
- | `admin` | home, users, roles, settings | Dashboard admin/backoffice |
1172
- | `crm` | home, companies, contacts, deals | CRM |
1173
- | `inventory` | home + gestione inventario | Magazzino |
1174
- | `project` | home + gestione progetti | PM tool |
1175
-
1176
- **Struttura generata in-place nella current directory:**
1177
- ```
1178
- src/
1179
- index.tsx ← App entry
1180
- vite-env.d.ts
1181
- conf/
1182
- app.ts ← providers config letta da .env (VITE_PROVIDER, VITE_AI_PROVIDER...)
1183
- menu.ts ← MenuConfig con path, title, icon, page (layout opzionale: c'è LayoutDefault)
1184
- data/
1185
- mockData.ts ← dati fake per MockDataProvider
1186
- layouts/
1187
- Default.tsx ← layout wrapper (header + sidebar + main + footer)
1188
- sections/
1189
- Header.tsx / Sidebar.tsx / PageHeader.tsx / Footer.tsx ← solo componenti pubblici (SideNav, AuthButton, ActionButton, Brand, Breadcrumbs)
1190
- pages/
1191
- home/HomePage.tsx
1192
- [altre pagine dal template scelto]
1193
- styles/
1194
- globals.css ← @import '@llmnative/react/dist/index.css' + Tailwind override
1195
- .env ← VITE_PROVIDER, VITE_THEME, chiavi API (non committare)
1196
- .env.example ← stessa struttura, valori vuoti (committare)
1197
- vite.config.ts / tsconfig.json / postcss.config.js / index.html
1198
- ```
1199
-
1200
- **Pattern conf/app.ts** (auto-generato, leggere per capire come funziona):
1201
- ```ts
1202
- import type { AppProvidersConfig } from '@llmnative/react'
1203
- import { mockData } from '../data/mockData'
1204
- const env = import.meta.env
1205
-
1206
- export const providers: AppProvidersConfig = {
1207
- mock: { data: mockData },
1208
- ai: { openaiApiKey: env.VITE_OPENAI_API_KEY ?? '' }, // AI dentro providers, non prop <App>
1209
- services: { data: 'mock', auth: 'googleAuth' },
1210
- }
1211
- ```
1212
-
1213
- Driver per `VITE_PROVIDER`: `firebase` → `firestoreDb` + `firestorage` + `firebaseAuth`; `supabase` → `supabaseDb` + `supabaseStorage` + `supabaseAuth`; `mock` → `mock` + `googleAuth`. `index.tsx` passa `LayoutDefault={Default}` ad `<App>`.
1214
-
1215
- ---
1216
-
1217
- ## Gotchas — pitfall frequenti
1218
-
1219
- | Errore | Causa | Fix |
1220
- |---|---|---|
1221
- | `aiConfig` prop non esiste su `<App>` | La config AI va dentro `providers.ai`, NON come prop separata | `providers={{ ai: { openaiApiKey } }}` |
1222
- | `inputType` o `Input.Number`/`Input.Email` non esistono | Il tipo HTML è la prop `type` | `<Input type="number">`, `<Input type="email">`, `<Input type="date">` |
1223
- | `Menu context=` non esiste | La prop si chiama `menuKey` | `<Menu menuKey="main" />` |
1224
- | `SignInButton` non esiste | Rinominato | `<AuthButton />` |
1225
- | `firebase: { config: ... }` errato | FirebaseConfig è flat | `firebase: { apiKey, authDomain, databaseURL, ... }` |
1226
- | `google: { oAuth2: { clientId } }` errato | GoogleProviderConfig è flat | `google: { clientId, scope }` |
1227
- | `children` su `Grid` | Grid non accetta children | Usa `form={<Fields />}` per il form inline |
1228
- | `recordId` su `Form` | Prop non esiste | La chiave del record viene da URL automaticamente |
1229
- | `MenuConfig` non importabile | Era type interno | Ora esportato: `import type { MenuConfig } from '@llmnative/react'` |
1230
- | `GridCellContext` non importabile | Mancava dall'index | Ora esportato: `import type { GridCellContext } from '@llmnative/react'` |
1231
-
1232
- ---
1233
-
1234
- ## Dove cercare nel codice sorgente
1235
-
1236
- | Cosa | File |
1237
- |---|---|
1238
- | Form | `src/components/widgets/Form.tsx` |
1239
- | Grid | `src/components/widgets/Grid.tsx` |
1240
- | Prompt | `src/components/widgets/Prompt.tsx` |
1241
- | Campi form | `src/components/ui/fields/` |
1242
- | Blocks (Menu, Toolbar, Notifications, Dropdown…) | `src/components/blocks/` |
1243
- | Provider data Firebase (RTDB) | `src/providers/data/firebase.ts` |
1244
- | Provider data Firestore | `src/providers/data/firestore.ts` |
1245
- | Provider data Supabase | `src/providers/data/supabase.ts` |
1246
- | Provider storage Firebase | `src/providers/storage/firebase.ts` |
1247
- | Provider storage Supabase | `src/providers/storage/supabase.ts` |
1248
- | Provider auth Firebase | `src/providers/auth/firebase/FirebaseAuthProvider.ts` |
1249
- | Provider auth Supabase | `src/providers/auth/supabase/` |
1250
- | Provider auth Google | `src/providers/auth/google/` |
1251
- | Provider auth Dropbox | `src/providers/auth/dropbox/` |
1252
- | Provider email Gmail | `src/providers/email/google/GmailEmailProvider.ts` |
1253
- | Provider AI definitions | `src/providers/ai/` |
1254
- | Provider credenziali | `src/providers/credentials/` |
1255
- | Provider session | `src/providers/ProviderSession.ts` |
1256
- | Proxy CORS | `src/providers/proxy.ts` |
1257
- | Motion system | `src/motion.ts` |
1258
- | I18n | `src/I18n.tsx` |
1259
- | Dropbox integration | `src/providers/dropbox/` |
1260
- | Interfaccia DataProvider | `src/providers/data/DataProvider.ts` |
1261
- | Interfaccia StorageProvider | `src/providers/storage/StorageProvider.ts` |
1262
- | Interfaccia AuthProvider | `src/providers/auth/AuthProvider.ts` |
1263
- | Interfaccia EmailProvider | `src/providers/email/EmailProvider.ts` |
1264
- | Interfaccia AIProvider | `src/providers/ai/AIProvider.ts` |
1265
- | Registry provider | `src/providers/manifest.ts` |
1266
- | Config provider | `src/providers/ProviderConfiguration.ts` |
1267
- | SEO / Google Trends | `src/providers/seo/google/` |
1268
- | Sistema tema | `src/Theme.tsx` |
1269
- | Config runtime | `src/Config.tsx` |
1270
- | Tipi TypeScript | `src/types/` |
1271
- | 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
+ ### AppThemeProviderConfig
67
+ ```ts
68
+ {
69
+ mode?: 'light' | 'dark' | 'system';
70
+ theme: string;
71
+ themes?: Record<string, {
72
+ preset?: { colors?: ColorScale; radius?: number; font?: string };
73
+ motion?: MotionRegistry;
74
+ components?: Record<string, Partial<ThemeComponent>>;
75
+ }>;
76
+ themeOverride?: Record<string, Partial<ThemeComponent>>;
77
+ }
78
+ ```
79
+
80
+ Built-in themes: `default`, `flat`, `cyber`, `vscode-dark-modern`, `vscode-light-modern`, `vscode-dark-plus`, `vscode-light-plus`, `tokyo-night`, `tokyo-night-light`.
81
+ 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.
82
+
83
+ `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)));`.
84
+
85
+ ---
86
+
87
+ ## Provider System
88
+
89
+ ### Matrix completa
90
+
91
+ | Servizio | Interfaccia | Driver | Config key | Obbligatorio |
92
+ |---|---|---|---|---|
93
+ | data | `DataProviderAdapter` | `mock`, `dbRealtime`, `firestoreDb`, `supabaseDb` | `providers.mock/firebase/supabase` | sì (fallback: mock) |
94
+ | storage | `StorageProviderAdapter` | `firestorage`, `supabaseStorage` | `providers.firebase/supabase` | no |
95
+ | auth | `AuthProviderAdapter` | `googleAuth`, `firebaseAuth`, `supabaseAuth`, `dropboxAuth`, `githubAuth` | `providers.google/firebase/supabase/dropbox/github` | sì (fallback: googleAuth) |
96
+ | email | `EmailProviderAdapter` | `gmail` | `providers.google` | no |
97
+ | ai | `AIProviderAdapter` | `openai`, `gemini`, `anthropic`, `deepseek`, `mistral`, `openrouter`, `opencode`, `cloudflare`, `groq` | `Config.tsx AIConfig` | no |
98
+ | credentials | `CredentialsAdapter` | `googleServiceAccount` | `providers.google.serviceAccount` | no |
99
+
100
+ ### Hooks
101
+
102
+ ```ts
103
+ const data = useDataProvider() // DataProviderAdapter | null
104
+ const storage = useStorageProvider() // StorageProviderAdapter | null
105
+ const auth = useAuthProvider() // AuthProviderAdapter | null
106
+ const email = useEmailProvider() // EmailProviderAdapter | null
107
+ const ai = useAIProvider() // AIProviderAdapter | null
108
+ const creds = useCredentialsProvider() // CredentialsAdapter | null
109
+
110
+ // Named provider (multi-provider setup)
111
+ const supabase = useDataProvider('supabase')
112
+ ```
113
+
114
+ ### GitHub (`githubAuth`, sessione sul server dell'app)
115
+
116
+ GitHub richiede il client secret per scambiare il codice: scambio, token e sessione stanno sul server
117
+ dell'app, il browser vede solo il profilo. Config `providers.github = { sessionUrl: '/api/auth/github' }`,
118
+ driver `auth: 'githubAuth'`; funziona con `AuthButton` (pulsante e `aspect="avatar"`) e
119
+ `useAuthProvider('githubAuth')`. Il server espone sotto `sessionUrl`:
120
+
121
+ | Rotta | Risposta |
122
+ |---|---|
123
+ | `GET /login?returnTo=<path>[&scope=…]` | redirect a GitHub, poi di nuovo a `<path>` |
124
+ | `GET /me` | `{ login, name, avatarUrl, email }`, 401 senza sessione |
125
+ | `POST /logout` | chiude la sessione |
126
+
127
+ Lato server, da `@llmnative/react/server`:
128
+
129
+ ```ts
130
+ const oauth = createGitHubOAuth({ clientId, clientSecret, scopes: ['read:org'] })
131
+ oauth.authorizeUrl({ state, redirectUri, codeChallenge }) // PKCE S256
132
+ const { accessToken } = await oauth.exchangeCode({ code, redirectUri, codeVerifier }) // GitHubOAuthError se rifiutato
133
+ await oauth.getUser(accessToken) // { login, name, avatarUrl, email }
134
+ await oauth.getOrganizations(accessToken) // [{ login, avatarUrl, role: 'admin' | 'member' }]
135
+ ```
136
+
137
+ ### Interfacce principali
138
+
139
+ ```ts
140
+ // DataProviderAdapter
141
+ read(path, options?) / set(path, data) / update(path, data) / remove(path)
142
+ subscribe(path, callback: (records: RecordArray) => void): () => void
143
+ count?(path, where?): Promise<number>
144
+
145
+ // StorageProviderAdapter
146
+ upload(file, path): Promise<string|undefined>
147
+ getURL(path) / download(path): Promise<Blob|undefined> / delete(path): Promise<boolean>
148
+
149
+ // AuthProviderAdapter
150
+ signIn(intent?, options?) / signOut() / getUser(): UserProfile|null
151
+ onAuthChange(callback) / getAccessToken(): Promise<string|null>
152
+ ```
153
+
154
+ ### Auth sign-in methods
155
+
156
+ | method | Firebase | Supabase | Google |
157
+ |---|---|---|---|
158
+ | `password` | ✅ | ✅ | — |
159
+ | `anonymous` | ✅ | ✅ | — |
160
+ | `magic_link` | — | ✅ | — |
161
+ | `oauth` (github, apple…) | ✅ | ✅ | — |
162
+ | GIS + scoped token | — | — | ✅ |
163
+
164
+ ```ts
165
+ await auth.signIn({ method: 'password', email: '...', password: '...' })
166
+ await auth.signIn({ method: 'oauth', provider: 'github' })
167
+ // Google: token per API scope
168
+ const token = await auth.getAccessToken('https://www.googleapis.com/auth/gmail.send')
169
+ ```
170
+
171
+ ### CredentialsAdapter (Google Service Account)
172
+ ```tsx
173
+ // Chiama Google APIs lato browser senza Node.js
174
+ <App providers={{ google: { serviceAccount: { clientEmail, privateKey } }, services: { credentials: 'googleServiceAccount' } }} />
175
+
176
+ const creds = useCredentialsProvider()
177
+ const token = await creds.getToken('https://www.googleapis.com/auth/solar')
178
+ ```
179
+
180
+ ### Provider custom
181
+ ```ts
182
+ import { DataProviderAdapter, RecordArray } from '@llmnative/react'
183
+
184
+ export class RestDataProvider implements DataProviderAdapter {
185
+ async read(path: string): Promise<unknown> { ... }
186
+ async set(path: string, data: object): Promise<void> { ... }
187
+ async update(path: string, data: object): Promise<void> { ... }
188
+ async remove(path: string): Promise<void> { ... }
189
+ subscribe(path: string | undefined, callback: (records: RecordArray) => void): () => void {
190
+ return () => undefined
191
+ }
192
+ }
193
+ ```
194
+
195
+ ---
196
+
197
+ ## Grid — CRUD table/gallery
198
+
199
+ ```tsx
200
+ <Grid
201
+ path="/users" // DataProvider-backed — oppure records={array} per in-memory
202
+ columns={[
203
+ { key: 'name', label: 'Nome', sortable: true },
204
+ { key: 'email', label: 'Email' },
205
+ { key: 'role', label: 'Ruolo', render: ({ value }) => <Badge>{value}</Badge> },
206
+ { key: 'date', label: 'Data', render: 'date' },
207
+ ]}
208
+ actions={['add', 'edit', 'delete']} // oppure Record<string, GridAction>
209
+ view="table" // 'table' | 'gallery'
210
+ pagination={{ limit: 20 }}
211
+ groupBy="status"
212
+ sortable={{ field: 'name', dir: 'asc' }}
213
+ form={<FormFields />}
214
+ onSave={async ({ record, action }) => record._key}
215
+ onComplete={async ({ record, action }) => true}
216
+ selection={{ mode: 'multiple', onChange: (sel) => {} }}
217
+ reorderable
218
+ onReorder={(records, meta) => {}}
219
+ header={(ctx) => <div>{ctx.title}</div>}
220
+ footer={(ctx) => <div>{ctx.records.length} records</div>}
221
+ />
222
+ ```
223
+
224
+ | Prop | Tipo | Note |
225
+ |---|---|---|---|
226
+ | `path` | `string \| "fromUrl"` | Path provider-backed |
227
+ | `records` | `RecordArray` | Dati in memoria (alternativa a path) |
228
+ | `columns` | `GridColumn[]` | `{ key, label, sortable?, render?, className? }` |
229
+ | `actions` | `Array<'add'\|'edit'\|'delete'> \| Record<string, GridAction>` | |
230
+ | `view` | `'table' \| 'gallery'` | |
231
+ | `groupBy` | `string \| string[]` | |
232
+ | `pagination` | `PaginationParams` | `{ limit, page?, maxPageButtons?, align?, sticky? }` |
233
+ | `sortable` | `boolean \| OrderConfig` | |
234
+ | `selection` | `false \| 'single' \| 'multiple' \| GridSelectionConfig` | |
235
+ | `form` | `ReactElement \| ((ctx) => ReactNode)` | Form condiviso per CRUD |
236
+ | `onSave` | `GridMutationSaveHandler` | `async ({ record, action }) => string` |
237
+ | `onDelete` | `GridMutationDeleteHandler` | `async ({ record }) => string` |
238
+ | `onComplete` | `GridAfterActionHandler` | `async ({ record, action }) => boolean` |
239
+ | `onRowClick` | `(record) => void` | |
240
+ | `reorderable` | `boolean` | Abilita drag & drop righe |
241
+ | `onReorder` | `GridReorderHandler` | `(records, meta) => void` |
242
+ | `onLoad` | `(records) => TRecord[]` | Trasforma records dopo il fetch |
243
+ | `editDeepLink` | `boolean` | Sincronizza modal edit con URL |
244
+ | `audit` | `boolean` | Logga mutazioni |
245
+ | `sticky` | `'top' \| 'bottom'` | Header/footer sticky |
246
+ | `wrapperClassName` | `string` | CSS wrapper esterno |
247
+ | `loading` | `boolean` | Stato loading override |
248
+ | `title` | `ReactNode` | Titolo header grid |
249
+ | `before` / `after` | `ReactNode` | Slot prima/dopo il contenuto |
250
+ | `header` / `footer` | `ReactNode \| ((ctx) => ReactNode)` | Header/footer custom |
251
+ | `searchable` | `boolean \| GridSearchConfig` | Search box nell'header default — `{ fields?, placeholder? }` |
252
+ | `filters` | `GridFilterConfig[]` | Checkbox toggle nell'header default, applicati PRIMA di `searchable` — `{ key, label, defaultValue?, predicate(record, value) }` |
253
+
254
+ **GridAction kind:** `'modal'` (default), `'route'`, `'external'`, `'inline'`, `'delete'`
255
+
256
+ ---
257
+
258
+ ## Form — form CRUD con lifecycle
259
+
260
+ ```tsx
261
+ <Form
262
+ path="/products"
263
+ appearance="card" // 'card' | 'empty'
264
+ showBack
265
+ defaultValues={{ status: 'draft' }}
266
+ keyGenerator={() => `prod_${Date.now()}`}
267
+ onLoad={(data) => { /* side-effect hook, non trasforma */ }}
268
+ onSave={async ({ record, action }) => { /* return storagePath or undefined */ }}
269
+ onDelete={async ({ record }) => { /* confirm */ }}
270
+ onComplete={async ({ action }) => { if (action === 'save') navigate('/products') }}
271
+ >
272
+ <Input name="title" label="Titolo" required />
273
+ <Input name="price" label="Prezzo" type="number" />
274
+ <Input name="address.city" label="Città" /> {/* oggetto annidato */}
275
+ <Repeat name="tags" defaultLength={1}>
276
+ {(i) => <Input name={`tags.${i}`} label={`Tag ${i+1}`} />}
277
+ </Repeat>
278
+ </Form>
279
+ ```
280
+
281
+ | Prop | Tipo | Note |
282
+ |---|---|---|---|
283
+ | `path` | `string` | Path provider-backed |
284
+ | `appearance` | `'card' \| 'empty'` | Guscio visuale |
285
+ | `controller` | `FormController` | Controller condiviso per bottoni custom esterni |
286
+ | `showBack` | `boolean` | Pulsante Back nel footer |
287
+ | `defaultValues` | `RecordProps` | Valori iniziali per nuovo record |
288
+ | `keyGenerator` | `(record) => string` | Generatore chiave primaria custom |
289
+ | `draftBucket` | `string` | Bucket stabile che isola la bozza locale; omettilo per disabilitare la persistenza |
290
+ | `noticeAnchorRef` | `React.RefObject<HTMLElement>` | Ancoraggio sticky per notifiche |
291
+ | `showNotice` | `boolean` | Mostra notifiche save/delete (default `true`) |
292
+ | `children` | `ReactNode \| ((fields) => ReactNode) \| (({ record }) => ReactNode)` | Contenuto form |
293
+ | `header` | `ReactNode` | Contenuto header custom |
294
+ | `footer` | `ReactNode` | Contenuto footer custom |
295
+ | `wrapperClassName` | `string` | CSS wrapper esterno |
296
+ | `headerClassName` | `string` | CSS header |
297
+ | `className` | `string` | CSS body form |
298
+ | `footerClassName` | `string` | CSS footer |
299
+ | `log` | `boolean` | Logga ogni modifica su console |
300
+ | `onLoad` | `(record) => void` | Side-effect dopo il caricamento (non trasforma) |
301
+ | `onRecordChange` | `(record) => void` | Cambio campo in tempo reale |
302
+ | `onSave` | `FormSaveHandler` | `async ({ record, prevRecord?, storagePath?, action }) => string \| undefined` |
303
+ | `onDelete` | `FormDeleteHandler` | `async ({ record }) => string \| undefined` |
304
+ | `onComplete` | `FormFinallyHandler` | `async ({ record, action }) => boolean` |
305
+
306
+ **Form controller** — stato e azioni native del form accessibili da qualsiasi punto della pagina.
307
+
308
+ Due hook:
309
+
310
+ | Hook | Dove usarlo | Cosa restituisce |
311
+ |---|---|---|
312
+ | `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. |
313
+ | `useFormActions()` | Solo dentro `<Form>` (legge dal context) | Restituisce lo stesso `FormController` del form genitore. Lancia errore se usato fuori. |
314
+
315
+ Esempio — bottone custom fuori dal form:
316
+ ```tsx
317
+ const form = useFormController();
318
+
319
+ <ActionButton disabled={form.saveDisabled} onClick={() => { void form.save(); }} />
320
+ <Form controller={form} draftBucket="workspace/acme" onSave={...} />
321
+ ```
322
+
323
+ Esempio — uso dentro il form (senza passare controller):
324
+ ```tsx
325
+ function MySaveButton() {
326
+ const form = useFormActions();
327
+ return <LoadingButton disabled={form.saveDisabled} loading={form.isSaving} onClick={form.save} />;
328
+ }
329
+ ```
330
+
331
+ Stato esposto dal controller: `record`, `isNewRecord`, `isDirty`, `canSave`, `canDelete`, `isSaving`, `isDeleting`, `saveDisabled`, `deleteDisabled`, `hasDraft`, `draftStatus`, `errors`, `hasErrors`.
332
+
333
+ Azioni: `save()`, `delete()`, `reset()`, `restoreDraft()`, `discardDraft()`.
334
+
335
+ ---
336
+
337
+ ## Campi form
338
+
339
+ ### Input
340
+ ```tsx
341
+ <Input name="x" label="..." required /> // text (default)
342
+ <Input name="price" type="number" min={0} max={100} step={0.01} />
343
+ <Input name="email" type="email" />
344
+ <Input name="pwd" type="password" />
345
+ <Input name="date" type="date" />
346
+ <Input name="color" type="color" />
347
+ <TextArea name="bio" minHeight={96} />
348
+ <Checkbox name="active" valueChecked="yes" />
349
+ ```
350
+ `Input` props: `name`(req) `label` `type` `required` `disabled` `placeholder` `min` `max` `step` `validator:(v)=>string|undefined`
351
+ `type`: `'text' | 'number' | 'email' | 'password' | 'color' | 'date' | 'time' | 'datetime-local' | 'week' | 'month' | 'range' | 'checkbox' | 'radio' | 'url'`
352
+
353
+ **NOTA**: il tipo HTML si passa con `type`. `inputType` e i sotto-componenti `Input.Number`/`Input.Email`/`Input.Date` non esistono.
354
+
355
+ **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)`.
356
+ ```tsx
357
+ <Select name="skill" required options={skills} label={<>Skill <ActionButton icon="info" ariaLabel="Apri la skill" variant="link" onClick={openSkill} /></>} />
358
+ ```
359
+
360
+ ### Select / Autocomplete / Checklist
361
+ ```tsx
362
+ <Select name="role" options={[{ label: 'Admin', value: 'admin' }]} />
363
+ <Select name="categoryId" optionsSource={{ path: '/categories', labelField: 'name', valueField: '_key' }} />
364
+ <Autocomplete name="userId" optionsSource={{ path: '/users', labelField: 'email' }} maxItems={1} />
365
+ <Checklist name="tags" options={['a', 'b', 'c']} />
366
+ ```
367
+
368
+ | Prop | Tipo | Note |
369
+ |---|---|---|
370
+ | `options` | `Option[] \| string[] \| number[]` | |
371
+ | `optionsSource` | `{ path, labelField, valueField?, where?, order?, fieldMap?, onLoad? }` | Carica da provider |
372
+ | `order` | `{ field: 'label' \| 'value', dir: 'asc' \| 'desc' }` | |
373
+ | `placeholderOption` | `Option` | Solo Select |
374
+ | `placeholder` | `string` | Solo Autocomplete |
375
+ | `creatable` | `boolean` | Solo Autocomplete — crea nuovi valori |
376
+ | `onCreate` | `(value) => void \| boolean \| Promise<void \| boolean>` | Solo Autocomplete — restituire `false` per non selezionare il valore creato (es. aprire un modulo di creazione) |
377
+ | `listClassName` / `optionClassName` | `string` | Solo Autocomplete — classi della lista e delle voci (anche da tema `Autocomplete.listClassName` / `optionClassName`) |
378
+ | `minItems` / `maxItems` | `number` | Solo Autocomplete |
379
+ | `itemClassName` | `string` | Solo Checklist |
380
+ | `validator` | `(value) => string \| undefined` | Tutte le varianti |
381
+ | `readOnlyAfterSet` | `boolean` | readonly dopo primo valore |
382
+ | `disabled` | `boolean` | |
383
+ | `title` | `string` | |
384
+ | `feedback` | `string` | Messaggio di errore/suggerimento |
385
+
386
+ `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.
387
+
388
+ ### UploadImage / UploadDocument / UploadCSV
389
+ ```tsx
390
+ <UploadImage name="cover" label="Copertina" /> {/* con crop editor */}
391
+ <UploadDocument name="pdf" label="PDF" />
392
+ <UploadCSV name="data" label="Importa CSV" /> {/* con preview tabellare */}
393
+ ```
394
+
395
+ **UploadImageProps** (eredita FormFieldProps):
396
+ | Prop | Tipo | Note |
397
+ |---|---|---|
398
+ | `name` | `string` (required) | |
399
+ | `uploadPath` | `string` | Path storage per upload automatico |
400
+ | `accept` | `string` | MIME types accettati |
401
+ | `editable` | `boolean` | Abilita crop editor |
402
+ | `multiple` | `boolean` | Multipla selezione |
403
+ | `max` | `number` | Numero massimo file |
404
+ | `feedback` | `string` | Testo placeholder drop zone |
405
+ | `srcsetWidths` | `number[]` | Larghezze varianti responsive |
406
+ | `previewHeight` / `previewWidth` | `number` | Dimensioni preview |
407
+
408
+ **UploadDocumentProps** (eredita FormFieldProps): `name`, `uploadPath`, `accept`, `editable`, `multiple`, `max`
409
+
410
+ ### UploadCSV
411
+ ```tsx
412
+ <UploadCSV name="data" label="Importa CSV" />
413
+ ```
414
+ | Prop | Tipo |
415
+ |---|---|
416
+ | `name` | `string` (required) |
417
+ | `onDataLoaded` | `(data: UploadCSVData) => void` |
418
+ | `onParseField` | `([key, value]) => [key, value] \| undefined` |
419
+ | `normalizeKeys` | `boolean` |
420
+ | `removeEmptyFields` | `boolean` |
421
+ | `delimiter` | `string` |
422
+ | `label` / `icon` | Opzionali |
423
+
424
+ ### ImageField
425
+ ```tsx
426
+ <ImageField
427
+ name="hero"
428
+ label="Hero image"
429
+ defaultValue={{ src: 'https://example.com/hero.jpg', alt: 'Hero shot' }}
430
+ srcsetWidths={[400, 800]}
431
+ uploadPath="/content/images"
432
+ />
433
+ ```
434
+
435
+ Gestisce un oggetto `{ src, alt, srcset?, sizes? }`, preview inline, crop editor e generazione opzionale di varianti responsive.
436
+
437
+ ### CropImage
438
+ ```tsx
439
+ <CropImage img={imageObj} title="Ritaglia" scales={{ '1:1': 1, '4:3': 1.33 }} />
440
+ ```
441
+ 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.
442
+
443
+ ### CodeEditor
444
+ ```tsx
445
+ <CodeEditor
446
+ name="code"
447
+ label="Template"
448
+ language="html"
449
+ placeholder="Scrivi HTML..."
450
+ minHeight={200}
451
+ maxHeight={600}
452
+ disabled={false}
453
+ required
454
+ validateSyntax
455
+ commands={[{ name: 'wrap-section', handler: ({ value }) => `<section>\n${value}\n</section>` }]}
456
+ commandsTrigger="/"
457
+ />
458
+ ```
459
+ Editor basato su CodeMirror con syntax highlighting e validazione. Linguaggi: `liquid`, `html`, `json`, `js`, `ts`, `css`.
460
+ Quando `commands` e presente, `CodeEditor` apre internamente `ContextMenu` sul trigger configurato.
461
+
462
+ | Prop extra | Tipo |
463
+ |---|---|
464
+ | `language` | `CodeEditorLanguage` |
465
+ | `placeholder` | `string` |
466
+ | `minHeight` / `maxHeight` | `number` |
467
+ | `validateSyntax` | `boolean` |
468
+ | `validator` | `(value) => string \| undefined \| Promise<string \| undefined>` |
469
+ | `extensions` | `unknown[]` |
470
+
471
+ ### RichText
472
+ ```tsx
473
+ <RichText
474
+ name="body"
475
+ label="Article body"
476
+ placeholder="Scrivi..."
477
+ toolbar="fixed" // 'fixed' | 'floating' | false
478
+ toolbarCommands={['bold', 'italic', 'heading1', '|', 'bulletList', 'link']}
479
+ outputFormat="html" // 'html' | 'json' | 'text'
480
+ statusBar={{ tagBreadcrumb: true, wordCount: true }}
481
+ minHeight={200}
482
+ maxHeight={800}
483
+ imageUpload={{ path: '/content/images', srcsetWidths: [400, 800] }}
484
+ commands={[{ name: 'summary', icon: 'sparkles' }]}
485
+ commandsTrigger="/"
486
+ />
487
+ ```
488
+
489
+ | Prop extra | Tipo |
490
+ |---|---|
491
+ | `placeholder` | `string` |
492
+ | `disabled` | `boolean` |
493
+ | `feedback` | `string` |
494
+ | `toolbar` | `'fixed' \| 'floating' \| false` |
495
+ | `toolbarCommands` | `ToolbarCommand[]` |
496
+ | `outputFormat` | `'html' \| 'json' \| 'text'` |
497
+ | `statusBar` | `boolean \| StatusBarConfig` |
498
+ | `minHeight` / `maxHeight` | `number` |
499
+ | `imageUpload` | `RichTextImageUploadConfig` |
500
+ | `documentUpload` | `RichTextDocumentUploadConfig` |
501
+ | `validator` | `(value) => string \| undefined` |
502
+
503
+ ### Repeat — array dinamici
504
+ ```tsx
505
+ <Repeat name="items" defaultLength={3} minItems={1} maxItems={10} label="Elementi" layout="vertical" readOnly>
506
+ {({ index, record, records, remove }) => (
507
+ <>
508
+ <Input name={`items.${index}.name`} label="Nome" />
509
+ <UploadImage name={`items.${index}.photo`} label="Foto" />
510
+ </>
511
+ )}
512
+ </Repeat>
513
+ ```
514
+
515
+ | Prop | Tipo | Note |
516
+ |---|---|---|
517
+ | `name` | `string` (required) | |
518
+ | `children` | `ReactNode \| ((args) => ReactNode)` | Render prop con `{ index, record, records, remove }` |
519
+ | `defaultLength` | `number` | Righe iniziali |
520
+ | `minItems` / `maxItems` | `number` | Min/max righe |
521
+ | `layout` | `'vertical' \| 'horizontal' \| 'inline'` | |
522
+ | `label` | `string` | Etichetta gruppo |
523
+ | `labelPosition` | `'top' \| 'bottom'` | |
524
+ | `hideRemoveButton` | `boolean` | Nascondi rimozione |
525
+ | `readOnly` | `boolean` | Sola lettura |
526
+ | `onChange` | `FieldOnChange` | |
527
+ | `onAdd` / `onRemove` | `(records) => void` | Callback aggiunta/rimozione |
528
+
529
+ ### Prompt — campo AI-potenziato
530
+ ```tsx
531
+ <Prompt
532
+ name="summary"
533
+ mode="run" // 'edit' | 'run'
534
+ onRunPrompt={async (prompt, options) => AI.fetch(prompt)}
535
+ commands={[{ name: 'translate', icon: 'languages', handler: (v) => `Translate:\n${v}` }]}
536
+ commandsTrigger="/" // default automatico quando commands e presente
537
+ attachments
538
+ statusItems={['tokensIn', 'tokensOut', 'contextPercent', 'duration']}
539
+ />
540
+ ```
541
+
542
+ 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.
543
+
544
+ `renderFallback`: quando l'AI non e configurata, `Prompt` monta un fallback testuale; passa `renderFallback` per personalizzarlo (riceve `{ name, label, required, onChange }`).
545
+
546
+ ---
547
+
548
+ ## UI Primitives
549
+
550
+ ### Alert
551
+ ```tsx
552
+ <Alert variant="success">Salvato!</Alert>
553
+ <Alert variant="warning" icon placement="fixed" timeout={3000}>Attenzione</Alert>
554
+ ```
555
+ `variant`: `'info' | 'success' | 'warning' | 'danger' | 'primary' | 'secondary' | 'light' | 'dark'`
556
+ `appearance`: `'default' | 'text'`
557
+ `placement`: `'inline' | 'fixed'`
558
+
559
+ ### Badge
560
+ ```tsx
561
+ <Badge variant="success">Attivo</Badge>
562
+ ```
563
+ `variant`: stessi valori di Alert
564
+
565
+ ### Button variants
566
+ ```tsx
567
+ <ActionButton variant="primary" label="Salva" icon="save" onClick={handleSave} />
568
+ <LoadingButton variant="primary" label="Invia" onClick={async (e, setMsg) => { await save(); setMsg('Salvato!') }} />
569
+ <BackLink label="Indietro" />
570
+ <GoSite href="https://..." label="Visita" />
571
+ ```
572
+
573
+ **IButton props:** `variant`, `label`, `icon`, `badge`, `disabled`, `ariaLabel`, `title`, `iconClassName`, `onClick`
574
+ **LoadingButton aggiunge:** `loading`, `loadingLabel` — `onClick` riceve `(e, setMessage?) => Promise<unknown>`
575
+
576
+ ### Card
577
+ ```tsx
578
+ <Card title="Titolo" header={<Actions />} footer={<Pagination />} loading={isLoading}>
579
+ {children}
580
+ </Card>
581
+ ```
582
+
583
+ ### Modal
584
+ ```tsx
585
+ <Modal title="Conferma" size="md" position="center" onClose={() => {}} onSave={handleSave} onDelete={handleDelete} motion="fade" allowFullscreen stackedBehind>
586
+ {content}
587
+ </Modal>
588
+ <ModalYesNo title="Sicuro?" onClose={() => {}} onYes={async () => true}>Eliminare il record?</ModalYesNo>
589
+ <ModalOk title="Completato!" onClose={() => {}}>Salvato.</ModalOk>
590
+ ```
591
+ `size`: `'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'fullscreen'`
592
+ `position`: `'center' | 'top' | 'left' | 'right' | 'bottom'`
593
+ `ModalYesNo` e `ModalOk` sono export separati: `Modal.YesNo` e `Modal.Ok` non esistono.
594
+ Tastiera: Esc chiude il modal in cima alla pila (`closeOnEscape`, default `true`).
595
+ 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 })`.
596
+
597
+ | Prop | Tipo | Note |
598
+ |---|---|---|
599
+ | `children` | `ReactNode` (required) | |
600
+ | `title` | `ReactNode` | |
601
+ | `header` / `footer` | `ReactNode \| false` | Custom header/footer |
602
+ | `size` / `position` | Come sopra | |
603
+ | `onClose` | `() => void` | |
604
+ | `onSave` / `onDelete` | `(e) => Promise<boolean>` | |
605
+ | `allowFullscreen` | `boolean` | Toggle fullscreen |
606
+ | `showCancel` | `boolean` | Default `true` |
607
+ | `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 |
608
+ | `closeOnBackdrop` | `boolean` | Default `true` |
609
+ | `closeOnEscape` | `boolean` | Default `true` — solo il modal in cima reagisce |
610
+ | `zIndex` | `number` | |
611
+ | `motion` | `MotionReference` | Preset animazione |
612
+ | Classi CSS header/title/subtitle/body/footer | `string` | |
613
+
614
+ ### Table
615
+ ```tsx
616
+ <Table
617
+ columns={[{ key: 'name', label: 'Nome', sort: true }]}
618
+ records={records}
619
+ onRowClick={(record) => {}}
620
+ selection="multiple"
621
+ sortable={{ field: 'name', dir: 'asc' }}
622
+ pagination={{ limit: 20 }}
623
+ onReorder={(records, meta) => {}}
624
+ onSelectionChange={(sel) => {}}
625
+ groupBy="status"
626
+ renderCell={(record, key, index) => <CustomCell />}
627
+ />
628
+ ```
629
+
630
+ | Prop | Tipo |
631
+ |---|---|
632
+ | `columns` | `TableHeaderProp[]` |
633
+ | `records` | `RecordArray` |
634
+ | `sortable` | `boolean \| OrderConfig` |
635
+ | `pagination` | `PaginationParams` |
636
+ | `selection` | `'single' \| 'multiple'` |
637
+ | `onRowClick` | `(record) => void` |
638
+ | `onReorder` | `(records, meta) => void` |
639
+ | `onSelectionChange` | `(selection) => void` |
640
+ | `renderCell` | `(record, key, index) => ReactNode` |
641
+ | `groupBy` | `string \| string[]` |
642
+ | `activeKey` | `string \| null` |
643
+ | `selectedKeys` | `string[]` |
644
+ | `header` / `footer` | `ReactNode` |
645
+ | `headerClassName` / `bodyClassName` / `footerClassName` / `scrollClassName` / `selectedClassName` / `heightClassName` | `string` |
646
+
647
+ ### Gallery
648
+ ```tsx
649
+ <Gallery
650
+ records={records}
651
+ overlays={[{ position: 'topRight', badge: { variant: 'success', children: 'New' } }]}
652
+ columns={3}
653
+ gap={2}
654
+ sortable={{ field: 'name', dir: 'asc' }}
655
+ pagination={{ limit: 20 }}
656
+ onRowClick={(record) => {}}
657
+ onSelectionChange={(sel) => {}}
658
+ header="Titolo"
659
+ groupBy="status"
660
+ />
661
+ ```
662
+
663
+ `position`: `'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight' | 'middleLeft' | 'middleRight'`
664
+
665
+ | Prop | Tipo |
666
+ |---|---|
667
+ | `records` | `GalleryRecord[]` (`{ img?, thumbnail?, name?, width?, height? }`) |
668
+ | `columns` | `1 \| 2 \| 3 \| 4 \| 6` |
669
+ | `gap` | `0 \| 1 \| 2 \| 3 \| 4 \| 5` |
670
+ | `overlays` | `GalleryOverlay[]` |
671
+ | `sortable` | `boolean \| OrderConfig` |
672
+ | `pagination` | `PaginationParams` |
673
+ | `onRowClick` | `(record) => void` |
674
+ | `onSelectionChange` | `(selection) => void` |
675
+ | `groupBy` | `string \| string[]` |
676
+ | `selectedKeys` | `string[]` |
677
+ | `header` / `footer` | `ReactNode` |
678
+ | Classi CSS: `headerClassName`, `bodyClassName`, `footerClassName`, `scrollClassName`, `selectedClassName` | `string` |
679
+
680
+ ### Tab
681
+ ```tsx
682
+ import { Tab, TabItem } from '@llmnative/react'
683
+
684
+ <Tab defaultIndex={0} layout="top">
685
+ <TabItem label="Generale">{content1}</TabItem>
686
+ <TabItem label="SEO">{content2}</TabItem>
687
+ </Tab>
688
+ ```
689
+ `layout`: `'default' | 'top' | 'left' | 'right' | 'bottom'`
690
+ Le schede sono `<TabItem>`, export separato: `Tab.Item` non esiste.
691
+
692
+ ### Image
693
+ ```tsx
694
+ <Image src="..." fit="cover" position="center" width={400} height={300} />
695
+ ```
696
+ `fit`: `'cover' | 'contain' | 'fill' | 'scale-down' | 'none'`
697
+
698
+ ### Pagination (standalone)
699
+ ```tsx
700
+ <Pagination records={items} limit={20}>
701
+ {(pageRecords, offset) => pageRecords.map(r => <Row key={r._key} record={r} />)}
702
+ </Pagination>
703
+ ```
704
+
705
+ ### Percentage
706
+ ```tsx
707
+ <Percentage value={75} appearance="bar" variant="success" showText />
708
+ <Percentage value={0.75} appearance="circle" size={60} />
709
+ ```
710
+
711
+ | Prop | Tipo | Default |
712
+ |---|---|---|
713
+ | `value` | `number` | — |
714
+ | `max` | `number` | `100` |
715
+ | `min` | `number` | — |
716
+ | `appearance` | `'bar' \| 'circle'` | `'bar'` |
717
+ | `variant` | `ColorType` | — |
718
+ | `trackVariant` | `ColorType` | — |
719
+ | `thickness` | `number` | — (px) |
720
+ | `showText` | `boolean` | — |
721
+ | `size` | `number` | Diametro in modalità `'circle'` (px) |
722
+ | `fontSize` | `number` | — |
723
+ | `label` | `string` | — |
724
+
725
+ ### DescriptionList
726
+ 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>`.
727
+ ```tsx
728
+ <DescriptionList items={[{ label: 'Email', value: 'a@b.it' }, { label: 'Telefono', value: null }]} />
729
+ <DescriptionList layout="stacked" columns={4} truncate items={[{ label: 'Stato', value: <Badge variant="success">Spedito</Badge> }]} />
730
+ ```
731
+
732
+ | Prop | Tipo | Default |
733
+ |---|---|---|
734
+ | `items` | `DescriptionListItem[]` — `{ key?, label, value?, title? }` | — |
735
+ | `layout` | `'horizontal' \| 'stacked'` | `'horizontal'` (etichette a sinistra, impilate su mobile) |
736
+ | `columns` | `1 \| 2 \| 3 \| 4 \| 5 \| 6` | `1` (solo `stacked`, dal breakpoint `lg`) |
737
+ | `labelWidth` | `string` (lunghezza CSS) | `'12rem'` (solo `horizontal`) |
738
+ | `emptyValue` | `ReactNode` | `'—'` per `null` / `undefined` / `''` (lo `0` resta) |
739
+ | `truncate` | `boolean` | `false`; un valore testuale diventa il suo `title` |
740
+ | Classi | `wrapperClassName`, `className`, `itemClassName`, `labelClassName`, `valueClassName` | tema `DescriptionList` |
741
+
742
+ ### Tree
743
+ 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.
744
+ ```tsx
745
+ <Tree nodes={treeFromPaths(paths)} defaultExpanded selectedId={path} onSelect={(node) => setPath(node.id)} ariaLabel="File" />
746
+ <Tree nodes={[{ id: 'a', label: 'Docs', children: [{ id: 'a/1', label: 'README.md', badge: <Badge>new</Badge> }] }]} />
747
+ ```
748
+ | Prop | Tipo | Note |
749
+ |---|---|---|
750
+ | `nodes` | `TreeNode[]` — `{ id, label, icon?, badge?, description?, children?, disabled? }` | `id` unico; con `children` è una cartella |
751
+ | `selectedId` + `onSelect` / `defaultSelectedId` | `string \| null` | selezione controllata o no |
752
+ | `expanded` + `onExpandedChange` / `defaultExpanded` | `string[]`; `defaultExpanded` anche `true` (tutto aperto) | apertura controllata o no |
753
+ | `selectableBranches` | `boolean` (default `false`) | anche le cartelle si selezionano |
754
+ | `ariaLabel` | `string` | nome accessibile |
755
+ | Classi | `wrapperClassName`, `className`, `itemClassName`, `selectedClassName` | tema `Tree` |
756
+
757
+ `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…).
758
+
759
+ ### Dropdown
760
+ ```tsx
761
+ <Dropdown trigger={<Icon name="menu" />} position="end">
762
+ <DropdownItem label="Modifica" icon="edit" onClick={() => {}} />
763
+ <DropdownItem label="Elimina" icon="trash" variant="danger" />
764
+ <DropdownDivider />
765
+ <DropdownHeader label="Azioni rapide" />
766
+ </Dropdown>
767
+ ```
768
+
769
+ Azioni secondarie di una voce (CR-107): `actions` mostra icone in fondo alla riga, al passaggio
770
+ del mouse o al focus (sempre sui dispositivi touch). Non selezionano la voce e lasciano il menu aperto
771
+ salvo `closeOnClick`.
772
+
773
+ ```tsx
774
+ <DropdownItem icon="messages-square" onClick={() => open(chat)}
775
+ actions={[{ icon: 'archive', label: 'Archivia', onClick: () => archive(chat) }]}>
776
+ {chat.title}
777
+ </DropdownItem>
778
+ ```
779
+
780
+ Per elenchi caricati dinamicamente usare `AsyncDropdown`: gestisce ricerca con debounce,
781
+ cancellazione delle richieste precedenti tramite `AbortSignal` e stati loading/empty/error.
782
+
783
+ ```tsx
784
+ <AsyncDropdown
785
+ trigger={<ActionButton label="Select user" />}
786
+ loadItems={(query, signal) => users.search(query, { signal })}
787
+ getItemId={user => user.id}
788
+ renderItem={user => user.name}
789
+ onSelect={user => setUser(user)}
790
+ selectedId={user?.id}
791
+ />
792
+ ```
793
+
794
+ ### ContextMenu
795
+ ```tsx
796
+ <ContextMenu trigger="/" searchable>
797
+ <ContextMenu.Heading>Comandi</ContextMenu.Heading>
798
+ <ContextMenu.Item label="Titolo" value="# " icon="heading" />
799
+ <ContextMenu.Separator />
800
+ <ContextMenu.Item label="Bold" value="**bold**" icon="bold" />
801
+ </ContextMenu>
802
+ ```
803
+ Funziona su qualsiasi `<textarea>` / `<input>` figlio. Trigger custom (`/`, `@`, `{`), filtro searchable, navigazione tastiera, floating positioning.
804
+
805
+ | Prop | Tipo | Note |
806
+ |---|---|---|
807
+ | `trigger` | `string` (required) | Es. `"/"`, `"@"`, `"{"` |
808
+ | `searchable` | `boolean` | Filtro testuale |
809
+ | `controlled` | `ContextMenuControlledState` | Stato controllato esterno |
810
+ | `onSelect` | `(item, context) => void` | |
811
+
812
+ **EditorCommand** (usato da `commands` prop su `RichText`, `CodeEditor`, `Prompt`):
813
+ ```ts
814
+ {
815
+ name: string;
816
+ description?: string;
817
+ icon?: string;
818
+ group?: string;
819
+ consumeSuffix?: string;
820
+ handler?: (context: TextCommandContext) => string | Promise<string>;
821
+ }
822
+ ```
823
+
824
+ `consumeSuffix` elimina una chiusura automatica adiacente durante la sostituzione del trigger,
825
+ utile quando un comando cambia famiglia sintattica (per esempio da `{{ ... }}` a `{% ... %}`).
826
+
827
+ ### Altre primitive
828
+ ```tsx
829
+ <Icon name="user" size={20} /> // usa provider icone configurato
830
+ <ImageAvatar src="..." title="Mario" alt="Mario" width={40} height={40} />
831
+ <Identicon value="acme/app" size={32} title="acme/app" /> // icona generata dal valore, stile GitHub
832
+ <Loader show={isLoading}>{content}</Loader> // indicatore al posto dei figli finché show è true
833
+ <Loader show>{null}</Loader> // solo indicatore (es. pagina in caricamento)
834
+ <Code language="tsx">{snippet}</Code> // syntax highlight
835
+ <GridSystem.Row><GridSystem.Col xs={12} md={6}>...</GridSystem.Col></GridSystem.Row>
836
+ <LocaleSwitcher locales={[{ code: 'it', label: 'Italiano' }]} />
837
+ <ThemeSwitcher />
838
+ <ProviderSwitcher />
839
+ <LayoutBuilder components={...} />
840
+ ```
841
+
842
+ ---
843
+
844
+ ## Blocks
845
+
846
+ ```tsx
847
+ <Breadcrumbs trail={[{ label: 'Home', href: '/' }, { label: 'Utenti' }]} separator="/" jsonLd />
848
+ <Brand url="/" label="MyApp" logo="/logo.svg" width={120} />
849
+ <Search onQueryChange={(e) => setQ(e.target.value)} />
850
+ <Notifications items={[...]} seeAllUrl="/notifications" onMarkAllRead={() => {}} />
851
+ <Carousel images={[...]} />
852
+ <Toolbar items={[...]}>
853
+ {children}
854
+ </Toolbar>
855
+ <SideNav />
856
+ <ListCard records={records} onRowClick={(r) => {}} />
857
+ ```
858
+
859
+ **Brand:**
860
+ | Prop | Tipo |
861
+ |---|---|
862
+ | `url` | `string` |
863
+ | `label` | `string` |
864
+ | `logo` | `string` |
865
+ | `width` / `height` | `number` |
866
+ | `wrapperClassName` / `className` / `logoClassName` / `labelClassName` | `string` |
867
+
868
+ **SideNav:**
869
+ | Prop | Tipo |
870
+ |---|---|
871
+ | `items` | `SideNavItemDef[]` (in alternativa a `menuKey`) |
872
+ | `menuKey` | `string` — voci dal menu registrato in `<App>` |
873
+ | `bottomItems` | `SideNavItemDef[]` — voci fissate in fondo, sopra il footer e fuori dalla lista scorrevole (es. Impostazioni) |
874
+ | `header` / `footer` | `ReactNode` |
875
+ | `collapsed` + `onCollapsedChange` / `defaultCollapsed` | `boolean` — compressione controllata o no |
876
+ | `showIcons` / `showCollapseButton` | `boolean` (default `true`) |
877
+ | `embedded` | `boolean` — solo le voci, senza guscio (drawer, pannelli); `bottomItems` seguono le voci principali |
878
+
879
+ `SideNavItemDef`: `{ path, title?, icon?, group?, end?, badge?, children? }`. La voce attiva ha
880
+ `aria-current="page"`.
881
+
882
+ ```tsx
883
+ <SideNav
884
+ items={[{ path: '/dashboard', title: 'Dashboard', icon: 'home' }]}
885
+ bottomItems={[{ path: '/settings', title: 'Impostazioni', icon: 'settings' }]}
886
+ />
887
+ ```
888
+
889
+ **ImageAvatar:**
890
+ | Prop | Tipo |
891
+ |---|---|
892
+ | `src` | `string` (obbligatoria) |
893
+ | `width` / `height` | `number` |
894
+ | `title` / `alt` | `string` |
895
+ | `fit` | `AvatarFit` |
896
+ | `badge` | `BadgeDescriptor` |
897
+ | `feedback` | `ReactNode` |
898
+
899
+ **Identicon:** l'icona di un'entità senza immagine (repository, tenant, utente senza foto), come quelle di
900
+ GitHub: griglia 5×5 simmetrica, celle e tinta da un hash di `value`. Lo stesso valore dà sempre la stessa
901
+ icona; niente rete né storage. Default: `rounded-md bg-muted` (tema `Identicon.className`).
902
+ `identiconPattern(value)` restituisce celle e tinta, per chi la disegna altrove.
903
+ | Prop | Tipo |
904
+ |---|---|
905
+ | `value` | `string` (obbligatoria) |
906
+ | `size` | `number` (px, default 40) |
907
+ | `title` | `string`: nome accessibile (`role="img"`); senza, `aria-hidden` |
908
+ | `before` / `after` / `className` / `wrapperClassName` | come le altre primitive |
909
+
910
+ **Search:**
911
+ | Prop | Tipo |
912
+ |---|---|
913
+ | `onQueryChange` | `(e: React.ChangeEvent<HTMLInputElement>) => void` |
914
+
915
+ **Notifications:**
916
+ | Prop | Tipo |
917
+ |---|---|
918
+ | `items` | `NotificationItem[]` |
919
+ | `badge` | `BadgeProps` |
920
+ | `seeAllUrl` | `string` |
921
+ | `onMarkAllRead` | `() => void` |
922
+ | `motion` | `MotionReference` |
923
+
924
+ **ListCard:**
925
+ | Prop | Tipo |
926
+ |---|---|
927
+ | `title` / `description` / `meta` | `ReactNode` |
928
+ | `badge` | `ReactNode` |
929
+ | `icon` | `string \| ReactNode` |
930
+ | `trailing` / `footer` / `children` | `ReactNode` |
931
+ | `href` | `string` |
932
+ | `external` / `active` / `disabled` / `dashed` / `compact` | `boolean` |
933
+ | `align` | `'start' \| 'center'` |
934
+ | `onClick` | `(e) => void` |
935
+ | Classi CSS: `titleClassName`, `descriptionClassName`, `metaClassName`, `badgeClassName`, `leadingClassName`, `bodyClassName`, `headerClassName`, `trailingClassName`, `footerClassName` | `string` |
936
+
937
+ **Dropdown:**
938
+ | Prop | Tipo |
939
+ |---|---|
940
+ | `trigger` | `string \| ReactNode \| DropdownTogglerProps` |
941
+ | `badge` | `BadgeProps` |
942
+ | `header` / `footer` | `ReactNode` |
943
+ | `defaultOpen` / `open` | `boolean` |
944
+ | `onOpenChange` | `(open) => void` |
945
+ | `position` | `'start' \| 'end'` |
946
+ | `placement` | `'auto' \| 'top' \| 'bottom'` |
947
+ | `strategy` | `'fixed' \| 'absolute'` |
948
+
949
+ // Menu — renderizza una sezione del menuConfig passato ad <App>
950
+ <Menu menuKey="main" /> // 'main' o qualsiasi chiave definita in MenuConfig
951
+ <Menu menuKey="topbar" className="nav flex-row gap-2" />
952
+ // NON usare context= — la prop si chiama menuKey
953
+
954
+ // AuthButton — login/logout con il provider auth configurato
955
+ <AuthButton />
956
+ ```
957
+
958
+ ---
959
+
960
+ ## Widgets
961
+
962
+ ### MarkdownReader
963
+ ```tsx
964
+ <MarkdownReader
965
+ content={markdownString}
966
+ onInternalLinkClick={(href, e) => { e.preventDefault(); navigate(href) }}
967
+ wrapperClassName="prose"
968
+ />
969
+ ```
970
+
971
+ ### ImageEditor
972
+ ```tsx
973
+ <ImageEditor src="..." onSave={(dataUrl) => save(dataUrl)} />
974
+ ```
975
+
976
+ `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.
977
+
978
+ ### TabDynamic
979
+ Tab con lazy loading dei contenuti — gestione dinamica aggiunta/rimozione tab.
980
+
981
+ ---
982
+
983
+ ## AI Integration
984
+
985
+ ```ts
986
+ import { useAIProvider, getAIModelCatalog, createAIProviderRegistry } from '@llmnative/react'
987
+
988
+ // Hooks
989
+ const provider = useAIProvider() // provider di default
990
+ const registry = useAIProviderRegistry() // tutti i provider AI registrati
991
+ const catalog = getAIModelCatalog() // modelli disponibili
992
+ // ogni modello: { id, provider, model, label, pricing? } — pricing in USD per 1M token
993
+ // { input, output, currency: 'USD', source: 'provider' | 'models.dev' }; assente = prezzo
994
+ // non trovato (il modello resta in lista). isFreeAIModel(m) → input e output a 0.
995
+ // Il model picker di Prompt/Chatbot mostra "$in / $out", evidenzia i free, segnala i mancanti,
996
+ // e raggruppa per provider (ChatbotModelOption.group = providerLabel) con header sticky.
997
+
998
+ // Provider adapter restituito da useAIProvider()
999
+ const text = await provider.fetch("Scrivi un titolo per: {keyword}", { keyword: "React" })
1000
+ const json = await provider.json("Lista di 5 categorie per blog tech")
1001
+ const arr = await provider.array("5 tag per: machine learning")
1002
+
1003
+ // Provider custom
1004
+ class MyAIProvider implements AIProviderAdapter {
1005
+ async fetch(prompt: string, options?: AIRequestOptions): Promise<string> { ... }
1006
+ async json<T>(prompt: string, options?: AIRequestOptions): Promise<T> { ... }
1007
+ async array(prompt: string, options?: AIRequestOptions): Promise<string[]> { ... }
1008
+ }
1009
+
1010
+ // Factory per registri esterni
1011
+ const registry = createAIProviderRegistry(definitions)
1012
+ // Azioni di Chatbot (CR-107): con `content` aprono un menu; senza, sono pulsanti con `onClick`.
1013
+ // <Chatbot actions={[{ key: 'finish', icon: 'git-pull-request', label: 'Concludi', showLabel: true,
1014
+ // disabled: running, onClick: finish }]} … />
1015
+ ```
1016
+
1017
+ ### Identità dei modelli indipendente dal provider (CR-103)
1018
+
1019
+ ```ts
1020
+ const index = await loadModelIdentityIndex() // models.dev, un fetch per sessione
1021
+ canonicalModelName('DeepSeek V4.1 Flash (Alibaba Cloud)') // 'deepseek v4.1 flash'
1022
+ index.models['deepseek v4.1 flash'] // { key, name, family?, providers: { openrouter: [{ id, name }], … } }
1023
+ resolveModel(index, 'DeepSeek V4.1 Flash', ['openrouter', 'deepseek'])
1024
+ // → { provider: 'openrouter', model: 'deepseek/deepseek-v4.1-flash', ref: 'openrouter/deepseek/deepseek-v4.1-flash' }
1025
+ ```
1026
+
1027
+ Il nome canonico toglie data, Free, Latest e host o regione tra parentesi; una modalità
1028
+ ("(Thinking)", "(Reasoning)", "(Fast)") resta. Per ogni provider l'id preferito è quello stabile (non
1029
+ alias `~`, non free tier, non datato). I provider sono le chiavi di models.dev, le stesse di opencode.
1030
+ Puro: anche da `@llmnative/react/server`.
1031
+
1032
+ ### Chiavi tenute dal server (CR-102)
1033
+
1034
+ Per un'app che non mette mai le chiavi dei provider nel browser. Il browser conosce solo quali
1035
+ provider sono collegati; il proxy dell'app mette la chiave.
1036
+
1037
+ ```ts
1038
+ // Browser: gli stessi adapter, con un segnaposto dove andrebbe la chiave. Serve il proxy attivo.
1039
+ const registry = createServerCredentialAIRegistry(
1040
+ [{ id: 'anthropic' }, { id: 'cloudflare', accountId }, { id: 'openai-compatible', baseUrl }],
1041
+ { scope: companyId }, // lettere, cifre, - e _
1042
+ )
1043
+ Object.entries(registry).forEach(([id, adapter]) => setProvider('ai', id, adapter))
1044
+
1045
+ // Server (Node, nessuna dipendenza da React): nel proxy, prima di inoltrare.
1046
+ import { resolveServerCredentials } from '@llmnative/react/server'
1047
+ const resolved = await resolveServerCredentials({ url: target, headers },
1048
+ (scope, provider) => keysOf(scope)[provider]) // { id, apiKey, accountId?, baseUrl? } | undefined
1049
+ if (!resolved.ok) return reply(resolved.status, resolved.error) // 404 non collegato, 403 host estraneo
1050
+ await fetch(resolved.url, { headers: resolved.headers, ... })
1051
+ ```
1052
+
1053
+ La chiave va solo agli host del provider (`AI_PROVIDER_HOSTS`, il `baseUrl` di openai-compatible,
1054
+ l'account di Cloudflare): una destinazione diversa è rifiutata. `createProxyPlugin(route, log,
1055
+ lookup)` fa lo stesso nel proxy di sviluppo di Vite. Senza proxy, `proxyFetch` rifiuta di inviare
1056
+ un segnaposto. `createAIProviderRegistry` (chiavi nel browser) resta com'è.
1057
+
1058
+ 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`).
1059
+
1060
+ ---
1061
+
1062
+ ## Theme e icone
1063
+
1064
+ ```tsx
1065
+ const theme = useThemeController()
1066
+ theme.applyTheme('flat') // BuiltInThemeId ('default' | 'flat' | 'cyber' | 'vscode-dark-modern' | …) | custom
1067
+ theme.setMode('dark') // 'light' | 'dark' | 'system'
1068
+
1069
+ const icons = useIconController()
1070
+ icons.setProvider('phosphor') // 'lucide' | 'phosphor' | custom
1071
+ ```
1072
+
1073
+ ---
1074
+
1075
+ ## Head (SEO)
1076
+
1077
+ ```ts
1078
+ useHead({
1079
+ title: 'Pagina',
1080
+ description: '...',
1081
+ robots: 'noindex',
1082
+ canonical: 'https://...',
1083
+ og: { title: '...', image: '...' }
1084
+ })
1085
+ ```
1086
+
1087
+ ---
1088
+
1089
+ ## Global state (localStorage)
1090
+
1091
+ ```ts
1092
+ const vars = useGlobalVars()
1093
+ getGlobalVars('key')
1094
+ setGlobalVars({ key: 'value' })
1095
+ removeGlobalVars('key')
1096
+ ```
1097
+
1098
+ ---
1099
+
1100
+ ## Hooks completi
1101
+
1102
+ | Hook | Ritorna |
1103
+ |---|---|
1104
+ | `useDataProvider(name?)` | `DataProviderAdapter \| null` |
1105
+ | `useStorageProvider(name?)` | `StorageProviderAdapter \| null` |
1106
+ | `useAuthProvider(name?)` | `AuthProviderAdapter \| null` |
1107
+ | `useEmailProvider(name?)` | `EmailProviderAdapter \| null` |
1108
+ | `useAIProvider(name?)` | `AIProviderAdapter \| null` |
1109
+ | `useAIProviderRegistry()` | `Record<string, AIProviderAdapter>` |
1110
+ | `useCredentialsProvider()` | `CredentialsAdapter \| null` |
1111
+ | `useTheme()` | `Theme \| undefined` |
1112
+ | `useThemeController()` | `ThemeController` |
1113
+ | `useIconController()` | `IconController` |
1114
+ | `useAccessToken(clientID, renew?)` | `boolean` | Ottiene token per servizio esterno (true = ok) |
1115
+ | `useGlobalVars()` | `Record<string, unknown>` |
1116
+ | `useHead()` | `HeadController` |
1117
+ | `useDocumentHead()` | `HeadController` |
1118
+ | `useAssetsHead(title?)` | `void` |
1119
+ | `useLanguageHead(lang?)` | `void` |
1120
+ | `useSocialHead(config)` | `void` |
1121
+ | `usePaginationHead(config)` | `void` |
1122
+ | `usePwaHead(config)` | `void` |
1123
+ | `useSchemaOrgHead(config)` | `void` |
1124
+ | `useHeadLinks(links)` | `void` |
1125
+ | `useProxy()` | `(url, init?) => Promise<Response>` |
1126
+ | `useImage()` | `UseImageResult` |
1127
+ | `useI18n()` | `I18nController` |
1128
+ | `useMenu()` | Menu hook |
1129
+ | `useFormController(controller?)` | `FormController` |
1130
+ | `useFormActions()` | `FormController` |
1131
+ | `useApiProvider(pathname?)` | `ApiProviderAdapter \| null` |
1132
+ | `useSetProvider(service, driver?)` | `void` |
1133
+ | `useProvider(name)` | `ProviderConfigurationState` |
1134
+ | `useProviderSession()` | `ProviderSession` |
1135
+ | `useDropBoxConnect(config?)` | `DropBoxConnectResult` |
1136
+ | `useEnterMotion(baseStyle?, ref?, fallback?)` | `CSSProperties` |
1137
+ | `useMotionState(active, ref?, fallback?, baseStyle?)` | `CSSProperties` |
1138
+ | `useMotionEffect(ref?, fallback?)` | `ResolvedMotionEffect` |
1139
+ | `usePressMotion(hovered, baseStyle?, ref?, fallback?)` | `{ style, pressHandlers }` |
1140
+ | `useIconProvider()` | `IconProvider` |
1141
+
1142
+ ---
1143
+
1144
+ ## Tipi chiave
1145
+
1146
+ ```ts
1147
+ type RecordProps = Record<string, FieldValue>
1148
+ type FieldValue = string | number | boolean | null | undefined | Record<string, unknown> | unknown[]
1149
+ type RecordArray = RecordProps[]
1150
+
1151
+ type OrderConfig = { field: string; dir: 'asc' | 'desc' }
1152
+ type WhereClause = { field: string; op: '==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any'; value: unknown }
1153
+
1154
+ interface UIProps {
1155
+ before?: React.ReactNode
1156
+ after?: React.ReactNode
1157
+ wrapperClassName?: string
1158
+ className?: string
1159
+ }
1160
+
1161
+ type UserProfile = { uid?: string; email?: string; displayName?: string; photoURL?: string; [key: string]: unknown }
1162
+ ```
1163
+
1164
+ ---
1165
+
1166
+ ## Utilities
1167
+
1168
+ ```ts
1169
+ import { cn, converter, Sanitizer, Order, path, fetchJson, fetchRest, fetchWithRetry } from '@llmnative/react'
1170
+ import { getKeywordIdeas, getGoogleTrendsData, getGoogleTrendsRelated } from '@llmnative/react'
1171
+
1172
+ cn('base', condition && 'extra', className) // tailwind-merge classname
1173
+ new Sanitizer().sanitize(html) // XSS sanitizer (non usare dangerouslySetInnerHTML)
1174
+ new Order().order(records, { field: 'name', dir: 'asc' }) // ordina record array
1175
+ fetchJson(url, init?) // fetch + JSON parse + error handling
1176
+ fetchRest(path, init?) // fetch REST con auth
1177
+ getKeywordIdeas(keyword) // Google Ads Keyword Ideas
1178
+ getGoogleTrendsData(keyword) // Google Trends interest over time
1179
+ getGoogleTrendsRelated(keyword) // Google Trends related queries
1180
+ ```
1181
+
1182
+ ---
1183
+
1184
+ ## Scaffold (npx create)
1185
+
1186
+ ```bash
1187
+ npx @llmnative/react create
1188
+ npx @llmnative/react create --yes --provider=mock --template=admin
1189
+ ```
1190
+
1191
+ Flag disponibili: `--name` `--provider=firebase|supabase|mock|custom` `--ai-provider` `--icon-provider` `--theme` `--template=blank|admin|crm|inventory|project`
1192
+
1193
+ **5 template disponibili:**
1194
+ | Template | Pagine incluse | Uso tipico |
1195
+ |---|---|---|
1196
+ | `blank` | home | App vuota — massima libertà |
1197
+ | `admin` | home, users, roles, settings | Dashboard admin/backoffice |
1198
+ | `crm` | home, companies, contacts, deals | CRM |
1199
+ | `inventory` | home + gestione inventario | Magazzino |
1200
+ | `project` | home + gestione progetti | PM tool |
1201
+
1202
+ **Struttura generata in-place nella current directory:**
1203
+ ```
1204
+ src/
1205
+ index.tsx ← App entry
1206
+ vite-env.d.ts
1207
+ conf/
1208
+ app.ts ← providers config letta da .env (VITE_PROVIDER, VITE_AI_PROVIDER...)
1209
+ menu.ts ← MenuConfig con path, title, icon, page (layout opzionale: c'è LayoutDefault)
1210
+ data/
1211
+ mockData.ts ← dati fake per MockDataProvider
1212
+ layouts/
1213
+ Default.tsx ← layout wrapper (header + sidebar + main + footer)
1214
+ sections/
1215
+ Header.tsx / Sidebar.tsx / PageHeader.tsx / Footer.tsx ← solo componenti pubblici (SideNav, AuthButton, ActionButton, Brand, Breadcrumbs)
1216
+ pages/
1217
+ home/HomePage.tsx
1218
+ [altre pagine dal template scelto]
1219
+ styles/
1220
+ globals.css ← @import '@llmnative/react/dist/index.css' + Tailwind override
1221
+ .env ← VITE_PROVIDER, VITE_THEME, chiavi API (non committare)
1222
+ .env.example ← stessa struttura, valori vuoti (committare)
1223
+ vite.config.ts / tsconfig.json / postcss.config.js / index.html
1224
+ ```
1225
+
1226
+ **Pattern conf/app.ts** (auto-generato, leggere per capire come funziona):
1227
+ ```ts
1228
+ import type { AppProvidersConfig } from '@llmnative/react'
1229
+ import { mockData } from '../data/mockData'
1230
+ const env = import.meta.env
1231
+
1232
+ export const providers: AppProvidersConfig = {
1233
+ mock: { data: mockData },
1234
+ ai: { openaiApiKey: env.VITE_OPENAI_API_KEY ?? '' }, // AI dentro providers, non prop <App>
1235
+ services: { data: 'mock', auth: 'googleAuth' },
1236
+ }
1237
+ ```
1238
+
1239
+ Driver per `VITE_PROVIDER`: `firebase` → `firestoreDb` + `firestorage` + `firebaseAuth`; `supabase` → `supabaseDb` + `supabaseStorage` + `supabaseAuth`; `mock` → `mock` + `googleAuth`. `index.tsx` passa `LayoutDefault={Default}` ad `<App>`.
1240
+
1241
+ ---
1242
+
1243
+ ## Gotchas — pitfall frequenti
1244
+
1245
+ | Errore | Causa | Fix |
1246
+ |---|---|---|
1247
+ | `aiConfig` prop non esiste su `<App>` | La config AI va dentro `providers.ai`, NON come prop separata | `providers={{ ai: { openaiApiKey } }}` |
1248
+ | `inputType` o `Input.Number`/`Input.Email` non esistono | Il tipo HTML è la prop `type` | `<Input type="number">`, `<Input type="email">`, `<Input type="date">` |
1249
+ | `Menu context=` non esiste | La prop si chiama `menuKey` | `<Menu menuKey="main" />` |
1250
+ | `SignInButton` non esiste | Rinominato | `<AuthButton />` |
1251
+ | `firebase: { config: ... }` errato | FirebaseConfig è flat | `firebase: { apiKey, authDomain, databaseURL, ... }` |
1252
+ | `google: { oAuth2: { clientId } }` errato | GoogleProviderConfig è flat | `google: { clientId, scope }` |
1253
+ | `children` su `Grid` | Grid non accetta children | Usa `form={<Fields />}` per il form inline |
1254
+ | `recordId` su `Form` | Prop non esiste | La chiave del record viene da URL automaticamente |
1255
+ | `MenuConfig` non importabile | Era type interno | Ora esportato: `import type { MenuConfig } from '@llmnative/react'` |
1256
+ | `GridCellContext` non importabile | Mancava dall'index | Ora esportato: `import type { GridCellContext } from '@llmnative/react'` |
1257
+
1258
+ ---
1259
+
1260
+ ## Dove cercare nel codice sorgente
1261
+
1262
+ | Cosa | File |
1263
+ |---|---|
1264
+ | Form | `src/components/widgets/Form.tsx` |
1265
+ | Grid | `src/components/widgets/Grid.tsx` |
1266
+ | Prompt | `src/components/widgets/Prompt.tsx` |
1267
+ | Campi form | `src/components/ui/fields/` |
1268
+ | Blocks (Menu, Toolbar, Notifications, Dropdown…) | `src/components/blocks/` |
1269
+ | Provider data Firebase (RTDB) | `src/providers/data/firebase.ts` |
1270
+ | Provider data Firestore | `src/providers/data/firestore.ts` |
1271
+ | Provider data Supabase | `src/providers/data/supabase.ts` |
1272
+ | Provider storage Firebase | `src/providers/storage/firebase.ts` |
1273
+ | Provider storage Supabase | `src/providers/storage/supabase.ts` |
1274
+ | Provider auth Firebase | `src/providers/auth/firebase/FirebaseAuthProvider.ts` |
1275
+ | Provider auth Supabase | `src/providers/auth/supabase/` |
1276
+ | Provider auth Google | `src/providers/auth/google/` |
1277
+ | Provider auth Dropbox | `src/providers/auth/dropbox/` |
1278
+ | Provider email Gmail | `src/providers/email/google/GmailEmailProvider.ts` |
1279
+ | Provider AI definitions | `src/providers/ai/` |
1280
+ | Provider credenziali | `src/providers/credentials/` |
1281
+ | Provider session | `src/providers/ProviderSession.ts` |
1282
+ | Proxy CORS | `src/providers/proxy.ts` |
1283
+ | Motion system | `src/motion.ts` |
1284
+ | I18n | `src/I18n.tsx` |
1285
+ | Dropbox integration | `src/providers/dropbox/` |
1286
+ | Interfaccia DataProvider | `src/providers/data/DataProvider.ts` |
1287
+ | Interfaccia StorageProvider | `src/providers/storage/StorageProvider.ts` |
1288
+ | Interfaccia AuthProvider | `src/providers/auth/AuthProvider.ts` |
1289
+ | Interfaccia EmailProvider | `src/providers/email/EmailProvider.ts` |
1290
+ | Interfaccia AIProvider | `src/providers/ai/AIProvider.ts` |
1291
+ | Registry provider | `src/providers/manifest.ts` |
1292
+ | Config provider | `src/providers/ProviderConfiguration.ts` |
1293
+ | SEO / Google Trends | `src/providers/seo/google/` |
1294
+ | Sistema tema | `src/Theme.tsx` |
1295
+ | Config runtime | `src/Config.tsx` |
1296
+ | Tipi TypeScript | `src/types/` |
1297
+ | Utilities pure | `src/libs/` |