@charisol/plexo-sdk 2.0.28 → 2.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +324 -0
  2. package/dist/{InlineColorPicker-BYcOgLVc.js → InlineColorPicker-Cb9p4I_m.js} +395 -114
  3. package/dist/{v1-Cz7qypQd.js → blank-Dg8GIfQP.js} +4681 -10906
  4. package/dist/brandGuide-Dd4fqVjS.js +33 -0
  5. package/dist/{client-DUSU8g5z.js → client-CWui0-3q.js} +1 -1
  6. package/dist/codeEditor-Cux0ud2j.js +205 -0
  7. package/dist/files-Bjoz1wCf.js +2182 -0
  8. package/dist/id-CR6Y8qD6.js +8 -0
  9. package/dist/index.js +12754 -13035
  10. package/dist/{brandGuide-DgoZ7spo.js → lint-CV3DmM0X.js} +78 -109
  11. package/dist/pdfImport-BOev0Pc1.js +262 -0
  12. package/dist/plexo-sdk.css +1 -1
  13. package/dist/v1-B6QkDh9R.js +6253 -0
  14. package/dist/v2/CanvasEditor.d.ts +25 -0
  15. package/dist/v2/V2Editor.d.ts +15 -20
  16. package/dist/v2/compile/build.d.ts +5 -0
  17. package/dist/v2/components/layout/TopToolbar.d.ts +7 -0
  18. package/dist/v2/components/properties/PropertiesPanel.d.ts +1 -0
  19. package/dist/v2/components/simple/SimpleCoach.d.ts +8 -0
  20. package/dist/v2/components/simple/SimpleHint.d.ts +3 -0
  21. package/dist/v2/components/simple/SimpleInspector.d.ts +3 -0
  22. package/dist/v2/components/simple/SimpleSidebar.d.ts +3 -0
  23. package/dist/v2/components/simple/SimpleTopBar.d.ts +5 -0
  24. package/dist/v2/components/simple/words.d.ts +12 -0
  25. package/dist/v2/data/blankPage.d.ts +5 -0
  26. package/dist/v2/files/aiPicture.d.ts +85 -0
  27. package/dist/v2/files/build.d.ts +49 -0
  28. package/dist/v2/files/capture.d.ts +52 -0
  29. package/dist/v2/files/convert.d.ts +24 -0
  30. package/dist/v2/files/docx.d.ts +1 -0
  31. package/dist/v2/files/engine.d.ts +2 -0
  32. package/dist/v2/files/export.d.ts +97 -0
  33. package/dist/v2/files/import.d.ts +34 -0
  34. package/dist/v2/files/index.d.ts +16 -0
  35. package/dist/v2/files/pdf.d.ts +15 -0
  36. package/dist/v2/files/pdfImport.d.ts +28 -0
  37. package/dist/v2/files/sheet.d.ts +16 -0
  38. package/dist/v2/files/text.d.ts +8 -0
  39. package/dist/v2/files/types.d.ts +96 -0
  40. package/dist/v2/files/ui/ExportDock.d.ts +11 -0
  41. package/dist/v2/files/ui/ExportMenu.d.ts +5 -0
  42. package/dist/v2/files/ui/ExportPanel.d.ts +17 -0
  43. package/dist/v2/files/ui/FileEditor.d.ts +14 -0
  44. package/dist/v2/files/ui/HtmlWorkbench.d.ts +15 -0
  45. package/dist/v2/files/ui/codeEditor.d.ts +12 -0
  46. package/dist/v2/files/ui/editors.d.ts +28 -0
  47. package/dist/v2/files/vector.d.ts +19 -0
  48. package/dist/v2/files/zip.d.ts +10 -0
  49. package/dist/v2/host/HostContext.d.ts +20 -3
  50. package/dist/v2/index.d.ts +7 -2
  51. package/dist/v2-compile.js +20 -19
  52. package/dist/v2-files.js +3 -0
  53. package/dist/v2-strata.js +2 -2
  54. package/dist/v2.js +5434 -2713
  55. package/package.json +18 -3
package/README.md CHANGED
@@ -14,6 +14,7 @@
14
14
  - 🤖 **AI content generation** — edit a single element, edit the whole layout, or generate a fresh layout from a prompt, with support for OpenAI, Gemini, and Claude
15
15
  - 🔒 **Server-proxied AI, no exposed keys** — your provider API key is never sent to or stored in the browser; every AI request is authenticated with your Plexo API key and resolved against your account's server-side configuration
16
16
  - 💬 **Claude-Code-style AI feedback** — a loading bubble followed by a one-line summary of what changed, for both the per-element editor and the layout prompt bar
17
+ - 📁 **File editor & export** — open or create designs, HTML (with a code editor), documents, text, Markdown, spreadsheets, PDFs and pictures; export to PNG, JPG, PDF, SVG, DOCX, XLSX and more, including a Figma-style export from the landing-page canvas (see [File editor & export](#file-editor--export-v2))
17
18
  - 🖼️ **Stock image search** — Unsplash, Pexels, Pixabay integrations
18
19
  - 🎨 **Design token system** — Strata token support for consistent brand theming
19
20
  - 📦 **ESM-only, pure client-side component** — nothing to self-host; the SDK talks directly to Plexo's hosted API for AI/publish/compile using your Plexo API key
@@ -262,6 +263,29 @@ The editor's own colours (not your visitors' page) follow three props. Pass any
262
263
  <V2Editor theme={{ accent: '#96F02E', background: '#000000', text: '#ffffff' }} />
263
264
  ```
264
265
 
266
+ ### A simpler screen for beginners — `experience`
267
+
268
+ ```tsx
269
+ <V2Editor experience="beginner" pages={pages} onChange={setPages} onSave={save} onPublish={publish} />
270
+ ```
271
+
272
+ `experience` is `'beginner'` or `'pro'` (the default). `'beginner'` is not a trimmed toolbar, it is a different, much simpler screen
273
+ meant for someone who has never used a design tool:
274
+
275
+ - **Your page is a list.** The left side shows the page as its sections, top to bottom. Click one, then Up / Down / Copy / Delete, or
276
+ "Add a section" to pick a ready-made one. No layers, no pixels, no free dragging.
277
+ - **Plain words on the right.** Click a section and you get boxes to type in, a layout picker and a few looks. Click a heading, text, button
278
+ or picture and you get only what applies: type new words, bigger/smaller, left/middle/right, colour, where a button goes, replace a picture.
279
+ - **Guidance built in.** A five-step first-time guide (comes back with the Help button), and a one-line tip that follows what is selected.
280
+ - **A filled-in start.** With no `pages`, it opens to a short finished page (menu, main message, highlights, footer) instead of an empty canvas.
281
+ `starterPages()` is exported if you want the same page yourself.
282
+ - Everything else is the same editor: `onSave`, `onPublish`, `pageSource`, `onAskSol`, `pageSettings`, `shell`, `headerLeft`/`headerRight`,
283
+ `theme`, `mode="email"` all work, and the saved pages are identical, so an owner can switch between `'beginner'` and `'pro'` at any time.
284
+
285
+ Anything you put in `headerRight` is shown exactly as you styled it. If you would like plain links and buttons there to match the editor's own buttons, opt in with `headerSlotStyle="editor"` (add `data-primary` to one for the highlighted look), or put the `plexo-header-button` class on a single button.
286
+
287
+ Plexo's own dashboard passes the owner's chosen experience level, so beginners get this screen and pros get the full editor.
288
+
265
289
  ### Emails
266
290
 
267
291
  The same editor designs emails: `<V2Editor mode="email" />`. In email mode only what every email app can draw is offered: text, buttons, pictures, dividers, spacing and rows of columns (which stack on a phone), in ready-made email sections (header, main message, text, highlights, call to action, picture, footer). There is no free placement, grid, shadow, animation or script, and Preview shows the email as it will arrive. Write the finished email with the compiler (tables with inline styles, plus a plain-text version):
@@ -319,6 +343,305 @@ The previous V2 (`V2Canvas`, `useCanvasStore`, `compilePageToReact(nodes, pageOr
319
343
 
320
344
  ---
321
345
 
346
+ ## File editor & export (v2)
347
+
348
+ Everything in this section ships in `@charisol/plexo-sdk/v2` (the editor) and `@charisol/plexo-sdk/v2/files` (the same engine without any UI).
349
+
350
+ ### Quick start
351
+
352
+ ```bash
353
+ npm install @charisol/plexo-sdk # one package; the PDF reader and code editor are included and load only when needed
354
+ ```
355
+
356
+ ```tsx
357
+ 'use client'; // the editor runs in the browser (in Next.js, load it with next/dynamic and ssr: false)
358
+ import { V2Editor } from '@charisol/plexo-sdk/v2';
359
+ import '@charisol/plexo-sdk/dist/plexo-sdk.css';
360
+
361
+ export default function Files() {
362
+ return (
363
+ <div style={{ height: '100vh' }}> {/* the editor fills its container, so give the parent a height */}
364
+ <V2Editor mode="file" /> {/* that's it: start screen, editors, preview and Export all work with no other props */}
365
+ </div>
366
+ );
367
+ }
368
+ ```
369
+
370
+ With no other props, people can create or open files and **Export** them (downloads). Add what your app needs:
371
+
372
+ | You want to… | Pass |
373
+ |---|---|
374
+ | Get the finished file back in your app (upload it, store it) | `files={{ onSaveFile }}` → shows **Save** |
375
+ | Choose what they make yourself, or open a given file | `files={{ kind }}` or `files={{ file }}` (see "Using your own screens") |
376
+ | Store pictures the editor makes on your storage instead of embedding them | `onUpload={(file) => url}` |
377
+ | Turn pictures into editable designs with AI | nothing inside the Plexo dashboard; elsewhere `files={{ imageAi }}` |
378
+ | Match your brand | `theme={{ accent, background, text }}` |
379
+ | Only export from the landing-page / email canvas | nothing — it's already there (section 1) |
380
+
381
+ Things that are **not** needed: an API key (only for the AI inside the Plexo dashboard), a server, or any build configuration.
382
+
383
+ ### 1. Export from the landing-page / email canvas
384
+
385
+ Nothing to set up — every `V2Editor` has it. Click an element (or several, or nothing for the whole page) and use the **Export** section under the right-hand panel (shortcut ⇧⌘E / Ctrl+Shift+E), or the Export button in the top bar.
386
+
387
+ | You get | How |
388
+ |---|---|
389
+ | PNG, JPG, PDF, SVG | One or more rows of *size + format* (1x–4x), then **Export**. Several rows download as one zip. |
390
+ | Just part of a page | The selection is cut out like Figma does: one element, or several together as one picture. Nothing selected = the whole page at the current screen size (desktop / tablet / phone). |
391
+ | PDF | One long page, or split into A4 pages. |
392
+ | SVG | **Editable shapes and text** (default; opens in Figma / Illustrator) or **Exact look** (the browser's own drawing wrapped in an SVG). Rotation, gradients (linear, radial, conic), shadows (several, inset, text), gradient text, filters, tiled backgrounds, form fields and list bullets are all drawn. Embedded videos/maps from other sites appear as a grey play-mark box, and frosted-glass blur isn't possible in SVG; the owner is told when either is present. |
393
+ | Emails | Exported whole, as they will be sent. |
394
+
395
+ Hide the top-bar button with `features={{ exportMenu: false }}` (the panel stays). Pictures hosted on another site must allow copying (CORS) to be included; the owner sees a plain-words warning when one can't be.
396
+
397
+ ### 2. The file editor — `mode="file"` and `mode="hybrid"`
398
+
399
+ Pass a flag and the editor opens as a **file editor** instead of the page builder, the same way `mode="email"` switches it to emails:
400
+
401
+ ```tsx
402
+ import { V2Editor } from '@charisol/plexo-sdk/v2';
403
+
404
+ <V2Editor
405
+ mode="file" // or "hybrid"
406
+ apiKey="workspace-internal" // inside the Plexo dashboard — turns the built-in AI on (see below)
407
+ onUpload={uploadImage} // optional: where pictures made by the editor are stored (else they're embedded)
408
+ files={{
409
+ file, // optional: a File/Blob to open, or a FileSource you saved before
410
+ kind: 'design', // optional: start a new file of this kind
411
+ onSaveFile: async (r) => { // optional: shows Save; called with the finished file
412
+ await upload(r.blob, r.filename); // r.blob is in the format the person chose
413
+ await db.save(r.source); // r.source reopens it later: files={{ file: r.source }}
414
+ },
415
+ onClose: () => router.back(), // optional: shows a Back button
416
+ }}
417
+ />
418
+ ```
419
+
420
+ - **`mode="file"`** — Design (a single-page visual canvas), **HTML** (a web page as code), Document, Text, Markdown and Sheet.
421
+ - **`mode="hybrid"`** — the same, plus Email, and the design view keeps your full page tooling (page list, branding, library; pass `pageSource`, `features` etc. as usual).
422
+ - With no `file` or `kind` the person sees a start screen: pick a type, or drop in a file.
423
+
424
+ **What the person can do**
425
+
426
+ - **Switch type** with the toggle at the top: the content is converted (and Undo is offered). **Text** is plain text only: no design tools, no preview.
427
+ - **HTML files** open exactly as written (nothing stripped or rewritten) in a code editor with syntax colours for HTML, CSS and JavaScript, auto-closing tags, indent, folding and search, with the page live beside it (computer / tablet / phone width). Paste a whole page or a fragment, edit it, then Export or Save as PNG, PDF, SVG and more; what's exported is what the preview shows (scripts don't run). The editor engine (CodeMirror) loads only when an HTML file is opened. A design's HTML tab has **Edit this as HTML** to turn it into a code file.
428
+ - **Switch view**: Visual / HTML / Preview. Preview is the picture an export would make. A Document's HTML is editable.
429
+ - **Open** PDF, pictures (PNG, JPG, WebP, GIF, SVG), `.docx`, `.xlsx`, `.csv`, `.html` (as code), `.md`, `.txt`.
430
+ - **Export** (downloads) and **Save** (sends to your app via `onSaveFile`) in: PNG, JPG, PDF, SVG, HTML, TXT, MD, DOCX, CSV, XLSX. The formats offered depend on the type; limit them with `files.saveFormats`.
431
+ - **Spreadsheets** have a grid with formulas (`=SUM(A1:A5)`, `+ − × ÷`, `AVERAGE MIN MAX COUNT ROUND ABS SQRT`), paste from Excel/Sheets, and `.xlsx` / `.csv` export.
432
+
433
+ **What a saved file looks like**
434
+
435
+ ```ts
436
+ // What onSaveFile receives
437
+ interface FileSaveResult {
438
+ kind: FileKind; // 'design' | 'email' | 'html' | 'document' | 'text' | 'markdown' | 'sheet'
439
+ name: string; // without extension
440
+ format: ExportFormat; // what they chose: 'png' | 'jpeg' | 'pdf' | 'svg' | 'html' | 'txt' | 'md' | 'docx' | 'csv' | 'xlsx'
441
+ filename: string; // "Quarterly report.pdf"
442
+ blob: Blob; // the finished file: upload this
443
+ source: FileSource; // the editable version: store this, reopen it later with files={{ file: source }}
444
+ warnings: string[]; // plain-words notes for the person (e.g. a picture that couldn't be included)
445
+ }
446
+
447
+ // FileSource is plain JSON, safe to keep in your database
448
+ type FileSource =
449
+ | { kind: 'design' | 'email'; name: string; content: PageDefinition[] } // pages from the visual canvas
450
+ | { kind: 'html' | 'document' | 'text' | 'markdown'; name: string; content: string }
451
+ | { kind: 'sheet'; name: string; content: string[][] }; // rows of cells ("=SUM(A1:A3)" for formulas)
452
+ ```
453
+
454
+ **`files` options**
455
+
456
+ | Option | What it does |
457
+ |---|---|
458
+ | `file` | `File` / `Blob` to open (type detected from its name), or a `FileSource` returned earlier by `onSaveFile`. |
459
+ | `fileName` | Name to use when `file` is an unnamed Blob. |
460
+ | `kind` | Start a new file of `'design' \| 'email' \| 'html' \| 'document' \| 'text' \| 'markdown' \| 'sheet'`. |
461
+ | `kinds` | Which types to offer. |
462
+ | `saveFormats` | Formats under "Save as". |
463
+ | `onSaveFile(result)` | Save button. `result` = `{ kind, name, format, filename, blob, source, warnings }`. |
464
+ | `onClose` | Back button. |
465
+ | `onConvertImage`, `imageAi`, `aiConversion` | AI picture conversion — see below. |
466
+
467
+ ### Using your own screens (you choose, we edit)
468
+
469
+ You don't have to use our "What would you like to make?" screen. Decide in your own UI, then hand the editor the result; it handles everything after that (the editing screens, preview, export, save) in your colours.
470
+
471
+ ```tsx
472
+ import { V2Editor, type V2EditorHandle } from '@charisol/plexo-sdk/v2';
473
+ const ref = useRef<V2EditorHandle>(null);
474
+
475
+ // 1. Your chooser decided: open straight into it. No start screen, and no type switch if the type shouldn't change.
476
+ <V2Editor ref={ref} mode="file" theme={{ accent: '#7c3aed', background: '#ffffff', text: '#111827' }}
477
+ files={{ kind: 'html', showTypeSwitcher: false, onSaveFile: save }} />
478
+
479
+ // 2. Or hand it a file the person picked or you stored (File/Blob of any supported type, or a FileSource).
480
+ <V2Editor mode="file" files={{ file: pickedFile, showTypeSwitcher: false }} />
481
+
482
+ // 3. Or keep one mounted editor and drive it: switching is also just a prop change (`files.kind` / `files.file`).
483
+ await ref.current.open(file); // open a file, replacing what is open
484
+ ref.current.create('sheet', 'Budget'); // a new empty file
485
+ const source = ref.current.getSource(); // store this; reopen later with files={{ file: source }}
486
+ const png = await ref.current.exportAs('png', { scale: 2 }); // { blob, filename, warnings }, nothing saved anywhere
487
+ await ref.current.save('pdf'); // through your onSaveFile
488
+ ```
489
+
490
+ | Option | What it does |
491
+ |---|---|
492
+ | `files.startScreen: false` | Never show our chooser. With nothing given, a new file of the first of `kinds` opens. |
493
+ | `files.kind` / `files.file` | What to open. Followed as they change, not read once. |
494
+ | `files.showTypeSwitcher: false` | Hide the Design / HTML / Document… switch. |
495
+ | `files.kinds` | Which types exist (also limits the switch). |
496
+ | `headerLeft` / `headerRight` | Your own controls in the editor's top bar. |
497
+ | `theme` | `{ accent, background, text }`: every shade (panels, borders, hover, muted text) is mixed from these, and a light background works as well as a dark one. |
498
+
499
+ ### 3. Opening a PDF for editing
500
+
501
+ A PDF opens as a multi-page design (up to 30 pages): each page is drawn as a picture with its words wiped out, and the words are placed on top as **real, movable, editable text** (position, size, colour, bold/italic and font family are carried over). **Export → PDF** writes every page back. A **scanned** PDF has no words to read, so each page goes through the AI picture conversion below (up to 10 pages), or is placed as a picture when AI isn't available. Password-protected PDFs are refused with a plain message. The PDF reader (`pdfjs-dist`) is loaded only when a PDF is opened. Your bundler must be able to resolve it (it is a dependency of this package; with Next.js nothing extra is needed).
502
+
503
+ ### 4. Turning a picture into an editable design (AI)
504
+
505
+ When someone opens a picture (or a scanned PDF page), a vision model describes its parts — text, boxes, photos with positions — and the editor rebuilds them as real elements. Photos are cut out of the original, never redrawn. The person can **Skip** while it works and **Undo** afterwards to get the original picture on the canvas.
506
+
507
+ - **Inside the Plexo dashboard** (`apiKey="workspace-internal"`): built in. It calls `POST /api/v1/ai/image-to-design` on plexo-web, which uses the account's AI credits/keys. Nothing to pass.
508
+ - **Elsewhere**, give the editor a way to reach a vision model — the simplest is `imageAi`, which only sends the picture and returns the model's JSON:
509
+
510
+ ```tsx
511
+ import { IMAGE_TO_DESIGN_PROMPT } from '@charisol/plexo-sdk/v2/files';
512
+
513
+ <V2Editor
514
+ mode="file"
515
+ files={{
516
+ imageAi: async ({ image, width, height }) => {
517
+ // `image` is a JPEG data URL, at most 1600px. Send it to YOUR server, which calls a vision model with
518
+ // IMAGE_TO_DESIGN_PROMPT (replace {width}/{height}) as the system prompt, and return the parsed JSON.
519
+ const res = await fetch('/my-api/rebuild', { method: 'POST', body: JSON.stringify({ image, width, height }) });
520
+ return (await res.json()).spec;
521
+ },
522
+ }}
523
+ />
524
+ ```
525
+
526
+ The SDK validates the answer (colours, sizes and counts are checked; anything unusable is dropped), so the model's output is never trusted. For full control pass `onConvertImage(input) => Promise<PageDefinition[]>` instead.
527
+ - **Without AI** a picture is placed on the canvas as one image the person can crop, resize and put text over. Turn the AI off with `aiConversion: false`.
528
+
529
+ ### 5. Use the engine without the editor
530
+
531
+ ```ts
532
+ import { exportSource, downloadResult, openFile, convertContent } from '@charisol/plexo-sdk/v2/files';
533
+
534
+ // Export a landing page, or just one element of it
535
+ const png = await exportSource({ kind: 'design', page, nodeIds: [heroId] }, { format: 'png', scale: 2 });
536
+ downloadResult(png); // { blob, filename, mime, warnings }
537
+
538
+ // Every page of a multi-page design as one PDF
539
+ await exportSource({ kind: 'design', page: pages[0], pages }, { format: 'pdf' });
540
+
541
+ // Documents, text, Markdown and spreadsheets
542
+ await exportSource({ kind: 'html', name: 'Notes', body: '<h1>Hi</h1>' }, { format: 'docx' });
543
+ // A whole web page, drawn exactly as the browser shows it
544
+ await exportSource({ kind: 'rawhtml', name: 'Landing', html: pastedHtml, width: 1200 }, { format: 'png' });
545
+ await exportSource({ kind: 'sheet', name: 'Budget', grid: [['a', 'b'], ['1', '=A2*2']] }, { format: 'xlsx' });
546
+
547
+ // Open any supported file
548
+ const opened = await openFile(file); // → source | image | pdf
549
+ ```
550
+
551
+ `ExportOptions`: `format`, `scale` (1–4), `background` (`null` = see-through), `quality`, `svgMode` (`'vector' \| 'exact'`), `pdfPaging` (`'single' \| 'a4'`), `filename`. Everything here runs **in the browser** (pages are drawn with the browser's own engine) and returns a plain `Blob`.
552
+
553
+ ### 6. A complete host integration, end to end
554
+
555
+ [`examples/host-integration`](examples/host-integration) is a small, runnable host app ("Acme Studio") with its own backend. It is tested end to end in a real browser: the host's own chooser, create, edit, Save to the host's storage, list, download, reopen from the saved source, re-save without duplicating, and picture upload / AI. Run it:
556
+
557
+ ```bash
558
+ npm install && npm run build # once
559
+ ANTHROPIC_API_KEY=sk-ant-… npm run example # key is optional: without it the picture rebuild shows a plain "not set up" message
560
+ # web app on http://localhost:5181, backend on :5180
561
+ ```
562
+
563
+ What the host builds is four small pieces. Everything else (the editors, preview, export, formats, theming) is the SDK's.
564
+
565
+ **1. Its own screens, then hand over to the editor**
566
+
567
+ ```tsx
568
+ // "My files" + a chooser are YOUR screens. When someone picks, mount the editor with the answer:
569
+ <V2Editor
570
+ mode="file"
571
+ theme={{ accent: '#7c3aed', background: '#ffffff', text: '#1f2937' }} // your brand: three colours
572
+ onUpload={uploadPicture} // 2. your storage for pictures the editor makes
573
+ files={{
574
+ kind: 'html', // new file of this type… or file: savedSource / aFile to open one
575
+ startScreen: false, // you have your own chooser
576
+ showTypeSwitcher: false, // the type was chosen on your screen
577
+ imageAi: describePicture, // 3. your AI
578
+ onSaveFile: (r) => save(r, existingId), // 4. your save
579
+ defaultSaveFormat: 'png', // optional: keep saving in the format this file was saved in
580
+ onClose: () => showMyFiles(), // Back button
581
+ }}
582
+ />
583
+ ```
584
+
585
+ **2. Storage for pictures the editor makes** (cut-out photos, PDF pages). Return where you stored each:
586
+
587
+ ```ts
588
+ const uploadPicture = async (file: File) => {
589
+ const body = new FormData(); body.append('file', file);
590
+ const res = await fetch('/api/upload', { method: 'POST', body });
591
+ if (!res.ok) throw new Error('The picture could not be uploaded.'); // shown to the person
592
+ return (await res.json()).url;
593
+ };
594
+ // Without onUpload, small pictures are embedded in the design instead (fine for trying it out).
595
+ ```
596
+
597
+ **3. AI for pictures** (optional). The editor sends a picture; your server asks a vision model with the prompt the SDK ships and returns its JSON:
598
+
599
+ ```ts
600
+ // client
601
+ const describePicture = async ({ image, width, height, signal }) => {
602
+ const res = await fetch('/api/rebuild-picture', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image, width, height }), signal });
603
+ const out = await res.json();
604
+ if (!res.ok) throw new Error(out.error); // plain words: the person sees this, and their picture is placed on the canvas instead
605
+ return out.spec;
606
+ };
607
+
608
+ // server (Node; any language works: it only needs to call a vision model)
609
+ import { IMAGE_TO_DESIGN_PROMPT } from '@charisol/plexo-sdk/v2/files';
610
+ const r = await fetch('https://api.anthropic.com/v1/messages', {
611
+ method: 'POST',
612
+ headers: { 'content-type': 'application/json', 'x-api-key': process.env.ANTHROPIC_API_KEY, 'anthropic-version': '2023-06-01' },
613
+ body: JSON.stringify({
614
+ model: 'claude-sonnet-5-5', max_tokens: 8000,
615
+ system: IMAGE_TO_DESIGN_PROMPT.replaceAll('{width}', String(width)).replaceAll('{height}', String(height)),
616
+ messages: [{ role: 'user', content: [{ type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data } }, { type: 'text', text: 'Describe this picture as the JSON object.' }] }],
617
+ }),
618
+ });
619
+ // …parse the text of the reply as JSON and return it as { spec }. The SDK validates it; you don't have to.
620
+ ```
621
+
622
+ **4. Save** — `result.blob` is the finished file in the format they chose; `result.source` is the editable version. Store both:
623
+
624
+ ```ts
625
+ async function save(result: FileSaveResult, existingId?: string) {
626
+ const body = new FormData();
627
+ body.append('file', result.blob, result.filename); // upload this (S3, disk, …)
628
+ body.append('source', JSON.stringify(result.source)); // keep this in your database
629
+ body.append('meta', JSON.stringify({ id: existingId, name: result.name, kind: result.kind, format: result.format }));
630
+ const res = await fetch('/api/files', { method: 'POST', body });
631
+ if (!res.ok) throw new Error('Saving failed. Please try again.'); // shown to the person; they can retry
632
+ }
633
+
634
+ // Reopen later: fetch the stored source and pass it back
635
+ <V2Editor mode="file" files={{ file: storedSource, defaultSaveFormat: row.format, showTypeSwitcher: false, onSaveFile: … }} />
636
+ ```
637
+
638
+ A few things worth knowing when you build the real thing:
639
+ - **Errors are for people.** Whatever `uploadPicture`, `imageAi` or `onSaveFile` throws is shown as its message, so write them as plain sentences. A failed AI call never blocks anything: the picture is placed on the canvas and they carry on.
640
+ - **Large files:** `result.blob` can be several MB (a 2x PNG of a long page, a many-page PDF). Send it as multipart (as above) or upload straight to storage with a presigned URL; don't base64 it into JSON.
641
+ - **Pictures hosted elsewhere** must allow cross-origin reading (CORS) to be included in PNG/PDF exports; the person gets a warning when one can't be. Pictures you store with `onUpload` are fine if served from your own origin.
642
+ - **Reopening is lossless** because `source` is the editor's own data (page JSON, HTML, text, or cells), not the exported file. Don't reopen a saved PNG/PDF to edit it: store `source` next to it.
643
+ - **Security:** treat what you load as untrusted if people can share files: HTML files run in a sandbox with scripts off, and the AI answer is validated by the SDK before it is used.
644
+
322
645
  ## Framework Notes
323
646
 
324
647
  ### Vite
@@ -363,6 +686,7 @@ const PlexoBuilder = lazy(() =>
363
686
  - Every row/column/element wrapper now carries a `data-plexo-node-type="row"|"column"|"element"` attribute alongside its existing `id` (already the node's stable JSON id).
364
687
 
365
688
  ### Unreleased
689
+ - **File editor & export (v2):** `mode="file"` / `"hybrid"`; Figma-style PNG / JPG / PDF / SVG export from the canvas; HTML files with a code editor and live preview; PDF editing; AI picture-to-design; host-driven screens (`files.kind`, `files.file`, `startScreen`, `showTypeSwitcher`, a ref); new entry `@charisol/plexo-sdk/v2/files`; new compile option `nodeIds`; new `features.exportMenu`. New dependencies: `pdfjs-dist` and CodeMirror (both loaded only when used).
366
690
  - **Breaking:** Removed the `aiApiKey` prop. AI generation now runs server-side — your provider key is configured once against your Plexo account (encrypted at rest) instead of being passed to the browser on every render.
367
691
  - **Breaking:** `TemplateJSON.body.aiConfig` no longer accepts `apiKey`/`provider` — only `useAi`/`tier` remain, for the same reason (a template's JSON is loaded client-side, so it can't hold a secret safely).
368
692
  - `aiProvider` is now display/label-only; the effective provider comes from your account configuration, not this prop.