@nocode-factory/sanity-kit 2.45.0 → 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 CHANGED
@@ -106,6 +106,8 @@ Les outils de schéma sont aussi dans l'entrée `@nocode-factory/sanity-kit/sche
106
106
  | `defineComponentDefaults({sections})` | `@nocode-factory/sanity-kit/schema` | type du document des valeurs par défaut |
107
107
  | `requiredUnlessDefault` | `@nocode-factory/sanity-kit/schema` | obligatoire sauf valeur par défaut |
108
108
  | `componentDefaultsMainDocument({language})` | `@nocode-factory/sanity-kit/schema` | Presentation : page de rendu = valeurs par défaut |
109
+ | `defineCodeEmbedType()` | `@nocode-factory/sanity-kit` | type « Code embed » (HTML/CSS/JS, éditeur sombre, iframe sandboxée) |
110
+ | `NcfCodeEmbed` | `@nocode-factory/sanity-kit/web` | rendu site d'un bloc « Code embed » |
109
111
  | `applyDefaults`, `inherit` | `@nocode-factory/sanity-kit/web/defaults` | héritage côté site |
110
112
  | `componentDefaultsQuery` | `@nocode-factory/sanity-kit/web/defaults` | requête des valeurs par défaut |
111
113
  | `stegaFilter`, `isOptionValue` | `@nocode-factory/sanity-kit/web/defaults` | preview : options jamais encodées |
@@ -0,0 +1,88 @@
1
+ import { useEffect, useId, useMemo, useRef, useState } from "react";
2
+ import { jsx } from "react/jsx-runtime";
3
+ /**
4
+ * Assemble le document isolé injecté dans l'iframe.
5
+ *
6
+ * Un petit script mesure la hauteur réelle du contenu et la transmet au parent
7
+ * (`postMessage`) : le parent ajuste la hauteur de l'iframe, il n'y a donc jamais
8
+ * de barre de défilement interne. Le `token` relie chaque message à son iframe.
9
+ */
10
+ function buildCodeEmbedDoc({ html = "", css = "", js = "" }, token) {
11
+ return `<!doctype html>
12
+ <html>
13
+ <head>
14
+ <meta charset="utf-8">
15
+ <meta name="viewport" content="width=device-width, initial-scale=1">
16
+ <style>
17
+ html,body{margin:0;padding:0}
18
+ ${css}
19
+ </style>
20
+ </head>
21
+ <body>
22
+ ${html}
23
+ ${js ? `<script>\n${js}\n<\/script>` : ""}
24
+ <script>
25
+ (function(){
26
+ var token=${JSON.stringify(token)};
27
+ function post(){
28
+ try{
29
+ var h=Math.ceil(document.documentElement.getBoundingClientRect().height);
30
+ parent.postMessage({ncfCodeEmbed:token,height:h},'*');
31
+ }catch(e){}
32
+ }
33
+ if(typeof ResizeObserver!=='undefined'){new ResizeObserver(post).observe(document.body);}
34
+ window.addEventListener('load',post);
35
+ post();
36
+ })();
37
+ <\/script>
38
+ </body>
39
+ </html>`;
40
+ }
41
+ /**
42
+ * Rend un bloc HTML / CSS / JS arbitraire dans une iframe **sandboxée**.
43
+ *
44
+ * Le code tourne dans une origine isolée (pas de `allow-same-origin`) : il ne
45
+ * peut lire ni les cookies ni le stockage du site hôte, mais le JS reste actif.
46
+ * La hauteur s'ajuste automatiquement au contenu.
47
+ *
48
+ * Même composant côté Studio (aperçu dans le formulaire) et côté site, pour que
49
+ * ce qui est édité soit exactement ce qui s'affiche.
50
+ */
51
+ function NcfCodeEmbed(props) {
52
+ let { html, css, js, title, className, style, minHeight = 0 } = props, token = useId(), srcDoc = useMemo(() => buildCodeEmbedDoc({
53
+ html,
54
+ css,
55
+ js
56
+ }, token), [
57
+ html,
58
+ css,
59
+ js,
60
+ token
61
+ ]), ref = useRef(null), [height, setHeight] = useState(minHeight);
62
+ return useEffect(() => {
63
+ function onMessage(event) {
64
+ let data = event.data;
65
+ if (!data || data.ncfCodeEmbed !== token) return;
66
+ let next = Number(data.height);
67
+ Number.isFinite(next) && next > 0 && setHeight(next);
68
+ }
69
+ return window.addEventListener("message", onMessage), () => window.removeEventListener("message", onMessage);
70
+ }, [token]), !html && !css && !js ? null : /* @__PURE__ */ jsx("iframe", {
71
+ ref,
72
+ title: title || "Code embed",
73
+ srcDoc,
74
+ sandbox: "allow-scripts allow-popups allow-forms allow-top-navigation-by-user-activation allow-modals",
75
+ loading: "lazy",
76
+ className,
77
+ style: {
78
+ display: "block",
79
+ width: "100%",
80
+ border: 0,
81
+ height: height ? `${height}px` : void 0,
82
+ ...style
83
+ }
84
+ });
85
+ }
86
+ export { buildCodeEmbedDoc as n, NcfCodeEmbed as t };
87
+
88
+ //# sourceMappingURL=CodeEmbedFrame-DWsj6Z8T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CodeEmbedFrame-DWsj6Z8T.js","names":[],"sources":["../src/web/CodeEmbedFrame.tsx"],"sourcesContent":["'use client'\n\nimport {useEffect, useId, useMemo, useRef, useState, type CSSProperties} from 'react'\n\n/** Contenu d'un bloc « Code embed » : trois langages, tous optionnels. */\nexport interface CodeEmbedValue {\n html?: string\n css?: string\n js?: string\n}\n\nexport interface CodeEmbedFrameProps extends CodeEmbedValue {\n /** Titre de l'iframe (accessibilité). */\n title?: string\n className?: string\n style?: CSSProperties\n /** Hauteur de départ, avant la première mesure (évite le saut au chargement). */\n minHeight?: number\n}\n\n/**\n * Assemble le document isolé injecté dans l'iframe.\n *\n * Un petit script mesure la hauteur réelle du contenu et la transmet au parent\n * (`postMessage`) : le parent ajuste la hauteur de l'iframe, il n'y a donc jamais\n * de barre de défilement interne. Le `token` relie chaque message à son iframe.\n */\nexport function buildCodeEmbedDoc({html = '', css = '', js = ''}: CodeEmbedValue, token: string): string {\n return `<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<style>\nhtml,body{margin:0;padding:0}\n${css}\n</style>\n</head>\n<body>\n${html}\n${js ? `<script>\\n${js}\\n</script>` : ''}\n<script>\n(function(){\n var token=${JSON.stringify(token)};\n function post(){\n try{\n var h=Math.ceil(document.documentElement.getBoundingClientRect().height);\n parent.postMessage({ncfCodeEmbed:token,height:h},'*');\n }catch(e){}\n }\n if(typeof ResizeObserver!=='undefined'){new ResizeObserver(post).observe(document.body);}\n window.addEventListener('load',post);\n post();\n})();\n</script>\n</body>\n</html>`\n}\n\n/**\n * Rend un bloc HTML / CSS / JS arbitraire dans une iframe **sandboxée**.\n *\n * Le code tourne dans une origine isolée (pas de `allow-same-origin`) : il ne\n * peut lire ni les cookies ni le stockage du site hôte, mais le JS reste actif.\n * La hauteur s'ajuste automatiquement au contenu.\n *\n * Même composant côté Studio (aperçu dans le formulaire) et côté site, pour que\n * ce qui est édité soit exactement ce qui s'affiche.\n */\nexport function NcfCodeEmbed(props: CodeEmbedFrameProps): React.JSX.Element | null {\n const {html, css, js, title, className, style, minHeight = 0} = props\n const token = useId()\n const srcDoc = useMemo(() => buildCodeEmbedDoc({html, css, js}, token), [html, css, js, token])\n const ref = useRef<HTMLIFrameElement>(null)\n const [height, setHeight] = useState(minHeight)\n\n useEffect(() => {\n function onMessage(event: MessageEvent) {\n const data = event.data as {ncfCodeEmbed?: string; height?: number} | null\n if (!data || data.ncfCodeEmbed !== token) return\n const next = Number(data.height)\n if (Number.isFinite(next) && next > 0) setHeight(next)\n }\n window.addEventListener('message', onMessage)\n return () => window.removeEventListener('message', onMessage)\n }, [token])\n\n if (!html && !css && !js) return null\n\n return (\n <iframe\n ref={ref}\n title={title || 'Code embed'}\n srcDoc={srcDoc}\n // Pas de `allow-same-origin` : l'embed ne peut pas lire les cookies ni le\n // stockage du site. `allow-scripts` garde le JS actif ; la navigation du\n // haut n'est permise que sur un clic de l'utilisateur.\n sandbox=\"allow-scripts allow-popups allow-forms allow-top-navigation-by-user-activation allow-modals\"\n loading=\"lazy\"\n className={className}\n style={{display: 'block', width: '100%', border: 0, height: height ? `${height}px` : undefined, ...style}}\n />\n )\n}\n"],"mappings":";;;;;;;;;AA2BA,SAAgB,kBAAkB,EAAC,OAAO,IAAI,MAAM,IAAI,KAAK,MAAqB,OAAuB;CACvG,OAAO;;;;;;;EAOP,IAAI;;;;EAIJ,KAAK;EACL,KAAK,aAAa,GAAG,gBAAe,GAAG;;;cAG3B,KAAK,UAAU,KAAK,EAAE;;;;;;;;;;;;;;AAcpC;;;;;;;;;;;AAYA,SAAgB,aAAa,OAAsD;CACjF,IAAM,EAAC,MAAM,KAAK,IAAI,OAAO,WAAW,OAAO,YAAY,MAAK,OAC1D,QAAQ,MAAM,GACd,SAAS,cAAc,kBAAkB;EAAC;EAAM;EAAK;CAAE,GAAG,KAAK,GAAG;EAAC;EAAM;EAAK;EAAI;CAAK,CAAC,GACxF,MAAM,OAA0B,IAAI,GACpC,CAAC,QAAQ,aAAa,SAAS,SAAS;CAe9C,OAbA,gBAAgB;EACd,SAAS,UAAU,OAAqB;GACtC,IAAM,OAAO,MAAM;GACnB,IAAI,CAAC,QAAQ,KAAK,iBAAiB,OAAO;GAC1C,IAAM,OAAO,OAAO,KAAK,MAAM;GAC/B,AAAI,OAAO,SAAS,IAAI,KAAK,OAAO,KAAG,UAAU,IAAI;EACvD;EAEA,OADA,OAAO,iBAAiB,WAAW,SAAS,SAC/B,OAAO,oBAAoB,WAAW,SAAS;CAC9D,GAAG,CAAC,KAAK,CAAC,GAEN,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAW,OAG/B,oBAAC,UAAD;EACO;EACL,OAAO,SAAS;EACR;EAIR,SAAQ;EACR,SAAQ;EACG;EACX,OAAO;GAAC,SAAS;GAAS,OAAO;GAAQ,QAAQ;GAAG,QAAQ,SAAS,GAAG,OAAO,MAAM,KAAA;GAAW,GAAG;EAAK;CACzG,CAAA;AAEL"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { A as ResolvedDocumentColumn, C as NcfInternalFieldOption, D as NcfToolName, E as NcfPageTypeInput, M as ResolvedI18n, N as ResolvedKitConfig, O as NcfToolsConfig, P as ResolvedPageType, S as NcfInternalField, T as NcfPageTypeConfig, _ as NcfComponentPreviewConfig, a as pageTypesFromSiteRoutes, b as NcfHistoryConfig, c as componentDefaultsMainDocuments, d as requiredUnlessDefault, f as requiredUnlessDefaultFor, g as NcfBoardTag, h as KitContextValue, i as SiteRoutesRegistry, j as ResolvedHistory, k as ResolvedComponentPreview, l as defaultsFieldName, m as IssueLevel, n as fixCrossLanguageReferences, o as DEFAULT_COMPONENT_DEFAULTS_TYPE, p as ConfigIssue, r as withSameLanguageReferences, s as componentDefaultsMainDocument, t as CrossLanguageReport, u as defineComponentDefaults, v as NcfDocumentColumn, w as NcfKitConfig, x as NcfI18nConfig, y as NcfEnvironment } from "./fixCrossLanguageReferences-CFZax-Nb.js";
2
2
  import { ComponentType, ReactNode } from "react";
3
- import { SanityClient, Schema, Tool, ToolMenuProps } from "sanity";
3
+ import { LayoutProps, ObjectDefinition, ObjectInputProps, SanityClient, Schema, TextInputProps, Tool, ToolMenuProps } from "sanity";
4
4
  import { PreviewHeaderProps } from "sanity/presentation";
5
5
  /** Garantit un chemin absolu ('accueil' -> '/accueil', '' -> '/'). */
6
6
  export declare const normalizePath: (path: string) => string;
@@ -889,6 +889,54 @@ export declare function createPreviewLauncher(config: ResolvedKitConfig, issues:
889
889
  export declare function NcfKitUpdate(props: {
890
890
  inline?: boolean;
891
891
  }): import("react").JSX.Element | null;
892
+ /**
893
+ * Posé sur `studio.components.layout` : rend le Studio tel quel, et ajoute la
894
+ * feuille de style. Un seul `<style>` pour tout le Studio.
895
+ */
896
+ export declare function HelpTextStyle(props: LayoutProps): import("react").JSX.Element;
897
+ interface CodeEmbedTypeOptions {
898
+ /** Nom du type (défaut `codeEmbed`). */
899
+ name?: string;
900
+ /** Titre affiché (défaut `Code embed`). */
901
+ title?: string;
902
+ }
903
+ /**
904
+ * Type d'objet « Code embed » : HTML, CSS et JS libres, éditables dans une
905
+ * interface sombre à coloration syntaxique, rendus dans une iframe sandboxée
906
+ * (aperçu live dans le Studio, même rendu sur le site via {@link NcfCodeEmbed}).
907
+ *
908
+ * Réutilisable partout où un objet est accepté : section de page, article de
909
+ * blog (`articleContent`), texte riche (`blockContent`).
910
+ *
911
+ * ```ts
912
+ * import {defineCodeEmbedType} from '@nocode-factory/sanity-kit'
913
+ * export const codeEmbed = defineCodeEmbedType()
914
+ * ```
915
+ */
916
+ export declare function defineCodeEmbedType(options?: CodeEmbedTypeOptions): ObjectDefinition;
917
+ /** Langage de coloration ; lu dans `options.language` du champ. */
918
+ type CodeLanguage = 'html' | 'css' | 'js';
919
+ /**
920
+ * Fabrique l'input d'un champ de code pour un langage donné. À poser sur un
921
+ * champ `text` : `components: {input: codeEditorInput('css')}`.
922
+ */
923
+ export declare function codeEditorInput(language: CodeLanguage): {
924
+ (props: TextInputProps): React.JSX.Element;
925
+ displayName: string;
926
+ };
927
+ /** Input HTML prêt à l'emploi (le plus courant). */
928
+ export declare const CodeEditorInput: {
929
+ (props: TextInputProps): React.JSX.Element;
930
+ displayName: string;
931
+ };
932
+ /**
933
+ * Formulaire d'un bloc « Code embed » : les trois éditeurs de code, suivis d'un
934
+ * **aperçu live** rendu dans la même iframe sandboxée que le site.
935
+ *
936
+ * Le marketing voit immédiatement le résultat (une `div` stylée en CSS
937
+ * s'affiche vraiment), sans quitter le Studio ni publier.
938
+ */
939
+ export declare function CodeEmbedInput(props: ObjectInputProps): React.JSX.Element;
892
940
  interface KitUpdate {
893
941
  current: string;
894
942
  latest: string | null;
@@ -1059,7 +1107,7 @@ export declare function ActorName(props: {
1059
1107
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1060
1108
  * le vérifie.
1061
1109
  */
1062
- export declare const KIT_VERSION = "2.45.0";
1110
+ export declare const KIT_VERSION = "2.47.0";
1063
1111
  /**
1064
1112
  * Données de la page proposées comme colonnes.
1065
1113
  *
@@ -1555,5 +1603,5 @@ export declare const NCF_HISTORY_TOOL = "ncf-history";
1555
1603
  export declare const NCF_DESIGN_SYSTEM_TOOL = "ncf-design-system";
1556
1604
  export declare const NCF_TOOL_NAMES: readonly ["ncf-pages", "ncf-components", "ncf-history", "ncf-design-system"];
1557
1605
  export declare const ncfKit: import("sanity").Plugin<NcfKitConfig>;
1558
- export { type AddColumnInput, type Annotation, type AnnotationsState, type BlockOccurrence, type BlockTypeInfo, type BoardEdge, type BoardGraph, type BoardLayoutState, type BoardNode, CONTENT_SCAN_LIMIT as OCCURRENCE_SCAN_LIMIT, type Change, type ChangeKind, type CollectedLinks, type ColorBy, type ColorOptions, type ConfigIssue, type CrossLanguageReport, DEFAULT_COMPONENT_DEFAULTS_TYPE, type DeriveOptions, type GroupBy, type GroupOptions, type HistoryDetail, type HistoryEvent, type IssueLevel, type KitContextValue, type KitUpdate, type LayoutMode, type MainDocumentRoute, type MergedDoc, type NcfBoardTag, type NcfComponentPreviewConfig, type NcfDocumentColumn, type NcfEnvironment, type NcfHistoryConfig, type NcfI18nConfig, type NcfInternalField, type NcfInternalFieldOption, type NcfKitConfig, type NcfPageTypeConfig, type NcfPageTypeInput, type NcfToolName, type NcfToolsConfig, type NodeLayout, type NodePosition, type OccurrenceInput, type OccurrencePage, type OccurrencesState, type PageContent, type PageContentsState, type PageDoc, type PageFilters, type PageRow, type PageStatus, type PagesState, type PathInput, type Positioned, type PresentationOptions, type PreviewGrant, type PreviewPerspective, type PreviewTargetState, type ProjectStatus, type Registration, type ResolvedComponentPreview, type ResolvedDocumentColumn, type ResolvedHistory, type ResolvedI18n, type ResolvedKitConfig, type ResolvedPageType, type RowColor, type RowGroup, type SchemaFieldLike, type SchemaTypeLike, type SectionLayout, type SectionMapNode, type SectionOrder, type SectionsMapOptions, type Segment, type SiteRoutesRegistry, type SortDirection, type SortKey, type ThumbnailInput, type VersionedDoc, componentDefaultsMainDocument, componentDefaultsMainDocuments, defaultsFieldName, defineComponentDefaults, fixCrossLanguageReferences, pageTypesFromSiteRoutes, requiredUnlessDefault, requiredUnlessDefaultFor, withSameLanguageReferences };
1606
+ export { type AddColumnInput, type Annotation, type AnnotationsState, type BlockOccurrence, type BlockTypeInfo, type BoardEdge, type BoardGraph, type BoardLayoutState, type BoardNode, CONTENT_SCAN_LIMIT as OCCURRENCE_SCAN_LIMIT, type Change, type ChangeKind, type CodeEmbedTypeOptions, type CodeLanguage, type CollectedLinks, type ColorBy, type ColorOptions, type ConfigIssue, type CrossLanguageReport, DEFAULT_COMPONENT_DEFAULTS_TYPE, type DeriveOptions, type GroupBy, type GroupOptions, type HistoryDetail, type HistoryEvent, type IssueLevel, type KitContextValue, type KitUpdate, type LayoutMode, type MainDocumentRoute, type MergedDoc, type NcfBoardTag, type NcfComponentPreviewConfig, type NcfDocumentColumn, type NcfEnvironment, type NcfHistoryConfig, type NcfI18nConfig, type NcfInternalField, type NcfInternalFieldOption, type NcfKitConfig, type NcfPageTypeConfig, type NcfPageTypeInput, type NcfToolName, type NcfToolsConfig, type NodeLayout, type NodePosition, type OccurrenceInput, type OccurrencePage, type OccurrencesState, type PageContent, type PageContentsState, type PageDoc, type PageFilters, type PageRow, type PageStatus, type PagesState, type PathInput, type Positioned, type PresentationOptions, type PreviewGrant, type PreviewPerspective, type PreviewTargetState, type ProjectStatus, type Registration, type ResolvedComponentPreview, type ResolvedDocumentColumn, type ResolvedHistory, type ResolvedI18n, type ResolvedKitConfig, type ResolvedPageType, type RowColor, type RowGroup, type SchemaFieldLike, type SchemaTypeLike, type SectionLayout, type SectionMapNode, type SectionOrder, type SectionsMapOptions, type Segment, type SiteRoutesRegistry, type SortDirection, type SortKey, type ThumbnailInput, type VersionedDoc, componentDefaultsMainDocument, componentDefaultsMainDocuments, defaultsFieldName, defineComponentDefaults, fixCrossLanguageReferences, pageTypesFromSiteRoutes, requiredUnlessDefault, requiredUnlessDefaultFor, withSameLanguageReferences };
1559
1607
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { A as DEFAULT_PAGE_BUILDER_FIELD, C as toUrl, D as DEFAULT_COMPONENT_PREVIEW, E as DEFAULT_BOARD_TAGS, M as DEFAULT_TITLE_FIELD, O as DEFAULT_I18N, S as toPath, T as resolveConfig, _ as redirectMapOf, a as componentDefaultsMainDocument, b as parentPath, c as defineComponentDefaults, d as syncTranslationRedirects, f as translationRedirectId, i as DEFAULT_COMPONENT_DEFAULTS_TYPE, j as DEFAULT_SLUG_FIELD, k as DEFAULT_INTERNAL_FIELDS, l as requiredUnlessDefault, m as finalPath, n as withSameLanguageReferences, o as componentDefaultsMainDocuments, p as translationRedirectOptions, r as pageTypesFromSiteRoutes, s as defaultsFieldName, t as fixCrossLanguageReferences, u as requiredUnlessDefaultFor, v as depth, w as normalizePath, x as segments, y as pageTypeFor } from "./fixCrossLanguageReferences-CQGzpNii.js";
2
+ import { t as NcfCodeEmbed } from "./CodeEmbedFrame-DWsj6Z8T.js";
2
3
  import { createContext, createElement, forwardRef, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
3
4
  import { ToolLink, defineField, definePlugin, defineType, pathToString, set, unset, useClient, useCurrentUser, useFormValue, usePerspective, useSchema, useSetPerspective, useUser, useWorkspace } from "sanity";
4
5
  import { ClockIcon } from "@sanity/icons/Clock";
@@ -43,6 +44,12 @@ import { useToast } from "@sanity/ui/toast";
43
44
  import { createPortal } from "react-dom";
44
45
  import { TabletDeviceIcon } from "@sanity/icons/TabletDevice";
45
46
  import { PanelRightIcon } from "@sanity/icons/PanelRight";
47
+ import { CodeBlockIcon } from "@sanity/icons";
48
+ import CodeMirror from "@uiw/react-codemirror";
49
+ import { oneDark } from "@codemirror/theme-one-dark";
50
+ import { html } from "@codemirror/lang-html";
51
+ import { css } from "@codemirror/lang-css";
52
+ import { javascript } from "@codemirror/lang-javascript";
46
53
  const isAbsoluteHttpUrl = (value) => {
47
54
  try {
48
55
  let url = new URL(value);
@@ -977,6 +984,20 @@ function pathOf$1(url) {
977
984
  return url.startsWith("/") ? url : `/${url}`;
978
985
  }
979
986
  }
987
+ /**
988
+ * Chemin de la page actuellement montrée dans Presentation.
989
+ *
990
+ * Presentation garde l'adresse prévisualisée dans le paramètre `preview` de
991
+ * l'URL du Studio — une URL complète (`https://site.fr/a-propos`) ou un chemin.
992
+ * Le lanceur s'en sert pour rouvrir la MÊME page sur un autre environnement,
993
+ * au lieu de retomber sur l'accueil.
994
+ *
995
+ * Rend `null` hors de Presentation, ou si le paramètre est absent.
996
+ */
997
+ function previewPathFromLocation(search) {
998
+ let preview = new URLSearchParams(search).get("preview");
999
+ return preview ? pathOf$1(preview) : null;
1000
+ }
980
1001
  /** Lien d'édition classique, pour les cas où l'on veut le formulaire. */
981
1002
  function editIntentPath(id, type) {
982
1003
  return `/intent/edit/id=${encodeURIComponent(id)};type=${encodeURIComponent(type)}/`;
@@ -1260,7 +1281,7 @@ function explainGrantError(error) {
1260
1281
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1261
1282
  * le vérifie.
1262
1283
  */
1263
- const KIT_VERSION = "2.45.0";
1284
+ const KIT_VERSION = "2.47.0";
1264
1285
  /**
1265
1286
  * Signale ce Studio au service du kit, une fois par montage.
1266
1287
  *
@@ -1603,7 +1624,7 @@ function useKitUpdate() {
1603
1624
  !controller.signal.aborted && body?.version && setLatest(body.version);
1604
1625
  }).catch(() => {}), () => controller.abort();
1605
1626
  }, []);
1606
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.45.0") > 0);
1627
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.47.0") > 0);
1607
1628
  return {
1608
1629
  current: KIT_VERSION,
1609
1630
  latest,
@@ -1861,13 +1882,17 @@ function NcfPreviewLauncher(props) {
1861
1882
  }), /* @__PURE__ */ jsx(NcfKitUpdate, { inline: props.context === "topbar" })]
1862
1883
  });
1863
1884
  let openInStudio = (environment, perspective) => {
1864
- let target = editableEnvironment(environment, environments, config.previewUrl) ?? environment, shown = isPublicEnvironment(environment, config.previewUrl) ? "published" : perspective, path = presentationPath(target.url, {
1885
+ let target = editableEnvironment(environment, environments, config.previewUrl) ?? environment, shown = isPublicEnvironment(environment, config.previewUrl) ? "published" : perspective, path = presentationPath((typeof window > "u" ? null : previewPathFromLocation(window.location.search)) ?? target.url, {
1865
1886
  environment: target,
1866
1887
  perspective: shown
1867
1888
  });
1868
1889
  path && router.navigateUrl({ path });
1869
1890
  }, openOnline = (environment, perspective) => {
1870
- open(environment, { perspective });
1891
+ let current = typeof window > "u" ? null : previewPathFromLocation(window.location.search);
1892
+ open(environment, {
1893
+ perspective,
1894
+ path: current
1895
+ });
1871
1896
  }, inline = props.context === "topbar";
1872
1897
  return /* @__PURE__ */ jsxs(Flex, {
1873
1898
  align: inline ? "center" : "stretch",
@@ -1975,6 +2000,16 @@ function createPreviewLauncher(config, issues) {
1975
2000
  };
1976
2001
  }
1977
2002
  /**
2003
+ * Posé sur `studio.components.layout` : rend le Studio tel quel, et ajoute la
2004
+ * feuille de style. Un seul `<style>` pour tout le Studio.
2005
+ */
2006
+ function HelpTextStyle(props) {
2007
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("style", {
2008
+ "data-ncf": "help-text",
2009
+ children: "\n[id^=\"desc_\"] {\n font-size: 0.72rem !important;\n font-style: italic !important;\n line-height: 1.45 !important;\n opacity: 0.72;\n}\n"
2010
+ }), props.renderDefault(props)] });
2011
+ }
2012
+ /**
1978
2013
  * RÈGLE D'OR : URL finales. Le site (starter : /api/url-check) appelle chaque URL de
1979
2014
  * sa sitemap et chaque redirection du Studio ; ce bandeau prévient l'équipe quand
1980
2015
  * une page de la sitemap répond 301 / 308 / 404, ou qu'une redirection fait deux
@@ -8392,6 +8427,24 @@ function shortValue(value, max = 32) {
8392
8427
  return d.length > max ? `${d.slice(0, max - 1)}…` : d;
8393
8428
  }
8394
8429
  /**
8430
+ * Un champ hérité doit-il afficher la valeur par défaut **pré-sélectionnée**
8431
+ * dans son contrôle ?
8432
+ *
8433
+ * Oui pour un choix (liste d'options : style, taille, position, niveau de
8434
+ * titre…) et pour une case à cocher : l'éditeur voit ce qui s'appliquera, au
8435
+ * lieu d'un contrôle vide doublé d'une mention. La valeur n'est pas écrite —
8436
+ * le champ reste vide, donc hérité ; choisir autre chose l'emporte et fait
8437
+ * apparaître la pastille de réinitialisation.
8438
+ *
8439
+ * Non pour le texte libre (déjà traité par un placeholder grisé) ni pour les
8440
+ * objets, listes et images (pas de « valeur sélectionnée » à montrer).
8441
+ */
8442
+ function preselectsDefault(schemaType, inherited) {
8443
+ if (isEmptyValue(inherited)) return !1;
8444
+ let jt = schemaType?.jsonType;
8445
+ return jt === "boolean" || (jt === "string" || jt === "number") && (schemaType?.options?.list?.length ?? 0) > 0;
8446
+ }
8447
+ /**
8395
8448
  * Pastille bleue sur tout champ d'une instance de composant dont la valeur
8396
8449
  * DIFFÈRE de la valeur par défaut du composant (valeur par défaut vide comprise),
8397
8450
  * éléments de liste compris (comparés à l'élément de même rang). Au survol, elle
@@ -8437,7 +8490,10 @@ function createOverrideInput(config) {
8437
8490
  setTranslating(!1);
8438
8491
  }
8439
8492
  }
8440
- }, router = useRouter(), inherits = isEmptyValue(inputProps.value) && !isEmptyValue(inherited), st = inputProps.schemaType, freeText = (st.jsonType === "string" || st.jsonType === "number") && !st.options?.list?.length, placeholder = inherits && freeText ? inheritedPlaceholder(inherited) : null, shown = placeholder === null ? inputProps : {
8493
+ }, router = useRouter(), inherits = isEmptyValue(inputProps.value) && !isEmptyValue(inherited), st = inputProps.schemaType, freeText = (st.jsonType === "string" || st.jsonType === "number") && !st.options?.list?.length, placeholder = inherits && freeText ? inheritedPlaceholder(inherited) : null, preselect = inherits && placeholder === null && preselectsDefault(st, inherited), shown = placeholder === null ? preselect ? {
8494
+ ...inputProps,
8495
+ value: inherited
8496
+ } : inputProps : {
8441
8497
  ...inputProps,
8442
8498
  elementProps: {
8443
8499
  ...inputProps.elementProps,
@@ -8483,7 +8539,7 @@ function createOverrideInput(config) {
8483
8539
  })
8484
8540
  ]
8485
8541
  }),
8486
- inherits && placeholder === null && /* @__PURE__ */ jsxs(Flex, {
8542
+ inherits && placeholder === null && !preselect && /* @__PURE__ */ jsxs(Flex, {
8487
8543
  align: "center",
8488
8544
  gap: 2,
8489
8545
  marginTop: 2,
@@ -10022,6 +10078,154 @@ function ncfPresentationComponents(options) {
10022
10078
  unstable_header: { component: NcfPresentationHeader }
10023
10079
  };
10024
10080
  }
10081
+ function extensionsFor(language) {
10082
+ return language === "css" ? [css()] : language === "js" ? [javascript()] : [html()];
10083
+ }
10084
+ /**
10085
+ * Éditeur de code sombre (CodeMirror, thème One Dark) pour un champ texte.
10086
+ *
10087
+ * Interface « type éditeur de code » demandée par le marketing : coloration
10088
+ * syntaxique, numéros de ligne, fond sombre. Le langage est figé par
10089
+ * {@link codeEditorInput} au moment de câbler le champ.
10090
+ */
10091
+ function CodeEditor(props, language) {
10092
+ let { value = "", onChange, readOnly, elementProps } = props, handleChange = useCallback((next) => {
10093
+ onChange(next ? set(next) : unset());
10094
+ }, [onChange]);
10095
+ return /* @__PURE__ */ jsx(Card, {
10096
+ radius: 2,
10097
+ overflow: "hidden",
10098
+ border: !0,
10099
+ id: elementProps.id,
10100
+ children: /* @__PURE__ */ jsx(CodeMirror, {
10101
+ value,
10102
+ theme: oneDark,
10103
+ editable: !readOnly,
10104
+ readOnly,
10105
+ extensions: extensionsFor(language),
10106
+ onChange: handleChange,
10107
+ onFocus: elementProps.onFocus,
10108
+ onBlur: elementProps.onBlur,
10109
+ basicSetup: {
10110
+ lineNumbers: !0,
10111
+ foldGutter: !1,
10112
+ highlightActiveLine: !readOnly,
10113
+ autocompletion: !1
10114
+ },
10115
+ minHeight: "140px",
10116
+ maxHeight: "520px",
10117
+ style: { fontSize: 13 }
10118
+ })
10119
+ });
10120
+ }
10121
+ /**
10122
+ * Fabrique l'input d'un champ de code pour un langage donné. À poser sur un
10123
+ * champ `text` : `components: {input: codeEditorInput('css')}`.
10124
+ */
10125
+ function codeEditorInput(language) {
10126
+ function CodeEditorInput(props) {
10127
+ return CodeEditor(props, language);
10128
+ }
10129
+ return CodeEditorInput.displayName = `CodeEditorInput(${language})`, CodeEditorInput;
10130
+ }
10131
+ /** Input HTML prêt à l'emploi (le plus courant). */
10132
+ const CodeEditorInput = codeEditorInput("html");
10133
+ /**
10134
+ * Formulaire d'un bloc « Code embed » : les trois éditeurs de code, suivis d'un
10135
+ * **aperçu live** rendu dans la même iframe sandboxée que le site.
10136
+ *
10137
+ * Le marketing voit immédiatement le résultat (une `div` stylée en CSS
10138
+ * s'affiche vraiment), sans quitter le Studio ni publier.
10139
+ */
10140
+ function CodeEmbedInput(props) {
10141
+ let value = props.value ?? {}, hasContent = !!(value.html || value.css || value.js);
10142
+ return /* @__PURE__ */ jsxs(Stack, {
10143
+ gap: 4,
10144
+ children: [props.renderDefault(props), hasContent ? /* @__PURE__ */ jsxs(Stack, {
10145
+ gap: 2,
10146
+ children: [/* @__PURE__ */ jsx(Text, {
10147
+ size: 1,
10148
+ muted: !0,
10149
+ weight: "semibold",
10150
+ children: "Aperçu"
10151
+ }), /* @__PURE__ */ jsx(Card, {
10152
+ border: !0,
10153
+ radius: 2,
10154
+ overflow: "hidden",
10155
+ tone: "transparent",
10156
+ children: /* @__PURE__ */ jsx(NcfCodeEmbed, {
10157
+ html: value.html,
10158
+ css: value.css,
10159
+ js: value.js,
10160
+ minHeight: 60
10161
+ })
10162
+ })]
10163
+ }) : null]
10164
+ });
10165
+ }
10166
+ /**
10167
+ * Type d'objet « Code embed » : HTML, CSS et JS libres, éditables dans une
10168
+ * interface sombre à coloration syntaxique, rendus dans une iframe sandboxée
10169
+ * (aperçu live dans le Studio, même rendu sur le site via {@link NcfCodeEmbed}).
10170
+ *
10171
+ * Réutilisable partout où un objet est accepté : section de page, article de
10172
+ * blog (`articleContent`), texte riche (`blockContent`).
10173
+ *
10174
+ * ```ts
10175
+ * import {defineCodeEmbedType} from '@nocode-factory/sanity-kit'
10176
+ * export const codeEmbed = defineCodeEmbedType()
10177
+ * ```
10178
+ */
10179
+ function defineCodeEmbedType(options = {}) {
10180
+ let { name = "codeEmbed", title = "Code embed" } = options;
10181
+ return defineType({
10182
+ name,
10183
+ title,
10184
+ type: "object",
10185
+ icon: CodeBlockIcon,
10186
+ components: { input: CodeEmbedInput },
10187
+ fields: [
10188
+ defineField({
10189
+ name: "html",
10190
+ title: "HTML",
10191
+ type: "text",
10192
+ rows: 8,
10193
+ components: { input: codeEditorInput("html") }
10194
+ }),
10195
+ defineField({
10196
+ name: "css",
10197
+ title: "CSS",
10198
+ type: "text",
10199
+ rows: 6,
10200
+ components: { input: codeEditorInput("css") }
10201
+ }),
10202
+ defineField({
10203
+ name: "js",
10204
+ title: "JavaScript",
10205
+ type: "text",
10206
+ rows: 6,
10207
+ components: { input: codeEditorInput("js") }
10208
+ })
10209
+ ],
10210
+ preview: {
10211
+ select: {
10212
+ html: "html",
10213
+ css: "css",
10214
+ js: "js"
10215
+ },
10216
+ prepare({ html, css, js }) {
10217
+ return {
10218
+ title: "Code embed",
10219
+ subtitle: [
10220
+ html && "HTML",
10221
+ css && "CSS",
10222
+ js && "JS"
10223
+ ].filter(Boolean).join(" · ") || "Vide"
10224
+ };
10225
+ }
10226
+ }
10227
+ });
10228
+ }
10025
10229
  const SAFE = /^[A-Za-z0-9_.-]+$/, quote = (value) => JSON.stringify(value);
10026
10230
  /**
10027
10231
  * Presentation : le document du panneau de droite est TOUJOURS celui de la page
@@ -10176,7 +10380,10 @@ const ncfKit = definePlugin((options) => {
10176
10380
  newDocumentOptions: (prev) => prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
10177
10381
  actions: (prev, context) => config.pageTypeNames.includes(context.schemaType) ? prev.map((action) => action.action === "unpublish" ? config.i18n ? createRemoveFromSite(config) : RemoveFromSiteAction : action.action === "publish" && config.i18n ? withTranslationRedirects(withPropagation(action, config, void 0, { allowCreate: !0 }), config) : action.action === "delete" && config.i18n ? withTranslationDelete(action, config) : action) : context.schemaType === config.componentPreview.defaultsType && config.i18n ? prev.map((action) => action.action === "publish" ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action.action === "delete" ? withTranslationDelete(action, config, config.i18n?.defaultsSourceLocale) : action) : config.i18n && !isKitType(context.schemaType) && hasLanguageField(context.schema.get(context.schemaType), config.i18n.field) ? prev.map((action) => action.action === "publish" ? withPropagation(action, config, void 0, { allowCreate: !0 }) : action.action === "delete" ? withTranslationDelete(action, config) : action.action === "unpublish" ? createRemoveFromSite(config) : action) : prev
10178
10382
  },
10179
- studio: { components: { toolMenu: createPreviewLauncher(config, issues) } },
10383
+ studio: { components: {
10384
+ toolMenu: createPreviewLauncher(config, issues),
10385
+ layout: HelpTextStyle
10386
+ } },
10180
10387
  form: { components: { input: createKitInput(config) } }
10181
10388
  };
10182
10389
  });
@@ -10185,6 +10392,6 @@ function hasLanguageField(schemaType, field) {
10185
10392
  let fields = schemaType?.fields;
10186
10393
  return Array.isArray(fields) && fields.some((f) => f?.name === field);
10187
10394
  }
10188
- export { ANNOTATION_TYPE, ActorName, BOARD_LAYOUT_ID, BOARD_LAYOUT_TYPE, BRAIN_NODE_SIZE, BoardLayoutProvider, COLUMN_TYPE, CONTENT_SCAN_LIMIT, CONTENT_SCAN_LIMIT as OCCURRENCE_SCAN_LIMIT, CUSTOM_ENVIRONMENT_ID, DATA_PREFIX, DEFAULT_BOARD_TAGS, DEFAULT_COMPONENT_DEFAULTS_TYPE, DEFAULT_COMPONENT_PREVIEW, DEFAULT_I18N, DEFAULT_INTERNAL_FIELDS, DEFAULT_MORE_TOOLS, DEFAULT_PAGE_BUILDER_FIELD, DEFAULT_SLUG_FIELD, DEFAULT_TITLE_FIELD, KIT_API_VERSION, KIT_VERSION, NCF_COMPONENTS_TOOL, NCF_DESIGN_SYSTEM_TOOL, NCF_HIDDEN_TYPES, NCF_HISTORY_TOOL, NCF_MORE_TOOL, NCF_PAGES_TOOL, NCF_TOOL_NAMES, NODE_FIELD_TYPE, NODE_HEIGHT, NODE_WIDTH, NcfKitUpdate, NcfPreviewHeader, NcfPreviewLauncher, PERSPECTIVES, PROJECTION, SECTION_NODE_TYPE, STATUS_COLORS, STATUS_LABELS, SharePreview, UNSET_LABEL, addColumn, addColumnOption, announce, applySavedPositions, baseId, blockName, blockTypesFromSchema, buildContentsQuery, buildLinkGraph, buildPageRows, buildPagesQuery, collectLinks, collectOccurrences, colorForRow, colorFromString, columnId, compareVersions, componentDefaultsMainDocument, componentDefaultsMainDocuments, createPreviewLauncher, customEnvironment, defaultNodeSize, defaultsFieldName, defineComponentDefaults, depth, deriveDocumentColumns, diffDocuments, diffWords, editIntentPath, explainGrantError, fallbackLayout, fetchDetail, fetchTimeline, fillTemplate, filterRows, fixCrossLanguageReferences, flatten, formatDocumentValue, groupPageRows, groupValue, hasBlockingIssue, humanizeBlockName, isDraftId, isKitType, isPrerelease, isSafeColumnKey, isSafeFieldPath, isTextChange, isVersionId, issuesForTool, keyForPath, kitSchemaTypes, layoutGraph, layoutSectionsMap, localesInRows, mergeVersions, missingPageTypes, moveColumn, ncfAllowedOrigins, ncfKit, ncfMainDocuments, ncfPresentationComponents, ncfPreviewComponents, normalizeInternalPath, normalizePath, occurrencesForTypes, pageThumbnailUrl, pageTypeFor, pageTypesFromSiteRoutes, pageTypesWithoutBuilder, parentPath, presentationPath, pruneSavedPositions, releaseId, removeColumn, renameColumn, requestPreviewGrant, requiredUnlessDefault, requiredUnlessDefaultFor, resolveColorBy, resolveConfig, segments, slugKey, sortRows, summarize, toKebabCase, toPath, toUrl, topLevelBlockCount, uniqueColumnId, upsertLayout, urlOn, useAnnotations, useBoardLayout, useDocumentColumns, useHistory, useInternalColumns, useKitClient, useKitConfig, useKitContext, useKitUpdate, useOccurrences, usePageContents, usePages, usePreviewTarget, useRegistration, validateConfig, withAlpha, withMoreTool, withSameLanguageReferences };
10395
+ export { ANNOTATION_TYPE, ActorName, BOARD_LAYOUT_ID, BOARD_LAYOUT_TYPE, BRAIN_NODE_SIZE, BoardLayoutProvider, COLUMN_TYPE, CONTENT_SCAN_LIMIT, CONTENT_SCAN_LIMIT as OCCURRENCE_SCAN_LIMIT, CUSTOM_ENVIRONMENT_ID, CodeEditorInput, CodeEmbedInput, DATA_PREFIX, DEFAULT_BOARD_TAGS, DEFAULT_COMPONENT_DEFAULTS_TYPE, DEFAULT_COMPONENT_PREVIEW, DEFAULT_I18N, DEFAULT_INTERNAL_FIELDS, DEFAULT_MORE_TOOLS, DEFAULT_PAGE_BUILDER_FIELD, DEFAULT_SLUG_FIELD, DEFAULT_TITLE_FIELD, HelpTextStyle, KIT_API_VERSION, KIT_VERSION, NCF_COMPONENTS_TOOL, NCF_DESIGN_SYSTEM_TOOL, NCF_HIDDEN_TYPES, NCF_HISTORY_TOOL, NCF_MORE_TOOL, NCF_PAGES_TOOL, NCF_TOOL_NAMES, NODE_FIELD_TYPE, NODE_HEIGHT, NODE_WIDTH, NcfKitUpdate, NcfPreviewHeader, NcfPreviewLauncher, PERSPECTIVES, PROJECTION, SECTION_NODE_TYPE, STATUS_COLORS, STATUS_LABELS, SharePreview, UNSET_LABEL, addColumn, addColumnOption, announce, applySavedPositions, baseId, blockName, blockTypesFromSchema, buildContentsQuery, buildLinkGraph, buildPageRows, buildPagesQuery, codeEditorInput, collectLinks, collectOccurrences, colorForRow, colorFromString, columnId, compareVersions, componentDefaultsMainDocument, componentDefaultsMainDocuments, createPreviewLauncher, customEnvironment, defaultNodeSize, defaultsFieldName, defineCodeEmbedType, defineComponentDefaults, depth, deriveDocumentColumns, diffDocuments, diffWords, editIntentPath, explainGrantError, fallbackLayout, fetchDetail, fetchTimeline, fillTemplate, filterRows, fixCrossLanguageReferences, flatten, formatDocumentValue, groupPageRows, groupValue, hasBlockingIssue, humanizeBlockName, isDraftId, isKitType, isPrerelease, isSafeColumnKey, isSafeFieldPath, isTextChange, isVersionId, issuesForTool, keyForPath, kitSchemaTypes, layoutGraph, layoutSectionsMap, localesInRows, mergeVersions, missingPageTypes, moveColumn, ncfAllowedOrigins, ncfKit, ncfMainDocuments, ncfPresentationComponents, ncfPreviewComponents, normalizeInternalPath, normalizePath, occurrencesForTypes, pageThumbnailUrl, pageTypeFor, pageTypesFromSiteRoutes, pageTypesWithoutBuilder, parentPath, presentationPath, pruneSavedPositions, releaseId, removeColumn, renameColumn, requestPreviewGrant, requiredUnlessDefault, requiredUnlessDefaultFor, resolveColorBy, resolveConfig, segments, slugKey, sortRows, summarize, toKebabCase, toPath, toUrl, topLevelBlockCount, uniqueColumnId, upsertLayout, urlOn, useAnnotations, useBoardLayout, useDocumentColumns, useHistory, useInternalColumns, useKitClient, useKitConfig, useKitContext, useKitUpdate, useOccurrences, usePageContents, usePages, usePreviewTarget, useRegistration, validateConfig, withAlpha, withMoreTool, withSameLanguageReferences };
10189
10396
 
10190
10397
  //# sourceMappingURL=index.js.map