@nocode-factory/sanity-kit 2.6.2 → 2.8.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/dist/index.d.ts CHANGED
@@ -51,6 +51,14 @@ interface NcfComponentPreviewConfig {
51
51
  anchor?: string;
52
52
  /** Chemin de la capture, relatif à `previewUrl`. Gabarit : {name} / {kebab}. */
53
53
  thumbnail?: string;
54
+ /**
55
+ * Type du document des valeurs par défaut des composants (un champ par
56
+ * composant, nommé `{name}`). Présent dans le schéma : un clic sur un composant
57
+ * ouvre Presentation avec son rendu réel et ses valeurs par défaut côte à côte.
58
+ */
59
+ defaultsType?: string;
60
+ /** Page qui rend un composant seul, avec ses valeurs par défaut. Gabarit : {name} / {kebab}. */
61
+ live?: string;
54
62
  }
55
63
  /** Journal des modifications (phase 2). */
56
64
  interface NcfHistoryConfig {
@@ -218,6 +226,8 @@ interface ResolvedComponentPreview {
218
226
  path: string;
219
227
  anchor: string;
220
228
  thumbnail: string;
229
+ defaultsType: string;
230
+ live: string;
221
231
  }
222
232
  interface ResolvedKitConfig {
223
233
  pageTypes: ResolvedPageType[];
@@ -776,6 +786,17 @@ interface BlockOccurrence {
776
786
  count: number;
777
787
  /** Identifiants des documents où le bloc apparaît, sans doublon. */
778
788
  documentIds: string[];
789
+ /**
790
+ * Emplacement de chaque instance : document et chemin depuis la racine du
791
+ * champ page builder (`[{_key}]`, ou plus profond pour un bloc imbriqué).
792
+ * Sert à ouvrir le formulaire directement sur l'instance.
793
+ */
794
+ locations: {
795
+ documentId: string;
796
+ path: ({
797
+ _key: string;
798
+ } | string | number)[];
799
+ }[];
779
800
  }
780
801
  interface OccurrenceInput {
781
802
  _id: string;
@@ -1270,7 +1291,7 @@ export declare function ActorName(props: {
1270
1291
  * Version du kit, rapportée au service pour savoir quels projets tournent sur
1271
1292
  * quelle version. Tenue à jour avec `package.json`.
1272
1293
  */
1273
- export declare const KIT_VERSION = "2.6.2";
1294
+ export declare const KIT_VERSION = "2.8.0";
1274
1295
  /**
1275
1296
  * Données de la page proposées comme colonnes.
1276
1297
  *
@@ -1739,16 +1760,6 @@ export declare const NCF_PAGES_TOOL = "ncf-pages";
1739
1760
  export declare const NCF_COMPONENTS_TOOL = "ncf-components";
1740
1761
  export declare const NCF_HISTORY_TOOL = "ncf-history";
1741
1762
  export declare const NCF_TOOL_NAMES: readonly ["ncf-pages", "ncf-components", "ncf-history"];
1742
- /**
1743
- * Plugin Studio de NoCode Factory : Pages, Composants, Historique.
1744
- *
1745
- * ```ts
1746
- * plugins: [ncfKit({pageTypes: [{type: 'homePage', path: '/'}, 'page']})]
1747
- * ```
1748
- *
1749
- * La configuration est validée au démarrage. Une option invalide n'empêche
1750
- * pas le Studio de démarrer : l'onglet concerné affiche le détail à corriger.
1751
- */
1752
1763
  export declare const ncfKit: import("sanity").Plugin<NcfKitConfig>;
1753
1764
  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 DeriveOptions, type GroupBy, type GroupOptions, type HistoryDetail, type HistoryEvent, type IssueLevel, type KitContextValue, type KitUpdate, type LayoutMode, 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 };
1754
1765
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import { defineField, definePlugin, defineType, useClient, useCurrentUser, useSchema, useUser } from "sanity";
1
+ import { defineField, definePlugin, defineType, pathToString, unset, useClient, useCurrentUser, useFormValue, useSchema, useUser } from "sanity";
2
2
  import { ClockIcon } from "@sanity/icons/Clock";
3
3
  import { ComponentIcon } from "@sanity/icons/Component";
4
4
  import { DocumentsIcon } from "@sanity/icons/Documents";
5
5
  import { Badge, Box, Button, Card, Container, Flex, Grid, Select, Spinner, Stack, Tab, TabList, TabPanel, Text, TextArea, TextInput } from "@sanity/ui";
6
- import { createContext, memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
6
+ import { createContext, memo, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
7
7
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
8
  import { IntentLink, useRouter } from "sanity/router";
9
9
  import { EyeOpenIcon } from "@sanity/icons/EyeOpen";
@@ -30,6 +30,7 @@ import "@xyflow/react/dist/style.css";
30
30
  import { TrashIcon } from "@sanity/icons/Trash";
31
31
  import { RefreshIcon } from "@sanity/icons/Refresh";
32
32
  import { RestoreIcon } from "@sanity/icons/Restore";
33
+ import { Tooltip } from "@sanity/ui/tooltip";
33
34
  import { EllipsisHorizontalIcon } from "@sanity/icons/EllipsisHorizontal";
34
35
  const DEFAULT_PAGE_BUILDER_FIELD = "sections", DEFAULT_SLUG_FIELD = "slug", DEFAULT_TITLE_FIELD = "title", DEFAULT_NOINDEX_FIELDS = ["seo.noindex", "noindex"], DEFAULT_I18N = {
35
36
  field: "language",
@@ -39,7 +40,9 @@ const DEFAULT_PAGE_BUILDER_FIELD = "sections", DEFAULT_SLUG_FIELD = "slug", DEFA
39
40
  provider: "designSystemPage",
40
41
  path: "/design-system",
41
42
  anchor: "{name}",
42
- thumbnail: "/sections/{name}.png"
43
+ thumbnail: "/sections/{name}.png",
44
+ defaultsType: "componentDefaults",
45
+ live: "/design-system/composant?type={name}"
43
46
  }, DEFAULT_TOOLS = {
44
47
  pages: !0,
45
48
  components: !0,
@@ -128,7 +131,9 @@ function resolveConfig(input) {
128
131
  provider: input.componentPreview?.provider ?? DEFAULT_COMPONENT_PREVIEW.provider,
129
132
  path: input.componentPreview?.path ?? DEFAULT_COMPONENT_PREVIEW.path,
130
133
  anchor: input.componentPreview?.anchor ?? DEFAULT_COMPONENT_PREVIEW.anchor,
131
- thumbnail: input.componentPreview?.thumbnail ?? DEFAULT_COMPONENT_PREVIEW.thumbnail
134
+ thumbnail: input.componentPreview?.thumbnail ?? DEFAULT_COMPONENT_PREVIEW.thumbnail,
135
+ defaultsType: input.componentPreview?.defaultsType ?? DEFAULT_COMPONENT_PREVIEW.defaultsType,
136
+ live: input.componentPreview?.live ?? DEFAULT_COMPONENT_PREVIEW.live
132
137
  },
133
138
  serviceEndpoint: input.serviceEndpoint === !1 ? null : trimTrailingSlash((input.serviceEndpoint || "https://dkoxgivytgsmvqmjvmjt.supabase.co/functions/v1").trim()),
134
139
  history: input.history?.projectKey?.trim() ? {
@@ -1300,7 +1305,7 @@ function explainGrantError(error) {
1300
1305
  * Version du kit, rapportée au service pour savoir quels projets tournent sur
1301
1306
  * quelle version. Tenue à jour avec `package.json`.
1302
1307
  */
1303
- const KIT_VERSION = "2.6.2";
1308
+ const KIT_VERSION = "2.8.0";
1304
1309
  /**
1305
1310
  * Signale ce Studio au service du kit, une fois par montage.
1306
1311
  *
@@ -1611,7 +1616,7 @@ function useKitUpdate() {
1611
1616
  !controller.signal.aborted && body?.version && setLatest(body.version);
1612
1617
  }).catch(() => {}), () => controller.abort();
1613
1618
  }, []);
1614
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.6.2") > 0);
1619
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.8.0") > 0);
1615
1620
  return {
1616
1621
  current: KIT_VERSION,
1617
1622
  latest,
@@ -5539,29 +5544,36 @@ function pageTypesWithoutBuilder(schema, pageTypes, pageBuilderField) {
5539
5544
  /** Compte les blocs par type sur un ensemble de documents. */
5540
5545
  function collectOccurrences(docs, options) {
5541
5546
  let known = new Set(options.blockTypes), result = /* @__PURE__ */ new Map(), seenPerType = /* @__PURE__ */ new Map();
5542
- for (let doc of docs) walk(doc.blocks, (type) => {
5547
+ for (let doc of docs) walk(doc.blocks, (type, path) => {
5543
5548
  if (!known.has(type)) return;
5544
5549
  let entry = result.get(type) ?? {
5545
5550
  type,
5546
5551
  count: 0,
5547
- documentIds: []
5552
+ documentIds: [],
5553
+ locations: []
5548
5554
  };
5549
- entry.count += 1, result.set(type, entry);
5555
+ entry.count += 1, entry.locations.push({
5556
+ documentId: doc._id,
5557
+ path
5558
+ }), result.set(type, entry);
5550
5559
  let seen = seenPerType.get(type) ?? /* @__PURE__ */ new Set();
5551
5560
  seen.has(doc._id) || (seen.add(doc._id), seenPerType.set(type, seen), entry.documentIds.push(doc._id));
5552
5561
  });
5553
5562
  return result;
5554
5563
  }
5555
- /** Appelle `visit` pour chaque `_type` rencontré, à toute profondeur. */
5556
- function walk(value, visit) {
5564
+ /** Appelle `visit` pour chaque `_type` rencontré, à toute profondeur, avec son chemin. */
5565
+ function walk(value, visit, path = []) {
5557
5566
  if (Array.isArray(value)) {
5558
- for (let item of value) walk(item, visit);
5567
+ value.forEach((item, i) => {
5568
+ let key = item?._key;
5569
+ walk(item, visit, [...path, typeof key == "string" ? { _key: key } : i]);
5570
+ });
5559
5571
  return;
5560
5572
  }
5561
5573
  if (typeof value != "object" || !value) return;
5562
5574
  let type = value._type;
5563
- typeof type == "string" && visit(type);
5564
- for (let child of Object.values(value)) walk(child, visit);
5575
+ typeof type == "string" && visit(type, path);
5576
+ for (let [k, child] of Object.entries(value)) walk(child, visit, [...path, k]);
5565
5577
  }
5566
5578
  /**
5567
5579
  * Occurrences de tous les types connus, y compris ceux à zéro — ce sont eux
@@ -5572,7 +5584,8 @@ function occurrencesForTypes(docs, blockTypes) {
5572
5584
  return blockTypes.map((type) => counted.get(type) ?? {
5573
5585
  type,
5574
5586
  count: 0,
5575
- documentIds: []
5587
+ documentIds: [],
5588
+ locations: []
5576
5589
  });
5577
5590
  }
5578
5591
  /** Nombre de blocs de premier niveau d'une page (colonne « blocs » de la liste). */
@@ -5638,6 +5651,47 @@ function humanizeBlockName(type, namespace) {
5638
5651
  return [first.charAt(0).toUpperCase() + first.slice(1), ...rest].join(" ");
5639
5652
  }
5640
5653
  /**
5654
+ * Paramètres de l'intention qui ouvre un composant dans Presentation : son rendu
5655
+ * réel (page `live`) à gauche, le champ de ses valeurs par défaut à droite.
5656
+ * `documentId` : document des valeurs par défaut (créé à la première saisie s'il
5657
+ * n'existe pas encore).
5658
+ */
5659
+ function componentIntentParams(type, namespace, preview, documentId) {
5660
+ return {
5661
+ id: documentId.replace(/^drafts\./, ""),
5662
+ type: preview.defaultsType,
5663
+ mode: "presentation",
5664
+ path: blockName(type, namespace),
5665
+ preview: fillTemplate(preview.live, type, namespace)
5666
+ };
5667
+ }
5668
+ /**
5669
+ * Ouvre un composant : Presentation avec son rendu réel et ses valeurs par
5670
+ * défaut côte à côte. Sans document de valeurs par défaut dans le schéma : la
5671
+ * démo du design system dans un nouvel onglet. `null` : rien à ouvrir.
5672
+ * Partagé par la grille et la vue Map de l'onglet Composants.
5673
+ */
5674
+ function useOpenComponent() {
5675
+ let config = useKitConfig(), schema = useSchema(), router = useRouter(), client = useKitClient(), preview = config.componentPreview, hasDefaults = !!schema.get(preview.defaultsType), open = useCallback(async (type) => {
5676
+ if (!hasDefaults) {
5677
+ config.previewUrl && window.open(`${config.previewUrl}${preview.path}#${fillTemplate(preview.anchor, type, config.blockNamespace)}`, "_blank", "noopener");
5678
+ return;
5679
+ }
5680
+ let lang = config.i18n?.defaultLocale ?? null, id = await client.fetch(`*[_type == $type] | order(select($lang != null && ${config.i18n?.field ?? "language"} == $lang => 0, 1))[0]._id`, {
5681
+ type: preview.defaultsType,
5682
+ lang
5683
+ }).catch(() => null);
5684
+ router.navigateIntent("edit", componentIntentParams(type, config.blockNamespace, preview, id ?? preview.defaultsType));
5685
+ }, [
5686
+ hasDefaults,
5687
+ config,
5688
+ preview,
5689
+ client,
5690
+ router
5691
+ ]);
5692
+ return !hasDefaults && !config.previewUrl ? null : (type) => void open(type);
5693
+ }
5694
+ /**
5641
5695
  * Tuile d'un bloc dans la grille.
5642
5696
  *
5643
5697
  * Volontairement dépouillée : la capture, le nom, sa référence technique et
@@ -5646,14 +5700,20 @@ function humanizeBlockName(type, namespace) {
5646
5700
  * à le lire.
5647
5701
  */
5648
5702
  function BlockCard(props) {
5649
- let { block, occurrence, namespace, thumbnailUrl } = props, [failed, setFailed] = useState(!1), unused = occurrence.count === 0;
5703
+ let { block, occurrence, namespace, thumbnailUrl, onOpen } = props, [failed, setFailed] = useState(!1), unused = occurrence.count === 0;
5650
5704
  return /* @__PURE__ */ jsx(Card, {
5651
5705
  radius: 3,
5652
5706
  shadow: 1,
5653
5707
  padding: 0,
5708
+ as: onOpen ? "button" : void 0,
5709
+ onClick: onOpen,
5710
+ title: onOpen ? "Voir le composant en vrai et régler ses valeurs par défaut" : void 0,
5654
5711
  style: {
5655
5712
  height: "100%",
5656
- overflow: "hidden"
5713
+ overflow: "hidden",
5714
+ width: "100%",
5715
+ textAlign: "left",
5716
+ cursor: onOpen ? "pointer" : void 0
5657
5717
  },
5658
5718
  children: /* @__PURE__ */ jsxs(Stack, {
5659
5719
  gap: 0,
@@ -5746,7 +5806,8 @@ function layoutSectionsMap(blocks, occurrences, options = {}) {
5746
5806
  occurrence: byType.get(block.name) ?? {
5747
5807
  type: block.name,
5748
5808
  count: 0,
5749
- documentIds: []
5809
+ documentIds: [],
5810
+ locations: []
5750
5811
  }
5751
5812
  })).sort(compareBy(order)), max = Math.max(1, ...entries.map((entry) => entry.occurrence.count)), cell = maxSize + gap;
5752
5813
  return entries.map((entry, index) => {
@@ -5875,7 +5936,7 @@ const nodeTypes = {
5875
5936
  "--xy-attribution-background-color": "transparent"
5876
5937
  };
5877
5938
  function MapCanvas(props) {
5878
- let { blockTypes, occurrences, pagesById, order } = props, config = useKitConfig(), { sectionsByName, loading, saveError, saveSections, resetSections } = useBoardLayout(), [selected, setSelected] = useState(null), { screenToFlowPosition } = useReactFlow(), { annotations, add: addAnnotation, update: updateAnnotation, remove: removeAnnotation } = useAnnotations("sections"), [nodes, setNodes, onNodesChange] = useNodesState([]), preview = config.componentPreview, canPreview = preview.provider === "designSystemPage" && !!config.previewUrl, placed = useMemo(() => layoutSectionsMap(blockTypes, occurrences, { order }), [
5939
+ let { blockTypes, occurrences, pagesById, order } = props, config = useKitConfig(), { sectionsByName, loading, saveError, saveSections, resetSections } = useBoardLayout(), [selected, setSelected] = useState(null), { screenToFlowPosition } = useReactFlow(), { annotations, add: addAnnotation, update: updateAnnotation, remove: removeAnnotation } = useAnnotations("sections"), [nodes, setNodes, onNodesChange] = useNodesState([]), openComponent = useOpenComponent(), preview = config.componentPreview, canPreview = preview.provider === "designSystemPage" && !!config.previewUrl, placed = useMemo(() => layoutSectionsMap(blockTypes, occurrences, { order }), [
5879
5940
  blockTypes,
5880
5941
  occurrences,
5881
5942
  order
@@ -6102,24 +6163,40 @@ function MapCanvas(props) {
6102
6163
  muted: !0,
6103
6164
  children: selectedEntry.occurrence.count === 0 ? "Jamais utilisé sur le site." : `${selectedPages.length} page${selectedPages.length > 1 ? "s" : ""} · ${selectedEntry.occurrence.count} instance${selectedEntry.occurrence.count > 1 ? "s" : ""}`
6104
6165
  }),
6166
+ openComponent && /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Button, {
6167
+ mode: "default",
6168
+ tone: "primary",
6169
+ fontSize: 1,
6170
+ padding: 2,
6171
+ text: "Ouvrir le composant",
6172
+ title: "Rendu réel et valeurs par défaut, côte à côte",
6173
+ onClick: () => openComponent(selectedEntry.block.name)
6174
+ }) }),
6105
6175
  /* @__PURE__ */ jsx(Stack, {
6106
6176
  gap: 2,
6107
- children: selectedPages.map((page) => /* @__PURE__ */ jsx(IntentLink, {
6108
- intent: "edit",
6109
- params: {
6110
- id: page.id,
6111
- type: page.type
6112
- },
6113
- style: {
6114
- textDecoration: "none",
6115
- color: "inherit"
6116
- },
6117
- children: /* @__PURE__ */ jsx(Text, {
6118
- size: 1,
6119
- textOverflow: "ellipsis",
6120
- children: page.title
6121
- })
6122
- }, page.id))
6177
+ children: selectedPages.map((page) => {
6178
+ let here = selectedEntry.occurrence.locations.filter((l) => l.documentId === page.id), first = here[0], path = first ? pathToString([config.pageBuilderField, ...first.path]) : void 0;
6179
+ return /* @__PURE__ */ jsx(IntentLink, {
6180
+ intent: "edit",
6181
+ params: path ? {
6182
+ id: page.id,
6183
+ type: page.type,
6184
+ path
6185
+ } : {
6186
+ id: page.id,
6187
+ type: page.type
6188
+ },
6189
+ style: {
6190
+ textDecoration: "none",
6191
+ color: "inherit"
6192
+ },
6193
+ children: /* @__PURE__ */ jsxs(Text, {
6194
+ size: 1,
6195
+ textOverflow: "ellipsis",
6196
+ children: [page.title, here.length > 1 ? ` (${here.length} instances)` : ""]
6197
+ })
6198
+ }, page.id);
6199
+ })
6123
6200
  }),
6124
6201
  designSystemUrl && /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Button, {
6125
6202
  as: "a",
@@ -6141,7 +6218,7 @@ function MapCanvas(props) {
6141
6218
  size: 0,
6142
6219
  muted: !0,
6143
6220
  align: "center",
6144
- children: "Cliquer une section pour voir les pages qui l’utilisent."
6221
+ children: "Cliquer une section pour l’ouvrir (rendu réel et valeurs par défaut) ou aller à ses emplacements dans les pages."
6145
6222
  })
6146
6223
  })
6147
6224
  })]
@@ -6171,7 +6248,7 @@ const ORDERS = [
6171
6248
  }
6172
6249
  ];
6173
6250
  function ComponentsTool() {
6174
- let config = useKitConfig(), { blockTypes, occurrences, pagesById, truncated, scanned, loading, error, refresh } = useOccurrences(), [order, setOrder] = useState("type"), [view, setView] = useState("grid"), preview = config.componentPreview, canPreview = preview.provider === "designSystemPage" && !!config.previewUrl, cards = useMemo(() => {
6251
+ let config = useKitConfig(), { blockTypes, occurrences, pagesById, truncated, scanned, loading, error, refresh } = useOccurrences(), [order, setOrder] = useState("type"), [view, setView] = useState("grid"), preview = config.componentPreview, canPreview = preview.provider === "designSystemPage" && !!config.previewUrl, openComponent = useOpenComponent(), cards = useMemo(() => {
6175
6252
  let byName = new Map(blockTypes.map((b) => [b.name, b])), rows = occurrences.map((occurrence) => ({
6176
6253
  occurrence,
6177
6254
  block: byName.get(occurrence.type)
@@ -6311,7 +6388,8 @@ function ComponentsTool() {
6311
6388
  block,
6312
6389
  occurrence,
6313
6390
  namespace: config.blockNamespace,
6314
- thumbnailUrl: canPreview ? `${config.previewUrl}${fillTemplate(preview.thumbnail, block.name, config.blockNamespace)}` : null
6391
+ thumbnailUrl: canPreview ? `${config.previewUrl}${fillTemplate(preview.thumbnail, block.name, config.blockNamespace)}` : null,
6392
+ onOpen: openComponent ? () => openComponent(block.name) : void 0
6315
6393
  }, block.name))
6316
6394
  })
6317
6395
  ]
@@ -7067,6 +7145,199 @@ function HistoryTool() {
7067
7145
  })
7068
7146
  });
7069
7147
  }
7148
+ const store = /* @__PURE__ */ new Map();
7149
+ function entryFor(client, type, languageField, language) {
7150
+ let { projectId, dataset } = client.config(), key = `${projectId}:${dataset}:${type}:${language ?? ""}`, entry = store.get(key);
7151
+ entry || (entry = {
7152
+ value: null,
7153
+ listeners: /* @__PURE__ */ new Set(),
7154
+ stop: null
7155
+ }, store.set(key, entry));
7156
+ let e = entry;
7157
+ if (!e.stop) {
7158
+ let filter = `_type == $type && !(_id in path("drafts.**")) && ($language == null || !defined(${languageField}) || ${languageField} == $language)`, params = {
7159
+ type,
7160
+ language
7161
+ }, load = () => client.fetch(`*[${filter}][0]`, params).then((value) => {
7162
+ e.value = value, e.listeners.forEach((l) => l());
7163
+ }).catch(() => {});
7164
+ load();
7165
+ let sub = client.listen(`*[${filter}]`, params, {
7166
+ visibility: "query",
7167
+ includeResult: !1
7168
+ }).subscribe({ next: () => void load() });
7169
+ e.stop = () => sub.unsubscribe();
7170
+ }
7171
+ return [key, e];
7172
+ }
7173
+ function useComponentDefaults(client, type, languageField, language) {
7174
+ let [, entry] = entryFor(client, type, languageField, language), value = useSyncExternalStore((listener) => (entry.listeners.add(listener), () => {
7175
+ entry.listeners.delete(listener);
7176
+ }), () => entry.value);
7177
+ return useEffect(() => () => {
7178
+ entry.listeners.size === 0 && entry.stop && (entry.stop(), entry.stop = null);
7179
+ }, [entry]), value;
7180
+ }
7181
+ const LINK_TYPES = /* @__PURE__ */ new Set(["link", "cardLink"]);
7182
+ function isEmptyValue(value) {
7183
+ return value == null || value === "" || Array.isArray(value) && value.length === 0;
7184
+ }
7185
+ const isKeyed = (s) => typeof s == "object" && !!s && !Array.isArray(s) && typeof s._key == "string";
7186
+ /** Index du premier élément de liste du chemin (l'instance de composant dans le page builder), ou -1. */
7187
+ function firstKeyedIndex(path) {
7188
+ return path.findIndex(isKeyed);
7189
+ }
7190
+ /**
7191
+ * Chemin du champ à l'intérieur de l'instance (`['cta', 'style']`), si `instance`
7192
+ * est bien un composant de l'espace de noms et que le chemin ne traverse pas une
7193
+ * liste (une liste remplie remplace celle du défaut en entier : pas d'héritage
7194
+ * élément par élément).
7195
+ */
7196
+ function relativeFieldPath(path, index, instance, namespace) {
7197
+ let type = instance?._type;
7198
+ if (index < 0 || typeof type != "string" || !type.startsWith(namespace)) return null;
7199
+ let rel = path.slice(index + 1);
7200
+ return rel.length === 0 || !rel.every((s) => typeof s == "string") ? null : rel;
7201
+ }
7202
+ /** Valeur par défaut d'un champ de composant. */
7203
+ function defaultValueAt(defaults, blockShortName, relPath) {
7204
+ let node = defaults?.[blockShortName];
7205
+ for (let key of relPath) {
7206
+ if (!node || typeof node != "object") return;
7207
+ node = node[key];
7208
+ }
7209
+ return node;
7210
+ }
7211
+ /**
7212
+ * Le champ est-il un override ? Valeur propre à l'instance ET valeur par défaut
7213
+ * existante (sans défaut, il n'y a rien à surcharger). Le type d'un lien n'est
7214
+ * jamais signalé : il est prérempli par le Studio et ne compte que si le lien a
7215
+ * une cible.
7216
+ */
7217
+ function isOverride(local, inherited, field, parent) {
7218
+ if (isEmptyValue(local) || isEmptyValue(inherited)) return !1;
7219
+ let parentType = parent?._type;
7220
+ return !(field === "type" && typeof parentType == "string" && LINK_TYPES.has(parentType));
7221
+ }
7222
+ /** Égalité de valeurs (champ identique au défaut : override « figé »). */
7223
+ function sameValue(a, b) {
7224
+ if (a === b) return !0;
7225
+ let clean = (v) => Array.isArray(v) ? v.map(clean) : v && typeof v == "object" ? Object.fromEntries(Object.entries(v).filter(([k]) => !k.startsWith("_") || k === "_ref").sort(([x], [y]) => x.localeCompare(y)).map(([k, x]) => [k, clean(x)])) : v;
7226
+ return JSON.stringify(clean(a)) === JSON.stringify(clean(b));
7227
+ }
7228
+ /** Valeur par défaut lisible, pour la bulle de la pastille. */
7229
+ function describeValue(value) {
7230
+ if (typeof value == "string") return value.length > 60 ? `« ${value.slice(0, 57)}… »` : `« ${value} »`;
7231
+ if (typeof value == "boolean") return value ? "Oui" : "Non";
7232
+ if (typeof value == "number") return String(value);
7233
+ if (Array.isArray(value)) return `${value.length} élément${value.length > 1 ? "s" : ""}`;
7234
+ if (value && typeof value == "object") {
7235
+ let v = value;
7236
+ if (typeof v.token == "string") return `couleur ${v.token}`;
7237
+ if (typeof v.customHex == "string") return `couleur ${v.customHex}`;
7238
+ if (typeof v.label == "string") return `« ${v.label} »`;
7239
+ if (v.asset) return "une image";
7240
+ if (typeof v._ref == "string") return "un document";
7241
+ }
7242
+ return "une valeur";
7243
+ }
7244
+ /**
7245
+ * Pastille bleue sur un champ d'une instance de composant qui a sa PROPRE valeur
7246
+ * alors que le composant en a une par défaut (override). Au survol, elle devient
7247
+ * « Réinitialiser » : le champ est vidé et reprend la valeur par défaut du
7248
+ * composant. Seuls les champs « simples » en portent une (texte, nombre, choix,
7249
+ * case, liste, image, couleur...) ; un objet composé (lien) les porte sur ses
7250
+ * sous-champs.
7251
+ */
7252
+ function createOverrideInput(config) {
7253
+ let { defaultsType } = config.componentPreview, namespace = config.blockNamespace;
7254
+ function OverrideInput(props) {
7255
+ let schema = useSchema(), path = props.path, index = firstKeyedIndex(path), instance = useFormValue(index >= 0 ? path.slice(0, index + 1) : path), parent = useFormValue(path.length > 1 ? path.slice(0, -1) : path), rel = index >= 0 ? relativeFieldPath(path, index, instance, namespace) : null;
7256
+ if (!rel || !schema.get(defaultsType) || !carriesDot(props.schemaType)) return props.renderDefault(props);
7257
+ let shortName = blockName(instance._type, namespace);
7258
+ return /* @__PURE__ */ jsx(WithDot, {
7259
+ ...props,
7260
+ rel,
7261
+ shortName,
7262
+ parent
7263
+ });
7264
+ }
7265
+ function WithDot(props) {
7266
+ let { rel, shortName, parent, ...inputProps } = props, client = useKitClient(), languageField = config.i18n?.field ?? "language", language = useFormValue([languageField]) ?? null, inherited = defaultValueAt(useComponentDefaults(client, defaultsType, languageField, language), shortName, rel), field = rel[rel.length - 1] ?? "";
7267
+ return isOverride(inputProps.value, inherited, field, parent) ? /* @__PURE__ */ jsxs(Flex, {
7268
+ align: "flex-start",
7269
+ gap: 2,
7270
+ children: [/* @__PURE__ */ jsx(Box, {
7271
+ flex: 1,
7272
+ style: { minWidth: 0 },
7273
+ children: inputProps.renderDefault(inputProps)
7274
+ }), /* @__PURE__ */ jsx(OverrideDot, {
7275
+ inherited: describeValue(inherited),
7276
+ same: sameValue(inputProps.value, inherited),
7277
+ onReset: () => inputProps.onChange(unset())
7278
+ })]
7279
+ }) : inputProps.renderDefault(inputProps);
7280
+ }
7281
+ return OverrideInput;
7282
+ }
7283
+ function carriesDot(schemaType) {
7284
+ if (schemaType.jsonType !== "object") return !0;
7285
+ let t = schemaType;
7286
+ for (; t;) {
7287
+ if (t.components?.input || t.name === "image" || t.name === "file" || t.name === "reference") return !0;
7288
+ t = t.type;
7289
+ }
7290
+ return !1;
7291
+ }
7292
+ function OverrideDot(props) {
7293
+ let [hover, setHover] = useState(!1);
7294
+ return /* @__PURE__ */ jsx(Tooltip, {
7295
+ portal: !0,
7296
+ placement: "left",
7297
+ content: /* @__PURE__ */ jsx(Box, {
7298
+ padding: 2,
7299
+ style: { maxWidth: 260 },
7300
+ children: /* @__PURE__ */ jsxs(Text, {
7301
+ size: 1,
7302
+ children: [
7303
+ "Valeur propre à cette instance",
7304
+ props.same ? " (identique au défaut, mais figée : elle ne suivra pas ses changements)" : "",
7305
+ ". Défaut du composant : ",
7306
+ props.inherited,
7307
+ "."
7308
+ ]
7309
+ })
7310
+ }),
7311
+ children: /* @__PURE__ */ jsx("button", {
7312
+ type: "button",
7313
+ onClick: props.onReset,
7314
+ onMouseEnter: () => setHover(!0),
7315
+ onMouseLeave: () => setHover(!1),
7316
+ onFocus: () => setHover(!0),
7317
+ onBlur: () => setHover(!1),
7318
+ "aria-label": "Réinitialiser à la valeur par défaut du composant",
7319
+ style: {
7320
+ marginTop: 9,
7321
+ flex: "none",
7322
+ height: hover ? 22 : 10,
7323
+ minWidth: 10,
7324
+ padding: hover ? "0 8px" : 0,
7325
+ borderRadius: 999,
7326
+ border: 0,
7327
+ background: "var(--card-badge-primary-dot-color, #2276fc)",
7328
+ color: "#fff",
7329
+ fontSize: 11,
7330
+ fontWeight: 600,
7331
+ lineHeight: "22px",
7332
+ whiteSpace: "nowrap",
7333
+ cursor: "pointer",
7334
+ transform: hover ? "translateY(-6px)" : "none",
7335
+ transition: "all 120ms ease"
7336
+ },
7337
+ children: hover ? "↺ Réinitialiser" : ""
7338
+ })
7339
+ });
7340
+ }
7070
7341
  /**
7071
7342
  * `pageTypes` déduits du registre du starter, pour ne pas redire au kit ce que
7072
7343
  * le site sait déjà : l'accueil (chemin fixe `/`) et chaque collection avec
@@ -7230,6 +7501,16 @@ function NcfPreviewHeader(props) {
7230
7501
  function ncfPreviewComponents() {
7231
7502
  return { unstable_header: { component: NcfPreviewHeader } };
7232
7503
  }
7504
+ /**
7505
+ * Plugin Studio de NoCode Factory : Pages, Composants, Historique.
7506
+ *
7507
+ * ```ts
7508
+ * plugins: [ncfKit({pageTypes: [{type: 'homePage', path: '/'}, 'page']})]
7509
+ * ```
7510
+ *
7511
+ * La configuration est validée au démarrage. Une option invalide n'empêche
7512
+ * pas le Studio de démarrer : l'onglet concerné affiche le détail à corriger.
7513
+ */
7233
7514
  /** Noms des outils dans la barre du Studio. Exportés pour filtrer `tools`. */
7234
7515
  const NCF_PAGES_TOOL = "ncf-pages", NCF_COMPONENTS_TOOL = "ncf-components", NCF_HISTORY_TOOL = "ncf-history", NCF_TOOL_NAMES = [
7235
7516
  NCF_PAGES_TOOL,
@@ -7291,7 +7572,8 @@ const NCF_PAGES_TOOL = "ncf-pages", NCF_COMPONENTS_TOOL = "ncf-components", NCF_
7291
7572
  templates: (prev) => prev.filter((template) => !isKitType(template.schemaType))
7292
7573
  },
7293
7574
  document: { newDocumentOptions: (prev) => prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE) },
7294
- studio: { components: { toolMenu: createPreviewLauncher(config, issues) } }
7575
+ studio: { components: { toolMenu: createPreviewLauncher(config, issues) } },
7576
+ form: { components: { input: createOverrideInput(config) } }
7295
7577
  };
7296
7578
  });
7297
7579
  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_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_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, createPreviewLauncher, customEnvironment, defaultNodeSize, depth, deriveDocumentColumns, diffDocuments, diffWords, editIntentPath, explainGrantError, fallbackLayout, fetchDetail, fetchTimeline, fillTemplate, filterRows, flatten, formatDocumentValue, groupPageRows, groupValue, hasBlockingIssue, humanizeBlockName, isDraftId, isKitType, isPrerelease, isSafeColumnKey, isSafeFieldPath, isTextChange, isVersionId, issuesForTool, keyForPath, kitSchemaTypes, layoutGraph, layoutSectionsMap, localesInRows, mergeVersions, missingPageTypes, moveColumn, ncfAllowedOrigins, ncfKit, ncfPreviewComponents, normalizeInternalPath, normalizePath, occurrencesForTypes, pageThumbnailUrl, pageTypeFor, pageTypesFromSiteRoutes, pageTypesWithoutBuilder, parentPath, presentationPath, pruneSavedPositions, releaseId, removeColumn, renameColumn, requestPreviewGrant, 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 };