@nocode-factory/sanity-kit 2.49.1 → 2.50.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-C1kzYMzQ.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-CaFXmYvm.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-BZk9CkdI.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";
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";
@@ -8,7 +8,8 @@ import { ClockIcon } from "@sanity/icons/Clock";
8
8
  import { ComponentIcon } from "@sanity/icons/Component";
9
9
  import { DocumentsIcon } from "@sanity/icons/Documents";
10
10
  import { ColorWheelIcon } from "@sanity/icons/ColorWheel";
11
- import { Badge, Box, Button, Card, Checkbox, Container, Dialog, Flex, Grid, Select, Spinner, Stack, Tab, TabList, TabPanel, Text, TextArea, TextInput } from "@sanity/ui";
11
+ import { ImagesIcon } from "@sanity/icons/Images";
12
+ import { Badge, Box, Button, Card, Checkbox, Container, Dialog, Flex, Grid, Label, Select, Spinner, Stack, Tab, TabList, TabPanel, Text, TextArea, TextInput } from "@sanity/ui";
12
13
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
13
14
  import { IntentLink, useRouter } from "sanity/router";
14
15
  import { EyeOpenIcon } from "@sanity/icons/EyeOpen";
@@ -39,6 +40,11 @@ import { TrashIcon } from "@sanity/icons/Trash";
39
40
  import { RefreshIcon } from "@sanity/icons/Refresh";
40
41
  import { RestoreIcon } from "@sanity/icons/Restore";
41
42
  import { UndoIcon } from "@sanity/icons/Undo";
43
+ import { FolderIcon } from "@sanity/icons/Folder";
44
+ import { EditIcon } from "@sanity/icons/Edit";
45
+ import { ThLargeIcon } from "@sanity/icons/ThLarge";
46
+ import { ThListIcon } from "@sanity/icons/ThList";
47
+ import { DocumentIcon } from "@sanity/icons/Document";
42
48
  import { Tooltip } from "@sanity/ui/tooltip";
43
49
  import { EyeClosedIcon } from "@sanity/icons/EyeClosed";
44
50
  import { usePresentationNavigate, usePresentationParams } from "sanity/presentation";
@@ -162,7 +168,75 @@ const TRANSLATION_TODO_TYPE = "ncfTranslationTodo", translationTodoId = (documen
162
168
  select: { title: "documentId" },
163
169
  prepare: ({ title }) => ({ title: `To translate: ${title}` })
164
170
  }
165
- }), BOARD_LAYOUT_TYPE = "ncfBoardLayout", BOARD_LAYOUT_ID = "ncfBoardLayout", BOARD_NODE_TYPE = "ncfBoardNode", SECTION_NODE_TYPE = "ncfSectionNode", NODE_FIELD_TYPE = "ncfNodeField", COLUMN_TYPE = "ncfColumn", COLUMN_OPTION_TYPE = "ncfColumnOption", ANNOTATION_TYPE = "ncfAnnotation", NCF_HIDDEN_TYPES = [BOARD_LAYOUT_TYPE, TRANSLATION_TODO_TYPE], boardNodeType = defineType({
171
+ }), ASSET_META_TYPE = "ncfAssetMeta", ASSET_META_ID = "ncfAssetMeta", ASSET_FOLDER_TYPE = "ncfAssetFolder", ASSET_ASSIGNMENT_TYPE = "ncfAssetAssignment", assetFolderType = defineType({
172
+ name: ASSET_FOLDER_TYPE,
173
+ title: "Asset folder",
174
+ type: "object",
175
+ fields: [
176
+ defineField({
177
+ name: "id",
178
+ title: "Id",
179
+ type: "string"
180
+ }),
181
+ defineField({
182
+ name: "name",
183
+ title: "Name",
184
+ type: "string"
185
+ }),
186
+ defineField({
187
+ name: "parent",
188
+ title: "Parent",
189
+ type: "string"
190
+ })
191
+ ],
192
+ preview: { select: {
193
+ title: "name",
194
+ subtitle: "id"
195
+ } }
196
+ }), assetAssignmentType = defineType({
197
+ name: ASSET_ASSIGNMENT_TYPE,
198
+ title: "Asset folder assignment",
199
+ type: "object",
200
+ fields: [defineField({
201
+ name: "folder",
202
+ title: "Folder",
203
+ type: "string"
204
+ })],
205
+ preview: { select: { title: "folder" } }
206
+ }), assetMetaSchemaTypes = [
207
+ defineType({
208
+ name: ASSET_META_TYPE,
209
+ title: "Asset organization (NCF)",
210
+ type: "document",
211
+ fields: [
212
+ defineField({
213
+ name: "folders",
214
+ title: "Folders",
215
+ type: "array",
216
+ of: [{ type: ASSET_FOLDER_TYPE }]
217
+ }),
218
+ defineField({
219
+ name: "assignments",
220
+ title: "Folder assignments",
221
+ type: "array",
222
+ of: [{ type: ASSET_ASSIGNMENT_TYPE }]
223
+ }),
224
+ defineField({
225
+ name: "updatedBy",
226
+ title: "Modified by",
227
+ type: "string",
228
+ readOnly: !0
229
+ })
230
+ ],
231
+ preview: { prepare: () => ({ title: "Asset organization (NCF)" }) }
232
+ }),
233
+ assetFolderType,
234
+ assetAssignmentType
235
+ ], BOARD_LAYOUT_TYPE = "ncfBoardLayout", BOARD_LAYOUT_ID = "ncfBoardLayout", BOARD_NODE_TYPE = "ncfBoardNode", SECTION_NODE_TYPE = "ncfSectionNode", NODE_FIELD_TYPE = "ncfNodeField", COLUMN_TYPE = "ncfColumn", COLUMN_OPTION_TYPE = "ncfColumnOption", ANNOTATION_TYPE = "ncfAnnotation", NCF_HIDDEN_TYPES = [
236
+ BOARD_LAYOUT_TYPE,
237
+ TRANSLATION_TODO_TYPE,
238
+ ASSET_META_TYPE
239
+ ], boardNodeType = defineType({
166
240
  name: BOARD_NODE_TYPE,
167
241
  title: "Page position",
168
242
  type: "object",
@@ -442,7 +516,8 @@ const TRANSLATION_TODO_TYPE = "ncfTranslationTodo", translationTodoId = (documen
442
516
  nodeFieldType,
443
517
  columnType,
444
518
  columnOptionType,
445
- annotationType
519
+ annotationType,
520
+ ...assetMetaSchemaTypes
446
521
  ], isKitType = (typeName) => NCF_HIDDEN_TYPES.includes(typeName), IGNORED_PREFIXES = [
447
522
  "//",
448
523
  "http://",
@@ -1266,7 +1341,7 @@ function explainGrantError(error) {
1266
1341
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1267
1342
  * le vérifie.
1268
1343
  */
1269
- const KIT_VERSION = "2.49.1";
1344
+ const KIT_VERSION = "2.50.0";
1270
1345
  /**
1271
1346
  * Signale ce Studio au service du kit, une fois par montage.
1272
1347
  *
@@ -1764,7 +1839,7 @@ function useKitUpdate() {
1764
1839
  !controller.signal.aborted && body?.version && setLatest(body.version);
1765
1840
  }).catch(() => {}), () => controller.abort();
1766
1841
  }, []);
1767
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.49.1") > 0);
1842
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.50.0") > 0);
1768
1843
  return {
1769
1844
  current: KIT_VERSION,
1770
1845
  latest,
@@ -4995,7 +5070,7 @@ function ColumnVisibility(props) {
4995
5070
  })
4996
5071
  });
4997
5072
  }
4998
- function Row(props) {
5073
+ function Row$1(props) {
4999
5074
  return /* @__PURE__ */ jsxs(Flex, {
5000
5075
  align: "center",
5001
5076
  gap: 2,
@@ -5040,7 +5115,7 @@ function DataColumnList(props) {
5040
5115
  }, [dataColumns, filter]);
5041
5116
  return /* @__PURE__ */ jsxs(Stack, {
5042
5117
  gap: 0,
5043
- children: [HIDEABLE.map((column) => /* @__PURE__ */ jsx(Row, {
5118
+ children: [HIDEABLE.map((column) => /* @__PURE__ */ jsx(Row$1, {
5044
5119
  label: column.label,
5045
5120
  checked: !hidden.has(column.key),
5046
5121
  onClick: () => onToggle(column.key)
@@ -5077,7 +5152,7 @@ function DataColumnList(props) {
5077
5152
  }
5078
5153
  })
5079
5154
  }),
5080
- matches.map((column) => /* @__PURE__ */ jsx(Row, {
5155
+ matches.map((column) => /* @__PURE__ */ jsx(Row$1, {
5081
5156
  label: column.label,
5082
5157
  checked: shownData.has(column.key),
5083
5158
  onClick: () => onToggleData(column.key)
@@ -8344,177 +8419,1451 @@ function DesignSystemTool() {
8344
8419
  })
8345
8420
  });
8346
8421
  }
8347
- const store$1 = /* @__PURE__ */ new Map();
8348
- function entryFor$1(client, type, languageField, language) {
8349
- let { projectId, dataset } = client.config(), key = `${projectId}:${dataset}:${type}:${language ?? ""}`, entry = store$1.get(key);
8350
- entry || (entry = {
8351
- value: null,
8352
- listeners: /* @__PURE__ */ new Set(),
8353
- stop: null
8354
- }, store$1.set(key, entry));
8355
- let e = entry;
8356
- if (!e.stop) {
8357
- let filter = `_type == $type && ($language == null || !defined(${languageField}) || ${languageField} == $language)`, params = {
8358
- type,
8359
- language
8360
- }, drafts = client.withConfig({ perspective: "drafts" }), load = () => drafts.fetch(`*[${filter}][0]`, params).then((value) => {
8361
- e.value = value, e.listeners.forEach((l) => l());
8362
- }).catch(() => {});
8363
- load();
8364
- let sub = client.listen(`*[${filter}]`, params, {
8365
- visibility: "query",
8366
- includeResult: !1
8367
- }).subscribe({ next: () => void load() });
8368
- e.stop = () => sub.unsubscribe();
8369
- }
8370
- return [key, e];
8371
- }
8372
- function useComponentDefaults(client, type, languageField, language) {
8373
- let [, entry] = entryFor$1(client, type, languageField, language), value = useSyncExternalStore((listener) => (entry.listeners.add(listener), () => {
8374
- entry.listeners.delete(listener);
8375
- }), () => entry.value);
8376
- return useEffect(() => () => {
8377
- entry.listeners.size === 0 && entry.stop && (entry.stop(), entry.stop = null);
8378
- }, [entry]), value;
8379
- }
8380
- const LINK_TARGET_FIELDS = [
8381
- "page",
8382
- "fixedPath",
8383
- "href",
8384
- "email",
8385
- "phone",
8386
- "file"
8387
- ], LINK_TYPES = /* @__PURE__ */ new Set(["link", "cardLink"]);
8388
- function isEmptyValue(value) {
8389
- return value == null || value === "" || Array.isArray(value) && value.length === 0;
8390
- }
8391
- const isKeyed = (s) => typeof s == "object" && !!s && !Array.isArray(s) && typeof s._key == "string";
8392
- /** Index du premier élément de liste du chemin (l'instance de composant dans le page builder), ou -1. */
8393
- function firstKeyedIndex(path) {
8394
- return path.findIndex(isKeyed);
8422
+ const ASSET_TYPES = ["sanity.imageAsset", "sanity.fileAsset"];
8423
+ /**
8424
+ * Tous les assets du dataset (images et fichiers), en direct. `uses` compte les
8425
+ * documents qui référencent l'asset (utilisé / inutilisé) : il suit les
8426
+ * mutations d'assets ; un changement de contenu qui (dé)référence un asset est
8427
+ * pris au prochain rafraîchissement.
8428
+ */
8429
+ function useAssets() {
8430
+ return useQueryData("*[_type in $types]{\n _id, _type, _createdAt, _updatedAt, originalFilename, extension, mimeType, size, url,\n title, altText, description,\n \"dimensions\": metadata.dimensions, \"lqip\": metadata.lqip,\n \"uses\": count(*[references(^._id)])\n } | order(_createdAt desc)", { types: ASSET_TYPES }, { listenTypes: ASSET_TYPES });
8395
8431
  }
8432
+ const newId = () => `f${Math.random().toString(36).slice(2, 10)}`;
8396
8433
  /**
8397
- * Chemin du champ à l'intérieur de l'instance, listes comprises : un élément de
8398
- * liste est repéré par son rang (`['items', 0, 'title']`), comparé à l'élément de
8399
- * même rang de la valeur par défaut. `inList` : le champ est dans un élément de
8400
- * liste (une liste remplie remplace celle du défaut en entier : réinitialiser
8401
- * RECOPIE la valeur par défaut au lieu de vider le champ). `null` : pas un
8402
- * composant de l'espace de noms.
8434
+ * Lit et écrit l'organisation des assets (dossiers + affectations) dans le
8435
+ * singleton du kit `ncfAssetMeta`. Même principe que la disposition du board :
8436
+ * document unique réécrit en entier, écriture directe (pas de brouillon),
8437
+ * débouncée. À appeler UNE fois (outil Assets) : deux instances s'écraseraient.
8403
8438
  */
8404
- function resolveFieldPath(path, index, instance, namespace) {
8405
- let type = instance?._type;
8406
- if (index < 0 || typeof type != "string" || !type.startsWith(namespace)) return null;
8407
- let rest = path.slice(index + 1);
8408
- if (rest.length === 0) return null;
8409
- let out = [], inList = !1, node = instance;
8410
- for (let seg of rest) if (typeof seg == "string") out.push(seg), node = node && typeof node == "object" ? node[seg] : void 0;
8411
- else if (isKeyed(seg) || typeof seg == "number") {
8412
- if (!Array.isArray(node)) return null;
8413
- let i = typeof seg == "number" ? seg : node.findIndex((item) => item?._key === seg._key);
8414
- if (i < 0 || node[i]?._type === "block") return null;
8415
- out.push(i), inList = !0, node = node[i];
8416
- } else return null;
8439
+ function useAssetMeta() {
8440
+ let client = useKitClient(), user = useCurrentUser(), [folders, setFolders] = useState([]), [assignments, setAssignments] = useState([]), [loading, setLoading] = useState(!0), [saveError, setSaveError] = useState(null);
8441
+ useEffect(() => {
8442
+ let cancelled = !1;
8443
+ return client.fetch("*[_id == $id][0]{folders, assignments}", { id: ASSET_META_ID }).then((doc) => {
8444
+ cancelled || (setFolders((doc?.folders ?? []).filter((f) => !!(f.id && f.name)).map((f) => ({
8445
+ id: f.id,
8446
+ name: f.name,
8447
+ ...f.parent ? { parent: f.parent } : {}
8448
+ }))), setAssignments((doc?.assignments ?? []).filter((a) => !!(a._key && a.folder)).map((a) => ({
8449
+ assetId: a._key,
8450
+ folder: a.folder
8451
+ }))));
8452
+ }).catch(() => {
8453
+ cancelled || (setFolders([]), setAssignments([]));
8454
+ }).finally(() => {
8455
+ cancelled || setLoading(!1);
8456
+ }), () => {
8457
+ cancelled = !0;
8458
+ };
8459
+ }, [client]);
8460
+ let timer = useRef(void 0);
8461
+ useEffect(() => () => {
8462
+ timer.current && clearTimeout(timer.current);
8463
+ }, []);
8464
+ let foldersRef = useRef([]), assignmentsRef = useRef([]);
8465
+ foldersRef.current = folders, assignmentsRef.current = assignments;
8466
+ let write = useCallback((next) => {
8467
+ let nextFolders = next?.folders ?? foldersRef.current, nextAssignments = next?.assignments ?? assignmentsRef.current;
8468
+ timer.current && clearTimeout(timer.current), timer.current = setTimeout(() => {
8469
+ client.createOrReplace({
8470
+ _id: ASSET_META_ID,
8471
+ _type: ASSET_META_TYPE,
8472
+ folders: nextFolders.map((folder) => ({
8473
+ _key: folder.id,
8474
+ _type: ASSET_FOLDER_TYPE,
8475
+ id: folder.id,
8476
+ name: folder.name,
8477
+ ...folder.parent ? { parent: folder.parent } : {}
8478
+ })),
8479
+ assignments: nextAssignments.filter((assignment) => assignment.folder).map((assignment) => ({
8480
+ _key: assignment.assetId,
8481
+ _type: ASSET_ASSIGNMENT_TYPE,
8482
+ folder: assignment.folder
8483
+ })),
8484
+ updatedBy: user?.id ?? null
8485
+ }).then(() => setSaveError(null)).catch((cause) => setSaveError(cause instanceof Error ? cause : Error(String(cause))));
8486
+ }, 800);
8487
+ }, [client, user?.id]), createFolder = useCallback((name) => {
8488
+ let id = newId(), next = [...foldersRef.current, {
8489
+ id,
8490
+ name: name.trim() || "Dossier"
8491
+ }];
8492
+ return setFolders(next), write({ folders: next }), id;
8493
+ }, [write]), renameFolder = useCallback((id, name) => {
8494
+ let next = foldersRef.current.map((folder) => folder.id === id ? {
8495
+ ...folder,
8496
+ name: name.trim() || folder.name
8497
+ } : folder);
8498
+ setFolders(next), write({ folders: next });
8499
+ }, [write]), deleteFolder = useCallback((id) => {
8500
+ let nextFolders = foldersRef.current.filter((folder) => folder.id !== id), nextAssignments = assignmentsRef.current.filter((assignment) => assignment.folder !== id);
8501
+ setFolders(nextFolders), setAssignments(nextAssignments), write({
8502
+ folders: nextFolders,
8503
+ assignments: nextAssignments
8504
+ });
8505
+ }, [write]), moveAssets = useCallback((assetIds, folder) => {
8506
+ let ids = new Set(assetIds), kept = assignmentsRef.current.filter((assignment) => !ids.has(assignment.assetId)), added = folder ? assetIds.map((assetId) => ({
8507
+ assetId,
8508
+ folder
8509
+ })) : [], next = [...kept, ...added];
8510
+ setAssignments(next), write({ assignments: next });
8511
+ }, [write]);
8417
8512
  return {
8418
- path: out,
8419
- inList
8513
+ folders,
8514
+ assignments,
8515
+ loading,
8516
+ saveError,
8517
+ createFolder,
8518
+ renameFolder,
8519
+ deleteFolder,
8520
+ moveAsset: useCallback((assetId, folder) => moveAssets([assetId], folder), [moveAssets]),
8521
+ moveAssets
8420
8522
  };
8421
8523
  }
8422
- /** Valeur par défaut d'un champ de composant. */
8423
- function defaultValueAt(defaults, blockShortName, relPath) {
8424
- let node = defaults?.[blockShortName];
8425
- for (let key of relPath) {
8426
- if (!node || typeof node != "object") return;
8427
- node = node[key];
8428
- }
8429
- return node;
8524
+ const isImageAsset = (asset) => asset._type === "sanity.imageAsset";
8525
+ /** Nom affiché : titre saisi, sinon nom de fichier, sinon id. */
8526
+ function assetName(asset) {
8527
+ return asset.title?.trim() || asset.originalFilename || asset._id;
8528
+ }
8529
+ /** Taille lisible (o / Ko / Mo / Go). */
8530
+ function formatBytes(size) {
8531
+ if (!size || size <= 0) return "—";
8532
+ let units = [
8533
+ "o",
8534
+ "Ko",
8535
+ "Mo",
8536
+ "Go",
8537
+ "To"
8538
+ ], value = size, unit = 0;
8539
+ for (; value >= 1024 && unit < units.length - 1;) value /= 1024, unit += 1;
8540
+ return `${unit === 0 ? value : value < 10 ? Math.round(value * 10) / 10 : Math.round(value)} ${units[unit]}`;
8541
+ }
8542
+ /**
8543
+ * URL de vignette depuis l'URL CDN de l'asset (paramètres de transformation
8544
+ * Sanity). Renvoie `undefined` pour un non-image (pas de rendu).
8545
+ */
8546
+ function thumbnailUrl(asset, opts = {}) {
8547
+ if (!asset.url || !isImageAsset(asset)) return;
8548
+ let params = new URLSearchParams();
8549
+ return opts.w && params.set("w", String(opts.w)), opts.h && params.set("h", String(opts.h)), params.set("fit", "crop"), params.set("auto", "format"), `${asset.url}?${params.toString()}`;
8550
+ }
8551
+ function matchesSearch(asset, query) {
8552
+ return [
8553
+ asset.title,
8554
+ asset.originalFilename,
8555
+ asset.altText,
8556
+ asset.description,
8557
+ asset.extension
8558
+ ].filter(Boolean).join(" ").toLowerCase().includes(query);
8559
+ }
8560
+ /** Filtre par recherche, type (image/fichier) et usage. */
8561
+ function filterAssets(assets, filter = {}) {
8562
+ let query = filter.search?.trim().toLowerCase() ?? "", type = filter.type ?? "all", usage = filter.usage ?? "all";
8563
+ return assets.filter((asset) => !(query && !matchesSearch(asset, query) || type === "image" && !isImageAsset(asset) || type === "file" && isImageAsset(asset) || usage === "used" && !(asset.uses && asset.uses > 0) || usage === "unused" && asset.uses && asset.uses > 0));
8564
+ }
8565
+ /** Tri stable par date / nom / taille / type. */
8566
+ function sortAssets(assets, key, direction = "desc") {
8567
+ let factor = direction === "asc" ? 1 : -1, compare = (a, b) => {
8568
+ switch (key) {
8569
+ case "name": return assetName(a).localeCompare(assetName(b), "fr", { numeric: !0 });
8570
+ case "size": return (a.size ?? 0) - (b.size ?? 0);
8571
+ case "type": return (a.extension ?? a._type).localeCompare(b.extension ?? b._type);
8572
+ default: return a._createdAt < b._createdAt ? -1 : +(a._createdAt > b._createdAt);
8573
+ }
8574
+ };
8575
+ return [...assets].sort((a, b) => factor * compare(a, b));
8430
8576
  }
8431
- const hasLinkTarget = (link) => {
8432
- let l = link ?? {};
8433
- return LINK_TARGET_FIELDS.some((k) => k === "file" ? !!l.file?.asset : !isEmptyValue(l[k]));
8434
- };
8435
- /**
8436
- * Le champ est-il un override ? Valeur propre à l'instance DIFFÉRENTE de la
8437
- * valeur par défaut du composant (y compris quand le composant n'a pas de valeur
8438
- * par défaut pour ce champ). Un champ vide hérite : jamais d'override. Une case
8439
- * décochée vaut une case non renseignée. Le type d'un lien ne compte que si le
8440
- * lien a sa propre cible (il est prérempli par le Studio).
8441
- */
8442
- function isOverride(local, inherited, field, parent) {
8443
- if (isEmptyValue(local) || local === !1 && isEmptyValue(inherited)) return !1;
8444
- let parentType = parent?._type;
8445
- return field === "type" && typeof parentType == "string" && LINK_TYPES.has(parentType) && !hasLinkTarget(parent) ? !1 : !sameValue(local, inherited);
8577
+ /** Map assetId -> id de dossier, à partir des affectations stockées. */
8578
+ function assignmentMap(assignments) {
8579
+ let map = /* @__PURE__ */ new Map();
8580
+ for (let { assetId, folder } of assignments) folder && map.set(assetId, folder);
8581
+ return map;
8446
8582
  }
8447
- /** Égalité de valeurs (champ identique au défaut : override « figé »). */
8448
- function sameValue(a, b) {
8449
- if (a === b) return !0;
8450
- let clean = (v) => Array.isArray(v) ? v.map(clean) : v && typeof v == "object" ? Object.fromEntries(Object.entries(v).filter(([k]) => !k.startsWith("_") || k === "_ref").sort(([x], [y]) => x.localeCompare(y)).map(([k, x]) => [k, clean(x)])) : v;
8451
- return JSON.stringify(clean(a)) === JSON.stringify(clean(b));
8583
+ /** Assets du dossier sélectionné (`null` = tous, `''` = sans dossier). */
8584
+ function assetsInFolder(assets, folders, selection) {
8585
+ return selection === null ? [...assets] : selection === "" ? assets.filter((asset) => !folders.has(asset._id)) : assets.filter((asset) => folders.get(asset._id) === selection);
8452
8586
  }
8453
- /** Valeur par défaut lisible, pour la bulle de la pastille. */
8454
- function describeValue(value) {
8455
- if (isEmptyValue(value)) return "empty (design system value)";
8456
- if (typeof value == "string") return value.length > 60 ? `"${value.slice(0, 57)}…"` : `"${value}"`;
8457
- if (typeof value == "boolean") return value ? "Yes" : "No";
8458
- if (typeof value == "number") return String(value);
8459
- if (Array.isArray(value)) return `${value.length} item${value.length > 1 ? "s" : ""}`;
8460
- if (value && typeof value == "object") {
8461
- let v = value;
8462
- if (typeof v.token == "string") return `color ${v.token}`;
8463
- if (typeof v.customHex == "string") return `color ${v.customHex}`;
8464
- if (typeof v.label == "string") return `"${v.label}"`;
8465
- if (v.asset) return "an image";
8466
- if (typeof v._ref == "string") return "a document";
8587
+ /** Nombre d'assets par dossier (+ `''` pour les non classés). */
8588
+ function countByFolder(assets, folders) {
8589
+ let counts = /* @__PURE__ */ new Map();
8590
+ for (let asset of assets) {
8591
+ let folder = folders.get(asset._id) ?? "";
8592
+ counts.set(folder, (counts.get(folder) ?? 0) + 1);
8467
8593
  }
8468
- return "a value";
8469
- }
8470
- /**
8471
- * Ce que fait « Réinitialiser » : remettre le champ en HÉRITAGE (le vider en
8472
- * base). Il suit alors la valeur par défaut du composant, aujourd'hui comme
8473
- * après ses changements (une copie serait figée). Le champ affiche la valeur
8474
- * héritée (grisée). Sans valeur par défaut, rien à hériter : le champ resterait
8475
- * vide, la pastille renvoie donc au réglage du composant.
8476
- */
8477
- function resetAction(inherited) {
8478
- return isEmptyValue(inherited) ? { kind: "noDefault" } : { kind: "inherit" };
8479
- }
8480
- /** Texte grisé d'un champ texte vide qui hérite de la valeur par défaut. */
8481
- function inheritedPlaceholder(value) {
8482
- return typeof value == "string" && value.trim() ? value : typeof value == "number" ? String(value) : null;
8483
- }
8484
- /** Libellé court de la valeur par défaut, pour la pastille au survol. */
8485
- function shortValue(value, max = 32) {
8486
- let d = describeValue(value);
8487
- return d.length > max ? `${d.slice(0, max - 1)}…` : d;
8594
+ return counts;
8488
8595
  }
8489
- /**
8490
- * Un champ hérité doit-il afficher la valeur par défaut **pré-sélectionnée**
8491
- * dans son contrôle ?
8492
- *
8493
- * Oui pour un choix (liste d'options : style, taille, position, niveau de
8494
- * titre…) et pour une case à cocher : l'éditeur voit ce qui s'appliquera, au
8495
- * lieu d'un contrôle vide doublé d'une mention. La valeur n'est pas écrite —
8496
- * le champ reste vide, donc hérité ; choisir autre chose l'emporte et fait
8497
- * apparaître la pastille de réinitialisation.
8498
- *
8499
- * Non pour le texte libre (déjà traité par un placeholder grisé) ni pour les
8500
- * objets, listes et images (pas de « valeur sélectionnée » à montrer).
8501
- */
8502
- function preselectsDefault(schemaType, inherited) {
8503
- if (isEmptyValue(inherited)) return !1;
8504
- let jt = schemaType?.jsonType;
8505
- return jt === "boolean" || (jt === "string" || jt === "number") && (schemaType?.options?.list?.length ?? 0) > 0;
8596
+ function Row(props) {
8597
+ return /* @__PURE__ */ jsxs(Flex, {
8598
+ align: "center",
8599
+ gap: 1,
8600
+ children: [/* @__PURE__ */ jsx(Button, {
8601
+ mode: props.active ? "default" : "bleed",
8602
+ tone: props.active ? "primary" : "default",
8603
+ onClick: props.onClick,
8604
+ justify: "flex-start",
8605
+ style: {
8606
+ flex: 1,
8607
+ minWidth: 0
8608
+ },
8609
+ padding: 2,
8610
+ fontSize: 1,
8611
+ children: /* @__PURE__ */ jsxs(Flex, {
8612
+ align: "center",
8613
+ gap: 2,
8614
+ style: { width: "100%" },
8615
+ children: [
8616
+ props.icon ? /* @__PURE__ */ jsx(Text, {
8617
+ size: 1,
8618
+ children: props.icon
8619
+ }) : null,
8620
+ /* @__PURE__ */ jsx(Text, {
8621
+ size: 1,
8622
+ textOverflow: "ellipsis",
8623
+ style: {
8624
+ flex: 1,
8625
+ textAlign: "left"
8626
+ },
8627
+ children: props.label
8628
+ }),
8629
+ typeof props.count == "number" ? /* @__PURE__ */ jsx(Text, {
8630
+ size: 0,
8631
+ muted: !0,
8632
+ style: {
8633
+ ...TABULAR,
8634
+ flex: "none"
8635
+ },
8636
+ children: props.count
8637
+ }) : null
8638
+ ]
8639
+ })
8640
+ }), props.actions ? /* @__PURE__ */ jsx(Box, {
8641
+ style: { flex: "none" },
8642
+ children: props.actions
8643
+ }) : null]
8644
+ });
8506
8645
  }
8507
- /**
8508
- * Pastille bleue sur tout champ d'une instance de composant dont la valeur
8509
- * DIFFÈRE de la valeur par défaut du composant (valeur par défaut vide comprise),
8510
- * éléments de liste compris (comparés à l'élément de même rang). Au survol, elle
8511
- * affiche la valeur par défaut ; au clic, le champ revient en HÉRITAGE et suit la
8512
- * valeur par défaut, même quand elle change (sans valeur par défaut, elle ouvre
8513
- * le réglage du composant). Un champ vide affiche la valeur héritée. Les champs
8514
- * « simples » la portent (texte, nombre, choix, case, liste, image, référence,
8515
- * couleur...) ; un objet composé (lien) la porte sur ses sous-champs.
8516
- */
8517
- function createOverrideInput(config) {
8646
+ function FolderSidebar(props) {
8647
+ let { folders, counts, total, selection, onSelect, onCreate, onRename, onDelete } = props, [creating, setCreating] = useState(!1), [renaming, setRenaming] = useState(null), [deleting, setDeleting] = useState(null), [name, setName] = useState(""), openCreate = () => {
8648
+ setName(""), setCreating(!0);
8649
+ }, openRename = (folder) => {
8650
+ setName(folder.name), setRenaming(folder);
8651
+ };
8652
+ return /* @__PURE__ */ jsxs(Stack, {
8653
+ gap: 2,
8654
+ children: [
8655
+ /* @__PURE__ */ jsxs(Flex, {
8656
+ align: "center",
8657
+ justify: "space-between",
8658
+ children: [/* @__PURE__ */ jsx(Text, {
8659
+ size: 1,
8660
+ weight: "semibold",
8661
+ muted: !0,
8662
+ children: "Dossiers"
8663
+ }), /* @__PURE__ */ jsx(Button, {
8664
+ icon: AddIcon,
8665
+ mode: "bleed",
8666
+ fontSize: 1,
8667
+ padding: 2,
8668
+ title: "Nouveau dossier",
8669
+ "aria-label": "Nouveau dossier",
8670
+ onClick: openCreate
8671
+ })]
8672
+ }),
8673
+ /* @__PURE__ */ jsxs(Stack, {
8674
+ gap: 1,
8675
+ children: [
8676
+ /* @__PURE__ */ jsx(Row, {
8677
+ label: "Tous les médias",
8678
+ count: total,
8679
+ active: selection === null,
8680
+ onClick: () => onSelect(null)
8681
+ }),
8682
+ /* @__PURE__ */ jsx(Row, {
8683
+ label: "Non classés",
8684
+ count: counts.get("") ?? 0,
8685
+ active: selection === "",
8686
+ onClick: () => onSelect("")
8687
+ }),
8688
+ folders.map((folder) => /* @__PURE__ */ jsx(Row, {
8689
+ label: folder.name,
8690
+ count: counts.get(folder.id) ?? 0,
8691
+ active: selection === folder.id,
8692
+ onClick: () => onSelect(folder.id),
8693
+ icon: /* @__PURE__ */ jsx(FolderIcon, {}),
8694
+ actions: /* @__PURE__ */ jsxs(Flex, {
8695
+ gap: 1,
8696
+ children: [/* @__PURE__ */ jsx(Button, {
8697
+ icon: EditIcon,
8698
+ mode: "bleed",
8699
+ fontSize: 0,
8700
+ padding: 2,
8701
+ title: "Renommer",
8702
+ "aria-label": "Renommer",
8703
+ onClick: () => openRename(folder)
8704
+ }), /* @__PURE__ */ jsx(Button, {
8705
+ icon: TrashIcon,
8706
+ mode: "bleed",
8707
+ tone: "critical",
8708
+ fontSize: 0,
8709
+ padding: 2,
8710
+ title: "Supprimer",
8711
+ "aria-label": "Supprimer",
8712
+ onClick: () => setDeleting(folder)
8713
+ })]
8714
+ })
8715
+ }, folder.id))
8716
+ ]
8717
+ }),
8718
+ creating || renaming ? /* @__PURE__ */ jsx(Dialog, {
8719
+ id: "asset-folder-dialog",
8720
+ header: renaming ? "Renommer le dossier" : "Nouveau dossier",
8721
+ onClose: () => {
8722
+ setCreating(!1), setRenaming(null);
8723
+ },
8724
+ width: 0,
8725
+ footer: /* @__PURE__ */ jsxs(Flex, {
8726
+ justify: "flex-end",
8727
+ gap: 2,
8728
+ padding: 2,
8729
+ children: [/* @__PURE__ */ jsx(Button, {
8730
+ text: "Annuler",
8731
+ mode: "bleed",
8732
+ onClick: () => {
8733
+ setCreating(!1), setRenaming(null);
8734
+ }
8735
+ }), /* @__PURE__ */ jsx(Button, {
8736
+ text: renaming ? "Renommer" : "Créer",
8737
+ tone: "primary",
8738
+ disabled: !name.trim(),
8739
+ onClick: () => {
8740
+ renaming ? onRename(renaming.id, name) : onCreate(name), setCreating(!1), setRenaming(null);
8741
+ }
8742
+ })]
8743
+ }),
8744
+ children: /* @__PURE__ */ jsx(Box, {
8745
+ padding: 4,
8746
+ children: /* @__PURE__ */ jsx(TextInput, {
8747
+ value: name,
8748
+ autoFocus: !0,
8749
+ placeholder: "Nom du dossier",
8750
+ onChange: (event) => setName(event.currentTarget.value),
8751
+ onKeyDown: (event) => {
8752
+ event.key === "Enter" && name.trim() && (renaming ? onRename(renaming.id, name) : onCreate(name), setCreating(!1), setRenaming(null));
8753
+ }
8754
+ })
8755
+ })
8756
+ }) : null,
8757
+ deleting ? /* @__PURE__ */ jsx(Dialog, {
8758
+ id: "asset-folder-delete",
8759
+ header: "Supprimer le dossier",
8760
+ onClose: () => setDeleting(null),
8761
+ width: 0,
8762
+ footer: /* @__PURE__ */ jsxs(Flex, {
8763
+ justify: "flex-end",
8764
+ gap: 2,
8765
+ padding: 2,
8766
+ children: [/* @__PURE__ */ jsx(Button, {
8767
+ text: "Annuler",
8768
+ mode: "bleed",
8769
+ onClick: () => setDeleting(null)
8770
+ }), /* @__PURE__ */ jsx(Button, {
8771
+ text: "Supprimer",
8772
+ tone: "critical",
8773
+ onClick: () => {
8774
+ onDelete(deleting.id), setDeleting(null);
8775
+ }
8776
+ })]
8777
+ }),
8778
+ children: /* @__PURE__ */ jsx(Box, {
8779
+ padding: 4,
8780
+ children: /* @__PURE__ */ jsxs(Text, {
8781
+ size: 1,
8782
+ children: [
8783
+ "Supprimer « ",
8784
+ deleting.name,
8785
+ " » ? Les médias qu'il contient ne sont pas supprimés : ils redeviennent « Non classés »."
8786
+ ]
8787
+ })
8788
+ })
8789
+ }) : null
8790
+ ]
8791
+ });
8792
+ }
8793
+ function AssetsToolbar(props) {
8794
+ return /* @__PURE__ */ jsxs(Flex, {
8795
+ gap: 2,
8796
+ align: "center",
8797
+ wrap: "wrap",
8798
+ children: [
8799
+ /* @__PURE__ */ jsx(Box, {
8800
+ flex: 1,
8801
+ style: { minWidth: 180 },
8802
+ children: /* @__PURE__ */ jsx(TextInput, {
8803
+ value: props.search,
8804
+ onChange: (event) => props.onSearch(event.currentTarget.value),
8805
+ placeholder: "Rechercher un média",
8806
+ icon: SearchIcon,
8807
+ clearButton: props.search.length > 0,
8808
+ onClear: () => props.onSearch(""),
8809
+ fontSize: 1,
8810
+ radius: 2
8811
+ })
8812
+ }),
8813
+ /* @__PURE__ */ jsxs(Select, {
8814
+ fontSize: 1,
8815
+ value: props.type,
8816
+ onChange: (e) => props.onType(e.currentTarget.value),
8817
+ style: {
8818
+ flex: "none",
8819
+ width: 120
8820
+ },
8821
+ children: [
8822
+ /* @__PURE__ */ jsx("option", {
8823
+ value: "all",
8824
+ children: "Tous types"
8825
+ }),
8826
+ /* @__PURE__ */ jsx("option", {
8827
+ value: "image",
8828
+ children: "Images"
8829
+ }),
8830
+ /* @__PURE__ */ jsx("option", {
8831
+ value: "file",
8832
+ children: "Fichiers"
8833
+ })
8834
+ ]
8835
+ }),
8836
+ /* @__PURE__ */ jsxs(Select, {
8837
+ fontSize: 1,
8838
+ value: props.usage,
8839
+ onChange: (e) => props.onUsage(e.currentTarget.value),
8840
+ style: {
8841
+ flex: "none",
8842
+ width: 130
8843
+ },
8844
+ children: [
8845
+ /* @__PURE__ */ jsx("option", {
8846
+ value: "all",
8847
+ children: "Tout usage"
8848
+ }),
8849
+ /* @__PURE__ */ jsx("option", {
8850
+ value: "used",
8851
+ children: "Utilisés"
8852
+ }),
8853
+ /* @__PURE__ */ jsx("option", {
8854
+ value: "unused",
8855
+ children: "Inutilisés"
8856
+ })
8857
+ ]
8858
+ }),
8859
+ /* @__PURE__ */ jsxs(Select, {
8860
+ fontSize: 1,
8861
+ value: `${props.sort}:${props.direction}`,
8862
+ onChange: (e) => {
8863
+ let [key, dir] = e.currentTarget.value.split(":");
8864
+ props.onSort(key, dir);
8865
+ },
8866
+ style: {
8867
+ flex: "none",
8868
+ width: 170
8869
+ },
8870
+ children: [
8871
+ /* @__PURE__ */ jsx("option", {
8872
+ value: "date:desc",
8873
+ children: "Plus récents"
8874
+ }),
8875
+ /* @__PURE__ */ jsx("option", {
8876
+ value: "date:asc",
8877
+ children: "Plus anciens"
8878
+ }),
8879
+ /* @__PURE__ */ jsx("option", {
8880
+ value: "name:asc",
8881
+ children: "Nom (A→Z)"
8882
+ }),
8883
+ /* @__PURE__ */ jsx("option", {
8884
+ value: "name:desc",
8885
+ children: "Nom (Z→A)"
8886
+ }),
8887
+ /* @__PURE__ */ jsx("option", {
8888
+ value: "size:desc",
8889
+ children: "Plus lourds"
8890
+ }),
8891
+ /* @__PURE__ */ jsx("option", {
8892
+ value: "size:asc",
8893
+ children: "Plus légers"
8894
+ }),
8895
+ /* @__PURE__ */ jsx("option", {
8896
+ value: "type:asc",
8897
+ children: "Type"
8898
+ })
8899
+ ]
8900
+ }),
8901
+ /* @__PURE__ */ jsxs(Flex, {
8902
+ style: { flex: "none" },
8903
+ gap: 1,
8904
+ children: [/* @__PURE__ */ jsx(Button, {
8905
+ icon: ThLargeIcon,
8906
+ mode: props.view === "grid" ? "default" : "bleed",
8907
+ tone: props.view === "grid" ? "primary" : "default",
8908
+ padding: 2,
8909
+ fontSize: 1,
8910
+ title: "Grille",
8911
+ "aria-label": "Grille",
8912
+ onClick: () => props.onView("grid")
8913
+ }), /* @__PURE__ */ jsx(Button, {
8914
+ icon: ThListIcon,
8915
+ mode: props.view === "table" ? "default" : "bleed",
8916
+ tone: props.view === "table" ? "primary" : "default",
8917
+ padding: 2,
8918
+ fontSize: 1,
8919
+ title: "Table",
8920
+ "aria-label": "Table",
8921
+ onClick: () => props.onView("table")
8922
+ })]
8923
+ }),
8924
+ /* @__PURE__ */ jsx(Button, {
8925
+ icon: SyncIcon,
8926
+ mode: "bleed",
8927
+ padding: 2,
8928
+ fontSize: 1,
8929
+ title: "Rafraîchir",
8930
+ "aria-label": "Rafraîchir",
8931
+ onClick: props.onRefresh,
8932
+ disabled: props.busy
8933
+ })
8934
+ ]
8935
+ });
8936
+ }
8937
+ /** Tuile d'un asset dans la grille : aperçu, nom, taille, type, usage. */
8938
+ function AssetCard(props) {
8939
+ let { asset, selected, onToggleSelect, onOpen } = props, [failed, setFailed] = useState(!1), thumb = thumbnailUrl(asset, {
8940
+ w: 320,
8941
+ h: 220
8942
+ }), unused = asset.uses === 0, meta = [
8943
+ formatBytes(asset.size),
8944
+ asset.dimensions?.width ? `${asset.dimensions.width}×${asset.dimensions.height}` : null,
8945
+ asset.extension?.toUpperCase()
8946
+ ].filter(Boolean).join(" · ");
8947
+ return /* @__PURE__ */ jsxs(Card, {
8948
+ radius: 3,
8949
+ shadow: 1,
8950
+ padding: 0,
8951
+ tone: selected ? "primary" : "default",
8952
+ style: {
8953
+ height: "100%",
8954
+ overflow: "hidden",
8955
+ position: "relative"
8956
+ },
8957
+ children: [/* @__PURE__ */ jsx(Box, {
8958
+ style: {
8959
+ position: "absolute",
8960
+ top: 8,
8961
+ left: 8,
8962
+ zIndex: 1
8963
+ },
8964
+ onClick: (e) => e.stopPropagation(),
8965
+ children: /* @__PURE__ */ jsx(Card, {
8966
+ radius: 2,
8967
+ padding: 1,
8968
+ tone: "default",
8969
+ style: { opacity: selected ? 1 : .85 },
8970
+ children: /* @__PURE__ */ jsx(Checkbox, {
8971
+ checked: selected,
8972
+ onChange: onToggleSelect,
8973
+ "aria-label": "Sélectionner"
8974
+ })
8975
+ })
8976
+ }), /* @__PURE__ */ jsxs(Stack, {
8977
+ gap: 0,
8978
+ as: "button",
8979
+ onClick: onOpen,
8980
+ style: {
8981
+ height: "100%",
8982
+ width: "100%",
8983
+ textAlign: "left",
8984
+ cursor: "pointer",
8985
+ background: "transparent",
8986
+ border: 0,
8987
+ padding: 0
8988
+ },
8989
+ children: [/* @__PURE__ */ jsx(Box, {
8990
+ style: {
8991
+ aspectRatio: "16 / 11",
8992
+ overflow: "hidden",
8993
+ background: "var(--card-muted-bg-color, rgba(127,127,127,0.08))"
8994
+ },
8995
+ children: thumb && !failed ? /* @__PURE__ */ jsx("img", {
8996
+ src: thumb,
8997
+ alt: "",
8998
+ loading: "lazy",
8999
+ onError: () => setFailed(!0),
9000
+ style: {
9001
+ width: "100%",
9002
+ height: "100%",
9003
+ objectFit: "cover",
9004
+ display: "block"
9005
+ }
9006
+ }) : /* @__PURE__ */ jsxs(Flex, {
9007
+ align: "center",
9008
+ justify: "center",
9009
+ direction: "column",
9010
+ gap: 2,
9011
+ style: { height: "100%" },
9012
+ padding: 3,
9013
+ children: [/* @__PURE__ */ jsx(Text, {
9014
+ size: 3,
9015
+ muted: !0,
9016
+ children: /* @__PURE__ */ jsx(DocumentIcon, {})
9017
+ }), /* @__PURE__ */ jsx(Text, {
9018
+ size: 0,
9019
+ muted: !0,
9020
+ children: asset.extension?.toUpperCase() || (isImageAsset(asset) ? "IMAGE" : "FICHIER")
9021
+ })]
9022
+ })
9023
+ }), /* @__PURE__ */ jsx(Box, {
9024
+ padding: 3,
9025
+ children: /* @__PURE__ */ jsxs(Stack, {
9026
+ gap: 2,
9027
+ children: [/* @__PURE__ */ jsxs(Flex, {
9028
+ align: "center",
9029
+ gap: 2,
9030
+ justify: "space-between",
9031
+ children: [/* @__PURE__ */ jsx(Text, {
9032
+ size: 1,
9033
+ weight: "medium",
9034
+ textOverflow: "ellipsis",
9035
+ style: { minWidth: 0 },
9036
+ children: assetName(asset)
9037
+ }), unused ? /* @__PURE__ */ jsx(Badge, {
9038
+ tone: "caution",
9039
+ fontSize: 0,
9040
+ style: { flex: "none" },
9041
+ title: "Aucun document ne l’utilise",
9042
+ children: "inutilisé"
9043
+ }) : null]
9044
+ }), /* @__PURE__ */ jsx(Text, {
9045
+ size: 0,
9046
+ muted: !0,
9047
+ textOverflow: "ellipsis",
9048
+ style: MONO,
9049
+ children: meta
9050
+ })]
9051
+ })
9052
+ })]
9053
+ })]
9054
+ });
9055
+ }
9056
+ const COLS = [
9057
+ {
9058
+ key: "name",
9059
+ label: "Nom"
9060
+ },
9061
+ {
9062
+ key: "type",
9063
+ label: "Type"
9064
+ },
9065
+ {
9066
+ key: "size",
9067
+ label: "Taille",
9068
+ align: "right"
9069
+ },
9070
+ {
9071
+ key: null,
9072
+ label: "Dimensions",
9073
+ align: "right"
9074
+ },
9075
+ {
9076
+ key: null,
9077
+ label: "Dossier"
9078
+ },
9079
+ {
9080
+ key: null,
9081
+ label: "Usage",
9082
+ align: "right"
9083
+ },
9084
+ {
9085
+ key: "date",
9086
+ label: "Ajouté",
9087
+ align: "right"
9088
+ }
9089
+ ];
9090
+ function AssetTable(props) {
9091
+ let { assets, selected, onToggleSelect, onToggleAll, onOpen, folderName, folderOf, sortKey, sortDirection, onSort } = props, allSelected = assets.length > 0 && assets.every((a) => selected.has(a._id)), arrow = (key) => sortKey === key ? sortDirection === "asc" ? " ↑" : " ↓" : "";
9092
+ return /* @__PURE__ */ jsx(Box, {
9093
+ overflow: "auto",
9094
+ children: /* @__PURE__ */ jsxs("table", {
9095
+ style: {
9096
+ width: "100%",
9097
+ borderCollapse: "collapse",
9098
+ fontSize: 13
9099
+ },
9100
+ children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", {
9101
+ style: {
9102
+ textAlign: "left",
9103
+ borderBottom: "1px solid var(--card-border-color)"
9104
+ },
9105
+ children: [/* @__PURE__ */ jsx("th", {
9106
+ style: {
9107
+ padding: "8px 10px",
9108
+ width: 36
9109
+ },
9110
+ children: /* @__PURE__ */ jsx(Checkbox, {
9111
+ checked: allSelected,
9112
+ indeterminate: !allSelected && assets.some((a) => selected.has(a._id)),
9113
+ onChange: onToggleAll,
9114
+ "aria-label": "Tout sélectionner"
9115
+ })
9116
+ }), COLS.map((col) => /* @__PURE__ */ jsx("th", {
9117
+ onClick: col.key ? () => onSort(col.key) : void 0,
9118
+ style: {
9119
+ padding: "8px 10px",
9120
+ whiteSpace: "nowrap",
9121
+ textAlign: col.align ?? "left",
9122
+ cursor: col.key ? "pointer" : "default",
9123
+ userSelect: "none"
9124
+ },
9125
+ children: /* @__PURE__ */ jsxs(Text, {
9126
+ size: 1,
9127
+ weight: "medium",
9128
+ muted: !0,
9129
+ children: [col.label, col.key ? arrow(col.key) : ""]
9130
+ })
9131
+ }, col.label))]
9132
+ }) }), /* @__PURE__ */ jsx("tbody", { children: assets.map((asset) => {
9133
+ let thumb = thumbnailUrl(asset, {
9134
+ w: 64,
9135
+ h: 64
9136
+ }), folder = folderOf(asset._id);
9137
+ return /* @__PURE__ */ jsxs("tr", {
9138
+ onClick: () => onOpen(asset),
9139
+ style: {
9140
+ borderBottom: "1px solid var(--card-border-color)",
9141
+ cursor: "pointer",
9142
+ background: selected.has(asset._id) ? "var(--card-badge-primary-bg-color, rgba(45,114,225,0.08))" : void 0
9143
+ },
9144
+ children: [
9145
+ /* @__PURE__ */ jsx("td", {
9146
+ style: { padding: "6px 10px" },
9147
+ onClick: (e) => e.stopPropagation(),
9148
+ children: /* @__PURE__ */ jsx(Checkbox, {
9149
+ checked: selected.has(asset._id),
9150
+ onChange: () => onToggleSelect(asset._id),
9151
+ "aria-label": "Sélectionner"
9152
+ })
9153
+ }),
9154
+ /* @__PURE__ */ jsx("td", {
9155
+ style: { padding: "6px 10px" },
9156
+ children: /* @__PURE__ */ jsxs(Flex, {
9157
+ align: "center",
9158
+ gap: 2,
9159
+ children: [/* @__PURE__ */ jsx(Box, {
9160
+ style: {
9161
+ width: 32,
9162
+ height: 32,
9163
+ flex: "none",
9164
+ borderRadius: 4,
9165
+ overflow: "hidden",
9166
+ background: "var(--card-muted-bg-color, rgba(127,127,127,0.08))"
9167
+ },
9168
+ children: thumb ? /* @__PURE__ */ jsx("img", {
9169
+ src: thumb,
9170
+ alt: "",
9171
+ loading: "lazy",
9172
+ style: {
9173
+ width: "100%",
9174
+ height: "100%",
9175
+ objectFit: "cover"
9176
+ }
9177
+ }) : null
9178
+ }), /* @__PURE__ */ jsx(Text, {
9179
+ size: 1,
9180
+ textOverflow: "ellipsis",
9181
+ children: assetName(asset)
9182
+ })]
9183
+ })
9184
+ }),
9185
+ /* @__PURE__ */ jsx("td", {
9186
+ style: {
9187
+ padding: "6px 10px",
9188
+ whiteSpace: "nowrap"
9189
+ },
9190
+ children: /* @__PURE__ */ jsx(Text, {
9191
+ size: 1,
9192
+ muted: !0,
9193
+ style: MONO,
9194
+ children: asset.extension?.toUpperCase() || (isImageAsset(asset) ? "IMG" : "FICHIER")
9195
+ })
9196
+ }),
9197
+ /* @__PURE__ */ jsx("td", {
9198
+ style: {
9199
+ padding: "6px 10px",
9200
+ textAlign: "right",
9201
+ whiteSpace: "nowrap"
9202
+ },
9203
+ children: /* @__PURE__ */ jsx(Text, {
9204
+ size: 1,
9205
+ style: TABULAR,
9206
+ children: formatBytes(asset.size)
9207
+ })
9208
+ }),
9209
+ /* @__PURE__ */ jsx("td", {
9210
+ style: {
9211
+ padding: "6px 10px",
9212
+ textAlign: "right",
9213
+ whiteSpace: "nowrap"
9214
+ },
9215
+ children: /* @__PURE__ */ jsx(Text, {
9216
+ size: 1,
9217
+ muted: !0,
9218
+ style: TABULAR,
9219
+ children: asset.dimensions?.width ? `${asset.dimensions.width}×${asset.dimensions.height}` : "—"
9220
+ })
9221
+ }),
9222
+ /* @__PURE__ */ jsx("td", {
9223
+ style: {
9224
+ padding: "6px 10px",
9225
+ whiteSpace: "nowrap"
9226
+ },
9227
+ children: /* @__PURE__ */ jsx(Text, {
9228
+ size: 1,
9229
+ muted: !0,
9230
+ textOverflow: "ellipsis",
9231
+ children: folder ? folderName(folder) : "—"
9232
+ })
9233
+ }),
9234
+ /* @__PURE__ */ jsx("td", {
9235
+ style: {
9236
+ padding: "6px 10px",
9237
+ textAlign: "right",
9238
+ whiteSpace: "nowrap"
9239
+ },
9240
+ children: asset.uses === 0 ? /* @__PURE__ */ jsx(Badge, {
9241
+ tone: "caution",
9242
+ fontSize: 0,
9243
+ children: "0"
9244
+ }) : /* @__PURE__ */ jsx(Text, {
9245
+ size: 1,
9246
+ style: TABULAR,
9247
+ children: asset.uses ?? "—"
9248
+ })
9249
+ }),
9250
+ /* @__PURE__ */ jsx("td", {
9251
+ style: {
9252
+ padding: "6px 10px",
9253
+ textAlign: "right",
9254
+ whiteSpace: "nowrap"
9255
+ },
9256
+ children: /* @__PURE__ */ jsx(Text, {
9257
+ size: 1,
9258
+ muted: !0,
9259
+ style: TABULAR,
9260
+ children: formatDate(asset._createdAt)
9261
+ })
9262
+ })
9263
+ ]
9264
+ }, asset._id);
9265
+ }) })]
9266
+ })
9267
+ });
9268
+ }
9269
+ function Metric(props) {
9270
+ return /* @__PURE__ */ jsxs(Stack, {
9271
+ gap: 2,
9272
+ children: [/* @__PURE__ */ jsx(Label, {
9273
+ size: 0,
9274
+ muted: !0,
9275
+ children: props.label
9276
+ }), /* @__PURE__ */ jsx(Text, {
9277
+ size: 1,
9278
+ style: MONO,
9279
+ textOverflow: "ellipsis",
9280
+ children: props.value
9281
+ })]
9282
+ });
9283
+ }
9284
+ function AssetDetail(props) {
9285
+ let { asset, folders, folder, onMove, onClose } = props, client = useKitClient(), [title, setTitle] = useState(asset.title ?? ""), [alt, setAlt] = useState(asset.altText ?? ""), [description, setDescription] = useState(asset.description ?? ""), [copied, setCopied] = useState(!1);
9286
+ useEffect(() => {
9287
+ setTitle(asset.title ?? ""), setAlt(asset.altText ?? ""), setDescription(asset.description ?? "");
9288
+ }, [
9289
+ asset._id,
9290
+ asset.title,
9291
+ asset.altText,
9292
+ asset.description
9293
+ ]);
9294
+ let save = (patch) => {
9295
+ client.patch(asset._id).set(patch).commit().catch(() => {});
9296
+ }, commit = (field, value, original) => {
9297
+ let next = value.trim();
9298
+ next !== (original ?? "") && save({ [field]: next || void 0 });
9299
+ }, preview = thumbnailUrl(asset, { w: 640 }), copyUrl = () => {
9300
+ asset.url && navigator.clipboard?.writeText(asset.url).then(() => {
9301
+ setCopied(!0), setTimeout(() => setCopied(!1), 1500);
9302
+ });
9303
+ };
9304
+ return /* @__PURE__ */ jsx(Card, {
9305
+ borderLeft: !0,
9306
+ height: "fill",
9307
+ style: {
9308
+ width: 340,
9309
+ flex: "none"
9310
+ },
9311
+ overflow: "auto",
9312
+ tone: "transparent",
9313
+ children: /* @__PURE__ */ jsxs(Stack, {
9314
+ gap: 4,
9315
+ padding: 4,
9316
+ children: [
9317
+ /* @__PURE__ */ jsxs(Flex, {
9318
+ align: "center",
9319
+ justify: "space-between",
9320
+ gap: 2,
9321
+ children: [/* @__PURE__ */ jsx(Text, {
9322
+ size: 1,
9323
+ weight: "semibold",
9324
+ textOverflow: "ellipsis",
9325
+ children: assetName(asset)
9326
+ }), /* @__PURE__ */ jsx(Button, {
9327
+ icon: CloseIcon,
9328
+ mode: "bleed",
9329
+ padding: 2,
9330
+ fontSize: 1,
9331
+ "aria-label": "Fermer",
9332
+ onClick: onClose
9333
+ })]
9334
+ }),
9335
+ /* @__PURE__ */ jsx(Card, {
9336
+ radius: 2,
9337
+ border: !0,
9338
+ overflow: "hidden",
9339
+ tone: "transparent",
9340
+ style: { background: "var(--card-muted-bg-color, rgba(127,127,127,0.08))" },
9341
+ children: preview ? /* @__PURE__ */ jsx("img", {
9342
+ src: preview,
9343
+ alt: asset.altText ?? "",
9344
+ style: {
9345
+ width: "100%",
9346
+ display: "block",
9347
+ maxHeight: 280,
9348
+ objectFit: "contain"
9349
+ }
9350
+ }) : /* @__PURE__ */ jsx(Flex, {
9351
+ align: "center",
9352
+ justify: "center",
9353
+ padding: 5,
9354
+ children: /* @__PURE__ */ jsxs(Text, {
9355
+ size: 1,
9356
+ muted: !0,
9357
+ children: [asset.extension?.toUpperCase() || "Fichier", " — pas d'aperçu"]
9358
+ })
9359
+ })
9360
+ }),
9361
+ /* @__PURE__ */ jsxs(Flex, {
9362
+ gap: 2,
9363
+ children: [/* @__PURE__ */ jsx(Button, {
9364
+ icon: CopyIcon,
9365
+ text: copied ? "Copié" : "Copier l'URL",
9366
+ mode: "ghost",
9367
+ fontSize: 1,
9368
+ onClick: copyUrl,
9369
+ disabled: !asset.url,
9370
+ style: { flex: 1 }
9371
+ }), /* @__PURE__ */ jsx(Button, {
9372
+ icon: LaunchIcon,
9373
+ text: "Ouvrir",
9374
+ mode: "ghost",
9375
+ fontSize: 1,
9376
+ onClick: () => asset.url && window.open(asset.url, "_blank", "noopener"),
9377
+ disabled: !asset.url,
9378
+ style: { flex: 1 }
9379
+ })]
9380
+ }),
9381
+ /* @__PURE__ */ jsxs(Stack, {
9382
+ gap: 3,
9383
+ children: [
9384
+ /* @__PURE__ */ jsxs(Stack, {
9385
+ gap: 2,
9386
+ children: [/* @__PURE__ */ jsx(Label, {
9387
+ size: 0,
9388
+ muted: !0,
9389
+ children: "Dossier"
9390
+ }), /* @__PURE__ */ jsxs(Select, {
9391
+ fontSize: 1,
9392
+ value: folder ?? "",
9393
+ onChange: (event) => onMove(event.currentTarget.value || null),
9394
+ children: [/* @__PURE__ */ jsx("option", {
9395
+ value: "",
9396
+ children: "Non classé"
9397
+ }), folders.map((f) => /* @__PURE__ */ jsx("option", {
9398
+ value: f.id,
9399
+ children: f.name
9400
+ }, f.id))]
9401
+ })]
9402
+ }),
9403
+ /* @__PURE__ */ jsxs(Stack, {
9404
+ gap: 2,
9405
+ children: [/* @__PURE__ */ jsx(Label, {
9406
+ size: 0,
9407
+ muted: !0,
9408
+ children: "Titre"
9409
+ }), /* @__PURE__ */ jsx(TextInput, {
9410
+ fontSize: 1,
9411
+ value: title,
9412
+ onChange: (e) => setTitle(e.currentTarget.value),
9413
+ onBlur: () => commit("title", title, asset.title),
9414
+ placeholder: "Titre du média"
9415
+ })]
9416
+ }),
9417
+ isImageAsset(asset) ? /* @__PURE__ */ jsxs(Stack, {
9418
+ gap: 2,
9419
+ children: [/* @__PURE__ */ jsx(Label, {
9420
+ size: 0,
9421
+ muted: !0,
9422
+ children: "Texte alternatif (alt)"
9423
+ }), /* @__PURE__ */ jsx(TextInput, {
9424
+ fontSize: 1,
9425
+ value: alt,
9426
+ onChange: (e) => setAlt(e.currentTarget.value),
9427
+ onBlur: () => commit("altText", alt, asset.altText),
9428
+ placeholder: "Décrit l'image (SEO, accessibilité)"
9429
+ })]
9430
+ }) : null,
9431
+ /* @__PURE__ */ jsxs(Stack, {
9432
+ gap: 2,
9433
+ children: [/* @__PURE__ */ jsx(Label, {
9434
+ size: 0,
9435
+ muted: !0,
9436
+ children: "Description"
9437
+ }), /* @__PURE__ */ jsx(TextArea, {
9438
+ fontSize: 1,
9439
+ rows: 2,
9440
+ value: description,
9441
+ onChange: (e) => setDescription(e.currentTarget.value),
9442
+ onBlur: () => commit("description", description, asset.description)
9443
+ })]
9444
+ })
9445
+ ]
9446
+ }),
9447
+ /* @__PURE__ */ jsxs(Grid, {
9448
+ gridTemplateColumns: [1, 2],
9449
+ gap: 3,
9450
+ children: [
9451
+ /* @__PURE__ */ jsx(Metric, {
9452
+ label: "Fichier",
9453
+ value: asset.originalFilename ?? "—"
9454
+ }),
9455
+ /* @__PURE__ */ jsx(Metric, {
9456
+ label: "Type",
9457
+ value: asset.extension?.toUpperCase() || asset._type.replace("sanity.", "")
9458
+ }),
9459
+ /* @__PURE__ */ jsx(Metric, {
9460
+ label: "Taille",
9461
+ value: formatBytes(asset.size)
9462
+ }),
9463
+ /* @__PURE__ */ jsx(Metric, {
9464
+ label: "Dimensions",
9465
+ value: asset.dimensions?.width ? `${asset.dimensions.width}×${asset.dimensions.height}` : "—"
9466
+ }),
9467
+ /* @__PURE__ */ jsx(Metric, {
9468
+ label: "Usage",
9469
+ value: asset.uses === void 0 ? "—" : `${asset.uses}`
9470
+ }),
9471
+ /* @__PURE__ */ jsx(Metric, {
9472
+ label: "Ajouté",
9473
+ value: formatDate(asset._createdAt)
9474
+ })
9475
+ ]
9476
+ })
9477
+ ]
9478
+ })
9479
+ });
9480
+ }
9481
+ function AssetsTool() {
9482
+ let { data, loading, error, refresh } = useAssets(), meta = useAssetMeta(), assets = useMemo(() => data ?? [], [data]), [search, setSearch] = useState(""), [type, setType] = useState("all"), [usage, setUsage] = useState("all"), [sort, setSort] = useState("date"), [direction, setDirection] = useState("desc"), [view, setView] = useState("grid"), [selection, setSelection] = useState(null), [selectedIds, setSelectedIds] = useState(/* @__PURE__ */ new Set()), [openedId, setOpenedId] = useState(null), folderMap = useMemo(() => assignmentMap(meta.assignments), [meta.assignments]), counts = useMemo(() => countByFolder(assets, folderMap), [assets, folderMap]), folderName = useCallback((id) => meta.folders.find((f) => f.id === id)?.name ?? id, [meta.folders]), folderOf = useCallback((assetId) => folderMap.get(assetId) ?? null, [folderMap]), visible = useMemo(() => sortAssets(filterAssets(assetsInFolder(assets, folderMap, selection), {
9483
+ search,
9484
+ type,
9485
+ usage
9486
+ }), sort, direction), [
9487
+ assets,
9488
+ folderMap,
9489
+ selection,
9490
+ search,
9491
+ type,
9492
+ usage,
9493
+ sort,
9494
+ direction
9495
+ ]), opened = openedId ? assets.find((a) => a._id === openedId) ?? null : null, toggleSelect = useCallback((id) => {
9496
+ setSelectedIds((prev) => {
9497
+ let next = new Set(prev);
9498
+ return next.has(id) ? next.delete(id) : next.add(id), next;
9499
+ });
9500
+ }, []), toggleAll = useCallback(() => {
9501
+ setSelectedIds((prev) => {
9502
+ if (visible.every((a) => prev.has(a._id))) {
9503
+ let next = new Set(prev);
9504
+ for (let a of visible) next.delete(a._id);
9505
+ return next;
9506
+ }
9507
+ let next = new Set(prev);
9508
+ for (let a of visible) next.add(a._id);
9509
+ return next;
9510
+ });
9511
+ }, [visible]), clearSelection = useCallback(() => setSelectedIds(/* @__PURE__ */ new Set()), []), moveSelected = useCallback((folder) => {
9512
+ meta.moveAssets([...selectedIds], folder), clearSelection();
9513
+ }, [
9514
+ meta,
9515
+ selectedIds,
9516
+ clearSelection
9517
+ ]);
9518
+ return loading && assets.length === 0 ? /* @__PURE__ */ jsx(Flex, {
9519
+ align: "center",
9520
+ justify: "center",
9521
+ padding: 6,
9522
+ children: /* @__PURE__ */ jsx(Spinner, { muted: !0 })
9523
+ }) : error ? /* @__PURE__ */ jsx(QueryError, {
9524
+ error,
9525
+ onRetry: refresh
9526
+ }) : /* @__PURE__ */ jsxs(Flex, {
9527
+ gap: 4,
9528
+ align: "stretch",
9529
+ style: { minHeight: 420 },
9530
+ children: [
9531
+ /* @__PURE__ */ jsx(Box, {
9532
+ style: {
9533
+ width: 220,
9534
+ flex: "none"
9535
+ },
9536
+ children: /* @__PURE__ */ jsx(FolderSidebar, {
9537
+ folders: meta.folders,
9538
+ counts,
9539
+ total: assets.length,
9540
+ selection,
9541
+ onSelect: setSelection,
9542
+ onCreate: meta.createFolder,
9543
+ onRename: meta.renameFolder,
9544
+ onDelete: (id) => {
9545
+ selection === id && setSelection(null), meta.deleteFolder(id);
9546
+ }
9547
+ })
9548
+ }),
9549
+ /* @__PURE__ */ jsxs(Stack, {
9550
+ gap: 3,
9551
+ flex: 1,
9552
+ style: { minWidth: 0 },
9553
+ children: [
9554
+ /* @__PURE__ */ jsx(AssetsToolbar, {
9555
+ search,
9556
+ onSearch: setSearch,
9557
+ type,
9558
+ onType: setType,
9559
+ usage,
9560
+ onUsage: setUsage,
9561
+ sort,
9562
+ direction,
9563
+ onSort: (k, d) => {
9564
+ setSort(k), setDirection(d);
9565
+ },
9566
+ view,
9567
+ onView: setView,
9568
+ onRefresh: refresh,
9569
+ busy: loading
9570
+ }),
9571
+ selectedIds.size > 0 ? /* @__PURE__ */ jsx(Card, {
9572
+ tone: "primary",
9573
+ border: !0,
9574
+ radius: 2,
9575
+ padding: 2,
9576
+ children: /* @__PURE__ */ jsxs(Flex, {
9577
+ align: "center",
9578
+ gap: 3,
9579
+ wrap: "wrap",
9580
+ children: [
9581
+ /* @__PURE__ */ jsxs(Text, {
9582
+ size: 1,
9583
+ weight: "medium",
9584
+ children: [
9585
+ selectedIds.size,
9586
+ " sélectionné",
9587
+ selectedIds.size > 1 ? "s" : ""
9588
+ ]
9589
+ }),
9590
+ /* @__PURE__ */ jsxs(Flex, {
9591
+ align: "center",
9592
+ gap: 2,
9593
+ children: [/* @__PURE__ */ jsx(Text, {
9594
+ size: 1,
9595
+ muted: !0,
9596
+ children: "Déplacer vers"
9597
+ }), /* @__PURE__ */ jsxs(Select, {
9598
+ fontSize: 1,
9599
+ value: "",
9600
+ onChange: (e) => {
9601
+ let v = e.currentTarget.value;
9602
+ v === "__none" ? moveSelected(null) : v && moveSelected(v);
9603
+ },
9604
+ style: { width: 170 },
9605
+ children: [
9606
+ /* @__PURE__ */ jsx("option", {
9607
+ value: "",
9608
+ children: "Choisir…"
9609
+ }),
9610
+ /* @__PURE__ */ jsx("option", {
9611
+ value: "__none",
9612
+ children: "Non classé"
9613
+ }),
9614
+ meta.folders.map((f) => /* @__PURE__ */ jsx("option", {
9615
+ value: f.id,
9616
+ children: f.name
9617
+ }, f.id))
9618
+ ]
9619
+ })]
9620
+ }),
9621
+ /* @__PURE__ */ jsx(Box, { flex: 1 }),
9622
+ /* @__PURE__ */ jsx(Button, {
9623
+ text: "Désélectionner",
9624
+ mode: "bleed",
9625
+ fontSize: 1,
9626
+ onClick: clearSelection
9627
+ })
9628
+ ]
9629
+ })
9630
+ }) : null,
9631
+ /* @__PURE__ */ jsxs(Text, {
9632
+ size: 1,
9633
+ muted: !0,
9634
+ children: [
9635
+ visible.length,
9636
+ " média",
9637
+ visible.length > 1 ? "s" : "",
9638
+ visible.length === assets.length ? "" : ` sur ${assets.length}`
9639
+ ]
9640
+ }),
9641
+ visible.length === 0 ? /* @__PURE__ */ jsx(Card, {
9642
+ border: !0,
9643
+ radius: 2,
9644
+ padding: 5,
9645
+ tone: "transparent",
9646
+ children: /* @__PURE__ */ jsxs(Text, {
9647
+ size: 1,
9648
+ muted: !0,
9649
+ align: "center",
9650
+ children: [
9651
+ "Aucun média ",
9652
+ search || type !== "all" || usage !== "all" ? "ne correspond aux filtres" : selection ? "dans ce dossier" : "pour l’instant",
9653
+ "."
9654
+ ]
9655
+ })
9656
+ }) : view === "grid" ? /* @__PURE__ */ jsx(Grid, {
9657
+ gridTemplateColumns: [
9658
+ 2,
9659
+ 3,
9660
+ 4,
9661
+ 5
9662
+ ],
9663
+ gap: 3,
9664
+ children: visible.map((asset) => /* @__PURE__ */ jsx(AssetCard, {
9665
+ asset,
9666
+ selected: selectedIds.has(asset._id),
9667
+ onToggleSelect: () => toggleSelect(asset._id),
9668
+ onOpen: () => setOpenedId(asset._id)
9669
+ }, asset._id))
9670
+ }) : /* @__PURE__ */ jsx(AssetTable, {
9671
+ assets: visible,
9672
+ selected: selectedIds,
9673
+ onToggleSelect: toggleSelect,
9674
+ onToggleAll: toggleAll,
9675
+ onOpen: (asset) => setOpenedId(asset._id),
9676
+ folderName,
9677
+ folderOf,
9678
+ sortKey: sort,
9679
+ sortDirection: direction,
9680
+ onSort: (key) => {
9681
+ setSort(key), setDirection((d) => sort === key && d === "asc" ? "desc" : "asc");
9682
+ }
9683
+ })
9684
+ ]
9685
+ }),
9686
+ opened ? /* @__PURE__ */ jsx(AssetDetail, {
9687
+ asset: opened,
9688
+ folders: meta.folders,
9689
+ folder: folderOf(opened._id),
9690
+ onMove: (folder) => meta.moveAsset(opened._id, folder),
9691
+ onClose: () => setOpenedId(null)
9692
+ }) : null
9693
+ ]
9694
+ });
9695
+ }
9696
+ const store$1 = /* @__PURE__ */ new Map();
9697
+ function entryFor$1(client, type, languageField, language) {
9698
+ let { projectId, dataset } = client.config(), key = `${projectId}:${dataset}:${type}:${language ?? ""}`, entry = store$1.get(key);
9699
+ entry || (entry = {
9700
+ value: null,
9701
+ listeners: /* @__PURE__ */ new Set(),
9702
+ stop: null
9703
+ }, store$1.set(key, entry));
9704
+ let e = entry;
9705
+ if (!e.stop) {
9706
+ let filter = `_type == $type && ($language == null || !defined(${languageField}) || ${languageField} == $language)`, params = {
9707
+ type,
9708
+ language
9709
+ }, drafts = client.withConfig({ perspective: "drafts" }), load = () => drafts.fetch(`*[${filter}][0]`, params).then((value) => {
9710
+ e.value = value, e.listeners.forEach((l) => l());
9711
+ }).catch(() => {});
9712
+ load();
9713
+ let sub = client.listen(`*[${filter}]`, params, {
9714
+ visibility: "query",
9715
+ includeResult: !1
9716
+ }).subscribe({ next: () => void load() });
9717
+ e.stop = () => sub.unsubscribe();
9718
+ }
9719
+ return [key, e];
9720
+ }
9721
+ function useComponentDefaults(client, type, languageField, language) {
9722
+ let [, entry] = entryFor$1(client, type, languageField, language), value = useSyncExternalStore((listener) => (entry.listeners.add(listener), () => {
9723
+ entry.listeners.delete(listener);
9724
+ }), () => entry.value);
9725
+ return useEffect(() => () => {
9726
+ entry.listeners.size === 0 && entry.stop && (entry.stop(), entry.stop = null);
9727
+ }, [entry]), value;
9728
+ }
9729
+ const LINK_TARGET_FIELDS = [
9730
+ "page",
9731
+ "fixedPath",
9732
+ "href",
9733
+ "email",
9734
+ "phone",
9735
+ "file"
9736
+ ], LINK_TYPES = /* @__PURE__ */ new Set(["link", "cardLink"]);
9737
+ function isEmptyValue(value) {
9738
+ return value == null || value === "" || Array.isArray(value) && value.length === 0;
9739
+ }
9740
+ const isKeyed = (s) => typeof s == "object" && !!s && !Array.isArray(s) && typeof s._key == "string";
9741
+ /** Index du premier élément de liste du chemin (l'instance de composant dans le page builder), ou -1. */
9742
+ function firstKeyedIndex(path) {
9743
+ return path.findIndex(isKeyed);
9744
+ }
9745
+ /**
9746
+ * Chemin du champ à l'intérieur de l'instance, listes comprises : un élément de
9747
+ * liste est repéré par son rang (`['items', 0, 'title']`), comparé à l'élément de
9748
+ * même rang de la valeur par défaut. `inList` : le champ est dans un élément de
9749
+ * liste (une liste remplie remplace celle du défaut en entier : réinitialiser
9750
+ * RECOPIE la valeur par défaut au lieu de vider le champ). `null` : pas un
9751
+ * composant de l'espace de noms.
9752
+ */
9753
+ function resolveFieldPath(path, index, instance, namespace) {
9754
+ let type = instance?._type;
9755
+ if (index < 0 || typeof type != "string" || !type.startsWith(namespace)) return null;
9756
+ let rest = path.slice(index + 1);
9757
+ if (rest.length === 0) return null;
9758
+ let out = [], inList = !1, node = instance;
9759
+ for (let seg of rest) if (typeof seg == "string") out.push(seg), node = node && typeof node == "object" ? node[seg] : void 0;
9760
+ else if (isKeyed(seg) || typeof seg == "number") {
9761
+ if (!Array.isArray(node)) return null;
9762
+ let i = typeof seg == "number" ? seg : node.findIndex((item) => item?._key === seg._key);
9763
+ if (i < 0 || node[i]?._type === "block") return null;
9764
+ out.push(i), inList = !0, node = node[i];
9765
+ } else return null;
9766
+ return {
9767
+ path: out,
9768
+ inList
9769
+ };
9770
+ }
9771
+ /** Valeur par défaut d'un champ de composant. */
9772
+ function defaultValueAt(defaults, blockShortName, relPath) {
9773
+ let node = defaults?.[blockShortName];
9774
+ for (let key of relPath) {
9775
+ if (!node || typeof node != "object") return;
9776
+ node = node[key];
9777
+ }
9778
+ return node;
9779
+ }
9780
+ const hasLinkTarget = (link) => {
9781
+ let l = link ?? {};
9782
+ return LINK_TARGET_FIELDS.some((k) => k === "file" ? !!l.file?.asset : !isEmptyValue(l[k]));
9783
+ };
9784
+ /**
9785
+ * Le champ est-il un override ? Valeur propre à l'instance DIFFÉRENTE de la
9786
+ * valeur par défaut du composant (y compris quand le composant n'a pas de valeur
9787
+ * par défaut pour ce champ). Un champ vide hérite : jamais d'override. Une case
9788
+ * décochée vaut une case non renseignée. Le type d'un lien ne compte que si le
9789
+ * lien a sa propre cible (il est prérempli par le Studio).
9790
+ */
9791
+ function isOverride(local, inherited, field, parent) {
9792
+ if (isEmptyValue(local) || local === !1 && isEmptyValue(inherited)) return !1;
9793
+ let parentType = parent?._type;
9794
+ return field === "type" && typeof parentType == "string" && LINK_TYPES.has(parentType) && !hasLinkTarget(parent) ? !1 : !sameValue(local, inherited);
9795
+ }
9796
+ /** Égalité de valeurs (champ identique au défaut : override « figé »). */
9797
+ function sameValue(a, b) {
9798
+ if (a === b) return !0;
9799
+ let clean = (v) => Array.isArray(v) ? v.map(clean) : v && typeof v == "object" ? Object.fromEntries(Object.entries(v).filter(([k]) => !k.startsWith("_") || k === "_ref").sort(([x], [y]) => x.localeCompare(y)).map(([k, x]) => [k, clean(x)])) : v;
9800
+ return JSON.stringify(clean(a)) === JSON.stringify(clean(b));
9801
+ }
9802
+ /** Valeur par défaut lisible, pour la bulle de la pastille. */
9803
+ function describeValue(value) {
9804
+ if (isEmptyValue(value)) return "empty (design system value)";
9805
+ if (typeof value == "string") return value.length > 60 ? `"${value.slice(0, 57)}…"` : `"${value}"`;
9806
+ if (typeof value == "boolean") return value ? "Yes" : "No";
9807
+ if (typeof value == "number") return String(value);
9808
+ if (Array.isArray(value)) return `${value.length} item${value.length > 1 ? "s" : ""}`;
9809
+ if (value && typeof value == "object") {
9810
+ let v = value;
9811
+ if (typeof v.token == "string") return `color ${v.token}`;
9812
+ if (typeof v.customHex == "string") return `color ${v.customHex}`;
9813
+ if (typeof v.label == "string") return `"${v.label}"`;
9814
+ if (v.asset) return "an image";
9815
+ if (typeof v._ref == "string") return "a document";
9816
+ }
9817
+ return "a value";
9818
+ }
9819
+ /**
9820
+ * Ce que fait « Réinitialiser » : remettre le champ en HÉRITAGE (le vider en
9821
+ * base). Il suit alors la valeur par défaut du composant, aujourd'hui comme
9822
+ * après ses changements (une copie serait figée). Le champ affiche la valeur
9823
+ * héritée (grisée). Sans valeur par défaut, rien à hériter : le champ resterait
9824
+ * vide, la pastille renvoie donc au réglage du composant.
9825
+ */
9826
+ function resetAction(inherited) {
9827
+ return isEmptyValue(inherited) ? { kind: "noDefault" } : { kind: "inherit" };
9828
+ }
9829
+ /** Texte grisé d'un champ texte vide qui hérite de la valeur par défaut. */
9830
+ function inheritedPlaceholder(value) {
9831
+ return typeof value == "string" && value.trim() ? value : typeof value == "number" ? String(value) : null;
9832
+ }
9833
+ /** Libellé court de la valeur par défaut, pour la pastille au survol. */
9834
+ function shortValue(value, max = 32) {
9835
+ let d = describeValue(value);
9836
+ return d.length > max ? `${d.slice(0, max - 1)}…` : d;
9837
+ }
9838
+ /**
9839
+ * Un champ hérité doit-il afficher la valeur par défaut **pré-sélectionnée**
9840
+ * dans son contrôle ?
9841
+ *
9842
+ * Oui pour un choix (liste d'options : style, taille, position, niveau de
9843
+ * titre…) et pour une case à cocher : l'éditeur voit ce qui s'appliquera, au
9844
+ * lieu d'un contrôle vide doublé d'une mention. La valeur n'est pas écrite —
9845
+ * le champ reste vide, donc hérité ; choisir autre chose l'emporte et fait
9846
+ * apparaître la pastille de réinitialisation.
9847
+ *
9848
+ * Non pour le texte libre (déjà traité par un placeholder grisé) ni pour les
9849
+ * objets, listes et images (pas de « valeur sélectionnée » à montrer).
9850
+ */
9851
+ function preselectsDefault(schemaType, inherited) {
9852
+ if (isEmptyValue(inherited)) return !1;
9853
+ let jt = schemaType?.jsonType;
9854
+ return jt === "boolean" || (jt === "string" || jt === "number") && (schemaType?.options?.list?.length ?? 0) > 0;
9855
+ }
9856
+ /**
9857
+ * Pastille bleue sur tout champ d'une instance de composant dont la valeur
9858
+ * DIFFÈRE de la valeur par défaut du composant (valeur par défaut vide comprise),
9859
+ * éléments de liste compris (comparés à l'élément de même rang). Au survol, elle
9860
+ * affiche la valeur par défaut ; au clic, le champ revient en HÉRITAGE et suit la
9861
+ * valeur par défaut, même quand elle change (sans valeur par défaut, elle ouvre
9862
+ * le réglage du composant). Un champ vide affiche la valeur héritée. Les champs
9863
+ * « simples » la portent (texte, nombre, choix, case, liste, image, référence,
9864
+ * couleur...) ; un objet composé (lien) la porte sur ses sous-champs.
9865
+ */
9866
+ function createOverrideInput(config) {
8518
9867
  let { defaultsType } = config.componentPreview, namespace = config.blockNamespace;
8519
9868
  function OverrideInput(props) {
8520
9869
  let schema = useSchema(), path = props.path, keyed = firstKeyedIndex(path), anchor = keyed >= 0 ? keyed : 0, instance = useFormValue(path.slice(0, anchor + 1)), parent = useFormValue(path.length > 1 ? path.slice(0, -1) : path), resolved = resolveFieldPath(path, anchor, instance, namespace);
@@ -10249,11 +11598,12 @@ function ncfMainDocuments(options, extra = {}) {
10249
11598
  * pas le Studio de démarrer : l'onglet concerné affiche le détail à corriger.
10250
11599
  */
10251
11600
  /** Noms des outils dans la barre du Studio. Exportés pour filtrer `tools`. */
10252
- const NCF_PAGES_TOOL = "ncf-pages", NCF_COMPONENTS_TOOL = "ncf-components", NCF_HISTORY_TOOL = "ncf-history", NCF_DESIGN_SYSTEM_TOOL = "ncf-design-system", NCF_TOOL_NAMES = [
11601
+ const NCF_PAGES_TOOL = "ncf-pages", NCF_COMPONENTS_TOOL = "ncf-components", NCF_HISTORY_TOOL = "ncf-history", NCF_DESIGN_SYSTEM_TOOL = "ncf-design-system", NCF_ASSETS_TOOL = "ncf-assets", NCF_TOOL_NAMES = [
10253
11602
  NCF_PAGES_TOOL,
10254
11603
  NCF_COMPONENTS_TOOL,
10255
11604
  NCF_HISTORY_TOOL,
10256
- NCF_DESIGN_SYSTEM_TOOL
11605
+ NCF_DESIGN_SYSTEM_TOOL,
11606
+ NCF_ASSETS_TOOL
10257
11607
  ];
10258
11608
  /** Champs du formulaire : adresse sous le Slug d'une page, pastille sur les sections. */
10259
11609
  function createKitInput(config, issues) {
@@ -10332,6 +11682,21 @@ const ncfKit = definePlugin((options) => {
10332
11682
  Component: DesignSystemTool
10333
11683
  })
10334
11684
  }
11685
+ },
11686
+ {
11687
+ name: "assets",
11688
+ tool: {
11689
+ name: NCF_ASSETS_TOOL,
11690
+ title: "Assets",
11691
+ icon: ImagesIcon,
11692
+ component: createToolComponent({
11693
+ name: "assets",
11694
+ title: "Assets",
11695
+ config,
11696
+ issues,
11697
+ Component: AssetsTool
11698
+ })
11699
+ }
10335
11700
  }
10336
11701
  ].filter((d) => config.tools[d.name]).map((d) => d.tool),
10337
11702
  schema: {
@@ -10354,6 +11719,6 @@ function hasLanguageField(schemaType, field) {
10354
11719
  let fields = schemaType?.fields;
10355
11720
  return Array.isArray(fields) && fields.some((f) => f?.name === field);
10356
11721
  }
10357
- export { ANNOTATION_TYPE, ActorName, BOARD_LAYOUT_ID, BOARD_LAYOUT_TYPE, BRAIN_NODE_SIZE, BoardLayoutProvider, COLUMN_TYPE, CONTENT_SCAN_LIMIT, CONTENT_SCAN_LIMIT as OCCURRENCE_SCAN_LIMIT, CUSTOM_ENVIRONMENT_ID, CodeEditorInput, CodeEmbedInput, DATA_PREFIX, DEFAULT_BOARD_TAGS, DEFAULT_COMPONENT_DEFAULTS_TYPE, DEFAULT_COMPONENT_PREVIEW, DEFAULT_I18N, DEFAULT_INTERNAL_FIELDS, DEFAULT_MORE_TOOLS, DEFAULT_PAGE_BUILDER_FIELD, DEFAULT_SLUG_FIELD, DEFAULT_TITLE_FIELD, HelpTextStyle, KIT_API_VERSION, KIT_VERSION, NCF_COMPONENTS_TOOL, NCF_DESIGN_SYSTEM_TOOL, NCF_HIDDEN_TYPES, NCF_HISTORY_TOOL, NCF_MORE_TOOL, NCF_PAGES_TOOL, NCF_TOOL_NAMES, NODE_FIELD_TYPE, NODE_HEIGHT, NODE_WIDTH, NcfKitUpdate, NcfPreviewHeader, NcfPreviewLauncher, PERSPECTIVES, PROJECTION, SECTION_NODE_TYPE, STATUS_COLORS, STATUS_LABELS, SharePreview, UNSET_LABEL, addColumn, addColumnOption, announce, applySavedPositions, baseId, blockName, blockTypesFromSchema, buildContentsQuery, buildLinkGraph, buildPageRows, buildPagesQuery, codeEditorInput, collectLinks, collectOccurrences, colorForRow, colorFromString, columnId, compareVersions, componentDefaultsMainDocument, componentDefaultsMainDocuments, createPreviewLauncher, customEnvironment, defaultNodeSize, defaultsFieldName, defineCodeEmbedType, defineComponentDefaults, depth, deriveDocumentColumns, detectPageBuilderField, diffDocuments, diffWords, editIntentPath, explainGrantError, fallbackLayout, fetchDetail, fetchTimeline, fillTemplate, filterRows, fixCrossLanguageReferences, flatten, formatDocumentValue, groupPageRows, groupValue, hasBlockingIssue, humanizeBlockName, isDraftId, isKitType, isPrerelease, isSafeColumnKey, isSafeFieldPath, isTextChange, isVersionId, issuesForTool, keyForPath, kitSchemaTypes, layoutGraph, layoutSectionsMap, localesInRows, mergeVersions, missingPageTypes, moveColumn, ncfAllowedOrigins, ncfKit, ncfMainDocuments, ncfPresentationComponents, ncfPreviewComponents, normalizeInternalPath, normalizePath, occurrencesForTypes, pageThumbnailUrl, pageTypeFor, pageTypesFromSiteRoutes, pageTypesWithoutBuilder, parentPath, presentationPath, pruneSavedPositions, releaseId, removeColumn, renameColumn, requestPreviewGrant, requiredUnlessDefault, requiredUnlessDefaultFor, resolveColorBy, resolveConfig, resolvePageBuilderField, sectionNamesFromDefaults, segments, slugKey, sortRows, summarize, toKebabCase, toPath, toUrl, topLevelBlockCount, uniqueColumnId, upsertLayout, urlOn, useAnnotations, useBoardLayout, useDocumentColumns, useHistory, useInternalColumns, useKitClient, useKitConfig, useKitContext, useKitUpdate, useOccurrences, useOptionalKitConfig, useOptionalKitContext, usePageBuilder, usePageContents, usePages, usePreviewTarget, useRegistration, validateConfig, withAlpha, withMoreTool, withSameLanguageReferences };
11722
+ export { ANNOTATION_TYPE, ActorName, 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, groupPageRows, groupValue, hasBlockingIssue, humanizeBlockName, isDraftId, isImageAsset, isKitType, isPrerelease, isSafeColumnKey, isSafeFieldPath, isTextChange, isVersionId, issuesForTool, keyForPath, kitSchemaTypes, layoutGraph, layoutSectionsMap, localesInRows, mergeVersions, missingPageTypes, moveColumn, ncfAllowedOrigins, ncfKit, ncfMainDocuments, ncfPresentationComponents, ncfPreviewComponents, normalizeInternalPath, normalizePath, occurrencesForTypes, pageThumbnailUrl, pageTypeFor, pageTypesFromSiteRoutes, pageTypesWithoutBuilder, parentPath, presentationPath, pruneSavedPositions, releaseId, removeColumn, renameColumn, requestPreviewGrant, requiredUnlessDefault, requiredUnlessDefaultFor, resolveColorBy, resolveConfig, resolvePageBuilderField, sectionNamesFromDefaults, segments, slugKey, sortAssets, sortRows, summarize, thumbnailUrl, toKebabCase, toPath, toUrl, topLevelBlockCount, uniqueColumnId, upsertLayout, urlOn, useAnnotations, useAssetMeta, useAssets, useBoardLayout, useDocumentColumns, useHistory, useInternalColumns, useKitClient, useKitConfig, useKitContext, useKitUpdate, useOccurrences, useOptionalKitConfig, useOptionalKitContext, usePageBuilder, usePageContents, usePages, usePreviewTarget, useRegistration, validateConfig, withAlpha, withMoreTool, withSameLanguageReferences };
10358
11723
 
10359
11724
  //# sourceMappingURL=index.js.map