@nocode-factory/sanity-kit 2.46.1 → 2.47.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/CodeEmbedFrame-DWsj6Z8T.js +88 -0
- package/dist/CodeEmbedFrame-DWsj6Z8T.js.map +1 -0
- package/dist/index.d.ts +46 -3
- package/dist/index.js +158 -3
- package/dist/index.js.map +1 -1
- package/dist/web.d.ts +35 -1
- package/dist/web.js +2 -1
- package/dist/web.js.map +1 -1
- package/package.json +6 -1
- package/src/form/CodeEditorInput.tsx +75 -0
- package/src/form/CodeEmbedInput.tsx +31 -0
- package/src/form/codeEmbedType.ts +66 -0
- package/src/index.ts +5 -0
- package/src/version.ts +1 -1
- package/src/web/CodeEmbedFrame.tsx +104 -0
- package/src/web/index.ts +2 -0
package/dist/web.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CSSProperties } from "react";
|
|
1
2
|
interface PreviewBannerProps {
|
|
2
3
|
/** Le site affiche-t-il actuellement les brouillons ? */
|
|
3
4
|
isDraft: boolean;
|
|
@@ -53,5 +54,38 @@ export declare function createPreviewRefresh(refresh: () => void, delay?: number
|
|
|
53
54
|
* ```
|
|
54
55
|
*/
|
|
55
56
|
export declare function useNcfPreviewRefresh(delay?: number): (payload: PreviewRefreshPayload) => false | Promise<void>;
|
|
56
|
-
|
|
57
|
+
/** Contenu d'un bloc « Code embed » : trois langages, tous optionnels. */
|
|
58
|
+
interface CodeEmbedValue {
|
|
59
|
+
html?: string;
|
|
60
|
+
css?: string;
|
|
61
|
+
js?: string;
|
|
62
|
+
}
|
|
63
|
+
interface CodeEmbedFrameProps extends CodeEmbedValue {
|
|
64
|
+
/** Titre de l'iframe (accessibilité). */
|
|
65
|
+
title?: string;
|
|
66
|
+
className?: string;
|
|
67
|
+
style?: CSSProperties;
|
|
68
|
+
/** Hauteur de départ, avant la première mesure (évite le saut au chargement). */
|
|
69
|
+
minHeight?: number;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Assemble le document isolé injecté dans l'iframe.
|
|
73
|
+
*
|
|
74
|
+
* Un petit script mesure la hauteur réelle du contenu et la transmet au parent
|
|
75
|
+
* (`postMessage`) : le parent ajuste la hauteur de l'iframe, il n'y a donc jamais
|
|
76
|
+
* de barre de défilement interne. Le `token` relie chaque message à son iframe.
|
|
77
|
+
*/
|
|
78
|
+
export declare function buildCodeEmbedDoc({ html, css, js }: CodeEmbedValue, token: string): string;
|
|
79
|
+
/**
|
|
80
|
+
* Rend un bloc HTML / CSS / JS arbitraire dans une iframe **sandboxée**.
|
|
81
|
+
*
|
|
82
|
+
* Le code tourne dans une origine isolée (pas de `allow-same-origin`) : il ne
|
|
83
|
+
* peut lire ni les cookies ni le stockage du site hôte, mais le JS reste actif.
|
|
84
|
+
* La hauteur s'ajuste automatiquement au contenu.
|
|
85
|
+
*
|
|
86
|
+
* Même composant côté Studio (aperçu dans le formulaire) et côté site, pour que
|
|
87
|
+
* ce qui est édité soit exactement ce qui s'affiche.
|
|
88
|
+
*/
|
|
89
|
+
export declare function NcfCodeEmbed(props: CodeEmbedFrameProps): React.JSX.Element | null;
|
|
90
|
+
export type { CodeEmbedFrameProps, CodeEmbedValue, PreviewBannerProps, PreviewRefreshPayload };
|
|
57
91
|
//# sourceMappingURL=web.d.ts.map
|
package/dist/web.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
'use client'
|
|
2
|
+
import { n as buildCodeEmbedDoc, t as NcfCodeEmbed } from "./CodeEmbedFrame-DWsj6Z8T.js";
|
|
2
3
|
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
|
3
4
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
4
5
|
import { usePathname, useRouter } from "next/navigation.js";
|
|
@@ -203,6 +204,6 @@ function useNcfPreviewRefresh(delay = 300) {
|
|
|
203
204
|
let router = useRouter(), handler = useMemo(() => createPreviewRefresh(() => router.refresh(), delay), [router, delay]);
|
|
204
205
|
return useCallback((payload) => handler(payload), [handler]);
|
|
205
206
|
}
|
|
206
|
-
export { NcfPreviewBanner, createPreviewRefresh, useNcfPreviewRefresh };
|
|
207
|
+
export { NcfCodeEmbed, NcfPreviewBanner, buildCodeEmbedDoc, createPreviewRefresh, useNcfPreviewRefresh };
|
|
207
208
|
|
|
208
209
|
//# sourceMappingURL=web.js.map
|
package/dist/web.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web.js","names":[],"sources":["../src/web/PreviewBanner.tsx","../src/web/previewRefresh.ts"],"sourcesContent":["'use client'\n\nimport {usePathname} from 'next/navigation'\nimport {useEffect, useState, useSyncExternalStore, type CSSProperties} from 'react'\n\n/** Mêmes noms que le garde (`previewGrant.ts`), sans importer de code serveur. */\nconst GRANT_PARAM = 'ncf_preview'\nconst GRANT_COOKIE = 'ncf_preview_grant'\n\nconst noSubscribe = () => () => {}\nfunction readGrant(): string | null {\n const match = document.cookie.match(new RegExp(`(?:^|; )${GRANT_COOKIE}=([^;]*)`))\n return match?.[1] ? decodeURIComponent(match[1]) : null\n}\n\n/**\n * Page affichée DANS le Studio (Presentation l'encastre dans un iframe) : le\n * Studio a déjà sa propre bascule brouillons / en ligne, le bandeau ferait doublon\n * et masquerait le bas de la page. Faux au rendu serveur (bandeau rendu), vrai\n * dès l'hydratation dans un iframe (bandeau retiré).\n */\nconst readEmbedded = () => {\n try {\n return window.self !== window.top\n } catch {\n // Accès refusé au parent : on est forcément encastré.\n return true\n }\n}\n\n/** Adresse courante avec la clé de préversion (partageable telle quelle). */\nfunction shareableUrl(grant: string): string {\n const url = new URL(window.location.href)\n url.searchParams.set(GRANT_PARAM, grant)\n return url.toString()\n}\n\nexport interface PreviewBannerProps {\n /** Le site affiche-t-il actuellement les brouillons ? */\n isDraft: boolean\n /** Chemin de la route de bascule. Défaut : `/api/draft-mode/toggle`. */\n togglePath?: string\n /** Libellé de l'environnement. Défaut : « Préversion ». */\n label?: string\n position?: 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'\n}\n\n/**\n * Bandeau des environnements de test : il dit où l'on est, et laisse choisir\n * ce qu'on regarde.\n *\n * Sur une préversion, la question du relecteur est toujours la même :\n * « qu'est-ce qui sortira quand je publierai ? ». Y répondre demande de voir\n * les brouillons sur le vrai site, pas dans un aperçu encastré.\n *\n * Les styles sont en ligne, délibérément. Des classes utilitaires obligeraient\n * chaque site à déclarer ce paquet dans ses globs de scan — une dépendance\n * invisible dont l'oubli ne se verrait qu'à l'exécution, par un bandeau nu.\n *\n * Rendu hors production seulement : c'est à l'appelant de s'en assurer, avec\n * `isPreviewSite()`.\n */\nexport function NcfPreviewBanner(props: PreviewBannerProps) {\n const {isDraft, togglePath = '/api/draft-mode/toggle', label = 'Preview'} = props\n const pathname = usePathname()\n // Clé de préversion mémorisée par le garde (absente avec une session Presentation).\n const grant = useSyncExternalStore(noSubscribe, readGrant, () => null)\n const [copied, setCopied] = useState(false)\n const embedded = useSyncExternalStore(noSubscribe, readEmbedded, () => false)\n\n // Après une navigation côté client, Next affiche l'URL du lien, sans la clé : on\n // la remet, pour que l'adresse copiée depuis la barre ouvre la préversion chez\n // n'importe qui (un client, sans compte).\n useEffect(() => {\n if (!grant) return\n const url = new URL(window.location.href)\n if (url.searchParams.get(GRANT_PARAM) === grant) return\n url.searchParams.set(GRANT_PARAM, grant)\n window.history.replaceState(window.history.state, '', url.toString())\n }, [grant, pathname])\n\n // Retour de bascule sur la même page, clé comprise.\n const backPath = grant ? `${pathname || '/'}?${GRANT_PARAM}=${encodeURIComponent(grant)}` : pathname || '/'\n const back = encodeURIComponent(backPath)\n\n const share = async () => {\n if (!grant) return\n try {\n await navigator.clipboard.writeText(shareableUrl(grant))\n setCopied(true)\n window.setTimeout(() => setCopied(false), 2000)\n } catch {\n // Presse-papiers refusé : l'adresse de la barre contient déjà la clé.\n }\n }\n\n const href = (enable: boolean) => `${togglePath}?enable=${enable}&redirect=${back}`\n\n // Dans le Studio : rien (voir readEmbedded).\n if (embedded) return null\n\n return (\n // data-ncf-preview-banner : repère technique du test prod / préprod\n // (check-environments), indépendant de la langue des libellés.\n <div data-ncf-preview-banner=\"\" style={{...anchor(props.position ?? 'bottom-left'), zIndex: 2147483000}}>\n <div style={shell}>\n <span style={{display: 'inline-flex', alignItems: 'center', gap: 6, fontWeight: 500}}>\n {/* Pastille pleine plutôt qu'un caractère décoratif : elle se lit à\n toutes les tailles et ne dépend d'aucune police. */}\n <span aria-hidden style={dot} />\n {label}\n </span>\n\n <span aria-hidden style={divider} />\n <span style={{opacity: 0.75}}>Data</span>\n\n <span role=\"group\" aria-label=\"Displayed data\" style={{display: 'inline-flex', gap: 2}}>\n <a\n href={href(true)}\n title=\"What will go live after publishing\"\n aria-current={isDraft ? 'true' : undefined}\n style={isDraft ? segmentOn : segmentOff}\n >\n Drafts\n </a>\n <a\n href={href(false)}\n title=\"What the public sees today\"\n aria-current={isDraft ? undefined : 'true'}\n style={isDraft ? segmentOff : segmentOn}\n >\n Published\n </a>\n </span>\n\n {grant && (\n <>\n <span aria-hidden style={divider} />\n <button type=\"button\" onClick={share} title=\"Copy the address of this page, including the preview key\" style={shareButton}>\n {copied ? 'Link copied' : 'Copy link'}\n </button>\n </>\n )}\n </div>\n </div>\n )\n}\n\nconst anchor = (position: NonNullable<PreviewBannerProps['position']>): CSSProperties => ({\n position: 'fixed',\n ...(position.startsWith('bottom') ? {bottom: 16} : {top: 16}),\n ...(position.endsWith('left') ? {left: 16} : {right: 16}),\n})\n\nconst shell: CSSProperties = {\n display: 'flex',\n alignItems: 'center',\n gap: 10,\n padding: '6px 12px',\n borderRadius: 999,\n // Ambre : la couleur des environnements de test, assez saturée pour ne pas\n // se confondre avec le site, assez sobre pour ne pas le masquer.\n background: '#fef3c7',\n color: '#451a03',\n border: '1px solid #fcd34d',\n boxShadow: '0 4px 16px rgba(0,0,0,0.14)',\n font: '500 12px/1 ui-sans-serif, system-ui, -apple-system, Segoe UI, sans-serif',\n}\n\nconst dot: CSSProperties = {\n width: 7,\n height: 7,\n borderRadius: '50%',\n background: '#d97706',\n flex: 'none',\n}\n\nconst divider: CSSProperties = {width: 1, height: 14, background: '#00000022'}\n\nconst segmentBase: CSSProperties = {\n padding: '4px 10px',\n borderRadius: 999,\n textDecoration: 'none',\n fontSize: 12,\n lineHeight: 1,\n whiteSpace: 'nowrap',\n}\n\nconst segmentOn: CSSProperties = {...segmentBase, background: '#451a03', color: '#fffbeb'}\nconst segmentOff: CSSProperties = {...segmentBase, color: '#451a03', opacity: 0.7}\n\nconst shareButton: CSSProperties = {\n ...segmentBase,\n border: 'none',\n background: 'transparent',\n color: '#451a03',\n cursor: 'pointer',\n font: 'inherit',\n textDecoration: 'underline',\n textUnderlineOffset: 3,\n}\n","import {useCallback, useMemo} from 'react'\nimport {useRouter} from 'next/navigation'\n\n/** Ce que l'édition visuelle de Sanity passe à `refresh` (next-sanity <VisualEditing/>). */\nexport interface PreviewRefreshPayload {\n source: 'manual' | 'mutation' | string\n}\n\n/**\n * Rafraîchissement de l'aperçu (Presentation) à CHAQUE modification faite dans le\n * Studio, regroupée : une rafale de frappes = un seul rafraîchissement.\n *\n * Sans lui, <VisualEditing/> de next-sanity ignore les modifications du Studio et\n * compte sur le signal live, qui ne part pas toujours : un champ remis à sa valeur\n * par défaut (vidé, la pastille bleue) ne s'affichait qu'après un rechargement.\n * Pur et testable : `refresh` et les minuteries sont injectés.\n */\nexport function createPreviewRefresh(\n refresh: () => void,\n delay = 300,\n timers: {set: (fn: () => void, ms: number) => unknown; clear: (id: unknown) => void} = {\n set: (fn, ms) => setTimeout(fn, ms),\n clear: (id) => clearTimeout(id as ReturnType<typeof setTimeout>),\n },\n): (payload: PreviewRefreshPayload) => false | Promise<void> {\n let pending: unknown = null\n let waiting: (() => void)[] = []\n const flush = () => {\n pending = null\n refresh()\n const done = waiting\n waiting = []\n // Laisse le temps au rendu serveur d'arriver avant d'éteindre l'indicateur.\n timers.set(() => done.forEach((resolve) => resolve()), 1000)\n }\n return (payload) => {\n if (payload.source !== 'manual' && payload.source !== 'mutation') return false\n if (pending !== null) timers.clear(pending)\n pending = timers.set(flush, payload.source === 'manual' ? 0 : delay)\n return new Promise<void>((resolve) => waiting.push(resolve))\n }\n}\n\n/**\n * À passer à <VisualEditing refresh={...}/> (next-sanity), dans un composant client :\n *\n * ```tsx\n * 'use client'\n * import {VisualEditing} from 'next-sanity/visual-editing'\n * import {useNcfPreviewRefresh} from '@nocode-factory/sanity-kit/web'\n * export function PreviewEditing() {\n * return <VisualEditing refresh={useNcfPreviewRefresh()} />\n * }\n * ```\n */\nexport function useNcfPreviewRefresh(delay = 300): (payload: PreviewRefreshPayload) => false | Promise<void> {\n const router = useRouter()\n const handler = useMemo(() => createPreviewRefresh(() => router.refresh(), delay), [router, delay])\n return useCallback((payload: PreviewRefreshPayload) => handler(payload), [handler])\n}\n"],"mappings":";;;;AAMA,MAAM,cAAc,eAGd,0BAA0B,CAAC;AACjC,SAAS,YAA2B;CAClC,IAAM,QAAQ,SAAS,OAAO,MAAM,gBAAI,OAAO,mCAAiC,CAAC;CACjF,OAAO,QAAQ,KAAK,mBAAmB,MAAM,EAAE,IAAI;AACrD;;;;;;;AAQA,MAAM,qBAAqB;CACzB,IAAI;EACF,OAAO,OAAO,SAAS,OAAO;CAChC,QAAQ;EAEN,OAAO;CACT;AACF;;AAGA,SAAS,aAAa,OAAuB;CAC3C,IAAM,MAAM,IAAI,IAAI,OAAO,SAAS,IAAI;CAExC,OADA,IAAI,aAAa,IAAI,aAAa,KAAK,GAChC,IAAI,SAAS;AACtB;;;;;;;;;;;;;;;;AA2BA,SAAgB,iBAAiB,OAA2B;CAC1D,IAAM,EAAC,SAAS,aAAa,0BAA0B,QAAQ,cAAa,OACtE,WAAW,YAAY,GAEvB,QAAQ,qBAAqB,aAAa,iBAAiB,IAAI,GAC/D,CAAC,QAAQ,aAAa,SAAS,EAAK,GACpC,WAAW,qBAAqB,aAAa,oBAAo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qBAAqB;AACvB;;;;;;;;;;ACvLA,SAAgB,qBACd,SACA,QAAQ,KACR,SAAuF;CACrF,MAAM,IAAI,OAAO,WAAW,IAAI,EAAE;CAClC,QAAQ,OAAO,aAAa,EAAmC;AACjE,GAC2D;CAC3D,IAAI,UAAmB,MACnB,UAA0B,CAAC,GACzB,cAAc;EAElB,AADA,UAAU,MACV,QAAQ;EACR,IAAM,OAAO;EAGb,AAFA,UAAU,CAAC,GAEX,OAAO,UAAU,KAAK,SAAS,YAAY,QAAQ,CAAC,GAAG,GAAI;CAC7D;CACA,QAAQ,YACF,QAAQ,WAAW,YAAY,QAAQ,WAAW,aAAmB,MACrE,YAAY,QAAM,OAAO,MAAM,OAAO,GAC1C,UAAU,OAAO,IAAI,OAAO,QAAQ,WAAW,WAAW,IAAI,KAAK,GAC5D,IAAI,SAAe,YAAY,QAAQ,KAAK,OAAO,CAAC;AAE/D;;;;;;;;;;;;;AAcA,SAAgB,qBAAqB,QAAQ,KAAgE;CAC3G,IAAM,SAAS,UAAU,GACnB,UAAU,cAAc,2BAA2B,OAAO,QAAQ,GAAG,KAAK,GAAG,CAAC,QAAQ,KAAK,CAAC;CAClG,OAAO,aAAa,YAAmC,QAAQ,OAAO,GAAG,CAAC,OAAO,CAAC;AACpF"}
|
|
1
|
+
{"version":3,"file":"web.js","names":[],"sources":["../src/web/PreviewBanner.tsx","../src/web/previewRefresh.ts"],"sourcesContent":["'use client'\n\nimport {usePathname} from 'next/navigation'\nimport {useEffect, useState, useSyncExternalStore, type CSSProperties} from 'react'\n\n/** Mêmes noms que le garde (`previewGrant.ts`), sans importer de code serveur. */\nconst GRANT_PARAM = 'ncf_preview'\nconst GRANT_COOKIE = 'ncf_preview_grant'\n\nconst noSubscribe = () => () => {}\nfunction readGrant(): string | null {\n const match = document.cookie.match(new RegExp(`(?:^|; )${GRANT_COOKIE}=([^;]*)`))\n return match?.[1] ? decodeURIComponent(match[1]) : null\n}\n\n/**\n * Page affichée DANS le Studio (Presentation l'encastre dans un iframe) : le\n * Studio a déjà sa propre bascule brouillons / en ligne, le bandeau ferait doublon\n * et masquerait le bas de la page. Faux au rendu serveur (bandeau rendu), vrai\n * dès l'hydratation dans un iframe (bandeau retiré).\n */\nconst readEmbedded = () => {\n try {\n return window.self !== window.top\n } catch {\n // Accès refusé au parent : on est forcément encastré.\n return true\n }\n}\n\n/** Adresse courante avec la clé de préversion (partageable telle quelle). */\nfunction shareableUrl(grant: string): string {\n const url = new URL(window.location.href)\n url.searchParams.set(GRANT_PARAM, grant)\n return url.toString()\n}\n\nexport interface PreviewBannerProps {\n /** Le site affiche-t-il actuellement les brouillons ? */\n isDraft: boolean\n /** Chemin de la route de bascule. Défaut : `/api/draft-mode/toggle`. */\n togglePath?: string\n /** Libellé de l'environnement. Défaut : « Préversion ». */\n label?: string\n position?: 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'\n}\n\n/**\n * Bandeau des environnements de test : il dit où l'on est, et laisse choisir\n * ce qu'on regarde.\n *\n * Sur une préversion, la question du relecteur est toujours la même :\n * « qu'est-ce qui sortira quand je publierai ? ». Y répondre demande de voir\n * les brouillons sur le vrai site, pas dans un aperçu encastré.\n *\n * Les styles sont en ligne, délibérément. Des classes utilitaires obligeraient\n * chaque site à déclarer ce paquet dans ses globs de scan — une dépendance\n * invisible dont l'oubli ne se verrait qu'à l'exécution, par un bandeau nu.\n *\n * Rendu hors production seulement : c'est à l'appelant de s'en assurer, avec\n * `isPreviewSite()`.\n */\nexport function NcfPreviewBanner(props: PreviewBannerProps) {\n const {isDraft, togglePath = '/api/draft-mode/toggle', label = 'Preview'} = props\n const pathname = usePathname()\n // Clé de préversion mémorisée par le garde (absente avec une session Presentation).\n const grant = useSyncExternalStore(noSubscribe, readGrant, () => null)\n const [copied, setCopied] = useState(false)\n const embedded = useSyncExternalStore(noSubscribe, readEmbedded, () => false)\n\n // Après une navigation côté client, Next affiche l'URL du lien, sans la clé : on\n // la remet, pour que l'adresse copiée depuis la barre ouvre la préversion chez\n // n'importe qui (un client, sans compte).\n useEffect(() => {\n if (!grant) return\n const url = new URL(window.location.href)\n if (url.searchParams.get(GRANT_PARAM) === grant) return\n url.searchParams.set(GRANT_PARAM, grant)\n window.history.replaceState(window.history.state, '', url.toString())\n }, [grant, pathname])\n\n // Retour de bascule sur la même page, clé comprise.\n const backPath = grant ? `${pathname || '/'}?${GRANT_PARAM}=${encodeURIComponent(grant)}` : pathname || '/'\n const back = encodeURIComponent(backPath)\n\n const share = async () => {\n if (!grant) return\n try {\n await navigator.clipboard.writeText(shareableUrl(grant))\n setCopied(true)\n window.setTimeout(() => setCopied(false), 2000)\n } catch {\n // Presse-papiers refusé : l'adresse de la barre contient déjà la clé.\n }\n }\n\n const href = (enable: boolean) => `${togglePath}?enable=${enable}&redirect=${back}`\n\n // Dans le Studio : rien (voir readEmbedded).\n if (embedded) return null\n\n return (\n // data-ncf-preview-banner : repère technique du test prod / préprod\n // (check-environments), indépendant de la langue des libellés.\n <div data-ncf-preview-banner=\"\" style={{...anchor(props.position ?? 'bottom-left'), zIndex: 2147483000}}>\n <div style={shell}>\n <span style={{display: 'inline-flex', alignItems: 'center', gap: 6, fontWeight: 500}}>\n {/* Pastille pleine plutôt qu'un caractère décoratif : elle se lit à\n toutes les tailles et ne dépend d'aucune police. */}\n <span aria-hidden style={dot} />\n {label}\n </span>\n\n <span aria-hidden style={divider} />\n <span style={{opacity: 0.75}}>Data</span>\n\n <span role=\"group\" aria-label=\"Displayed data\" style={{display: 'inline-flex', gap: 2}}>\n <a\n href={href(true)}\n title=\"What will go live after publishing\"\n aria-current={isDraft ? 'true' : undefined}\n style={isDraft ? segmentOn : segmentOff}\n >\n Drafts\n </a>\n <a\n href={href(false)}\n title=\"What the public sees today\"\n aria-current={isDraft ? undefined : 'true'}\n style={isDraft ? segmentOff : segmentOn}\n >\n Published\n </a>\n </span>\n\n {grant && (\n <>\n <span aria-hidden style={divider} />\n <button type=\"button\" onClick={share} title=\"Copy the address of this page, including the preview key\" style={shareButton}>\n {copied ? 'Link copied' : 'Copy link'}\n </button>\n </>\n )}\n </div>\n </div>\n )\n}\n\nconst anchor = (position: NonNullable<PreviewBannerProps['position']>): CSSProperties => ({\n position: 'fixed',\n ...(position.startsWith('bottom') ? {bottom: 16} : {top: 16}),\n ...(position.endsWith('left') ? {left: 16} : {right: 16}),\n})\n\nconst shell: CSSProperties = {\n display: 'flex',\n alignItems: 'center',\n gap: 10,\n padding: '6px 12px',\n borderRadius: 999,\n // Ambre : la couleur des environnements de test, assez saturée pour ne pas\n // se confondre avec le site, assez sobre pour ne pas le masquer.\n background: '#fef3c7',\n color: '#451a03',\n border: '1px solid #fcd34d',\n boxShadow: '0 4px 16px rgba(0,0,0,0.14)',\n font: '500 12px/1 ui-sans-serif, system-ui, -apple-system, Segoe UI, sans-serif',\n}\n\nconst dot: CSSProperties = {\n width: 7,\n height: 7,\n borderRadius: '50%',\n background: '#d97706',\n flex: 'none',\n}\n\nconst divider: CSSProperties = {width: 1, height: 14, background: '#00000022'}\n\nconst segmentBase: CSSProperties = {\n padding: '4px 10px',\n borderRadius: 999,\n textDecoration: 'none',\n fontSize: 12,\n lineHeight: 1,\n whiteSpace: 'nowrap',\n}\n\nconst segmentOn: CSSProperties = {...segmentBase, background: '#451a03', color: '#fffbeb'}\nconst segmentOff: CSSProperties = {...segmentBase, color: '#451a03', opacity: 0.7}\n\nconst shareButton: CSSProperties = {\n ...segmentBase,\n border: 'none',\n background: 'transparent',\n color: '#451a03',\n cursor: 'pointer',\n font: 'inherit',\n textDecoration: 'underline',\n textUnderlineOffset: 3,\n}\n","import {useCallback, useMemo} from 'react'\nimport {useRouter} from 'next/navigation'\n\n/** Ce que l'édition visuelle de Sanity passe à `refresh` (next-sanity <VisualEditing/>). */\nexport interface PreviewRefreshPayload {\n source: 'manual' | 'mutation' | string\n}\n\n/**\n * Rafraîchissement de l'aperçu (Presentation) à CHAQUE modification faite dans le\n * Studio, regroupée : une rafale de frappes = un seul rafraîchissement.\n *\n * Sans lui, <VisualEditing/> de next-sanity ignore les modifications du Studio et\n * compte sur le signal live, qui ne part pas toujours : un champ remis à sa valeur\n * par défaut (vidé, la pastille bleue) ne s'affichait qu'après un rechargement.\n * Pur et testable : `refresh` et les minuteries sont injectés.\n */\nexport function createPreviewRefresh(\n refresh: () => void,\n delay = 300,\n timers: {set: (fn: () => void, ms: number) => unknown; clear: (id: unknown) => void} = {\n set: (fn, ms) => setTimeout(fn, ms),\n clear: (id) => clearTimeout(id as ReturnType<typeof setTimeout>),\n },\n): (payload: PreviewRefreshPayload) => false | Promise<void> {\n let pending: unknown = null\n let waiting: (() => void)[] = []\n const flush = () => {\n pending = null\n refresh()\n const done = waiting\n waiting = []\n // Laisse le temps au rendu serveur d'arriver avant d'éteindre l'indicateur.\n timers.set(() => done.forEach((resolve) => resolve()), 1000)\n }\n return (payload) => {\n if (payload.source !== 'manual' && payload.source !== 'mutation') return false\n if (pending !== null) timers.clear(pending)\n pending = timers.set(flush, payload.source === 'manual' ? 0 : delay)\n return new Promise<void>((resolve) => waiting.push(resolve))\n }\n}\n\n/**\n * À passer à <VisualEditing refresh={...}/> (next-sanity), dans un composant client :\n *\n * ```tsx\n * 'use client'\n * import {VisualEditing} from 'next-sanity/visual-editing'\n * import {useNcfPreviewRefresh} from '@nocode-factory/sanity-kit/web'\n * export function PreviewEditing() {\n * return <VisualEditing refresh={useNcfPreviewRefresh()} />\n * }\n * ```\n */\nexport function useNcfPreviewRefresh(delay = 300): (payload: PreviewRefreshPayload) => false | Promise<void> {\n const router = useRouter()\n const handler = useMemo(() => createPreviewRefresh(() => router.refresh(), delay), [router, delay])\n return useCallback((payload: PreviewRefreshPayload) => handler(payload), [handler])\n}\n"],"mappings":";;;;;AAMA,MAAM,cAAc,eAGd,0BAA0B,CAAC;AACjC,SAAS,YAA2B;CAClC,IAAM,QAAQ,SAAS,OAAO,MAAM,gBAAI,OAAO,mCAAiC,CAAC;CACjF,OAAO,QAAQ,KAAK,mBAAmB,MAAM,EAAE,IAAI;A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,OAAO,GAAG,CAAC,OAAO,CAAC;AACpF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nocode-factory/sanity-kit",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.47.0",
|
|
4
4
|
"description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"private": false,
|
|
@@ -51,9 +51,14 @@
|
|
|
51
51
|
"version": "node scripts/sync-version.mjs && git add src/version.ts"
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
|
+
"@codemirror/lang-css": "^6.3.1",
|
|
55
|
+
"@codemirror/lang-html": "^6.4.12",
|
|
56
|
+
"@codemirror/lang-javascript": "^6.2.5",
|
|
57
|
+
"@codemirror/theme-one-dark": "^6.1.3",
|
|
54
58
|
"@sanity/client": "^7.27.0",
|
|
55
59
|
"@sanity/icons": "^5.2.2",
|
|
56
60
|
"@sanity/ui": "^4.2.0",
|
|
61
|
+
"@uiw/react-codemirror": "^4.25.12",
|
|
57
62
|
"@vercel/stega": "^1.1.0",
|
|
58
63
|
"@xyflow/react": "12.11.6",
|
|
59
64
|
"elkjs": "0.12.0"
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import {useCallback} from 'react'
|
|
2
|
+
import {set, unset, type TextInputProps} from 'sanity'
|
|
3
|
+
import {Card} from '@sanity/ui'
|
|
4
|
+
import CodeMirror from '@uiw/react-codemirror'
|
|
5
|
+
import {oneDark} from '@codemirror/theme-one-dark'
|
|
6
|
+
import {html as htmlLang} from '@codemirror/lang-html'
|
|
7
|
+
import {css as cssLang} from '@codemirror/lang-css'
|
|
8
|
+
import {javascript as jsLang} from '@codemirror/lang-javascript'
|
|
9
|
+
|
|
10
|
+
/** Langage de coloration ; lu dans `options.language` du champ. */
|
|
11
|
+
export type CodeLanguage = 'html' | 'css' | 'js'
|
|
12
|
+
|
|
13
|
+
function extensionsFor(language: CodeLanguage | undefined) {
|
|
14
|
+
if (language === 'css') return [cssLang()]
|
|
15
|
+
if (language === 'js') return [jsLang()]
|
|
16
|
+
// HTML par défaut : le plus courant, et il colore aussi le `<style>`/`<script>` inline.
|
|
17
|
+
return [htmlLang()]
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Éditeur de code sombre (CodeMirror, thème One Dark) pour un champ texte.
|
|
22
|
+
*
|
|
23
|
+
* Interface « type éditeur de code » demandée par le marketing : coloration
|
|
24
|
+
* syntaxique, numéros de ligne, fond sombre. Le langage est figé par
|
|
25
|
+
* {@link codeEditorInput} au moment de câbler le champ.
|
|
26
|
+
*/
|
|
27
|
+
function CodeEditor(props: TextInputProps, language: CodeLanguage): React.JSX.Element {
|
|
28
|
+
const {value = '', onChange, readOnly, elementProps} = props
|
|
29
|
+
|
|
30
|
+
const handleChange = useCallback(
|
|
31
|
+
(next: string) => {
|
|
32
|
+
onChange(next ? set(next) : unset())
|
|
33
|
+
},
|
|
34
|
+
[onChange],
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
return (
|
|
38
|
+
<Card radius={2} overflow="hidden" border id={elementProps.id}>
|
|
39
|
+
<CodeMirror
|
|
40
|
+
value={value}
|
|
41
|
+
theme={oneDark}
|
|
42
|
+
editable={!readOnly}
|
|
43
|
+
readOnly={readOnly}
|
|
44
|
+
extensions={extensionsFor(language)}
|
|
45
|
+
onChange={handleChange}
|
|
46
|
+
onFocus={elementProps.onFocus}
|
|
47
|
+
onBlur={elementProps.onBlur}
|
|
48
|
+
basicSetup={{
|
|
49
|
+
lineNumbers: true,
|
|
50
|
+
foldGutter: false,
|
|
51
|
+
highlightActiveLine: !readOnly,
|
|
52
|
+
autocompletion: false,
|
|
53
|
+
}}
|
|
54
|
+
minHeight="140px"
|
|
55
|
+
maxHeight="520px"
|
|
56
|
+
style={{fontSize: 13}}
|
|
57
|
+
/>
|
|
58
|
+
</Card>
|
|
59
|
+
)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Fabrique l'input d'un champ de code pour un langage donné. À poser sur un
|
|
64
|
+
* champ `text` : `components: {input: codeEditorInput('css')}`.
|
|
65
|
+
*/
|
|
66
|
+
export function codeEditorInput(language: CodeLanguage) {
|
|
67
|
+
function CodeEditorInput(props: TextInputProps): React.JSX.Element {
|
|
68
|
+
return CodeEditor(props, language)
|
|
69
|
+
}
|
|
70
|
+
CodeEditorInput.displayName = `CodeEditorInput(${language})`
|
|
71
|
+
return CodeEditorInput
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Input HTML prêt à l'emploi (le plus courant). */
|
|
75
|
+
export const CodeEditorInput = codeEditorInput('html')
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {type ObjectInputProps} from 'sanity'
|
|
2
|
+
import {Card, Stack, Text} from '@sanity/ui'
|
|
3
|
+
import {NcfCodeEmbed, type CodeEmbedValue} from '../web/CodeEmbedFrame'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Formulaire d'un bloc « Code embed » : les trois éditeurs de code, suivis d'un
|
|
7
|
+
* **aperçu live** rendu dans la même iframe sandboxée que le site.
|
|
8
|
+
*
|
|
9
|
+
* Le marketing voit immédiatement le résultat (une `div` stylée en CSS
|
|
10
|
+
* s'affiche vraiment), sans quitter le Studio ni publier.
|
|
11
|
+
*/
|
|
12
|
+
export function CodeEmbedInput(props: ObjectInputProps): React.JSX.Element {
|
|
13
|
+
const value = (props.value ?? {}) as CodeEmbedValue
|
|
14
|
+
const hasContent = Boolean(value.html || value.css || value.js)
|
|
15
|
+
|
|
16
|
+
return (
|
|
17
|
+
<Stack gap={4}>
|
|
18
|
+
{props.renderDefault(props)}
|
|
19
|
+
{hasContent ? (
|
|
20
|
+
<Stack gap={2}>
|
|
21
|
+
<Text size={1} muted weight="semibold">
|
|
22
|
+
Aperçu
|
|
23
|
+
</Text>
|
|
24
|
+
<Card border radius={2} overflow="hidden" tone="transparent">
|
|
25
|
+
<NcfCodeEmbed html={value.html} css={value.css} js={value.js} minHeight={60} />
|
|
26
|
+
</Card>
|
|
27
|
+
</Stack>
|
|
28
|
+
) : null}
|
|
29
|
+
</Stack>
|
|
30
|
+
)
|
|
31
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import {defineField, defineType, type ObjectDefinition} from 'sanity'
|
|
2
|
+
import {CodeBlockIcon} from '@sanity/icons'
|
|
3
|
+
import {codeEditorInput} from './CodeEditorInput'
|
|
4
|
+
import {CodeEmbedInput} from './CodeEmbedInput'
|
|
5
|
+
|
|
6
|
+
export interface CodeEmbedTypeOptions {
|
|
7
|
+
/** Nom du type (défaut `codeEmbed`). */
|
|
8
|
+
name?: string
|
|
9
|
+
/** Titre affiché (défaut `Code embed`). */
|
|
10
|
+
title?: string
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Type d'objet « Code embed » : HTML, CSS et JS libres, éditables dans une
|
|
15
|
+
* interface sombre à coloration syntaxique, rendus dans une iframe sandboxée
|
|
16
|
+
* (aperçu live dans le Studio, même rendu sur le site via {@link NcfCodeEmbed}).
|
|
17
|
+
*
|
|
18
|
+
* Réutilisable partout où un objet est accepté : section de page, article de
|
|
19
|
+
* blog (`articleContent`), texte riche (`blockContent`).
|
|
20
|
+
*
|
|
21
|
+
* ```ts
|
|
22
|
+
* import {defineCodeEmbedType} from '@nocode-factory/sanity-kit'
|
|
23
|
+
* export const codeEmbed = defineCodeEmbedType()
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export function defineCodeEmbedType(options: CodeEmbedTypeOptions = {}): ObjectDefinition {
|
|
27
|
+
const {name = 'codeEmbed', title = 'Code embed'} = options
|
|
28
|
+
|
|
29
|
+
return defineType({
|
|
30
|
+
name,
|
|
31
|
+
title,
|
|
32
|
+
type: 'object',
|
|
33
|
+
icon: CodeBlockIcon,
|
|
34
|
+
components: {input: CodeEmbedInput},
|
|
35
|
+
fields: [
|
|
36
|
+
defineField({
|
|
37
|
+
name: 'html',
|
|
38
|
+
title: 'HTML',
|
|
39
|
+
type: 'text',
|
|
40
|
+
rows: 8,
|
|
41
|
+
components: {input: codeEditorInput('html')},
|
|
42
|
+
}),
|
|
43
|
+
defineField({
|
|
44
|
+
name: 'css',
|
|
45
|
+
title: 'CSS',
|
|
46
|
+
type: 'text',
|
|
47
|
+
rows: 6,
|
|
48
|
+
components: {input: codeEditorInput('css')},
|
|
49
|
+
}),
|
|
50
|
+
defineField({
|
|
51
|
+
name: 'js',
|
|
52
|
+
title: 'JavaScript',
|
|
53
|
+
type: 'text',
|
|
54
|
+
rows: 6,
|
|
55
|
+
components: {input: codeEditorInput('js')},
|
|
56
|
+
}),
|
|
57
|
+
],
|
|
58
|
+
preview: {
|
|
59
|
+
select: {html: 'html', css: 'css', js: 'js'},
|
|
60
|
+
prepare({html, css, js}) {
|
|
61
|
+
const langs = [html && 'HTML', css && 'CSS', js && 'JS'].filter(Boolean).join(' · ')
|
|
62
|
+
return {title: 'Code embed', subtitle: langs || 'Vide'}
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
}) as ObjectDefinition
|
|
66
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -291,6 +291,11 @@ export {ncfPresentationComponents} from './tools/presentation/PagesNavigator'
|
|
|
291
291
|
export {NcfPreviewLauncher, createPreviewLauncher} from './tools/navbar/PreviewLauncher'
|
|
292
292
|
export {NcfKitUpdate} from './tools/navbar/KitUpdate'
|
|
293
293
|
export {HelpTextStyle} from './ui/HelpTextStyle'
|
|
294
|
+
export {defineCodeEmbedType} from './form/codeEmbedType'
|
|
295
|
+
export type {CodeEmbedTypeOptions} from './form/codeEmbedType'
|
|
296
|
+
export {CodeEditorInput, codeEditorInput} from './form/CodeEditorInput'
|
|
297
|
+
export type {CodeLanguage} from './form/CodeEditorInput'
|
|
298
|
+
export {CodeEmbedInput} from './form/CodeEmbedInput'
|
|
294
299
|
export {useKitUpdate} from './hooks/useKitUpdate'
|
|
295
300
|
export type {KitUpdate} from './hooks/useKitUpdate'
|
|
296
301
|
export {compareVersions, isPrerelease} from './lib/version'
|
package/src/version.ts
CHANGED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
|
|
3
|
+
import {useEffect, useId, useMemo, useRef, useState, type CSSProperties} from 'react'
|
|
4
|
+
|
|
5
|
+
/** Contenu d'un bloc « Code embed » : trois langages, tous optionnels. */
|
|
6
|
+
export interface CodeEmbedValue {
|
|
7
|
+
html?: string
|
|
8
|
+
css?: string
|
|
9
|
+
js?: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface CodeEmbedFrameProps extends CodeEmbedValue {
|
|
13
|
+
/** Titre de l'iframe (accessibilité). */
|
|
14
|
+
title?: string
|
|
15
|
+
className?: string
|
|
16
|
+
style?: CSSProperties
|
|
17
|
+
/** Hauteur de départ, avant la première mesure (évite le saut au chargement). */
|
|
18
|
+
minHeight?: number
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Assemble le document isolé injecté dans l'iframe.
|
|
23
|
+
*
|
|
24
|
+
* Un petit script mesure la hauteur réelle du contenu et la transmet au parent
|
|
25
|
+
* (`postMessage`) : le parent ajuste la hauteur de l'iframe, il n'y a donc jamais
|
|
26
|
+
* de barre de défilement interne. Le `token` relie chaque message à son iframe.
|
|
27
|
+
*/
|
|
28
|
+
export function buildCodeEmbedDoc({html = '', css = '', js = ''}: CodeEmbedValue, token: string): string {
|
|
29
|
+
return `<!doctype html>
|
|
30
|
+
<html>
|
|
31
|
+
<head>
|
|
32
|
+
<meta charset="utf-8">
|
|
33
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
34
|
+
<style>
|
|
35
|
+
html,body{margin:0;padding:0}
|
|
36
|
+
${css}
|
|
37
|
+
</style>
|
|
38
|
+
</head>
|
|
39
|
+
<body>
|
|
40
|
+
${html}
|
|
41
|
+
${js ? `<script>\n${js}\n</script>` : ''}
|
|
42
|
+
<script>
|
|
43
|
+
(function(){
|
|
44
|
+
var token=${JSON.stringify(token)};
|
|
45
|
+
function post(){
|
|
46
|
+
try{
|
|
47
|
+
var h=Math.ceil(document.documentElement.getBoundingClientRect().height);
|
|
48
|
+
parent.postMessage({ncfCodeEmbed:token,height:h},'*');
|
|
49
|
+
}catch(e){}
|
|
50
|
+
}
|
|
51
|
+
if(typeof ResizeObserver!=='undefined'){new ResizeObserver(post).observe(document.body);}
|
|
52
|
+
window.addEventListener('load',post);
|
|
53
|
+
post();
|
|
54
|
+
})();
|
|
55
|
+
</script>
|
|
56
|
+
</body>
|
|
57
|
+
</html>`
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Rend un bloc HTML / CSS / JS arbitraire dans une iframe **sandboxée**.
|
|
62
|
+
*
|
|
63
|
+
* Le code tourne dans une origine isolée (pas de `allow-same-origin`) : il ne
|
|
64
|
+
* peut lire ni les cookies ni le stockage du site hôte, mais le JS reste actif.
|
|
65
|
+
* La hauteur s'ajuste automatiquement au contenu.
|
|
66
|
+
*
|
|
67
|
+
* Même composant côté Studio (aperçu dans le formulaire) et côté site, pour que
|
|
68
|
+
* ce qui est édité soit exactement ce qui s'affiche.
|
|
69
|
+
*/
|
|
70
|
+
export function NcfCodeEmbed(props: CodeEmbedFrameProps): React.JSX.Element | null {
|
|
71
|
+
const {html, css, js, title, className, style, minHeight = 0} = props
|
|
72
|
+
const token = useId()
|
|
73
|
+
const srcDoc = useMemo(() => buildCodeEmbedDoc({html, css, js}, token), [html, css, js, token])
|
|
74
|
+
const ref = useRef<HTMLIFrameElement>(null)
|
|
75
|
+
const [height, setHeight] = useState(minHeight)
|
|
76
|
+
|
|
77
|
+
useEffect(() => {
|
|
78
|
+
function onMessage(event: MessageEvent) {
|
|
79
|
+
const data = event.data as {ncfCodeEmbed?: string; height?: number} | null
|
|
80
|
+
if (!data || data.ncfCodeEmbed !== token) return
|
|
81
|
+
const next = Number(data.height)
|
|
82
|
+
if (Number.isFinite(next) && next > 0) setHeight(next)
|
|
83
|
+
}
|
|
84
|
+
window.addEventListener('message', onMessage)
|
|
85
|
+
return () => window.removeEventListener('message', onMessage)
|
|
86
|
+
}, [token])
|
|
87
|
+
|
|
88
|
+
if (!html && !css && !js) return null
|
|
89
|
+
|
|
90
|
+
return (
|
|
91
|
+
<iframe
|
|
92
|
+
ref={ref}
|
|
93
|
+
title={title || 'Code embed'}
|
|
94
|
+
srcDoc={srcDoc}
|
|
95
|
+
// Pas de `allow-same-origin` : l'embed ne peut pas lire les cookies ni le
|
|
96
|
+
// stockage du site. `allow-scripts` garde le JS actif ; la navigation du
|
|
97
|
+
// haut n'est permise que sur un clic de l'utilisateur.
|
|
98
|
+
sandbox="allow-scripts allow-popups allow-forms allow-top-navigation-by-user-activation allow-modals"
|
|
99
|
+
loading="lazy"
|
|
100
|
+
className={className}
|
|
101
|
+
style={{display: 'block', width: '100%', border: 0, height: height ? `${height}px` : undefined, ...style}}
|
|
102
|
+
/>
|
|
103
|
+
)
|
|
104
|
+
}
|
package/src/web/index.ts
CHANGED
|
@@ -15,3 +15,5 @@ export {NcfPreviewBanner} from './PreviewBanner'
|
|
|
15
15
|
export type {PreviewBannerProps} from './PreviewBanner'
|
|
16
16
|
export {useNcfPreviewRefresh, createPreviewRefresh} from './previewRefresh'
|
|
17
17
|
export type {PreviewRefreshPayload} from './previewRefresh'
|
|
18
|
+
export {NcfCodeEmbed, buildCodeEmbedDoc} from './CodeEmbedFrame'
|
|
19
|
+
export type {CodeEmbedValue, CodeEmbedFrameProps} from './CodeEmbedFrame'
|