@nocode-factory/sanity-kit 2.26.0 → 2.27.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/bin/check-environments.mjs +4 -2
- package/dist/index.d.ts +10 -2
- package/dist/index.js +247 -48
- package/dist/index.js.map +1 -1
- package/dist/web.js +1 -0
- package/dist/web.js.map +1 -1
- package/package.json +1 -1
- package/src/actions/PropagatePublish.tsx +40 -9
- package/src/config/defaults.ts +1 -1
- package/src/config/resolve.ts +3 -0
- package/src/config/types.ts +8 -0
- package/src/form/OverrideInput.tsx +62 -1
- package/src/form/TranslationTodoInput.tsx +36 -2
- package/src/hooks/useTranslationTodo.ts +2 -1
- package/src/index.ts +5 -1
- package/src/lib/aiTexts.ts +72 -0
- package/src/lib/aiTranslate.ts +61 -0
- package/src/version.ts +1 -1
- package/src/web/PreviewBanner.tsx +3 -1
package/dist/web.js
CHANGED
|
@@ -54,6 +54,7 @@ function NcfPreviewBanner(props) {
|
|
|
54
54
|
} catch {}
|
|
55
55
|
}, href = (enable) => `${togglePath}?enable=${enable}&redirect=${back}`;
|
|
56
56
|
return embedded ? null : /* @__PURE__ */ jsx("div", {
|
|
57
|
+
"data-ncf-preview-banner": "",
|
|
57
58
|
style: {
|
|
58
59
|
...anchor(props.position ?? "bottom-left"),
|
|
59
60
|
zIndex: 2147483e3
|
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 <div 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,mBAA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mC,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;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,oBAAoB,EAAK;CAK5E,gBAAgB;EACd,IAAI,CAAC,OAAO;EACZ,IAAM,MAAM,IAAI,IAAI,OAAO,SAAS,IAAI;EACpC,IAAI,aAAa,IAAI,WAAW,MAAM,UAC1C,IAAI,aAAa,IAAI,aAAa,KAAK,GACvC,OAAO,QAAQ,aAAa,OAAO,QAAQ,OAAO,IAAI,IAAI,SAAS,CAAC;CACtE,GAAG,CAAC,OAAO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,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"}
|
package/package.json
CHANGED
|
@@ -6,6 +6,8 @@ import type {ResolvedKitConfig} from '../config/types'
|
|
|
6
6
|
import {useKitClient} from '../hooks/useKitClient'
|
|
7
7
|
import {hasChanges, propagate, type PropagationResult, type SchemaTypeLike} from '../lib/propagate'
|
|
8
8
|
import {TRANSLATION_TODO_TYPE, translationTodoId} from '../schema/translationTodo'
|
|
9
|
+
import {setAtKey, valueAtKey} from '../lib/aiTexts'
|
|
10
|
+
import {translateValues} from '../lib/aiTranslate'
|
|
9
11
|
|
|
10
12
|
type Doc = Record<string, unknown>
|
|
11
13
|
interface Target {
|
|
@@ -20,18 +22,22 @@ interface Target {
|
|
|
20
22
|
* part normalement, puis « Propager aux autres langues ? » propose d'appliquer aux
|
|
21
23
|
* BROUILLONS des traductions la structure (sections ajoutées, supprimées, déplacées)
|
|
22
24
|
* et les valeurs non textuelles (images, liens, options…). Les textes traduits ne
|
|
23
|
-
* sont jamais écrasés : les textes modifiés sont
|
|
24
|
-
*
|
|
25
|
+
* sont jamais écrasés à la main : les textes modifiés sont traduits par l'IA
|
|
26
|
+
* (« Translate with AI », service du kit, coché par défaut) ou marqués « à
|
|
27
|
+
* traduire ». Rien n'est publié dans les autres langues : on relit, on publie.
|
|
28
|
+
* `masterLocale` : langue source (défaut : langue principale du site ; les valeurs
|
|
29
|
+
* par défaut des composants ont la leur, `i18n.defaultsSourceLocale`).
|
|
25
30
|
*/
|
|
26
|
-
export function withPropagation(Publish: DocumentActionComponent, config: ResolvedKitConfig): DocumentActionComponent {
|
|
31
|
+
export function withPropagation(Publish: DocumentActionComponent, config: ResolvedKitConfig, masterLocale?: string): DocumentActionComponent {
|
|
27
32
|
const i18n = config.i18n
|
|
33
|
+
const master = masterLocale ?? i18n?.defaultLocale
|
|
28
34
|
const Wrapped: DocumentActionComponent = (props: DocumentActionProps) => {
|
|
29
35
|
const base = Publish(props)
|
|
30
36
|
const client = useKitClient()
|
|
31
37
|
const schema = useSchema()
|
|
32
38
|
const [run, setRun] = useState<{before: Doc; after: Doc; targets: Target[]} | null>(null)
|
|
33
39
|
const current = (props.draft ?? props.published) as Doc | null
|
|
34
|
-
if (!base || !i18n || current?.[i18n.field] !==
|
|
40
|
+
if (!base || !i18n || current?.[i18n.field] !== master) return base
|
|
35
41
|
return {
|
|
36
42
|
...base,
|
|
37
43
|
onHandle: () => {
|
|
@@ -119,17 +125,32 @@ function PropagateDialog(props: {
|
|
|
119
125
|
const [busy, setBusy] = useState(false)
|
|
120
126
|
const toast = useToast()
|
|
121
127
|
const [error, setError] = useState<string | null>(null)
|
|
128
|
+
// Textes modifiés : traduits par l'IA (service du kit) plutôt que marqués « à traduire ».
|
|
129
|
+
const [ai, setAi] = useState(Boolean(config.history))
|
|
122
130
|
|
|
123
131
|
const apply = async () => {
|
|
124
132
|
setBusy(true)
|
|
125
133
|
setError(null)
|
|
126
134
|
try {
|
|
127
135
|
const applied: string[] = []
|
|
136
|
+
let translatedCount = 0
|
|
137
|
+
let aiError: string | null = null
|
|
128
138
|
for (const t of targets) {
|
|
129
139
|
if (!t.selected) continue
|
|
130
140
|
const {_rev, _createdAt, _updatedAt, ...doc} = t.result.document
|
|
141
|
+
let remaining = t.result.toTranslate
|
|
142
|
+
if (ai && config.history && remaining.length) {
|
|
143
|
+
try {
|
|
144
|
+
const values = remaining.map((path) => valueAtKey(after, path))
|
|
145
|
+
const translated = await translateValues(config.history, source, t.language, values)
|
|
146
|
+
remaining = remaining.filter((path, n) => values[n] === undefined || !setAtKey(doc, path, translated[n]))
|
|
147
|
+
translatedCount += t.result.toTranslate.length - remaining.length
|
|
148
|
+
} catch (cause) {
|
|
149
|
+
aiError = cause instanceof Error ? cause.message : String(cause)
|
|
150
|
+
}
|
|
151
|
+
}
|
|
131
152
|
await client.createOrReplace({...doc, _id: `drafts.${t.id}`, _type: type} as {_id: string; _type: string})
|
|
132
|
-
if (
|
|
153
|
+
if (remaining.length) {
|
|
133
154
|
const todoId = translationTodoId(t.id)
|
|
134
155
|
const existing = await client.fetch<string[] | null>(`*[_id == $todoId][0].paths`, {todoId})
|
|
135
156
|
await client.createOrReplace({
|
|
@@ -138,16 +159,20 @@ function PropagateDialog(props: {
|
|
|
138
159
|
documentId: t.id,
|
|
139
160
|
sourceId: id,
|
|
140
161
|
sourceLanguage: source,
|
|
141
|
-
paths: [...new Set([...(existing ?? []), ...
|
|
162
|
+
paths: [...new Set([...(existing ?? []), ...remaining])],
|
|
142
163
|
})
|
|
143
164
|
}
|
|
144
165
|
applied.push(t.language.toUpperCase())
|
|
145
166
|
}
|
|
146
167
|
// Fini : la fenêtre se ferme seule, le résultat s'affiche en notification.
|
|
147
168
|
toast.push({
|
|
148
|
-
status: 'success',
|
|
169
|
+
status: aiError ? 'warning' : 'success',
|
|
149
170
|
title: `Drafts updated: ${applied.join(', ')}`,
|
|
150
|
-
description:
|
|
171
|
+
description: aiError
|
|
172
|
+
? `AI translation failed (${aiError}): the changed texts are marked "To translate".`
|
|
173
|
+
: translatedCount
|
|
174
|
+
? `${translatedCount} text${translatedCount > 1 ? 's' : ''} translated with AI. Review, then publish each language.`
|
|
175
|
+
: 'Translate the fields marked "To translate", then publish each language.',
|
|
151
176
|
duration: 8000,
|
|
152
177
|
})
|
|
153
178
|
onDone()
|
|
@@ -162,8 +187,14 @@ function PropagateDialog(props: {
|
|
|
162
187
|
<Stack gap={4} padding={4}>
|
|
163
188
|
<Text size={1}>
|
|
164
189
|
The {source.toUpperCase()} version is published. Apply its changes to the drafts of the other languages?
|
|
165
|
-
|
|
190
|
+
Changed texts are {ai ? 'translated with AI' : 'marked "To translate"'}. Nothing is published.
|
|
166
191
|
</Text>
|
|
192
|
+
{config.history && targets.some((t) => t.result.toTranslate.length) && (
|
|
193
|
+
<Flex as="label" align="center" gap={2}>
|
|
194
|
+
<Checkbox checked={ai} onChange={() => setAi(!ai)} />
|
|
195
|
+
<Text size={1}>Translate changed texts with AI</Text>
|
|
196
|
+
</Flex>
|
|
197
|
+
)}
|
|
167
198
|
<Stack gap={3}>
|
|
168
199
|
{targets.map((t, index) => (
|
|
169
200
|
<Card key={t.id} padding={3} radius={2} border>
|
package/src/config/defaults.ts
CHANGED
|
@@ -18,7 +18,7 @@ export const DEFAULT_BLOCK_NAMESPACE = ''
|
|
|
18
18
|
*/
|
|
19
19
|
export const DEFAULT_NOINDEX_FIELDS = ['seo.noindex', 'noindex']
|
|
20
20
|
|
|
21
|
-
export const DEFAULT_I18N: Required<NcfI18nConfig> = {
|
|
21
|
+
export const DEFAULT_I18N: Omit<Required<NcfI18nConfig>, 'defaultsSourceLocale'> = {
|
|
22
22
|
field: 'language',
|
|
23
23
|
defaultLocale: 'fr',
|
|
24
24
|
locales: [],
|
package/src/config/resolve.ts
CHANGED
|
@@ -79,6 +79,9 @@ export function resolveConfig(input: NcfKitConfig): ResolvedKitConfig {
|
|
|
79
79
|
field: input.i18n.field?.trim() || DEFAULT_I18N.field,
|
|
80
80
|
defaultLocale: input.i18n.defaultLocale?.trim() || DEFAULT_I18N.defaultLocale,
|
|
81
81
|
locales: input.i18n.locales ?? DEFAULT_I18N.locales,
|
|
82
|
+
defaultsSourceLocale:
|
|
83
|
+
input.i18n.defaultsSourceLocale?.trim() ||
|
|
84
|
+
((input.i18n.locales ?? DEFAULT_I18N.locales).includes('en') ? 'en' : input.i18n.defaultLocale?.trim() || DEFAULT_I18N.defaultLocale),
|
|
82
85
|
}
|
|
83
86
|
|
|
84
87
|
return {
|
package/src/config/types.ts
CHANGED
|
@@ -37,6 +37,13 @@ export interface NcfI18nConfig {
|
|
|
37
37
|
defaultLocale?: string
|
|
38
38
|
/** Langues attendues. Vide = déduites des documents rencontrés. */
|
|
39
39
|
locales?: string[]
|
|
40
|
+
/**
|
|
41
|
+
* Langue SOURCE des valeurs par défaut des composants (défaut : `en` si le site
|
|
42
|
+
* l'a, sinon la langue principale). Publier ses valeurs par défaut propose de
|
|
43
|
+
* retraduire celles des autres langues ; un champ qui hérite d'une valeur par
|
|
44
|
+
* défaut non traduite propose « Translate default with AI ».
|
|
45
|
+
*/
|
|
46
|
+
defaultsSourceLocale?: string
|
|
40
47
|
}
|
|
41
48
|
|
|
42
49
|
/**
|
|
@@ -241,6 +248,7 @@ export interface ResolvedI18n {
|
|
|
241
248
|
field: string
|
|
242
249
|
defaultLocale: string
|
|
243
250
|
locales: string[]
|
|
251
|
+
defaultsSourceLocale: string
|
|
244
252
|
}
|
|
245
253
|
|
|
246
254
|
export interface ResolvedComponentPreview {
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import {useState, type ComponentType} from 'react'
|
|
2
2
|
import {set, unset, useFormValue, useSchema, type InputProps} from 'sanity'
|
|
3
3
|
import {useRouter} from 'sanity/router'
|
|
4
|
-
import {Box, Flex, Text} from '@sanity/ui'
|
|
4
|
+
import {Box, Button, Flex, Text} from '@sanity/ui'
|
|
5
5
|
import {Tooltip} from '@sanity/ui/tooltip'
|
|
6
6
|
import type {ResolvedKitConfig} from '../config/types'
|
|
7
7
|
import {blockName, componentIntentParams} from '../lib/blocks'
|
|
8
8
|
import {useKitClient} from '../hooks/useKitClient'
|
|
9
|
+
import {collectTexts} from '../lib/aiTexts'
|
|
10
|
+
import {translateValues} from '../lib/aiTranslate'
|
|
9
11
|
import {useComponentDefaults} from '../hooks/useComponentDefaults'
|
|
10
12
|
import {
|
|
11
13
|
defaultValueAt,
|
|
@@ -59,6 +61,44 @@ export function createOverrideInput(config: ResolvedKitConfig): ComponentType<In
|
|
|
59
61
|
const defaults = useComponentDefaults(client, defaultsType, languageField, language)
|
|
60
62
|
const inherited = defaultValueAt(defaults, shortName, rel)
|
|
61
63
|
const field = rel[rel.length - 1] ?? ''
|
|
64
|
+
// Valeurs par défaut dans la langue SOURCE (anglais en général) : un champ qui
|
|
65
|
+
// hérite d'une valeur par défaut pas encore traduite dans cette langue (vide,
|
|
66
|
+
// ou identique au texte source) propose « Translate default with AI ».
|
|
67
|
+
const sourceLocale = config.i18n?.defaultsSourceLocale ?? null
|
|
68
|
+
const sourceDefaults = useComponentDefaults(client, defaultsType, languageField, sourceLocale)
|
|
69
|
+
const sourceDefault = defaultValueAt(sourceDefaults, shortName, rel)
|
|
70
|
+
const [translating, setTranslating] = useState(false)
|
|
71
|
+
const [translateError, setTranslateError] = useState<string | null>(null)
|
|
72
|
+
const untranslatedDefault =
|
|
73
|
+
Boolean(config.history && config.i18n && language && sourceLocale && language !== sourceLocale) &&
|
|
74
|
+
!inputProps.readOnly &&
|
|
75
|
+
isEmptyValue(inputProps.value) &&
|
|
76
|
+
collectTexts(sourceDefault).some((t) => t.trim()) &&
|
|
77
|
+
(isEmptyValue(inherited) || JSON.stringify(inherited) === JSON.stringify(sourceDefault))
|
|
78
|
+
const translateDefault = async () => {
|
|
79
|
+
const localeId = (defaults as {_id?: string} | null)?._id?.replace(/^drafts\./, '')
|
|
80
|
+
if (!config.history || !sourceLocale || !language) return
|
|
81
|
+
setTranslating(true)
|
|
82
|
+
setTranslateError(null)
|
|
83
|
+
try {
|
|
84
|
+
if (!localeId) throw new Error(`No ${language.toUpperCase()} component defaults document.`)
|
|
85
|
+
const [translated] = await translateValues(config.history, sourceLocale, language, [sourceDefault])
|
|
86
|
+
// Écrit dans le BROUILLON des valeurs par défaut de cette langue (à publier).
|
|
87
|
+
const published = await client.getDocument(localeId)
|
|
88
|
+
const path = [shortName, ...rel].map((seg, n) => (typeof seg === 'number' ? `[${seg}]` : n ? `.${seg}` : seg)).join('')
|
|
89
|
+
const tx = client.transaction()
|
|
90
|
+
if (published) {
|
|
91
|
+
const {_rev, _updatedAt, _createdAt, ...copy} = published
|
|
92
|
+
tx.createIfNotExists({...copy, _id: `drafts.${localeId}`} as {_id: string; _type: string})
|
|
93
|
+
}
|
|
94
|
+
tx.patch(`drafts.${localeId}`, (patch) => patch.set({[path]: translated}))
|
|
95
|
+
await tx.commit()
|
|
96
|
+
} catch (cause) {
|
|
97
|
+
setTranslateError(cause instanceof Error ? cause.message : String(cause))
|
|
98
|
+
} finally {
|
|
99
|
+
setTranslating(false)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
62
102
|
|
|
63
103
|
const router = useRouter()
|
|
64
104
|
|
|
@@ -99,6 +139,27 @@ export function createOverrideInput(config: ResolvedKitConfig): ComponentType<In
|
|
|
99
139
|
<Flex align="flex-start" gap={2}>
|
|
100
140
|
<Box flex={1} style={{minWidth: 0}}>
|
|
101
141
|
{inputProps.renderDefault(shown)}
|
|
142
|
+
{untranslatedDefault && (
|
|
143
|
+
<Flex align="center" gap={2} marginTop={2} wrap="wrap">
|
|
144
|
+
<Text size={0} muted>
|
|
145
|
+
Default not translated to {String(language).toUpperCase()}.
|
|
146
|
+
</Text>
|
|
147
|
+
<Button
|
|
148
|
+
mode="ghost"
|
|
149
|
+
tone="primary"
|
|
150
|
+
fontSize={0}
|
|
151
|
+
padding={2}
|
|
152
|
+
text={translating ? 'Translating…' : 'Translate default with AI'}
|
|
153
|
+
disabled={translating}
|
|
154
|
+
onClick={() => void translateDefault()}
|
|
155
|
+
/>
|
|
156
|
+
{translateError && (
|
|
157
|
+
<Text size={0} style={{color: 'var(--card-badge-critical-fg-color, #c00)'}}>
|
|
158
|
+
{translateError}
|
|
159
|
+
</Text>
|
|
160
|
+
)}
|
|
161
|
+
</Flex>
|
|
162
|
+
)}
|
|
102
163
|
{inherits && placeholder === null && (
|
|
103
164
|
<Box marginTop={2}>
|
|
104
165
|
<Text size={0} muted>
|
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import {createElement, useState, type ComponentType} from 'react'
|
|
2
|
-
import {useFormValue, type InputProps} from 'sanity'
|
|
2
|
+
import {set, useFormValue, type InputProps} from 'sanity'
|
|
3
3
|
import {Button, Card, Flex, Stack, Text} from '@sanity/ui'
|
|
4
4
|
import type {ResolvedKitConfig} from '../config/types'
|
|
5
5
|
import {useKitClient} from '../hooks/useKitClient'
|
|
6
6
|
import {fieldPathKey, useTranslationTodo} from '../hooks/useTranslationTodo'
|
|
7
|
+
import {valueAtKey} from '../lib/aiTexts'
|
|
8
|
+
import {translateValues} from '../lib/aiTranslate'
|
|
7
9
|
|
|
8
10
|
/**
|
|
9
11
|
* Sous un champ d'une traduction modifié dans la version principale (propagation) :
|
|
10
|
-
* « À traduire », avec « Marquer comme traduit » qui le retire de la liste
|
|
12
|
+
* « À traduire », avec « Marquer comme traduit » qui le retire de la liste, et
|
|
13
|
+
* « Translate with AI » (service du kit) : traduit le texte de la version principale
|
|
14
|
+
* dans ce champ (brouillon de cette langue), puis le retire de la liste.
|
|
11
15
|
*/
|
|
12
16
|
export function withTranslationTodo(Inner: ComponentType<InputProps>, config: ResolvedKitConfig): ComponentType<InputProps> {
|
|
13
17
|
function TranslationTodoInput(props: InputProps) {
|
|
@@ -15,6 +19,8 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
|
|
|
15
19
|
const client = useKitClient()
|
|
16
20
|
const todo = useTranslationTodo(client, config.i18n ? id : undefined)
|
|
17
21
|
const [busy, setBusy] = useState(false)
|
|
22
|
+
const [error, setError] = useState<string | null>(null)
|
|
23
|
+
const language = useFormValue([config.i18n?.field ?? 'language']) as string | undefined
|
|
18
24
|
const key = fieldPathKey(props.path)
|
|
19
25
|
const inner = createElement(Inner, props)
|
|
20
26
|
const show = Boolean(todo?.paths?.includes(key))
|
|
@@ -27,6 +33,26 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
|
|
|
27
33
|
.commit()
|
|
28
34
|
.finally(() => setBusy(false))
|
|
29
35
|
}
|
|
36
|
+
const translate = async () => {
|
|
37
|
+
if (!todo?.sourceId || !todo.sourceLanguage || !language || !config.history) return
|
|
38
|
+
setBusy(true)
|
|
39
|
+
setError(null)
|
|
40
|
+
try {
|
|
41
|
+
const source = (await client.getDocument(todo.sourceId)) ?? (await client.getDocument(`drafts.${todo.sourceId}`))
|
|
42
|
+
const value = valueAtKey(source, key)
|
|
43
|
+
if (value === undefined) throw new Error('Source text not found.')
|
|
44
|
+
const [translated] = await translateValues(config.history, todo.sourceLanguage, language, [value])
|
|
45
|
+
props.onChange(set(translated))
|
|
46
|
+
await client
|
|
47
|
+
.patch(todo._id)
|
|
48
|
+
.set({paths: (todo.paths ?? []).filter((p) => p !== key)})
|
|
49
|
+
.commit()
|
|
50
|
+
} catch (cause) {
|
|
51
|
+
setError(cause instanceof Error ? cause.message : String(cause))
|
|
52
|
+
} finally {
|
|
53
|
+
setBusy(false)
|
|
54
|
+
}
|
|
55
|
+
}
|
|
30
56
|
// Même structure que la mention soit là ou non : le champ n'est jamais recréé.
|
|
31
57
|
return (
|
|
32
58
|
<Stack gap={2}>
|
|
@@ -37,8 +63,16 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
|
|
|
37
63
|
<Text size={1} style={{flex: 1}}>
|
|
38
64
|
To translate: changed in the {(todo?.sourceLanguage ?? '').toUpperCase()} version.
|
|
39
65
|
</Text>
|
|
66
|
+
{config.history && !props.readOnly && (
|
|
67
|
+
<Button tone="primary" fontSize={1} padding={2} text={busy ? 'Translating…' : 'Translate with AI'} disabled={busy} onClick={() => void translate()} />
|
|
68
|
+
)}
|
|
40
69
|
<Button mode="ghost" fontSize={1} padding={2} text="Mark as translated" disabled={busy} onClick={done} />
|
|
41
70
|
</Flex>
|
|
71
|
+
{error && (
|
|
72
|
+
<Text size={1} style={{marginTop: 8, color: 'var(--card-badge-critical-fg-color, #c00)'}}>
|
|
73
|
+
{error}
|
|
74
|
+
</Text>
|
|
75
|
+
)}
|
|
42
76
|
</Card>
|
|
43
77
|
)}
|
|
44
78
|
</Stack>
|
|
@@ -8,6 +8,7 @@ import {translationTodoId} from '../schema/translationTodo'
|
|
|
8
8
|
*/
|
|
9
9
|
export interface TranslationTodo {
|
|
10
10
|
_id: string
|
|
11
|
+
sourceId?: string
|
|
11
12
|
sourceLanguage?: string
|
|
12
13
|
paths?: string[]
|
|
13
14
|
}
|
|
@@ -31,7 +32,7 @@ function entryFor(client: SanityClient, documentId: string): Entry {
|
|
|
31
32
|
if (!e.stop) {
|
|
32
33
|
const load = () =>
|
|
33
34
|
client
|
|
34
|
-
.fetch<TranslationTodo | null>(`*[_id == $id][0]{_id, sourceLanguage, paths}`, {id})
|
|
35
|
+
.fetch<TranslationTodo | null>(`*[_id == $id][0]{_id, sourceId, sourceLanguage, paths}`, {id})
|
|
35
36
|
.then((value) => {
|
|
36
37
|
e.value = value
|
|
37
38
|
e.listeners.forEach((l) => l())
|
package/src/index.ts
CHANGED
|
@@ -152,7 +152,11 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
|
|
|
152
152
|
? prev.map((action) =>
|
|
153
153
|
action.action === 'unpublish' ? RemoveFromSiteAction : action.action === 'publish' && config.i18n ? withPropagation(action, config) : action,
|
|
154
154
|
)
|
|
155
|
-
:
|
|
155
|
+
: // Valeurs par défaut des composants : publier celles de la langue source
|
|
156
|
+
// (anglais en général) propose de retraduire celles des autres langues.
|
|
157
|
+
context.schemaType === config.componentPreview.defaultsType && config.i18n
|
|
158
|
+
? prev.map((action) => (action.action === 'publish' ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action))
|
|
159
|
+
: prev,
|
|
156
160
|
},
|
|
157
161
|
|
|
158
162
|
// Le lanceur d'aperçu s'ajoute à droite des outils, dans la barre du haut
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Textes d'une valeur de champ, pour la traduction par IA : une chaîne, ou les
|
|
3
|
+
* morceaux de texte (spans) d'un texte riche. La structure (styles, liens, marques,
|
|
4
|
+
* _key) n'est jamais envoyée ni modifiée : seuls les textes sont remplacés.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
type Rec = Record<string, unknown>
|
|
8
|
+
const isObj = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
9
|
+
|
|
10
|
+
/** Textes d'une valeur, dans l'ordre. */
|
|
11
|
+
export function collectTexts(value: unknown): string[] {
|
|
12
|
+
if (typeof value === 'string') return [value]
|
|
13
|
+
if (!Array.isArray(value)) return []
|
|
14
|
+
const out: string[] = []
|
|
15
|
+
for (const item of value) {
|
|
16
|
+
if (typeof item === 'string') out.push(item)
|
|
17
|
+
else if (isObj(item) && Array.isArray(item.children))
|
|
18
|
+
for (const child of item.children) if (isObj(child) && typeof child.text === 'string') out.push(child.text)
|
|
19
|
+
}
|
|
20
|
+
return out
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** La même valeur avec ses textes remplacés (dans l'ordre de `collectTexts`). */
|
|
24
|
+
export function replaceTexts(value: unknown, texts: readonly string[]): unknown {
|
|
25
|
+
let i = 0
|
|
26
|
+
const next = () => texts[i++] ?? ''
|
|
27
|
+
if (typeof value === 'string') return next()
|
|
28
|
+
if (!Array.isArray(value)) return value
|
|
29
|
+
return value.map((item) => {
|
|
30
|
+
if (typeof item === 'string') return next()
|
|
31
|
+
if (isObj(item) && Array.isArray(item.children))
|
|
32
|
+
return {...item, children: item.children.map((child) => (isObj(child) && typeof child.text === 'string' ? {...child, text: next()} : child))}
|
|
33
|
+
return item
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** `sections[a].title` → segments (`[x]` : clé d'élément de liste, ou rang). */
|
|
38
|
+
export function parsePathKey(path: string): ({field: string} | {item: string})[] {
|
|
39
|
+
const out: ({field: string} | {item: string})[] = []
|
|
40
|
+
for (const m of path.matchAll(/([^.[\]]+)|\[([^\]]+)\]/g)) out.push(m[1] !== undefined ? {field: m[1]} : {item: m[2]!})
|
|
41
|
+
return out
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function itemOf(list: unknown[], key: string): unknown {
|
|
45
|
+
return list.find((i) => isObj(i) && i._key === key) ?? (/^\d+$/.test(key) ? list[Number(key)] : undefined)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Valeur d'un document au chemin `sections[a].title`. */
|
|
49
|
+
export function valueAtKey(doc: unknown, path: string): unknown {
|
|
50
|
+
let cur: unknown = doc
|
|
51
|
+
for (const seg of parsePathKey(path)) {
|
|
52
|
+
if (cur == null) return undefined
|
|
53
|
+
if ('field' in seg) cur = isObj(cur) ? cur[seg.field] : undefined
|
|
54
|
+
else cur = Array.isArray(cur) ? itemOf(cur, seg.item) : undefined
|
|
55
|
+
}
|
|
56
|
+
return cur
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Écrit `value` au chemin dans `doc` (modifié sur place). Faux si le chemin n'existe pas. */
|
|
60
|
+
export function setAtKey(doc: Rec, path: string, value: unknown): boolean {
|
|
61
|
+
const segs = parsePathKey(path)
|
|
62
|
+
let cur: unknown = doc
|
|
63
|
+
for (let n = 0; n < segs.length - 1; n++) {
|
|
64
|
+
const seg = segs[n]!
|
|
65
|
+
cur = 'field' in seg ? (isObj(cur) ? cur[seg.field] : undefined) : Array.isArray(cur) ? itemOf(cur, seg.item) : undefined
|
|
66
|
+
if (cur == null) return false
|
|
67
|
+
}
|
|
68
|
+
const last = segs[segs.length - 1]
|
|
69
|
+
if (!last || !('field' in last) || !isObj(cur)) return false
|
|
70
|
+
cur[last.field] = value
|
|
71
|
+
return true
|
|
72
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import {collectTexts, replaceTexts} from './aiTexts'
|
|
2
|
+
|
|
3
|
+
/** Service du kit (même clé de projet et même adresse que l'historique). */
|
|
4
|
+
export interface TranslateService {
|
|
5
|
+
endpoint: string
|
|
6
|
+
projectKey: string
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const MAX_TEXTS = 250
|
|
10
|
+
const MAX_CHARS = 30_000
|
|
11
|
+
|
|
12
|
+
const MESSAGES: Record<string, string> = {
|
|
13
|
+
daily_limit: 'Daily AI translation limit reached for this project.',
|
|
14
|
+
project_inactive: 'This project is not active in the NCF kit.',
|
|
15
|
+
bad_key: 'This project is not registered in the NCF kit (npx ncf-kit setup).',
|
|
16
|
+
not_configured: 'AI translation is not configured on the NCF kit service.',
|
|
17
|
+
too_long: 'Text too long to translate at once.',
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function call(service: TranslateService, from: string, to: string, texts: string[]): Promise<string[]> {
|
|
21
|
+
const response = await fetch(`${service.endpoint}/translate`, {
|
|
22
|
+
method: 'POST',
|
|
23
|
+
headers: {'content-type': 'application/json'},
|
|
24
|
+
body: JSON.stringify({key: service.projectKey, from, to, texts}),
|
|
25
|
+
})
|
|
26
|
+
const body = (await response.json().catch(() => ({}))) as {texts?: string[]; error?: string}
|
|
27
|
+
if (!response.ok || !Array.isArray(body.texts) || body.texts.length !== texts.length)
|
|
28
|
+
throw new Error(MESSAGES[body.error ?? ''] ?? `AI translation failed (${body.error ?? response.status}).`)
|
|
29
|
+
return body.texts
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Traduit des valeurs de champs (chaînes ou textes riches) de `from` vers `to` :
|
|
34
|
+
* mêmes valeurs, textes traduits. Découpe en lots si besoin.
|
|
35
|
+
*/
|
|
36
|
+
export async function translateValues(service: TranslateService, from: string, to: string, values: readonly unknown[]): Promise<unknown[]> {
|
|
37
|
+
const perValue = values.map((v) => collectTexts(v))
|
|
38
|
+
const all = perValue.flat()
|
|
39
|
+
const translated: string[] = []
|
|
40
|
+
let batch: string[] = []
|
|
41
|
+
let size = 0
|
|
42
|
+
const flush = async () => {
|
|
43
|
+
if (!batch.length) return
|
|
44
|
+
translated.push(...(await call(service, from, to, batch)))
|
|
45
|
+
batch = []
|
|
46
|
+
size = 0
|
|
47
|
+
}
|
|
48
|
+
for (const text of all) {
|
|
49
|
+
if (batch.length >= MAX_TEXTS || size + text.length > MAX_CHARS) await flush()
|
|
50
|
+
batch.push(text)
|
|
51
|
+
size += text.length
|
|
52
|
+
}
|
|
53
|
+
await flush()
|
|
54
|
+
let offset = 0
|
|
55
|
+
return values.map((value, n) => {
|
|
56
|
+
const count = perValue[n]!.length
|
|
57
|
+
const slice = translated.slice(offset, offset + count)
|
|
58
|
+
offset += count
|
|
59
|
+
return count ? replaceTexts(value, slice) : value
|
|
60
|
+
})
|
|
61
|
+
}
|
package/src/version.ts
CHANGED
|
@@ -100,7 +100,9 @@ export function NcfPreviewBanner(props: PreviewBannerProps) {
|
|
|
100
100
|
if (embedded) return null
|
|
101
101
|
|
|
102
102
|
return (
|
|
103
|
-
|
|
103
|
+
// data-ncf-preview-banner : repère technique du test prod / préprod
|
|
104
|
+
// (check-environments), indépendant de la langue des libellés.
|
|
105
|
+
<div data-ncf-preview-banner="" style={{...anchor(props.position ?? 'bottom-left'), zIndex: 2147483000}}>
|
|
104
106
|
<div style={shell}>
|
|
105
107
|
<span style={{display: 'inline-flex', alignItems: 'center', gap: 6, fontWeight: 500}}>
|
|
106
108
|
{/* Pastille pleine plutôt qu'un caractère décoratif : elle se lit à
|