tess_edit 0.5.6 → 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: f40808bae8dcda2f666c84361d3827261aaec15ae2260df2dede99b15d6783b2
4
- data.tar.gz: 2f68441c824237fc96a258305d5583f473ad4f8fd4630d4a6d9b2cb65a946b7f
3
+ metadata.gz: b4f503a410953c3f8a0fe8182ef443136e0f2e6d8aed2f59d231b9e6417385e9
4
+ data.tar.gz: 42472bc71adb394f68d7ee5ede4ed7621692a20c0d96a60cc04849944f2aeb95
5
5
  SHA512:
6
- metadata.gz: 2dbde1a8dde3fbad145f33c77547547ed7cd9973557f8c54941ac9d26b78511f93ee283e722c866e1d4d893e93c4eddf3e4b8163c119be6acea14f5b86669136
7
- data.tar.gz: 46eb21506a8e333555a6bd5c7454c1cae49286de3f8eaa0ad2292a8ae6b8a1922e28bfef7d8698f40e17da900b4d853af392ef730d3846c73a9af0fab087daba
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
  }
@@ -40,6 +40,8 @@
40
40
  // the kit's outputs (an <output>Input target for each)
41
41
  // slot an element of the host's, named by data-tess-edit-slot,
42
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)
43
45
  // Events:
44
46
  // tess-edit:change detail: { json, ...the kit's outputs, errors, document }:
45
47
  // for an email { json, mjml, html, errors, document }, with
@@ -48,6 +50,7 @@
48
50
  import { Controller } from "@hotwired/stimulus"
49
51
  import { accepted, ancestors, createDocument, createFromPalette, duplicate, find, findType, getValue, insert, itemType, misfit, move, normalize, remove, setValue, walk } from "tess_edit/core/document"
50
52
  import { History } from "tess_edit/core/history"
53
+ import { setTranslations, t } from "tess_edit/core/i18n"
51
54
  import { canEditField, canFill, isFree, parseLock } from "tess_edit/core/lock"
52
55
  import { DEFAULT_KIT, getBlock, getKit, inlinePart, inlineParts, paletteItems, paletteSources } from "tess_edit/core/registry"
53
56
  import { COMPILE_URL } from "tess_edit/export/compile"
@@ -85,9 +88,10 @@ function placed(node, at) {
85
88
 
86
89
  export default class extends Controller {
87
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 }
88
- static targets = ["jsonInput", "mjmlInput", "htmlInput", "slot"]
91
+ static targets = ["jsonInput", "mjmlInput", "htmlInput", "slot", "translations"]
89
92
 
90
93
  connect() {
94
+ if (this.hasTranslationsTarget) setTranslations(this.parseJson(this.translationsTarget.textContent, "translations"))
91
95
  this.kit = getKit(this.kitValue)
92
96
  if (!this.kit) {
93
97
  console.error(`TessEdit: unknown kit ${this.kitValue}, editing an email instead`)
@@ -196,7 +200,7 @@ export default class extends Controller {
196
200
  const translations = this.translations
197
201
  const locale = this.translationLocale || translations.locales[0]
198
202
  if (!locale) {
199
- 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."))
200
204
  return null
201
205
  }
202
206
  const translation = toTranslation(text)
@@ -393,9 +397,9 @@ export default class extends Controller {
393
397
  this.inspectorElement = h("div", { class: "flex flex-1 flex-col min-h-0", dataset: { tessEditPanel: "inspect" } })
394
398
  this.sidePanel = h("aside")
395
399
  this.inspectPanel = h("aside")
396
- this.sheetClose = h("button", { type: "button", title: "Hide panels", class: `${TOOL} ml-auto self-center`, html: icon("close"), onclick: () => this.setSheetOpen(false) })
400
+ this.sheetClose = h("button", { type: "button", title: t("Hide panels"), class: `${TOOL} ml-auto self-center`, html: icon("close"), onclick: () => this.setSheetOpen(false) })
397
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" })
398
- 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) }) })
399
403
  this.frameWrap = h("div", { class: "relative h-full mx-auto" }, this.frame)
400
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" })
401
405
  this.body = h("div", { class: "flex flex-1 min-h-0" })
@@ -448,7 +452,7 @@ export default class extends Controller {
448
452
  this.inspector?.freezeSlots()
449
453
  if (!this.hasBlocks) {
450
454
  this.inspectPanel.className = this.compact ? sheetClass : panelClass("border-l", "w-80")
451
- const children = this.compact ? [this.sheetHeader("Inspect"), this.inspectorElement] : [this.inspectorElement]
455
+ const children = this.compact ? [this.sheetHeader(t("Inspect")), this.inspectorElement] : [this.inspectorElement]
452
456
  const current = [...this.inspectPanel.children]
453
457
  if (current.length !== children.length || children.some((child, index) => current[index] !== child)) this.inspectPanel.replaceChildren(...children)
454
458
  if (this.main.nextSibling !== this.inspectPanel) this.main.after(this.inspectPanel)
@@ -581,30 +585,30 @@ export default class extends Controller {
581
585
  this.topBar.classList.toggle("overflow-x-auto", this.compact)
582
586
  // replaceChildren would turn a null into the text "null", so only pass real elements.
583
587
  this.topBar.replaceChildren(...[
584
- this.compact ? null : h("span", { class: "font-semibold text-gray-900 dark:text-gray-100 mr-3" }, this.kit.name),
585
- toggle(this.mode, [["edit", "edit", "Edit"], ["preview", "eye", this.kit.previewTitle || "Preview"]], (mode) => this.setMode(mode)),
586
- 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,
587
591
  this.translations.enabled ? this.translationLocaleMenu() : null,
588
592
  h("div", { class: "flex-1" }),
589
593
  // A compact editor shows its panels or not; one without blocks has none to arrange
590
- this.compact && h("button", { type: "button", title: 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) }),
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) }),
591
595
  this.hasBlocks && !this.compact && toggle(
592
596
  this.layout,
593
597
  [
594
- ["left", "panels-left", "All panels on the left"],
595
- ["split", "panels-split", this.narrow ? "Too narrow to split the panels" : "Blocks on the left, Inspect on the right", this.narrow],
596
- ["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")]
597
601
  ],
598
602
  (panels) => this.setPanels(panels)
599
603
  ),
600
604
  (this.hasBlocks || this.compact) && h("span", { class: "mx-1 h-5 w-px bg-gray-200 dark:bg-gray-700" }),
601
- h("button", { type: "button", title: "Undo (⌘Z)", class: TOOL, disabled: !this.history.canUndo, html: icon("undo"), onclick: () => this.undo() }),
602
- h("button", { type: "button", title: "Redo (⇧⌘Z)", class: TOOL, disabled: !this.history.canRedo, html: icon("redo"), onclick: () => this.redo() }),
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() }),
603
607
  h(
604
608
  "button",
605
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() },
606
610
  h("span", { html: icon("export") }),
607
- "Code"
611
+ t("Code")
608
612
  )
609
613
  ].filter(Boolean))
610
614
  }
@@ -614,17 +618,17 @@ export default class extends Controller {
614
618
  const current = this.translationLocale || ""
615
619
  return h(
616
620
  "label",
617
- { 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") },
618
622
  h("span", { html: icon("globe") }),
619
623
  h(
620
624
  "select",
621
625
  {
622
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",
623
- "aria-label": "Show translations in",
627
+ "aria-label": t("Show translations in"),
624
628
  onchange: (event) => this.setTranslationLocale(event.target.value)
625
629
  },
626
630
  this.translations.locales.map((locale) => h("option", { value: locale, selected: locale === current }, locale.toUpperCase())),
627
- h("option", { value: "", selected: current === "" }, "Keys")
631
+ h("option", { value: "", selected: current === "" }, t("Keys"))
628
632
  )
629
633
  )
630
634
  }
@@ -633,8 +637,8 @@ export default class extends Controller {
633
637
  const tab = (key, name) =>
634
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)
635
639
  // replaceChildren would turn a null into the text "null", so only pass real tabs.
636
- const tabs = [tab("blocks", "Blocks"), tab("layers", "Layers")]
637
- 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")))
638
642
  if (this.compact && this.hasBlocks) tabs.push(this.sheetClose)
639
643
  this.leftTabs.replaceChildren(...tabs)
640
644
  this.blocksElement.classList.toggle("hidden", this.leftTab !== "blocks")
@@ -688,7 +692,7 @@ export default class extends Controller {
688
692
  }
689
693
 
690
694
  showErrors(errors) {
691
- 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("; ")}` : ""
692
696
  this.errorBar.classList.toggle("hidden", !errors.length)
693
697
  }
694
698
 
@@ -915,8 +919,8 @@ export default class extends Controller {
915
919
  const place = this.placeFor((parentId) => this.accepted(parentId).includes(type))
916
920
  if (place) return this.insertAt(key, place.parentId, place.index)
917
921
  const definition = getBlock(type)
918
- if (definition?.unique && findType(this.doc, type)) return this.flash(`There is a ${definition.name} already; a document has one.`)
919
- 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 }))
920
924
  }
921
925
 
922
926
  // Where a click on a tile adds a block, for blocks that `fits` a parent
@@ -953,12 +957,12 @@ export default class extends Controller {
953
957
  this.flash(error.message)
954
958
  return null
955
959
  }
956
- const name = item.label || getBlock(node.type)?.name || "This"
960
+ const name = t(item.label || getBlock(node.type)?.name) || t("This")
957
961
  const fits = (id) => this.canFill(id) && !misfit(node, accepted(this.doc, id, { moving: true }))
958
962
  const place = parentId ? { parentId, index } : this.placeFor(fits)
959
963
  if (!place || !fits(place.parentId)) {
960
964
  const type = place && misfit(node, accepted(this.doc, place.parentId, { moving: true }))
961
- 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 }))
962
966
  return null
963
967
  }
964
968
  this.commit((doc) => insert(doc, place.parentId, place.index, node))
@@ -983,7 +987,7 @@ export default class extends Controller {
983
987
  this.menu = h(
984
988
  "div",
985
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" },
986
- 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")),
987
991
  items.map((item) =>
988
992
  h(
989
993
  "button",
@@ -997,7 +1001,7 @@ export default class extends Controller {
997
1001
  }
998
1002
  },
999
1003
  h("span", { class: "text-gray-400 dark:text-gray-500", html: icon(item.icon) }),
1000
- item.label
1004
+ t(item.label)
1001
1005
  )
1002
1006
  )
1003
1007
  )
@@ -1085,7 +1089,7 @@ export default class extends Controller {
1085
1089
  status.textContent = error.message
1086
1090
  status.className = "text-xs text-red-600 dark:text-red-400"
1087
1091
  }
1088
- } }, "Load this JSON")
1092
+ } }, t("Load this JSON"))
1089
1093
 
1090
1094
  const show = (key) => {
1091
1095
  tab = key
@@ -1096,7 +1100,7 @@ export default class extends Controller {
1096
1100
  apply.classList.toggle("hidden", !loadable)
1097
1101
  status.className = "text-xs text-gray-500 dark:text-gray-400"
1098
1102
  status.textContent =
1099
- 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]) || ""
1100
1104
  tabs.replaceChildren(
1101
1105
  ...Object.keys(contents).map((name) =>
1102
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())
@@ -1118,13 +1122,13 @@ export default class extends Controller {
1118
1122
  h(
1119
1123
  "div",
1120
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" },
1121
- 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 })),
1122
1126
  textarea,
1123
1127
  h(
1124
1128
  "div",
1125
1129
  { class: "flex items-center justify-end gap-2" },
1126
- 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"),
1127
- 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")),
1128
1132
  apply
1129
1133
  )
1130
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>`
@@ -3,6 +3,7 @@
3
3
  // allowed. The tiles of the host's palette sources (core/registry.js) follow,
4
4
  // a list per source, to drag or click in the same way.
5
5
 
6
+ import { t } from "tess_edit/core/i18n"
6
7
  import { categories, getBlock } from "tess_edit/core/registry"
7
8
  import { h } from "tess_edit/ui/dom"
8
9
  import { icon } from "tess_edit/ui/icons"
@@ -13,7 +14,7 @@ export function renderBlocksPanel(editor, element) {
13
14
  h(
14
15
  "section",
15
16
  { class: "px-3 pt-3" },
16
- h("h3", { class: "mb-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400" }, category.label),
17
+ h("h3", { class: "mb-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400" }, t(category.label)),
17
18
  h(
18
19
  "div",
19
20
  { class: "grid grid-cols-3 gap-1.5" },
@@ -25,7 +26,7 @@ export function renderBlocksPanel(editor, element) {
25
26
  {
26
27
  type: "button",
27
28
  draggable: true,
28
- title: `Drag onto the canvas, or click to add`,
29
+ title: t("Drag onto the canvas, or click to add"),
29
30
  class: `flex flex-col items-center justify-center gap-1 h-16 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 hover:border-blue-400 hover:text-blue-600 dark:hover:text-blue-400 hover:shadow-sm cursor-grab active:cursor-grabbing ${category.key === "liquid" ? "text-amber-700 dark:text-amber-400" : ""}`,
30
31
  ondragstart: (event) => {
31
32
  event.dataTransfer.effectAllowed = "copy"
@@ -36,13 +37,13 @@ export function renderBlocksPanel(editor, element) {
36
37
  onclick: () => editor.addFromPalette(item.key)
37
38
  },
38
39
  h("span", { html: icon(item.icon, "w-5 h-5") }),
39
- h("span", { class: "text-[11px] leading-none" }, item.label)
40
+ h("span", { class: "text-[11px] leading-none" }, t(item.label))
40
41
  )
41
42
  )
42
43
  )
43
44
  )
44
45
  )
45
- element.replaceChildren(...groups, ...sourceSections(editor), h("p", { class: "px-3 py-4 text-xs text-gray-500 dark:text-gray-400" }, "Drag blocks onto the canvas or into the Layers tree. Liquid blocks wrap other blocks in {% for %} or {% if %}."))
46
+ element.replaceChildren(...groups, ...sourceSections(editor), h("p", { class: "px-3 py-4 text-xs text-gray-500 dark:text-gray-400" }, t("Drag blocks onto the canvas or into the Layers tree. Liquid blocks wrap other blocks in {% for %} or {% if %}.")))
46
47
  }
47
48
 
48
49
  const SEARCH_FROM = 8
@@ -60,7 +61,7 @@ function sourceSections(editor) {
60
61
  {
61
62
  type: "button",
62
63
  draggable: true,
63
- title: item.description || "Drag onto the canvas, or click to add",
64
+ title: item.description || t("Drag onto the canvas, or click to add"),
64
65
  "data-tess-edit-source-item": item.key,
65
66
  class: "flex w-full items-center gap-2 rounded-md border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 px-2 py-1.5 text-left text-[13px] text-gray-700 dark:text-gray-300 hover:border-blue-400 hover:text-blue-600 dark:hover:text-blue-400 cursor-grab active:cursor-grabbing",
66
67
  ondragstart: (event) => {
@@ -76,15 +77,15 @@ function sourceSections(editor) {
76
77
  item.version ? h("span", { class: "text-[11px] text-gray-400 dark:text-gray-500" }, `v${item.version}`) : null
77
78
  )
78
79
  ),
79
- ...(matches.length ? [] : [h("p", { class: "text-xs text-gray-500 dark:text-gray-400" }, items.length ? "Nothing matches." : "There's nothing here yet.")])
80
+ ...(matches.length ? [] : [h("p", { class: "text-xs text-gray-500 dark:text-gray-400" }, t(items.length ? "Nothing matches." : "There's nothing here yet."))])
80
81
  )
81
82
  }
82
83
  show()
83
- const search = items.length >= SEARCH_FROM ? h("input", { type: "search", placeholder: `Find in ${source.label}`, class: "mb-2 w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-2 py-1 text-[13px]", oninput: (event) => show(event.target.value) }) : null
84
+ const search = items.length >= SEARCH_FROM ? h("input", { type: "search", placeholder: t("Find in %{source}", { source: t(source.label) }), class: "mb-2 w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-2 py-1 text-[13px]", oninput: (event) => show(event.target.value) }) : null
84
85
  return h(
85
86
  "section",
86
87
  { class: "px-3 pt-3", "data-tess-edit-source": source.key },
87
- h("h3", { class: "mb-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400" }, source.label),
88
+ h("h3", { class: "mb-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400" }, t(source.label)),
88
89
  error ? h("p", { class: "text-xs text-red-600 dark:text-red-400" }, error) : null,
89
90
  search,
90
91
  rows
@@ -5,6 +5,7 @@
5
5
  // filters show their text in the editor's language (see annotate).
6
6
 
7
7
  import { ancestors, find, isDescendant, isHorizontal } from "tess_edit/core/document"
8
+ import { t } from "tess_edit/core/i18n"
8
9
  import { imageFields } from "tess_edit/core/media"
9
10
  import { getBlock, inlinePart, label } from "tess_edit/core/registry"
10
11
  import { missingArguments, textParts, translationCalls } from "tess_edit/core/translations"
@@ -173,7 +174,7 @@ export class Canvas {
173
174
  const unfilled = value === null ? [] : missingArguments(value, { args: span.dataset.tessArgs ? span.dataset.tessArgs.split(",") : [] })
174
175
  if (value === null) span.textContent = span.dataset.tessCall
175
176
  else showText(span, value)
176
- span.title = unfilled.length ? `No argument for ${unfilled.map((name) => `%{${name}}`).join(", ")} in the t filter` : ""
177
+ span.title = unfilled.length ? t("No argument for %{names} in the t filter", { names: unfilled.map((name) => `%{${name}}`).join(", ") }) : ""
177
178
  span.classList.toggle("tess-t-missing", unfilled.length > 0 || (translations.has(key) && (locale ? value === null : translations.missing(key).length > 0)))
178
179
  }
179
180
  this.refresh()
@@ -278,7 +279,7 @@ export class Canvas {
278
279
  if (!rect) return
279
280
  const box = this.box(rect, editingId === selectedId ? "tess-selected tess-editing" : "tess-selected")
280
281
  const free = this.editor.isFree(selectedId)
281
- box.append(Object.assign(this.doc.createElement("div"), { className: "tess-label", textContent: editingId === selectedId ? `Editing text · ${this.editor.editingPart?.plain ? "Enter" : "Esc"} to finish` : free || !this.editor.lock ? label(hit.node) : `${label(hit.node)} · Layout` }))
282
+ box.append(Object.assign(this.doc.createElement("div"), { className: "tess-label", textContent: editingId === selectedId ? t("Editing text · %{key} to finish", { key: this.editor.editingPart?.plain ? "Enter" : "Esc" }) : free || !this.editor.lock ? label(hit.node) : `${label(hit.node)} · ${t("Layout")}` }))
282
283
 
283
284
  const handle = this.free.handle(selectedId)
284
285
  if (handle) box.append(handle)
@@ -287,8 +288,8 @@ export class Canvas {
287
288
  const tools = this.doc.createElement("div")
288
289
  tools.className = "tess-tools"
289
290
  tools.innerHTML = [
290
- ["parent", "Select parent"],
291
- ...(free ? [["drag", "Drag to move"], ["duplicate", "Duplicate"], ["delete", "Delete"]] : [])
291
+ ["parent", t("Select parent")],
292
+ ...(free ? [["drag", t("Drag to move")], ["duplicate", t("Duplicate")], ["delete", t("Delete")]] : [])
292
293
  ]
293
294
  .map(([tool, title]) => `<span data-tool="${tool}" title="${title}" ${tool === "drag" ? 'draggable="true"' : ""}>${icon({ parent: "parent", drag: "move", duplicate: "copy", delete: "trash" }[tool], "tess-icon")}</span>`)
294
295
  .join("")
@@ -315,7 +316,7 @@ export class Canvas {
315
316
  if (hit.parent && this.editor.canFill(hit.parent.id)) {
316
317
  const plus = this.doc.createElement("button")
317
318
  plus.className = "tess-plus"
318
- plus.title = "Add a block below"
319
+ plus.title = t("Add a block below")
319
320
  plus.innerHTML = icon("plus")
320
321
  plus.querySelector("svg").setAttribute("style", "width:12px;height:12px")
321
322
  plus.addEventListener("click", (event) => {