@llmnative/react 1.35.0 → 1.36.1

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