@nocode-factory/sanity-kit 2.13.1 → 2.14.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
@@ -200,6 +200,11 @@ interface NcfKitConfig {
200
200
  * (« Scheduled drafts » / Releases, nom d'outil `releases`). `false` : aucun.
201
201
  */
202
202
  moreTools?: string[] | false;
203
+ /**
204
+ * « Publier » ouvre la liste de tous les brouillons du projet, cochés : on publie
205
+ * vingt modifications d'un coup, ou on décoche ce qui n'est pas prêt. Défaut : `true`.
206
+ */
207
+ batchPublish?: boolean;
203
208
  /**
204
209
  * Étiquettes de suivi du board. Remplacent entièrement les valeurs par
205
210
  * défaut quand elles sont fournies.
@@ -255,6 +260,7 @@ interface ResolvedKitConfig {
255
260
  tools: Required<NcfToolsConfig>;
256
261
  /** Outils rangés dans le menu « Plus » de la barre (noms d'outils). */
257
262
  moreTools: string[];
263
+ batchPublish: boolean;
258
264
  boardTags: NcfBoardTag[];
259
265
  internalFields: NcfInternalField[];
260
266
  documentColumns: ResolvedDocumentColumn[];
@@ -1303,7 +1309,7 @@ export declare function ActorName(props: {
1303
1309
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1304
1310
  * le vérifie.
1305
1311
  */
1306
- export declare const KIT_VERSION = "2.13.1";
1312
+ export declare const KIT_VERSION = "2.14.1";
1307
1313
  /**
1308
1314
  * Données de la page proposées comme colonnes.
1309
1315
  *
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { a as defineComponentDefaults, i as defaultsFieldName, n as componentDefaultsMainDocument, o as requiredUnlessDefault, r as componentDefaultsMainDocuments, s as requiredUnlessDefaultFor, t as DEFAULT_COMPONENT_DEFAULTS_TYPE } from "./componentDefaults-BY3hQ6aD.js";
2
- import { ToolLink, defineField, definePlugin, defineType, pathToString, set, unset, useClient, useCurrentUser, useFormValue, useSchema, useUser, useWorkspace } from "sanity";
2
+ import { Preview, ToolLink, defineField, definePlugin, defineType, pathToString, set, unset, useClient, useCurrentUser, useFormValue, useSchema, useSyncState, useUser, useValidationStatus, useWorkspace } from "sanity";
3
3
  import { ClockIcon } from "@sanity/icons/Clock";
4
4
  import { ComponentIcon } from "@sanity/icons/Component";
5
5
  import { DocumentsIcon } from "@sanity/icons/Documents";
6
6
  import { ColorWheelIcon } from "@sanity/icons/ColorWheel";
7
- import { Badge, Box, Button, Card, Container, Flex, Grid, Select, Spinner, Stack, Tab, TabList, TabPanel, Text, TextArea, TextInput } from "@sanity/ui";
7
+ import { Badge, Box, Button, Card, Checkbox, Container, Flex, Grid, Select, Spinner, Stack, Tab, TabList, TabPanel, Text, TextArea, TextInput } from "@sanity/ui";
8
8
  import { createContext, forwardRef, memo, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
9
9
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
10
10
  import { IntentLink, useRouter, useRouterState } from "sanity/router";
@@ -34,6 +34,8 @@ 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 { useToast } from "@sanity/ui/toast";
38
+ import { PublishIcon } from "@sanity/icons/Publish";
37
39
  import { Tooltip } from "@sanity/ui/tooltip";
38
40
  const DEFAULT_PAGE_BUILDER_FIELD = "sections", DEFAULT_SLUG_FIELD = "slug", DEFAULT_TITLE_FIELD = "title", DEFAULT_NOINDEX_FIELDS = ["seo.noindex", "noindex"], DEFAULT_I18N = {
39
41
  field: "language",
@@ -153,6 +155,7 @@ function resolveConfig(input) {
153
155
  ...input.tools
154
156
  },
155
157
  moreTools: input.moreTools === !1 ? [] : input.moreTools ?? DEFAULT_TOOLBAR_MORE,
158
+ batchPublish: input.batchPublish !== !1,
156
159
  boardTags: input.boardTags?.length ? input.boardTags : DEFAULT_BOARD_TAGS,
157
160
  internalFields: input.internalFields?.length ? input.internalFields : DEFAULT_INTERNAL_FIELDS,
158
161
  documentColumns: (input.documentColumns ?? []).map((column) => ({
@@ -1361,7 +1364,7 @@ function explainGrantError(error) {
1361
1364
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1362
1365
  * le vérifie.
1363
1366
  */
1364
- const KIT_VERSION = "2.13.1";
1367
+ const KIT_VERSION = "2.14.1";
1365
1368
  /**
1366
1369
  * Signale ce Studio au service du kit, une fois par montage.
1367
1370
  *
@@ -1688,7 +1691,7 @@ function useKitUpdate() {
1688
1691
  !controller.signal.aborted && body?.version && setLatest(body.version);
1689
1692
  }).catch(() => {}), () => controller.abort();
1690
1693
  }, []);
1691
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.13.1") > 0);
1694
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.14.1") > 0);
1692
1695
  return {
1693
1696
  current: KIT_VERSION,
1694
1697
  latest,
@@ -7416,6 +7419,339 @@ function DesignSystemTool() {
7416
7419
  })
7417
7420
  });
7418
7421
  }
7422
+ /**
7423
+ * Publication groupée : logique pure (testée), sans React ni Studio.
7424
+ *
7425
+ * On modifie vingt documents, on publie tout d'un coup, ou seulement ce qu'on a
7426
+ * coché. La publication passe par l'API Actions de Sanity, en UNE transaction :
7427
+ * tout part ensemble ou rien ne part (un document qui en référence un autre encore
7428
+ * jamais publié peut ainsi partir avec lui).
7429
+ */
7430
+ const DRAFTS_PREFIX = "drafts.", publishedIdOf = (id) => id.startsWith(DRAFTS_PREFIX) ? id.slice(7) : id;
7431
+ /**
7432
+ * Brouillons publiables : types du schéma (documents), hors types internes (kit,
7433
+ * `sanity.*`). Le document ouvert d'abord, puis du plus récent au plus ancien.
7434
+ */
7435
+ function publishableDrafts(rows, publishedIds, options) {
7436
+ let published = new Set(publishedIds), current = options.currentId ? publishedIdOf(options.currentId) : null;
7437
+ return rows.filter((row) => row._id.startsWith(DRAFTS_PREFIX) && !row._id.slice(7).includes(".")).filter((row) => !row._type.startsWith("sanity.") && options.isDocumentType(row._type) && !options.isInternalType?.(row._type)).map((row) => ({
7438
+ ...row,
7439
+ publishedId: publishedIdOf(row._id),
7440
+ published: published.has(publishedIdOf(row._id))
7441
+ })).sort((a, b) => a.publishedId === current ? -1 : b.publishedId === current ? 1 : b._updatedAt.localeCompare(a._updatedAt));
7442
+ }
7443
+ /**
7444
+ * Actions de publication. `ifDraftRevisionId` : on publie exactement la version
7445
+ * affichée ; si quelqu'un l'a modifiée entre-temps, la transaction est refusée
7446
+ * plutôt que de publier un contenu que personne n'a relu.
7447
+ */
7448
+ function publishActions(selected) {
7449
+ return selected.map((draft) => ({
7450
+ actionType: "sanity.action.document.publish",
7451
+ draftId: draft._id,
7452
+ publishedId: draft.publishedId,
7453
+ ifDraftRevisionId: draft._rev
7454
+ }));
7455
+ }
7456
+ /** Libellé du bouton : « Publier 1 document », « Publier 12 documents ». */
7457
+ function publishLabel(count) {
7458
+ return count === 0 ? "Rien à publier" : `Publier ${count} document${count > 1 ? "s" : ""}`;
7459
+ }
7460
+ /** Erreur de l'API rendue lisible. */
7461
+ function explainPublishError(error) {
7462
+ let err = error, description = err?.details?.description ?? err?.details?.items?.[0]?.error?.description ?? err?.message ?? "";
7463
+ return /revision|mismatch|ifDraftRevisionId/i.test(description) ? "Un des documents a été modifié pendant que la fenêtre était ouverte : la liste vient d'être mise à jour, relancez la publication." : /reference/i.test(description) ? `Un document référence un contenu jamais publié qui n'est pas coché : cochez-le aussi, ou retirez la référence. (${description})` : err?.statusCode === 403 || /permission/i.test(description) ? "Vous n'avez pas le droit de publier un de ces documents." : description ? `Publication refusée : ${description}` : "Publication refusée.";
7464
+ }
7465
+ /** « à l'instant », « il y a 5 min », « il y a 3 h », « il y a 2 j ». */
7466
+ function sinceLabel(iso, now = Date.now()) {
7467
+ let minutes = Math.max(0, Math.round((now - Date.parse(iso)) / 6e4));
7468
+ if (minutes < 1) return "à l'instant";
7469
+ if (minutes < 60) return `il y a ${minutes} min`;
7470
+ let hours = Math.round(minutes / 60);
7471
+ return hours < 24 ? `il y a ${hours} h` : `il y a ${Math.round(hours / 24)} j`;
7472
+ }
7473
+ /**
7474
+ * Brouillons du projet, tenus à jour en direct : chaque modification, publication ou
7475
+ * suppression relance la requête (regroupées, une fois par demi-seconde au plus).
7476
+ */
7477
+ function useDrafts(currentId) {
7478
+ let client = useKitClient(), schema = useSchema(), [rows, setRows] = useState(null), [reloadKey, setReloadKey] = useState(0);
7479
+ useEffect(() => {
7480
+ let cancelled = !1, timer, retry, subscription, load = async () => {
7481
+ let drafts = await client.fetch("*[_id in path(\"drafts.**\")]{_id, _rev, _type, _updatedAt}"), published = await client.fetch("*[_id in $ids]._id", { ids: drafts.map((d) => publishedIdOf(d._id)) });
7482
+ cancelled || setRows({
7483
+ drafts,
7484
+ published
7485
+ });
7486
+ };
7487
+ load().catch(() => {
7488
+ cancelled || setRows((prev) => prev ?? {
7489
+ drafts: [],
7490
+ published: []
7491
+ });
7492
+ });
7493
+ let listen = (delay) => {
7494
+ subscription = client.listen("*[_id in path(\"drafts.**\") || _id in path(\"*\")]", {}, {
7495
+ visibility: "query",
7496
+ includeResult: !1,
7497
+ events: ["mutation"]
7498
+ }).subscribe({
7499
+ next: () => {
7500
+ clearTimeout(timer), timer = setTimeout(() => void load().catch(() => {}), 500);
7501
+ },
7502
+ error: () => {
7503
+ cancelled || (retry = setTimeout(() => listen(Math.min(delay * 2, 12e4)), delay));
7504
+ }
7505
+ });
7506
+ };
7507
+ return listen(15e3), () => {
7508
+ cancelled = !0, clearTimeout(timer), clearTimeout(retry), subscription?.unsubscribe();
7509
+ };
7510
+ }, [client, reloadKey]);
7511
+ let reload = useCallback(() => setReloadKey((k) => k + 1), []);
7512
+ return {
7513
+ drafts: useMemo(() => rows ? publishableDrafts(rows.drafts, rows.published, {
7514
+ isDocumentType: (type) => schema.get(type)?.jsonType === "object" && isDocumentSchema(schema.get(type)),
7515
+ isInternalType: isKitType,
7516
+ currentId
7517
+ }) : null, [
7518
+ rows,
7519
+ schema,
7520
+ currentId
7521
+ ]),
7522
+ reload
7523
+ };
7524
+ }
7525
+ function isDocumentSchema(type) {
7526
+ let current = type;
7527
+ for (; current;) {
7528
+ if (current.name === "document") return !0;
7529
+ current = current.type;
7530
+ }
7531
+ return !1;
7532
+ }
7533
+ /**
7534
+ * Remplace le bouton « Publier » du document : il ouvre la liste de TOUS les
7535
+ * brouillons du projet, cochés par défaut. On publie tout d'un coup ou on décoche
7536
+ * ce qui n'est pas prêt. Avec un seul brouillon (celui qu'on édite), le bouton
7537
+ * d'origine est gardé tel quel : pas de fenêtre pour rien.
7538
+ *
7539
+ * En perspective de release ou de variante, l'action d'origine reste aussi : la
7540
+ * publication groupée ne concerne que les brouillons.
7541
+ */
7542
+ function createBatchPublishAction(original) {
7543
+ let BatchPublishAction = (props) => {
7544
+ let base = original(props), { drafts, reload } = useDrafts(props.id), [open, setOpen] = useState(!1);
7545
+ if (!base || props.release || props.version || !drafts) return base;
7546
+ let current = publishedIdOf(props.id);
7547
+ return drafts.filter((d) => d.publishedId !== current).length === 0 ? base : {
7548
+ ...base,
7549
+ label: `Publier… (${drafts.length})`,
7550
+ title: "Choisir les brouillons à publier, ensemble",
7551
+ icon: PublishIcon,
7552
+ disabled: !1,
7553
+ onHandle: () => {
7554
+ reload(), setOpen(!0);
7555
+ },
7556
+ dialog: open ? {
7557
+ type: "dialog",
7558
+ width: "medium",
7559
+ header: "Publier les modifications",
7560
+ onClose: () => setOpen(!1),
7561
+ content: /* @__PURE__ */ jsx(BatchPublishDialog, {
7562
+ drafts,
7563
+ currentId: current,
7564
+ currentType: props.type,
7565
+ onDone: () => setOpen(!1)
7566
+ })
7567
+ } : null
7568
+ };
7569
+ };
7570
+ return BatchPublishAction.action = original.action, BatchPublishAction.displayName = "NcfBatchPublishAction", BatchPublishAction;
7571
+ }
7572
+ function BatchPublishDialog(props) {
7573
+ let { drafts, currentId, currentType, onDone } = props, client = useKitClient(), toast = useToast(), [unchecked, setUnchecked] = useState(() => /* @__PURE__ */ new Set()), [invalid, setInvalid] = useState(() => /* @__PURE__ */ new Set()), [busy, setBusy] = useState(!1), [error, setError] = useState(null), { isSyncing } = useSyncState(currentId, currentType), report = useCallback((id, hasErrors) => {
7574
+ setInvalid((prev) => {
7575
+ if (prev.has(id) === hasErrors) return prev;
7576
+ let next = new Set(prev);
7577
+ return hasErrors ? next.add(id) : next.delete(id), next;
7578
+ });
7579
+ }, []), selectable = drafts.filter((d) => !invalid.has(d._id)), selected = selectable.filter((d) => !unchecked.has(d._id)), allChecked = selected.length === selectable.length && selectable.length > 0, toggle = (id) => setUnchecked((prev) => {
7580
+ let next = new Set(prev);
7581
+ return next.has(id) ? next.delete(id) : next.add(id), next;
7582
+ }), toggleAll = () => setUnchecked(allChecked ? new Set(selectable.map((d) => d._id)) : /* @__PURE__ */ new Set()), publish = async () => {
7583
+ setBusy(!0), setError(null);
7584
+ try {
7585
+ await client.action(publishActions(selected)), toast.push({
7586
+ status: "success",
7587
+ title: selected.length > 1 ? `${selected.length} documents publiés` : "Document publié"
7588
+ }), onDone();
7589
+ } catch (cause) {
7590
+ setError(explainPublishError(cause));
7591
+ } finally {
7592
+ setBusy(!1);
7593
+ }
7594
+ };
7595
+ return /* @__PURE__ */ jsxs(Stack, {
7596
+ gap: 4,
7597
+ padding: 4,
7598
+ children: [
7599
+ /* @__PURE__ */ jsxs(Flex, {
7600
+ align: "center",
7601
+ justify: "space-between",
7602
+ gap: 3,
7603
+ children: [/* @__PURE__ */ jsxs(Text, {
7604
+ size: 1,
7605
+ muted: !0,
7606
+ children: [
7607
+ drafts.length,
7608
+ " document",
7609
+ drafts.length > 1 ? "s" : "",
7610
+ " en brouillon. Décochez ce qui n'est pas prêt."
7611
+ ]
7612
+ }), /* @__PURE__ */ jsx(Button, {
7613
+ mode: "bleed",
7614
+ fontSize: 1,
7615
+ padding: 2,
7616
+ text: allChecked ? "Tout décocher" : "Tout cocher",
7617
+ onClick: toggleAll,
7618
+ disabled: busy
7619
+ })]
7620
+ }),
7621
+ /* @__PURE__ */ jsx(Card, {
7622
+ radius: 2,
7623
+ border: !0,
7624
+ style: {
7625
+ maxHeight: "55vh",
7626
+ overflowY: "auto"
7627
+ },
7628
+ children: /* @__PURE__ */ jsx(Stack, { children: drafts.map((draft, index) => /* @__PURE__ */ jsx(DraftLine, {
7629
+ draft,
7630
+ current: draft.publishedId === currentId,
7631
+ checked: !unchecked.has(draft._id) && !invalid.has(draft._id),
7632
+ invalid: invalid.has(draft._id),
7633
+ onToggle: () => toggle(draft._id),
7634
+ onValidation: report,
7635
+ divider: index > 0,
7636
+ disabled: busy
7637
+ }, draft._id)) })
7638
+ }),
7639
+ error && /* @__PURE__ */ jsx(Card, {
7640
+ padding: 3,
7641
+ radius: 2,
7642
+ tone: "critical",
7643
+ children: /* @__PURE__ */ jsx(Text, {
7644
+ size: 1,
7645
+ children: error
7646
+ })
7647
+ }),
7648
+ /* @__PURE__ */ jsxs(Flex, {
7649
+ justify: "flex-end",
7650
+ align: "center",
7651
+ gap: 2,
7652
+ children: [
7653
+ isSyncing && /* @__PURE__ */ jsxs(Flex, {
7654
+ align: "center",
7655
+ gap: 2,
7656
+ children: [/* @__PURE__ */ jsx(Spinner, { muted: !0 }), /* @__PURE__ */ jsx(Text, {
7657
+ size: 1,
7658
+ muted: !0,
7659
+ children: "Enregistrement en cours…"
7660
+ })]
7661
+ }),
7662
+ /* @__PURE__ */ jsx(Button, {
7663
+ mode: "bleed",
7664
+ text: "Annuler",
7665
+ onClick: onDone,
7666
+ disabled: busy
7667
+ }),
7668
+ /* @__PURE__ */ jsx(Button, {
7669
+ tone: "positive",
7670
+ icon: busy ? Spinner : PublishIcon,
7671
+ text: busy ? "Publication…" : publishLabel(selected.length),
7672
+ disabled: busy || isSyncing || selected.length === 0,
7673
+ onClick: publish
7674
+ })
7675
+ ]
7676
+ })
7677
+ ]
7678
+ });
7679
+ }
7680
+ function DraftLine(props) {
7681
+ let { draft, current, checked, invalid, disabled, divider, onToggle, onValidation } = props, schemaType = useSchema().get(draft._type), { validation, isValidating } = useValidationStatus(draft._id, draft._type, !1), hasErrors = validation.some((marker) => marker.level === "error");
7682
+ return useEffect(() => {
7683
+ isValidating || onValidation(draft._id, hasErrors);
7684
+ }, [
7685
+ draft._id,
7686
+ hasErrors,
7687
+ isValidating,
7688
+ onValidation
7689
+ ]), /* @__PURE__ */ jsx(Card, {
7690
+ as: "label",
7691
+ padding: 2,
7692
+ paddingX: 3,
7693
+ tone: invalid ? "critical" : current ? "primary" : "default",
7694
+ style: {
7695
+ cursor: invalid || disabled ? "default" : "pointer",
7696
+ borderTop: divider ? "1px solid var(--card-border-color)" : void 0
7697
+ },
7698
+ children: /* @__PURE__ */ jsxs(Flex, {
7699
+ align: "center",
7700
+ gap: 3,
7701
+ children: [
7702
+ /* @__PURE__ */ jsx(Checkbox, {
7703
+ checked,
7704
+ disabled: invalid || disabled,
7705
+ onChange: onToggle
7706
+ }),
7707
+ /* @__PURE__ */ jsx(Box, {
7708
+ flex: 1,
7709
+ style: { minWidth: 0 },
7710
+ children: schemaType ? /* @__PURE__ */ jsx(Preview, {
7711
+ schemaType,
7712
+ value: {
7713
+ _id: draft._id,
7714
+ _type: draft._type
7715
+ },
7716
+ layout: "default"
7717
+ }) : /* @__PURE__ */ jsx(Text, {
7718
+ size: 1,
7719
+ children: draft.publishedId
7720
+ })
7721
+ }),
7722
+ /* @__PURE__ */ jsxs(Stack, {
7723
+ gap: 2,
7724
+ style: {
7725
+ flex: "none",
7726
+ textAlign: "right"
7727
+ },
7728
+ children: [/* @__PURE__ */ jsxs(Flex, {
7729
+ gap: 1,
7730
+ justify: "flex-end",
7731
+ children: [current && /* @__PURE__ */ jsx(Badge, {
7732
+ tone: "primary",
7733
+ children: "Ouvert"
7734
+ }), invalid ? /* @__PURE__ */ jsx(Badge, {
7735
+ tone: "critical",
7736
+ children: "Erreurs à corriger"
7737
+ }) : /* @__PURE__ */ jsx(Badge, {
7738
+ tone: draft.published ? "caution" : "positive",
7739
+ children: draft.published ? "Modifié" : "Nouveau"
7740
+ })]
7741
+ }), /* @__PURE__ */ jsxs(Text, {
7742
+ size: 0,
7743
+ muted: !0,
7744
+ children: [
7745
+ schemaType?.title ?? draft._type,
7746
+ " · ",
7747
+ sinceLabel(draft._updatedAt)
7748
+ ]
7749
+ })]
7750
+ })
7751
+ ]
7752
+ })
7753
+ });
7754
+ }
7419
7755
  const store = /* @__PURE__ */ new Map();
7420
7756
  function entryFor(client, type, languageField, language) {
7421
7757
  let { projectId, dataset } = client.config(), key = `${projectId}:${dataset}:${type}:${language ?? ""}`, entry = store.get(key);
@@ -7971,7 +8307,10 @@ const NCF_PAGES_TOOL = "ncf-pages", NCF_COMPONENTS_TOOL = "ncf-components", NCF_
7971
8307
  types: kitSchemaTypes,
7972
8308
  templates: (prev) => prev.filter((template) => !isKitType(template.schemaType))
7973
8309
  },
7974
- document: { newDocumentOptions: (prev) => prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE) },
8310
+ document: {
8311
+ newDocumentOptions: (prev) => prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
8312
+ actions: (prev) => config.batchPublish ? prev.map((action) => action.action === "publish" ? createBatchPublishAction(action) : action) : prev
8313
+ },
7975
8314
  studio: { components: { toolMenu: createPreviewLauncher(config, issues) } },
7976
8315
  form: { components: { input: createOverrideInput(config) } }
7977
8316
  };