@unbase-app/layer 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,71 @@
1
+ export interface PageToolsOptions {
2
+ /** Component titles by data-c key ("layout/VibeHero" → "Hero"); a key without one is named by its last part. */
3
+ titles?: Record<string, string>;
4
+ /** A regular expression (as text) for components that only wrap: left out of the chain. */
5
+ wrappers?: string;
6
+ /** A regular expression (as text) for atoms: in the chain, but never the name of the place. */
7
+ atoms?: string;
8
+ /** Elements that are not the page's own (the layer, the bridge's outline): looked through. */
9
+ skip?: (el: Element) => boolean;
10
+ }
11
+
12
+ export interface Point {
13
+ x: number;
14
+ y: number;
15
+ }
16
+
17
+ export interface ComponentInfo {
18
+ /** The innermost meaningful component's title, or the section's heading. */
19
+ title: string | null;
20
+ /** Its source file, e.g. "src/components/layout/VibeHero.astro". */
21
+ file: string | null;
22
+ /** The chain outside in, e.g. "VibeNav › MegaMenu". */
23
+ path: string;
24
+ }
25
+
26
+ /** Where a pin is: the columns of unbase.comments that place it. */
27
+ export interface Place {
28
+ selector: string | null;
29
+ element_tag: string | null;
30
+ element_text: string | null;
31
+ x_pct: number | null;
32
+ y_pct: number | null;
33
+ page_x: number | null;
34
+ page_y: number | null;
35
+ }
36
+
37
+ /** A place as recorded at a click: also the component, and the element's window rectangle. */
38
+ export interface PlaceAt extends Place {
39
+ component: string | null;
40
+ component_file: string | null;
41
+ component_path: string | null;
42
+ rect: { x: number; y: number; width: number; height: number };
43
+ }
44
+
45
+ /** A live point between windows of another size: an element's path, a point in it in percent,
46
+ and the page point as a fallback. */
47
+ export interface Anchor {
48
+ sel: string | null;
49
+ xp: number;
50
+ yp: number;
51
+ px: number;
52
+ py: number;
53
+ }
54
+
55
+ export interface PageTools {
56
+ short(text: string, max: number): string;
57
+ componentOf(el: Element): ComponentInfo;
58
+ targetOf(el: Element): Element;
59
+ tagOf(el: Element): string;
60
+ textOf(el: Element): string;
61
+ pathOf(el: Element): string;
62
+ elementAt(x: number, y: number): Element | null;
63
+ placeAt(x: number, y: number): PlaceAt | null;
64
+ find(place: Place): Element | null;
65
+ pinPoint(place: Place): Point | null;
66
+ anchorAt(x: number, y: number): Anchor;
67
+ anchorPoint(anchor: Anchor): Point;
68
+ }
69
+
70
+ /** One self-contained function: its source text can be shipped into another page as is. */
71
+ export function pageTools(options?: PageToolsOptions): PageTools;
@@ -0,0 +1,216 @@
1
+ // ============================================================================
2
+ // PAGE — where on the page something is, in one place.
3
+ //
4
+ // The layer on the site (`?comment`) and the bridge Unbase puts in each canvas
5
+ // frame both point at elements: a pin, a cursor, what someone has in view. They
6
+ // must agree to the character, or a pin placed in the editor lands on another
7
+ // element on the site. So both use this module.
8
+ //
9
+ // `pageTools` is one self-contained function: the bridge ships it as its own
10
+ // source text (`pageTools.toString()`) into pages it does not own, so nothing
11
+ // in its body may reach outside it. Plain JavaScript, typed in index.d.ts, so
12
+ // it runs from node_modules without a build.
13
+ //
14
+ // Coordinates are window coordinates (clientX/Y), as the DOM gives them; the
15
+ // page point (`page_x`, `px`) is the window point plus the scroll.
16
+ // ============================================================================
17
+
18
+ /** @param {import("./index.mjs").PageToolsOptions} [options] */
19
+ export function pageTools(options = {}) {
20
+ const titles = options.titles ?? {};
21
+ // Wrappers say nothing about what is there (a section, an animation): left out of the chain.
22
+ const wrapper = options.wrappers ? new RegExp(options.wrappers) : /$^/;
23
+ // Atoms stay in the chain but do not name the place: "VibeHero › Knop", not "Button › Knop".
24
+ const atom = options.atoms ? new RegExp(options.atoms) : /$^/;
25
+ const skip = options.skip ?? (() => false);
26
+
27
+ const short = (text, max) => {
28
+ const clean = text.replace(/\s+/g, " ").trim();
29
+ return clean.length > max ? clean.slice(0, max - 1).trimEnd() + "…" : clean;
30
+ };
31
+ const oneDecimal = (n) => Math.round(n * 10) / 10;
32
+ const clamp = (n) => Math.min(100, Math.max(0, n));
33
+
34
+ // ── Components ──
35
+ const islandName = (el) => {
36
+ const opts = el.getAttribute("opts");
37
+ if (!opts) return null;
38
+ try {
39
+ return JSON.parse(opts).name ?? null;
40
+ } catch {
41
+ return null;
42
+ }
43
+ };
44
+
45
+ /** Every component around `el`, inside out: data-c markers and Astro islands. */
46
+ const chainOf = (el) => {
47
+ const chain = [];
48
+ for (let node = el; node && node !== document.body; node = node.parentElement) {
49
+ const c = node.getAttribute("data-c");
50
+ if (c) chain.push({ key: c, title: titles[c] ?? c.split("/").pop(), file: `src/components/${c}.astro` });
51
+ else if (node.tagName === "ASTRO-ISLAND") {
52
+ const name = islandName(node);
53
+ if (name) {
54
+ const key = Object.keys(titles).find((k) => k.endsWith("/" + name)) ?? `islands/${name}`;
55
+ chain.push({ key, title: titles[key] ?? name, file: `src/components/${key}.tsx` });
56
+ }
57
+ }
58
+ }
59
+ return chain;
60
+ };
61
+
62
+ /** The innermost meaningful component, its file, and the chain outside in. */
63
+ const componentOf = (el) => {
64
+ const meaningful = chainOf(el).filter((k) => !wrapper.test(k.key));
65
+ const inner = meaningful.find((k) => !atom.test(k.key)) ?? null;
66
+ let title = inner?.title ?? null;
67
+ if (!title) {
68
+ // Only a section wrapper around it: name the section after its heading.
69
+ const heading = el.closest("section")?.querySelector("h1, h2, h3")?.textContent?.trim();
70
+ title = heading ? `Sectie “${short(heading, 32)}”` : null;
71
+ }
72
+ return { title, file: inner?.file ?? null, path: meaningful.map((k) => k.title).reverse().join(" › ") };
73
+ };
74
+
75
+ // ── Elements ──
76
+ const INLINE = new Set(["SPAN", "STRONG", "EM", "B", "I", "SMALL", "BR", "MARK", "SUP", "SUB", "ABBR", "TIME", "PATH", "G", "USE", "CIRCLE", "RECT", "LINE", "POLYLINE", "POLYGON"]);
77
+
78
+ /** Out of inline elements (a <strong> in a paragraph is the paragraph); an icon in a button is the button. */
79
+ const targetOf = (el) => {
80
+ let node = el;
81
+ while (INLINE.has(node.tagName.toUpperCase()) && node.parentElement && !node.hasAttribute("data-c")) node = node.parentElement;
82
+ if (node.tagName.toUpperCase() === "SVG" && node.parentElement?.closest("a, button")) node = node.parentElement.closest("a, button");
83
+ return node;
84
+ };
85
+
86
+ /** The tag, with the button class when there is one: "a.btn", "h1", "img". */
87
+ const tagOf = (el) => {
88
+ const tag = el.tagName.toLowerCase();
89
+ if ((tag === "a" || tag === "button") && /\bbtn\b/.test(el.getAttribute("class") ?? "")) return `${tag}.btn`;
90
+ return tag;
91
+ };
92
+
93
+ const textOf = (el) => {
94
+ const text = el.innerText ?? el.textContent ?? "";
95
+ const alt = el.getAttribute("alt") ?? el.querySelector("img")?.getAttribute("alt") ?? "";
96
+ return short(text || alt, 120);
97
+ };
98
+
99
+ /** A CSS path to exactly this element: from the nearest unique id, else from <body>. */
100
+ const pathOf = (el) => {
101
+ const parts = [];
102
+ let node = el;
103
+ while (node && node !== document.body && node !== document.documentElement) {
104
+ if (node.id && document.querySelectorAll(`#${CSS.escape(node.id)}`).length === 1) {
105
+ parts.unshift(`#${CSS.escape(node.id)}`);
106
+ return parts.join(" > ");
107
+ }
108
+ const parent = node.parentElement;
109
+ if (!parent) break;
110
+ const same = Array.from(parent.children).filter((c) => c.tagName === node.tagName);
111
+ const tag = node.tagName.toLowerCase();
112
+ parts.unshift(same.length > 1 ? `${tag}:nth-of-type(${same.indexOf(node) + 1})` : tag);
113
+ node = parent;
114
+ }
115
+ parts.unshift("body");
116
+ return parts.join(" > ");
117
+ };
118
+
119
+ /** What lies at this window point of the page itself: not the layer's, not html or body. */
120
+ const elementAt = (x, y) => {
121
+ for (const el of document.elementsFromPoint(x, y)) {
122
+ if (skip(el)) continue;
123
+ if (el === document.documentElement || el === document.body) return null;
124
+ return el;
125
+ }
126
+ return null;
127
+ };
128
+
129
+ // ── Places: where a pin is ──
130
+
131
+ /** Everything a pin records about the element at this window point, or null over nothing. */
132
+ const placeAt = (x, y) => {
133
+ const hit = elementAt(x, y);
134
+ if (!hit) return null;
135
+ const el = targetOf(hit);
136
+ const r = el.getBoundingClientRect();
137
+ const xp = r.width ? clamp(((x - r.left) / r.width) * 100) : 0;
138
+ const yp = r.height ? clamp(((y - r.top) / r.height) * 100) : 0;
139
+ const component = componentOf(el);
140
+ return {
141
+ selector: pathOf(el),
142
+ element_tag: tagOf(el),
143
+ element_text: textOf(el) || null,
144
+ x_pct: oneDecimal(xp),
145
+ y_pct: oneDecimal(yp),
146
+ page_x: Math.round(r.left + (r.width * xp) / 100 + scrollX),
147
+ page_y: Math.round(r.top + (r.height * yp) / 100 + scrollY),
148
+ component: component.title,
149
+ component_file: component.file,
150
+ component_path: component.path || null,
151
+ rect: { x: r.left, y: r.top, width: r.width, height: r.height },
152
+ };
153
+ };
154
+
155
+ /** A stored place's element on this page: its path (if its text still starts the same), else the
156
+ first element with that tag and text, else null. */
157
+ const find = (p) => {
158
+ if (p.selector) {
159
+ try {
160
+ const el = document.querySelector(p.selector);
161
+ if (el && (!p.element_text || textOf(el).startsWith(p.element_text.slice(0, 24)))) return el;
162
+ } catch {
163
+ // Not a path this page understands: fall back.
164
+ }
165
+ }
166
+ if (p.element_tag && p.element_text) {
167
+ const tag = p.element_tag.split(".")[0];
168
+ const start = p.element_text.slice(0, 24);
169
+ for (const el of Array.from(document.querySelectorAll(tag))) if (textOf(el).startsWith(start)) return el;
170
+ }
171
+ return null;
172
+ };
173
+
174
+ /** A stored place's window point, or null while its element is not shown. */
175
+ const pinPoint = (p) => {
176
+ const el = find(p);
177
+ if (el) {
178
+ const r = el.getBoundingClientRect();
179
+ if (r.width === 0 && r.height === 0) return null;
180
+ return { x: r.left + (r.width * (p.x_pct ?? 0)) / 100, y: r.top + (r.height * (p.y_pct ?? 0)) / 100 };
181
+ }
182
+ if (p.page_x != null && p.page_y != null) return { x: p.page_x - scrollX, y: p.page_y - scrollY };
183
+ return null;
184
+ };
185
+
186
+ // ── Anchors: cursors and views, live between windows of another size ──
187
+
188
+ /** This window point as an element and a point in it, with the page point as a fallback. */
189
+ const anchorAt = (x, y) => {
190
+ const fallback = { px: Math.round(x + scrollX), py: Math.round(y + scrollY) };
191
+ const el = elementAt(x, y);
192
+ if (!el) return { sel: null, xp: 0, yp: 0, ...fallback };
193
+ const r = el.getBoundingClientRect();
194
+ return {
195
+ sel: pathOf(el),
196
+ xp: r.width ? oneDecimal(((x - r.left) / r.width) * 100) : 0,
197
+ yp: r.height ? oneDecimal(((y - r.top) / r.height) * 100) : 0,
198
+ ...fallback,
199
+ };
200
+ };
201
+
202
+ /** An anchor's window point here. */
203
+ const anchorPoint = (a) => {
204
+ if (a.sel) {
205
+ try {
206
+ const r = document.querySelector(a.sel)?.getBoundingClientRect();
207
+ if (r && (r.width || r.height)) return { x: r.left + (r.width * a.xp) / 100, y: r.top + (r.height * a.yp) / 100 };
208
+ } catch {
209
+ // Not a path this page understands: the page point.
210
+ }
211
+ }
212
+ return { x: a.px - scrollX, y: a.py - scrollY };
213
+ };
214
+
215
+ return { short, componentOf, targetOf, tagOf, textOf, pathOf, elementAt, placeAt, find, pinPoint, anchorAt, anchorPoint };
216
+ }