@nocode-factory/sanity-kit 2.53.0 → 2.56.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.js CHANGED
@@ -1,6 +1,6 @@
1
- import { _ as DEFAULT_PAGE_BUILDER_FIELD, a as depth, c as segments, d as normalizePath, f as resolveConfig, g as DEFAULT_INTERNAL_FIELDS, h as DEFAULT_I18N, i as redirectMapOf, l as toPath, m as DEFAULT_COMPONENT_PREVIEW, o as pageTypeFor, p as DEFAULT_BOARD_TAGS, s as parentPath, t as finalPath, u as toUrl, v as DEFAULT_SLUG_FIELD, y as DEFAULT_TITLE_FIELD } from "./finalUrl-CaFXmYvm.js";
1
+ import { _ as DEFAULT_PAGE_BUILDER_FIELD, a as depth, c as segments, d as normalizePath, f as resolveConfig, g as DEFAULT_INTERNAL_FIELDS, h as DEFAULT_I18N, i as redirectMapOf, l as toPath, m as DEFAULT_COMPONENT_PREVIEW, o as pageTypeFor, p as DEFAULT_BOARD_TAGS, s as parentPath, t as finalPath, u as toUrl, v as DEFAULT_SLUG_FIELD, y as DEFAULT_TITLE_FIELD } from "./finalUrl-IXF3zbT9.js";
2
2
  import { a as collectTexts$1, c as valueAtKey, d as useKitContext, f as useOptionalKitConfig, i as guessDocumentTitle, l as KitProvider, o as replaceTexts, p as useOptionalKitContext, r as collectDocumentText, s as setAtKey, t as generateJsonLd, u as useKitConfig } from "./aiJsonLd-BFyxgYen.js";
3
- import { a as componentDefaultsMainDocument, c as defineComponentDefaults, d as syncTranslationRedirects, f as translationRedirectId, i as DEFAULT_COMPONENT_DEFAULTS_TYPE, l as requiredUnlessDefault, n as withSameLanguageReferences, o as componentDefaultsMainDocuments, p as translationRedirectOptions, r as pageTypesFromSiteRoutes, s as defaultsFieldName, t as fixCrossLanguageReferences, u as requiredUnlessDefaultFor } from "./fixCrossLanguageReferences-BeXywAAU.js";
3
+ import { a as componentDefaultsMainDocument, c as defineComponentDefaults, d as syncTranslationRedirects, f as translationRedirectId, i as DEFAULT_COMPONENT_DEFAULTS_TYPE, l as requiredUnlessDefault, n as withSameLanguageReferences, o as componentDefaultsMainDocuments, p as translationRedirectOptions, r as pageTypesFromSiteRoutes, s as defaultsFieldName, t as fixCrossLanguageReferences, u as requiredUnlessDefaultFor } from "./fixCrossLanguageReferences-CDczoic9.js";
4
4
  import { i as codeEditorInput, n as CodeEmbedInput, r as CodeEditorInput, t as defineCodeEmbedType } from "./codeEmbedType-1bEOTxBT.js";
5
5
  import { createContext, createElement, forwardRef, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
6
6
  import { ToolLink, defineField, definePlugin, defineType, pathToString, set, unset, useClient, useCurrentUser, useFormValue, usePerspective, useSchema, useSetPerspective, useUser, useWorkspace } from "sanity";
@@ -54,6 +54,8 @@ import { DragHandleIcon } from "@sanity/icons/DragHandle";
54
54
  import { createPortal } from "react-dom";
55
55
  import { TabletDeviceIcon } from "@sanity/icons/TabletDevice";
56
56
  import { PanelRightIcon } from "@sanity/icons/PanelRight";
57
+ import { usePaneRouter } from "sanity/structure";
58
+ import { DownloadIcon } from "@sanity/icons/Download";
57
59
  const isAbsoluteHttpUrl = (value) => {
58
60
  try {
59
61
  let url = new URL(value);
@@ -1420,7 +1422,7 @@ function explainGrantError(error) {
1420
1422
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1421
1423
  * le vérifie.
1422
1424
  */
1423
- const KIT_VERSION = "2.53.0";
1425
+ const KIT_VERSION = "2.56.0";
1424
1426
  /**
1425
1427
  * Signale ce Studio au service du kit, une fois par montage.
1426
1428
  *
@@ -1918,7 +1920,7 @@ function useKitUpdate() {
1918
1920
  !controller.signal.aborted && body?.version && setLatest(body.version);
1919
1921
  }).catch(() => {}), () => controller.abort();
1920
1922
  }, []);
1921
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.53.0") > 0);
1923
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.56.0") > 0);
1922
1924
  return {
1923
1925
  current: KIT_VERSION,
1924
1926
  latest,
@@ -1938,7 +1940,7 @@ const TABULAR = { fontVariantNumeric: "tabular-nums" }, MONO = {
1938
1940
  fontFamily: "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
1939
1941
  fontVariantNumeric: "tabular-nums",
1940
1942
  letterSpacing: "-0.01em"
1941
- }, CELL = { minWidth: 0 }, BORDER = "var(--card-border-color, rgba(127,127,127,0.22))", OPTION_COLORS = [
1943
+ }, CELL = { minWidth: 0 }, BORDER = "var(--card-border-color, rgba(127,127,127,0.22))", BORDER_SOFT = "var(--card-border-color, rgba(127,127,127,0.12))", OPTION_COLORS = [
1942
1944
  "#f5a623",
1943
1945
  "#43d675",
1944
1946
  "#2276fc",
@@ -2561,7 +2563,7 @@ const STATUS_ORDER = {
2561
2563
  case "blockCount": return a.blockCount - b.blockCount;
2562
2564
  }
2563
2565
  };
2564
- function sortRows(rows, key, direction, options = {}) {
2566
+ function sortRows$1(rows, key, direction, options = {}) {
2565
2567
  if (key === "manual") {
2566
2568
  let sorted = orderByIds([...rows].sort((a, b) => a.title.localeCompare(b.title, void 0, { sensitivity: "base" })), options.pageOrder ?? []);
2567
2569
  return direction === "asc" ? sorted : sorted.reverse();
@@ -2569,10 +2571,10 @@ function sortRows(rows, key, direction, options = {}) {
2569
2571
  let sorted = [...rows].sort((a, b) => compare(a, b, key, options));
2570
2572
  return direction === "asc" ? sorted : sorted.reverse();
2571
2573
  }
2572
- const normalize = (value) => value.toLocaleLowerCase().normalize("NFD").replace(/\p{Diacritic}/gu, "");
2573
- function filterRows(rows, filters) {
2574
- let search = filters.search?.trim() ? normalize(filters.search.trim()) : null;
2575
- return rows.filter((row) => !(filters.types?.length && !filters.types.includes(row.type) || filters.statuses?.length && !filters.statuses.includes(row.status) || filters.locales?.length && row.locale && !filters.locales.includes(row.locale) || search && !`${normalize(row.title)} ${normalize(row.path ?? "")}`.includes(search)));
2574
+ const normalize$1 = (value) => value.toLocaleLowerCase().normalize("NFD").replace(/\p{Diacritic}/gu, "");
2575
+ function filterRows$1(rows, filters) {
2576
+ let search = filters.search?.trim() ? normalize$1(filters.search.trim()) : null;
2577
+ return rows.filter((row) => !(filters.types?.length && !filters.types.includes(row.type) || filters.statuses?.length && !filters.statuses.includes(row.status) || filters.locales?.length && row.locale && !filters.locales.includes(row.locale) || search && !`${normalize$1(row.title)} ${normalize$1(row.path ?? "")}`.includes(search)));
2576
2578
  }
2577
2579
  /** Langues réellement présentes, pour ne proposer que des filtres utiles. */
2578
2580
  function localesInRows(rows) {
@@ -2679,6 +2681,10 @@ const OPAQUE_TYPES = /* @__PURE__ */ new Set([
2679
2681
  "globalDocumentReference",
2680
2682
  "block",
2681
2683
  "geopoint"
2684
+ ]), REFERENCE_TYPES = /* @__PURE__ */ new Set([
2685
+ "reference",
2686
+ "crossDatasetReference",
2687
+ "globalDocumentReference"
2682
2688
  ]);
2683
2689
  /** Remonte la chaîne d'héritage jusqu'à trouver la nature JSON du champ. */
2684
2690
  function jsonTypeOf(type) {
@@ -2705,6 +2711,15 @@ function isOpaque(type) {
2705
2711
  }
2706
2712
  return !1;
2707
2713
  }
2714
+ /** Vrai pour un champ référence (vers un autre document). */
2715
+ function isReference(type) {
2716
+ let current = type;
2717
+ for (let depth = 0; current && depth < 10; depth += 1) {
2718
+ if (current.name && REFERENCE_TYPES.has(current.name)) return !0;
2719
+ current = current.type;
2720
+ }
2721
+ return !1;
2722
+ }
2708
2723
  const labelOf = (field) => field.type?.title?.trim() || humanise(field.name);
2709
2724
  /** `metaDescription` → `Meta description`. */
2710
2725
  function humanise(name) {
@@ -4175,7 +4190,7 @@ const formatter = new Intl.DateTimeFormat("en-US", {
4175
4190
  minute: "2-digit"
4176
4191
  });
4177
4192
  /** Date lisible, ou un tiret cadratin quand il n'y en a pas. */
4178
- function formatDate(value) {
4193
+ function formatDate$1(value) {
4179
4194
  if (!value) return "—";
4180
4195
  let date = new Date(value);
4181
4196
  return Number.isNaN(date.getTime()) ? "—" : formatter.format(date);
@@ -4863,7 +4878,7 @@ function PagesTable(props) {
4863
4878
  ].join(" "),
4864
4879
  gap: "0.875rem",
4865
4880
  alignItems: "center",
4866
- borderBottom: "1px solid var(--card-border-color, rgba(127,127,127,0.12))"
4881
+ borderBottom: `1px solid ${BORDER_SOFT}`
4867
4882
  };
4868
4883
  return /* @__PURE__ */ jsxs(Box, {
4869
4884
  style: { overflowX: "auto" },
@@ -5063,7 +5078,7 @@ function PagesTable(props) {
5063
5078
  size: 0,
5064
5079
  muted: !0,
5065
5080
  style: TABULAR,
5066
- children: formatDate(entryRow.updatedAt)
5081
+ children: formatDate$1(entryRow.updatedAt)
5067
5082
  })
5068
5083
  }),
5069
5084
  dataColumns.map((column) => {
@@ -5186,7 +5201,7 @@ function ColumnVisibility(props) {
5186
5201
  })
5187
5202
  });
5188
5203
  }
5189
- function Row$1(props) {
5204
+ function Row$2(props) {
5190
5205
  return /* @__PURE__ */ jsxs(Flex, {
5191
5206
  align: "center",
5192
5207
  gap: 2,
@@ -5231,7 +5246,7 @@ function DataColumnList(props) {
5231
5246
  }, [dataColumns, filter]);
5232
5247
  return /* @__PURE__ */ jsxs(Stack, {
5233
5248
  gap: 0,
5234
- children: [HIDEABLE.map((column) => /* @__PURE__ */ jsx(Row$1, {
5249
+ children: [HIDEABLE.map((column) => /* @__PURE__ */ jsx(Row$2, {
5235
5250
  label: column.label,
5236
5251
  checked: !hidden.has(column.key),
5237
5252
  onClick: () => onToggle(column.key)
@@ -5268,7 +5283,7 @@ function DataColumnList(props) {
5268
5283
  }
5269
5284
  })
5270
5285
  }),
5271
- matches.map((column) => /* @__PURE__ */ jsx(Row$1, {
5286
+ matches.map((column) => /* @__PURE__ */ jsx(Row$2, {
5272
5287
  label: column.label,
5273
5288
  checked: shownData.has(column.key),
5274
5289
  onClick: () => onToggleData(column.key)
@@ -6431,7 +6446,7 @@ function PagesTool() {
6431
6446
  let next = new Set(current);
6432
6447
  return next.has(key) ? next.delete(key) : next.add(key), next;
6433
6448
  });
6434
- }, []), documentColumns = useDocumentColumns(), visibleDataColumns = useMemo(() => documentColumns.filter((column) => shownData.has(column.key)), [documentColumns, shownData]), { rows, loading, error, refresh } = usePages(visibleDataColumns), colorBy = resolveColorBy(rawColorBy, columns), locales = useMemo(() => config.i18n?.locales.length ? config.i18n.locales : localesInRows(rows), [config.i18n, rows]), effectiveSortKey = sortKey ?? (pageOrder.length > 0 ? "manual" : "structure"), visible = useMemo(() => sortRows(filterRows(rows, {
6449
+ }, []), documentColumns = useDocumentColumns(), visibleDataColumns = useMemo(() => documentColumns.filter((column) => shownData.has(column.key)), [documentColumns, shownData]), { rows, loading, error, refresh } = usePages(visibleDataColumns), colorBy = resolveColorBy(rawColorBy, columns), locales = useMemo(() => config.i18n?.locales.length ? config.i18n.locales : localesInRows(rows), [config.i18n, rows]), effectiveSortKey = sortKey ?? (pageOrder.length > 0 ? "manual" : "structure"), visible = useMemo(() => sortRows$1(filterRows$1(rows, {
6435
6450
  search,
6436
6451
  locales: locale ? [locale] : void 0
6437
6452
  }).filter((row) => !onlyTodo || todos.has(row.id)), effectiveSortKey, sortDirection, {
@@ -9198,7 +9213,7 @@ function countByFolder(assets, folders) {
9198
9213
  }
9199
9214
  return counts;
9200
9215
  }
9201
- function Row(props) {
9216
+ function Row$1(props) {
9202
9217
  return /* @__PURE__ */ jsxs(Flex, {
9203
9218
  align: "center",
9204
9219
  gap: 1,
@@ -9278,19 +9293,19 @@ function FolderSidebar(props) {
9278
9293
  /* @__PURE__ */ jsxs(Stack, {
9279
9294
  gap: 1,
9280
9295
  children: [
9281
- /* @__PURE__ */ jsx(Row, {
9296
+ /* @__PURE__ */ jsx(Row$1, {
9282
9297
  label: "Tous les médias",
9283
9298
  count: total,
9284
9299
  active: selection === null,
9285
9300
  onClick: () => onSelect(null)
9286
9301
  }),
9287
- /* @__PURE__ */ jsx(Row, {
9302
+ /* @__PURE__ */ jsx(Row$1, {
9288
9303
  label: "Non classés",
9289
9304
  count: counts.get("") ?? 0,
9290
9305
  active: selection === "",
9291
9306
  onClick: () => onSelect("")
9292
9307
  }),
9293
- folders.map((folder) => /* @__PURE__ */ jsx(Row, {
9308
+ folders.map((folder) => /* @__PURE__ */ jsx(Row$1, {
9294
9309
  label: folder.name,
9295
9310
  count: counts.get(folder.id) ?? 0,
9296
9311
  active: selection === folder.id,
@@ -9868,7 +9883,7 @@ function AssetTable(props) {
9868
9883
  size: 1,
9869
9884
  muted: !0,
9870
9885
  style: TABULAR,
9871
- children: formatDate(asset._createdAt)
9886
+ children: formatDate$1(asset._createdAt)
9872
9887
  })
9873
9888
  })
9874
9889
  ]
@@ -9908,7 +9923,7 @@ function toPatchPath(segments) {
9908
9923
  function assetUnsetPaths(doc, assetId) {
9909
9924
  return findAssetRefPaths(doc, assetId).map(toPatchPath).filter(Boolean);
9910
9925
  }
9911
- const baseId$1 = (id) => id.replace(/^drafts\./, "");
9926
+ const baseId$2 = (id) => id.replace(/^drafts\./, "");
9912
9927
  /**
9913
9928
  * Suppression d'un asset depuis l'outil Assets. Sanity refuse de supprimer un
9914
9929
  * asset référencé : on retire d'abord l'asset de chaque document (le champ
@@ -9920,7 +9935,7 @@ function useAssetDelete() {
9920
9935
  usage: useCallback(async (assetId) => {
9921
9936
  let docs = await client.fetch("*[references($id)]{_id, _type, \"title\": coalesce(title, name, originalFilename, slug.current, _id)}", { id: assetId }), seen = /* @__PURE__ */ new Map();
9922
9937
  for (let doc of docs ?? []) {
9923
- let id = baseId$1(doc._id);
9938
+ let id = baseId$2(doc._id);
9924
9939
  seen.has(id) || seen.set(id, {
9925
9940
  id,
9926
9941
  type: doc._type,
@@ -10149,7 +10164,7 @@ function AssetDetail(props) {
10149
10164
  }),
10150
10165
  /* @__PURE__ */ jsx(Metric, {
10151
10166
  label: "Ajouté",
10152
- value: formatDate(asset._createdAt)
10167
+ value: formatDate$1(asset._createdAt)
10153
10168
  })
10154
10169
  ]
10155
10170
  }),
@@ -12670,6 +12685,898 @@ function ncfPresentationComponents(options) {
12670
12685
  unstable_header: { component: NcfPresentationHeader }
12671
12686
  };
12672
12687
  }
12688
+ /** Champs d'un titre affichable d'un document référencé, par ordre de préférence. */
12689
+ const REFERENCE_TITLE_FIELDS = [
12690
+ "title",
12691
+ "name",
12692
+ "label",
12693
+ "heading"
12694
+ ];
12695
+ /**
12696
+ * Colonnes tirées du schéma d'un type de collection. Aucune liste à tenir :
12697
+ * chaque champ scalaire, date ou référence devient une colonne proposable. Les
12698
+ * tableaux, images, fichiers et blocs sont écartés — rien à rendre en ligne.
12699
+ */
12700
+ function deriveCollectionColumns(type, options = {}) {
12701
+ let maxDepth = options.depth ?? 1, found = /* @__PURE__ */ new Map(), add = (path, label, kind, projection) => {
12702
+ let key = keyForPath(path);
12703
+ !found.has(key) && isSafeColumnKey(key) && found.set(key, {
12704
+ key,
12705
+ label,
12706
+ kind,
12707
+ projection
12708
+ });
12709
+ }, visit = (fields, prefix, prefixLabel, depth) => {
12710
+ for (let field of fields) {
12711
+ if (!field.name || field.name.startsWith("_")) continue;
12712
+ let path = prefix ? `${prefix}.${field.name}` : field.name;
12713
+ if (!isSafeFieldPath(path)) continue;
12714
+ let label = prefixLabel ? `${prefixLabel} · ${labelOf(field)}` : labelOf(field), typeName = typeNameOf(field.type);
12715
+ if (typeName === "slug") {
12716
+ add(path, label, "text", `${path}.current`);
12717
+ continue;
12718
+ }
12719
+ if (isReference(field.type)) {
12720
+ let titles = REFERENCE_TITLE_FIELDS.map((f) => `${path}->${f}`);
12721
+ add(path, label, "reference", `coalesce(${titles.join(", ")}, ${path}->_id)`);
12722
+ continue;
12723
+ }
12724
+ if (isOpaque(field.type)) continue;
12725
+ if (typeName === "datetime" || typeName === "date") {
12726
+ add(path, label, "date", path);
12727
+ continue;
12728
+ }
12729
+ let json = jsonTypeOf(field.type);
12730
+ if (json === "string") {
12731
+ add(path, label, "text", path);
12732
+ continue;
12733
+ }
12734
+ if (json === "number" || json === "boolean") {
12735
+ add(path, label, json, path);
12736
+ continue;
12737
+ }
12738
+ json === "object" && depth < maxDepth && field.type?.fields?.length && visit(field.type.fields, path, label, depth + 1);
12739
+ }
12740
+ };
12741
+ return type?.fields?.length && visit(type.fields, "", "", 0), [...found.values()];
12742
+ }
12743
+ /** Nom du champ titre d'une collection, pour la colonne mise en avant. */
12744
+ function titleColumn(columns) {
12745
+ return columns.find((c) => c.key === "title") ?? columns.find((c) => c.kind === "text");
12746
+ }
12747
+ /**
12748
+ * Requête d'une collection : `_id`, `_updatedAt`, et une projection par colonne
12749
+ * **visible** (clé préfixée `ncfData_` pour ne jamais heurter un champ du
12750
+ * client). Les expressions des colonnes sont construites par le kit à partir de
12751
+ * chemins déjà validés (`deriveCollectionColumns`), donc sûres ; la clé est
12752
+ * revérifiée par prudence avant interpolation.
12753
+ *
12754
+ * Le type passe en paramètre (`$type`), jamais interpolé dans la requête.
12755
+ *
12756
+ * `filter` est un prédicat GROQ supplémentaire écrit par l'intégrateur (dans le
12757
+ * résolveur de structure), par exemple `language == $lang` : il restreint la
12758
+ * table au niveau feuille (une langue, une catégorie, une page…). Il est
12759
+ * parenthésé puis combiné en `&&`, et ses valeurs passent par `params`, jamais
12760
+ * interpolées. Même niveau de confiance que `S.documentList().filter(...)`.
12761
+ *
12762
+ * On ne filtre pas les brouillons : le client (perspective `raw`) renvoie
12763
+ * `drafts.x` ET `x`, que `buildCollectionRows` fusionne par id de base — sans
12764
+ * quoi un item jamais publié n'apparaîtrait pas.
12765
+ */
12766
+ function buildCollectionQuery(columns, filter) {
12767
+ let lines = columns.filter((column) => isSafeColumnKey(column.key)).map((column) => ` "${DATA_PREFIX}${column.key}": ${column.projection},`);
12768
+ return [
12769
+ `*[${filter && filter.trim() ? `_type == $type && (${filter.trim()})` : "_type == $type"}]{`,
12770
+ " _id, _updatedAt,",
12771
+ ...lines,
12772
+ "}"
12773
+ ].join("\n");
12774
+ }
12775
+ const baseId$1 = (id) => id.startsWith("drafts.") ? id.slice(7) : id, isDraft = (id) => id.startsWith("drafts."), dateFormatter = new Intl.DateTimeFormat("en-US", {
12776
+ day: "2-digit",
12777
+ month: "2-digit",
12778
+ year: "numeric"
12779
+ });
12780
+ function formatDate(value) {
12781
+ if (typeof value != "string" || !value) return "";
12782
+ let date = new Date(value);
12783
+ return Number.isNaN(date.getTime()) ? "" : dateFormatter.format(date);
12784
+ }
12785
+ function cellOf(raw, kind) {
12786
+ if (raw == null) return {
12787
+ raw: null,
12788
+ text: ""
12789
+ };
12790
+ if (kind === "boolean") {
12791
+ let value = !!raw;
12792
+ return {
12793
+ raw: value,
12794
+ text: value ? "Yes" : "No"
12795
+ };
12796
+ }
12797
+ if (kind === "number") return typeof raw == "number" ? {
12798
+ raw,
12799
+ text: String(raw)
12800
+ } : {
12801
+ raw: null,
12802
+ text: ""
12803
+ };
12804
+ if (kind === "date") return {
12805
+ raw: typeof raw == "string" ? raw : null,
12806
+ text: formatDate(raw)
12807
+ };
12808
+ let text = typeof raw == "string" ? raw.trim() : String(raw);
12809
+ return {
12810
+ raw: text,
12811
+ text
12812
+ };
12813
+ }
12814
+ /**
12815
+ * Documents → lignes, une par item. Le client (perspective `raw`) renvoie le
12816
+ * brouillon ET la version publiée : on les fusionne par id de base, en gardant
12817
+ * le brouillon s'il existe (valeurs les plus fraîches).
12818
+ */
12819
+ function buildCollectionRows(docs, columns) {
12820
+ let byId = /* @__PURE__ */ new Map();
12821
+ for (let doc of docs) {
12822
+ if (!doc?._id) continue;
12823
+ let entry = byId.get(baseId$1(doc._id)) ?? {};
12824
+ isDraft(doc._id) ? entry.draft = doc : entry.published = doc, byId.set(baseId$1(doc._id), entry);
12825
+ }
12826
+ let rows = [];
12827
+ for (let [id, { draft, published }] of byId) {
12828
+ let source = draft ?? published;
12829
+ if (!source) continue;
12830
+ let cells = {};
12831
+ for (let column of columns) cells[column.key] = cellOf(source[`${DATA_PREFIX}${column.key}`], column.kind);
12832
+ rows.push({
12833
+ id,
12834
+ updatedAt: source._updatedAt ?? null,
12835
+ draftOnly: !!draft && !published,
12836
+ cells
12837
+ });
12838
+ }
12839
+ return rows;
12840
+ }
12841
+ /**
12842
+ * Données d'une collection pour la vue table : colonnes tirées du schéma,
12843
+ * lignes en direct. Seules les colonnes visibles sont projetées (comme
12844
+ * `usePages`), pour ne pas tirer tout le schéma sur chaque document.
12845
+ *
12846
+ * `filter`/`params` restreignent la table au niveau feuille (une langue, une
12847
+ * catégorie…). `useQueryData` stabilise lui-même les paramètres, donc l'objet
12848
+ * peut être reconstruit à chaque rendu sans relancer la requête en boucle.
12849
+ */
12850
+ function useCollection(type, visibleKeys, options = {}) {
12851
+ let { filter, params: extraParams } = options, schema = useSchema(), allColumns = useMemo(() => deriveCollectionColumns(schema.get(type)), [schema, type]), visibleColumns = useMemo(() => visibleKeys.map((key) => allColumns.find((c) => c.key === key)).filter((c) => !!c), [allColumns, visibleKeys]), { data, loading, error, refresh } = useQueryData(useMemo(() => buildCollectionQuery(visibleColumns, filter), [visibleColumns, filter]), {
12852
+ type,
12853
+ ...extraParams
12854
+ }, { listenTypes: [type] });
12855
+ return {
12856
+ allColumns,
12857
+ visibleColumns,
12858
+ rows: useMemo(() => buildCollectionRows(data ?? [], visibleColumns), [data, visibleColumns]),
12859
+ loading,
12860
+ error,
12861
+ refresh
12862
+ };
12863
+ }
12864
+ /** Insensible à la casse et aux accents, comme la recherche de l'onglet Pages. */
12865
+ const normalize = (value) => value.toLocaleLowerCase().normalize("NFD").replace(/\p{Diacritic}/gu, "");
12866
+ /** Compare deux valeurs non vides selon le type de la colonne. */
12867
+ function compareNonNull(ra, rb, kind) {
12868
+ return kind === "number" || kind === "boolean" ? Number(ra) - Number(rb) : kind === "date" ? String(ra).localeCompare(String(rb)) : String(ra).localeCompare(String(rb), void 0, { sensitivity: "base" });
12869
+ }
12870
+ function sortRows(rows, sort, columns) {
12871
+ if (!sort.key) return [...rows];
12872
+ let column = columns.find((c) => c.key === sort.key);
12873
+ if (!column) return [...rows];
12874
+ let dir = sort.direction === "asc" ? 1 : -1;
12875
+ return [...rows].sort((a, b) => {
12876
+ let ra = a.cells[column.key]?.raw ?? null, rb = b.cells[column.key]?.raw ?? null;
12877
+ return ra === null && rb === null ? 0 : ra === null ? 1 : rb === null ? -1 : dir * compareNonNull(ra, rb, column.kind);
12878
+ });
12879
+ }
12880
+ function filterRows(rows, filters, visibleColumns) {
12881
+ let search = filters.search?.trim() ? normalize(filters.search.trim()) : null, columnNeedles = Object.entries(filters.columns ?? {}).map(([key, value]) => [key, normalize(value.trim())]).filter(([, value]) => value.length > 0);
12882
+ return !search && columnNeedles.length === 0 ? [...rows] : rows.filter((row) => {
12883
+ if (search && !visibleColumns.map((c) => normalize(row.cells[c.key]?.text ?? "")).join(" ").includes(search)) return !1;
12884
+ for (let [key, needle] of columnNeedles) if (!normalize(row.cells[key]?.text ?? "").includes(needle)) return !1;
12885
+ return !0;
12886
+ });
12887
+ }
12888
+ /** Échappement RFC 4180 : guillemets doublés, champ cité s'il contient `,` `"` ou un saut de ligne. */
12889
+ function escapeField(value) {
12890
+ return /[",\n\r]/.test(value) ? `"${value.replace(/"/g, "\"\"")}"` : value;
12891
+ }
12892
+ /**
12893
+ * Lignes → CSV. En-têtes = libellés des colonnes visibles, cellules = le texte
12894
+ * déjà mis en forme (`row.cells[key].text`). Lignes séparées par CRLF, comme
12895
+ * l'attendent les tableurs. Pur : l'appelant ajoute l'éventuel BOM au moment du
12896
+ * téléchargement.
12897
+ */
12898
+ function toCsv(rows, columns) {
12899
+ let header = columns.map((column) => escapeField(column.label)), body = rows.map((row) => columns.map((column) => escapeField(row.cells[column.key]?.text ?? "")).join(","));
12900
+ return [header.join(","), ...body].join("\r\n");
12901
+ }
12902
+ /**
12903
+ * Propose un fichier texte au téléchargement depuis le navigateur. Déclenché
12904
+ * par un clic de l'utilisateur (bouton « Exporter »), jamais tout seul.
12905
+ *
12906
+ * Un BOM UTF-8 est ajouté par défaut pour que les accents s'affichent dans
12907
+ * Excel. No-op hors navigateur (rendu serveur, tests).
12908
+ */
12909
+ function downloadText(filename, text, mime = "text/csv;charset=utf-8", withBom = !0) {
12910
+ if (typeof window > "u" || typeof document > "u") return;
12911
+ let blob = new Blob([withBom ? `${text}` : text], { type: mime }), url = URL.createObjectURL(blob), anchor = document.createElement("a");
12912
+ anchor.href = url, anchor.download = filename, document.body.appendChild(anchor), anchor.click(), anchor.remove(), URL.revokeObjectURL(url);
12913
+ }
12914
+ /** Choix des colonnes affichées, sans quitter la table (façon tableur). */
12915
+ function CollectionColumnPicker(props) {
12916
+ let { columns, visible, onToggle } = props, visibleSet = useMemo(() => new Set(visible), [visible]);
12917
+ return /* @__PURE__ */ jsx(InlinePopover, {
12918
+ width: 264,
12919
+ trigger: ({ toggle }) => /* @__PURE__ */ jsx(Button, {
12920
+ mode: "bleed",
12921
+ fontSize: 1,
12922
+ padding: 2,
12923
+ icon: ControlsIcon,
12924
+ text: `Columns · ${visible.length}`,
12925
+ onClick: toggle
12926
+ }),
12927
+ children: () => /* @__PURE__ */ jsx(ColumnList, {
12928
+ columns,
12929
+ visibleSet,
12930
+ onToggle
12931
+ })
12932
+ });
12933
+ }
12934
+ function Row(props) {
12935
+ return /* @__PURE__ */ jsxs(Flex, {
12936
+ align: "center",
12937
+ gap: 2,
12938
+ padding: 2,
12939
+ onClick: props.onClick,
12940
+ style: {
12941
+ cursor: "pointer",
12942
+ borderRadius: 3
12943
+ },
12944
+ onMouseEnter: (event) => {
12945
+ event.currentTarget.style.background = "var(--card-muted-bg-color, rgba(127,127,127,0.12))";
12946
+ },
12947
+ onMouseLeave: (event) => {
12948
+ event.currentTarget.style.background = "transparent";
12949
+ },
12950
+ children: [/* @__PURE__ */ jsx(Box, {
12951
+ style: {
12952
+ width: 14,
12953
+ flex: "none"
12954
+ },
12955
+ children: props.checked && /* @__PURE__ */ jsx(CheckmarkIcon, { style: {
12956
+ fontSize: 14,
12957
+ opacity: .7
12958
+ } })
12959
+ }), /* @__PURE__ */ jsx(Text, {
12960
+ size: 1,
12961
+ muted: !props.checked,
12962
+ textOverflow: "ellipsis",
12963
+ children: props.label
12964
+ })]
12965
+ });
12966
+ }
12967
+ /** Au-delà d'une poignée de champs, un filtre apparaît pour en chercher un. */
12968
+ function ColumnList(props) {
12969
+ let { columns, visibleSet, onToggle } = props, [filter, setFilter] = useState(""), matches = useMemo(() => {
12970
+ let needle = filter.trim().toLowerCase();
12971
+ return needle ? columns.filter((column) => column.label.toLowerCase().includes(needle)) : columns;
12972
+ }, [columns, filter]);
12973
+ return /* @__PURE__ */ jsxs(Stack, {
12974
+ gap: 0,
12975
+ children: [
12976
+ columns.length > 8 && /* @__PURE__ */ jsx(Box, {
12977
+ paddingX: 1,
12978
+ paddingBottom: 1,
12979
+ children: /* @__PURE__ */ jsx("input", {
12980
+ type: "text",
12981
+ value: filter,
12982
+ placeholder: "Filter…",
12983
+ onChange: (event) => setFilter(event.currentTarget.value),
12984
+ style: {
12985
+ width: "100%",
12986
+ font: "inherit",
12987
+ fontSize: 12,
12988
+ padding: "6px",
12989
+ borderRadius: 3,
12990
+ border: "1px solid var(--card-border-color, rgba(127,127,127,0.22))",
12991
+ background: "var(--card-bg-color)",
12992
+ color: "var(--card-fg-color)",
12993
+ outline: "none"
12994
+ }
12995
+ })
12996
+ }),
12997
+ matches.map((column) => /* @__PURE__ */ jsx(Row, {
12998
+ label: column.label,
12999
+ checked: visibleSet.has(column.key),
13000
+ onClick: () => onToggle(column.key)
13001
+ }, column.key)),
13002
+ matches.length === 0 && /* @__PURE__ */ jsx(Box, {
13003
+ padding: 2,
13004
+ children: /* @__PURE__ */ jsx(Text, {
13005
+ size: 0,
13006
+ muted: !0,
13007
+ children: "No matching fields."
13008
+ })
13009
+ })
13010
+ ]
13011
+ });
13012
+ }
13013
+ /** Barre au-dessus de la collection : switch de vue, création, recherche, colonnes, export. */
13014
+ function CollectionToolbar(props) {
13015
+ let { view, onView, search, onSearch, columns, visible, onToggleColumn, onExport, onRefresh, onCreate, busy, summary } = props;
13016
+ return /* @__PURE__ */ jsxs(Flex, {
13017
+ align: "center",
13018
+ gap: 2,
13019
+ wrap: "wrap",
13020
+ children: [
13021
+ /* @__PURE__ */ jsx(Card, {
13022
+ radius: 2,
13023
+ border: !0,
13024
+ style: { flex: "none" },
13025
+ children: /* @__PURE__ */ jsxs(Flex, { children: [/* @__PURE__ */ jsx(Button, {
13026
+ mode: view === "list" ? "default" : "bleed",
13027
+ tone: view === "list" ? "primary" : "default",
13028
+ fontSize: 1,
13029
+ padding: 2,
13030
+ icon: UlistIcon,
13031
+ title: "List view",
13032
+ "aria-label": "List view",
13033
+ onClick: () => onView("list")
13034
+ }), /* @__PURE__ */ jsx(Button, {
13035
+ mode: view === "table" ? "default" : "bleed",
13036
+ tone: view === "table" ? "primary" : "default",
13037
+ fontSize: 1,
13038
+ padding: 2,
13039
+ icon: ThLargeIcon,
13040
+ title: "Table view",
13041
+ "aria-label": "Table view",
13042
+ onClick: () => onView("table")
13043
+ })] })
13044
+ }),
13045
+ /* @__PURE__ */ jsx(Box, {
13046
+ style: {
13047
+ flex: 1,
13048
+ minWidth: 180
13049
+ },
13050
+ children: /* @__PURE__ */ jsx(TextInput, {
13051
+ icon: SearchIcon,
13052
+ fontSize: 1,
13053
+ padding: 2,
13054
+ radius: 2,
13055
+ placeholder: "Search",
13056
+ value: search,
13057
+ onChange: (event) => onSearch(event.currentTarget.value),
13058
+ clearButton: !!search,
13059
+ onClear: () => onSearch("")
13060
+ })
13061
+ }),
13062
+ /* @__PURE__ */ jsx(Text, {
13063
+ size: 1,
13064
+ muted: !0,
13065
+ style: { flex: "none" },
13066
+ children: summary
13067
+ }),
13068
+ /* @__PURE__ */ jsxs(Flex, {
13069
+ gap: 1,
13070
+ style: { flex: "none" },
13071
+ children: [
13072
+ onCreate && /* @__PURE__ */ jsx(Button, {
13073
+ mode: "ghost",
13074
+ tone: "primary",
13075
+ fontSize: 1,
13076
+ padding: 2,
13077
+ icon: AddIcon,
13078
+ text: "New",
13079
+ onClick: onCreate
13080
+ }),
13081
+ view === "table" && /* @__PURE__ */ jsx(CollectionColumnPicker, {
13082
+ columns,
13083
+ visible,
13084
+ onToggle: onToggleColumn
13085
+ }),
13086
+ /* @__PURE__ */ jsx(Button, {
13087
+ mode: "bleed",
13088
+ fontSize: 1,
13089
+ padding: 2,
13090
+ icon: DownloadIcon,
13091
+ text: "Export CSV",
13092
+ onClick: onExport
13093
+ }),
13094
+ /* @__PURE__ */ jsx(Button, {
13095
+ mode: "bleed",
13096
+ fontSize: 1,
13097
+ padding: 2,
13098
+ icon: RefreshIcon,
13099
+ title: "Refresh",
13100
+ "aria-label": "Refresh",
13101
+ onClick: onRefresh,
13102
+ disabled: busy
13103
+ })
13104
+ ]
13105
+ })
13106
+ ]
13107
+ });
13108
+ }
13109
+ function defaultVisible(columns) {
13110
+ let title = columns.find((c) => c.key === "title") ?? columns.find((c) => c.kind === "text");
13111
+ return (title ? [title, ...columns.filter((c) => c !== title)] : [...columns]).slice(0, 6).map((c) => c.key);
13112
+ }
13113
+ /** Largeur par défaut d'une colonne : le titre large, le reste selon le type. */
13114
+ function defaultWidth(column, isFirst) {
13115
+ if (isFirst) return 320;
13116
+ switch (column.kind) {
13117
+ case "number": return 110;
13118
+ case "boolean": return 90;
13119
+ case "date": return 150;
13120
+ case "reference": return 200;
13121
+ default: return 190;
13122
+ }
13123
+ }
13124
+ /** Déplace `fromKey` à la position de `toKey` dans la liste des clés. */
13125
+ function moveKey(keys, fromKey, toKey) {
13126
+ let from = keys.indexOf(fromKey), to = keys.indexOf(toKey);
13127
+ if (from < 0 || to < 0 || from === to) return keys;
13128
+ let next = [...keys];
13129
+ return next.splice(from, 1), next.splice(to, 0, fromKey), next;
13130
+ }
13131
+ function CollectionTable({ type, filter, params, newTemplate }) {
13132
+ let router = useRouter(), { ChildLink } = usePaneRouter(), [view, setView] = useState("table"), [selected, setSelected] = useState(null), [sort, setSort] = useState({
13133
+ key: null,
13134
+ direction: "asc"
13135
+ }), [search, setSearch] = useState(""), [columnFilters, setColumnFilters] = useState({}), [widths, setWidths] = useState({}), schema = useSchema(), allColumns = useMemo(() => deriveCollectionColumns(schema.get(type)), [schema, type]), visibleKeys = useMemo(() => selected ?? defaultVisible(allColumns), [selected, allColumns]), { visibleColumns, rows, loading, error, refresh } = useCollection(type, visibleKeys, {
13136
+ filter,
13137
+ params
13138
+ }), visible = useMemo(() => sortRows(filterRows(rows, {
13139
+ search,
13140
+ columns: columnFilters
13141
+ }, visibleColumns), sort, visibleColumns), [
13142
+ rows,
13143
+ search,
13144
+ columnFilters,
13145
+ visibleColumns,
13146
+ sort
13147
+ ]), cols = useMemo(() => visibleColumns.map((column, index) => ({
13148
+ column,
13149
+ width: widths[column.key] ?? defaultWidth(column, index === 0)
13150
+ })), [visibleColumns, widths]), totalWidth = useMemo(() => cols.reduce((sum, c) => sum + c.width, 0), [cols]), onToggleColumn = useCallback((key) => {
13151
+ setSelected((current) => {
13152
+ let base = current ?? defaultVisible(allColumns);
13153
+ return base.includes(key) ? base.filter((k) => k !== key) : [...base, key];
13154
+ }), setColumnFilters((current) => {
13155
+ if (!current[key]) return current;
13156
+ let { [key]: _removed, ...rest } = current;
13157
+ return rest;
13158
+ });
13159
+ }, [allColumns]), onSort = useCallback((key) => {
13160
+ setSort((current) => current.key === key ? {
13161
+ key,
13162
+ direction: current.direction === "asc" ? "desc" : "asc"
13163
+ } : {
13164
+ key,
13165
+ direction: "asc"
13166
+ });
13167
+ }, []), onExport = useCallback(() => {
13168
+ downloadText(`${type}.csv`, toCsv(visible, visibleColumns));
13169
+ }, [
13170
+ type,
13171
+ visible,
13172
+ visibleColumns
13173
+ ]), onColumnFilter = useCallback((key, value) => {
13174
+ setColumnFilters((current) => ({
13175
+ ...current,
13176
+ [key]: value
13177
+ }));
13178
+ }, []), onCreate = useCallback(() => {
13179
+ router.navigateIntent("create", newTemplate ? {
13180
+ type,
13181
+ template: newTemplate
13182
+ } : { type });
13183
+ }, [
13184
+ router,
13185
+ type,
13186
+ newTemplate
13187
+ ]), dragKeyRef = useRef(null), [dragOverKey, setDragOverKey] = useState(null), onReorder = useCallback((toKey) => {
13188
+ let fromKey = dragKeyRef.current;
13189
+ dragKeyRef.current = null, setDragOverKey(null), fromKey && fromKey !== toKey && setSelected((current) => moveKey(current ?? defaultVisible(allColumns), fromKey, toKey));
13190
+ }, [allColumns]), onResizeStart = useCallback((key, startW) => (event) => {
13191
+ event.preventDefault(), event.stopPropagation();
13192
+ let startX = event.clientX, onMove = (ev) => {
13193
+ setWidths((current) => ({
13194
+ ...current,
13195
+ [key]: Math.max(80, startW + (ev.clientX - startX))
13196
+ }));
13197
+ }, onUp = () => {
13198
+ window.removeEventListener("pointermove", onMove), window.removeEventListener("pointerup", onUp);
13199
+ };
13200
+ window.addEventListener("pointermove", onMove), window.addEventListener("pointerup", onUp);
13201
+ }, []);
13202
+ if (error) return /* @__PURE__ */ jsx(QueryError, {
13203
+ error,
13204
+ onRetry: refresh
13205
+ });
13206
+ let summary = visible.length === rows.length ? `${rows.length} item${rows.length > 1 ? "s" : ""}` : `${visible.length} of ${rows.length}`, subtitleKey = visibleColumns.find((c, i) => i > 0 && c.kind === "text")?.key;
13207
+ return /* @__PURE__ */ jsxs(Stack, {
13208
+ gap: 3,
13209
+ children: [/* @__PURE__ */ jsx(CollectionToolbar, {
13210
+ view,
13211
+ onView: setView,
13212
+ search,
13213
+ onSearch: setSearch,
13214
+ columns: allColumns,
13215
+ visible: visibleKeys,
13216
+ onToggleColumn,
13217
+ onExport,
13218
+ onRefresh: refresh,
13219
+ onCreate,
13220
+ busy: loading,
13221
+ summary
13222
+ }), loading && rows.length === 0 ? /* @__PURE__ */ jsxs(Flex, {
13223
+ align: "center",
13224
+ justify: "center",
13225
+ padding: 6,
13226
+ gap: 3,
13227
+ children: [/* @__PURE__ */ jsx(Spinner, { muted: !0 }), /* @__PURE__ */ jsx(Text, {
13228
+ size: 1,
13229
+ muted: !0,
13230
+ children: "Loading…"
13231
+ })]
13232
+ }) : visibleColumns.length === 0 ? /* @__PURE__ */ jsx(Box, {
13233
+ padding: 5,
13234
+ children: /* @__PURE__ */ jsx(Text, {
13235
+ size: 1,
13236
+ muted: !0,
13237
+ align: "center",
13238
+ children: "No displayable field in this type. Pick columns above."
13239
+ })
13240
+ }) : view === "list" ? /* @__PURE__ */ jsxs(Box, {
13241
+ style: {
13242
+ border: `1px solid ${BORDER_SOFT}`,
13243
+ borderRadius: 6
13244
+ },
13245
+ children: [/* @__PURE__ */ jsx("style", { children: ".ncf-coll-body a{display:contents;color:inherit;text-decoration:none}" }), /* @__PURE__ */ jsxs(Box, {
13246
+ className: "ncf-coll-body",
13247
+ children: [visible.map((row) => /* @__PURE__ */ jsx(ChildLink, {
13248
+ childId: row.id,
13249
+ children: /* @__PURE__ */ jsx(ListRowView, {
13250
+ row,
13251
+ titleKey: visibleColumns[0]?.key,
13252
+ subtitleKey
13253
+ })
13254
+ }, row.id)), visible.length === 0 && /* @__PURE__ */ jsx(Box, {
13255
+ padding: 5,
13256
+ children: /* @__PURE__ */ jsx(Text, {
13257
+ size: 1,
13258
+ muted: !0,
13259
+ align: "center",
13260
+ children: rows.length === 0 ? "No item yet." : "No match."
13261
+ })
13262
+ })]
13263
+ })]
13264
+ }) : /* @__PURE__ */ jsxs(Box, {
13265
+ style: {
13266
+ overflowX: "auto",
13267
+ border: `1px solid ${BORDER_SOFT}`,
13268
+ borderRadius: 6
13269
+ },
13270
+ children: [/* @__PURE__ */ jsx("style", { children: ".ncf-coll-body a{display:contents;color:inherit;text-decoration:none}" }), /* @__PURE__ */ jsxs(Box, {
13271
+ style: {
13272
+ width: totalWidth,
13273
+ minWidth: "100%"
13274
+ },
13275
+ children: [/* @__PURE__ */ jsx(Flex, {
13276
+ paddingX: 3,
13277
+ paddingY: 2,
13278
+ align: "flex-end",
13279
+ style: {
13280
+ borderBottom: `1px solid ${BORDER}`,
13281
+ position: "sticky",
13282
+ top: 0,
13283
+ background: "var(--card-bg-color, inherit)",
13284
+ zIndex: 2
13285
+ },
13286
+ children: cols.map(({ column, width }) => {
13287
+ let active = sort.key === column.key, Arrow = sort.direction === "asc" ? ChevronUpIcon : ChevronDownIcon;
13288
+ return /* @__PURE__ */ jsxs(Box, {
13289
+ paddingRight: 2,
13290
+ onDragOver: (e) => {
13291
+ dragKeyRef.current && dragKeyRef.current !== column.key && (e.preventDefault(), setDragOverKey(column.key));
13292
+ },
13293
+ onDrop: () => onReorder(column.key),
13294
+ style: {
13295
+ width,
13296
+ flex: "none",
13297
+ position: "relative",
13298
+ boxSizing: "border-box",
13299
+ borderLeft: dragOverKey === column.key ? "2px solid var(--card-focus-ring-color, #2276fc)" : "2px solid transparent"
13300
+ },
13301
+ children: [/* @__PURE__ */ jsxs(Stack, {
13302
+ gap: 2,
13303
+ style: CELL,
13304
+ children: [/* @__PURE__ */ jsxs(Flex, {
13305
+ align: "center",
13306
+ gap: 1,
13307
+ draggable: !0,
13308
+ onDragStart: () => {
13309
+ dragKeyRef.current = column.key;
13310
+ },
13311
+ onDragEnd: () => {
13312
+ dragKeyRef.current = null, setDragOverKey(null);
13313
+ },
13314
+ onClick: () => onSort(column.key),
13315
+ style: {
13316
+ cursor: "grab",
13317
+ userSelect: "none"
13318
+ },
13319
+ title: `Sort by ${column.label.toLowerCase()} — drag to reorder`,
13320
+ children: [/* @__PURE__ */ jsx(Text, {
13321
+ size: 0,
13322
+ weight: "medium",
13323
+ muted: !active,
13324
+ textOverflow: "ellipsis",
13325
+ children: column.label
13326
+ }), active && /* @__PURE__ */ jsx(Arrow, { style: {
13327
+ fontSize: 12,
13328
+ opacity: .7,
13329
+ flex: "none"
13330
+ } })]
13331
+ }), /* @__PURE__ */ jsx("input", {
13332
+ type: "text",
13333
+ value: columnFilters[column.key] ?? "",
13334
+ placeholder: "Filter…",
13335
+ onChange: (event) => onColumnFilter(column.key, event.currentTarget.value),
13336
+ style: {
13337
+ width: "100%",
13338
+ boxSizing: "border-box",
13339
+ font: "inherit",
13340
+ fontSize: 11,
13341
+ padding: "3px 6px",
13342
+ borderRadius: 3,
13343
+ border: `1px solid ${BORDER_SOFT}`,
13344
+ background: "var(--card-bg-color)",
13345
+ color: "var(--card-fg-color)",
13346
+ outline: "none"
13347
+ }
13348
+ })]
13349
+ }), /* @__PURE__ */ jsx("div", {
13350
+ onPointerDown: onResizeStart(column.key, width),
13351
+ title: "Drag to resize",
13352
+ style: {
13353
+ position: "absolute",
13354
+ top: 0,
13355
+ right: 0,
13356
+ width: 9,
13357
+ height: "100%",
13358
+ cursor: "col-resize",
13359
+ touchAction: "none"
13360
+ }
13361
+ })]
13362
+ }, column.key);
13363
+ })
13364
+ }), /* @__PURE__ */ jsxs(Box, {
13365
+ className: "ncf-coll-body",
13366
+ children: [visible.map((row) => /* @__PURE__ */ jsx(ChildLink, {
13367
+ childId: row.id,
13368
+ children: /* @__PURE__ */ jsx(TableRowView, {
13369
+ row,
13370
+ cols
13371
+ })
13372
+ }, row.id)), visible.length === 0 && /* @__PURE__ */ jsx(Box, {
13373
+ padding: 5,
13374
+ children: /* @__PURE__ */ jsx(Text, {
13375
+ size: 1,
13376
+ muted: !0,
13377
+ align: "center",
13378
+ children: rows.length === 0 ? "No item yet." : "No match."
13379
+ })
13380
+ })]
13381
+ })]
13382
+ })]
13383
+ })]
13384
+ });
13385
+ }
13386
+ /** Ligne de la vue TABLE : une cellule par colonne, largeurs fixes. */
13387
+ function TableRowView(props) {
13388
+ let { row, cols } = props, [hovered, setHovered] = useState(!1);
13389
+ return /* @__PURE__ */ jsx(Flex, {
13390
+ paddingX: 3,
13391
+ paddingY: 2,
13392
+ onMouseEnter: () => setHovered(!0),
13393
+ onMouseLeave: () => setHovered(!1),
13394
+ style: {
13395
+ cursor: "pointer",
13396
+ borderBottom: `1px solid ${BORDER_SOFT}`,
13397
+ background: hovered ? "var(--card-muted-bg-color, rgba(127,127,127,0.08))" : "transparent"
13398
+ },
13399
+ children: cols.map(({ column, width }, index) => {
13400
+ let cell = row.cells[column.key], empty = !cell || cell.raw === null || cell.text === "";
13401
+ return /* @__PURE__ */ jsxs(Flex, {
13402
+ align: "center",
13403
+ gap: 2,
13404
+ paddingRight: 2,
13405
+ style: {
13406
+ width,
13407
+ flex: "none",
13408
+ boxSizing: "border-box"
13409
+ },
13410
+ children: [/* @__PURE__ */ jsx(Text, {
13411
+ size: 0,
13412
+ muted: empty,
13413
+ weight: index === 0 ? "medium" : "regular",
13414
+ textOverflow: "ellipsis",
13415
+ style: {
13416
+ flex: 1,
13417
+ minWidth: 0,
13418
+ ...column.kind === "number" || column.kind === "date" ? TABULAR : null
13419
+ },
13420
+ children: empty ? "—" : cell.text
13421
+ }), index === 0 && row.draftOnly && /* @__PURE__ */ jsx(Badge, {
13422
+ tone: "caution",
13423
+ fontSize: 0,
13424
+ style: { flex: "none" },
13425
+ children: "Draft"
13426
+ })]
13427
+ }, column.key);
13428
+ })
13429
+ });
13430
+ }
13431
+ /** Ligne de la vue LISTE : titre + sous-titre, façon liste native. */
13432
+ function ListRowView(props) {
13433
+ let { row, titleKey, subtitleKey } = props, [hovered, setHovered] = useState(!1), title = titleKey ? row.cells[titleKey]?.text : "", subtitle = subtitleKey ? row.cells[subtitleKey]?.text : "";
13434
+ return /* @__PURE__ */ jsxs(Flex, {
13435
+ align: "center",
13436
+ gap: 2,
13437
+ paddingX: 3,
13438
+ paddingY: 2,
13439
+ onMouseEnter: () => setHovered(!0),
13440
+ onMouseLeave: () => setHovered(!1),
13441
+ style: {
13442
+ cursor: "pointer",
13443
+ borderBottom: `1px solid ${BORDER_SOFT}`,
13444
+ background: hovered ? "var(--card-muted-bg-color, rgba(127,127,127,0.08))" : "transparent"
13445
+ },
13446
+ children: [/* @__PURE__ */ jsxs(Stack, {
13447
+ gap: 2,
13448
+ flex: 1,
13449
+ style: { minWidth: 0 },
13450
+ children: [/* @__PURE__ */ jsx(Text, {
13451
+ size: 1,
13452
+ weight: "medium",
13453
+ textOverflow: "ellipsis",
13454
+ children: title || "Untitled"
13455
+ }), subtitle ? /* @__PURE__ */ jsx(Text, {
13456
+ size: 0,
13457
+ muted: !0,
13458
+ textOverflow: "ellipsis",
13459
+ children: subtitle
13460
+ }) : null]
13461
+ }), row.draftOnly && /* @__PURE__ */ jsx(Badge, {
13462
+ tone: "caution",
13463
+ fontSize: 0,
13464
+ style: { flex: "none" },
13465
+ children: "Draft"
13466
+ })]
13467
+ });
13468
+ }
13469
+ const isReserved = (name) => name.startsWith("sanity.") || name.startsWith("_");
13470
+ /**
13471
+ * Types de collection retenus.
13472
+ *
13473
+ * - `include` fournie → on respecte cette liste (dans son ordre), en gardant
13474
+ * seulement ce qui est un type de document connu et hors `exclude`.
13475
+ * - sinon → tous les types de documents, moins `exclude` et les types réservés,
13476
+ * triés par nom pour une liste stable.
13477
+ */
13478
+ function discoverCollectionTypes(types, options = {}) {
13479
+ let excluded = new Set(options.exclude ?? []), documents = new Set(types.filter((t) => t.jsonType === "document").map((t) => t.name));
13480
+ if (options.include?.length) {
13481
+ let seen = /* @__PURE__ */ new Set();
13482
+ return options.include.filter((name) => seen.has(name) || excluded.has(name) || !documents.has(name) ? !1 : (seen.add(name), !0));
13483
+ }
13484
+ return [...documents].filter((name) => !excluded.has(name) && !isReserved(name)).sort((a, b) => a.localeCompare(b));
13485
+ }
13486
+ /**
13487
+ * Composant de panneau pour une collection. Le type arrive par les `options`
13488
+ * du pane de structure ; la configuration est fermée par la fabrique (elle
13489
+ * n'est pas sérialisable dans les options).
13490
+ */
13491
+ function createCollectionPane(config, issues) {
13492
+ return function NcfCollectionPane(props) {
13493
+ let opts = props.options ?? {}, type = typeof opts.type == "string" ? opts.type : "", filter = typeof opts.filter == "string" ? opts.filter : void 0, params = opts.params && typeof opts.params == "object" ? opts.params : void 0, newTemplate = typeof opts.newTemplate == "string" ? opts.newTemplate : void 0;
13494
+ return /* @__PURE__ */ jsx(KitProvider, {
13495
+ config,
13496
+ issues,
13497
+ children: /* @__PURE__ */ jsx(Box, {
13498
+ padding: 3,
13499
+ height: "fill",
13500
+ overflow: "auto",
13501
+ children: type ? /* @__PURE__ */ jsx(CollectionTable, {
13502
+ type,
13503
+ filter,
13504
+ params,
13505
+ newTemplate
13506
+ }) : null
13507
+ })
13508
+ });
13509
+ };
13510
+ }
13511
+ /**
13512
+ * Vue table d'UNE collection, à utiliser comme enfant d'une entrée de structure
13513
+ * pour que cliquer la collection ouvre la table (au lieu de la liste native) :
13514
+ *
13515
+ * ```ts
13516
+ * S.listItem().title('Articles').child(ncfCollectionTable(S, ncfOptions, 'article'))
13517
+ * ```
13518
+ *
13519
+ * `filter`/`params` posent la table au **niveau feuille** (une langue, une
13520
+ * catégorie…) sans mélanger le reste ; `newTemplate` garde la création
13521
+ * pré-taguée de ce niveau ; `id` sert quand un même type a plusieurs tables
13522
+ * (ex. une par langue), pour des identifiants de structure uniques.
13523
+ *
13524
+ * ```ts
13525
+ * S.documentList() // ancien niveau feuille…
13526
+ * ncfCollectionTable(S, ncfOptions, 'newsArticle', {
13527
+ * id: `ncf-col-newsArticle-${lang}`,
13528
+ * title: `News (${lang})`,
13529
+ * filter: 'language == $lang',
13530
+ * params: {lang},
13531
+ * newTemplate: `newsArticle-${lang}`,
13532
+ * })
13533
+ * ```
13534
+ */
13535
+ function ncfCollectionTable(S, options, type, opts = {}) {
13536
+ let config = resolveConfig(options), pane = createCollectionPane(config, validateConfig(config));
13537
+ return S.component(pane).id(opts.id ?? `ncf-collection-${type}`).title(opts.title ?? type).options({
13538
+ type,
13539
+ filter: opts.filter,
13540
+ params: opts.params,
13541
+ newTemplate: opts.newTemplate
13542
+ }).child((childId) => S.document().schemaType(type).documentId(childId));
13543
+ }
13544
+ /** Libellé d'une entrée de collection : config, puis titre du schéma, puis nom humanisé. */
13545
+ function labelFor(type, config, schemaTitle) {
13546
+ return config.collections.labels[type] ?? schemaTitle ?? humanise(type);
13547
+ }
13548
+ /** Types toujours écartés de la découverte, en plus de l'`exclude` du projet. */
13549
+ function reservedExcludes(config) {
13550
+ return [
13551
+ ...config.pageTypeNames,
13552
+ config.redirectType,
13553
+ config.componentPreview.defaultsType,
13554
+ ...NCF_HIDDEN_TYPES,
13555
+ ...config.collections.exclude
13556
+ ].filter(Boolean);
13557
+ }
13558
+ /**
13559
+ * Entrées « collection » pour la structure du Studio, une par type découvert,
13560
+ * chacune ouvrant la vue table. À épandre dans la liste racine :
13561
+ *
13562
+ * ```ts
13563
+ * structure: (S, context) =>
13564
+ * S.list().title('Contenu').items([..., ...ncfCollections(S, context, ncfOptions)])
13565
+ * ```
13566
+ */
13567
+ function ncfCollections(S, context, options) {
13568
+ let config = resolveConfig(options);
13569
+ return discoverCollectionTypes(context.schema.getTypeNames().map((name) => ({
13570
+ name,
13571
+ jsonType: context.schema.get(name)?.jsonType
13572
+ })), {
13573
+ include: config.collections.include,
13574
+ exclude: reservedExcludes(config)
13575
+ }).map((type) => {
13576
+ let schemaType = context.schema.get(type), label = labelFor(type, config, schemaType?.title), item = S.listItem().id(`ncf-collection-${type}`).title(label).child(ncfCollectionTable(S, options, type, { title: label }));
13577
+ return schemaType?.icon ? item.icon(schemaType.icon) : item;
13578
+ });
13579
+ }
12673
13580
  const SAFE = /^[A-Za-z0-9_.-]+$/, quote = (value) => JSON.stringify(value);
12674
13581
  /**
12675
13582
  * Presentation : le document du panneau de droite est TOUJOURS celui de la page
@@ -12868,6 +13775,6 @@ function hasLanguageField(schemaType, field) {
12868
13775
  let fields = schemaType?.fields;
12869
13776
  return Array.isArray(fields) && fields.some((f) => f?.name === field);
12870
13777
  }
12871
- export { ANNOTATION_TYPE, ActorName, AssetSourceBrowser, AssetsTool, 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_ASSETS_TOOL, 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, assetName, assetsInFolder, assignmentMap, baseId, blockName, blockTypesFromSchema, buildContentsQuery, buildLinkGraph, buildPageRows, buildPagesQuery, codeEditorInput, collectLinks, collectOccurrences, colorForRow, colorFromString, columnId, compareVersions, componentDefaultsMainDocument, componentDefaultsMainDocuments, countByFolder, createPreviewLauncher, customEnvironment, defaultNodeSize, defaultsFieldName, defineCodeEmbedType, defineComponentDefaults, depth, deriveDocumentColumns, detectPageBuilderField, diffDocuments, diffWords, editIntentPath, explainGrantError, fallbackLayout, fetchDetail, fetchTimeline, fillTemplate, filterAssets, filterRows, fixCrossLanguageReferences, flatten, formatBytes, formatDocumentValue, groupComponents, groupMap, groupPageRows, groupValue, hasBlockingIssue, humanizeBlockName, isDraftId, isImageAsset, isKitType, isPrerelease, isSafeColumnKey, isSafeFieldPath, isTextChange, isVersionId, issuesForTool, keyForPath, kitSchemaTypes, layoutGraph, layoutSectionsMap, localesInRows, mergeVersions, missingPageTypes, moveColumn, nameMap, ncfAllowedOrigins, ncfKit, ncfMainDocuments, ncfPresentationComponents, ncfPreviewComponents, normalizeInternalPath, normalizePath, occurrencesForTypes, pageThumbnailUrl, pageTypeFor, pageTypesFromSiteRoutes, pageTypesWithoutBuilder, parentPath, presentationPath, pruneSavedPositions, releaseId, removeColumn, renameColumn, requestPreviewGrant, requiredUnlessDefault, requiredUnlessDefaultFor, resolveColorBy, resolveConfig, resolvePageBuilderField, sectionNamesFromDefaults, segments, slugKey, sortAssets, sortRows, summarize, thumbnailUrl, toKebabCase, toPath, toUrl, topLevelBlockCount, uniqueColumnId, upsertLayout, urlOn, useAnnotations, useAssetMeta, useAssetUpload, useAssets, useBoardLayout, useComponentNames, useDocumentColumns, useHistory, useInternalColumns, useKitClient, useKitConfig, useKitContext, useKitUpdate, useOccurrences, useOptionalKitConfig, useOptionalKitContext, usePageBuilder, usePageContents, usePages, usePreviewTarget, useRegistration, validateConfig, withAlpha, withCustomNames, withMoreTool, withSameLanguageReferences };
13778
+ export { ANNOTATION_TYPE, ActorName, AssetSourceBrowser, AssetsTool, 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, CollectionTable, 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_ASSETS_TOOL, 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, assetName, assetsInFolder, assignmentMap, baseId, blockName, blockTypesFromSchema, buildCollectionQuery, buildCollectionRows, buildContentsQuery, buildLinkGraph, buildPageRows, buildPagesQuery, codeEditorInput, collectLinks, collectOccurrences, colorForRow, colorFromString, columnId, compareVersions, componentDefaultsMainDocument, componentDefaultsMainDocuments, countByFolder, createPreviewLauncher, customEnvironment, defaultNodeSize, defaultsFieldName, defineCodeEmbedType, defineComponentDefaults, depth, deriveCollectionColumns, deriveDocumentColumns, detectPageBuilderField, diffDocuments, diffWords, discoverCollectionTypes, downloadText, editIntentPath, explainGrantError, fallbackLayout, fetchDetail, fetchTimeline, fillTemplate, filterAssets, filterRows as filterCollectionRows, filterRows$1 as filterRows, fixCrossLanguageReferences, flatten, formatBytes, formatDocumentValue, groupComponents, groupMap, groupPageRows, groupValue, hasBlockingIssue, humanizeBlockName, isDraftId, isImageAsset, isKitType, isPrerelease, isSafeColumnKey, isSafeFieldPath, isTextChange, isVersionId, issuesForTool, keyForPath, kitSchemaTypes, layoutGraph, layoutSectionsMap, localesInRows, mergeVersions, missingPageTypes, moveColumn, nameMap, ncfAllowedOrigins, ncfCollectionTable, ncfCollections, ncfKit, ncfMainDocuments, ncfPresentationComponents, ncfPreviewComponents, normalizeInternalPath, normalizePath, occurrencesForTypes, pageThumbnailUrl, pageTypeFor, pageTypesFromSiteRoutes, pageTypesWithoutBuilder, parentPath, presentationPath, pruneSavedPositions, releaseId, removeColumn, renameColumn, requestPreviewGrant, requiredUnlessDefault, requiredUnlessDefaultFor, resolveColorBy, resolveConfig, resolvePageBuilderField, sectionNamesFromDefaults, segments, slugKey, sortAssets, sortRows as sortCollectionRows, sortRows$1 as sortRows, summarize, thumbnailUrl, titleColumn, toCsv, toKebabCase, toPath, toUrl, topLevelBlockCount, uniqueColumnId, upsertLayout, urlOn, useAnnotations, useAssetMeta, useAssetUpload, useAssets, useBoardLayout, useCollection, useComponentNames, useDocumentColumns, useHistory, useInternalColumns, useKitClient, useKitConfig, useKitContext, useKitUpdate, useOccurrences, useOptionalKitConfig, useOptionalKitContext, usePageBuilder, usePageContents, usePages, usePreviewTarget, useRegistration, validateConfig, withAlpha, withCustomNames, withMoreTool, withSameLanguageReferences };
12872
13779
 
12873
13780
  //# sourceMappingURL=index.js.map