@preprio/toolkit 0.5.0-rc.2 → 0.5.0-rc.3

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 (50) hide show
  1. package/README.md +207 -10
  2. package/dist/astro/index.cjs +1174 -1
  3. package/dist/astro/index.d.cts +47 -1
  4. package/dist/astro/index.d.ts +47 -1
  5. package/dist/astro/index.js +1177 -1
  6. package/dist/chunk-42Z2VW7G.js +1161 -0
  7. package/dist/chunk-6WY3MWCX.js +246 -0
  8. package/dist/chunk-MDAV2FLM.js +26 -0
  9. package/dist/{chunk-FLPNN3CV.js → chunk-PP3O7RB4.js} +1370 -623
  10. package/dist/chunk-S3VT4UWM.js +75 -0
  11. package/dist/chunk-SXUDBGLZ.js +184 -0
  12. package/dist/chunk-URXSDJOU.js +356 -0
  13. package/dist/index.cjs +3108 -392
  14. package/dist/index.d.cts +238 -4
  15. package/dist/index.d.ts +238 -4
  16. package/dist/index.js +189 -149
  17. package/dist/live-preview-EADA3ZL4.js +18 -0
  18. package/dist/nextjs/components.cjs +1522 -359
  19. package/dist/nextjs/components.d.cts +1 -1
  20. package/dist/nextjs/components.d.ts +1 -1
  21. package/dist/nextjs/components.js +4 -1
  22. package/dist/nextjs/index.cjs +1065 -6
  23. package/dist/nextjs/index.d.cts +73 -1
  24. package/dist/nextjs/index.d.ts +73 -1
  25. package/dist/nextjs/index.js +1059 -7
  26. package/dist/nextjs/live-action.cjs +285 -0
  27. package/dist/nextjs/live-action.d.cts +12 -0
  28. package/dist/nextjs/live-action.d.ts +12 -0
  29. package/dist/nextjs/live-action.js +68 -0
  30. package/dist/nextjs/live.cjs +1838 -0
  31. package/dist/nextjs/live.d.cts +52 -0
  32. package/dist/nextjs/live.d.ts +52 -0
  33. package/dist/nextjs/live.js +265 -0
  34. package/dist/nuxt/index.cjs +1 -1
  35. package/dist/nuxt/index.js +1 -1
  36. package/dist/nuxt/live-preview-PTEC3GPC.js +1462 -0
  37. package/dist/nuxt/live.cjs +1662 -0
  38. package/dist/nuxt/live.d.cts +43 -0
  39. package/dist/nuxt/live.d.ts +43 -0
  40. package/dist/nuxt/live.js +94 -0
  41. package/dist/{pixel-B3oQNbZ3.d.cts → pixel-CX422dCO.d.cts} +10 -1
  42. package/dist/{pixel-B3oQNbZ3.d.ts → pixel-CX422dCO.d.ts} +10 -1
  43. package/dist/react/components.cjs +1522 -359
  44. package/dist/react/components.d.cts +9 -0
  45. package/dist/react/components.d.ts +9 -0
  46. package/dist/react/components.js +1522 -359
  47. package/dist/sveltekit/index.cjs +1 -1
  48. package/dist/sveltekit/index.js +1 -1
  49. package/package.json +12 -1
  50. package/src/astro/PreprToolbar.astro +7 -1
package/README.md CHANGED
@@ -250,6 +250,155 @@ The loader rewrites `w_` to the width Next asks for and scales `h_` alongside it
250
250
 
251
251
  See the runnable example at `examples/nextjs` for the full source of truth.
252
252
 
253
+ ### Live preview (beta)
254
+
255
+ True live preview inside the Prepr editor iframe: keystrokes patch your query
256
+ results instantly by item `_id`; saves refetch the affected queries.
257
+
258
+ **Requirements.** Live preview runs only where the Prepr middleware handles
259
+ the request with `preview: true` (`createPreprMiddleware(request, { preview })`
260
+ in `proxy.ts`). Make sure your middleware `matcher` covers every page you
261
+ preview: on a page it skips, live preview does nothing and shows no error.
262
+ Pass your preview flag as `enabled` to every live preview entry point below;
263
+ each one does nothing without it.
264
+
265
+ Live updates and click-to-edit find content by id, never by position, so
266
+ they stay correct while an editor adds, removes or reorders blocks before
267
+ saving:
268
+
269
+ - Select `_id` (and ideally `__typename`) on every model and component level
270
+ that should live-update. Items without `_id` silently stay static.
271
+ - In dynamic content fields, select `_id` on every entry type (`Text`,
272
+ `Quote`, …). `Assets` entries have no `_id` of their own: select
273
+ `items { _id }` instead.
274
+ - Render each dynamic content entry inside an element marked with
275
+ `data-prepr-edit-target="<field>.<index>"` and
276
+ `data-prepr-entry-id="<entry _id>"` (for `Assets`, the first asset's
277
+ `_id`). The index is the fallback when no id matches.
278
+ - Values without a hidden edit link (images, videos, other URLs) are made
279
+ click-to-edit with `previewAttrs({ id, field }, { enabled: isPreview })`
280
+ on the element that renders them.
281
+ - Where the page renders a linked item whose content comes from items nested
282
+ inside it (for example a personalization or a shared section referenced
283
+ from a stack), wrap it in an element with
284
+ `data-prepr-reference="<linked item _id>"`. The editor only knows the items
285
+ the open item links to directly; content inside the wrapper is outlined as
286
+ that linked item, and clicking it opens the link in the editor.
287
+
288
+ Configure once in a small client component mounted in your root layout:
289
+
290
+ ```tsx
291
+ 'use client';
292
+ import { useEffect } from 'react';
293
+ import { initLivePreview } from '@preprio/toolkit/nextjs/live';
294
+
295
+ export default function LivePreviewInit({ preview }: { preview: boolean }) {
296
+ useEffect(() => {
297
+ initLivePreview({
298
+ // Your preview flag. Without it nothing starts.
299
+ enabled: preview,
300
+ // Runs a registered query against Prepr GraphQL. `query` is whatever
301
+ // you registered (string or DocumentNode) — you own the transport.
302
+ fetcher: async (query, variables) => {
303
+ /* POST to your Prepr GraphQL endpoint, return json.data */
304
+ },
305
+ });
306
+ }, [preview]);
307
+ return null;
308
+ }
309
+ ```
310
+
311
+ Register query results in client components with `useLive`:
312
+
313
+ ```tsx
314
+ 'use client';
315
+ import { useLive } from '@preprio/toolkit/nextjs/live';
316
+
317
+ export default function PageContent({ data, slug }) {
318
+ const liveData = useLive(data, {
319
+ query: GetPageBySlugDocument,
320
+ variables: { slug },
321
+ });
322
+ // render from liveData — it re-renders on editor keystrokes and saves
323
+ }
324
+ ```
325
+
326
+ In `'use client'` files always import from `@preprio/toolkit/nextjs/live` —
327
+ the `/nextjs` barrel also exports server-only helpers (`next/headers`), which
328
+ a client module graph must not include.
329
+
330
+ Omitting `query`/`variables` degrades that registration to keystroke pushes
331
+ only. For server-component pages, mount `<PreprRefresh enabled={preview} />`
332
+ instead — it calls `router.refresh()` on every save. Don't combine
333
+ `PreprRefresh` with `useLive` registrations that pass a `query`: a save would
334
+ both refetch and refresh. `useLive` without a `query` works alongside it.
335
+
336
+ Without `enabled`, and outside the Prepr editor iframe, all of this is a
337
+ passthrough with zero overhead. The CMS editor must emit `prepr:fieldChange` (per keystroke) and
338
+ `prepr:itemChanged` (on save, with the root content item id) into the preview
339
+ iframe — `examples/editor-emulator` emulates this for local development.
340
+ Unsaved structural changes (adding/reordering components) appear after save;
341
+ typed text is live immediately.
342
+
343
+ #### Unsaved changes in server components: `normalizeQuery` (experimental, Next.js 16+)
344
+
345
+ Server components show the editor's unsaved changes when you pass their query
346
+ results through `normalizeQuery`, with whatever client you fetch with:
347
+
348
+ ```ts
349
+ import { normalizeQuery } from '@preprio/toolkit/nextjs';
350
+
351
+ const preview = process.env.VERCEL_ENV !== 'production';
352
+
353
+ const data = await fetchFromPrepr(GetPageDocument, { slug }); // any client
354
+ const page = await normalizeQuery(GetPageDocument, data, { enabled: preview });
355
+ ```
356
+
357
+ Mount `<PreprRefresh enabled={preview} />` in the root layout. While an
358
+ editor types, it sends the unsaved changes to the server and the route
359
+ re-renders with them; on save it refreshes with the stored content.
360
+
361
+ - The query (source text, a `DocumentNode`, or a typed document string) tells
362
+ the toolkit which response key holds which field. Changes land under
363
+ aliases, inside single components, on dynamic content entries, and on every
364
+ place the same item appears. Fields the query did not select are left
365
+ alone. Select `_id` on every item and component that should update.
366
+ - Changed text keeps its hidden edit link, so it stays click-to-edit.
367
+ - `useLive` data keeps the typed values across these re-renders.
368
+
369
+ **Production safety.** Pass `enabled` from the same preview flag you give the
370
+ middleware, and never `true` on a production deployment:
371
+
372
+ - With `enabled: false` (the default) the result is returned untouched and
373
+ the request is never read, so static and ISR pages stay static.
374
+ `PreprRefresh`, `initLivePreview` and `useLive` don't listen to the editor
375
+ at all.
376
+ - Next.js registers the toolkit's server action in every build that imports
377
+ `@preprio/toolkit/nextjs/live`, so anyone can call it, browsers and scripts
378
+ alike. It does nothing (no parsing, no storage, no re-render) unless the
379
+ Prepr middleware handled the request with `preview: true`. The middleware
380
+ drops `Prepr-*` headers a client sends, so this can't be forged on a page
381
+ the middleware runs for. On a page its `matcher` skips, a forged header can
382
+ at most trigger an extra render, never change content, because
383
+ `normalizeQuery` there still needs `enabled`.
384
+ - Changes only reach the re-render of the editor's own server action call.
385
+ The action stores them in the server process under a random, single-use
386
+ token and sets only that token as a cookie that expires immediately. Any
387
+ other request carrying the cookie, such as a plain or cacheable GET that
388
+ replays a token, sees nothing.
389
+ - Changes are only accepted from the Prepr editor (`https://*.prepr.io`, or
390
+ your `allowedEditorOrigins` via `initLivePreview`), never from another page
391
+ that frames your site. They are validated as hostile input: link fields
392
+ never take `javascript:`, `vbscript:` or `data:` URLs. HTML text is passed
393
+ on as typed, like rich text from the API.
394
+
395
+ On Next.js 15 and older the action does nothing and pages update on save.
396
+
397
+ For Astro and Nuxt, see their sections. The framework-free core exports,
398
+ `normalizeQuery(query, result, { log })`, `startHtmlLivePreview()` and
399
+ `readLiveLogFromRequest(request)` from `@preprio/toolkit`, cover any other
400
+ server-rendered stack.
401
+
253
402
  ## Astro
254
403
 
255
404
  **`src/middleware.ts`**
@@ -301,6 +450,34 @@ The `.astro` components ship as source, compiled by your own Astro/Vite pipeline
301
450
 
302
451
  See the runnable example at `examples/astro` for the full source of truth.
303
452
 
453
+ ### Live preview (experimental)
454
+
455
+ Show the editor's unsaved changes while they type. Pass `preview` to
456
+ `onPreprRequest` as above, and run each query result through
457
+ `normalizeQuery` with your preview flag:
458
+
459
+ ```astro
460
+ ---
461
+ import { normalizeQuery } from '@preprio/toolkit/astro';
462
+
463
+ const data = await fetchFromPrepr(GetPageDocument, { slug }); // any client
464
+ const page = normalizeQuery(GetPageDocument, data, {
465
+ enabled: preview,
466
+ locals: Astro.locals,
467
+ });
468
+ ---
469
+ ```
470
+
471
+ `PreprToolbar.astro` does the rest. Inside the Prepr editor it requests the
472
+ page again with the unsaved changes and updates only the parts of the DOM that
473
+ changed; on save it shows the stored content. Preview must render on demand
474
+ (`output: 'server'`).
475
+
476
+ Safety: the middleware only accepts changes in preview, from a same-origin
477
+ `POST` that carries the toolkit's header and a JSON body, and marks that
478
+ response `Cache-Control: private, no-store`. With `enabled: false` the result
479
+ is returned untouched. Changes are accepted only from the Prepr editor.
480
+
304
481
  ## SvelteKit
305
482
 
306
483
  **`src/hooks.server.ts`**
@@ -412,6 +589,25 @@ The `.vue` components ship as source (compiled by your own Vite/Vue pipeline) an
412
589
 
413
590
  See the runnable example at `examples/nuxt` for the full source of truth.
414
591
 
592
+ ### Live preview (experimental)
593
+
594
+ Show the editor's unsaved changes while they type, with no server round trip:
595
+
596
+ ```ts
597
+ import { useNormalizedQuery } from '@preprio/toolkit/nuxt/live';
598
+
599
+ const { data, refresh } = await useAsyncData('page', () => fetchPage(slug));
600
+ const page = useNormalizedQuery(GetPageDocument, data, {
601
+ enabled: preview, // your preview flag; nothing starts without it
602
+ onSave: refresh,
603
+ });
604
+ ```
605
+
606
+ Render from `page`. Nuxt hydrates the whole page, so every component that
607
+ shows a changed field updates. Without `enabled`, on the server and outside
608
+ the Prepr editor's preview iframe it returns the data unchanged. Changes are accepted only from
609
+ the Prepr editor.
610
+
415
611
  ## React (no framework)
416
612
 
417
613
  `@preprio/toolkit/react` carries the two components that need nothing but React — for Vite + React Router, TanStack Router, Remix SPA mode, or Create React App. Next.js users want the [Next.js section](#nextjs) instead; its `PreprToolbar` binds the App Router for you.
@@ -636,7 +832,7 @@ controller.destroy();
636
832
  | Option | Type | Description |
637
833
  | ------------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
638
834
  | `props` | `PreprToolbarProps` | From `getToolbarProps`. Optional — a headless preview has no segment list to pass. |
639
- | `options` | `PreprPreviewOptions` | `{ debug?, locale?, features?, ui?, allowedEditorOrigins?, autoClean? }`. See [Preview options](#preview-options). |
835
+ | `options` | `PreprPreviewOptions` | `{ debug?, locale?, features?, ui?, allowedEditorOrigins?, strictMode?, autoClean? }`. See [Preview options](#preview-options). |
640
836
  | `navigation` | `PreprNavigationAdapter` | How segment/variant switches navigate. Optional — omitted, the toolbar uses `window.location.assign` (a full page load). `reload` is optional too, runs after a preview-mode toggle, and defaults to `window.location.reload()`. The Next.js and SvelteKit wrappers wire all of this up for you. |
641
837
 
642
838
  `createPreprPreview` is a no-op outside a browser (no `window`/`document`) and returns a controller whose `destroy()` does nothing, so it is safe to call during SSR. Call it **once per page** — two calls start two bridges and announce the preview twice.
@@ -694,14 +890,15 @@ createPreprMiddleware(request, response, { preview });
694
890
  createPreprPreview({ props, options: { debug: true, locale: 'nl' } });
695
891
  ```
696
892
 
697
- | Option | Type | Default | Description |
698
- | ---------------------- | --------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
699
- | `debug` | `boolean` | `false` | Enable debug logging. |
700
- | `locale` | `'en' \| 'nl'` | auto-detected | UI language. Falls back to the first supported browser language, then `en`. |
701
- | `features` | `PreprFeatures` | all enabled | Which features run. See [Feature flags](#feature-flags). |
702
- | `ui` | `boolean` | `true` | Mount the visible toolbar. See [Headless preview](#headless-preview-no-toolbar-ui). |
703
- | `allowedEditorOrigins` | `string[]` | `*.prepr.io` | Exact editor origins allowed to drive this preview, for self-hosted or local editors. Replaces the wildcard. `['*']` accepts any origin — development only. |
704
- | `autoClean` | `boolean` | `true` | Strip the invisible stega characters from visible text. See [Stega auto-cleaning](#stega-auto-cleaning). |
893
+ | Option | Type | Default | Description |
894
+ | ---------------------- | ------------------------------ | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
895
+ | `debug` | `boolean` | `false` | Enable debug logging. |
896
+ | `locale` | `'en' \| 'nl' \| 'fr' \| 'de'` | auto-detected | UI language. Falls back to the first supported browser language, then `en`. Inside the Prepr editor, the editor's interface language wins. |
897
+ | `features` | `PreprFeatures` | all enabled | Which features run. See [Feature flags](#feature-flags). |
898
+ | `ui` | `boolean` | `true` | Mount the visible toolbar. See [Headless preview](#headless-preview-no-toolbar-ui). |
899
+ | `allowedEditorOrigins` | `string[]` | `*.prepr.io` | Exact editor origins allowed to drive this preview, for self-hosted or local editors. Replaces the wildcard. `['*']` accepts any origin — development only. |
900
+ | `strictMode` | `boolean` | `false` | Your preview token uses GraphQL strict mode (required fields never null). The editor then holds back new entries until their required fields are filled and never sends a cleared required field as null. Also on `PreprRefresh`, `initLivePreview` and `useNormalizedQuery`. |
901
+ | `autoClean` | `boolean` | `true` | Strip the invisible stega characters from visible text. See [Stega auto-cleaning](#stega-auto-cleaning). |
705
902
 
706
903
  `features` and `ui` are independent: `features` decides _what runs_, `ui` decides _whether the toolbar is visible_.
707
904
 
@@ -809,7 +1006,7 @@ Because the toolbar renders inside a shadow root, none of your own page CSS —
809
1006
 
810
1007
  ### Internationalization
811
1008
 
812
- The toolbar UI ships with English and Dutch. Pass `locale` explicitly, or omit it to auto-detect from the browser and fall back to `en`:
1009
+ The toolbar UI ships with English, Dutch, French and German. Pass `locale` explicitly, or omit it to auto-detect from the browser and fall back to `en`. Inside the Prepr editor's preview, the visual editor's labels follow the language the editor user has set for the CMS, falling back to `locale` when the editor sends a language the toolkit does not support:
813
1010
 
814
1011
  ```typescript
815
1012
  createPreprPreview({ props, options: { locale: 'nl' } });