@nocode-factory/sanity-kit 2.16.0 → 2.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1303,7 +1303,7 @@ export declare function ActorName(props: {
1303
1303
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1304
1304
  * le vérifie.
1305
1305
  */
1306
- export declare const KIT_VERSION = "2.16.0";
1306
+ export declare const KIT_VERSION = "2.17.1";
1307
1307
  /**
1308
1308
  * Données de la page proposées comme colonnes.
1309
1309
  *
package/dist/index.js CHANGED
@@ -34,6 +34,7 @@ import "@xyflow/react/dist/style.css";
34
34
  import { TrashIcon } from "@sanity/icons/Trash";
35
35
  import { RefreshIcon } from "@sanity/icons/Refresh";
36
36
  import { RestoreIcon } from "@sanity/icons/Restore";
37
+ import { UndoIcon } from "@sanity/icons/Undo";
37
38
  import { Tooltip } from "@sanity/ui/tooltip";
38
39
  const DEFAULT_PAGE_BUILDER_FIELD = "sections", DEFAULT_SLUG_FIELD = "slug", DEFAULT_TITLE_FIELD = "title", DEFAULT_NOINDEX_FIELDS = ["seo.noindex", "noindex"], DEFAULT_I18N = {
39
40
  field: "language",
@@ -1045,6 +1046,19 @@ function effectivePerspective(environment, perspective, previewUrl) {
1045
1046
  return environment && isPublicEnvironment(environment, previewUrl) ? "published" : perspective;
1046
1047
  }
1047
1048
  /**
1049
+ * Environnement où ouvrir Presentation : on n'édite jamais la production (elle ne
1050
+ * montre pas les brouillons et ne charge pas l'édition visuelle : « Unable to
1051
+ * connect »). Production choisie : la première préversion déclarée, qui montrera
1052
+ * le contenu en ligne. Sans préversion : l'environnement choisi, tel quel.
1053
+ */
1054
+ function editableEnvironment(selected, environments, previewUrl) {
1055
+ return !selected || !isPublicEnvironment(selected, previewUrl) ? selected : environments.find((e) => !isPublicEnvironment(e, previewUrl)) ?? selected;
1056
+ }
1057
+ /** Environnement proposé par défaut : la première préversion, sinon le premier déclaré. */
1058
+ function defaultEnvironmentId(environments, previewUrl) {
1059
+ return (environments.find((e) => !isPublicEnvironment(e, previewUrl)) ?? environments[0])?.id ?? null;
1060
+ }
1061
+ /**
1048
1062
  * URL du vrai site, en ligne, pour un environnement et un état de contenu.
1049
1063
  *
1050
1064
  * - Production : l'URL simple. Elle ne montre jamais de brouillons, et la
@@ -1177,7 +1191,7 @@ function write(key, value) {
1177
1191
  * différents sans se déranger.
1178
1192
  */
1179
1193
  function usePreviewTargetState() {
1180
- let config = useKitConfig(), scope = `ncf-kit:preview-target:${useKitClient().config().projectId ?? "sans-projet"}`, environments = config.environments, fallback = environments[0]?.id ?? null, [environmentId, setStoredEnvironment] = useState(() => {
1194
+ let config = useKitConfig(), scope = `ncf-kit:preview-target:${useKitClient().config().projectId ?? "sans-projet"}`, environments = config.environments, fallback = defaultEnvironmentId(environments, config.previewUrl), [environmentId, setStoredEnvironment] = useState(() => {
1181
1195
  let saved = read(`${scope}:environment`);
1182
1196
  return saved && environments.some((e) => e.id === saved) ? saved : fallback;
1183
1197
  }), [customUrl, setStoredCustomUrl] = useState(() => read(`${scope}:custom`)), [perspective, setStoredPerspective] = useState(() => read(`${scope}:perspective`) === "published" ? "published" : "drafts"), setEnvironment = useCallback((id) => {
@@ -1189,9 +1203,14 @@ function usePreviewTargetState() {
1189
1203
  setEnvironment,
1190
1204
  fallback
1191
1205
  ]), shown = effectivePerspective(environment, perspective, config.previewUrl), pathFor = useCallback((url) => presentationPath(url, {
1192
- environment,
1206
+ environment: editableEnvironment(environment, allEnvironments, config.previewUrl),
1193
1207
  perspective: shown
1194
- }), [environment, shown]), siteUrlFor = useCallback((url) => {
1208
+ }), [
1209
+ environment,
1210
+ allEnvironments,
1211
+ config.previewUrl,
1212
+ shown
1213
+ ]), siteUrlFor = useCallback((url) => {
1195
1214
  if (!url) return null;
1196
1215
  if (!environment) return url;
1197
1216
  try {
@@ -1361,7 +1380,7 @@ function explainGrantError(error) {
1361
1380
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1362
1381
  * le vérifie.
1363
1382
  */
1364
- const KIT_VERSION = "2.16.0";
1383
+ const KIT_VERSION = "2.17.1";
1365
1384
  /**
1366
1385
  * Signale ce Studio au service du kit, une fois par montage.
1367
1386
  *
@@ -1688,7 +1707,7 @@ function useKitUpdate() {
1688
1707
  !controller.signal.aborted && body?.version && setLatest(body.version);
1689
1708
  }).catch(() => {}), () => controller.abort();
1690
1709
  }, []);
1691
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.16.0") > 0);
1710
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.17.1") > 0);
1692
1711
  return {
1693
1712
  current: KIT_VERSION,
1694
1713
  latest,
@@ -1946,9 +1965,9 @@ function NcfPreviewLauncher(props) {
1946
1965
  }), /* @__PURE__ */ jsx(NcfKitUpdate, { inline: props.context === "topbar" })]
1947
1966
  });
1948
1967
  let openInStudio = (environment, perspective) => {
1949
- let path = presentationPath(environment.url, {
1950
- environment,
1951
- perspective
1968
+ let target = editableEnvironment(environment, environments, config.previewUrl) ?? environment, shown = isPublicEnvironment(environment, config.previewUrl) ? "published" : perspective, path = presentationPath(target.url, {
1969
+ environment: target,
1970
+ perspective: shown
1952
1971
  });
1953
1972
  path && router.navigateUrl({ path });
1954
1973
  }, openOnline = (environment, perspective) => {
@@ -5916,7 +5935,7 @@ async function openDesignSystem(options) {
5916
5935
  navigateIntent("edit", designSystemIntentParams(config, await defaultsDocumentId(config, client) ?? config.componentPreview.defaultsType));
5917
5936
  return;
5918
5937
  }
5919
- let path = presentationPath(config.previewUrl ? `${config.previewUrl}${config.componentPreview.path}` : null);
5938
+ let env = editableEnvironment(config.environments[0] ?? null, config.environments, config.previewUrl), path = presentationPath(urlOn(env, config.componentPreview.path) ?? (config.previewUrl ? `${config.previewUrl}${config.componentPreview.path}` : null), env ? { environment: env } : {});
5920
5939
  path && navigateUrl(path);
5921
5940
  }
5922
5941
  /** Ouvre un composant (voir openComponentDefaults). `null` : rien à ouvrir. */
@@ -6696,13 +6715,13 @@ function useHistory(documentId) {
6696
6715
  * noierait les vraies modifications sous du bruit. `_id` et `_type` ne
6697
6716
  * changent pas sans que ce soit un autre document.
6698
6717
  */
6699
- const SYSTEM_KEYS = /* @__PURE__ */ new Set([
6718
+ const SYSTEM_KEYS$1 = /* @__PURE__ */ new Set([
6700
6719
  "_rev",
6701
6720
  "_updatedAt",
6702
6721
  "_createdAt",
6703
6722
  "_id",
6704
6723
  "_type"
6705
- ]), NOISE_KEYS = /* @__PURE__ */ new Set(["_key"]), isObject = (value) => typeof value == "object" && !!value && !Array.isArray(value);
6724
+ ]), NOISE_KEYS = /* @__PURE__ */ new Set(["_key"]), isObject$1 = (value) => typeof value == "object" && !!value && !Array.isArray(value);
6706
6725
  /**
6707
6726
  * Aplatit un document en chemins terminaux.
6708
6727
  *
@@ -6712,9 +6731,9 @@ const SYSTEM_KEYS = /* @__PURE__ */ new Set([
6712
6731
  */
6713
6732
  function flatten(value, prefix = "", out = /* @__PURE__ */ new Map()) {
6714
6733
  if (Array.isArray(value)) return value.forEach((item, index) => {
6715
- flatten(item, `${prefix}[${isObject(item) && typeof item._key == "string" ? item._key : String(index)}]`, out);
6734
+ flatten(item, `${prefix}[${isObject$1(item) && typeof item._key == "string" ? item._key : String(index)}]`, out);
6716
6735
  }), out;
6717
- if (isObject(value)) {
6736
+ if (isObject$1(value)) {
6718
6737
  let keys = Object.keys(value).filter((key) => !NOISE_KEYS.has(key));
6719
6738
  keys.length === 0 && prefix && out.set(prefix, {});
6720
6739
  for (let key of keys) flatten(value[key], prefix ? `${prefix}.${key}` : key, out);
@@ -6722,7 +6741,7 @@ function flatten(value, prefix = "", out = /* @__PURE__ */ new Map()) {
6722
6741
  }
6723
6742
  return prefix && out.set(prefix, value), out;
6724
6743
  }
6725
- const same = (a, b) => a === b || Number.isNaN(a) && Number.isNaN(b) || JSON.stringify(a) === JSON.stringify(b);
6744
+ const same$1 = (a, b) => a === b || Number.isNaN(a) && Number.isNaN(b) || JSON.stringify(a) === JSON.stringify(b);
6726
6745
  /**
6727
6746
  * Modifications entre deux états, triées par chemin.
6728
6747
  *
@@ -6735,7 +6754,7 @@ function diffDocuments(before, after) {
6735
6754
  for (let path of paths) {
6736
6755
  let had = left.has(path), has = right.has(path), valueBefore = left.get(path), valueAfter = right.get(path);
6737
6756
  if (had && has) {
6738
- same(valueBefore, valueAfter) || changes.push({
6757
+ same$1(valueBefore, valueAfter) || changes.push({
6739
6758
  path,
6740
6759
  kind: "changed",
6741
6760
  before: valueBefore,
@@ -6760,7 +6779,7 @@ function diffDocuments(before, after) {
6760
6779
  /** Un chemin système, à la racine comme au fond d'un tableau. */
6761
6780
  function isSystemPath(path) {
6762
6781
  let last = path.split(".").pop() ?? "";
6763
- return SYSTEM_KEYS.has(last);
6782
+ return SYSTEM_KEYS$1.has(last);
6764
6783
  }
6765
6784
  /**
6766
6785
  * Résumé d'un changement en une ligne.
@@ -6812,7 +6831,55 @@ function diffWords(before, after, limit = 400) {
6812
6831
  return segments;
6813
6832
  }
6814
6833
  /** Une comparaison mot à mot n'a de sens qu'entre deux textes. */
6815
- const isTextChange = (before, after) => typeof before == "string" && typeof after == "string", MARK = {
6834
+ const isTextChange = (before, after) => typeof before == "string" && typeof after == "string", SYSTEM_KEYS = /* @__PURE__ */ new Set([
6835
+ "_rev",
6836
+ "_updatedAt",
6837
+ "_createdAt",
6838
+ "_id",
6839
+ "_type"
6840
+ ]), isObject = (v) => typeof v == "object" && !!v && !Array.isArray(v), same = (a, b) => JSON.stringify(a) === JSON.stringify(b), keyed = (v) => Array.isArray(v) && v.every((item) => isObject(item) && typeof item._key == "string"), ABSENT = Symbol("absent");
6841
+ function revert(current, before, after, path, out) {
6842
+ if (same(before, after)) return current;
6843
+ if (same(current, after)) return out.reverted++, before;
6844
+ if (isObject(current) && isObject(before) && isObject(after)) {
6845
+ let result = { ...current };
6846
+ for (let key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])) {
6847
+ if (SYSTEM_KEYS.has(key)) continue;
6848
+ let v = revert(key in current ? current[key] : ABSENT, key in before ? before[key] : ABSENT, key in after ? after[key] : ABSENT, path ? `${path}.${key}` : key, out);
6849
+ v === ABSENT ? delete result[key] : result[key] = v;
6850
+ }
6851
+ return result;
6852
+ }
6853
+ if (keyed(current) && keyed(before) && keyed(after)) {
6854
+ let result = [...current], at = (list, key) => list.findIndex((item) => item._key === key);
6855
+ for (let key of /* @__PURE__ */ new Set([...before.map((i) => i._key), ...after.map((i) => i._key)])) {
6856
+ let b = before[at(before, key)], a = after[at(after, key)], index = at(result, key), label = `${path}[${key}]`;
6857
+ if (index >= 0) {
6858
+ let v = revert(result[index], b ?? ABSENT, a ?? ABSENT, label, out);
6859
+ v === ABSENT ? result.splice(index, 1) : result[index] = v;
6860
+ } else b && !a ? (result.splice(Math.min(at(before, key), result.length), 0, b), out.reverted++) : b && a && !same(a, b) && out.conflicts.push(label);
6861
+ }
6862
+ return result;
6863
+ }
6864
+ return out.conflicts.push(path || "(document)"), current;
6865
+ }
6866
+ /**
6867
+ * Annule l'événement `before` → `after` dans `current` (brouillon ou version
6868
+ * publiée actuelle). `current` absent (document supprimé depuis) : l'état
6869
+ * d'avant l'événement.
6870
+ */
6871
+ function undoChange(current, before, after) {
6872
+ let out = {
6873
+ conflicts: [],
6874
+ reverted: 0
6875
+ }, document = revert(current ?? after ?? {}, before ?? {}, after ?? {}, "", out);
6876
+ return {
6877
+ document: isObject(document) ? document : {},
6878
+ conflicts: out.conflicts,
6879
+ reverted: out.reverted
6880
+ };
6881
+ }
6882
+ const MARK = {
6816
6883
  removed: {
6817
6884
  sign: "−",
6818
6885
  line: DIFF.removedLine,
@@ -6929,11 +6996,11 @@ function ActorName(props) {
6929
6996
  * client, et une restauration reste attribuée à qui l'a demandée.
6930
6997
  */
6931
6998
  function DiffPanel(props) {
6932
- let { event, onClose } = props, config = useKitConfig(), client = useKitClient(), [detail, setDetail] = useState(null), [loading, setLoading] = useState(!0), [error, setError] = useState(null), [restoring, setRestoring] = useState(!1), [restored, setRestored] = useState(null);
6999
+ let { event, onClose } = props, config = useKitConfig(), client = useKitClient(), [detail, setDetail] = useState(null), [loading, setLoading] = useState(!0), [error, setError] = useState(null), [restoring, setRestoring] = useState(!1), [restored, setRestored] = useState(null), [conflicts, setConflicts] = useState([]);
6933
7000
  useEffect(() => {
6934
7001
  if (!config.history) return;
6935
7002
  let controller = new AbortController();
6936
- return setLoading(!0), setError(null), setRestored(null), fetchDetail(config.history.endpoint, config.history.projectKey, event.id, controller.signal).then((result) => {
7003
+ return setLoading(!0), setError(null), setRestored(null), setConflicts([]), fetchDetail(config.history.endpoint, config.history.projectKey, event.id, controller.signal).then((result) => {
6937
7004
  controller.signal.aborted || setDetail(result);
6938
7005
  }).catch(() => {
6939
7006
  controller.signal.aborted || setError("Ce détail n'a pas pu être chargé.");
@@ -6941,23 +7008,29 @@ function DiffPanel(props) {
6941
7008
  controller.signal.aborted || setLoading(!1);
6942
7009
  }), () => controller.abort();
6943
7010
  }, [config.history, event.id]);
6944
- let snapshot = detail?.current.snapshot ?? null, changes = detail ? diffDocuments(detail.previous?.snapshot ?? null, snapshot) : [], restore = async () => {
6945
- if (snapshot) {
6946
- setRestoring(!0), setError(null);
6947
- try {
6948
- let { _rev, _createdAt, _updatedAt, ...content } = snapshot, base = event.document_id.replace(/^drafts\./, "");
6949
- await client.createOrReplace({
6950
- ...content,
6951
- _id: `drafts.${base}`,
6952
- _type: event.document_type
6953
- }), setRestored(base);
6954
- } catch (cause) {
6955
- setError(explainRestore(cause));
6956
- } finally {
6957
- setRestoring(!1);
6958
- }
7011
+ let snapshot = detail?.current.snapshot ?? null, changes = detail ? diffDocuments(detail.previous?.snapshot ?? null, snapshot) : [], base = event.document_id.replace(/^drafts\./, ""), writeDraft = async (content) => {
7012
+ let { _rev, _createdAt, _updatedAt, ...rest } = content;
7013
+ await client.createOrReplace({
7014
+ ...rest,
7015
+ _id: `drafts.${base}`,
7016
+ _type: event.document_type
7017
+ }), setRestored(base);
7018
+ }, run = async (action) => {
7019
+ setRestoring(!0), setError(null), setConflicts([]);
7020
+ try {
7021
+ await action();
7022
+ } catch (cause) {
7023
+ setError(explainRestore(cause));
7024
+ } finally {
7025
+ setRestoring(!1);
6959
7026
  }
6960
- };
7027
+ }, undo = () => run(async () => {
7028
+ if (!detail) return;
7029
+ let result = undoChange(await client.getDocument(`drafts.${base}`) ?? await client.getDocument(base) ?? null, detail.previous?.snapshot ?? null, snapshot ?? null);
7030
+ await writeDraft(result.document), setConflicts(result.conflicts);
7031
+ }), restore = () => run(async () => {
7032
+ snapshot && await writeDraft(snapshot);
7033
+ });
6961
7034
  return /* @__PURE__ */ jsx(Card, {
6962
7035
  radius: 3,
6963
7036
  shadow: 1,
@@ -7029,28 +7102,41 @@ function DiffPanel(props) {
7029
7102
  tone: "positive",
7030
7103
  children: /* @__PURE__ */ jsxs(Stack, {
7031
7104
  gap: 3,
7032
- children: [/* @__PURE__ */ jsxs(Text, {
7033
- size: 1,
7034
- children: [
7035
- "État restauré ",
7036
- /* @__PURE__ */ jsx("b", { children: "en brouillon" }),
7037
- ". Rien n'est encore en ligne : ouvrez le document, vérifiez, puis publiez."
7038
- ]
7039
- }), /* @__PURE__ */ jsx(IntentLink, {
7040
- intent: "edit",
7041
- params: {
7042
- id: restored,
7043
- type: event.document_type
7044
- },
7045
- style: { textDecoration: "none" },
7046
- children: /* @__PURE__ */ jsx(Button, {
7047
- mode: "ghost",
7048
- fontSize: 1,
7049
- padding: 2,
7050
- text: "Ouvrir le brouillon",
7051
- as: "span"
7105
+ children: [
7106
+ /* @__PURE__ */ jsxs(Text, {
7107
+ size: 1,
7108
+ children: [
7109
+ "Fait ",
7110
+ /* @__PURE__ */ jsx("b", { children: "en brouillon" }),
7111
+ ". Rien n'est encore en ligne : ouvrez le document, vérifiez, puis ",
7112
+ /* @__PURE__ */ jsx("b", { children: "publiez" }),
7113
+ "."
7114
+ ]
7115
+ }),
7116
+ conflicts.length > 0 && /* @__PURE__ */ jsxs(Text, {
7117
+ size: 1,
7118
+ children: [
7119
+ "Non annulé, car modifié depuis : ",
7120
+ conflicts.join(", "),
7121
+ "."
7122
+ ]
7123
+ }),
7124
+ /* @__PURE__ */ jsx(IntentLink, {
7125
+ intent: "edit",
7126
+ params: {
7127
+ id: restored,
7128
+ type: event.document_type
7129
+ },
7130
+ style: { textDecoration: "none" },
7131
+ children: /* @__PURE__ */ jsx(Button, {
7132
+ mode: "ghost",
7133
+ fontSize: 1,
7134
+ padding: 2,
7135
+ text: "Ouvrir le brouillon",
7136
+ as: "span"
7137
+ })
7052
7138
  })
7053
- })]
7139
+ ]
7054
7140
  })
7055
7141
  }),
7056
7142
  !loading && detail && /* @__PURE__ */ jsxs(Fragment, { children: [
@@ -7090,20 +7176,39 @@ function DiffPanel(props) {
7090
7176
  paddingTop: 12
7091
7177
  },
7092
7178
  children: /* @__PURE__ */ jsxs(Stack, {
7093
- gap: 2,
7094
- children: [/* @__PURE__ */ jsx(Button, {
7095
- mode: "ghost",
7096
- tone: "caution",
7097
- fontSize: 1,
7098
- padding: 3,
7099
- icon: RestoreIcon,
7100
- text: restoring ? "Restauration…" : "Restaurer cet état",
7101
- disabled: restoring,
7102
- onClick: restore
7103
- }), /* @__PURE__ */ jsx(Text, {
7104
- size: 0,
7105
- muted: !0,
7106
- children: "Recrée cet état dans le brouillon du document, avec vos droits. La version en ligne n'est pas touchée tant que vous ne publiez pas. Un brouillon en cours serait remplacé."
7179
+ gap: 3,
7180
+ children: [detail.previous && changes.length > 0 && /* @__PURE__ */ jsxs(Stack, {
7181
+ gap: 2,
7182
+ children: [/* @__PURE__ */ jsx(Button, {
7183
+ mode: "default",
7184
+ tone: "primary",
7185
+ fontSize: 1,
7186
+ padding: 3,
7187
+ icon: UndoIcon,
7188
+ text: restoring ? "Annulation…" : "Annuler cette modification",
7189
+ disabled: restoring,
7190
+ onClick: undo
7191
+ }), /* @__PURE__ */ jsx(Text, {
7192
+ size: 0,
7193
+ muted: !0,
7194
+ children: "Remet les valeurs d'avant cette modification, et seulement elles : ce qui a été modifié ensuite est conservé. Le résultat va dans le brouillon : publiez-le pour le mettre en ligne."
7195
+ })]
7196
+ }), /* @__PURE__ */ jsxs(Stack, {
7197
+ gap: 2,
7198
+ children: [/* @__PURE__ */ jsx(Button, {
7199
+ mode: "ghost",
7200
+ tone: "caution",
7201
+ fontSize: 1,
7202
+ padding: 3,
7203
+ icon: RestoreIcon,
7204
+ text: restoring ? "Restauration…" : "Restaurer le document tel qu’après cette modification",
7205
+ disabled: restoring,
7206
+ onClick: restore
7207
+ }), /* @__PURE__ */ jsx(Text, {
7208
+ size: 0,
7209
+ muted: !0,
7210
+ children: "Remet le document ENTIER dans l'état qui a suivi cette modification (les modifications plus récentes sont perdues), dans le brouillon. La version en ligne n'est pas touchée tant que vous ne publiez pas."
7211
+ })]
7107
7212
  })]
7108
7213
  })
7109
7214
  })