@poadio/app-core 0.1.0 → 0.3.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/app.d.ts +2 -0
  3. package/dist/app.d.ts.map +1 -1
  4. package/dist/app.js +5 -1
  5. package/dist/app.js.map +1 -1
  6. package/dist/catalog.d.ts +100 -0
  7. package/dist/catalog.d.ts.map +1 -0
  8. package/dist/catalog.js +538 -0
  9. package/dist/catalog.js.map +1 -0
  10. package/dist/designer.d.ts +4 -0
  11. package/dist/designer.d.ts.map +1 -0
  12. package/dist/designer.js +6 -0
  13. package/dist/designer.js.map +1 -0
  14. package/dist/draft-toolbar.d.ts +59 -0
  15. package/dist/draft-toolbar.d.ts.map +1 -0
  16. package/dist/draft-toolbar.js +74 -0
  17. package/dist/draft-toolbar.js.map +1 -0
  18. package/dist/grid.d.ts +83 -0
  19. package/dist/grid.d.ts.map +1 -0
  20. package/dist/grid.js +188 -0
  21. package/dist/grid.js.map +1 -0
  22. package/dist/index.d.ts +9 -1
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +4 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/model.d.ts +7 -2
  27. package/dist/model.d.ts.map +1 -1
  28. package/dist/model.js +7 -1
  29. package/dist/model.js.map +1 -1
  30. package/dist/nonvisual.d.ts +42 -0
  31. package/dist/nonvisual.d.ts.map +1 -0
  32. package/dist/nonvisual.js +89 -0
  33. package/dist/nonvisual.js.map +1 -0
  34. package/dist/preview.d.ts +13 -1
  35. package/dist/preview.d.ts.map +1 -1
  36. package/dist/preview.js +10 -2
  37. package/dist/preview.js.map +1 -1
  38. package/package.json +6 -1
  39. package/schema/front.v1.json +35 -2
  40. package/src/app.ts +5 -1
  41. package/src/catalog.ts +611 -0
  42. package/src/designer.ts +5 -0
  43. package/src/draft-toolbar.ts +104 -0
  44. package/src/grid.ts +189 -0
  45. package/src/index.ts +19 -1
  46. package/src/model.ts +9 -3
  47. package/src/nonvisual.ts +90 -0
  48. package/src/preview.ts +15 -3
@@ -0,0 +1,5 @@
1
+ // @poadio/app-core/designer : ce dont le designer de la console a besoin (catalogue des composants, gestes sur la
2
+ // grille), sans le schéma JSON ni le reste du moteur. Mêmes fonctions que l'entrée principale.
3
+ export * from './catalog.js';
4
+ export * from './grid.js';
5
+ export * from './nonvisual.js';
@@ -0,0 +1,104 @@
1
+ // Barre du brouillon : la petite barre flottante de la Lecture du brouillon (cookie de lecture posé par le lien de la
2
+ // console), jamais montrée à un visiteur. Ici l'état et ses règles, sans DOM : largeur d'écran simulée, thème, barre
3
+ // repliée ou fermée, côté de l'écran ; ce qui est gardé pour l'onglet (sessionStorage) ; ce qui est écrit dans le
4
+ // puits de logs. Jamais de lien vers la console ni de copie du lien du brouillon : il ne doit pas circuler.
5
+ import type { Theme } from './preview.js';
6
+
7
+ export type DraftDevice = 'desktop' | 'tablet' | 'phone';
8
+ /** Les mêmes largeurs que les tailles d'écran du designer de la console */
9
+ export const DRAFT_DEVICE_WIDTHS: Readonly<Record<DraftDevice, number>> = { desktop: 1280, tablet: 820, phone: 390 };
10
+ export const DRAFT_DEVICES: readonly DraftDevice[] = ['desktop', 'tablet', 'phone'];
11
+
12
+ export type DraftToolbarState = {
13
+ device: DraftDevice;
14
+ /** Thème choisi dans la barre ; null : celui du système */
15
+ theme: Theme | null;
16
+ collapsed: boolean;
17
+ side: 'left' | 'right';
18
+ /** Fermée pour cet onglet */
19
+ closed: boolean;
20
+ };
21
+
22
+ export const DRAFT_TOOLBAR_DEFAULT: DraftToolbarState = { device: 'desktop', theme: null, collapsed: false, side: 'left', closed: false };
23
+
24
+ /** Clé de l'onglet (sessionStorage), par front */
25
+ export const draftToolbarKey = (frontId: string) => `poad.draft-toolbar.${frontId}`;
26
+
27
+ const isDevice = (v: unknown): v is DraftDevice => v === 'desktop' || v === 'tablet' || v === 'phone';
28
+
29
+ /** L'état gardé pour l'onglet ; ce qui est absent ou illisible prend la valeur par défaut */
30
+ export const readDraftToolbar = (raw: string | null | undefined): DraftToolbarState => {
31
+ let v: Record<string, unknown> = {};
32
+ try {
33
+ const parsed: unknown = raw ? JSON.parse(raw) : {};
34
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) v = parsed as Record<string, unknown>;
35
+ } catch {
36
+ /* illisible : valeurs par défaut */
37
+ }
38
+ return {
39
+ device: isDevice(v['device']) ? v['device'] : DRAFT_TOOLBAR_DEFAULT.device,
40
+ theme: v['theme'] === 'light' || v['theme'] === 'dark' ? v['theme'] : null,
41
+ collapsed: v['collapsed'] === true,
42
+ side: v['side'] === 'right' ? 'right' : 'left',
43
+ closed: v['closed'] === true,
44
+ };
45
+ };
46
+
47
+ export const writeDraftToolbar = (s: DraftToolbarState): string => JSON.stringify(s);
48
+
49
+ export type DraftToolbarAction =
50
+ | { type: 'device'; device: DraftDevice }
51
+ | { type: 'theme'; theme: Theme }
52
+ | { type: 'collapse' }
53
+ | { type: 'expand' }
54
+ | { type: 'move' }
55
+ | { type: 'close' }
56
+ | { type: 'reload' }
57
+ | { type: 'page'; page: string };
58
+
59
+ /** L'état après un geste (recharger et aller à une page ne changent pas l'état de la barre) */
60
+ export const draftToolbarReduce = (s: DraftToolbarState, a: DraftToolbarAction): DraftToolbarState => {
61
+ switch (a.type) {
62
+ case 'device':
63
+ return { ...s, device: a.device };
64
+ case 'theme':
65
+ return { ...s, theme: a.theme };
66
+ case 'collapse':
67
+ return { ...s, collapsed: true };
68
+ case 'expand':
69
+ return { ...s, collapsed: false };
70
+ case 'move':
71
+ return { ...s, side: s.side === 'left' ? 'right' : 'left' };
72
+ case 'close':
73
+ return { ...s, closed: true };
74
+ default:
75
+ return s;
76
+ }
77
+ };
78
+
79
+ /**
80
+ * Largeur où contenir la page pour la taille choisie, dans une fenêtre de `available` pixels ; null : aucune.
81
+ * Ordinateur : jamais de cadre, la page occupe toute la fenêtre comme pour un vrai visiteur (le moteur publié ne
82
+ * borne pas la largeur). Tablette et Téléphone : la page contenue à leur largeur, si la fenêtre est plus large.
83
+ */
84
+ export const draftFrameWidth = (device: DraftDevice, available: number): number | null => {
85
+ if (device === 'desktop') return null;
86
+ const w = DRAFT_DEVICE_WIDTHS[device];
87
+ return available > w ? w : null;
88
+ };
89
+
90
+ /**
91
+ * Sens du chevron qui replie ou déplie la barre : il montre où la barre va. Dépliée à gauche, elle se replie vers la
92
+ * gauche ; repliée à gauche, elle se déplie vers la droite ; l'inverse quand elle est à droite.
93
+ */
94
+ export const draftFoldIcon = (s: Pick<DraftToolbarState, 'collapsed' | 'side'>): 'chevron-left' | 'chevron-right' =>
95
+ (s.side === 'left') === !s.collapsed ? 'chevron-left' : 'chevron-right';
96
+
97
+ /** La ligne du puits de logs pour un geste : l'action et ses valeurs, jamais de jeton ni de cookie */
98
+ export const draftToolbarLog = (a: DraftToolbarAction): { msg: string; attrs: Record<string, string> } => {
99
+ const attrs: Record<string, string> = { action: a.type };
100
+ if (a.type === 'device') attrs['device'] = a.device;
101
+ if (a.type === 'theme') attrs['theme'] = a.theme;
102
+ if (a.type === 'page') attrs['target'] = a.page;
103
+ return { msg: `barre du brouillon : ${a.type}`, attrs };
104
+ };
package/src/grid.ts ADDED
@@ -0,0 +1,189 @@
1
+ // Éléments posés sur la grille d'une page (section `grid`) : format, validation et gestes du designer, en fonctions
2
+ // pures. La console les emploie pour poser, déplacer, redimensionner et retirer ; le moteur pour valider et
3
+ // afficher. Aucune fonction ne modifie son entrée : chacune rend une nouvelle liste.
4
+ //
5
+ // { id, type, x, y, w, h, props } x : colonne (0 à 23), y : ligne (0…), w : largeur en colonnes, h : hauteur en
6
+ // lignes de `rowHeight` px ; props : les propriétés du type (catalog.ts)
7
+ import { catalogEntry, checkPropValue, defaultProps, type CatalogLang, type GridSize, type PropValue } from './catalog.js';
8
+
9
+ export const GRID_COLS = 24;
10
+ /** Éléments par grille, au plus (le schéma le dit aussi) */
11
+ export const MAX_ITEMS = 200;
12
+ /** Lignes d'une grille, au plus : y + h ≤ MAX_ROWS */
13
+ export const MAX_ROWS = 500;
14
+ export const ITEM_ID_RE = /^[a-z][a-z0-9-]{0,39}$/;
15
+
16
+ export type GridItem = { id: string; type: string; x: number; y: number; w: number; h: number; props: Record<string, unknown> };
17
+ export type Rect = { x: number; y: number; w: number; h: number };
18
+ export type Cell = { x: number; y: number };
19
+ export type GridIssue = { path: string; message: string };
20
+
21
+ export const overlaps = (a: Rect, b: Rect): boolean => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
22
+
23
+ export const inBounds = (r: Rect): boolean =>
24
+ Number.isInteger(r.x) && Number.isInteger(r.y) && Number.isInteger(r.w) && Number.isInteger(r.h) &&
25
+ r.x >= 0 && r.y >= 0 && r.w >= 1 && r.h >= 1 && r.x + r.w <= GRID_COLS && r.y + r.h <= MAX_ROWS;
26
+
27
+ /** La place est-elle libre (dans la grille, sans chevaucher un autre élément que `ignore`) ? */
28
+ export const fits = (items: readonly GridItem[], r: Rect, ignore?: string): boolean => inBounds(r) && !items.some((i) => i.id !== ignore && overlaps(i, r));
29
+
30
+ /** Nombre de lignes occupées (le bas du dernier élément) */
31
+ export const gridRows = (items: readonly GridItem[]): number => items.reduce((m, i) => Math.max(m, i.y + i.h), 0);
32
+
33
+ const minSize = (type: string): GridSize => catalogEntry(type)?.min ?? { w: 1, h: 1 };
34
+
35
+ /** Taille ramenée dans la grille et au-dessus du minimum du type */
36
+ export const clampSize = (type: string, w: number, h: number): GridSize => {
37
+ const min = minSize(type);
38
+ return {
39
+ w: Math.min(GRID_COLS, Math.max(min.w, Math.round(w) || min.w)),
40
+ h: Math.min(MAX_ROWS, Math.max(min.h, Math.round(h) || min.h)),
41
+ };
42
+ };
43
+
44
+ /** Position ramenée dans la grille pour une taille donnée */
45
+ export const clampCell = (cell: Cell, size: GridSize): Cell => ({
46
+ x: Math.min(GRID_COLS - size.w, Math.max(0, Math.round(cell.x) || 0)),
47
+ y: Math.min(MAX_ROWS - size.h, Math.max(0, Math.round(cell.y) || 0)),
48
+ });
49
+
50
+ /**
51
+ * La place libre la plus proche de `near` pour un élément de taille `size` (null : la grille est pleine).
52
+ * Sans `near` : la première place libre, ligne par ligne, de gauche à droite. Distance : euclidienne en cellules,
53
+ * à égalité la plus haute puis la plus à gauche.
54
+ */
55
+ export const findFreeSpot = (items: readonly GridItem[], size: GridSize, near?: Cell, ignore?: string): Cell | null => {
56
+ if (size.w > GRID_COLS || size.h > MAX_ROWS) return null;
57
+ const others = ignore ? items.filter((i) => i.id !== ignore) : items;
58
+ const lastRow = Math.min(MAX_ROWS - size.h, gridRows(others));
59
+ if (!near) {
60
+ for (let y = 0; y <= lastRow; y++) for (let x = 0; x + size.w <= GRID_COLS; x++) if (fits(others, { x, y, ...size })) return { x, y };
61
+ return null;
62
+ }
63
+ const target = clampCell(near, size);
64
+ if (fits(others, { ...target, ...size })) return target;
65
+ let best: Cell | null = null;
66
+ let bestD = Infinity;
67
+ // Au-delà du dernier élément tout est libre : chercher jusqu'à la ligne de la cible, ou juste sous le dernier
68
+ const maxY = Math.min(MAX_ROWS - size.h, Math.max(lastRow, target.y));
69
+ for (let y = 0; y <= maxY; y++) {
70
+ const dy = y - target.y;
71
+ if (dy * dy > bestD) {
72
+ if (y > target.y) break;
73
+ continue;
74
+ }
75
+ for (let x = 0; x + size.w <= GRID_COLS; x++) {
76
+ const dx = x - target.x;
77
+ const d = dx * dx + dy * dy;
78
+ if (d < bestD && fits(others, { x, y, ...size })) {
79
+ best = { x, y };
80
+ bestD = d;
81
+ }
82
+ }
83
+ }
84
+ return best;
85
+ };
86
+
87
+ /** Un identifiant libre pour un nouvel élément : <type>-<n>, le plus petit n libre */
88
+ export const newItemId = (items: readonly GridItem[], type: string): string => {
89
+ const base = /^[a-z][a-z0-9-]{0,33}$/.test(type) ? type : 'item';
90
+ const used = new Set(items.map((i) => i.id));
91
+ for (let n = 1; ; n++) if (!used.has(`${base}-${n}`)) return `${base}-${n}`;
92
+ };
93
+
94
+ export type AddResult = { items: GridItem[]; item: GridItem } | { items: GridItem[]; item: null; reason: 'unknown_type' | 'non_visual' | 'full' };
95
+
96
+ /**
97
+ * Pose un composant du catalogue : à sa taille par défaut, à la place libre la plus proche de `at` (glisser-déposer)
98
+ * ou à la première place libre (clic), avec ses props par défaut dans la langue de la console.
99
+ */
100
+ export const addItem = (items: readonly GridItem[], type: string, options: { at?: Cell; lang?: CatalogLang; id?: string } = {}): AddResult => {
101
+ const entry = catalogEntry(type);
102
+ if (!entry) return { items: [...items], item: null, reason: 'unknown_type' };
103
+ // Un composant non visuel va dans le bac de la page (nonvisual.ts), jamais sur la grille
104
+ if (entry.nonVisual) return { items: [...items], item: null, reason: 'non_visual' };
105
+ if (items.length >= MAX_ITEMS) return { items: [...items], item: null, reason: 'full' };
106
+ const size = clampSize(type, entry.size.w, entry.size.h);
107
+ const spot = findFreeSpot(items, size, options.at);
108
+ if (!spot) return { items: [...items], item: null, reason: 'full' };
109
+ const id = options.id && ITEM_ID_RE.test(options.id) && !items.some((i) => i.id === options.id) ? options.id : newItemId(items, type);
110
+ const item: GridItem = { id, type, ...spot, ...size, props: defaultProps(type, options.lang ?? 'fr') };
111
+ return { items: [...items, item], item };
112
+ };
113
+
114
+ /** Déplace un élément vers `to` ; occupé : la place libre la plus proche. Introuvable ou sans place : inchangé. */
115
+ export const moveItem = (items: readonly GridItem[], id: string, to: Cell): GridItem[] => {
116
+ const item = items.find((i) => i.id === id);
117
+ if (!item) return [...items];
118
+ const spot = findFreeSpot(items, { w: item.w, h: item.h }, to, id);
119
+ if (!spot || (spot.x === item.x && spot.y === item.y)) return [...items];
120
+ return items.map((i) => (i.id === id ? { ...i, ...spot } : i));
121
+ };
122
+
123
+ /**
124
+ * Redimensionne un élément (son coin haut-gauche reste en place) : taille bornée par le minimum du type et la
125
+ * grille ; si la nouvelle taille chevauche un voisin, la plus grande taille libre entre l'ancienne et la demandée.
126
+ */
127
+ export const resizeItem = (items: readonly GridItem[], id: string, size: GridSize): GridItem[] => {
128
+ const item = items.find((i) => i.id === id);
129
+ if (!item) return [...items];
130
+ const want = clampSize(item.type, size.w, size.h);
131
+ want.w = Math.min(want.w, GRID_COLS - item.x);
132
+ want.h = Math.min(want.h, MAX_ROWS - item.y);
133
+ const free = (w: number, h: number) => fits(items, { x: item.x, y: item.y, w, h }, id);
134
+ let w = want.w;
135
+ let h = want.h;
136
+ // Reculer vers l'ancienne taille, largeur puis hauteur, jusqu'à une place libre
137
+ while (!free(w, h) && (w !== item.w || h !== item.h)) {
138
+ if (w !== item.w) w += w > item.w ? -1 : 1;
139
+ else h += h > item.h ? -1 : 1;
140
+ }
141
+ if (w === item.w && h === item.h) return [...items];
142
+ return items.map((i) => (i.id === id ? { ...i, w, h } : i));
143
+ };
144
+
145
+ export const removeItem = (items: readonly GridItem[], id: string): GridItem[] => items.filter((i) => i.id !== id);
146
+
147
+ /** Change des props d'un élément (les autres gardent leur valeur) */
148
+ export const updateItemProps = (items: readonly GridItem[], id: string, patch: Record<string, PropValue>): GridItem[] =>
149
+ items.map((i) => (i.id === id ? { ...i, props: { ...i.props, ...patch } } : i));
150
+
151
+ /** Ordre de lecture (rangées puis colonnes) : l'ordre des calques, et l'empilement sur un petit écran */
152
+ export const readingOrder = (items: readonly GridItem[]): GridItem[] => [...items].sort((a, b) => a.y - b.y || a.x - b.x || a.id.localeCompare(b.id));
153
+
154
+ /**
155
+ * Ce qu'un schéma JSON ne dit pas des éléments d'une grille : type connu du catalogue, place dans les 24 colonnes,
156
+ * taille minimale du type, identifiants uniques, aucun chevauchement, props connues et du bon type.
157
+ */
158
+ export const validateGridItems = (items: readonly GridItem[], base = ''): GridIssue[] => {
159
+ const out: GridIssue[] = [];
160
+ const ids = new Set<string>();
161
+ items.forEach((it, i) => {
162
+ const at = `${base}/items[${i}]`;
163
+ if (ids.has(it.id)) out.push({ path: `${at}/id`, message: `duplicate item id "${it.id}"` });
164
+ ids.add(it.id);
165
+ const entry = catalogEntry(it.type);
166
+ if (!entry) {
167
+ out.push({ path: `${at}/type`, message: `unknown component type "${it.type}"` });
168
+ return;
169
+ }
170
+ if (entry.nonVisual) {
171
+ out.push({ path: `${at}/type`, message: `non-visual component "${it.type}" cannot be placed on the grid` });
172
+ return;
173
+ }
174
+ if (!inBounds(it)) out.push({ path: at, message: `out of the ${GRID_COLS}-column grid (x + w ≤ ${GRID_COLS}, y + h ≤ ${MAX_ROWS})` });
175
+ if (it.w < entry.min.w || it.h < entry.min.h) out.push({ path: at, message: `smaller than the minimum size of "${it.type}" (${entry.min.w}×${entry.min.h})` });
176
+ for (const [k, v] of Object.entries(it.props ?? {})) {
177
+ const spec = entry.props.find((p) => p.key === k);
178
+ if (!spec) out.push({ path: `${at}/props/${k}`, message: `unknown property of "${it.type}"` });
179
+ else {
180
+ const m = checkPropValue(spec, v);
181
+ if (m) out.push({ path: `${at}/props/${k}`, message: m });
182
+ }
183
+ }
184
+ });
185
+ for (let i = 0; i < items.length; i++)
186
+ for (let j = i + 1; j < items.length; j++)
187
+ if (overlaps(items[i]!, items[j]!)) out.push({ path: `${base}/items[${j}]`, message: `overlaps item "${items[i]!.id}"` });
188
+ return out;
189
+ };
package/src/index.ts CHANGED
@@ -12,10 +12,28 @@ export type { AuthPort, AuthResult, FrontUser, PoadAuthLike } from './auth.js';
12
12
  export { createFrontLogger, sanitizeLine, maskText, MAX_BATCH, MAX_PER_MINUTE } from './logs.js';
13
13
  export type { FrontLogger, BrowserLogLine, LogLevel, LogSender } from './logs.js';
14
14
  export { PROTOCOL, previewModeOf, createPreviewBridge } from './preview.js';
15
- export type { PreviewMode, PreviewOptions, ViewAs, Theme, ToConsole, ToFront, PreviewWindow, PreviewHandlers } from './preview.js';
15
+ export type { PreviewMode, PreviewOptions, ViewAs, Theme, ToConsole, ToFront, PreviewWindow, PreviewHandlers, GridLayout } from './preview.js';
16
16
  export { runActions, fail, ActionFailure } from './actions.js';
17
17
  export type { Action, AppContext, Handler, HandlerRegistry, RunResult } from './actions.js';
18
18
  export { createFrontApp, isFrontConfig } from './app.js';
19
19
  export type { FrontApp, FrontAppOptions, FrontConfig, AppState, Mode, Status } from './app.js';
20
20
  export { toFiles, fromFiles } from './files.js';
21
21
  export type { FrontFiles } from './files.js';
22
+ export {
23
+ CATEGORIES, CATALOG, CATALOG_TYPES, VISUAL_TYPES, NONVISUAL_TYPES, isNonVisual, catalogEntry, catalogLang, localize, defaultValue, defaultProps, resolveProps, checkPropValue, searchCatalog,
24
+ MAX_TEXT, MAX_LONGTEXT, MAX_LINES, MAX_LINE,
25
+ } from './catalog.js';
26
+ export type { CatalogEntry, CatalogLang, Category, CategoryId, GridSize, Localized, PropKind, PropOption, PropSpec, PropValue } from './catalog.js';
27
+ export {
28
+ GRID_COLS, MAX_ITEMS, MAX_ROWS, ITEM_ID_RE, overlaps, inBounds, fits, gridRows, clampSize, clampCell, findFreeSpot, newItemId, addItem, moveItem,
29
+ resizeItem, removeItem, updateItemProps, readingOrder, validateGridItems,
30
+ } from './grid.js';
31
+ export type { GridItem, Rect, Cell, GridIssue, AddResult } from './grid.js';
32
+ export {
33
+ DRAFT_DEVICE_WIDTHS, DRAFT_DEVICES, DRAFT_TOOLBAR_DEFAULT, draftToolbarKey, readDraftToolbar, writeDraftToolbar, draftToolbarReduce, draftFrameWidth, draftFoldIcon, draftToolbarLog,
34
+ } from './draft-toolbar.js';
35
+ export type { DraftDevice, DraftToolbarState, DraftToolbarAction } from './draft-toolbar.js';
36
+ export {
37
+ MAX_NONVISUAL, NONVISUAL_ID_RE, NONVISUAL_NAME_RE, newNonVisualName, addNonVisual, renameNonVisual, removeNonVisual, updateNonVisualProps, validateNonVisual,
38
+ } from './nonvisual.js';
39
+ export type { NonVisualItem, NonVisualIssue, AddNonVisualResult, RenameResult } from './nonvisual.js';
package/src/model.ts CHANGED
@@ -4,6 +4,8 @@
4
4
  // viennent de la configuration servie par l'engine (front.json), jamais de la définition.
5
5
  import schema from '../schema/front.v1.json' with { type: 'json' };
6
6
  import { checkSchema, type SchemaIssue } from './json-schema.js';
7
+ import { validateGridItems, type GridItem } from './grid.js';
8
+ import { validateNonVisual, type NonVisualItem } from './nonvisual.js';
7
9
 
8
10
  export const FORMAT = 'poad.front/1' as const;
9
11
  export const FRONT_SCHEMA: unknown = schema;
@@ -16,10 +18,12 @@ export type UnderConstructionSection = {
16
18
  type: 'under-construction';
17
19
  props: { project?: string; front?: string; message?: string };
18
20
  };
19
- export type GridSection = { id: string; type: 'grid'; cols: 24; rowHeight: number; items: [] };
21
+ /** Grille de 24 colonnes : les composants posés (grid.ts) */
22
+ export type GridSection = { id: string; type: 'grid'; cols: 24; rowHeight: number; items: GridItem[] };
20
23
  export type Section = UnderConstructionSection | GridSection;
21
24
 
22
- export type Page = { id: string; title: string; path: string; auth: PageAuth; sections: Section[] };
25
+ /** nonVisual : les composants non visuels de la page (bac du designer) ; absent = aucun */
26
+ export type Page = { id: string; title: string; path: string; auth: PageAuth; sections: Section[]; nonVisual?: NonVisualItem[] };
23
27
 
24
28
  /** Position d'un cadre de page sur le plan de travail de la console (coordonnées du plan, en pixels) */
25
29
  export type FramePosition = { page: string; x: number; y: number };
@@ -101,7 +105,7 @@ export type Validation = { ok: true; front: FrontDefinition } | { ok: false; iss
101
105
 
102
106
  /**
103
107
  * Valide une définition : le schéma JSON (front.v1.json), puis ce qu'un schéma ne dit pas (identifiants et
104
- * adresses de pages uniques, page d'accueil existante).
108
+ * adresses de pages uniques, page d'accueil existante, éléments des grilles : grid.ts).
105
109
  */
106
110
  export const validateFront = (value: unknown): Validation => {
107
111
  const issues = checkSchema(schema, value);
@@ -119,7 +123,9 @@ export const validateFront = (value: unknown): Validation => {
119
123
  p.sections.forEach((s, j) => {
120
124
  if (sections.has(s.id)) out.push({ path: `/pages[${i}]/sections[${j}]/id`, message: `duplicate section id "${s.id}"` });
121
125
  sections.add(s.id);
126
+ if (s.type === 'grid') out.push(...validateGridItems(s.items, `/pages[${i}]/sections[${j}]`));
122
127
  });
128
+ if (p.nonVisual) out.push(...validateNonVisual(p.nonVisual, `/pages[${i}]`));
123
129
  });
124
130
  if (!ids.has(front.home)) out.push({ path: '/home', message: `unknown page "${front.home}"` });
125
131
  const placed = new Set<string>();
@@ -0,0 +1,90 @@
1
+ // Composants non visuels d'une page (à la manière de Delphi ou Visual Basic) : une source de données, une minuterie,
2
+ // une boîte de dialogue, une notification, une confirmation, une action, une variable. Ils vivent dans le bac
3
+ // « Composants non visuels » du designer et dans `page.nonVisual`, jamais sur la grille. À cette étape ils n'ont que
4
+ // leurs propriétés minimales : le moteur ne les instancie pas encore (liaison aux données et événements : étapes 2 et 3).
5
+ //
6
+ // { id, type, name, props } name : un nom unique dans la page, lisible (store1, timer1…), renommable
7
+ import { catalogEntry, checkPropValue, defaultProps, type CatalogLang, type PropValue } from './catalog.js';
8
+
9
+ export type NonVisualItem = { id: string; type: string; name: string; props: Record<string, unknown> };
10
+ export type NonVisualIssue = { path: string; message: string };
11
+
12
+ /** Composants non visuels par page, au plus (le schéma le dit aussi) */
13
+ export const MAX_NONVISUAL = 50;
14
+ export const NONVISUAL_ID_RE = /^[a-z][a-z0-9-]{0,39}$/;
15
+ /** Un nom : une lettre, puis lettres, chiffres ou _ (40 au plus) — utilisable plus tard dans les expressions */
16
+ export const NONVISUAL_NAME_RE = /^[A-Za-z][A-Za-z0-9_]{0,39}$/;
17
+
18
+ /** Le premier nom libre pour un type : store1, store2… */
19
+ export const newNonVisualName = (list: readonly NonVisualItem[], type: string): string => {
20
+ const base = type.replace(/[^A-Za-z0-9]/g, '') || 'composant';
21
+ const taken = new Set(list.map((n) => n.name.toLowerCase()));
22
+ for (let i = 1; ; i++) if (!taken.has(`${base}${i}`.toLowerCase())) return `${base}${i}`;
23
+ };
24
+
25
+ const newId = (list: readonly NonVisualItem[], type: string): string => {
26
+ const base = /^[a-z][a-z0-9-]{0,33}$/.test(type) ? type : 'nv';
27
+ const used = new Set(list.map((n) => n.id));
28
+ for (let i = 1; ; i++) if (!used.has(`${base}-${i}`)) return `${base}-${i}`;
29
+ };
30
+
31
+ export type AddNonVisualResult = { list: NonVisualItem[]; item: NonVisualItem } | { list: NonVisualItem[]; item: null; reason: 'unknown_type' | 'visual' | 'full' };
32
+
33
+ /** Ajoute un composant non visuel du catalogue, avec un nom libre et ses props par défaut */
34
+ export const addNonVisual = (list: readonly NonVisualItem[], type: string, lang: CatalogLang = 'fr'): AddNonVisualResult => {
35
+ const entry = catalogEntry(type);
36
+ if (!entry) return { list: [...list], item: null, reason: 'unknown_type' };
37
+ if (!entry.nonVisual) return { list: [...list], item: null, reason: 'visual' };
38
+ if (list.length >= MAX_NONVISUAL) return { list: [...list], item: null, reason: 'full' };
39
+ const item: NonVisualItem = { id: newId(list, type), type, name: newNonVisualName(list, type), props: defaultProps(type, lang) };
40
+ return { list: [...list, item], item };
41
+ };
42
+
43
+ export type RenameResult = { list: NonVisualItem[]; error: null } | { list: NonVisualItem[]; error: 'invalid' | 'taken' | 'unknown' };
44
+
45
+ /** Renomme ; le nom doit être valide et libre dans la page (sans tenir compte de la casse) */
46
+ export const renameNonVisual = (list: readonly NonVisualItem[], id: string, name: string): RenameResult => {
47
+ const n = name.trim();
48
+ if (!list.some((x) => x.id === id)) return { list: [...list], error: 'unknown' };
49
+ if (!NONVISUAL_NAME_RE.test(n)) return { list: [...list], error: 'invalid' };
50
+ if (list.some((x) => x.id !== id && x.name.toLowerCase() === n.toLowerCase())) return { list: [...list], error: 'taken' };
51
+ return { list: list.map((x) => (x.id === id ? { ...x, name: n } : x)), error: null };
52
+ };
53
+
54
+ export const removeNonVisual = (list: readonly NonVisualItem[], id: string): NonVisualItem[] => list.filter((x) => x.id !== id);
55
+
56
+ export const updateNonVisualProps = (list: readonly NonVisualItem[], id: string, patch: Record<string, PropValue>): NonVisualItem[] =>
57
+ list.map((x) => (x.id === id ? { ...x, props: { ...x.props, ...patch } } : x));
58
+
59
+ /** Ce qu'un schéma ne dit pas : type non visuel connu, identifiants et noms uniques, props du type */
60
+ export const validateNonVisual = (list: readonly NonVisualItem[], base = ''): NonVisualIssue[] => {
61
+ const out: NonVisualIssue[] = [];
62
+ const ids = new Set<string>();
63
+ const names = new Set<string>();
64
+ list.forEach((it, i) => {
65
+ const at = `${base}/nonVisual[${i}]`;
66
+ if (ids.has(it.id)) out.push({ path: `${at}/id`, message: `duplicate component id "${it.id}"` });
67
+ ids.add(it.id);
68
+ const lower = String(it.name).toLowerCase();
69
+ if (names.has(lower)) out.push({ path: `${at}/name`, message: `duplicate component name "${it.name}"` });
70
+ names.add(lower);
71
+ const entry = catalogEntry(it.type);
72
+ if (!entry) {
73
+ out.push({ path: `${at}/type`, message: `unknown component type "${it.type}"` });
74
+ return;
75
+ }
76
+ if (!entry.nonVisual) {
77
+ out.push({ path: `${at}/type`, message: `visual component "${it.type}" belongs on the grid` });
78
+ return;
79
+ }
80
+ for (const [k, v] of Object.entries(it.props ?? {})) {
81
+ const spec = entry.props.find((p) => p.key === k);
82
+ if (!spec) out.push({ path: `${at}/props/${k}`, message: `unknown property of "${it.type}"` });
83
+ else {
84
+ const m = checkPropValue(spec, v);
85
+ if (m) out.push({ path: `${at}/props/${k}`, message: m });
86
+ }
87
+ }
88
+ });
89
+ return out;
90
+ };
package/src/preview.ts CHANGED
@@ -2,7 +2,9 @@
2
2
  //
3
3
  // iframe : <adresse du front><chemin de la page>?poad_preview=canvas|play
4
4
  // moteur → console { type: 'poad:front:ready', protocol: 1 }
5
- // { type: 'poad:front:rendered', page, width, height }
5
+ // { type: 'poad:front:rendered', page, width, height, grids? }
6
+ // grids : la place de chaque grille dans la page (px de l'iframe) — la console y dessine la
7
+ // sélection, les poignées et le dépôt des composants ; stacked : écran étroit, empilés
6
8
  // { type: 'poad:front:navigate', page }
7
9
  // console → moteur { type: 'poad:front:load', protocol: 1, definition, page, mode, theme, viewAs?, single? }
8
10
  // viewAs : 'member' (défaut : le contenu de la page, quelle que soit sa règle d'accès — en
@@ -24,9 +26,12 @@ export type Theme = 'light' | 'dark';
24
26
  export type ViewAs = 'member' | 'visitor';
25
27
  export type PreviewOptions = { viewAs?: ViewAs; single?: boolean };
26
28
 
29
+ /** Place d'une grille dans la page rendue (pixels de l'iframe, avant la mise à l'échelle de la console) */
30
+ export type GridLayout = { section: string; x: number; y: number; width: number; height: number; rowHeight: number; rows: number; stacked: boolean };
31
+
27
32
  export type ToConsole =
28
33
  | { type: 'poad:front:ready'; protocol: typeof PROTOCOL }
29
- | { type: 'poad:front:rendered'; page: string; width: number; height: number }
34
+ | { type: 'poad:front:rendered'; page: string; width: number; height: number; grids?: GridLayout[] }
30
35
  | { type: 'poad:front:navigate'; page: string }
31
36
  | { type: 'poad:front:invalid'; issues: { path: string; message: string }[] };
32
37
 
@@ -91,7 +96,14 @@ export const createPreviewBridge = (win: PreviewWindow, origins: readonly string
91
96
  win.addEventListener('message', onMessage);
92
97
  return {
93
98
  ready: () => send({ type: 'poad:front:ready', protocol: PROTOCOL }),
94
- rendered: (page: string, width: number, height: number) => send({ type: 'poad:front:rendered', page, width: Math.round(width), height: Math.round(height) }),
99
+ rendered: (page: string, width: number, height: number, grids?: GridLayout[]) =>
100
+ send({
101
+ type: 'poad:front:rendered',
102
+ page,
103
+ width: Math.round(width),
104
+ height: Math.round(height),
105
+ ...(grids ? { grids: grids.map((g) => ({ ...g, x: Math.round(g.x), y: Math.round(g.y), width: Math.round(g.width), height: Math.round(g.height) })) } : {}),
106
+ }),
95
107
  navigate: (page: string) => send({ type: 'poad:front:navigate', page }),
96
108
  dispose: () => win.removeEventListener('message', onMessage),
97
109
  };