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