@nocode-factory/sanity-kit 2.8.2 → 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.
- package/README.md +38 -0
- package/bin/ncf-kit.mjs +30 -0
- package/dist/componentDefaults-CbOXLaYE.d.ts +62 -0
- package/dist/componentDefaults-YFpAqFb4.js +77 -0
- package/dist/componentDefaults-YFpAqFb4.js.map +1 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +39 -18
- package/dist/index.js.map +1 -1
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +2 -0
- package/dist/web-defaults.d.ts +56 -0
- package/dist/web-defaults.js +140 -0
- package/dist/web-defaults.js.map +1 -0
- package/package.json +14 -2
- package/src/form/OverrideInput.tsx +45 -12
- package/src/index.ts +10 -0
- package/src/lib/overrides.ts +14 -7
- package/src/schema/componentDefaults.ts +106 -0
- package/src/schema/index.ts +17 -0
- package/src/version.ts +1 -1
- package/src/web/defaults.ts +142 -0
package/dist/schema.d.ts
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-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,QACrE,cAAc,GAAG,KAAK,cAAc,KAAK,KAAK,CAAC,IAAI,SAAM,IAAI,OAAO,QAAQ,KAAK,OAAO,WAAW,CAAC,GAAG,QAAQ,GAAG,CAAC;CAC9H;CAEA,KADe,WAAW,IAAI,OAAO,IAAI,SAAS,EAAE,CAAC,KAAK,WAAW,IAAI,OAAO,SAAS,SAAS,EAAE,CAAC,MACvF,CAAC,UAAU,QAAe,KAAK,UAAU,QAAQ,GACxD,KAAA,IAAM,OAAO,aAAa,AAAI,OAAO,aAAU,IAAI,OAAO,YAAY,UAAU,SAAS,MAAM,CAAC,GAAG,QAAQ,GAAG,CAAC,IAAI,SAAS;CAEnI,OAAO;AACT;;AAGA,SAAgB,cAAyC,SAAY,UAAgD,WAA0B;CAC7I,OAAO,QAAQ,SAAS,WAAW,QAAQ,QAAQ,SAAS;AAC9D;;;;;;AAOA,SAAgB,uBAAuB,cAAiC,mBAA2B,UAAuE,CAAC,GAAW;CACpL,IAAM,EAAC,OAAO,qBAAqB,YAAY,YAAY,gBAAgB,eAAc;CAKzF,OAAO,eAAe,KAAK,OAAO,cAAc,kBAJjC,aACZ,QAAQ,MAAM,EAAE,WAAW,SAAS,KAAK,QAAQ,KAAK,EAAE,MAAM,UAAU,MAAM,CAAC,CAAC,CAAC,CACjF,KAAK,MAAM,IAAI,EAAE,KAAK,EAAE,MAAM,UAAU,MAAM,EAAE,GAAG,kBAAkB,EAAE,CAAC,CACxE,KAAK,KAC+D,EAAE;AAC3E;;;;;;;AAUA,MAAa,qBAAqB;CAChC,QAAQ;EAAC;EAAS;EAAQ;EAAW;EAAQ;EAAU;EAAS;EAAQ;EAAS;EAAU;EAAW;EAAS;EAAa;EAAc;EAAS;EAAQ;EAAa;EAAQ;EAAS;EAAS;EAAY;EAAQ;EAAW;CAAQ;CACzO,YAAY;AACd,GAEM,gBAAqC,IAAI,IAAI,mBAAmB,MAAM,GACtE,aAAa,IAAI,OAAO,mBAAmB,UAAU;AAE3D,SAAgB,cAAc,MAA0B,OAAwB;CAC9E,IAAM,QAAQ,CAAC,GAAG,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM,MAAmB,OAAO,KAAM,QAAQ;CAChF,OAAQ,UAAU,KAAA,KAAa,cAAc,IAAI,KAAK,KAAM,WAAW,KAAK,KAAK;AACnF;;AAGA,SAAgB,YAA6G,OAAmB;CAC9I,OAAO,eAAc,MAAM,YAAY,MAAM,KAAK,KAAY,MAAM,cAAc,KAAK;AACzF;AAQA,MAAM,UAAU,MAA4D;CAC1E,IAAI;EACF,OAAO,kBAAkB,CAAC;CAC5B,QAAQ;EACN;CACF;AACF;;;;;;;;AASA,SAAgB,cAAc,QAAuB,KAAyB;CAC5E,IAAM,OAAO,OAAO,CAAC,OAAO,SAAS,GAAG,OAAO,KAAK,UAAU,IAAI,MAAM,OAAO,MACzE,SAAS,OAAgB,UAA2B;EACxD,IAAI,OAAO,SAAU,UAAU;GAC7B,IAAM,OAAO,OAAO,KAAK;GACzB,IAAI,CAAC,MAAM,MAAM,OAAO;GACxB,IAAM,MAAM,IAAI,IAAI,KAAK,MAAM,wBAAwB,GACjD,UAAU,IAAI,aAAa,IAAI,SAAS;GAC9C,IAAI,CAAC,SAAS,OAAO;GACrB,IAAM,OAAO,cAAc;IACzB;IACA,WAAW,IAAI,aAAa,IAAI,WAAW,KAAK,KAAA;IAChD,MAAM,IAAI,aAAa,IAAI,MAAM,KAAK,KAAA;IAEtC,IAAI,UAAU,OAAO,GAAG,QAAQ,aAAa,EAAE;IAC/C,MAAM,OAAO;IACb,MAAM,GAAG,KAAK,GAAG;GACnB,CAAC;GACD,OAAO,mBAAmB,iBAAiB,KAAK,GAAG;IAAC,QAAQ,KAAK,UAAU;IAAa;GAAI,CAAC;EAC/F;EAGA,OAFI,MAAM,QAAQ,KAAK,IAAU,MAAM,KAAK,MAAM,MAAM,GAAG,KAAK,CAAC,IAC7D,SAAS,OAAO,SAAU,WAAiB,OAAO,YAAY,OAAO,QAAQ,KAAK,CAAC,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.
|
|
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": {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {useState, type ComponentType} from 'react'
|
|
2
|
-
import {set, useFormValue, useSchema, type InputProps} from 'sanity'
|
|
2
|
+
import {set, unset, useFormValue, useSchema, type InputProps} from 'sanity'
|
|
3
3
|
import {useRouter} from 'sanity/router'
|
|
4
|
-
import {Box, Flex, Text} from '@sanity/ui'
|
|
4
|
+
import {Box, Flex, Stack, Text} from '@sanity/ui'
|
|
5
5
|
import {Tooltip} from '@sanity/ui/tooltip'
|
|
6
6
|
import type {ResolvedKitConfig} from '../config/types'
|
|
7
7
|
import {blockName, componentIntentParams} from '../lib/blocks'
|
|
@@ -11,6 +11,8 @@ import {
|
|
|
11
11
|
defaultValueAt,
|
|
12
12
|
describeValue,
|
|
13
13
|
firstKeyedIndex,
|
|
14
|
+
inheritedPlaceholder,
|
|
15
|
+
isEmptyValue,
|
|
14
16
|
isOverride,
|
|
15
17
|
resetAction,
|
|
16
18
|
resolveFieldPath,
|
|
@@ -22,8 +24,9 @@ import {
|
|
|
22
24
|
* Pastille bleue sur tout champ d'une instance de composant dont la valeur
|
|
23
25
|
* DIFFÈRE de la valeur par défaut du composant (valeur par défaut vide comprise),
|
|
24
26
|
* éléments de liste compris (comparés à l'élément de même rang). Au survol, elle
|
|
25
|
-
* affiche la valeur par défaut ; au clic,
|
|
26
|
-
*
|
|
27
|
+
* affiche la valeur par défaut ; au clic, le champ revient en HÉRITAGE et suit la
|
|
28
|
+
* valeur par défaut, même quand elle change (sans valeur par défaut, elle ouvre
|
|
29
|
+
* le réglage du composant). Un champ vide affiche la valeur héritée. Les champs
|
|
27
30
|
* « simples » la portent (texte, nombre, choix, case, liste, image, référence,
|
|
28
31
|
* couleur...) ; un objet composé (lien) la porte sur ses sous-champs.
|
|
29
32
|
*/
|
|
@@ -58,24 +61,54 @@ export function createOverrideInput(config: ResolvedKitConfig): ComponentType<In
|
|
|
58
61
|
const field = rel[rel.length - 1] ?? ''
|
|
59
62
|
|
|
60
63
|
const router = useRouter()
|
|
64
|
+
|
|
65
|
+
// Champ vide qui hérite : il affiche la valeur par défaut du composant
|
|
66
|
+
// (grisée dans un champ texte, mentionnée sous les autres champs).
|
|
67
|
+
if (isEmptyValue(inputProps.value) && !isEmptyValue(inherited)) {
|
|
68
|
+
// Texte grisé seulement dans une zone de saisie libre (texte, nombre) ; un
|
|
69
|
+
// choix (style, taille, variante, texture...) affiche la mention.
|
|
70
|
+
const st = inputProps.schemaType as {jsonType?: string; options?: {list?: unknown[]}}
|
|
71
|
+
const freeText = (st.jsonType === 'string' || st.jsonType === 'number') && !st.options?.list?.length
|
|
72
|
+
const placeholder = freeText ? inheritedPlaceholder(inherited) : null
|
|
73
|
+
const withPlaceholder =
|
|
74
|
+
placeholder !== null
|
|
75
|
+
? ({...inputProps, elementProps: {...(inputProps.elementProps as object), placeholder}} as InputProps)
|
|
76
|
+
: inputProps
|
|
77
|
+
return (
|
|
78
|
+
<Stack gap={2}>
|
|
79
|
+
{inputProps.renderDefault(withPlaceholder)}
|
|
80
|
+
{placeholder === null && (
|
|
81
|
+
<Text size={0} muted>
|
|
82
|
+
Valeur par défaut du composant : {describeValue(inherited)}
|
|
83
|
+
</Text>
|
|
84
|
+
)}
|
|
85
|
+
</Stack>
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
61
89
|
if (!isOverride(inputProps.value, inherited, field, parent)) return inputProps.renderDefault(inputProps)
|
|
62
|
-
// « Réinitialiser »
|
|
63
|
-
//
|
|
90
|
+
// « Réinitialiser » remet le champ en HÉRITAGE (vidé en base) : il suit la
|
|
91
|
+
// valeur par défaut, aujourd'hui comme après ses changements. Sans valeur par
|
|
92
|
+
// défaut : ouvre le réglage du composant (un champ vidé n'afficherait rien).
|
|
93
|
+
// Élément de liste : la liste remplie remplace celle du défaut en entier, la
|
|
94
|
+
// valeur par défaut y est donc recopiée.
|
|
64
95
|
const action = resetAction(inherited)
|
|
65
96
|
const onClick =
|
|
66
|
-
action.kind === '
|
|
67
|
-
? () =>
|
|
68
|
-
: () =>
|
|
97
|
+
action.kind === 'noDefault'
|
|
98
|
+
? () =>
|
|
69
99
|
router.navigateIntent(
|
|
70
100
|
'edit',
|
|
71
101
|
componentIntentParams(`${namespace}${shortName}`, namespace, config.componentPreview, defaultsType),
|
|
72
102
|
)
|
|
103
|
+
: inList
|
|
104
|
+
? () => inputProps.onChange(set(structuredClone(inherited)))
|
|
105
|
+
: () => inputProps.onChange(unset())
|
|
73
106
|
return (
|
|
74
107
|
<Flex align="flex-start" gap={2}>
|
|
75
108
|
<Box flex={1} style={{minWidth: 0}}>
|
|
76
109
|
{inputProps.renderDefault(inputProps)}
|
|
77
110
|
</Box>
|
|
78
|
-
<OverrideDot hasDefault={action.kind
|
|
111
|
+
<OverrideDot hasDefault={action.kind !== 'noDefault'} full={describeValue(inherited)} short={shortValue(inherited)} onClick={onClick} />
|
|
79
112
|
</Flex>
|
|
80
113
|
)
|
|
81
114
|
}
|
|
@@ -109,7 +142,7 @@ function OverrideDot(props: {hasDefault: boolean; full: string; short: string; o
|
|
|
109
142
|
<Box padding={2} style={{maxWidth: 280}}>
|
|
110
143
|
<Text size={1}>
|
|
111
144
|
{props.hasDefault
|
|
112
|
-
? `Différent de la valeur par défaut du composant. Cliquer pour
|
|
145
|
+
? `Différent de la valeur par défaut du composant (${props.full}). Cliquer pour revenir à la valeur par défaut : le champ la suivra, même si elle change.`
|
|
113
146
|
: 'Ce composant n\'a pas de valeur par défaut pour ce champ. Cliquer pour la définir (Composants : valeurs par défaut).'}
|
|
114
147
|
</Text>
|
|
115
148
|
</Box>
|
|
@@ -122,7 +155,7 @@ function OverrideDot(props: {hasDefault: boolean; full: string; short: string; o
|
|
|
122
155
|
onMouseLeave={() => setHover(false)}
|
|
123
156
|
onFocus={() => setHover(true)}
|
|
124
157
|
onBlur={() => setHover(false)}
|
|
125
|
-
aria-label={props.hasDefault ? `
|
|
158
|
+
aria-label={props.hasDefault ? `Revenir à la valeur par défaut du composant : ${props.full}` : 'Définir la valeur par défaut du composant'}
|
|
126
159
|
style={{
|
|
127
160
|
marginTop: 9,
|
|
128
161
|
flex: 'none',
|
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'
|
package/src/lib/overrides.ts
CHANGED
|
@@ -146,14 +146,21 @@ export function describeValue(value: unknown): string {
|
|
|
146
146
|
}
|
|
147
147
|
|
|
148
148
|
/**
|
|
149
|
-
* Ce que fait « Réinitialiser » :
|
|
150
|
-
*
|
|
151
|
-
*
|
|
152
|
-
*
|
|
149
|
+
* Ce que fait « Réinitialiser » : remettre le champ en HÉRITAGE (le vider en
|
|
150
|
+
* base). Il suit alors la valeur par défaut du composant, aujourd'hui comme
|
|
151
|
+
* après ses changements (une copie serait figée). Le champ affiche la valeur
|
|
152
|
+
* héritée (grisée). Sans valeur par défaut, rien à hériter : le champ resterait
|
|
153
|
+
* vide, la pastille renvoie donc au réglage du composant.
|
|
153
154
|
*/
|
|
154
|
-
export function resetAction(inherited: unknown): {kind: '
|
|
155
|
-
|
|
156
|
-
|
|
155
|
+
export function resetAction(inherited: unknown): {kind: 'inherit'} | {kind: 'noDefault'} {
|
|
156
|
+
return isEmptyValue(inherited) ? {kind: 'noDefault'} : {kind: 'inherit'}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Texte grisé d'un champ texte vide qui hérite de la valeur par défaut. */
|
|
160
|
+
export function inheritedPlaceholder(value: unknown): string | null {
|
|
161
|
+
if (typeof value === 'string' && value.trim()) return value
|
|
162
|
+
if (typeof value === 'number') return String(value)
|
|
163
|
+
return null
|
|
157
164
|
}
|
|
158
165
|
|
|
159
166
|
/** Libellé court de la valeur par défaut, pour la pastille au survol. */
|
|
@@ -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