@nuforge/editor 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,657 @@
1
+ import * as t from '@nuforge/types';
2
+ import { Parser } from '@nuforge/parser';
3
+
4
+ function lit(value) {
5
+ return t.literal({ value });
6
+ }
7
+ function text(value) {
8
+ return t.tagTemplate({
9
+ tag: 'text',
10
+ props: { text: lit(value) },
11
+ children: [],
12
+ });
13
+ }
14
+ function el(tag, props = {}, children = []) {
15
+ return t.tagTemplate({ tag, props, children });
16
+ }
17
+
18
+ function defineBlock(block) {
19
+ return block;
20
+ }
21
+ class BlockRegistry {
22
+ blocks = new Map();
23
+ constructor(initial = []) {
24
+ for (const block of initial) {
25
+ this.register(block);
26
+ }
27
+ }
28
+ register(block) {
29
+ this.blocks.set(block.id, block);
30
+ }
31
+ get(id) {
32
+ return this.blocks.get(id);
33
+ }
34
+ all() {
35
+ return [...this.blocks.values()];
36
+ }
37
+ byCategory() {
38
+ const out = {};
39
+ for (const block of this.blocks.values()) {
40
+ const key = block.category ?? 'Elements';
41
+ (out[key] ??= []).push(block);
42
+ }
43
+ return out;
44
+ }
45
+ }
46
+ const DEFAULT_BLOCKS = [
47
+ { id: 'box', label: 'Box', icon: 'square', create: () => el('div') },
48
+ { id: 'text', label: 'Text', icon: 'type', create: () => text('Text') },
49
+ {
50
+ id: 'heading',
51
+ label: 'Heading',
52
+ icon: 'heading',
53
+ create: () => el('h2', {}, [text('Heading')]),
54
+ },
55
+ {
56
+ id: 'paragraph',
57
+ label: 'Paragraph',
58
+ icon: 'pilcrow',
59
+ create: () => el('p', {}, [text('Paragraph text')]),
60
+ },
61
+ {
62
+ id: 'button',
63
+ label: 'Button',
64
+ icon: 'mouse-pointer-click',
65
+ create: () => el('button', {}, [text('Button')]),
66
+ },
67
+ {
68
+ id: 'container',
69
+ label: 'Container',
70
+ icon: 'box',
71
+ create: () => el('section', {}, [el('h3', {}, [text('Section')])]),
72
+ },
73
+ ];
74
+
75
+ class CommandRegistry {
76
+ editor;
77
+ commands = new Map();
78
+ constructor(editor) {
79
+ this.editor = editor;
80
+ }
81
+ register(command) {
82
+ this.commands.set(command.id, command);
83
+ }
84
+ get(id) {
85
+ return this.commands.get(id);
86
+ }
87
+ all() {
88
+ return [...this.commands.values()];
89
+ }
90
+ run(id) {
91
+ this.commands.get(id)?.run(this.editor);
92
+ }
93
+ }
94
+
95
+ function dropPositionFromPointer(clientY, rect, opts = {}) {
96
+ const ratio = rect.height > 0 ? (clientY - rect.top) / rect.height : 0;
97
+ if (opts.allowInside) {
98
+ if (ratio < 0.25)
99
+ return 'before';
100
+ if (ratio > 0.75)
101
+ return 'after';
102
+ return 'inside';
103
+ }
104
+ return ratio < 0.5 ? 'before' : 'after';
105
+ }
106
+ function templateLabel(node) {
107
+ if (node instanceof t.TagTemplate) {
108
+ return node.tag;
109
+ }
110
+ if (node instanceof t.ComponentTemplate) {
111
+ return node.component.name;
112
+ }
113
+ if (node instanceof t.SlotTemplate) {
114
+ return node.name ? `slot: ${node.name}` : 'slot';
115
+ }
116
+ if (t.is(node, t.FragmentTemplate)) {
117
+ return 'fragment';
118
+ }
119
+ return 'node';
120
+ }
121
+ function templateChildren(node) {
122
+ return (node.children ?? []).filter((child) => child instanceof t.Type);
123
+ }
124
+ function isTextTemplate(node) {
125
+ return node instanceof t.TagTemplate && node.tag === 'text';
126
+ }
127
+ function textPreview(node) {
128
+ if (!isTextTemplate(node)) {
129
+ return null;
130
+ }
131
+ const expr = node.props.text;
132
+ if (expr instanceof t.Literal) {
133
+ return String(expr.value);
134
+ }
135
+ return '{…}';
136
+ }
137
+ function canHaveChildren(node) {
138
+ if (!node || isTextTemplate(node)) {
139
+ return false;
140
+ }
141
+ return (node instanceof t.TagTemplate ||
142
+ node instanceof t.ComponentTemplate ||
143
+ t.is(node, t.FragmentTemplate));
144
+ }
145
+ function isAncestorOf(nu, ancestor, node) {
146
+ let parent = nu.getParentNode(node);
147
+ while (parent) {
148
+ if (parent === ancestor) {
149
+ return true;
150
+ }
151
+ parent = nu.getParentNode(parent);
152
+ }
153
+ return false;
154
+ }
155
+
156
+ class Editor {
157
+ nu;
158
+ blocks;
159
+ commands;
160
+ constructor(nu, opts = {}) {
161
+ this.nu = nu;
162
+ const base = opts.defaultBlocks === false ? [] : DEFAULT_BLOCKS;
163
+ this.blocks = new BlockRegistry([...base, ...(opts.blocks ?? [])]);
164
+ this.commands = new CommandRegistry(this);
165
+ this.commands.register({
166
+ id: 'undo',
167
+ label: 'Undo',
168
+ shortcut: 'mod+z',
169
+ run: (e) => e.nu.undo(),
170
+ });
171
+ this.commands.register({
172
+ id: 'redo',
173
+ label: 'Redo',
174
+ shortcut: 'mod+shift+z',
175
+ run: (e) => e.nu.redo(),
176
+ });
177
+ }
178
+ insertNode(parent, child, index) {
179
+ const kids = parent.children;
180
+ if (!Array.isArray(kids)) {
181
+ return;
182
+ }
183
+ this.nu.change(() => {
184
+ if (index === undefined || index >= kids.length) {
185
+ kids.push(child);
186
+ }
187
+ else {
188
+ kids.splice(Math.max(0, index), 0, child);
189
+ }
190
+ });
191
+ }
192
+ removeNode(node) {
193
+ let ok = false;
194
+ this.nu.change(() => {
195
+ ok = this.spliceFromParent(node);
196
+ });
197
+ return ok;
198
+ }
199
+ moveNode(dragged, target, position) {
200
+ if (dragged === target || isAncestorOf(this.nu, dragged, target)) {
201
+ return false;
202
+ }
203
+ let ok = false;
204
+ this.nu.change(() => {
205
+ ok = this.applyMove(dragged, target, position);
206
+ });
207
+ return ok;
208
+ }
209
+ clipboardNode = null;
210
+ copyNode(node) {
211
+ this.clipboardNode = node;
212
+ }
213
+ cutNode(node) {
214
+ this.copyNode(node);
215
+ return this.removeNode(node);
216
+ }
217
+ canPaste() {
218
+ return this.clipboardNode !== null;
219
+ }
220
+ pasteNode(target, position = 'after') {
221
+ if (!this.clipboardNode) {
222
+ return null;
223
+ }
224
+ return this.insertCloneRelativeTo(this.clipboardNode, target, position);
225
+ }
226
+ duplicateNode(node) {
227
+ return this.insertCloneRelativeTo(node, node, 'after');
228
+ }
229
+ insertNodeAt(node, target, position) {
230
+ let ok = false;
231
+ this.nu.change(() => {
232
+ ok = this.insertRelativeTo(node, target, position);
233
+ });
234
+ return ok ? (this.nu.getNodeFromId(node.id) ?? null) : null;
235
+ }
236
+ insertBlockAt(blockId, target, position) {
237
+ const block = this.blocks.get(blockId);
238
+ if (!block) {
239
+ return null;
240
+ }
241
+ return this.insertNodeAt(block.create(), target, position);
242
+ }
243
+ insertCloneRelativeTo(source, target, position) {
244
+ const clone = t.clone(source, { replaceExistingId: true });
245
+ let ok = false;
246
+ this.nu.change(() => {
247
+ ok = this.insertRelativeTo(clone, target, position);
248
+ });
249
+ return ok ? (this.nu.getNodeFromId(clone.id) ?? null) : null;
250
+ }
251
+ updateProps(node, props) {
252
+ this.nu.change(() => {
253
+ for (const [key, value] of Object.entries(props)) {
254
+ node.props[key] = value;
255
+ }
256
+ });
257
+ }
258
+ setProp(node, key, expr) {
259
+ this.nu.change(() => {
260
+ node.props[key] = expr;
261
+ });
262
+ }
263
+ removeProp(node, key) {
264
+ this.nu.change(() => {
265
+ delete node.props[key];
266
+ });
267
+ }
268
+ setExpression(node, key, source) {
269
+ let expr;
270
+ try {
271
+ expr = Parser.parseExpression(source);
272
+ }
273
+ catch {
274
+ return false;
275
+ }
276
+ this.setProp(node, key, expr);
277
+ return true;
278
+ }
279
+ setText(node, value) {
280
+ const expr = node.props?.text;
281
+ if (!(expr instanceof t.Literal)) {
282
+ return false;
283
+ }
284
+ this.nu.change(() => {
285
+ expr.value = value;
286
+ });
287
+ return true;
288
+ }
289
+ setTag(node, tag) {
290
+ const clean = tag.trim();
291
+ if (!clean) {
292
+ return;
293
+ }
294
+ this.nu.change(() => {
295
+ node.tag = clean;
296
+ });
297
+ }
298
+ addClass(node, name) {
299
+ const clean = name.trim();
300
+ if (!clean) {
301
+ return;
302
+ }
303
+ this.nu.change(() => {
304
+ const tag = node;
305
+ if (!tag.classList) {
306
+ tag.classList = t.objectExpression({ properties: {} });
307
+ }
308
+ tag.classList.properties[clean] = t.literal({ value: true });
309
+ });
310
+ }
311
+ setClassCondition(node, name, source) {
312
+ let expr;
313
+ try {
314
+ expr = Parser.parseExpression(source);
315
+ }
316
+ catch {
317
+ return false;
318
+ }
319
+ this.nu.change(() => {
320
+ const tag = node;
321
+ if (tag.classList) {
322
+ tag.classList.properties[name] = expr;
323
+ }
324
+ });
325
+ return true;
326
+ }
327
+ removeClass(node, name) {
328
+ this.nu.change(() => {
329
+ const tag = node;
330
+ if (!tag.classList) {
331
+ return;
332
+ }
333
+ delete tag.classList.properties[name];
334
+ if (Object.keys(tag.classList.properties).length === 0) {
335
+ tag.classList = null;
336
+ }
337
+ });
338
+ }
339
+ setCondition(node, source) {
340
+ let expr;
341
+ try {
342
+ expr = Parser.parseExpression(source);
343
+ }
344
+ catch {
345
+ return false;
346
+ }
347
+ this.nu.change(() => {
348
+ node.if = expr;
349
+ });
350
+ return true;
351
+ }
352
+ clearCondition(node) {
353
+ this.nu.change(() => {
354
+ node.if = null;
355
+ });
356
+ }
357
+ setEach(node, iterator, alias = 'item', indexName) {
358
+ let expr;
359
+ try {
360
+ expr = Parser.parseExpression(iterator);
361
+ }
362
+ catch {
363
+ return false;
364
+ }
365
+ this.nu.change(() => {
366
+ node.each = t.elementEach({
367
+ alias: t.elementEachAlias({ name: alias || 'item' }),
368
+ index: indexName ? t.elementEachIndex({ name: indexName }) : null,
369
+ iterator: expr,
370
+ });
371
+ });
372
+ return true;
373
+ }
374
+ clearEach(node) {
375
+ this.nu.change(() => {
376
+ node.each = null;
377
+ });
378
+ }
379
+ addState(component, name = 'value', init = '0') {
380
+ const taken = new Set(component.state.map((v) => v.name));
381
+ let unique = name;
382
+ let i = 2;
383
+ while (taken.has(unique)) {
384
+ unique = `${name}${i}`;
385
+ i += 1;
386
+ }
387
+ let initExpr;
388
+ try {
389
+ initExpr = Parser.parseExpression(init);
390
+ }
391
+ catch {
392
+ initExpr = t.literal({ value: 0 });
393
+ }
394
+ this.nu.change(() => {
395
+ component.state.push(t.val({ name: unique, init: initExpr }));
396
+ });
397
+ return component.state.find((v) => v.name === unique);
398
+ }
399
+ removeState(component, val) {
400
+ this.nu.change(() => {
401
+ const i = component.state.findIndex((v) => v.id === val.id);
402
+ if (i >= 0) {
403
+ component.state.splice(i, 1);
404
+ }
405
+ });
406
+ }
407
+ setStateInit(val, source) {
408
+ let expr;
409
+ try {
410
+ expr = Parser.parseExpression(source);
411
+ }
412
+ catch {
413
+ return false;
414
+ }
415
+ this.nu.change(() => {
416
+ val.init = expr;
417
+ });
418
+ return true;
419
+ }
420
+ addComponentProp(component, name = 'prop', init) {
421
+ const taken = new Set(component.props.map((p) => p.name));
422
+ let unique = name;
423
+ let i = 2;
424
+ while (taken.has(unique)) {
425
+ unique = `${name}${i}`;
426
+ i += 1;
427
+ }
428
+ let initExpr;
429
+ if (init) {
430
+ try {
431
+ initExpr = Parser.parseExpression(init);
432
+ }
433
+ catch {
434
+ initExpr = undefined;
435
+ }
436
+ }
437
+ this.nu.change(() => {
438
+ component.props.push(t.componentProp({ name: unique, init: initExpr }));
439
+ });
440
+ return component.props.find((p) => p.name === unique);
441
+ }
442
+ removeComponentProp(component, prop) {
443
+ this.nu.change(() => {
444
+ const i = component.props.findIndex((p) => p.id === prop.id);
445
+ if (i >= 0) {
446
+ component.props.splice(i, 1);
447
+ }
448
+ });
449
+ }
450
+ setComponentPropInit(prop, source) {
451
+ let expr;
452
+ try {
453
+ expr = Parser.parseExpression(source);
454
+ }
455
+ catch {
456
+ return false;
457
+ }
458
+ this.nu.change(() => {
459
+ prop.init = expr;
460
+ });
461
+ return true;
462
+ }
463
+ insertBlock(blockId, parent, index) {
464
+ const block = this.blocks.get(blockId);
465
+ if (!block || !canHaveChildren(parent)) {
466
+ return null;
467
+ }
468
+ const created = block.create();
469
+ this.insertNode(parent, created, index);
470
+ return created;
471
+ }
472
+ uniqueName(base) {
473
+ const taken = new Set(this.getComponents().map((c) => c.name));
474
+ if (!taken.has(base)) {
475
+ return base;
476
+ }
477
+ let i = 2;
478
+ while (taken.has(`${base}${i}`)) {
479
+ i += 1;
480
+ }
481
+ return `${base}${i}`;
482
+ }
483
+ addComponent(name = 'Page') {
484
+ const unique = this.uniqueName(name);
485
+ const component = t.nuComponent({
486
+ name: unique,
487
+ props: [],
488
+ state: [],
489
+ template: el('div', {}, [text(unique)]),
490
+ });
491
+ this.nu.change(() => {
492
+ this.nu.state.program.components.push(component);
493
+ });
494
+ return this.getComponent(unique);
495
+ }
496
+ renameComponent(component, name) {
497
+ const clean = name.trim();
498
+ if (!clean ||
499
+ this.getComponents().some((c) => c !== component && c.name === clean)) {
500
+ return false;
501
+ }
502
+ const old = component.name;
503
+ this.nu.change(() => {
504
+ component.name = clean;
505
+ for (const c of this.getComponents()) {
506
+ this.walkTemplates(c.template, (tpl) => {
507
+ if (tpl instanceof t.ComponentTemplate && tpl.component.name === old) {
508
+ tpl.component.name = clean;
509
+ }
510
+ });
511
+ }
512
+ });
513
+ return true;
514
+ }
515
+ removeComponent(component) {
516
+ const comps = this.nu.state.program.components;
517
+ let ok = false;
518
+ this.nu.change(() => {
519
+ const i = comps.findIndex((c) => c.id === component.id);
520
+ if (i >= 0) {
521
+ comps.splice(i, 1);
522
+ ok = true;
523
+ }
524
+ });
525
+ return ok;
526
+ }
527
+ duplicateComponent(component) {
528
+ const copy = t.clone(component, { replaceExistingId: true });
529
+ const name = this.uniqueName(`${component.name}Copy`);
530
+ copy.name = name;
531
+ this.nu.change(() => {
532
+ this.nu.state.program.components.push(copy);
533
+ });
534
+ return this.getComponent(name);
535
+ }
536
+ walkTemplates(node, fn) {
537
+ if (!node) {
538
+ return;
539
+ }
540
+ fn(node);
541
+ for (const child of templateChildren(node)) {
542
+ this.walkTemplates(child, fn);
543
+ }
544
+ }
545
+ getComponents() {
546
+ return this.nu.state.program.components.filter((c) => c instanceof t.NuComponent);
547
+ }
548
+ getComponent(name) {
549
+ return this.getComponents().find((c) => c.name === name);
550
+ }
551
+ getRootTemplate(name) {
552
+ return this.getComponent(name)?.template ?? null;
553
+ }
554
+ getChildren(node) {
555
+ return templateChildren(node);
556
+ }
557
+ getSiblings(node) {
558
+ const parent = this.nu.getParentNode(node);
559
+ return parent ? templateChildren(parent) : [];
560
+ }
561
+ getNodeIndex(node) {
562
+ return this.getSiblings(node).indexOf(node);
563
+ }
564
+ getNodePath(node) {
565
+ const out = [];
566
+ let current = node;
567
+ let loc = this.nu.getNodeLocation(current);
568
+ while (loc && loc.parent !== current) {
569
+ out.unshift(...loc.path);
570
+ current = loc.parent;
571
+ loc = this.nu.getNodeLocation(current);
572
+ }
573
+ return out;
574
+ }
575
+ onChange(cb) {
576
+ return this.nu.listenToMutations(cb);
577
+ }
578
+ onStructureChange(cb) {
579
+ return this.nu.listenToMutations((entries) => {
580
+ if (entries.some((e) => Array.isArray(e.target))) {
581
+ cb();
582
+ }
583
+ });
584
+ }
585
+ spliceFromParent(node) {
586
+ const parent = this.nu.getParentNode(node);
587
+ const kids = parent?.children;
588
+ if (!Array.isArray(kids)) {
589
+ return false;
590
+ }
591
+ const index = kids.indexOf(node);
592
+ if (index < 0) {
593
+ return false;
594
+ }
595
+ kids.splice(index, 1);
596
+ return true;
597
+ }
598
+ applyMove(dragged, target, position) {
599
+ const oldParent = this.nu.getParentNode(dragged);
600
+ const oldKids = oldParent?.children;
601
+ if (!Array.isArray(oldKids)) {
602
+ return false;
603
+ }
604
+ if (position === 'inside') {
605
+ if (!canHaveChildren(target)) {
606
+ return false;
607
+ }
608
+ const destKids = target.children;
609
+ const oi = oldKids.indexOf(dragged);
610
+ if (oi >= 0) {
611
+ oldKids.splice(oi, 1);
612
+ }
613
+ destKids.push(dragged);
614
+ return true;
615
+ }
616
+ const newParent = this.nu.getParentNode(target);
617
+ const destKids = newParent?.children;
618
+ if (!Array.isArray(destKids)) {
619
+ return false;
620
+ }
621
+ const oi = oldKids.indexOf(dragged);
622
+ if (oi >= 0) {
623
+ oldKids.splice(oi, 1);
624
+ }
625
+ let ti = destKids.indexOf(target);
626
+ if (ti < 0) {
627
+ ti = destKids.length - 1;
628
+ }
629
+ destKids.splice(position === 'after' ? ti + 1 : ti, 0, dragged);
630
+ return true;
631
+ }
632
+ insertRelativeTo(node, target, position) {
633
+ if (position === 'inside') {
634
+ if (!canHaveChildren(target)) {
635
+ return false;
636
+ }
637
+ target.children.push(node);
638
+ return true;
639
+ }
640
+ const parent = this.nu.getParentNode(target);
641
+ const kids = parent?.children;
642
+ if (!Array.isArray(kids)) {
643
+ return false;
644
+ }
645
+ let ti = kids.indexOf(target);
646
+ if (ti < 0) {
647
+ ti = kids.length - 1;
648
+ }
649
+ kids.splice(position === 'after' ? ti + 1 : ti, 0, node);
650
+ return true;
651
+ }
652
+ }
653
+ function createEditor(nu, opts) {
654
+ return new Editor(nu, opts);
655
+ }
656
+
657
+ export { BlockRegistry, CommandRegistry, DEFAULT_BLOCKS, Editor, canHaveChildren, createEditor, defineBlock, dropPositionFromPointer, el, isAncestorOf, isTextTemplate, lit, templateChildren, templateLabel, text, textPreview };