@nocode-factory/sanity-kit 2.8.3 → 2.9.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.
@@ -0,0 +1,2 @@
1
+ import { a as requiredUnlessDefault, i as defineComponentDefaults, n as componentDefaultsMainDocument, o as requiredUnlessDefaultFor, r as defaultsFieldName, t as DEFAULT_COMPONENT_DEFAULTS_TYPE } from "./componentDefaults-CbOXLaYE.js";
2
+ export { DEFAULT_COMPONENT_DEFAULTS_TYPE, componentDefaultsMainDocument, defaultsFieldName, defineComponentDefaults, requiredUnlessDefault, requiredUnlessDefaultFor };
package/dist/schema.js ADDED
@@ -0,0 +1,2 @@
1
+ import { a as requiredUnlessDefault, i as defineComponentDefaults, n as componentDefaultsMainDocument, o as requiredUnlessDefaultFor, r as defaultsFieldName, t as DEFAULT_COMPONENT_DEFAULTS_TYPE } from "./componentDefaults-YFpAqFb4.js";
2
+ export { DEFAULT_COMPONENT_DEFAULTS_TYPE, componentDefaultsMainDocument, defaultsFieldName, defineComponentDefaults, requiredUnlessDefault, requiredUnlessDefaultFor };
@@ -0,0 +1,56 @@
1
+ /** Valeurs par défaut, par type de section (`section.cta` -> objet). */
2
+ export type ComponentDefaults = Record<string, Record<string, unknown> | null | undefined>;
3
+ /** Appelé sur chaque valeur héritée (chemin depuis l'instance). */
4
+ export type OnInherit = (value: unknown, path: string[]) => unknown;
5
+ /** Complète les champs vides de `instance` avec `defaults`, récursivement. */
6
+ export declare function inherit<T>(instance: T, defaults: unknown, onInherit?: OnInherit, prefix?: string[]): T;
7
+ /** Section avec les valeurs par défaut de son composant appliquées. */
8
+ export declare function applyDefaults<S extends {
9
+ _type: string;
10
+ }>(section: S, defaults: ComponentDefaults | null | undefined, onInherit?: OnInherit): S;
11
+ /**
12
+ * Requête GROQ des valeurs par défaut (paramètre `$locale`), une clé par type de
13
+ * section, avec la projection des sections du projet (liens, images, références
14
+ * résolus comme dans une page).
15
+ */
16
+ export declare function componentDefaultsQuery(sectionTypes: readonly string[], sectionProjection: string, options?: {
17
+ type?: string;
18
+ namespace?: string;
19
+ languageField?: string;
20
+ }): string;
21
+ /**
22
+ * Valeurs JAMAIS encodées par le stega : champs d'options et valeurs
23
+ * « identifiant ». Encodée, une valeur d'option (« md », « secondary »,
24
+ * « eclat ») n'est plus reconnue en preview et le site retombe sur la valeur par
25
+ * défaut : une taille de bouton, un fond ou une texture modifiés ne s'affichent pas.
26
+ */
27
+ export declare const STEGA_OPTION_RULES: {
28
+ readonly fields: readonly ["style", "size", "variant", "kind", "layout", "align", "tone", "theme", "format", "texture", "token", "customHex", "background", "color", "type", "fixedPath", "href", "email", "phone", "language", "slug", "current", "search"];
29
+ readonly identifier: "^[a-z][a-z0-9-]{0,31}$";
30
+ };
31
+ export declare function isOptionValue(path: readonly unknown[], value: string): boolean;
32
+ /** Filtre stega du client Sanity : `stega: {studioUrl, filter: stegaFilter}`. */
33
+ export declare function stegaFilter<P extends {
34
+ sourcePath: readonly unknown[];
35
+ value: string;
36
+ filterDefault: (props: P) => boolean;
37
+ }>(props: P): boolean;
38
+ /**
39
+ * Où vit une instance : document (id, type) et chemin du champ qui la contient
40
+ * (une liste de sections, ou `single` : un champ qui EST la section).
41
+ */
42
+ export type SectionSource = {
43
+ id: string;
44
+ type: string;
45
+ path: string;
46
+ single?: boolean;
47
+ };
48
+ /**
49
+ * PREVIEW : une valeur héritée porte l'adresse du document des valeurs par
50
+ * défaut ; un clic dans Presentation ouvrirait ce document. Ce rappel (à passer
51
+ * à `applyDefaults` en mode brouillon) réétiquette chaque texte hérité vers le
52
+ * champ de l'INSTANCE dans la page, au format de Sanity : le clic ouvre
53
+ * l'instance, qui affiche la valeur héritée et permet de la surcharger.
54
+ */
55
+ export declare function reattributeTo(source: SectionSource, key?: string): OnInherit;
56
+ //# sourceMappingURL=web-defaults.d.ts.map
@@ -0,0 +1,140 @@
1
+ import { createEditUrl } from "@sanity/client/csm";
2
+ import { vercelStegaClean, vercelStegaCombine, vercelStegaDecode } from "@vercel/stega";
3
+ /**
4
+ * VALEURS PAR DÉFAUT DES COMPOSANTS, côté site. Module neutre (ni `'use client'`
5
+ * ni API serveur) : utilisable dans un composant serveur, un composant client et
6
+ * la configuration du client Sanity.
7
+ *
8
+ * ```ts
9
+ * import {applyDefaults, stegaFilter, reattributeTo} from '@nocode-factory/sanity-kit/web/defaults'
10
+ * ```
11
+ *
12
+ * Règle d'héritage : un champ VIDE d'une instance de section prend la valeur par
13
+ * défaut du composant (document Studio créé par `defineComponentDefaults`) ; un
14
+ * champ REMPLI est un override, jamais écrasé. La cible d'un lien (type +
15
+ * page/adresse/email...) forme un tout.
16
+ */
17
+ const isEmpty = (v) => v == null || v === "" || Array.isArray(v) && v.length === 0, isPlainObject = (v) => !!v && typeof v == "object" && !Array.isArray(v), LINK_TYPES = /* @__PURE__ */ new Set(["link", "cardLink"]), LINK_TARGET = [
18
+ "type",
19
+ "page",
20
+ "fixedPath",
21
+ "href",
22
+ "email",
23
+ "phone",
24
+ "file"
25
+ ], hasTarget = (l) => [
26
+ "page",
27
+ "fixedPath",
28
+ "href",
29
+ "email",
30
+ "phone"
31
+ ].some((k) => !isEmpty(l[k])) || !!l.file?.asset;
32
+ /** Complète les champs vides de `instance` avec `defaults`, récursivement. */
33
+ function inherit(instance, defaults, onInherit, prefix = []) {
34
+ if (!isPlainObject(defaults)) return instance;
35
+ if (!isPlainObject(instance)) return isEmpty(instance) ? onInherit ? onInherit(defaults, prefix) : defaults : instance;
36
+ let out = { ...instance };
37
+ for (let [key, value] of Object.entries(defaults)) {
38
+ if (key.startsWith("_")) continue;
39
+ let own = out[key];
40
+ isEmpty(own) ? out[key] = onInherit ? onInherit(value, [...prefix, key]) : value : isPlainObject(own) && isPlainObject(value) && !own._ref && (out[key] = inherit(own, value, onInherit, [...prefix, key]));
41
+ }
42
+ if ((LINK_TYPES.has(String(out._type ?? "")) || LINK_TYPES.has(String(defaults._type ?? ""))) && !hasTarget(instance) && hasTarget(defaults)) for (let key of LINK_TARGET) key in defaults && (out[key] = onInherit ? onInherit(defaults[key], [...prefix, key]) : defaults[key]);
43
+ return out;
44
+ }
45
+ /** Section avec les valeurs par défaut de son composant appliquées. */
46
+ function applyDefaults(section, defaults, onInherit) {
47
+ return inherit(section, defaults?.[section._type], onInherit);
48
+ }
49
+ /**
50
+ * Requête GROQ des valeurs par défaut (paramètre `$locale`), une clé par type de
51
+ * section, avec la projection des sections du projet (liens, images, références
52
+ * résolus comme dans une page).
53
+ */
54
+ function componentDefaultsQuery(sectionTypes, sectionProjection, options = {}) {
55
+ let { type = "componentDefaults", namespace = "section.", languageField = "language" } = options;
56
+ return `*[_type == "${type}" && ${languageField} == $locale][0]{${sectionTypes.filter((t) => t.startsWith(namespace) && /^\w+$/.test(t.slice(namespace.length))).map((t) => `"${t}": ${t.slice(namespace.length)}{${sectionProjection}}`).join(",\n")}}`;
57
+ }
58
+ /**
59
+ * Valeurs JAMAIS encodées par le stega : champs d'options et valeurs
60
+ * « identifiant ». Encodée, une valeur d'option (« md », « secondary »,
61
+ * « eclat ») n'est plus reconnue en preview et le site retombe sur la valeur par
62
+ * défaut : une taille de bouton, un fond ou une texture modifiés ne s'affichent pas.
63
+ */
64
+ const STEGA_OPTION_RULES = {
65
+ fields: [
66
+ "style",
67
+ "size",
68
+ "variant",
69
+ "kind",
70
+ "layout",
71
+ "align",
72
+ "tone",
73
+ "theme",
74
+ "format",
75
+ "texture",
76
+ "token",
77
+ "customHex",
78
+ "background",
79
+ "color",
80
+ "type",
81
+ "fixedPath",
82
+ "href",
83
+ "email",
84
+ "phone",
85
+ "language",
86
+ "slug",
87
+ "current",
88
+ "search"
89
+ ],
90
+ identifier: "^[a-z][a-z0-9-]{0,31}$"
91
+ }, OPTION_FIELDS = new Set(STEGA_OPTION_RULES.fields), IDENTIFIER = new RegExp(STEGA_OPTION_RULES.identifier);
92
+ function isOptionValue(path, value) {
93
+ let field = [...path].reverse().find((p) => typeof p == "string");
94
+ return field !== void 0 && OPTION_FIELDS.has(field) || IDENTIFIER.test(value);
95
+ }
96
+ /** Filtre stega du client Sanity : `stega: {studioUrl, filter: stegaFilter}`. */
97
+ function stegaFilter(props) {
98
+ return !isOptionValue(props.sourcePath, props.value) && props.filterDefault(props);
99
+ }
100
+ const decode = (s) => {
101
+ try {
102
+ return vercelStegaDecode(s);
103
+ } catch {
104
+ return;
105
+ }
106
+ };
107
+ /**
108
+ * PREVIEW : une valeur héritée porte l'adresse du document des valeurs par
109
+ * défaut ; un clic dans Presentation ouvrirait ce document. Ce rappel (à passer
110
+ * à `applyDefaults` en mode brouillon) réétiquette chaque texte hérité vers le
111
+ * champ de l'INSTANCE dans la page, au format de Sanity : le clic ouvre
112
+ * l'instance, qui affiche la valeur héritée et permet de la surcharger.
113
+ */
114
+ function reattributeTo(source, key) {
115
+ let base = key && !source.single ? `${source.path}[_key=="${key}"]` : source.path, retag = (value, field) => {
116
+ if (typeof value == "string") {
117
+ let info = decode(value);
118
+ if (!info?.href) return value;
119
+ let url = new URL(info.href, "https://studio.invalid"), baseUrl = url.searchParams.get("baseUrl");
120
+ if (!baseUrl) return value;
121
+ let href = createEditUrl({
122
+ baseUrl,
123
+ workspace: url.searchParams.get("workspace") ?? void 0,
124
+ tool: url.searchParams.get("tool") ?? void 0,
125
+ id: `drafts.${source.id.replace(/^drafts\./, "")}`,
126
+ type: source.type,
127
+ path: `${base}.${field}`
128
+ });
129
+ return vercelStegaCombine(vercelStegaClean(value), {
130
+ origin: info.origin ?? "sanity.io",
131
+ href
132
+ });
133
+ }
134
+ return Array.isArray(value) ? value.map((v) => retag(v, field)) : value && typeof value == "object" ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, retag(v, field)])) : value;
135
+ };
136
+ return (value, path) => retag(value, path[0] ?? "");
137
+ }
138
+ export { STEGA_OPTION_RULES, applyDefaults, componentDefaultsQuery, inherit, isOptionValue, reattributeTo, stegaFilter };
139
+
140
+ //# sourceMappingURL=web-defaults.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-defaults.js","names":[],"sources":["../src/web/defaults.ts"],"sourcesContent":["/**\n * VALEURS PAR DÉFAUT DES COMPOSANTS, côté site. Module neutre (ni `'use client'`\n * ni API serveur) : utilisable dans un composant serveur, un composant client et\n * la configuration du client Sanity.\n *\n * ```ts\n * import {applyDefaults, stegaFilter, reattributeTo} from '@nocode-factory/sanity-kit/web/defaults'\n * ```\n *\n * Règle d'héritage : un champ VIDE d'une instance de section prend la valeur par\n * défaut du composant (document Studio créé par `defineComponentDefaults`) ; un\n * champ REMPLI est un override, jamais écrasé. La cible d'un lien (type +\n * page/adresse/email...) forme un tout.\n */\nimport {createEditUrl} from '@sanity/client/csm'\nimport {vercelStegaClean, vercelStegaCombine, vercelStegaDecode} from '@vercel/stega'\n\n/** Valeurs par défaut, par type de section (`section.cta` -> objet). */\nexport type ComponentDefaults = Record<string, Record<string, unknown> | null | undefined>\n/** Appelé sur chaque valeur héritée (chemin depuis l'instance). */\nexport type OnInherit = (value: unknown, path: string[]) => unknown\n\ntype Obj = Record<string, unknown>\nconst isEmpty = (v: unknown) => v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0)\nconst isPlainObject = (v: unknown): v is Obj => !!v && typeof v === 'object' && !Array.isArray(v)\n\nconst LINK_TYPES = new Set(['link', 'cardLink'])\nconst LINK_TARGET = ['type', 'page', 'fixedPath', 'href', 'email', 'phone', 'file']\nconst hasTarget = (l: Obj) =>\n ['page', 'fixedPath', 'href', 'email', 'phone'].some((k) => !isEmpty(l[k])) || !!(l.file as Obj | undefined)?.asset\n\n/** Complète les champs vides de `instance` avec `defaults`, récursivement. */\nexport function inherit<T>(instance: T, defaults: unknown, onInherit?: OnInherit, prefix: string[] = []): T {\n if (!isPlainObject(defaults)) return instance\n if (!isPlainObject(instance)) return (isEmpty(instance) ? (onInherit ? onInherit(defaults, prefix) : defaults) : instance) as T\n const out: Obj = {...instance}\n for (const [key, value] of Object.entries(defaults)) {\n if (key.startsWith('_')) continue\n const own = out[key]\n if (isEmpty(own)) out[key] = onInherit ? onInherit(value, [...prefix, key]) : value\n else if (isPlainObject(own) && isPlainObject(value) && !own._ref) out[key] = inherit(own, value, onInherit, [...prefix, key])\n }\n const isLink = LINK_TYPES.has(String(out._type ?? '')) || LINK_TYPES.has(String(defaults._type ?? ''))\n if (isLink && !hasTarget(instance as Obj) && hasTarget(defaults)) {\n for (const key of LINK_TARGET) if (key in defaults) out[key] = onInherit ? onInherit(defaults[key], [...prefix, key]) : defaults[key]\n }\n return out as T\n}\n\n/** Section avec les valeurs par défaut de son composant appliquées. */\nexport function applyDefaults<S extends {_type: string}>(section: S, defaults: ComponentDefaults | null | undefined, onInherit?: OnInherit): S {\n return inherit(section, defaults?.[section._type], onInherit)\n}\n\n/**\n * Requête GROQ des valeurs par défaut (paramètre `$locale`), une clé par type de\n * section, avec la projection des sections du projet (liens, images, références\n * résolus comme dans une page).\n */\nexport function componentDefaultsQuery(sectionTypes: readonly string[], sectionProjection: string, options: {type?: string; namespace?: string; languageField?: string} = {}): string {\n const {type = 'componentDefaults', namespace = 'section.', languageField = 'language'} = options\n const fields = sectionTypes\n .filter((t) => t.startsWith(namespace) && /^\\w+$/.test(t.slice(namespace.length)))\n .map((t) => `\"${t}\": ${t.slice(namespace.length)}{${sectionProjection}}`)\n .join(',\\n')\n return `*[_type == \"${type}\" && ${languageField} == $locale][0]{${fields}}`\n}\n\n/* --- Preview (édition visuelle) --- */\n\n/**\n * Valeurs JAMAIS encodées par le stega : champs d'options et valeurs\n * « identifiant ». Encodée, une valeur d'option (« md », « secondary »,\n * « eclat ») n'est plus reconnue en preview et le site retombe sur la valeur par\n * défaut : une taille de bouton, un fond ou une texture modifiés ne s'affichent pas.\n */\nexport const STEGA_OPTION_RULES = {\n fields: ['style', 'size', 'variant', 'kind', 'layout', 'align', 'tone', 'theme', 'format', 'texture', 'token', 'customHex', 'background', 'color', 'type', 'fixedPath', 'href', 'email', 'phone', 'language', 'slug', 'current', 'search'],\n identifier: '^[a-z][a-z0-9-]{0,31}$',\n} as const\n\nconst OPTION_FIELDS: ReadonlySet<string> = new Set(STEGA_OPTION_RULES.fields)\nconst IDENTIFIER = new RegExp(STEGA_OPTION_RULES.identifier)\n\nexport function isOptionValue(path: readonly unknown[], value: string): boolean {\n const field = [...path].reverse().find((p): p is string => typeof p === 'string')\n return (field !== undefined && OPTION_FIELDS.has(field)) || IDENTIFIER.test(value)\n}\n\n/** Filtre stega du client Sanity : `stega: {studioUrl, filter: stegaFilter}`. */\nexport function stegaFilter<P extends {sourcePath: readonly unknown[]; value: string; filterDefault: (props: P) => boolean}>(props: P): boolean {\n return isOptionValue(props.sourcePath, props.value) ? false : props.filterDefault(props)\n}\n\n/**\n * Où vit une instance : document (id, type) et chemin du champ qui la contient\n * (une liste de sections, ou `single` : un champ qui EST la section).\n */\nexport type SectionSource = {id: string; type: string; path: string; single?: boolean}\n\nconst decode = (s: string): {origin?: string; href?: string} | undefined => {\n try {\n return vercelStegaDecode(s) as {origin?: string; href?: string} | undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * PREVIEW : une valeur héritée porte l'adresse du document des valeurs par\n * défaut ; un clic dans Presentation ouvrirait ce document. Ce rappel (à passer\n * à `applyDefaults` en mode brouillon) réétiquette chaque texte hérité vers le\n * champ de l'INSTANCE dans la page, au format de Sanity : le clic ouvre\n * l'instance, qui affiche la valeur héritée et permet de la surcharger.\n */\nexport function reattributeTo(source: SectionSource, key?: string): OnInherit {\n const base = key && !source.single ? `${source.path}[_key==\"${key}\"]` : source.path\n const retag = (value: unknown, field: string): unknown => {\n if (typeof value === 'string') {\n const info = decode(value)\n if (!info?.href) return value // valeur d'option, jamais encodée\n const url = new URL(info.href, 'https://studio.invalid')\n const baseUrl = url.searchParams.get('baseUrl')\n if (!baseUrl) return value\n const href = createEditUrl({\n baseUrl,\n workspace: url.searchParams.get('workspace') ?? undefined,\n tool: url.searchParams.get('tool') ?? undefined,\n // Identifiant de brouillon : pas de perspective imposée, Presentation garde la sienne.\n id: `drafts.${source.id.replace(/^drafts\\./, '')}`,\n type: source.type,\n path: `${base}.${field}`,\n })\n return vercelStegaCombine(vercelStegaClean(value), {origin: info.origin ?? 'sanity.io', href})\n }\n if (Array.isArray(value)) return value.map((v) => retag(v, field))\n if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, retag(v, field)]))\n return value\n }\n // Le clic ouvre le champ de premier niveau de l'instance (celui qui hérite).\n return (value, path) => retag(value, path[0] ?? '')\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,MAAM,WAAW,MAAe,KAAyB,QAAQ,MAAM,MAAO,MAAM,QAAQ,CAAC,KAAK,EAAE,WAAW,GACzG,iBAAiB,MAAyB,CAAC,CAAC,KAAK,OAAO,KAAM,YAAY,CAAC,MAAM,QAAQ,CAAC,GAE1F,6BAAa,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC,GACzC,cAAc;CAAC;CAAQ;CAAQ;CAAa;CAAQ;CAAS;CAAS;AAAM,GAC5E,aAAa,MACjB;CAAC;CAAQ;CAAa;CAAQ;CAAS;AAAO,CAAC,CAAC,MAAM,MAAM,CAAC,QAAQ,EAAE,EAAE,CAAC,KAAK,CAAC,CAAE,EAAE,MAA0B;;AAGhH,SAAgB,QAAW,UAAa,UAAmB,WAAuB,SAAmB,CAAC,GAAM;CAC1G,IAAI,CAAC,cAAc,QAAQ,GAAG,OAAO;CACrC,IAAI,CAAC,cAAc,QAAQ,GAAG,OAAQ,QAAQ,QAAQ,IAAK,YAAY,UAAU,UAAU,MAAM,IAAI,WAAY;CACjH,IAAM,MAAW,EAAC,GAAG,SAAQ;CAC7B,KAAK,IAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAAG;EACnD,IAAI,IAAI,WAAW,GAAG,GAAG;EACzB,IAAM,MAAM,IAAI;EAChB,AAAI,QAAQ,GAAG,IAAG,IAAI,OAAO,YAAY,UAAU,OAAO,CAAC,GAAG,QAAQ,GAAG,CAAC,IAAI,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CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,GAAG,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,IACtH;CACT;CAEA,QAAQ,OAAO,SAAS,MAAM,OAAO,KAAK,MAAM,EAAE;AACpD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocode-factory/sanity-kit",
3
- "version": "2.8.3",
3
+ "version": "2.9.0",
4
4
  "description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -11,6 +11,10 @@
11
11
  "source": "./src/index.ts",
12
12
  "default": "./dist/index.js"
13
13
  },
14
+ "./schema": {
15
+ "source": "./src/schema/index.ts",
16
+ "default": "./dist/schema.js"
17
+ },
14
18
  "./web": {
15
19
  "source": "./src/web/index.ts",
16
20
  "default": "./dist/web.js"
@@ -19,6 +23,10 @@
19
23
  "source": "./src/web/server.ts",
20
24
  "default": "./dist/web-server.js"
21
25
  },
26
+ "./web/defaults": {
27
+ "source": "./src/web/defaults.ts",
28
+ "default": "./dist/web-defaults.js"
29
+ },
22
30
  "./package.json": "./package.json"
23
31
  },
24
32
  "main": "./dist/index.js",
@@ -42,8 +50,10 @@
42
50
  "test:watch": "vitest"
43
51
  },
44
52
  "dependencies": {
53
+ "@sanity/client": "^7.27.0",
45
54
  "@sanity/icons": "^5.2.2",
46
55
  "@sanity/ui": "^4.2.0",
56
+ "@vercel/stega": "^1.1.0",
47
57
  "@xyflow/react": "12.11.6",
48
58
  "elkjs": "0.12.0"
49
59
  },
@@ -71,7 +81,9 @@
71
81
  ".": "./dist/index.js",
72
82
  "./package.json": "./package.json",
73
83
  "./web": "./dist/web.js",
74
- "./web/server": "./dist/web-server.js"
84
+ "./web/server": "./dist/web-server.js",
85
+ "./web/defaults": "./dist/web-defaults.js",
86
+ "./schema": "./dist/schema.js"
75
87
  }
76
88
  },
77
89
  "repository": {
package/src/index.ts CHANGED
@@ -124,6 +124,16 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
124
124
 
125
125
  /* --- API publique --- */
126
126
 
127
+ // Valeurs par défaut des composants (Studio). Côté site : '@nocode-factory/sanity-kit/web/defaults'.
128
+ export {
129
+ defineComponentDefaults,
130
+ requiredUnlessDefault,
131
+ requiredUnlessDefaultFor,
132
+ defaultsFieldName,
133
+ componentDefaultsMainDocument,
134
+ DEFAULT_COMPONENT_DEFAULTS_TYPE,
135
+ } from './schema/componentDefaults'
136
+
127
137
  export {resolveConfig} from './config/resolve'
128
138
  export {validateConfig, issuesForTool, hasBlockingIssue} from './config/validate'
129
139
  export {normalizePath} from './config/resolve'
@@ -0,0 +1,106 @@
1
+ import {defineField, defineType, type Rule} from 'sanity'
2
+
3
+ /**
4
+ * VALEURS PAR DÉFAUT DES COMPOSANTS, côté Studio.
5
+ *
6
+ * Un document (un par langue) avec un bloc par composant de la bibliothèque,
7
+ * GÉNÉRÉ depuis les schémas des sections : une section ajoutée y apparaît sans
8
+ * rien faire. Une instance dont un champ est vide affiche la valeur par défaut ;
9
+ * un champ rempli (override) n'est jamais écrasé. Côté site :
10
+ * `@nocode-factory/sanity-kit/web/defaults`. Dans le Studio, l'onglet Composants
11
+ * ouvre chaque composant (rendu réel + réglages), et une pastille bleue marque
12
+ * chaque champ d'instance qui diffère de la valeur par défaut.
13
+ *
14
+ * Deux règles pour les champs de section, qui en découlent :
15
+ * - jamais d'`initialValue` (ce serait un override involontaire) ;
16
+ * - « obligatoire » = `requiredUnlessDefault`.
17
+ */
18
+
19
+ type FieldDef = {name: string; type: string; validation?: unknown; initialValue?: unknown; fields?: FieldDef[]; of?: FieldDef[]; [k: string]: unknown}
20
+ type SectionDef = {name: string; title?: string; fields: FieldDef[]}
21
+
22
+ export const DEFAULT_COMPONENT_DEFAULTS_TYPE = 'componentDefaults'
23
+
24
+ /** Nom du champ d'un composant dans le document des valeurs par défaut : `section.cta` -> `cta`. */
25
+ export function defaultsFieldName(type: string, namespace = 'section.'): string {
26
+ return type.startsWith(namespace) ? type.slice(namespace.length) : type
27
+ }
28
+
29
+ // Dans les valeurs par défaut, rien n'est obligatoire et rien n'est prérempli.
30
+ const relax = (f: FieldDef): FieldDef => {
31
+ const {validation: _v, initialValue: _i, ...rest} = f
32
+ return {
33
+ ...rest,
34
+ ...(rest.fields ? {fields: rest.fields.map(relax)} : {}),
35
+ ...(rest.of ? {of: rest.of.map(relax)} : {}),
36
+ }
37
+ }
38
+
39
+ /** Document « Composants : valeurs par défaut », généré depuis les sections. */
40
+ export function defineComponentDefaults(options: {sections: readonly unknown[]; name?: string; title?: string; namespace?: string}) {
41
+ const {name = DEFAULT_COMPONENT_DEFAULTS_TYPE, title = '🧩 Composants : valeurs par défaut', namespace = 'section.'} = options
42
+ return defineType({
43
+ name,
44
+ title,
45
+ type: 'document',
46
+ description:
47
+ 'Valeurs appliquées à chaque instance d\'un composant dont le champ est vide. Un champ rempli dans une instance reste prioritaire (override).',
48
+ fields: (options.sections as SectionDef[]).map((t) =>
49
+ defineField({
50
+ name: defaultsFieldName(t.name, namespace),
51
+ title: t.title || t.name,
52
+ type: 'object',
53
+ description: 'Valeurs par défaut de ce composant. Vide = valeur du design system.',
54
+ options: {collapsible: true, collapsed: true},
55
+ fields: t.fields.map(relax) as never,
56
+ }),
57
+ ),
58
+ preview: {prepare: () => ({title: title.replace(/^\S+\s/, '')})},
59
+ })
60
+ }
61
+
62
+ const isEmpty = (v: unknown) => v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0)
63
+
64
+ /**
65
+ * Règle « obligatoire SAUF si le composant a une valeur par défaut » pour un autre
66
+ * type de document des valeurs par défaut ou un autre espace de noms.
67
+ * `validation: requiredUnlessDefaultFor({type: 'mesDefauts'})`
68
+ */
69
+ export function requiredUnlessDefaultFor(options: {type?: string; namespace?: string} = {}) {
70
+ const {type: defaultsType = DEFAULT_COMPONENT_DEFAULTS_TYPE, namespace = 'section.'} = options
71
+ return <R>(rule: R): R =>
72
+ (rule as unknown as Rule).custom(async (value, context) => {
73
+ if (!isEmpty(value)) return true
74
+ const type = (context.parent as {_type?: string} | undefined)?._type
75
+ const field = context.path?.[context.path.length - 1]
76
+ const name = type ? defaultsFieldName(type, namespace) : ''
77
+ if (!type?.startsWith(namespace) || typeof field !== 'string' || !/^\w+$/.test(name) || !/^\w+$/.test(field)) return 'Obligatoire.'
78
+ const language = (context.document as {language?: string} | undefined)?.language ?? null
79
+ const inherited = await context
80
+ .getClient({apiVersion: '2024-10-01'})
81
+ .fetch(
82
+ `*[_type == $defaultsType && !(_id in path("drafts.**")) && ($language == null || language == $language)][0].${name}.${field}`,
83
+ {defaultsType, language},
84
+ )
85
+ return isEmpty(inherited) ? 'Obligatoire (ou à définir dans Composants > valeurs par défaut).' : true
86
+ }) as unknown as R
87
+ }
88
+
89
+ /**
90
+ * Champ de section obligatoire, SAUF si le composant a une valeur par défaut
91
+ * pour ce champ (elle s'affichera). Tout type de champ.
92
+ * `validation: requiredUnlessDefault`
93
+ */
94
+ export const requiredUnlessDefault: <R>(rule: R) => R = requiredUnlessDefaultFor()
95
+
96
+ /**
97
+ * Presentation : la page qui rend un composant seul (par défaut
98
+ * `/design-system/composant`) a pour document principal les valeurs par défaut.
99
+ * Rendu réel et réglages côte à côte, en direct.
100
+ * `presentationTool({resolve: {mainDocuments: defineDocuments([componentDefaultsMainDocument({language: 'fr'})])}})`
101
+ */
102
+ export function componentDefaultsMainDocument(options: {language?: string; route?: string; type?: string} = {}): {route: string; filter: string} {
103
+ const {language, route = '/design-system/composant', type = DEFAULT_COMPONENT_DEFAULTS_TYPE} = options
104
+ const safeLang = language && /^[a-z]{2}(-[A-Za-z]{2})?$/.test(language) ? language : null
105
+ return {route, filter: `_type == "${type}"${safeLang ? ` && language == "${safeLang}"` : ''}`}
106
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Point d'entrée **schéma** : outils de schéma sans interface (aucun composant,
3
+ * aucune feuille de style). À importer dans les fichiers de schéma et les
4
+ * scripts (`sanity exec`) :
5
+ *
6
+ * ```ts
7
+ * import {requiredUnlessDefault, defineComponentDefaults} from '@nocode-factory/sanity-kit/schema'
8
+ * ```
9
+ */
10
+ export {
11
+ defineComponentDefaults,
12
+ requiredUnlessDefault,
13
+ requiredUnlessDefaultFor,
14
+ defaultsFieldName,
15
+ componentDefaultsMainDocument,
16
+ DEFAULT_COMPONENT_DEFAULTS_TYPE,
17
+ } from './componentDefaults'
package/src/version.ts CHANGED
@@ -2,4 +2,4 @@
2
2
  * Version du kit, rapportée au service pour savoir quels projets tournent sur
3
3
  * quelle version. Tenue à jour avec `package.json`.
4
4
  */
5
- export const KIT_VERSION = '2.8.3'
5
+ export const KIT_VERSION = '2.9.0'
@@ -0,0 +1,142 @@
1
+ /**
2
+ * VALEURS PAR DÉFAUT DES COMPOSANTS, côté site. Module neutre (ni `'use client'`
3
+ * ni API serveur) : utilisable dans un composant serveur, un composant client et
4
+ * la configuration du client Sanity.
5
+ *
6
+ * ```ts
7
+ * import {applyDefaults, stegaFilter, reattributeTo} from '@nocode-factory/sanity-kit/web/defaults'
8
+ * ```
9
+ *
10
+ * Règle d'héritage : un champ VIDE d'une instance de section prend la valeur par
11
+ * défaut du composant (document Studio créé par `defineComponentDefaults`) ; un
12
+ * champ REMPLI est un override, jamais écrasé. La cible d'un lien (type +
13
+ * page/adresse/email...) forme un tout.
14
+ */
15
+ import {createEditUrl} from '@sanity/client/csm'
16
+ import {vercelStegaClean, vercelStegaCombine, vercelStegaDecode} from '@vercel/stega'
17
+
18
+ /** Valeurs par défaut, par type de section (`section.cta` -> objet). */
19
+ export type ComponentDefaults = Record<string, Record<string, unknown> | null | undefined>
20
+ /** Appelé sur chaque valeur héritée (chemin depuis l'instance). */
21
+ export type OnInherit = (value: unknown, path: string[]) => unknown
22
+
23
+ type Obj = Record<string, unknown>
24
+ const isEmpty = (v: unknown) => v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0)
25
+ const isPlainObject = (v: unknown): v is Obj => !!v && typeof v === 'object' && !Array.isArray(v)
26
+
27
+ const LINK_TYPES = new Set(['link', 'cardLink'])
28
+ const LINK_TARGET = ['type', 'page', 'fixedPath', 'href', 'email', 'phone', 'file']
29
+ const hasTarget = (l: Obj) =>
30
+ ['page', 'fixedPath', 'href', 'email', 'phone'].some((k) => !isEmpty(l[k])) || !!(l.file as Obj | undefined)?.asset
31
+
32
+ /** Complète les champs vides de `instance` avec `defaults`, récursivement. */
33
+ export function inherit<T>(instance: T, defaults: unknown, onInherit?: OnInherit, prefix: string[] = []): T {
34
+ if (!isPlainObject(defaults)) return instance
35
+ if (!isPlainObject(instance)) return (isEmpty(instance) ? (onInherit ? onInherit(defaults, prefix) : defaults) : instance) as T
36
+ const out: Obj = {...instance}
37
+ for (const [key, value] of Object.entries(defaults)) {
38
+ if (key.startsWith('_')) continue
39
+ const own = out[key]
40
+ if (isEmpty(own)) out[key] = onInherit ? onInherit(value, [...prefix, key]) : value
41
+ else if (isPlainObject(own) && isPlainObject(value) && !own._ref) out[key] = inherit(own, value, onInherit, [...prefix, key])
42
+ }
43
+ const isLink = LINK_TYPES.has(String(out._type ?? '')) || LINK_TYPES.has(String(defaults._type ?? ''))
44
+ if (isLink && !hasTarget(instance as Obj) && hasTarget(defaults)) {
45
+ for (const key of LINK_TARGET) if (key in defaults) out[key] = onInherit ? onInherit(defaults[key], [...prefix, key]) : defaults[key]
46
+ }
47
+ return out as T
48
+ }
49
+
50
+ /** Section avec les valeurs par défaut de son composant appliquées. */
51
+ export function applyDefaults<S extends {_type: string}>(section: S, defaults: ComponentDefaults | null | undefined, onInherit?: OnInherit): S {
52
+ return inherit(section, defaults?.[section._type], onInherit)
53
+ }
54
+
55
+ /**
56
+ * Requête GROQ des valeurs par défaut (paramètre `$locale`), une clé par type de
57
+ * section, avec la projection des sections du projet (liens, images, références
58
+ * résolus comme dans une page).
59
+ */
60
+ export function componentDefaultsQuery(sectionTypes: readonly string[], sectionProjection: string, options: {type?: string; namespace?: string; languageField?: string} = {}): string {
61
+ const {type = 'componentDefaults', namespace = 'section.', languageField = 'language'} = options
62
+ const fields = sectionTypes
63
+ .filter((t) => t.startsWith(namespace) && /^\w+$/.test(t.slice(namespace.length)))
64
+ .map((t) => `"${t}": ${t.slice(namespace.length)}{${sectionProjection}}`)
65
+ .join(',\n')
66
+ return `*[_type == "${type}" && ${languageField} == $locale][0]{${fields}}`
67
+ }
68
+
69
+ /* --- Preview (édition visuelle) --- */
70
+
71
+ /**
72
+ * Valeurs JAMAIS encodées par le stega : champs d'options et valeurs
73
+ * « identifiant ». Encodée, une valeur d'option (« md », « secondary »,
74
+ * « eclat ») n'est plus reconnue en preview et le site retombe sur la valeur par
75
+ * défaut : une taille de bouton, un fond ou une texture modifiés ne s'affichent pas.
76
+ */
77
+ export const STEGA_OPTION_RULES = {
78
+ fields: ['style', 'size', 'variant', 'kind', 'layout', 'align', 'tone', 'theme', 'format', 'texture', 'token', 'customHex', 'background', 'color', 'type', 'fixedPath', 'href', 'email', 'phone', 'language', 'slug', 'current', 'search'],
79
+ identifier: '^[a-z][a-z0-9-]{0,31}$',
80
+ } as const
81
+
82
+ const OPTION_FIELDS: ReadonlySet<string> = new Set(STEGA_OPTION_RULES.fields)
83
+ const IDENTIFIER = new RegExp(STEGA_OPTION_RULES.identifier)
84
+
85
+ export function isOptionValue(path: readonly unknown[], value: string): boolean {
86
+ const field = [...path].reverse().find((p): p is string => typeof p === 'string')
87
+ return (field !== undefined && OPTION_FIELDS.has(field)) || IDENTIFIER.test(value)
88
+ }
89
+
90
+ /** Filtre stega du client Sanity : `stega: {studioUrl, filter: stegaFilter}`. */
91
+ export function stegaFilter<P extends {sourcePath: readonly unknown[]; value: string; filterDefault: (props: P) => boolean}>(props: P): boolean {
92
+ return isOptionValue(props.sourcePath, props.value) ? false : props.filterDefault(props)
93
+ }
94
+
95
+ /**
96
+ * Où vit une instance : document (id, type) et chemin du champ qui la contient
97
+ * (une liste de sections, ou `single` : un champ qui EST la section).
98
+ */
99
+ export type SectionSource = {id: string; type: string; path: string; single?: boolean}
100
+
101
+ const decode = (s: string): {origin?: string; href?: string} | undefined => {
102
+ try {
103
+ return vercelStegaDecode(s) as {origin?: string; href?: string} | undefined
104
+ } catch {
105
+ return undefined
106
+ }
107
+ }
108
+
109
+ /**
110
+ * PREVIEW : une valeur héritée porte l'adresse du document des valeurs par
111
+ * défaut ; un clic dans Presentation ouvrirait ce document. Ce rappel (à passer
112
+ * à `applyDefaults` en mode brouillon) réétiquette chaque texte hérité vers le
113
+ * champ de l'INSTANCE dans la page, au format de Sanity : le clic ouvre
114
+ * l'instance, qui affiche la valeur héritée et permet de la surcharger.
115
+ */
116
+ export function reattributeTo(source: SectionSource, key?: string): OnInherit {
117
+ const base = key && !source.single ? `${source.path}[_key=="${key}"]` : source.path
118
+ const retag = (value: unknown, field: string): unknown => {
119
+ if (typeof value === 'string') {
120
+ const info = decode(value)
121
+ if (!info?.href) return value // valeur d'option, jamais encodée
122
+ const url = new URL(info.href, 'https://studio.invalid')
123
+ const baseUrl = url.searchParams.get('baseUrl')
124
+ if (!baseUrl) return value
125
+ const href = createEditUrl({
126
+ baseUrl,
127
+ workspace: url.searchParams.get('workspace') ?? undefined,
128
+ tool: url.searchParams.get('tool') ?? undefined,
129
+ // Identifiant de brouillon : pas de perspective imposée, Presentation garde la sienne.
130
+ id: `drafts.${source.id.replace(/^drafts\./, '')}`,
131
+ type: source.type,
132
+ path: `${base}.${field}`,
133
+ })
134
+ return vercelStegaCombine(vercelStegaClean(value), {origin: info.origin ?? 'sanity.io', href})
135
+ }
136
+ if (Array.isArray(value)) return value.map((v) => retag(v, field))
137
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, retag(v, field)]))
138
+ return value
139
+ }
140
+ // Le clic ouvre le champ de premier niveau de l'instance (celui qui hérite).
141
+ return (value, path) => retag(value, path[0] ?? '')
142
+ }