iagenify 0.4.4 → 0.4.5
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 +0 -38
- package/dist/index.cjs +161 -1242
- package/dist/index.js +161 -1242
- package/package.json +2 -7
- package/dist/studio.js +0 -907
package/dist/studio.js
DELETED
|
@@ -1,907 +0,0 @@
|
|
|
1
|
-
// src/studio/errors.js
|
|
2
|
-
var StudioError = class extends Error {
|
|
3
|
-
constructor(code, message, details = void 0, status = 400) {
|
|
4
|
-
super(message);
|
|
5
|
-
this.name = "StudioError";
|
|
6
|
-
this.status = status;
|
|
7
|
-
this.code = code;
|
|
8
|
-
if (details !== void 0) this.details = details;
|
|
9
|
-
}
|
|
10
|
-
};
|
|
11
|
-
|
|
12
|
-
// src/studio/format.js
|
|
13
|
-
var FORMAT = "iagenify.design";
|
|
14
|
-
var FORMAT_VERSION = 1;
|
|
15
|
-
var NODE_TYPES = ["frame", "text", "image", "shape"];
|
|
16
|
-
var CONTENEURS = /* @__PURE__ */ new Set(["frame"]);
|
|
17
|
-
var TAGS = {
|
|
18
|
-
frame: ["div", "section", "header", "footer", "nav", "main", "article", "aside", "figure", "ul", "li", "a", "button"],
|
|
19
|
-
text: ["p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "a", "button", "li", "small", "strong", "em", "label"],
|
|
20
|
-
image: ["img"],
|
|
21
|
-
shape: ["div"]
|
|
22
|
-
};
|
|
23
|
-
var DEFAULT_TAG = { frame: "div", text: "p", image: "img", shape: "div" };
|
|
24
|
-
var CHAMPS_NOEUD = /* @__PURE__ */ new Set(["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"]);
|
|
25
|
-
var CHAMPS = {
|
|
26
|
-
layout: { mode: ["flex", "grid", "free"], direction: ["row", "column"], gap: "longueur", padding: "padding", align: ["start", "center", "end", "stretch"], justify: ["start", "center", "end", "between"], wrap: "booleen", columns: "entier" },
|
|
27
|
-
size: { w: "dimension", h: "dimension", minW: "longueur", minH: "longueur", maxW: "longueur", maxH: "longueur" },
|
|
28
|
-
position: { x: "nombre", y: "nombre", absolute: "booleen" },
|
|
29
|
-
style: { fill: "remplissage", stroke: "trait", radius: "rayon", shadow: "ombres", opacity: "opacite", clip: "booleen" },
|
|
30
|
-
text: { content: "texte", font: "police", size: "longueur", weight: "graisse", lineHeight: "interligne", align: ["left", "center", "right", "justify"], color: "couleur", letterSpacing: "nombre", transform: ["none", "uppercase", "lowercase", "capitalize"] },
|
|
31
|
-
image: { src: "source", fit: ["cover", "contain", "fill"] },
|
|
32
|
-
shape: { kind: ["rect", "ellipse", "line"] }
|
|
33
|
-
};
|
|
34
|
-
var COULEUR = /^(#[0-9a-f]{3}|#[0-9a-f]{4}|#[0-9a-f]{6}|#[0-9a-f]{8}|transparent|rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,\s*(0|1|0?\.\d+)\s*)?\))$/i;
|
|
35
|
-
var POLICE = /^[A-Za-z0-9 \-]{1,64}$/;
|
|
36
|
-
var SOURCE = /^asset:[A-Za-z0-9_\-]{1,64}$/;
|
|
37
|
-
var fini = (v) => typeof v === "number" && Number.isFinite(v);
|
|
38
|
-
function isColor(v) {
|
|
39
|
-
return typeof v === "string" && COULEUR.test(v.trim());
|
|
40
|
-
}
|
|
41
|
-
function verifierValeur(regle, v) {
|
|
42
|
-
if (Array.isArray(regle)) return regle.includes(v) ? null : `valeur_non_permise (${regle.join(", ")})`;
|
|
43
|
-
switch (regle) {
|
|
44
|
-
case "booleen":
|
|
45
|
-
return typeof v === "boolean" ? null : "booleen_attendu";
|
|
46
|
-
case "nombre":
|
|
47
|
-
return fini(v) ? null : "nombre_attendu";
|
|
48
|
-
case "entier":
|
|
49
|
-
return Number.isInteger(v) && v >= 1 && v <= 24 ? null : "entier_1_24_attendu";
|
|
50
|
-
case "longueur":
|
|
51
|
-
return fini(v) && v >= 0 && v <= 1e5 ? null : "longueur_positive_attendue";
|
|
52
|
-
case "dimension":
|
|
53
|
-
return v === "hug" || v === "fill" || fini(v) && v >= 0 && v <= 1e5 ? null : "hug_fill_ou_longueur_attendu";
|
|
54
|
-
case "padding":
|
|
55
|
-
if (fini(v) && v >= 0) return null;
|
|
56
|
-
if (Array.isArray(v) && (v.length === 2 || v.length === 4) && v.every((x) => fini(x) && x >= 0)) return null;
|
|
57
|
-
return "padding_nombre_ou_liste_2_4";
|
|
58
|
-
case "rayon":
|
|
59
|
-
if (fini(v) && v >= 0) return null;
|
|
60
|
-
if (Array.isArray(v) && v.length === 4 && v.every((x) => fini(x) && x >= 0)) return null;
|
|
61
|
-
return "rayon_nombre_ou_liste_4";
|
|
62
|
-
case "opacite":
|
|
63
|
-
return fini(v) && v >= 0 && v <= 1 ? null : "opacite_0_1";
|
|
64
|
-
case "couleur":
|
|
65
|
-
return isColor(v) ? null : "couleur_invalide";
|
|
66
|
-
case "remplissage":
|
|
67
|
-
if (isColor(v)) return null;
|
|
68
|
-
if (v && typeof v === "object" && v.type === "linear") {
|
|
69
|
-
const cles = Object.keys(v).filter((k) => !["type", "angle", "stops"].includes(k));
|
|
70
|
-
if (cles.length) return `champ_inconnu (${cles[0]})`;
|
|
71
|
-
if (!fini(v.angle)) return "angle_attendu";
|
|
72
|
-
if (!Array.isArray(v.stops) || v.stops.length < 2 || v.stops.length > 8) return "2_a_8_arrets";
|
|
73
|
-
for (const s of v.stops) if (!s || !isColor(s.color) || !fini(s.at) || s.at < 0 || s.at > 1 || Object.keys(s).length !== 2) return "arret_invalide";
|
|
74
|
-
return null;
|
|
75
|
-
}
|
|
76
|
-
return "couleur_ou_degrade_attendu";
|
|
77
|
-
case "trait":
|
|
78
|
-
if (v && typeof v === "object" && isColor(v.color) && fini(v.width) && v.width >= 0 && v.width <= 100 && Object.keys(v).length === 2) return null;
|
|
79
|
-
return "trait_{color,width}_attendu";
|
|
80
|
-
case "ombres":
|
|
81
|
-
if (!Array.isArray(v) || v.length > 4) return "liste_de_4_ombres_max";
|
|
82
|
-
for (const o of v) {
|
|
83
|
-
if (!o || typeof o !== "object") return "ombre_invalide";
|
|
84
|
-
const cles = Object.keys(o).filter((k) => !["x", "y", "blur", "spread", "color", "inset"].includes(k));
|
|
85
|
-
if (cles.length) return `champ_inconnu (${cles[0]})`;
|
|
86
|
-
if (![o.x, o.y, o.blur].every(fini) || !isColor(o.color) || o.spread !== void 0 && !fini(o.spread) || o.inset !== void 0 && typeof o.inset !== "boolean") return "ombre_invalide";
|
|
87
|
-
}
|
|
88
|
-
return null;
|
|
89
|
-
case "texte":
|
|
90
|
-
return typeof v === "string" && v.length <= 2e4 ? null : "texte_attendu";
|
|
91
|
-
case "police":
|
|
92
|
-
return typeof v === "string" && POLICE.test(v) ? null : "nom_de_police_invalide";
|
|
93
|
-
case "graisse":
|
|
94
|
-
return Number.isInteger(v) && v >= 100 && v <= 900 && v % 100 === 0 ? null : "graisse_100_a_900";
|
|
95
|
-
case "interligne":
|
|
96
|
-
return fini(v) && v > 0 && v <= 10 ? null : "interligne_0_10";
|
|
97
|
-
case "source":
|
|
98
|
-
return typeof v === "string" && SOURCE.test(v) ? null : "source_asset:<id>_attendue";
|
|
99
|
-
default:
|
|
100
|
-
return "regle_inconnue";
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
function verifierGroupe(groupe, objet, chemin, erreurs) {
|
|
104
|
-
if (objet === void 0) return;
|
|
105
|
-
if (!objet || typeof objet !== "object" || Array.isArray(objet)) {
|
|
106
|
-
erreurs.push({ path: chemin, reason: "objet_attendu" });
|
|
107
|
-
return;
|
|
108
|
-
}
|
|
109
|
-
const regles = CHAMPS[groupe];
|
|
110
|
-
for (const [cle, valeur] of Object.entries(objet)) {
|
|
111
|
-
if (!(cle in regles)) {
|
|
112
|
-
erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
|
|
113
|
-
continue;
|
|
114
|
-
}
|
|
115
|
-
if (valeur === null && ["stroke", "shadow"].includes(cle)) continue;
|
|
116
|
-
const motif = verifierValeur(regles[cle], valeur);
|
|
117
|
-
if (motif) erreurs.push({ path: `${chemin}.${cle}`, reason: motif });
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
function validateNode(node, chemin = "node") {
|
|
121
|
-
const erreurs = [];
|
|
122
|
-
if (!node || typeof node !== "object" || Array.isArray(node)) return [{ path: chemin, reason: "objet_attendu" }];
|
|
123
|
-
for (const cle of Object.keys(node)) if (!CHAMPS_NOEUD.has(cle)) erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
|
|
124
|
-
if (!NODE_TYPES.includes(node.type)) erreurs.push({ path: `${chemin}.type`, reason: `type_inconnu (${NODE_TYPES.join(", ")})` });
|
|
125
|
-
if (typeof node.name !== "string" || !node.name.trim() || node.name.length > 120) erreurs.push({ path: `${chemin}.name`, reason: "nom_1_a_120_caracteres" });
|
|
126
|
-
if (node.as !== void 0 && !(TAGS[node.type] || []).includes(node.as)) erreurs.push({ path: `${chemin}.as`, reason: "balise_non_permise" });
|
|
127
|
-
if (node.alt !== void 0 && (typeof node.alt !== "string" || node.alt.length > 500)) erreurs.push({ path: `${chemin}.alt`, reason: "texte_500_max" });
|
|
128
|
-
for (const groupe of ["layout", "size", "position", "style", "text", "image", "shape"]) verifierGroupe(groupe, node[groupe], `${chemin}.${groupe}`, erreurs);
|
|
129
|
-
if (node.type !== "frame" && node.layout !== void 0) erreurs.push({ path: `${chemin}.layout`, reason: "seul_un_cadre_a_une_mise_en_page" });
|
|
130
|
-
if (node.type !== "text" && node.text !== void 0) erreurs.push({ path: `${chemin}.text`, reason: "seul_un_texte_a_du_texte" });
|
|
131
|
-
if (node.type === "text" && typeof node.text?.content !== "string") erreurs.push({ path: `${chemin}.text.content`, reason: "texte_attendu" });
|
|
132
|
-
if (node.type !== "image" && node.image !== void 0) erreurs.push({ path: `${chemin}.image`, reason: "seule_une_image_a_une_source" });
|
|
133
|
-
if (node.type === "image" && typeof node.image?.src !== "string") erreurs.push({ path: `${chemin}.image.src`, reason: "source_asset:<id>_attendue" });
|
|
134
|
-
if (node.type !== "shape" && node.shape !== void 0) erreurs.push({ path: `${chemin}.shape`, reason: "seule_une_forme_a_un_genre" });
|
|
135
|
-
if (CONTENEURS.has(node.type)) {
|
|
136
|
-
if (!Array.isArray(node.children)) erreurs.push({ path: `${chemin}.children`, reason: "liste_attendue" });
|
|
137
|
-
} else if (node.children !== void 0) erreurs.push({ path: `${chemin}.children`, reason: "ce_type_n_a_pas_d_enfants" });
|
|
138
|
-
return erreurs;
|
|
139
|
-
}
|
|
140
|
-
function isContainer(node) {
|
|
141
|
-
return CONTENEURS.has(node?.type);
|
|
142
|
-
}
|
|
143
|
-
function createDocument() {
|
|
144
|
-
return { format: FORMAT, version: FORMAT_VERSION, meta: { nextId: 1 }, pages: [{ id: "p_1", name: "Page 1", frames: [] }], nodes: {} };
|
|
145
|
-
}
|
|
146
|
-
function validate(doc) {
|
|
147
|
-
const erreurs = [];
|
|
148
|
-
const err = (path, reason) => erreurs.push({ path, reason });
|
|
149
|
-
if (!doc || typeof doc !== "object" || Array.isArray(doc)) return { ok: false, errors: [{ path: "", reason: "objet_attendu" }] };
|
|
150
|
-
for (const cle of Object.keys(doc)) if (!["format", "version", "meta", "pages", "nodes"].includes(cle)) err(cle, "champ_inconnu");
|
|
151
|
-
if (doc.format !== FORMAT) err("format", `attendu_${FORMAT}`);
|
|
152
|
-
if (doc.version !== FORMAT_VERSION) err("version", `version_${FORMAT_VERSION}_attendue`);
|
|
153
|
-
if (!doc.meta || !Number.isInteger(doc.meta.nextId) || doc.meta.nextId < 1 || Object.keys(doc.meta).length !== 1) err("meta", "meta_{nextId}_attendu");
|
|
154
|
-
if (!doc.nodes || typeof doc.nodes !== "object" || Array.isArray(doc.nodes)) {
|
|
155
|
-
err("nodes", "objet_attendu");
|
|
156
|
-
return { ok: false, errors: erreurs };
|
|
157
|
-
}
|
|
158
|
-
if (!Array.isArray(doc.pages) || doc.pages.length === 0) {
|
|
159
|
-
err("pages", "au_moins_une_page");
|
|
160
|
-
return { ok: false, errors: erreurs };
|
|
161
|
-
}
|
|
162
|
-
const parents = /* @__PURE__ */ new Map();
|
|
163
|
-
const cite = (id, path) => {
|
|
164
|
-
if (typeof id !== "string" || !Object.hasOwn(doc.nodes, id)) {
|
|
165
|
-
err(path, "enfant_inexistant");
|
|
166
|
-
return;
|
|
167
|
-
}
|
|
168
|
-
parents.set(id, (parents.get(id) || 0) + 1);
|
|
169
|
-
};
|
|
170
|
-
const idsPages = /* @__PURE__ */ new Set();
|
|
171
|
-
doc.pages.forEach((p, i) => {
|
|
172
|
-
const c = `pages[${i}]`;
|
|
173
|
-
if (!p || typeof p !== "object") return err(c, "objet_attendu");
|
|
174
|
-
for (const cle of Object.keys(p)) if (!["id", "name", "route", "frames"].includes(cle)) err(`${c}.${cle}`, "champ_inconnu");
|
|
175
|
-
if (typeof p.id !== "string" || !/^p_[a-z0-9]+$/.test(p.id) || idsPages.has(p.id)) err(`${c}.id`, "id_de_page_invalide_ou_double");
|
|
176
|
-
idsPages.add(p.id);
|
|
177
|
-
if (typeof p.name !== "string" || !p.name.trim() || p.name.length > 120) err(`${c}.name`, "nom_1_a_120_caracteres");
|
|
178
|
-
if (p.route !== void 0 && (typeof p.route !== "string" || !/^\/[a-z0-9\-/[\]]*$/.test(p.route))) err(`${c}.route`, "route_invalide");
|
|
179
|
-
if (!Array.isArray(p.frames)) return err(`${c}.frames`, "liste_attendue");
|
|
180
|
-
p.frames.forEach((id, k) => {
|
|
181
|
-
cite(id, `${c}.frames[${k}]`);
|
|
182
|
-
if (typeof id === "string" && Object.hasOwn(doc.nodes, id) && doc.nodes[id]?.type !== "frame") {
|
|
183
|
-
err(`${c}.frames[${k}]`, "une_page_ne_contient_que_des_cadres");
|
|
184
|
-
}
|
|
185
|
-
});
|
|
186
|
-
});
|
|
187
|
-
const limite = doc.meta?.nextId ?? 1;
|
|
188
|
-
for (const [id, node] of Object.entries(doc.nodes)) {
|
|
189
|
-
const c = `nodes.${id}`;
|
|
190
|
-
if (!/^n_[0-9a-z]+$/.test(id)) err(c, "id_invalide");
|
|
191
|
-
else if (parseInt(id.slice(2), 36) >= limite) err(c, "id_au_dela_du_compteur");
|
|
192
|
-
if (node?.id !== id) err(`${c}.id`, "id_different_de_la_cle");
|
|
193
|
-
erreurs.push(...validateNode(node, c));
|
|
194
|
-
if (Array.isArray(node?.children)) node.children.forEach((enfant, k) => cite(enfant, `${c}.children[${k}]`));
|
|
195
|
-
}
|
|
196
|
-
for (const id of Object.keys(doc.nodes)) {
|
|
197
|
-
const n = parents.get(id) || 0;
|
|
198
|
-
if (n === 0) err(`nodes.${id}`, "noeud_orphelin");
|
|
199
|
-
if (n > 1) err(`nodes.${id}`, "noeud_a_plusieurs_parents");
|
|
200
|
-
}
|
|
201
|
-
if (erreurs.length) return { ok: false, errors: erreurs };
|
|
202
|
-
const vus = /* @__PURE__ */ new Set();
|
|
203
|
-
const pile = doc.pages.flatMap((p) => p.frames);
|
|
204
|
-
while (pile.length) {
|
|
205
|
-
const id = pile.pop();
|
|
206
|
-
vus.add(id);
|
|
207
|
-
for (const enfant of doc.nodes[id].children || []) pile.push(enfant);
|
|
208
|
-
}
|
|
209
|
-
for (const id of Object.keys(doc.nodes)) if (!vus.has(id)) err(`nodes.${id}`, "cycle");
|
|
210
|
-
return { ok: erreurs.length === 0, errors: erreurs };
|
|
211
|
-
}
|
|
212
|
-
function assertValid(doc) {
|
|
213
|
-
const r = validate(doc);
|
|
214
|
-
if (!r.ok) throw new StudioError("studio_document_invalid", `Document invalide : ${r.errors[0].path} \u2014 ${r.errors[0].reason}`, { errors: r.errors.slice(0, 20) });
|
|
215
|
-
return doc;
|
|
216
|
-
}
|
|
217
|
-
var ORDRE_NOEUD = ["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"];
|
|
218
|
-
var ordonner = (objet, ordre) => {
|
|
219
|
-
const out = {};
|
|
220
|
-
for (const k of ordre) if (objet[k] !== void 0) out[k] = objet[k];
|
|
221
|
-
return out;
|
|
222
|
-
};
|
|
223
|
-
function canonical(doc) {
|
|
224
|
-
const nodes = {};
|
|
225
|
-
const ids = Object.keys(doc.nodes).sort((a, b) => parseInt(a.slice(2), 36) - parseInt(b.slice(2), 36));
|
|
226
|
-
for (const id of ids) {
|
|
227
|
-
const n = ordonner(doc.nodes[id], ORDRE_NOEUD);
|
|
228
|
-
for (const g of Object.keys(CHAMPS)) if (n[g] && typeof n[g] === "object") n[g] = ordonner(n[g], Object.keys(CHAMPS[g]));
|
|
229
|
-
nodes[id] = n;
|
|
230
|
-
}
|
|
231
|
-
return {
|
|
232
|
-
format: doc.format,
|
|
233
|
-
version: doc.version,
|
|
234
|
-
meta: { nextId: doc.meta.nextId },
|
|
235
|
-
pages: doc.pages.map((p) => ordonner({ ...p, frames: [...p.frames] }, ["id", "name", "route", "frames"])),
|
|
236
|
-
nodes
|
|
237
|
-
};
|
|
238
|
-
}
|
|
239
|
-
function migrate(doc) {
|
|
240
|
-
if (doc && doc.version === FORMAT_VERSION) return doc;
|
|
241
|
-
throw new StudioError("studio_document_invalid", `Version de document non prise en charge : ${doc?.version}`, { errors: [{ path: "version", reason: `version_${FORMAT_VERSION}_attendue` }] });
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
// src/studio/ops.js
|
|
245
|
-
var GROUPES = /* @__PURE__ */ new Set(["layout", "size", "position", "style", "text", "image", "shape"]);
|
|
246
|
-
var SIMPLES = /* @__PURE__ */ new Set(["name", "as", "alt"]);
|
|
247
|
-
var refus = (index, reason, message) => {
|
|
248
|
-
throw new StudioError("studio_op_invalid", message || `Op\xE9ration ${index} refus\xE9e : ${reason}`, { index, reason });
|
|
249
|
-
};
|
|
250
|
-
function nouvelId(doc) {
|
|
251
|
-
const id = `n_${doc.meta.nextId.toString(36)}`;
|
|
252
|
-
doc.meta.nextId += 1;
|
|
253
|
-
return id;
|
|
254
|
-
}
|
|
255
|
-
function emplacement(doc, id) {
|
|
256
|
-
for (const p of doc.pages) {
|
|
257
|
-
const i = p.frames.indexOf(id);
|
|
258
|
-
if (i >= 0) return { parent: p.id, liste: p.frames, index: i };
|
|
259
|
-
}
|
|
260
|
-
for (const n of Object.values(doc.nodes)) if (n.children) {
|
|
261
|
-
const i = n.children.indexOf(id);
|
|
262
|
-
if (i >= 0) return { parent: n.id, liste: n.children, index: i };
|
|
263
|
-
}
|
|
264
|
-
return null;
|
|
265
|
-
}
|
|
266
|
-
function listeDuParent(doc, parent, type, index) {
|
|
267
|
-
const page = doc.pages.find((p) => p.id === parent);
|
|
268
|
-
if (page) {
|
|
269
|
-
if (type !== "frame") refus(index, "une_page_ne_contient_que_des_cadres");
|
|
270
|
-
return page.frames;
|
|
271
|
-
}
|
|
272
|
-
const n = doc.nodes[parent];
|
|
273
|
-
if (!n) refus(index, "parent_introuvable");
|
|
274
|
-
if (!isContainer(n)) refus(index, "le_parent_n_est_pas_un_cadre");
|
|
275
|
-
return n.children;
|
|
276
|
-
}
|
|
277
|
-
function sousArbre(doc, id, acc = {}) {
|
|
278
|
-
const n = doc.nodes[id];
|
|
279
|
-
acc[id] = n;
|
|
280
|
-
for (const e of n.children || []) sousArbre(doc, e, acc);
|
|
281
|
-
return acc;
|
|
282
|
-
}
|
|
283
|
-
function placer(liste, id, index, iop) {
|
|
284
|
-
const i = index === void 0 ? liste.length : index;
|
|
285
|
-
if (!Number.isInteger(i) || i < 0 || i > liste.length) refus(iop, "index_hors_limites");
|
|
286
|
-
liste.splice(i, 0, id);
|
|
287
|
-
return i;
|
|
288
|
-
}
|
|
289
|
-
function aplatir(doc, brut, iop, acc) {
|
|
290
|
-
if (!brut || typeof brut !== "object" || Array.isArray(brut)) refus(iop, "noeud_objet_attendu");
|
|
291
|
-
if ("id" in brut) refus(iop, "un_id_ne_se_choisit_pas");
|
|
292
|
-
const { children, ...reste } = brut;
|
|
293
|
-
const id = nouvelId(doc);
|
|
294
|
-
const node = { id, ...reste };
|
|
295
|
-
if (isContainer(node)) {
|
|
296
|
-
if (children !== void 0 && !Array.isArray(children)) refus(iop, "children_liste_attendue");
|
|
297
|
-
node.children = (children || []).map((c) => aplatir(doc, c, iop, acc));
|
|
298
|
-
} else if (children !== void 0) refus(iop, "ce_type_n_a_pas_d_enfants");
|
|
299
|
-
const erreurs = validateNode(node, "node");
|
|
300
|
-
if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
|
|
301
|
-
acc[id] = node;
|
|
302
|
-
return id;
|
|
303
|
-
}
|
|
304
|
-
function estDescendant(doc, ancetre, id) {
|
|
305
|
-
const n = doc.nodes[ancetre];
|
|
306
|
-
return (n?.children || []).some((e) => e === id || estDescendant(doc, e, id));
|
|
307
|
-
}
|
|
308
|
-
function lire(node, path) {
|
|
309
|
-
const [a, b] = path.split(".");
|
|
310
|
-
if (b === void 0) return node[a];
|
|
311
|
-
return node[a]?.[b];
|
|
312
|
-
}
|
|
313
|
-
function appliquerUne(doc, op, iop, inverses, created, removed) {
|
|
314
|
-
if (!op || typeof op !== "object") refus(iop, "operation_objet_attendue");
|
|
315
|
-
switch (op.op) {
|
|
316
|
-
case "set": {
|
|
317
|
-
const node = doc.nodes[op.id];
|
|
318
|
-
if (!node) refus(iop, "noeud_introuvable");
|
|
319
|
-
if (typeof op.path !== "string") refus(iop, "chemin_attendu");
|
|
320
|
-
const [a, b, ...trop] = op.path.split(".");
|
|
321
|
-
if (trop.length || !(SIMPLES.has(a) && b === void 0) && !GROUPES.has(a)) refus(iop, "chemin_non_modifiable");
|
|
322
|
-
const avant = lire(node, op.path);
|
|
323
|
-
const copie2 = structuredClone(node);
|
|
324
|
-
if (b === void 0) {
|
|
325
|
-
if (op.value === void 0) delete copie2[a];
|
|
326
|
-
else copie2[a] = structuredClone(op.value);
|
|
327
|
-
} else {
|
|
328
|
-
const groupe = { ...copie2[a] || {} };
|
|
329
|
-
if (op.value === void 0) delete groupe[b];
|
|
330
|
-
else groupe[b] = structuredClone(op.value);
|
|
331
|
-
if (Object.keys(groupe).length) copie2[a] = groupe;
|
|
332
|
-
else delete copie2[a];
|
|
333
|
-
}
|
|
334
|
-
const erreurs = validateNode(copie2, op.id);
|
|
335
|
-
if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
|
|
336
|
-
doc.nodes[op.id] = copie2;
|
|
337
|
-
inverses.push({ op: "set", id: op.id, path: op.path, value: avant === void 0 ? void 0 : structuredClone(avant) });
|
|
338
|
-
return;
|
|
339
|
-
}
|
|
340
|
-
case "insert": {
|
|
341
|
-
const acc = {};
|
|
342
|
-
const racine = aplatir(doc, op.node, iop, acc);
|
|
343
|
-
const liste = listeDuParent(doc, op.parent, acc[racine].type, iop);
|
|
344
|
-
Object.assign(doc.nodes, acc);
|
|
345
|
-
placer(liste, racine, op.index, iop);
|
|
346
|
-
created.push(...Object.keys(acc));
|
|
347
|
-
inverses.push({ op: "remove", id: racine });
|
|
348
|
-
return;
|
|
349
|
-
}
|
|
350
|
-
case "move": {
|
|
351
|
-
const node = doc.nodes[op.id];
|
|
352
|
-
if (!node) refus(iop, "noeud_introuvable");
|
|
353
|
-
if (op.parent === op.id || estDescendant(doc, op.id, op.parent)) refus(iop, "deplacement_dans_son_propre_descendant");
|
|
354
|
-
const ici = emplacement(doc, op.id);
|
|
355
|
-
const liste = listeDuParent(doc, op.parent, node.type, iop);
|
|
356
|
-
ici.liste.splice(ici.index, 1);
|
|
357
|
-
placer(liste, op.id, op.index, iop);
|
|
358
|
-
inverses.push({ op: "move", id: op.id, parent: ici.parent, index: ici.index });
|
|
359
|
-
return;
|
|
360
|
-
}
|
|
361
|
-
case "remove": {
|
|
362
|
-
if (!doc.nodes[op.id]) refus(iop, "noeud_introuvable");
|
|
363
|
-
const ici = emplacement(doc, op.id);
|
|
364
|
-
const arbre = sousArbre(doc, op.id);
|
|
365
|
-
ici.liste.splice(ici.index, 1);
|
|
366
|
-
for (const id of Object.keys(arbre)) delete doc.nodes[id];
|
|
367
|
-
removed.push(...Object.keys(arbre));
|
|
368
|
-
inverses.push({ op: "restore", parent: ici.parent, index: ici.index, root: op.id, nodes: arbre });
|
|
369
|
-
return;
|
|
370
|
-
}
|
|
371
|
-
case "restore": {
|
|
372
|
-
if (!op.__interne) refus(iop, "operation_inconnue");
|
|
373
|
-
const liste = listeDuParent(doc, op.parent, op.nodes[op.root].type, iop);
|
|
374
|
-
Object.assign(doc.nodes, structuredClone(op.nodes));
|
|
375
|
-
placer(liste, op.root, op.index, iop);
|
|
376
|
-
inverses.push({ op: "remove", id: op.root });
|
|
377
|
-
return;
|
|
378
|
-
}
|
|
379
|
-
default:
|
|
380
|
-
refus(iop, "operation_inconnue");
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
function applyOps(doc, ops, { internal = false } = {}) {
|
|
384
|
-
if (!Array.isArray(ops)) throw new StudioError("studio_op_invalid", "Un lot d'op\xE9rations est une liste.", { index: -1, reason: "liste_attendue" });
|
|
385
|
-
const copie2 = structuredClone(doc);
|
|
386
|
-
const inverses = [];
|
|
387
|
-
const created = [];
|
|
388
|
-
const removed = [];
|
|
389
|
-
ops.forEach((op, i) => appliquerUne(copie2, internal && op?.op === "restore" ? { ...op, __interne: true } : op, i, inverses, created, removed));
|
|
390
|
-
return { doc: copie2, inverse: inverses.reverse(), created, removed };
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
// src/studio/style.js
|
|
394
|
-
var px = (v) => `${+v.toFixed(3)}px`;
|
|
395
|
-
var ALIGN = { start: "flex-start", center: "center", end: "flex-end", stretch: "stretch" };
|
|
396
|
-
var JUSTIFY = { start: "flex-start", center: "center", end: "flex-end", between: "space-between" };
|
|
397
|
-
function remplissage(f) {
|
|
398
|
-
if (typeof f === "string") return f;
|
|
399
|
-
return `linear-gradient(${+f.angle.toFixed(3)}deg, ${f.stops.map((s) => `${s.color} ${+(s.at * 100).toFixed(3)}%`).join(", ")})`;
|
|
400
|
-
}
|
|
401
|
-
function padding(p) {
|
|
402
|
-
if (typeof p === "number") return px(p);
|
|
403
|
-
return p.map(px).join(" ");
|
|
404
|
-
}
|
|
405
|
-
function taille(decl, axe, v, parent) {
|
|
406
|
-
if (v === void 0) return;
|
|
407
|
-
const prop = axe === "w" ? "width" : "height";
|
|
408
|
-
const mode = parent?.layout?.mode;
|
|
409
|
-
const dir = parent?.layout?.direction || "row";
|
|
410
|
-
const principal = mode === "flex" && (axe === "w" && dir === "row" || axe === "h" && dir === "column");
|
|
411
|
-
if (typeof v === "number") {
|
|
412
|
-
decl.push([prop, px(v)]);
|
|
413
|
-
if (principal) decl.push(["flex-shrink", "0"]);
|
|
414
|
-
} else if (v === "fill") {
|
|
415
|
-
if (principal) decl.push(["flex", "1 1 0"], [axe === "w" ? "min-width" : "min-height", "0"]);
|
|
416
|
-
else if (mode === "flex") decl.push(["align-self", "stretch"]);
|
|
417
|
-
else decl.push([prop, "100%"]);
|
|
418
|
-
} else if (v === "hug") {
|
|
419
|
-
decl.push([prop, "fit-content"]);
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
function nodeCss(node, parent = null) {
|
|
423
|
-
const d = [];
|
|
424
|
-
const pos = node.position;
|
|
425
|
-
if (parent?.layout?.mode === "free" || pos?.absolute) {
|
|
426
|
-
d.push(["position", "absolute"], ["left", px(pos?.x ?? 0)], ["top", px(pos?.y ?? 0)]);
|
|
427
|
-
}
|
|
428
|
-
const l = node.layout;
|
|
429
|
-
if (node.type === "frame") {
|
|
430
|
-
if (l?.mode === "grid") {
|
|
431
|
-
d.push(["display", "grid"], ["grid-template-columns", `repeat(${l.columns || 2}, minmax(0, 1fr))`]);
|
|
432
|
-
} else if (l?.mode === "free") {
|
|
433
|
-
if (!d.some(([p]) => p === "position")) d.push(["position", "relative"]);
|
|
434
|
-
} else {
|
|
435
|
-
d.push(["display", "flex"], ["flex-direction", l?.direction || "column"]);
|
|
436
|
-
if (l?.wrap) d.push(["flex-wrap", "wrap"]);
|
|
437
|
-
if (l?.align) d.push(["align-items", ALIGN[l.align]]);
|
|
438
|
-
if (l?.justify) d.push(["justify-content", JUSTIFY[l.justify]]);
|
|
439
|
-
}
|
|
440
|
-
if (l?.gap !== void 0 && l.mode !== "free") d.push(["gap", px(l.gap)]);
|
|
441
|
-
if (l?.padding !== void 0) d.push(["padding", padding(l.padding)]);
|
|
442
|
-
}
|
|
443
|
-
taille(d, "w", node.size?.w, parent);
|
|
444
|
-
taille(d, "h", node.size?.h, parent);
|
|
445
|
-
for (const [k, prop] of [["minW", "min-width"], ["minH", "min-height"], ["maxW", "max-width"], ["maxH", "max-height"]]) {
|
|
446
|
-
if (node.size?.[k] !== void 0) d.push([prop, px(node.size[k])]);
|
|
447
|
-
}
|
|
448
|
-
const s = node.style || {};
|
|
449
|
-
if (s.fill !== void 0 && node.type !== "text") d.push(["background", remplissage(s.fill)]);
|
|
450
|
-
if (s.stroke) d.push(["border", `${px(s.stroke.width)} solid ${s.stroke.color}`]);
|
|
451
|
-
if (node.type === "shape" && node.shape?.kind === "ellipse") d.push(["border-radius", "50%"]);
|
|
452
|
-
else if (s.radius !== void 0) d.push(["border-radius", typeof s.radius === "number" ? px(s.radius) : s.radius.map(px).join(" ")]);
|
|
453
|
-
if (s.shadow?.length) d.push(["box-shadow", s.shadow.map((o) => `${o.inset ? "inset " : ""}${px(o.x)} ${px(o.y)} ${px(o.blur)} ${px(o.spread || 0)} ${o.color}`).join(", ")]);
|
|
454
|
-
if (s.opacity !== void 0 && s.opacity !== 1) d.push(["opacity", String(s.opacity)]);
|
|
455
|
-
if (s.clip) d.push(["overflow", "hidden"]);
|
|
456
|
-
if (node.type === "shape" && node.shape?.kind === "line") d.push(["height", "0"], ["border-top", `${px(s.stroke?.width ?? 1)} solid ${s.stroke?.color ?? "#000000"}`]);
|
|
457
|
-
const t = node.text;
|
|
458
|
-
if (node.type === "text") {
|
|
459
|
-
if (t.font) d.push(["font-family", `"${t.font}", sans-serif`]);
|
|
460
|
-
if (t.size !== void 0) d.push(["font-size", px(t.size)]);
|
|
461
|
-
if (t.weight !== void 0) d.push(["font-weight", String(t.weight)]);
|
|
462
|
-
if (t.lineHeight !== void 0) d.push(["line-height", String(t.lineHeight)]);
|
|
463
|
-
if (t.letterSpacing !== void 0) d.push(["letter-spacing", px(t.letterSpacing)]);
|
|
464
|
-
if (t.align) d.push(["text-align", t.align]);
|
|
465
|
-
if (t.transform && t.transform !== "none") d.push(["text-transform", t.transform]);
|
|
466
|
-
d.push(["color", t.color || "#000000"]);
|
|
467
|
-
if (s.fill !== void 0) d.push(["background", remplissage(s.fill)]);
|
|
468
|
-
d.push(["white-space", "pre-wrap"]);
|
|
469
|
-
}
|
|
470
|
-
if (node.type === "image") d.push(["display", "block"], ["object-fit", node.image.fit || "cover"]);
|
|
471
|
-
return d;
|
|
472
|
-
}
|
|
473
|
-
function tagOf(node) {
|
|
474
|
-
return node.as || DEFAULT_TAG[node.type];
|
|
475
|
-
}
|
|
476
|
-
var BASE_CSS = "*,*::before,*::after{box-sizing:border-box;margin:0}";
|
|
477
|
-
function parentsOf(doc) {
|
|
478
|
-
const m = /* @__PURE__ */ new Map();
|
|
479
|
-
for (const p of doc.pages) for (const id of p.frames) m.set(id, null);
|
|
480
|
-
for (const n of Object.values(doc.nodes)) for (const e of n.children || []) m.set(e, n);
|
|
481
|
-
return m;
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
// src/studio/check.js
|
|
485
|
-
function parseColor(c) {
|
|
486
|
-
if (!isColor(c)) return null;
|
|
487
|
-
const s = c.trim().toLowerCase();
|
|
488
|
-
if (s === "transparent") return [0, 0, 0, 0];
|
|
489
|
-
if (s.startsWith("#")) {
|
|
490
|
-
let h = s.slice(1);
|
|
491
|
-
if (h.length <= 4) h = [...h].map((x) => x + x).join("");
|
|
492
|
-
const n = (i) => parseInt(h.slice(i, i + 2), 16);
|
|
493
|
-
return [n(0), n(2), n(4), h.length === 8 ? n(6) / 255 : 1];
|
|
494
|
-
}
|
|
495
|
-
const v = s.match(/[\d.]+/g).map(Number);
|
|
496
|
-
return [v[0], v[1], v[2], v[3] ?? 1];
|
|
497
|
-
}
|
|
498
|
-
function luminance([r, g, b]) {
|
|
499
|
-
const lin = (x) => {
|
|
500
|
-
x /= 255;
|
|
501
|
-
return x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
|
|
502
|
-
};
|
|
503
|
-
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
|
|
504
|
-
}
|
|
505
|
-
var melange = (dessus, fond) => [0, 1, 2].map((i) => dessus[i] * dessus[3] + fond[i] * (1 - dessus[3])).concat(1);
|
|
506
|
-
function contrastRatio(a, b) {
|
|
507
|
-
const [l1, l2] = [luminance(a), luminance(b)].sort((x, y) => y - x);
|
|
508
|
-
return (l1 + 0.05) / (l2 + 0.05);
|
|
509
|
-
}
|
|
510
|
-
function fondsSous(doc, id, parents) {
|
|
511
|
-
const couches = [];
|
|
512
|
-
let n = doc.nodes[id];
|
|
513
|
-
if (n.type === "text" && n.style?.fill !== void 0) couches.push(n.style.fill);
|
|
514
|
-
for (let p = parents.get(id); p; p = parents.get(p.id)) if (p.style?.fill !== void 0) couches.push(p.style.fill);
|
|
515
|
-
let fonds = [[255, 255, 255, 1]];
|
|
516
|
-
for (const f of couches.reverse()) {
|
|
517
|
-
const couleurs = typeof f === "string" ? [parseColor(f)] : f.stops.map((s) => parseColor(s.color));
|
|
518
|
-
fonds = couleurs.flatMap((c) => fonds.map((base) => melange(c, base)));
|
|
519
|
-
}
|
|
520
|
-
return fonds;
|
|
521
|
-
}
|
|
522
|
-
function check(doc) {
|
|
523
|
-
const issues = [];
|
|
524
|
-
const parents = parentsOf(doc);
|
|
525
|
-
for (const n of Object.values(doc.nodes)) {
|
|
526
|
-
if (n.type === "text") {
|
|
527
|
-
const couleur = parseColor(n.text.color || "#000000");
|
|
528
|
-
const grand = (n.text.size ?? 16) >= 24 || (n.text.size ?? 16) >= 18.66 && (n.text.weight ?? 400) >= 700;
|
|
529
|
-
const requis = grand ? 3 : 4.5;
|
|
530
|
-
let pire = null;
|
|
531
|
-
for (const fond of fondsSous(doc, n.id, parents)) {
|
|
532
|
-
const ratio = contrastRatio(melange(couleur, fond), fond);
|
|
533
|
-
if (!pire || ratio < pire.ratio) pire = { ratio, fond };
|
|
534
|
-
}
|
|
535
|
-
if (pire && pire.ratio < requis) {
|
|
536
|
-
const hex = (c) => `#${c.slice(0, 3).map((x) => Math.round(x).toString(16).padStart(2, "0")).join("")}`;
|
|
537
|
-
issues.push({ rule: "contrast", severity: "error", node: n.id, name: n.name, detail: { ratio: Math.floor(pire.ratio * 100) / 100, required: requis, fg: n.text.color || "#000000", bg: hex(pire.fond) } });
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
if (n.type === "frame" && n.children.length === 0 && n.style?.fill === void 0 && !n.style?.stroke) {
|
|
541
|
-
issues.push({ rule: "empty-frame", severity: "warning", node: n.id, name: n.name });
|
|
542
|
-
}
|
|
543
|
-
if (n.type === "image" && !n.alt) issues.push({ rule: "image-alt", severity: "warning", node: n.id, name: n.name });
|
|
544
|
-
}
|
|
545
|
-
return { issues };
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
// src/studio/emit/html.js
|
|
549
|
-
var ECHAPPE = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
|
|
550
|
-
var escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ECHAPPE[c]);
|
|
551
|
-
function slug(nom) {
|
|
552
|
-
const s = String(nom).normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
|
|
553
|
-
return /^[a-z]/.test(s) ? s : `n-${s || "noeud"}`;
|
|
554
|
-
}
|
|
555
|
-
function classNames(doc, page) {
|
|
556
|
-
const prises = /* @__PURE__ */ new Set();
|
|
557
|
-
const classes = /* @__PURE__ */ new Map();
|
|
558
|
-
const unique = (base) => {
|
|
559
|
-
let c = base;
|
|
560
|
-
let k = 2;
|
|
561
|
-
while (prises.has(c)) c = `${base}-${k++}`;
|
|
562
|
-
prises.add(c);
|
|
563
|
-
return c;
|
|
564
|
-
};
|
|
565
|
-
const visiter = (id, racine) => {
|
|
566
|
-
const n = doc.nodes[id];
|
|
567
|
-
const c = racine ? unique(`${racine}__${slug(n.name)}`) : unique(slug(n.name));
|
|
568
|
-
classes.set(id, c);
|
|
569
|
-
for (const e of n.children || []) visiter(e, racine || c);
|
|
570
|
-
};
|
|
571
|
-
for (const id of page.frames) visiter(id, null);
|
|
572
|
-
return classes;
|
|
573
|
-
}
|
|
574
|
-
function emitHtml(doc, { page: pageId, assets = {}, title, lang = "fr" } = {}) {
|
|
575
|
-
const page = pageId ? doc.pages.find((p) => p.id === pageId) : doc.pages[0];
|
|
576
|
-
if (!page) throw new StudioError("studio_page_not_found", `Page introuvable : ${pageId}`, void 0, 404);
|
|
577
|
-
const parents = parentsOf(doc);
|
|
578
|
-
const classes = classNames(doc, page);
|
|
579
|
-
const warnings = [];
|
|
580
|
-
const regles = [BASE_CSS];
|
|
581
|
-
const html = (id, profondeur) => {
|
|
582
|
-
const n = doc.nodes[id];
|
|
583
|
-
const c = classes.get(id);
|
|
584
|
-
const decl = nodeCss(n, parents.get(id));
|
|
585
|
-
if (decl.length) regles.push(`.${c}{${decl.map(([p, v]) => `${p}:${v}`).join(";")}}`);
|
|
586
|
-
const tag = tagOf(n);
|
|
587
|
-
const pad = " ".repeat(profondeur);
|
|
588
|
-
if (n.type === "image") {
|
|
589
|
-
const asset = n.image.src.slice("asset:".length);
|
|
590
|
-
if (n.alt === void 0) warnings.push(`image-alt : \xAB ${n.name} \xBB n'a pas de texte alternatif`);
|
|
591
|
-
return `${pad}<img class="${c}" src="${escapeHtml(assets[asset] || `assets/${asset}`)}" alt="${escapeHtml(n.alt ?? "")}">`;
|
|
592
|
-
}
|
|
593
|
-
if (n.type === "text") return `${pad}<${tag} class="${c}">${escapeHtml(n.text.content)}</${tag}>`;
|
|
594
|
-
const enfants = (n.children || []).map((e) => html(e, profondeur + 1));
|
|
595
|
-
return enfants.length ? `${pad}<${tag} class="${c}">
|
|
596
|
-
${enfants.join("\n")}
|
|
597
|
-
${pad}</${tag}>` : `${pad}<${tag} class="${c}"></${tag}>`;
|
|
598
|
-
};
|
|
599
|
-
const corps = page.frames.map((id) => html(id, 2)).join("\n");
|
|
600
|
-
const index = `<!doctype html>
|
|
601
|
-
<html lang="${escapeHtml(lang)}">
|
|
602
|
-
<head>
|
|
603
|
-
<meta charset="utf-8">
|
|
604
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
605
|
-
<title>${escapeHtml(title || page.name)}</title>
|
|
606
|
-
<link rel="stylesheet" href="styles.css">
|
|
607
|
-
</head>
|
|
608
|
-
<body>
|
|
609
|
-
${corps}
|
|
610
|
-
</body>
|
|
611
|
-
</html>
|
|
612
|
-
`;
|
|
613
|
-
const css = `${regles.join("\n")}
|
|
614
|
-
`;
|
|
615
|
-
const octets = (s) => new TextEncoder().encode(s).length;
|
|
616
|
-
return {
|
|
617
|
-
target: "html",
|
|
618
|
-
files: [
|
|
619
|
-
{ path: "index.html", content: index, bytes: octets(index) },
|
|
620
|
-
{ path: "styles.css", content: css, bytes: octets(css) }
|
|
621
|
-
],
|
|
622
|
-
warnings
|
|
623
|
-
};
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
// src/studio/render.js
|
|
627
|
-
function renderPage(doc, { page: pageId, document: d = globalThis.document, assets = {} } = {}) {
|
|
628
|
-
if (!d || typeof d.createElement !== "function") {
|
|
629
|
-
throw new StudioError("studio_render_unavailable", "Le rendu demande un navigateur (aucun DOM ici).");
|
|
630
|
-
}
|
|
631
|
-
const page = pageId ? doc.pages.find((p) => p.id === pageId) : doc.pages[0];
|
|
632
|
-
if (!page) throw new StudioError("studio_page_not_found", `Page introuvable : ${pageId}`, void 0, 404);
|
|
633
|
-
const frag = d.createDocumentFragment();
|
|
634
|
-
const style = d.createElement("style");
|
|
635
|
-
style.textContent = BASE_CSS;
|
|
636
|
-
frag.appendChild(style);
|
|
637
|
-
const parents = parentsOf(doc);
|
|
638
|
-
for (const id of page.frames) frag.appendChild(renderNode(doc, id, { document: d, assets, parents }));
|
|
639
|
-
return frag;
|
|
640
|
-
}
|
|
641
|
-
function renderNode(doc, nodeId, { document: d = globalThis.document, assets = {}, parents = parentsOf(doc) } = {}) {
|
|
642
|
-
if (!d || typeof d.createElement !== "function") {
|
|
643
|
-
throw new StudioError("studio_render_unavailable", "Le rendu demande un navigateur (aucun DOM ici).");
|
|
644
|
-
}
|
|
645
|
-
const creer = (id) => {
|
|
646
|
-
const n = doc.nodes[id];
|
|
647
|
-
const el = d.createElement(tagOf(n));
|
|
648
|
-
el.setAttribute("data-node-id", id);
|
|
649
|
-
for (const [prop, valeur] of nodeCss(n, parents.get(id))) el.style.setProperty(prop, valeur);
|
|
650
|
-
if (n.type === "image") {
|
|
651
|
-
const asset = n.image.src.slice("asset:".length);
|
|
652
|
-
el.setAttribute("src", assets[asset] || `assets/${asset}`);
|
|
653
|
-
el.setAttribute("alt", n.alt ?? "");
|
|
654
|
-
} else if (n.type === "text") {
|
|
655
|
-
el.textContent = n.text.content;
|
|
656
|
-
} else {
|
|
657
|
-
for (const e of n.children || []) el.appendChild(creer(e));
|
|
658
|
-
}
|
|
659
|
-
return el;
|
|
660
|
-
};
|
|
661
|
-
if (!doc.nodes[nodeId]) throw new StudioError("studio_node_not_found", `N\u0153ud introuvable : ${nodeId}`, void 0, 404);
|
|
662
|
-
return creer(nodeId);
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
// src/studio/raster.js
|
|
666
|
-
var XHTML = "http://www.w3.org/1999/xhtml";
|
|
667
|
-
async function enData(url) {
|
|
668
|
-
const reponse = await fetch(url);
|
|
669
|
-
if (!reponse.ok) throw new StudioError("studio_asset_unavailable", `Ressource illisible pour l'export : ${url} (${reponse.status})`);
|
|
670
|
-
const blob = await reponse.blob();
|
|
671
|
-
return await new Promise((ok, ko) => {
|
|
672
|
-
const f = new FileReader();
|
|
673
|
-
f.onload = () => ok(f.result);
|
|
674
|
-
f.onerror = ko;
|
|
675
|
-
f.readAsDataURL(blob);
|
|
676
|
-
});
|
|
677
|
-
}
|
|
678
|
-
async function policesIncorporees(d) {
|
|
679
|
-
const regles = [];
|
|
680
|
-
for (const feuille of d.styleSheets) {
|
|
681
|
-
let liste;
|
|
682
|
-
try {
|
|
683
|
-
liste = feuille.cssRules;
|
|
684
|
-
} catch {
|
|
685
|
-
continue;
|
|
686
|
-
}
|
|
687
|
-
for (const r of liste) {
|
|
688
|
-
if (r.type !== 5) continue;
|
|
689
|
-
let css = r.cssText;
|
|
690
|
-
const base = feuille.href || d.baseURI;
|
|
691
|
-
for (const [, brut] of css.matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)/g)) {
|
|
692
|
-
if (brut.startsWith("data:")) continue;
|
|
693
|
-
css = css.replace(brut, await enData(new URL(brut, base).href));
|
|
694
|
-
}
|
|
695
|
-
regles.push(css);
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
return regles.join("\n");
|
|
699
|
-
}
|
|
700
|
-
function figerLignes(racine, d) {
|
|
701
|
-
for (const el of racine.querySelectorAll("[data-node-id]")) {
|
|
702
|
-
const texte = el.firstChild;
|
|
703
|
-
if (!texte || texte.nodeType !== 3 || el.childNodes.length !== 1) continue;
|
|
704
|
-
const t = texte.textContent;
|
|
705
|
-
const r = d.createRange();
|
|
706
|
-
let haut = null;
|
|
707
|
-
let sortie = "";
|
|
708
|
-
for (let i = 0; i < t.length; i++) {
|
|
709
|
-
r.setStart(texte, i);
|
|
710
|
-
r.setEnd(texte, i + 1);
|
|
711
|
-
const rect = r.getClientRects()[0];
|
|
712
|
-
if (rect && haut !== null && rect.top > haut + 1 && t[i] !== " " && t[i] !== "\n") sortie = `${sortie.replace(/ +$/, "")}
|
|
713
|
-
`;
|
|
714
|
-
if (rect) haut = rect.top;
|
|
715
|
-
sortie += t[i];
|
|
716
|
-
}
|
|
717
|
-
texte.textContent = sortie;
|
|
718
|
-
el.style.setProperty("white-space", "pre");
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
async function renderPng(doc, { frame, scale = 1, assets = {}, document: d = globalThis.document } = {}) {
|
|
722
|
-
const W = globalThis;
|
|
723
|
-
if (!d?.body || typeof W.XMLSerializer !== "function" || typeof W.Image !== "function" || typeof W.fetch !== "function") {
|
|
724
|
-
throw new StudioError("studio_render_unavailable", "L'export d'image se fait dans un navigateur (aucun DOM ici).");
|
|
725
|
-
}
|
|
726
|
-
if (![1, 2, 3, 4].includes(scale)) throw new StudioError("studio_render_invalid", "scale vaut 1, 2, 3 ou 4.", { reason: "scale_1_a_4" });
|
|
727
|
-
const id = doc.nodes[frame]?.type === "frame" ? frame : Object.values(doc.nodes).find((n) => n.type === "frame" && n.name === frame)?.id;
|
|
728
|
-
if (!id) throw new StudioError("studio_node_not_found", `Cadre introuvable : ${frame}`, void 0, 404);
|
|
729
|
-
const hote = d.createElement("div");
|
|
730
|
-
hote.setAttribute("aria-hidden", "true");
|
|
731
|
-
hote.setAttribute("data-studio-raster", "");
|
|
732
|
-
hote.style.cssText = "position:fixed;left:-100000px;top:0;contain:layout style;pointer-events:none";
|
|
733
|
-
const base = d.createElement("style");
|
|
734
|
-
base.textContent = "[data-studio-raster] *,[data-studio-raster] *::before,[data-studio-raster] *::after{box-sizing:border-box;margin:0}";
|
|
735
|
-
hote.append(base, renderNode(doc, id, { document: d, assets }));
|
|
736
|
-
d.body.appendChild(hote);
|
|
737
|
-
try {
|
|
738
|
-
const el = hote.lastChild;
|
|
739
|
-
await d.fonts?.ready;
|
|
740
|
-
await Promise.all([...el.querySelectorAll("img")].map((img) => img.decode().catch(() => {
|
|
741
|
-
})));
|
|
742
|
-
figerLignes(el, d);
|
|
743
|
-
const rect = el.getBoundingClientRect();
|
|
744
|
-
const width = Math.ceil(rect.width);
|
|
745
|
-
const height = Math.ceil(rect.height);
|
|
746
|
-
const copie2 = el.cloneNode(true);
|
|
747
|
-
for (const img of copie2.querySelectorAll("img")) img.setAttribute("src", await enData(new URL(img.getAttribute("src"), d.baseURI).href));
|
|
748
|
-
const polices = await policesIncorporees(d);
|
|
749
|
-
const xhtml = new W.XMLSerializer().serializeToString(copie2);
|
|
750
|
-
const style = `${BASE_CSS}
|
|
751
|
-
${polices}`.replace(/]]>/g, "]]>");
|
|
752
|
-
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width * scale}" height="${height * scale}" viewBox="0 0 ${width} ${height}"><foreignObject x="0" y="0" width="${width}" height="${height}"><div xmlns="${XHTML}"><style><![CDATA[${style}]]></style>${xhtml}</div></foreignObject></svg>`;
|
|
753
|
-
const image = new W.Image();
|
|
754
|
-
image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
|
755
|
-
await image.decode();
|
|
756
|
-
const canvas = d.createElement("canvas");
|
|
757
|
-
canvas.width = Math.round(width * scale);
|
|
758
|
-
canvas.height = Math.round(height * scale);
|
|
759
|
-
canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
|
|
760
|
-
const blob = await new Promise((ok) => canvas.toBlob(ok, "image/png"));
|
|
761
|
-
return { bytes: new Uint8Array(await blob.arrayBuffer()), mime: "image/png", width: canvas.width, height: canvas.height };
|
|
762
|
-
} finally {
|
|
763
|
-
hote.remove();
|
|
764
|
-
}
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
// src/studio/targets.js
|
|
768
|
-
var TARGETS = Object.freeze([
|
|
769
|
-
Object.freeze({ target: "html", status: "available" }),
|
|
770
|
-
Object.freeze({ target: "email", status: "planned", phase: 3 }),
|
|
771
|
-
Object.freeze({ target: "react", status: "planned", phase: 6 })
|
|
772
|
-
]);
|
|
773
|
-
|
|
774
|
-
// src/studio/document.js
|
|
775
|
-
var copie = (v) => v === void 0 ? void 0 : structuredClone(v);
|
|
776
|
-
var StudioDocument = class {
|
|
777
|
-
#doc;
|
|
778
|
-
#passe = [];
|
|
779
|
-
// lots qui défont, du plus ancien au plus récent
|
|
780
|
-
#futur = [];
|
|
781
|
-
// lots qui refont
|
|
782
|
-
#ecoutes = /* @__PURE__ */ new Set();
|
|
783
|
-
/** @param {object} [json] un document enregistré ; absent : un document vide */
|
|
784
|
-
constructor(json) {
|
|
785
|
-
this.#doc = json === void 0 ? createDocument() : assertValid(migrate(structuredClone(json)));
|
|
786
|
-
}
|
|
787
|
-
/* ── Lire ────────────────────────────────────────────────────────────────────────────────── */
|
|
788
|
-
get pages() {
|
|
789
|
-
return this.#doc.pages.map((p) => ({ ...p, frames: [...p.frames] }));
|
|
790
|
-
}
|
|
791
|
-
/** Une copie du nœud : la modifier ne change pas le document (seules les opérations le font). */
|
|
792
|
-
node(id) {
|
|
793
|
-
return copie(this.#doc.nodes[id]) ?? null;
|
|
794
|
-
}
|
|
795
|
-
/** Premier nœud qui correspond, dans l'ordre des pages puis de l'arbre. `{ name, type }` */
|
|
796
|
-
find(critere = {}) {
|
|
797
|
-
return this.findAll(critere)[0] ?? null;
|
|
798
|
-
}
|
|
799
|
-
findAll({ name, type } = {}) {
|
|
800
|
-
const out = [];
|
|
801
|
-
const visiter = (id) => {
|
|
802
|
-
const n = this.#doc.nodes[id];
|
|
803
|
-
if ((name === void 0 || n.name === name) && (type === void 0 || n.type === type)) out.push(copie(n));
|
|
804
|
-
for (const e of n.children || []) visiter(e);
|
|
805
|
-
};
|
|
806
|
-
for (const p of this.#doc.pages) for (const id of p.frames) visiter(id);
|
|
807
|
-
return out;
|
|
808
|
-
}
|
|
809
|
-
/** Le document en forme canonique : deux documents égaux donnent les mêmes octets. */
|
|
810
|
-
toJSON() {
|
|
811
|
-
return structuredClone(canonical(this.#doc));
|
|
812
|
-
}
|
|
813
|
-
/* ── Vérifier, émettre, rendre (P85) ─────────────────────────────────────────────────────── */
|
|
814
|
-
/** → `{ issues: [{ rule, severity, node, name, detail? }] }` */
|
|
815
|
-
check() {
|
|
816
|
-
return check(this.#doc);
|
|
817
|
-
}
|
|
818
|
-
/** → `{ target, files: [{ path, content, bytes }], warnings }`. Phase 1 : `target: "html"` seulement. */
|
|
819
|
-
emit({ target = "html", ...options } = {}) {
|
|
820
|
-
if (target !== "html") {
|
|
821
|
-
const prevue = TARGETS.find((t) => t.target === target);
|
|
822
|
-
throw new StudioError("studio_target_unavailable", prevue ? `La cible \xAB ${target} \xBB arrive en phase ${prevue.phase}.` : `Cible inconnue : ${target}`, { target, available: TARGETS.filter((t) => t.status === "available").map((t) => t.target) }, 501);
|
|
823
|
-
}
|
|
824
|
-
return emitHtml(this.#doc, options);
|
|
825
|
-
}
|
|
826
|
-
/** Un cadre en PNG, dans le navigateur. → `{ bytes, mime, width, height }` ; hors navigateur : `studio_render_unavailable`. */
|
|
827
|
-
async render({ frame, format = "png", scale = 1, assets, document } = {}) {
|
|
828
|
-
if (format !== "png") throw new StudioError("studio_target_unavailable", `Le format \xAB ${format} \xBB n'est pas encore livr\xE9 (phase 2) ; png l'est.`, { format, available: ["png"] }, 501);
|
|
829
|
-
return renderPng(this.#doc, { frame, scale, assets, document });
|
|
830
|
-
}
|
|
831
|
-
/* ── Modifier ────────────────────────────────────────────────────────────────────────────── */
|
|
832
|
-
/** Applique un lot, en entier ou pas du tout. → `{ applied, created, removed }` */
|
|
833
|
-
apply(ops, { source = "user" } = {}) {
|
|
834
|
-
const r = applyOps(this.#doc, ops);
|
|
835
|
-
this.#doc = r.doc;
|
|
836
|
-
this.#passe.push(r.inverse);
|
|
837
|
-
this.#futur = [];
|
|
838
|
-
this.#emettre(ops, source);
|
|
839
|
-
return { applied: ops.length, created: r.created, removed: r.removed };
|
|
840
|
-
}
|
|
841
|
-
set(id, path, value) {
|
|
842
|
-
return this.apply([{ op: "set", id, path, value }]);
|
|
843
|
-
}
|
|
844
|
-
/** Insère un nœud et rend son id. `parent` : id d'un cadre, ou d'une page. */
|
|
845
|
-
insert(parent, node, { index } = {}) {
|
|
846
|
-
return this.apply([{ op: "insert", parent, node, index }]).created[0];
|
|
847
|
-
}
|
|
848
|
-
move(id, { parent, index } = {}) {
|
|
849
|
-
return this.apply([{ op: "move", id, parent, index }]);
|
|
850
|
-
}
|
|
851
|
-
remove(id) {
|
|
852
|
-
return this.apply([{ op: "remove", id }]);
|
|
853
|
-
}
|
|
854
|
-
undo() {
|
|
855
|
-
return this.#deplacer(this.#passe, this.#futur, "undo");
|
|
856
|
-
}
|
|
857
|
-
redo() {
|
|
858
|
-
return this.#deplacer(this.#futur, this.#passe, "redo");
|
|
859
|
-
}
|
|
860
|
-
history() {
|
|
861
|
-
return { undo: this.#passe.length, redo: this.#futur.length };
|
|
862
|
-
}
|
|
863
|
-
/** Écoute les changements ; rend la fonction qui arrête l'écoute. `e = { ops, source }` */
|
|
864
|
-
on(evenement, fn) {
|
|
865
|
-
if (evenement !== "change") throw new StudioError("studio_event_unknown", `\xC9v\xE9nement inconnu : ${evenement}`);
|
|
866
|
-
this.#ecoutes.add(fn);
|
|
867
|
-
return () => this.#ecoutes.delete(fn);
|
|
868
|
-
}
|
|
869
|
-
#deplacer(depuis, vers, source) {
|
|
870
|
-
const lot = depuis.pop();
|
|
871
|
-
if (!lot) return false;
|
|
872
|
-
const r = applyOps(this.#doc, lot, { internal: true });
|
|
873
|
-
this.#doc = r.doc;
|
|
874
|
-
vers.push(r.inverse);
|
|
875
|
-
this.#emettre(lot, source);
|
|
876
|
-
return true;
|
|
877
|
-
}
|
|
878
|
-
#emettre(ops, source) {
|
|
879
|
-
for (const fn of this.#ecoutes) {
|
|
880
|
-
try {
|
|
881
|
-
fn({ ops: copie(ops), source });
|
|
882
|
-
} catch {
|
|
883
|
-
}
|
|
884
|
-
}
|
|
885
|
-
}
|
|
886
|
-
};
|
|
887
|
-
export {
|
|
888
|
-
BASE_CSS,
|
|
889
|
-
FORMAT,
|
|
890
|
-
FORMAT_VERSION,
|
|
891
|
-
NODE_TYPES,
|
|
892
|
-
StudioDocument,
|
|
893
|
-
StudioError,
|
|
894
|
-
TARGETS,
|
|
895
|
-
applyOps,
|
|
896
|
-
check,
|
|
897
|
-
contrastRatio,
|
|
898
|
-
createDocument,
|
|
899
|
-
emitHtml,
|
|
900
|
-
migrate,
|
|
901
|
-
nodeCss,
|
|
902
|
-
renderNode,
|
|
903
|
-
renderPage,
|
|
904
|
-
renderPng,
|
|
905
|
-
validate,
|
|
906
|
-
validateNode
|
|
907
|
-
};
|