tess_edit 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,19 @@
1
1
  // <div data-controller="tess-edit"> … </div>
2
2
  //
3
3
  // Values:
4
+ // kit what the editor makes: "email" (the default), or a kit the host
5
+ // registered (see core/registry.js)
4
6
  // document JSON of the document to load (falls back to the json input, then a sample)
5
7
  // sample load the sample document when there is nothing else (default true)
8
+ // frame a border with rounded corners around the editor (default true); a
9
+ // host that frames it itself, such as a card it fills, turns it off
6
10
  // panels "split" (Blocks and Layers left, Inspect right), "left" or "right" (all panels
7
11
  // as tabs on one side). The default; a choice made in the editor's
8
12
  // top bar is remembered per browser. Below NARROW_WIDTH the editor
9
13
  // puts all panels on the left, whatever the choice, to leave room
10
14
  // for the canvas.
11
- // compileUrl the endpoint that compiles MJML to HTML (default /tess_edit/compile,
12
- // the engine mounted at /tess_edit)
15
+ // compileUrl the endpoint that compiles the email kit's MJML to HTML (default
16
+ // /tess_edit/compile, the engine mounted at /tess_edit)
13
17
  // mediaUrl the host's images, chosen and uploaded in Image blocks (see
14
18
  // core/media.js); without it images only have a URL
15
19
  // variablesUrl the variables a template can use, suggested while typing {{
@@ -22,20 +26,25 @@
22
26
  // lock JSON: only the insides of some blocks and some root fields can
23
27
  // change, e.g. {"except": ["content"], "fields": ["data.subject"]}
24
28
  // (see core/lock.js)
29
+ // blocks JSON: the only block types that can be added, e.g. ["text", "image"];
30
+ // without it, all of the kit's
31
+ // options JSON: anything a host's blocks need from the page, as
32
+ // editor.options, e.g. the choices of a select field
33
+ // (options: (editor) => editor.options.parties)
25
34
  // Targets (all optional, usually hidden inputs in a form):
26
- // jsonInput, mjmlInput, htmlInput kept up to date with every change
35
+ // jsonInput, mjmlInput, htmlInput kept up to date with every change, with
36
+ // the kit's outputs (an <output>Input target for each)
27
37
  // Events:
28
- // tess-edit:change detail: { json, mjml, html, errors, document }; html is
29
- // empty when the MJML could not be compiled, with errors saying why
38
+ // tess-edit:change detail: { json, ...the kit's outputs, errors, document }:
39
+ // for an email { json, mjml, html, errors, document }, with
40
+ // html empty when the MJML could not be compiled and errors saying why
30
41
 
31
42
  import { Controller } from "@hotwired/stimulus"
32
- import { accepted, ancestors, createDocument, createFromPalette, duplicate, find, getValue, insert, itemType, move, normalize, remove, setValue, walk } from "tess_edit/core/document"
43
+ import { accepted, ancestors, createDocument, createFromPalette, duplicate, find, findType, getValue, insert, itemType, misfit, move, normalize, remove, setValue, walk } from "tess_edit/core/document"
33
44
  import { History } from "tess_edit/core/history"
34
45
  import { canEditField, canFill, isFree, parseLock } from "tess_edit/core/lock"
35
- import { getBlock, paletteItems } from "tess_edit/core/registry"
36
- import { starterDocument } from "tess_edit/core/starter"
37
- import { toMjml } from "tess_edit/export/mjml"
38
- import { COMPILE_URL, compile } from "tess_edit/export/compile"
46
+ import { DEFAULT_KIT, getBlock, getKit, paletteItems, paletteSources } from "tess_edit/core/registry"
47
+ import { COMPILE_URL } from "tess_edit/export/compile"
39
48
  import { IMAGE_FIELD, fetchMedia, uploadMedia } from "tess_edit/core/media"
40
49
  import { Translations, keysIn, suggestKey, toTranslation, translationTag } from "tess_edit/core/translations"
41
50
  import { Variables, loopScope } from "tess_edit/core/variables"
@@ -59,18 +68,27 @@ const TRANSLATION_LOCALE_KEY = "tess_edit:translation_locale"
59
68
  const NARROW_WIDTH = 1000
60
69
 
61
70
  export default class extends Controller {
62
- static values = { document: String, sample: { type: Boolean, default: true }, panels: { type: String, default: "split" }, compileUrl: { type: String, default: COMPILE_URL }, mediaUrl: String, variablesUrl: String, translationsUrl: String, lock: String }
71
+ static values = { kit: { type: String, default: DEFAULT_KIT }, document: String, sample: { type: Boolean, default: true }, frame: { type: Boolean, default: true }, panels: { type: String, default: "split" }, compileUrl: { type: String, default: COMPILE_URL }, mediaUrl: String, variablesUrl: String, translationsUrl: String, lock: String, blocks: String, options: String }
63
72
  static targets = ["jsonInput", "mjmlInput", "htmlInput"]
64
73
 
65
74
  connect() {
75
+ this.kit = getKit(this.kitValue)
76
+ if (!this.kit) {
77
+ console.error(`TessEdit: unknown kit ${this.kitValue}, editing an email instead`)
78
+ this.kit = getKit(DEFAULT_KIT)
79
+ }
66
80
  this.lock = parseLock(this.lockValue)
81
+ this.allowedTypes = this.parseJson(this.blocksValue, "blocks")
82
+ this.options = this.parseJson(this.optionsValue, "options") || {}
83
+ // The host's tiles from palette sources (core/registry.js), by source key
84
+ this.sources = new Map()
67
85
  this.history = new History()
68
86
  this.doc = this.loadInitial()
69
87
  this.selectedId = this.doc.id
70
88
  this.editingId = null
71
89
  this.drag = null
72
90
  this.mode = "edit"
73
- this.device = "desktop"
91
+ this.device = this.kit.devices?.[0]?.key || null
74
92
  this.leftTab = "blocks"
75
93
  this.panels = [this.storedPanels(), this.panelsValue].find((value) => PANELS.includes(value)) || "split"
76
94
  this.narrow = false
@@ -89,6 +107,7 @@ export default class extends Controller {
89
107
  this.renderAll()
90
108
  this.writeOutputs()
91
109
  if (this.media.enabled) this.loadMedia()
110
+ this.loadSources()
92
111
  if (this.translations.enabled) {
93
112
  this.translations.subscribe(() => this.showTranslations())
94
113
  this.loadTranslations()
@@ -163,6 +182,31 @@ export default class extends Controller {
163
182
  return translationTag(key, translation.args)
164
183
  }
165
184
 
185
+ parseJson(value, name) {
186
+ if (!value) return null
187
+ try {
188
+ return JSON.parse(value)
189
+ } catch (error) {
190
+ console.error(`TessEdit: the ${name} value is not JSON`, error)
191
+ return null
192
+ }
193
+ }
194
+
195
+ // The palette sources' tiles; a source whose items are null has none here
196
+ async loadSources() {
197
+ await Promise.all(
198
+ paletteSources().map(async (source) => {
199
+ try {
200
+ const items = await source.items(this)
201
+ if (items) this.sources.set(source.key, { source, items, error: null })
202
+ } catch (error) {
203
+ this.sources.set(source.key, { source, items: [], error: error.message })
204
+ }
205
+ })
206
+ )
207
+ if (this.sources.size) renderBlocksPanel(this, this.blocksElement)
208
+ }
209
+
166
210
  async loadMedia() {
167
211
  try {
168
212
  this.media.images = await fetchMedia(this.mediaUrlValue)
@@ -231,12 +275,12 @@ export default class extends Controller {
231
275
  const source = this.documentValue || (this.hasJsonInputTarget && this.jsonInputTarget.value)
232
276
  if (source && source.trim()) {
233
277
  try {
234
- return normalize(source)
278
+ return normalize(source, { kit: this.kit.key })
235
279
  } catch (error) {
236
280
  console.error("TessEdit: could not load the document", error)
237
281
  }
238
282
  }
239
- return this.sampleValue ? starterDocument() : createDocument()
283
+ return this.sampleValue ? this.kit.starter() : createDocument(this.kit.key)
240
284
  }
241
285
 
242
286
  // --- public API -------------------------------------------------------------
@@ -248,15 +292,15 @@ export default class extends Controller {
248
292
  setDocument(input) {
249
293
  this.stopEditing()
250
294
  this.history.record(JSON.stringify(this.doc))
251
- this.doc = normalize(input)
295
+ this.doc = normalize(input, { kit: this.kit.key })
252
296
  this.selectedId = this.doc.id
253
297
  this.renderAll()
254
298
  }
255
299
 
300
+ // The JSON and the kit's outputs, e.g. { json, mjml, html, errors } for an email
256
301
  async export() {
257
- const mjml = toMjml(this.doc)
258
- const { html, errors } = await compile(mjml, { url: this.compileUrlValue })
259
- return { json: JSON.stringify(this.doc), mjml, html: html || "", errors }
302
+ const { outputs, errors } = await this.kit.outputs(this.doc, { compileUrl: this.compileUrlValue })
303
+ return { json: JSON.stringify(this.doc), ...outputs, errors }
260
304
  }
261
305
 
262
306
  // --- locking ------------------------------------------------------------------
@@ -273,9 +317,29 @@ export default class extends Controller {
273
317
  return canEditField(this.doc, this.lock, id, key)
274
318
  }
275
319
 
276
- // The block types that may be added to the node: none when it is locked.
320
+ // The block types that may be added to the node: none when it is locked,
321
+ // only the allowed ones when the host limits them.
277
322
  accepted(parentId) {
278
- return this.canFill(parentId) ? accepted(this.doc, parentId) : []
323
+ if (!this.canFill(parentId)) return []
324
+ return accepted(this.doc, parentId).filter((type) => this.allows(type))
325
+ }
326
+
327
+ // Whether a block of the type can go in the node; with `moving`, a block
328
+ // that is in the document already, which can always move where it fits
329
+ // A palette source's tile counts as moving: the host gave it, so the allowed
330
+ // blocks don't apply.
331
+ canInsert(parentId, type, { moving = false } = {}) {
332
+ if (!moving) return this.accepted(parentId).includes(type)
333
+ return this.canFill(parentId) && accepted(this.doc, parentId, { moving }).includes(type)
334
+ }
335
+
336
+ allows(type) {
337
+ return !this.allowedTypes || this.allowedTypes.includes(type)
338
+ }
339
+
340
+ // The Blocks panel's tiles
341
+ paletteItems() {
342
+ return paletteItems(this.kit.key).filter((item) => this.allows(item.type))
279
343
  }
280
344
 
281
345
  // --- layout -------------------------------------------------------------------
@@ -288,14 +352,14 @@ export default class extends Controller {
288
352
  this.sidePanel = h("aside")
289
353
  this.inspectPanel = h("aside")
290
354
  this.textToolbar = h("div", { class: "hidden absolute left-1/2 top-3 z-20 -translate-x-1/2 flex items-center gap-0.5 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 px-1.5 py-1 shadow-md" })
291
- this.frame = h("iframe", { class: "block h-full w-full border-0 bg-white transition-[width] duration-200", title: "Email canvas" })
355
+ this.frame = h("iframe", { class: "block h-full w-full border-0 bg-white transition-[width] duration-200", title: `${this.kit.name} canvas` })
292
356
  this.frameWrap = h("div", { class: "relative h-full mx-auto" }, this.frame)
293
357
  this.topBar = h("div", { class: "flex items-center gap-1 h-12 px-3 border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shrink-0" })
294
358
  this.body = h("div", { class: "flex flex-1 min-h-0" })
295
359
 
296
360
  this.root = h(
297
361
  "div",
298
- { class: "tess-edit relative flex flex-col h-full min-h-[560px] overflow-hidden rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900 text-sm text-gray-800 dark:text-gray-200 antialiased dark:[color-scheme:dark]", tabindex: "-1", onkeydown: (event) => this.onKeydown(event) },
362
+ { class: `tess-edit relative flex flex-col h-full min-h-[560px] overflow-hidden ${this.frameValue ? "rounded-lg border border-gray-200 dark:border-gray-700 " : ""}bg-gray-50 dark:bg-gray-900 text-sm text-gray-800 dark:text-gray-200 antialiased dark:[color-scheme:dark]`, tabindex: "-1", onkeydown: (event) => this.onKeydown(event) },
299
363
  this.topBar,
300
364
  this.body
301
365
  )
@@ -428,9 +492,9 @@ export default class extends Controller {
428
492
 
429
493
  // replaceChildren would turn a null into the text "null", so only pass real elements.
430
494
  this.topBar.replaceChildren(...[
431
- h("span", { class: "font-semibold text-gray-900 dark:text-gray-100 mr-3" }, "Email"),
432
- toggle(this.mode, [["edit", "edit", "Edit"], ["preview", "eye", "Preview the email as sent, with Liquid tags"]], (mode) => this.setMode(mode)),
433
- toggle(this.device, [["desktop", "desktop", "Desktop"], ["mobile", "mobile", "Mobile"]], (device) => this.setDevice(device)),
495
+ h("span", { class: "font-semibold text-gray-900 dark:text-gray-100 mr-3" }, this.kit.name),
496
+ toggle(this.mode, [["edit", "edit", "Edit"], ["preview", "eye", this.kit.previewTitle || "Preview"]], (mode) => this.setMode(mode)),
497
+ this.kit.devices?.length ? toggle(this.device, this.kit.devices.map((device) => [device.key, device.icon, device.title]), (device) => this.setDevice(device)) : null,
434
498
  this.translations.enabled ? this.translationLocaleMenu() : null,
435
499
  h("div", { class: "flex-1" }),
436
500
  toggle(
@@ -500,51 +564,52 @@ export default class extends Controller {
500
564
 
501
565
  setDevice(device) {
502
566
  this.device = device
503
- // Desktop fills the canvas area; mobile shows a full-height 375px frame in the middle of it.
504
- const mobile = device === "mobile"
505
- this.frameWrap.style.width = mobile ? "375px" : ""
506
- this.frameWrap.classList.toggle("shadow-sm", mobile)
507
- this.main.classList.toggle("px-4", mobile)
567
+ // A device without a width (desktop) fills the canvas area; one with a
568
+ // width (mobile, 375px) shows a full-height frame in the middle of it.
569
+ const width = this.kit.devices?.find((option) => option.key === device)?.width
570
+ this.frameWrap.style.width = width || ""
571
+ this.frameWrap.classList.toggle("shadow-sm", !!width)
572
+ this.main.classList.toggle("px-4", !!width)
508
573
  this.renderTopBar()
509
574
  setTimeout(() => this.canvas.refresh(), 250)
510
575
  }
511
576
 
512
577
  // --- rendering --------------------------------------------------------------
513
578
 
514
- // Compiles on the server. A newer request on the same channel aborts the
515
- // older one, which then resolves to null.
516
- async compileMjml(mjml, channel) {
579
+ // Runs one of the kit's renderings, which may go to the server (the email's
580
+ // compiling). A newer run on the same channel aborts the older one, which
581
+ // then resolves to null.
582
+ async run(channel, render) {
517
583
  this.requests[channel]?.abort()
518
584
  const request = (this.requests[channel] = new AbortController())
519
- const result = await compile(mjml, { url: this.compileUrlValue, signal: request.signal })
585
+ const result = await render({ compileUrl: this.compileUrlValue, signal: request.signal })
520
586
  return request.signal.aborted ? null : result
521
587
  }
522
588
 
523
589
  async renderCanvas() {
524
590
  if (this.editingId) return
525
- const result = await this.compileMjml(toMjml(this.doc, { editor: this.mode === "edit" }), "canvas")
591
+ const result = await this.run("canvas", (options) => this.kit.canvas(this.doc, { ...options, editor: this.mode === "edit" }))
526
592
  if (!result || this.editingId) return
527
593
  this.showErrors(result.errors)
528
- // Without HTML the canvas keeps the last email that compiled.
594
+ // Without HTML the canvas keeps the last document that rendered.
529
595
  if (result.html !== null) this.canvas.write(result.html, this.mode)
530
596
  }
531
597
 
532
598
  showErrors(errors) {
533
- this.errorBar.textContent = errors.length ? `The email could not be compiled: ${errors.join("; ")}` : ""
599
+ this.errorBar.textContent = errors.length ? `${this.kit.errors}: ${errors.join("; ")}` : ""
534
600
  this.errorBar.classList.toggle("hidden", !errors.length)
535
601
  }
536
602
 
537
603
  async writeOutputs() {
538
604
  this.loadTranslations()
539
605
  const json = JSON.stringify(this.doc)
540
- const mjml = toMjml(this.doc)
541
- const result = await this.compileMjml(mjml, "outputs")
606
+ const result = await this.run("outputs", (options) => this.kit.outputs(this.doc, options))
542
607
  if (!result) return
543
- const html = result.html || ""
544
- if (this.hasJsonInputTarget) this.jsonInputTarget.value = json
545
- if (this.hasMjmlInputTarget) this.mjmlInputTarget.value = mjml
546
- if (this.hasHtmlInputTarget) this.htmlInputTarget.value = html
547
- this.dispatch("change", { detail: { json, mjml, html, errors: result.errors, document: this.doc } })
608
+ const outputs = { json, ...result.outputs }
609
+ for (const [name, value] of Object.entries(outputs)) {
610
+ if (this[`has${name[0].toUpperCase()}${name.slice(1)}InputTarget`]) this[`${name}InputTarget`].value = value
611
+ }
612
+ this.dispatch("change", { detail: { ...outputs, errors: result.errors, document: this.doc } })
548
613
  }
549
614
 
550
615
  // Applies a change to the document as one undo step.
@@ -669,7 +734,9 @@ export default class extends Controller {
669
734
 
670
735
  drop(drag, parentId, index) {
671
736
  if (!drag || !this.canFill(parentId) || (drag.kind === "move" && !this.isFree(drag.id))) return
672
- if (drag.kind === "new") {
737
+ if (drag.kind === "source") {
738
+ this.insertFromSource(drag.source, drag.item, { parentId, index })
739
+ } else if (drag.kind === "new") {
673
740
  const node = createFromPalette(drag.key)
674
741
  this.commit((doc) => insert(doc, parentId, index, node))
675
742
  this.select(node.id)
@@ -692,21 +759,53 @@ export default class extends Controller {
692
759
  // lock, at the end of the first unlocked block it fits in.
693
760
  addFromPalette(key) {
694
761
  const type = itemType(key)
762
+ const place = this.placeFor((parentId) => this.accepted(parentId).includes(type))
763
+ if (place) return this.insertAt(key, place.parentId, place.index)
764
+ const definition = getBlock(type)
765
+ if (definition?.unique && findType(this.doc, type)) return this.flash(`There is a ${definition.name} already; a document has one.`)
766
+ this.flash(`${definition?.name || key} has to go inside a column. Select one first, or drag it onto the canvas.`)
767
+ }
768
+
769
+ // Where a click on a tile adds a block, for blocks that `fits` a parent
770
+ placeFor(fits) {
695
771
  const chain = [find(this.doc, this.selectedId)?.node || this.doc, ...ancestors(this.doc, this.selectedId)]
696
- if (this.accepted(chain[0].id).includes(type)) return this.insertAt(key, chain[0].id, chain[0].children.length)
772
+ if (fits(chain[0].id)) return { parentId: chain[0].id, index: chain[0].children.length }
697
773
  for (let i = 0; i < chain.length - 1; i++) {
698
- if (this.accepted(chain[i + 1].id).includes(type)) return this.insertAt(key, chain[i + 1].id, chain[i + 1].children.indexOf(chain[i]) + 1)
774
+ if (fits(chain[i + 1].id)) return { parentId: chain[i + 1].id, index: chain[i + 1].children.indexOf(chain[i]) + 1 }
699
775
  }
700
- if (this.accepted(this.doc.id).includes(type)) return this.insertAt(key, this.doc.id, this.doc.children.length)
776
+ if (fits(this.doc.id)) return { parentId: this.doc.id, index: this.doc.children.length }
701
777
  if (this.lock) {
702
778
  let target = null
703
779
  walk(this.doc, (node) => {
704
780
  if (target) return false
705
- if (this.lock.except.includes(node.type) && this.accepted(node.id).includes(type)) target = node
781
+ if (this.lock.except.includes(node.type) && fits(node.id)) target = node
706
782
  })
707
- if (target) return this.insertAt(key, target.id, target.children.length)
783
+ if (target) return { parentId: target.id, index: target.children.length }
708
784
  }
709
- this.flash(`${getBlock(type)?.name || key} has to go inside a column. Select one first, or drag it onto the canvas.`)
785
+ return null
786
+ }
787
+
788
+ // Inserts what a palette source's tile creates (see core/registry.js) at a
789
+ // place, or where a click on a tile would add it
790
+ async insertFromSource(source, item, { parentId, index } = {}) {
791
+ let node
792
+ try {
793
+ node = await source.create(item, this)
794
+ } catch (error) {
795
+ this.flash(error.message)
796
+ return null
797
+ }
798
+ const name = item.label || getBlock(node.type)?.name || "This"
799
+ const fits = (id) => this.canFill(id) && !misfit(node, accepted(this.doc, id, { moving: true }))
800
+ const place = parentId ? { parentId, index } : this.placeFor(fits)
801
+ if (!place || !fits(place.parentId)) {
802
+ const type = place && misfit(node, accepted(this.doc, place.parentId, { moving: true }))
803
+ this.flash(type && type !== node.type ? `${name} can't go here: its ${getBlock(type)?.name || type} blocks don't fit.` : `${name} doesn't fit here. Select where it goes first, or drag it onto the canvas.`)
804
+ return null
805
+ }
806
+ this.commit((doc) => insert(doc, place.parentId, place.index, node))
807
+ this.select(node.id)
808
+ return node
710
809
  }
711
810
 
712
811
  openInsertMenu(parentId, index, rect) {
@@ -721,7 +820,7 @@ export default class extends Controller {
721
820
  }
722
821
  this.closeMenu()
723
822
  const allowed = this.accepted(parentId)
724
- const items = paletteItems().filter((item) => allowed.includes(item.type))
823
+ const items = this.paletteItems().filter((item) => allowed.includes(item.type))
725
824
  if (!items.length) return
726
825
  this.menu = h(
727
826
  "div",
@@ -812,8 +911,8 @@ export default class extends Controller {
812
911
 
813
912
  async openCodeDialog(tab = "json") {
814
913
  this.stopEditing()
815
- const { json, mjml, html, errors } = await this.export()
816
- const contents = { json: JSON.stringify(JSON.parse(json), null, 2), mjml, html }
914
+ const { json, errors, ...outputs } = await this.export()
915
+ const contents = { json: JSON.stringify(JSON.parse(json), null, 2), ...outputs }
817
916
  const textarea = h("textarea", { class: "flex-1 w-full resize-none rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 p-3 font-mono text-xs text-gray-800 dark:text-gray-200 outline-none focus:border-blue-500", spellcheck: false })
818
917
  const status = h("span", { class: "text-xs text-gray-500 dark:text-gray-400" })
819
918
  const tabs = h("div", { class: "flex gap-1" })
@@ -836,9 +935,9 @@ export default class extends Controller {
836
935
  apply.classList.toggle("hidden", !loadable)
837
936
  status.className = "text-xs text-gray-500 dark:text-gray-400"
838
937
  status.textContent =
839
- key === "json" ? (this.lock ? "The document. Parts of it are locked, so it can't be loaded here." : "The document. Edit and load it, or paste one in.") : key === "mjml" ? "Liquid loops and conditions are in <mj-raw> tags." : errors.length ? `The MJML could not be compiled: ${errors.join("; ")}` : "Liquid is left in place for rendering at send time."
938
+ key === "json" ? (this.lock ? "The document. Parts of it are locked, so it can't be loaded here." : "The document. Edit and load it, or paste one in.") : key === "html" && errors.length ? `${this.kit.errors}: ${errors.join("; ")}` : this.kit.notes?.[key] || ""
840
939
  tabs.replaceChildren(
841
- ...["json", "mjml", "html"].map((name) =>
940
+ ...Object.keys(contents).map((name) =>
842
941
  h("button", { type: "button", class: `rounded-md px-3 py-1.5 text-xs font-medium ${name === tab ? "bg-gray-900 text-white dark:bg-gray-100 dark:text-gray-900" : "text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"}`, onclick: () => show(name) }, name.toUpperCase())
843
942
  )
844
943
  )
@@ -847,7 +946,7 @@ export default class extends Controller {
847
946
  const close = () => dialog.remove()
848
947
  const download = () => {
849
948
  const blob = new Blob([textarea.value], { type: tab === "json" ? "application/json" : tab === "html" ? "text/html" : "text/plain" })
850
- const link = h("a", { href: URL.createObjectURL(blob), download: `email.${tab}` })
949
+ const link = h("a", { href: URL.createObjectURL(blob), download: `${this.kit.key}.${tab}` })
851
950
  link.click()
852
951
  URL.revokeObjectURL(link.href)
853
952
  }
@@ -1,10 +1,13 @@
1
1
  // The document is a plain JSON tree:
2
2
  // { id, type, attributes: {}, data: {}, children: [] }
3
- // `attributes` map one-to-one onto MJML attributes, `data` holds everything else
4
- // (rich text, Liquid expressions, link lists). All functions here are pure apart
3
+ // `attributes` hold a block's styling, named after MJML's attributes (a kit
4
+ // with other output maps them onto its own), `data` holds everything else
5
+ // (rich text, Liquid expressions, link lists). A block copied from elsewhere,
6
+ // such as a host's reusable content, may also have `origin`: the id of the
7
+ // block it is a copy of (see renumber). All functions here are pure apart
5
8
  // from the mutating helpers, which change the tree they are given in place.
6
9
 
7
- import { getBlock, paletteItem, typesForRoles } from "tess_edit/core/registry"
10
+ import { DEFAULT_KIT, getBlock, getKit, kitOf, paletteItem, typesForRoles } from "tess_edit/core/registry"
8
11
 
9
12
  export const VERSION = 1
10
13
 
@@ -30,8 +33,11 @@ export function createNode(type, overrides = {}) {
30
33
  }
31
34
  }
32
35
 
33
- export function createDocument() {
34
- return { version: VERSION, ...createNode("root") }
36
+ // An empty document of a kit (see core/registry.js), an email by default.
37
+ export function createDocument(kit = DEFAULT_KIT) {
38
+ const definition = getKit(kit)
39
+ if (!definition) throw new Error(`Unknown kit: ${kit}`)
40
+ return { version: VERSION, ...createNode(definition.root) }
35
41
  }
36
42
 
37
43
  // Calls fn(node, parent, index, depth) for every node, depth first.
@@ -79,12 +85,34 @@ export function acceptedRoles(doc, parentId) {
79
85
  const accepts = getBlock(hit.node.type)?.accepts
80
86
  if (accepts !== "inherit") return accepts || []
81
87
  const owner = ancestors(doc, parentId).find((node) => getBlock(node.type)?.accepts !== "inherit")
82
- return (owner ? getBlock(owner.type).accepts : getBlock("root").accepts).filter((role) => role !== "column")
88
+ return (owner ? getBlock(owner.type).accepts : getBlock(doc.type).accepts).filter((role) => role !== "column")
83
89
  }
84
90
 
85
- // The block types that may be placed directly inside the node with `parentId`.
86
- export function accepted(doc, parentId) {
87
- return typesForRoles(acceptedRoles(doc, parentId))
91
+ // The block types of the document's kit that may be placed directly inside
92
+ // the node with `parentId`. A block that is `unique`, such as the Content
93
+ // block, can't be added when the document has one, but it can be moved.
94
+ export function accepted(doc, parentId, { moving = false } = {}) {
95
+ const types = typesForRoles(acceptedRoles(doc, parentId), kitOf(doc)?.key)
96
+ return moving ? types : types.filter((type) => !getBlock(type).unique || !findType(doc, type))
97
+ }
98
+
99
+ // The first node of a type, depth first
100
+ export function findType(doc, type) {
101
+ let result = null
102
+ walk(doc, (node) => {
103
+ if (result) return false
104
+ if (node.type === type) result = node
105
+ })
106
+ return result
107
+ }
108
+
109
+ // The first type that keeps a node from going inside `parentId`, where the
110
+ // types in `allowed` can go, or null when it fits: the node's own, or for a
111
+ // container that takes what its parent takes ("inherit"), one of its children's.
112
+ export function misfit(node, allowed) {
113
+ if (!allowed.includes(node.type)) return node.type
114
+ if (getBlock(node.type)?.accepts !== "inherit") return null
115
+ return node.children.find((child) => !allowed.includes(child.type))?.type || null
88
116
  }
89
117
 
90
118
  export function canInsert(doc, parentId, type) {
@@ -97,10 +125,14 @@ export function isHorizontal(doc, parentId) {
97
125
  return hit ? !!getBlock(hit.node.type)?.horizontal : false
98
126
  }
99
127
 
100
- // Gives a node and all of its descendants fresh ids, for duplicating and pasting.
101
- export function renumber(node) {
128
+ // Gives a node and all of its descendants fresh ids, for duplicating and
129
+ // pasting. The copy is new content, so it has no origin; with `origin` each
130
+ // block's origin is the id of the block it is a copy of instead.
131
+ export function renumber(node, { origin = false } = {}) {
102
132
  const copy = clone(node)
103
133
  walk(copy, (n) => {
134
+ if (origin) n.origin = n.id
135
+ else delete n.origin
104
136
  n.id = uid()
105
137
  })
106
138
  return copy
@@ -162,12 +194,15 @@ export function getValue(node, key) {
162
194
  return node[scope]?.[name]
163
195
  }
164
196
 
165
- // Light validation of a document read from storage or an import.
166
- export function normalize(input) {
197
+ // Light validation of a document read from storage or an import. With a
198
+ // `kit`, the document has to be one of that kit's.
199
+ export function normalize(input, { kit } = {}) {
167
200
  const doc = typeof input === "string" ? JSON.parse(input) : clone(input)
168
- // The root block was called "page" before; such documents still load.
169
- if (doc?.type === "page") doc.type = "root"
170
- if (!doc || doc.type !== "root") throw new Error("Not a TessEdit document: the top node must be the root block")
201
+ // The email's root block was called "page", then "root"; such documents still load.
202
+ if (doc?.type === "page" || doc?.type === "root") doc.type = "email"
203
+ const own = kitOf(doc)
204
+ if (!own) throw new Error("Not a TessEdit document: the top node must be a root block")
205
+ if (kit && own.key !== kit) throw new Error(`This is a document for the ${own.name} editor, not the ${getKit(kit)?.name || kit} one`)
171
206
  walk(doc, (node) => {
172
207
  if (!getBlock(node.type)) throw new Error(`Unknown block type: ${node.type}`)
173
208
  node.id ||= uid()
@@ -179,6 +214,21 @@ export function normalize(input) {
179
214
  return doc
180
215
  }
181
216
 
217
+ // The Content block of a layout (see blocks/content.js): where the documents
218
+ // using the layout put their own blocks.
219
+ export function contentNode(doc) {
220
+ return findType(doc, "content")
221
+ }
222
+
223
+ // The layout with these blocks in its Content block, as a new document
224
+ export function withContent(layout, nodes) {
225
+ const doc = clone(layout)
226
+ const content = contentNode(doc)
227
+ if (!content) throw new Error("The layout has no Content block")
228
+ content.children = clone(nodes || [])
229
+ return doc
230
+ }
231
+
182
232
  // The node (or small tree) a Blocks panel tile creates.
183
233
  export function createFromPalette(key) {
184
234
  const item = paletteItem(key)