@nocode-factory/sanity-kit 2.8.3 → 2.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -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 +57 -19
- 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 +40 -1
- package/src/hooks/useOpenComponent.ts +4 -23
- package/src/index.ts +10 -0
- package/src/lib/openComponent.ts +34 -0
- 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":"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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nocode-factory/sanity-kit",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.9.1",
|
|
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,11 +1,12 @@
|
|
|
1
1
|
import {useState, type ComponentType} from 'react'
|
|
2
2
|
import {set, unset, useFormValue, useSchema, type InputProps} from 'sanity'
|
|
3
3
|
import {useRouter} from 'sanity/router'
|
|
4
|
-
import {Box, Flex, Stack, Text} from '@sanity/ui'
|
|
4
|
+
import {Box, Button, 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'
|
|
8
8
|
import {useKitClient} from '../hooks/useKitClient'
|
|
9
|
+
import {openComponentDefaults} from '../lib/openComponent'
|
|
9
10
|
import {useComponentDefaults} from '../hooks/useComponentDefaults'
|
|
10
11
|
import {
|
|
11
12
|
defaultValueAt,
|
|
@@ -46,6 +47,17 @@ export function createOverrideInput(config: ResolvedKitConfig): ComponentType<In
|
|
|
46
47
|
const parent = useFormValue((path.length > 1 ? path.slice(0, -1) : path) as never)
|
|
47
48
|
const resolved = resolveFieldPath(path, anchor, instance, namespace)
|
|
48
49
|
|
|
50
|
+
// L'instance elle-même (l'objet section) : bouton « Modifier l'instance principale ».
|
|
51
|
+
const own = props.value as {_type?: unknown} | undefined
|
|
52
|
+
if (
|
|
53
|
+
props.schemaType.jsonType === 'object' &&
|
|
54
|
+
typeof own?._type === 'string' &&
|
|
55
|
+
own._type.startsWith(namespace) &&
|
|
56
|
+
props.path.length > 0 &&
|
|
57
|
+
schema.get(defaultsType)
|
|
58
|
+
)
|
|
59
|
+
return <WithMainInstance {...props} type={own._type} />
|
|
60
|
+
|
|
49
61
|
if (!resolved || !schema.get(defaultsType) || !carriesDot(props.schemaType)) return props.renderDefault(props)
|
|
50
62
|
const shortName = blockName((instance as {_type: string})._type, namespace)
|
|
51
63
|
return <WithDot {...props} rel={resolved.path} inList={resolved.inList} shortName={shortName} parent={parent} />
|
|
@@ -113,6 +125,33 @@ export function createOverrideInput(config: ResolvedKitConfig): ComponentType<In
|
|
|
113
125
|
)
|
|
114
126
|
}
|
|
115
127
|
|
|
128
|
+
// En tête du formulaire d'une instance de composant : mène aux valeurs par
|
|
129
|
+
// défaut du composant (son « instance principale »), qui s'appliquent à toutes
|
|
130
|
+
// les instances dont le champ est vide.
|
|
131
|
+
function WithMainInstance(props: InputProps & {type: string}) {
|
|
132
|
+
const {type, ...inputProps} = props
|
|
133
|
+
const client = useKitClient()
|
|
134
|
+
const router = useRouter()
|
|
135
|
+
const open = () =>
|
|
136
|
+
void openComponentDefaults({type, config, hasDefaults: true, client, navigateIntent: (i, p) => router.navigateIntent(i, p)})
|
|
137
|
+
return (
|
|
138
|
+
<Stack gap={3}>
|
|
139
|
+
<Flex justify="flex-end">
|
|
140
|
+
<Button
|
|
141
|
+
mode="ghost"
|
|
142
|
+
tone="primary"
|
|
143
|
+
fontSize={1}
|
|
144
|
+
padding={2}
|
|
145
|
+
text="Modifier l'instance principale"
|
|
146
|
+
title="Valeurs par défaut du composant : elles s'appliquent à toutes ses instances dont le champ est vide"
|
|
147
|
+
onClick={open}
|
|
148
|
+
/>
|
|
149
|
+
</Flex>
|
|
150
|
+
{inputProps.renderDefault(inputProps)}
|
|
151
|
+
</Stack>
|
|
152
|
+
)
|
|
153
|
+
}
|
|
154
|
+
|
|
116
155
|
return OverrideInput
|
|
117
156
|
}
|
|
118
157
|
|
|
@@ -2,15 +2,10 @@ import {useCallback} from 'react'
|
|
|
2
2
|
import {useSchema} from 'sanity'
|
|
3
3
|
import {useRouter} from 'sanity/router'
|
|
4
4
|
import {useKitConfig} from '../context/KitContext'
|
|
5
|
-
import {
|
|
5
|
+
import {openComponentDefaults} from '../lib/openComponent'
|
|
6
6
|
import {useKitClient} from './useKitClient'
|
|
7
7
|
|
|
8
|
-
/**
|
|
9
|
-
* Ouvre un composant : Presentation avec son rendu réel et ses valeurs par
|
|
10
|
-
* défaut côte à côte. Sans document de valeurs par défaut dans le schéma : la
|
|
11
|
-
* démo du design system dans un nouvel onglet. `null` : rien à ouvrir.
|
|
12
|
-
* Partagé par la grille et la vue Map de l'onglet Composants.
|
|
13
|
-
*/
|
|
8
|
+
/** Ouvre un composant (voir openComponentDefaults). `null` : rien à ouvrir. */
|
|
14
9
|
export function useOpenComponent(): ((type: string) => void) | null {
|
|
15
10
|
const config = useKitConfig()
|
|
16
11
|
const schema = useSchema()
|
|
@@ -20,22 +15,8 @@ export function useOpenComponent(): ((type: string) => void) | null {
|
|
|
20
15
|
const hasDefaults = Boolean(schema.get(preview.defaultsType))
|
|
21
16
|
|
|
22
17
|
const open = useCallback(
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
if (config.previewUrl)
|
|
26
|
-
window.open(`${config.previewUrl}${preview.path}#${fillTemplate(preview.anchor, type, config.blockNamespace)}`, '_blank', 'noopener')
|
|
27
|
-
return
|
|
28
|
-
}
|
|
29
|
-
const lang = config.i18n?.defaultLocale ?? null
|
|
30
|
-
const id = await client
|
|
31
|
-
.fetch<string | null>(
|
|
32
|
-
`*[_type == $type] | order(select($lang != null && ${config.i18n?.field ?? 'language'} == $lang => 0, 1))[0]._id`,
|
|
33
|
-
{type: preview.defaultsType, lang},
|
|
34
|
-
)
|
|
35
|
-
.catch(() => null)
|
|
36
|
-
router.navigateIntent('edit', componentIntentParams(type, config.blockNamespace, preview, id ?? preview.defaultsType))
|
|
37
|
-
},
|
|
38
|
-
[hasDefaults, config, preview, client, router],
|
|
18
|
+
(type: string) => openComponentDefaults({type, config, hasDefaults, client, navigateIntent: (i, p) => router.navigateIntent(i, p)}),
|
|
19
|
+
[hasDefaults, config, client, router],
|
|
39
20
|
)
|
|
40
21
|
|
|
41
22
|
if (!hasDefaults && !config.previewUrl) return null
|
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,34 @@
|
|
|
1
|
+
import type {SanityClient} from 'sanity'
|
|
2
|
+
import type {ResolvedKitConfig} from '../config/types'
|
|
3
|
+
import {componentIntentParams, fillTemplate} from './blocks'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Ouvre un composant : Presentation avec son rendu réel et ses valeurs par
|
|
7
|
+
* défaut côte à côte (le document des valeurs par défaut, champ du composant).
|
|
8
|
+
* Sans document de valeurs par défaut dans le schéma : la démo du design system
|
|
9
|
+
* dans un nouvel onglet. Partagé par l'onglet Composants (grille, Map) et le
|
|
10
|
+
* bouton « Modifier l'instance principale » des formulaires.
|
|
11
|
+
*/
|
|
12
|
+
export async function openComponentDefaults(options: {
|
|
13
|
+
type: string
|
|
14
|
+
config: ResolvedKitConfig
|
|
15
|
+
hasDefaults: boolean
|
|
16
|
+
client: SanityClient
|
|
17
|
+
navigateIntent: (intent: string, params: Record<string, string>) => void
|
|
18
|
+
}): Promise<void> {
|
|
19
|
+
const {type, config, hasDefaults, client, navigateIntent} = options
|
|
20
|
+
const preview = config.componentPreview
|
|
21
|
+
if (!hasDefaults) {
|
|
22
|
+
if (config.previewUrl)
|
|
23
|
+
window.open(`${config.previewUrl}${preview.path}#${fillTemplate(preview.anchor, type, config.blockNamespace)}`, '_blank', 'noopener')
|
|
24
|
+
return
|
|
25
|
+
}
|
|
26
|
+
const lang = config.i18n?.defaultLocale ?? null
|
|
27
|
+
const id = await client
|
|
28
|
+
.fetch<string | null>(
|
|
29
|
+
`*[_type == $type] | order(select($lang != null && ${config.i18n?.field ?? 'language'} == $lang => 0, 1))[0]._id`,
|
|
30
|
+
{type: preview.defaultsType, lang},
|
|
31
|
+
)
|
|
32
|
+
.catch(() => null)
|
|
33
|
+
navigateIntent('edit', componentIntentParams(type, config.blockNamespace, preview, id ?? preview.defaultsType))
|
|
34
|
+
}
|
|
@@ -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