tess_edit 0.5.5 → 0.5.7

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d9e9b7a64743faae5c3291e13d37a4ed05e76501a6133218aabb569681df4974
4
- data.tar.gz: 322204628014614d615f0cad63d04acdd07d410b9ea02417287f47eaa4530919
3
+ metadata.gz: b4f503a410953c3f8a0fe8182ef443136e0f2e6d8aed2f59d231b9e6417385e9
4
+ data.tar.gz: 42472bc71adb394f68d7ee5ede4ed7621692a20c0d96a60cc04849944f2aeb95
5
5
  SHA512:
6
- metadata.gz: e1163e2a6a1c06464db00540eb42b467db92d5640ae05bedf0906e2968ae9541b54439bd685084bacde1b9c4a97b4512652c4d71210e190ace96ded1628dd392
7
- data.tar.gz: 7cbc3479b8009322508e19de37d1f2f959414d731feb9f1a87e059be3b95808b0d64b75d62ce1aee30e6a0636ab371297e7cd030383637d6b2fccfe45da801ac
6
+ metadata.gz: 46e299dc88f49182cabd9bb36c8e2f714b8188992ae57a490f8627b8d4887b818073d18be846e33f7328af40078476ba859e4b489857af41e74058b5d7957ee9
7
+ data.tar.gz: 614ee5db85232cba27ed64441d1ba91735ca03c3a552b41d643653b238631cd923d1e165a8d28e8eef5e975e67117aa9e3e8c8102b8248dbd279bd41f6dceb02
data/README.md CHANGED
@@ -94,6 +94,34 @@ The editor has a border with rounded corners. A page that frames it itself, such
94
94
 
95
95
  Every change updates the inputs and dispatches `tess-edit:change` with `{ json, mjml, html, errors, document }` in `event.detail`. When the MJML can't be compiled, `html` is empty and `errors` says why; the editor shows the reason under the canvas. The controller instance is available as `element.tessEdit`, with `getDocument()`, `setDocument(json)` and `export()`.
96
96
 
97
+ ### The editor's language
98
+
99
+ The editor's own words (its labels, hints and messages) are in English, and in Dutch in `config/locales/nl.yml`. To show them in the page's language (`I18n.locale`), put `tess_edit_translations` in the editor:
100
+
101
+ ```erb
102
+ <div data-controller="tess-edit" style="height: 80vh">
103
+ <%= tess_edit_translations %>
104
+ …
105
+ </div>
106
+ ```
107
+
108
+ It renders a `<script type="application/json">` with each English text and what it says in that language (`tess_edit.editor` in your locale files, where your app can change or add a language). Blocks, kits and fields of your own are written in English too, and the editor translates their names, group titles, labels, hints, placeholders and options where it shows them: give their texts keys in a scope of your own, the English as in your JavaScript, and name it:
109
+
110
+ ```yaml
111
+ # config/locales/nl.yml (and the English in en.yml)
112
+ nl:
113
+ shop:
114
+ editor:
115
+ product: "Product"
116
+ sku: "Artikelnummer"
117
+ ```
118
+
119
+ ```erb
120
+ <%= tess_edit_translations "shop.editor" %>
121
+ ```
122
+
123
+ A text your JavaScript makes itself, such as a block's `label(node)`, uses `t` from `tess_edit/core/i18n` (`t("Product")`, `t("%{count} items", { count })`). A text without a translation shows its English. The dummy app shows the editor in Dutch at `/?locale=nl`.
124
+
97
125
  ### What gets stored
98
126
 
99
127
  | Field | Contents |
@@ -0,0 +1,23 @@
1
+ module TessEdit
2
+ # The editor's words in the page's language (I18n.locale), as JSON in the
3
+ # editor for it to say them in (app/javascript/tess_edit/core/i18n.js): its
4
+ # own (tess_edit.editor in config/locales) and those of the scopes given,
5
+ # the host's kits' and blocks', whose keys say the English the editor shows
6
+ # in their en.yml. A text without a translation says its English.
7
+ #
8
+ # <div data-controller="tess-edit">
9
+ # <%= tess_edit_translations "nuntius.editor" %>
10
+ module TranslationsHelper
11
+ def tess_edit_translations(*scopes)
12
+ words = ["tess_edit.editor", *scopes].each_with_object({}) do |scope, words|
13
+ english = I18n.t(scope, locale: :en, default: {})
14
+ next unless english.is_a?(Hash)
15
+
16
+ english.each do |key, text|
17
+ words[text] = I18n.t(key, scope: scope, default: text) if text.is_a?(String)
18
+ end
19
+ end
20
+ tag.script(ERB::Util.json_escape(words.to_json).html_safe, type: "application/json", data: {tess_edit_target: "translations"})
21
+ end
22
+ end
23
+ end
@@ -1,4 +1,5 @@
1
1
  import { align, border, padding, typography } from "tess_edit/blocks/fields"
2
+ import { t } from "tess_edit/core/i18n"
2
3
 
3
4
  export default {
4
5
  type: "button",
@@ -27,7 +28,7 @@ export default {
27
28
  typography(),
28
29
  border
29
30
  ],
30
- label: (node) => `Button · ${node.data.content || ""}`,
31
+ label: (node) => `${t("Button")} · ${node.data.content || ""}`,
31
32
  render: {
32
33
  mjml: (node, { element, escapeText }) => element("mj-button", node, escapeText(node.data.content))
33
34
  }
@@ -11,8 +11,10 @@
11
11
  // as tabs on one side). The default; a choice made in the editor's
12
12
  // top bar is remembered per browser. Below NARROW_WIDTH the editor
13
13
  // puts all panels on the left, whatever the choice, to leave room
14
- // for the canvas. A kit without blocks (blocks: false) has Inspect
15
- // on the right only.
14
+ // for the canvas, and below COMPACT_WIDTH (a phone) in a sheet
15
+ // below the canvas, shown and hidden from the top bar and opened
16
+ // by a tap on a block. A kit without blocks (blocks: false) has
17
+ // Inspect on the right only, or in the sheet.
16
18
  // compileUrl the endpoint that compiles the email kit's MJML to HTML (default
17
19
  // /tess_edit/compile, the engine mounted at /tess_edit)
18
20
  // mediaUrl the host's images, chosen and uploaded in Image blocks (see
@@ -38,6 +40,8 @@
38
40
  // the kit's outputs (an <output>Input target for each)
39
41
  // slot an element of the host's, named by data-tess-edit-slot,
40
42
  // that a "slot" field shows in Inspect (see ui/inspector.js)
43
+ // translations a <script type="application/json"> with the editor's words
44
+ // in the page's language (see core/i18n.js)
41
45
  // Events:
42
46
  // tess-edit:change detail: { json, ...the kit's outputs, errors, document }:
43
47
  // for an email { json, mjml, html, errors, document }, with
@@ -46,6 +50,7 @@
46
50
  import { Controller } from "@hotwired/stimulus"
47
51
  import { accepted, ancestors, createDocument, createFromPalette, duplicate, find, findType, getValue, insert, itemType, misfit, move, normalize, remove, setValue, walk } from "tess_edit/core/document"
48
52
  import { History } from "tess_edit/core/history"
53
+ import { setTranslations, t } from "tess_edit/core/i18n"
49
54
  import { canEditField, canFill, isFree, parseLock } from "tess_edit/core/lock"
50
55
  import { DEFAULT_KIT, getBlock, getKit, inlinePart, inlineParts, paletteItems, paletteSources } from "tess_edit/core/registry"
51
56
  import { COMPILE_URL } from "tess_edit/export/compile"
@@ -71,6 +76,8 @@ const PANELS_KEY = "tess_edit:panels"
71
76
  const TRANSLATION_LOCALE_KEY = "tess_edit:translation_locale"
72
77
  // Two sidebars (256px + 320px) leave too little canvas below this editor width.
73
78
  const NARROW_WIDTH = 1000
79
+ // Even one sidebar (320px) leaves too little canvas below this editor width.
80
+ const COMPACT_WIDTH = 640
74
81
  const ARROWS = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }
75
82
 
76
83
  // A new block where it was let go in a free layout
@@ -81,9 +88,10 @@ function placed(node, at) {
81
88
 
82
89
  export default class extends Controller {
83
90
  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 }
84
- static targets = ["jsonInput", "mjmlInput", "htmlInput", "slot"]
91
+ static targets = ["jsonInput", "mjmlInput", "htmlInput", "slot", "translations"]
85
92
 
86
93
  connect() {
94
+ if (this.hasTranslationsTarget) setTranslations(this.parseJson(this.translationsTarget.textContent, "translations"))
87
95
  this.kit = getKit(this.kitValue)
88
96
  if (!this.kit) {
89
97
  console.error(`TessEdit: unknown kit ${this.kitValue}, editing an email instead`)
@@ -105,6 +113,8 @@ export default class extends Controller {
105
113
  this.leftTab = "blocks"
106
114
  this.panels = [this.storedPanels(), this.panelsValue].find((value) => PANELS.includes(value)) || "split"
107
115
  this.narrow = false
116
+ this.compact = false
117
+ this.sheetOpen = false
108
118
  this.requests = {}
109
119
  this.media = { enabled: Boolean(this.mediaUrlValue), images: [], uploading: false, error: null }
110
120
  this.variables = new Variables(this.variablesUrlValue)
@@ -190,7 +200,7 @@ export default class extends Controller {
190
200
  const translations = this.translations
191
201
  const locale = this.translationLocale || translations.locales[0]
192
202
  if (!locale) {
193
- this.flash(translations.error || "There are no languages to translate into yet.")
203
+ this.flash(translations.error || t("There are no languages to translate into yet."))
194
204
  return null
195
205
  }
196
206
  const translation = toTranslation(text)
@@ -387,8 +397,9 @@ export default class extends Controller {
387
397
  this.inspectorElement = h("div", { class: "flex flex-1 flex-col min-h-0", dataset: { tessEditPanel: "inspect" } })
388
398
  this.sidePanel = h("aside")
389
399
  this.inspectPanel = h("aside")
400
+ this.sheetClose = h("button", { type: "button", title: t("Hide panels"), class: `${TOOL} ml-auto self-center`, html: icon("close"), onclick: () => this.setSheetOpen(false) })
390
401
  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" })
391
- this.frame = h("iframe", { class: "block h-full w-full border-0 bg-white transition-[width] duration-200", title: `${this.kit.name} canvas` })
402
+ this.frame = h("iframe", { class: "block h-full w-full border-0 bg-white transition-[width] duration-200", title: t("%{name} canvas", { name: t(this.kit.name) }) })
392
403
  this.frameWrap = h("div", { class: "relative h-full mx-auto" }, this.frame)
393
404
  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" })
394
405
  this.body = h("div", { class: "flex flex-1 min-h-0" })
@@ -400,7 +411,7 @@ export default class extends Controller {
400
411
  this.body
401
412
  )
402
413
  this.errorBar = h("div", { class: "hidden absolute inset-x-3 bottom-3 z-20 rounded-md border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/40 px-3 py-2 text-xs text-red-700 dark:text-red-300 shadow-sm", role: "alert" })
403
- this.main = h("main", { class: "relative flex-1 min-w-0 bg-gray-100 dark:bg-gray-900", ondragover: (event) => this.drag && event.preventDefault() }, this.textToolbar, this.frameWrap, this.errorBar)
414
+ this.main = h("main", { class: "relative flex-1 min-w-0 min-h-0 bg-gray-100 dark:bg-gray-900", ondragover: (event) => this.drag && event.preventDefault() }, this.textToolbar, this.frameWrap, this.errorBar)
404
415
  this.arrangePanels()
405
416
  this.element.append(this.root)
406
417
 
@@ -430,20 +441,30 @@ export default class extends Controller {
430
441
  }
431
442
 
432
443
  // Split: Blocks and Layers on the left, Inspect on the right. Left or right:
433
- // one sidebar on that side with Blocks, Layers and Inspect as tabs.
444
+ // one sidebar on that side with Blocks, Layers and Inspect as tabs. Sheet:
445
+ // those tabs in the lower half, below the canvas, while it is open.
434
446
  arrangePanels() {
435
447
  const panelClass = (border, width) => `${width} shrink-0 flex flex-col ${border} border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 min-h-0`
448
+ const sheetClass = `${panelClass("border-t", "h-1/2")}${this.sheetOpen ? "" : " hidden"}`
436
449
  // Only the sidebars move: moving <main> would reload the canvas iframe and blank it.
437
450
  if (!this.main.isConnected) this.body.append(this.main)
451
+ this.body.classList.toggle("flex-col", this.compact)
438
452
  this.inspector?.freezeSlots()
439
453
  if (!this.hasBlocks) {
440
- this.inspectPanel.className = panelClass("border-l", "w-80")
441
- if (this.inspectorElement.parentNode !== this.inspectPanel) this.inspectPanel.replaceChildren(this.inspectorElement)
454
+ this.inspectPanel.className = this.compact ? sheetClass : panelClass("border-l", "w-80")
455
+ const children = this.compact ? [this.sheetHeader(t("Inspect")), this.inspectorElement] : [this.inspectorElement]
456
+ const current = [...this.inspectPanel.children]
457
+ if (current.length !== children.length || children.some((child, index) => current[index] !== child)) this.inspectPanel.replaceChildren(...children)
442
458
  if (this.main.nextSibling !== this.inspectPanel) this.main.after(this.inspectPanel)
443
459
  return
444
460
  }
445
461
  this.sidePanel.replaceChildren(this.leftTabs, this.blocksElement, this.treeElement)
446
- if (this.layout === "split") {
462
+ if (this.layout === "sheet") {
463
+ this.sidePanel.className = sheetClass
464
+ this.sidePanel.append(this.inspectorElement)
465
+ this.inspectPanel.remove()
466
+ this.main.after(this.sidePanel)
467
+ } else if (this.layout === "split") {
447
468
  this.sidePanel.className = panelClass("border-r", "w-64")
448
469
  this.inspectPanel.className = panelClass("border-l", "w-80")
449
470
  this.inspectPanel.replaceChildren(this.inspectorElement)
@@ -457,6 +478,22 @@ export default class extends Controller {
457
478
  }
458
479
  }
459
480
 
481
+ // The sheet's title bar for a kit without blocks, which has no tabs
482
+ sheetHeader(title) {
483
+ this.sheetTitle ||= h("div", { class: "flex items-center h-12 px-3 border-b border-gray-200 dark:border-gray-700 shrink-0 text-[13px] font-medium" })
484
+ this.sheetTitle.replaceChildren(title, this.sheetClose)
485
+ return this.sheetTitle
486
+ }
487
+
488
+ // Shows or hides the panels' sheet on a compact editor
489
+ setSheetOpen(open) {
490
+ if (!this.compact || open === this.sheetOpen) return
491
+ this.sheetOpen = open
492
+ ;(this.hasBlocks ? this.sidePanel : this.inspectPanel).classList.toggle("hidden", !open)
493
+ this.renderTopBar()
494
+ this.canvas.refresh()
495
+ }
496
+
460
497
  setPanels(panels) {
461
498
  if (!PANELS.includes(panels)) return
462
499
  this.panels = panels
@@ -473,13 +510,17 @@ export default class extends Controller {
473
510
  this.renderLeftTabs()
474
511
  }
475
512
 
476
- // Combines the panels while the editor is narrower than NARROW_WIDTH.
513
+ // Combines the panels while the editor is narrower than NARROW_WIDTH, and
514
+ // puts them in a sheet while it is narrower than COMPACT_WIDTH.
477
515
  observeWidth() {
478
516
  if (typeof ResizeObserver === "undefined") return
479
517
  this.resizeObserver = new ResizeObserver(([entry]) => {
480
518
  const narrow = entry.contentRect.width < NARROW_WIDTH
481
- if (narrow === this.narrow) return
519
+ const compact = entry.contentRect.width < COMPACT_WIDTH
520
+ if (narrow === this.narrow && compact === this.compact) return
482
521
  this.narrow = narrow
522
+ if (compact !== this.compact) this.sheetOpen = false
523
+ this.compact = compact
483
524
  this.applyPanels()
484
525
  this.canvas.refresh()
485
526
  })
@@ -490,6 +531,7 @@ export default class extends Controller {
490
531
  // split, or the kit has no blocks
491
532
  get layout() {
492
533
  if (!this.hasBlocks) return "split"
534
+ if (this.compact) return "sheet"
493
535
  return this.narrow && this.panels === "split" ? "left" : this.panels
494
536
  }
495
537
 
@@ -539,31 +581,34 @@ export default class extends Controller {
539
581
  )
540
582
  )
541
583
 
584
+ // A compact editor's top bar scrolls sideways rather than overflow
585
+ this.topBar.classList.toggle("overflow-x-auto", this.compact)
542
586
  // replaceChildren would turn a null into the text "null", so only pass real elements.
543
587
  this.topBar.replaceChildren(...[
544
- h("span", { class: "font-semibold text-gray-900 dark:text-gray-100 mr-3" }, this.kit.name),
545
- toggle(this.mode, [["edit", "edit", "Edit"], ["preview", "eye", this.kit.previewTitle || "Preview"]], (mode) => this.setMode(mode)),
546
- this.kit.devices?.length ? toggle(this.device, this.kit.devices.map((device) => [device.key, device.icon, device.title]), (device) => this.setDevice(device)) : null,
588
+ this.compact ? null : h("span", { class: "font-semibold text-gray-900 dark:text-gray-100 mr-3" }, t(this.kit.name)),
589
+ toggle(this.mode, [["edit", "edit", t("Edit")], ["preview", "eye", this.kit.previewTitle ? t(this.kit.previewTitle) : t("Preview")]], (mode) => this.setMode(mode)),
590
+ this.kit.devices?.length ? toggle(this.device, this.kit.devices.map((device) => [device.key, device.icon, t(device.title)]), (device) => this.setDevice(device)) : null,
547
591
  this.translations.enabled ? this.translationLocaleMenu() : null,
548
592
  h("div", { class: "flex-1" }),
549
- // Without blocks there are no panels to arrange
550
- this.hasBlocks && toggle(
593
+ // A compact editor shows its panels or not; one without blocks has none to arrange
594
+ this.compact && h("button", { type: "button", title: t(this.sheetOpen ? "Hide panels" : "Show panels"), "aria-pressed": String(this.sheetOpen), class: `${TOOL} ${this.sheetOpen ? "bg-gray-100 dark:bg-gray-700" : ""}`, html: icon("panels-bottom"), onclick: () => this.setSheetOpen(!this.sheetOpen) }),
595
+ this.hasBlocks && !this.compact && toggle(
551
596
  this.layout,
552
597
  [
553
- ["left", "panels-left", "All panels on the left"],
554
- ["split", "panels-split", this.narrow ? "Too narrow to split the panels" : "Blocks on the left, Inspect on the right", this.narrow],
555
- ["right", "panels-right", "All panels on the right"]
598
+ ["left", "panels-left", t("All panels on the left")],
599
+ ["split", "panels-split", t(this.narrow ? "Too narrow to split the panels" : "Blocks on the left, Inspect on the right"), this.narrow],
600
+ ["right", "panels-right", t("All panels on the right")]
556
601
  ],
557
602
  (panels) => this.setPanels(panels)
558
603
  ),
559
- this.hasBlocks && h("span", { class: "mx-1 h-5 w-px bg-gray-200 dark:bg-gray-700" }),
560
- h("button", { type: "button", title: "Undo (⌘Z)", class: TOOL, disabled: !this.history.canUndo, html: icon("undo"), onclick: () => this.undo() }),
561
- h("button", { type: "button", title: "Redo (⇧⌘Z)", class: TOOL, disabled: !this.history.canRedo, html: icon("redo"), onclick: () => this.redo() }),
604
+ (this.hasBlocks || this.compact) && h("span", { class: "mx-1 h-5 w-px bg-gray-200 dark:bg-gray-700" }),
605
+ h("button", { type: "button", title: t("Undo (⌘Z)"), class: TOOL, disabled: !this.history.canUndo, html: icon("undo"), onclick: () => this.undo() }),
606
+ h("button", { type: "button", title: t("Redo (⇧⌘Z)"), class: TOOL, disabled: !this.history.canRedo, html: icon("redo"), onclick: () => this.redo() }),
562
607
  h(
563
608
  "button",
564
609
  { type: "button", class: "ml-2 flex items-center gap-1.5 h-8 rounded-md bg-gray-900 px-3 text-[13px] font-medium text-white hover:bg-gray-700 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-300", onclick: () => this.openCodeDialog() },
565
610
  h("span", { html: icon("export") }),
566
- "Code"
611
+ t("Code")
567
612
  )
568
613
  ].filter(Boolean))
569
614
  }
@@ -573,17 +618,17 @@ export default class extends Controller {
573
618
  const current = this.translationLocale || ""
574
619
  return h(
575
620
  "label",
576
- { class: "ml-1 flex items-center gap-1 text-gray-500 dark:text-gray-400", title: "Show translations in" },
621
+ { class: "ml-1 flex items-center gap-1 text-gray-500 dark:text-gray-400", title: t("Show translations in") },
577
622
  h("span", { html: icon("globe") }),
578
623
  h(
579
624
  "select",
580
625
  {
581
626
  class: "h-7 rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 py-0 pl-1.5 pr-7 text-xs text-gray-800 dark:text-gray-200",
582
- "aria-label": "Show translations in",
627
+ "aria-label": t("Show translations in"),
583
628
  onchange: (event) => this.setTranslationLocale(event.target.value)
584
629
  },
585
630
  this.translations.locales.map((locale) => h("option", { value: locale, selected: locale === current }, locale.toUpperCase())),
586
- h("option", { value: "", selected: current === "" }, "Keys")
631
+ h("option", { value: "", selected: current === "" }, t("Keys"))
587
632
  )
588
633
  )
589
634
  }
@@ -592,8 +637,9 @@ export default class extends Controller {
592
637
  const tab = (key, name) =>
593
638
  h("button", { type: "button", class: `${TAB} ${this.leftTab === key ? "border-blue-600 dark:border-blue-400 text-blue-700 dark:text-blue-300" : "border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200"}`, onclick: () => this.setLeftTab(key) }, name)
594
639
  // replaceChildren would turn a null into the text "null", so only pass real tabs.
595
- const tabs = [tab("blocks", "Blocks"), tab("layers", "Layers")]
596
- if (this.combined) tabs.push(tab("inspect", "Inspect"))
640
+ const tabs = [tab("blocks", t("Blocks")), tab("layers", t("Layers"))]
641
+ if (this.combined) tabs.push(tab("inspect", t("Inspect")))
642
+ if (this.compact && this.hasBlocks) tabs.push(this.sheetClose)
597
643
  this.leftTabs.replaceChildren(...tabs)
598
644
  this.blocksElement.classList.toggle("hidden", this.leftTab !== "blocks")
599
645
  this.treeElement.classList.toggle("hidden", this.leftTab !== "layers")
@@ -646,7 +692,7 @@ export default class extends Controller {
646
692
  }
647
693
 
648
694
  showErrors(errors) {
649
- this.errorBar.textContent = errors.length ? `${this.kit.errors}: ${errors.join("; ")}` : ""
695
+ this.errorBar.textContent = errors.length ? `${t(this.kit.errors, { name: t(this.kit.name) })}: ${errors.join("; ")}` : ""
650
696
  this.errorBar.classList.toggle("hidden", !errors.length)
651
697
  }
652
698
 
@@ -704,9 +750,11 @@ export default class extends Controller {
704
750
 
705
751
  // --- selection and editing ---------------------------------------------------
706
752
 
707
- // `reveal` (a click on the canvas) shows the Inspect tab when the panels are combined.
753
+ // `reveal` (a click on the canvas) shows the Inspect tab when the panels are
754
+ // combined, and opens their sheet on a compact editor.
708
755
  select(id, { reveal = false } = {}) {
709
756
  if (reveal && this.combined && this.leftTab !== "inspect") this.setLeftTab("inspect")
757
+ if (reveal) this.setSheetOpen(true)
710
758
  if (this.editingId && this.editingId !== id) this.stopEditing()
711
759
  if (!find(this.doc, id)) id = this.doc.id
712
760
  if (this.selectedId === id) return
@@ -805,6 +853,8 @@ export default class extends Controller {
805
853
  if (drag.kind === "move" && !this.isFree(drag.id)) return
806
854
  this.closeMenu()
807
855
  if (this.editingId) this.stopEditing()
856
+ // Out of the way of the canvas it goes onto
857
+ if (drag.kind !== "move") this.setSheetOpen(false)
808
858
  this.drag = drag
809
859
  this.canvas.setHover(null)
810
860
  }
@@ -869,8 +919,8 @@ export default class extends Controller {
869
919
  const place = this.placeFor((parentId) => this.accepted(parentId).includes(type))
870
920
  if (place) return this.insertAt(key, place.parentId, place.index)
871
921
  const definition = getBlock(type)
872
- if (definition?.unique && findType(this.doc, type)) return this.flash(`There is a ${definition.name} already; a document has one.`)
873
- this.flash(`${definition?.name || key} doesn't fit anywhere yet. Add a block it goes in first, or drag it onto the canvas.`)
922
+ if (definition?.unique && findType(this.doc, type)) return this.flash(t("There is a %{name} already; a document has one.", { name: t(definition.name) }))
923
+ this.flash(t("%{name} doesn't fit anywhere yet. Add a block it goes in first, or drag it onto the canvas.", { name: t(definition?.name) || key }))
874
924
  }
875
925
 
876
926
  // Where a click on a tile adds a block, for blocks that `fits` a parent
@@ -907,12 +957,12 @@ export default class extends Controller {
907
957
  this.flash(error.message)
908
958
  return null
909
959
  }
910
- const name = item.label || getBlock(node.type)?.name || "This"
960
+ const name = t(item.label || getBlock(node.type)?.name) || t("This")
911
961
  const fits = (id) => this.canFill(id) && !misfit(node, accepted(this.doc, id, { moving: true }))
912
962
  const place = parentId ? { parentId, index } : this.placeFor(fits)
913
963
  if (!place || !fits(place.parentId)) {
914
964
  const type = place && misfit(node, accepted(this.doc, place.parentId, { moving: true }))
915
- 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.`)
965
+ this.flash(type && type !== node.type ? t("%{name} can't go here: its %{type} blocks don't fit.", { name, type: t(getBlock(type)?.name) || type }) : t("%{name} doesn't fit here. Select where it goes first, or drag it onto the canvas.", { name }))
916
966
  return null
917
967
  }
918
968
  this.commit((doc) => insert(doc, place.parentId, place.index, node))
@@ -937,7 +987,7 @@ export default class extends Controller {
937
987
  this.menu = h(
938
988
  "div",
939
989
  { class: "fixed z-50 w-56 max-h-80 overflow-y-auto rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-1 shadow-lg", role: "menu", "data-anchor": anchor, "data-tess-edit-menu": "insert" },
940
- h("div", { class: "px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400" }, "Add block"),
990
+ h("div", { class: "px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400" }, t("Add block")),
941
991
  items.map((item) =>
942
992
  h(
943
993
  "button",
@@ -951,7 +1001,7 @@ export default class extends Controller {
951
1001
  }
952
1002
  },
953
1003
  h("span", { class: "text-gray-400 dark:text-gray-500", html: icon(item.icon) }),
954
- item.label
1004
+ t(item.label)
955
1005
  )
956
1006
  )
957
1007
  )
@@ -1039,7 +1089,7 @@ export default class extends Controller {
1039
1089
  status.textContent = error.message
1040
1090
  status.className = "text-xs text-red-600 dark:text-red-400"
1041
1091
  }
1042
- } }, "Load this JSON")
1092
+ } }, t("Load this JSON"))
1043
1093
 
1044
1094
  const show = (key) => {
1045
1095
  tab = key
@@ -1050,7 +1100,7 @@ export default class extends Controller {
1050
1100
  apply.classList.toggle("hidden", !loadable)
1051
1101
  status.className = "text-xs text-gray-500 dark:text-gray-400"
1052
1102
  status.textContent =
1053
- 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] || ""
1103
+ key === "json" ? t(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 ? `${t(this.kit.errors, { name: t(this.kit.name) })}: ${errors.join("; ")}` : t(this.kit.notes?.[key]) || ""
1054
1104
  tabs.replaceChildren(
1055
1105
  ...Object.keys(contents).map((name) =>
1056
1106
  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())
@@ -1072,13 +1122,13 @@ export default class extends Controller {
1072
1122
  h(
1073
1123
  "div",
1074
1124
  { class: "flex h-full max-h-[720px] w-full max-w-4xl flex-col gap-3 rounded-xl bg-white dark:bg-gray-800 p-4 shadow-xl" },
1075
- h("div", { class: "flex items-center gap-3" }, tabs, status, h("button", { type: "button", class: "ml-auto " + TOOL, title: "Close", html: icon("close"), onclick: close })),
1125
+ h("div", { class: "flex items-center gap-3" }, tabs, status, h("button", { type: "button", class: "ml-auto " + TOOL, title: t("Close"), html: icon("close"), onclick: close })),
1076
1126
  textarea,
1077
1127
  h(
1078
1128
  "div",
1079
1129
  { class: "flex items-center justify-end gap-2" },
1080
- h("button", { type: "button", class: "rounded-md border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-xs font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700", onclick: () => navigator.clipboard?.writeText(textarea.value).then(() => (status.textContent = "Copied.")) }, "Copy"),
1081
- h("button", { type: "button", class: "rounded-md border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-xs font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700", onclick: download }, "Download"),
1130
+ h("button", { type: "button", class: "rounded-md border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-xs font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700", onclick: () => navigator.clipboard?.writeText(textarea.value).then(() => (status.textContent = t("Copied."))) }, t("Copy")),
1131
+ h("button", { type: "button", class: "rounded-md border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-xs font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700", onclick: download }, t("Download")),
1082
1132
  apply
1083
1133
  )
1084
1134
  )
@@ -0,0 +1,32 @@
1
+ // The editor's own words (its labels, titles, hints and messages) in the
2
+ // language of the page it's on. They're written in English everywhere, and
3
+ // that English is the key: the host gives what each says in its language as
4
+ // JSON in the editor, rendered by the tess_edit_translations helper from its
5
+ // locale files (config/locales/*.yml), with its own and its kits' words too:
6
+ //
7
+ // <div data-controller="tess-edit">
8
+ // <%= tess_edit_translations "nuntius.editor" %>
9
+ //
10
+ // <script type="application/json" data-tess-edit-target="translations">
11
+ // { "Preview text": "Voorbeeldtekst", "Edit %{label} in a larger window": "%{label} in een groter venster bewerken", … }
12
+ // </script>
13
+ //
14
+ // A block's or kit's definitions keep their English (a group's title is how
15
+ // another one says where it goes: before: "Message"); the editor translates
16
+ // them where it shows them. Without a text in the JSON it shows the English.
17
+ // One language for the page, so one set of words for all its editors.
18
+
19
+ let words = {}
20
+
21
+ export function setTranslations(translations) {
22
+ words = translations || {}
23
+ }
24
+
25
+ // A text in the page's language, its %{name}s filled from values:
26
+ //
27
+ // t("Edit %{label} in a larger window", { label: t(field.label) })
28
+ export function t(text, values = {}) {
29
+ if (typeof text !== "string" || !text) return text
30
+ const translated = Object.hasOwn(words, text) ? words[text] : text
31
+ return translated.replace(/%\{(\w+)\}/g, (placeholder, name) => (Object.hasOwn(values, name) ? String(values[name]) : placeholder))
32
+ }
@@ -8,6 +8,7 @@
8
8
  // key, the id and where the image comes from in its `image` and `source` keys.
9
9
 
10
10
  import { getValue } from "tess_edit/core/document"
11
+ import { t } from "tess_edit/core/i18n"
11
12
 
12
13
  function csrfHeaders() {
13
14
  const token = document.querySelector("meta[name='csrf-token']")?.content
@@ -16,20 +17,20 @@ function csrfHeaders() {
16
17
 
17
18
  async function json(response, action) {
18
19
  const result = (response.headers.get("Content-Type") || "").includes("json") ? await response.json() : null
19
- if (!response.ok || !result) throw new Error(result?.errors?.join(", ") || `${action} failed (${response.status} ${response.statusText})`)
20
+ if (!response.ok || !result) throw new Error(result?.errors?.join(", ") || t("%{action} failed (%{status})", { action, status: `${response.status} ${response.statusText}` }))
20
21
  return result
21
22
  }
22
23
 
23
24
  export async function fetchMedia(url) {
24
25
  const response = await fetch(url, { headers: { Accept: "application/json" }, credentials: "same-origin" })
25
- return (await json(response, "Loading the images")).images || []
26
+ return (await json(response, t("Loading the images"))).images || []
26
27
  }
27
28
 
28
29
  export async function uploadMedia(url, file) {
29
30
  const body = new FormData()
30
31
  body.append("file", file)
31
32
  const response = await fetch(url, { method: "POST", headers: { Accept: "application/json", ...csrfHeaders() }, body, credentials: "same-origin" })
32
- return json(response, "The upload")
33
+ return json(response, t("The upload"))
33
34
  }
34
35
 
35
36
  // The Image block's image field
@@ -81,6 +81,7 @@
81
81
  // gem replaced it.
82
82
 
83
83
  import { builtinBlocks, builtinCategories } from "tess_edit/blocks/builtin"
84
+ import { t } from "tess_edit/core/i18n"
84
85
  import { builtinKits } from "tess_edit/kits/builtin"
85
86
 
86
87
  const definitions = new Map()
@@ -91,12 +92,15 @@ const fieldTypeList = new Map()
91
92
 
92
93
  export const DEFAULT_KIT = "email"
93
94
 
95
+ // What the editor says when a kit's canvas can't be rendered, unless the kit says it itself (errors)
96
+ export const KIT_ERRORS = "The %{name} could not be rendered"
97
+
94
98
  export function registerKit(kit) {
95
99
  const { key, name, root, canvas, outputs } = kit || {}
96
100
  if (!key || !name) throw new Error("A kit needs a key and a name")
97
101
  if (!root) throw new Error(`Kit ${key} needs a root block type`)
98
102
  if (typeof canvas !== "function" || typeof outputs !== "function") throw new Error(`Kit ${key} needs canvas(doc, options) and outputs(doc, options)`)
99
- kitList.set(key, { devices: null, notes: {}, errors: `The ${name} could not be rendered`, ...kit })
103
+ kitList.set(key, { devices: null, notes: {}, errors: KIT_ERRORS, ...kit })
100
104
  return kitList.get(key)
101
105
  }
102
106
 
@@ -268,7 +272,7 @@ export function paletteItem(key) {
268
272
 
269
273
  export function label(node) {
270
274
  const definition = getBlock(node.type)
271
- return definition?.label?.(node) || definition?.name || node.type
275
+ return definition?.label?.(node) || t(definition?.name) || node.type
272
276
  }
273
277
 
274
278
  builtinKits.forEach(registerKit)
@@ -20,6 +20,8 @@
20
20
  //
21
21
  // which answers 422 with { errors: [...] } when it can't be saved.
22
22
 
23
+ import { t } from "tess_edit/core/i18n"
24
+
23
25
  // A t filter on a quoted key, with what follows it in the tag (its arguments)
24
26
  const CALL = /\{\{-?\s*(["'])([^"'{}|]+?)\1\s*\|\s*t(?:ranslate)?\b((?:(?!\}\}).)*?)-?\}\}/g
25
27
 
@@ -68,7 +70,7 @@ const RESERVED = new Set(["locale", "scope", "default", "separator", "resolve",
68
70
  // Gives { error } for Liquid a translation can't hold: tags ({% … %}) and
69
71
  // filters ({{ total | money }}).
70
72
  export function toTranslation(text) {
71
- if (/\{%/.test(text)) return { error: "Liquid tags ({% … %}) can't go into a translation. Select the text around them." }
73
+ if (/\{%/.test(text)) return { error: t("Liquid tags ({% … %}) can't go into a translation. Select the text around them.") }
72
74
  const args = []
73
75
  let error = null
74
76
  const converted = String(text).replace(/\{\{-?\s*(.*?)\s*-?\}\}/g, (tag, expression) => {
@@ -174,7 +176,7 @@ export class Translations {
174
176
  if (missing.length) url.searchParams.set("keys", missing.join(","))
175
177
  try {
176
178
  const response = await this.fetch(url, { headers: { Accept: "application/json" }, credentials: "same-origin" })
177
- if (!response.ok) throw new Error(`Loading the translations failed (${response.status} ${response.statusText})`)
179
+ if (!response.ok) throw new Error(t("Loading the translations failed (%{status})", { status: `${response.status} ${response.statusText}` }))
178
180
  const result = await response.json()
179
181
  this.locales = result.locales || []
180
182
  for (const [key, entry] of Object.entries(result.translations || {})) this.entries.set(key, entry || {})
@@ -220,7 +222,7 @@ export class Translations {
220
222
  credentials: "same-origin"
221
223
  })
222
224
  const result = (response.headers?.get("Content-Type") || "").includes("json") ? await response.json() : {}
223
- if (!response.ok) throw new Error(result.errors?.join(", ") || `Saving the translation failed (${response.status} ${response.statusText})`)
225
+ if (!response.ok) throw new Error(result.errors?.join(", ") || t("Saving the translation failed (%{status})", { status: `${response.status} ${response.statusText}` }))
224
226
  this.entries.set(key, result.translation || {})
225
227
  if (!this.suggestions.includes(key) && key.startsWith(".")) this.suggestions = [...this.suggestions, key].sort()
226
228
  this.changed()
@@ -14,6 +14,7 @@
14
14
  // such a path before asking.
15
15
 
16
16
  import { ancestors } from "tess_edit/core/document"
17
+ import { t } from "tess_edit/core/i18n"
17
18
 
18
19
  // The members Liquid gives every collection
19
20
  export const COLLECTION_MEMBERS = [
@@ -50,7 +51,7 @@ export class Variables {
50
51
  if (path) url.searchParams.set("path", path)
51
52
  const response = await this.fetch(url, { headers: { Accept: "application/json" }, credentials: "same-origin" })
52
53
  if (response.status === 404) return []
53
- if (!response.ok) throw new Error(`Loading the variables failed (${response.status} ${response.statusText})`)
54
+ if (!response.ok) throw new Error(t("Loading the variables failed (%{status})", { status: `${response.status} ${response.statusText}` }))
54
55
  return (await response.json()).variables || []
55
56
  }
56
57
 
@@ -84,7 +85,7 @@ export class Variables {
84
85
  }
85
86
 
86
87
  function loopVariable({ variable, collection }) {
87
- return { name: variable, label: `Each of ${collection}`, type: "object", children: true, loop: true }
88
+ return { name: variable, label: t("Each of %{collection}", { collection }), type: "object", children: true, loop: true }
88
89
  }
89
90
 
90
91
  // The path the host knows a template's path by: loop variables become their
@@ -23,6 +23,7 @@
23
23
  // liquid(node, open, close) children wrapped in Liquid tags (not in the editor)
24
24
  // indent(text, level), escapeText, escapeAttribute, richText(content)
25
25
 
26
+ import { t } from "tess_edit/core/i18n"
26
27
  import { getBlock } from "tess_edit/core/registry"
27
28
  import { escapeAttribute, escapeText, richTextToHtml } from "tess_edit/export/richtext"
28
29
 
@@ -71,7 +72,7 @@ class Renderer {
71
72
  }
72
73
 
73
74
  placeholder(node, context) {
74
- const text = context === "body" ? "Drop a section here" : context === "section" ? "Drop a column here" : "Drop content here"
75
+ const text = t(context === "body" ? "Drop a section here" : context === "section" ? "Drop a column here" : "Drop content here")
75
76
  const mjText = `<mj-text css-class="tessph-${node.id}" align="center" color="${PLACEHOLDER_COLOR}" font-size="13px" padding="18px 25px">${text}</mj-text>`
76
77
  if (context === "column") return mjText
77
78
  if (context === "section") return `<mj-column css-class="tessph-${node.id}">\n ${mjText}\n</mj-column>`