tess_edit 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +114 -9
  3. data/app/javascript/tess_edit/blocks/builtin.js +3 -2
  4. data/app/javascript/tess_edit/blocks/button.js +3 -1
  5. data/app/javascript/tess_edit/blocks/column.js +3 -1
  6. data/app/javascript/tess_edit/blocks/condition.js +3 -1
  7. data/app/javascript/tess_edit/blocks/content.js +36 -0
  8. data/app/javascript/tess_edit/blocks/divider.js +3 -1
  9. data/app/javascript/tess_edit/blocks/{root.js → email.js} +3 -3
  10. data/app/javascript/tess_edit/blocks/fields.js +4 -2
  11. data/app/javascript/tess_edit/blocks/image.js +3 -1
  12. data/app/javascript/tess_edit/blocks/loop.js +3 -1
  13. data/app/javascript/tess_edit/blocks/section.js +4 -2
  14. data/app/javascript/tess_edit/blocks/spacer.js +3 -1
  15. data/app/javascript/tess_edit/blocks/text.js +3 -1
  16. data/app/javascript/tess_edit/controllers/editor_controller.js +267 -60
  17. data/app/javascript/tess_edit/core/document.js +66 -16
  18. data/app/javascript/tess_edit/core/registry.js +119 -11
  19. data/app/javascript/tess_edit/core/translations.js +229 -0
  20. data/app/javascript/tess_edit/index.js +4 -3
  21. data/app/javascript/tess_edit/kits/builtin.js +5 -0
  22. data/app/javascript/tess_edit/kits/email.js +28 -0
  23. data/app/javascript/tess_edit/ui/blocks_panel.js +54 -5
  24. data/app/javascript/tess_edit/ui/canvas.js +96 -12
  25. data/app/javascript/tess_edit/ui/dialog.js +103 -0
  26. data/app/javascript/tess_edit/ui/icons.js +5 -1
  27. data/app/javascript/tess_edit/ui/inspector.js +76 -7
  28. data/app/javascript/tess_edit/ui/text_editing.js +112 -11
  29. data/app/javascript/tess_edit/ui/translate_dialog.js +30 -0
  30. data/app/javascript/tess_edit/ui/translation_popover.js +165 -0
  31. data/app/javascript/tess_edit/ui/tree.js +2 -2
  32. data/app/javascript/tess_edit/ui/variable_menu.js +29 -1
  33. data/lib/tess_edit/content.rb +62 -0
  34. data/lib/tess_edit/version.rb +1 -1
  35. data/lib/tess_edit.rb +1 -0
  36. data/vendor/javascript/tess_edit/tiptap.js +13 -13
  37. metadata +10 -2
@@ -1,13 +1,15 @@
1
1
  // The Blocks panel: draggable tiles, grouped by category. Clicking a tile adds
2
- // it after the selected block (or at the end of the page) when that is allowed.
2
+ // it after the selected block (or at the end of the document) when that is
3
+ // allowed. The tiles of the host's palette sources (core/registry.js) follow,
4
+ // a list per source, to drag or click in the same way.
3
5
 
4
- import { categories, paletteItems } from "tess_edit/core/registry"
6
+ import { categories, getBlock } from "tess_edit/core/registry"
5
7
  import { h } from "tess_edit/ui/dom"
6
8
  import { icon } from "tess_edit/ui/icons"
7
9
 
8
10
  export function renderBlocksPanel(editor, element) {
9
- const items = paletteItems()
10
- const groups = categories().map((category) =>
11
+ const items = editor.paletteItems()
12
+ const groups = categories().filter((category) => items.some((item) => item.category === category.key)).map((category) =>
11
13
  h(
12
14
  "section",
13
15
  { class: "px-3 pt-3" },
@@ -40,5 +42,52 @@ export function renderBlocksPanel(editor, element) {
40
42
  )
41
43
  )
42
44
  )
43
- element.replaceChildren(...groups, 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 %}."))
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
+ }
47
+
48
+ const SEARCH_FROM = 8
49
+
50
+ function sourceSections(editor) {
51
+ return [...editor.sources.values()].map(({ source, items, error }) => {
52
+ const rows = h("div", { class: "space-y-1" })
53
+ const show = (query = "") => {
54
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean)
55
+ const matches = items.filter((item) => words.every((word) => `${item.label} ${item.key} ${item.description || ""}`.toLowerCase().includes(word)))
56
+ rows.replaceChildren(
57
+ ...matches.map((item) =>
58
+ h(
59
+ "button",
60
+ {
61
+ type: "button",
62
+ draggable: true,
63
+ title: item.description || "Drag onto the canvas, or click to add",
64
+ "data-tess-edit-source-item": item.key,
65
+ 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
+ ondragstart: (event) => {
67
+ event.dataTransfer.effectAllowed = "copy"
68
+ event.dataTransfer.setData("text/plain", item.key)
69
+ editor.startDrag({ kind: "source", source, item, type: item.type })
70
+ },
71
+ ondragend: () => editor.endDrag(),
72
+ onclick: () => editor.insertFromSource(source, item)
73
+ },
74
+ h("span", { class: "text-gray-400 dark:text-gray-500", html: icon(item.icon || source.icon || getBlock(item.type)?.icon) }),
75
+ h("span", { class: "min-w-0 flex-1 truncate" }, item.label || item.key),
76
+ item.version ? h("span", { class: "text-[11px] text-gray-400 dark:text-gray-500" }, `v${item.version}`) : null
77
+ )
78
+ ),
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
+ )
81
+ }
82
+ 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
+ return h(
85
+ "section",
86
+ { 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
+ error ? h("p", { class: "text-xs text-red-600 dark:text-red-400" }, error) : null,
89
+ search,
90
+ rows
91
+ )
92
+ })
44
93
  }
@@ -1,11 +1,13 @@
1
1
  // The editing canvas: an iframe showing the compiled email, with an overlay for
2
2
  // hover and selection outlines, block tools, plus buttons and drop indicators.
3
3
  // Elements are mapped back to blocks through the "tess-<id>" classes that the
4
- // editor-mode MJML puts on every element.
4
+ // editor-mode MJML puts on every element. With the host's translations, t
5
+ // filters show their text in the editor's language (see annotate).
5
6
 
6
- import { ancestors, canInsert, find, isDescendant, isHorizontal } from "tess_edit/core/document"
7
+ import { ancestors, find, isDescendant, isHorizontal } from "tess_edit/core/document"
7
8
  import { imageFields } from "tess_edit/core/media"
8
9
  import { getBlock, label } from "tess_edit/core/registry"
10
+ import { missingArguments, textParts, translationCalls } from "tess_edit/core/translations"
9
11
  import { icon } from "tess_edit/ui/icons"
10
12
 
11
13
  const OVERLAY_CSS = `
@@ -34,6 +36,12 @@ a{cursor:default}
34
36
  .ProseMirror{outline:none;white-space:pre-wrap;word-wrap:break-word;cursor:text}
35
37
  .ProseMirror p{margin:0}
36
38
  .ProseMirror ul,.ProseMirror ol{margin:0;padding-left:1.5em}
39
+ .tess-t,.tess-t-raw{border-radius:3px;background:rgba(37,99,235,.08);box-shadow:inset 0 -1px 0 rgba(37,99,235,.55)}
40
+ .tess-t.tess-t-missing,.tess-t-raw.tess-t-missing{background:rgba(220,38,38,.08);box-shadow:inset 0 -1px 0 rgba(220,38,38,.65)}
41
+ .ProseMirror .tess-t{cursor:pointer}
42
+ .tess-t-arg{border-radius:3px;padding:0 2px;background:rgba(37,99,235,.18);font-size:.9em}
43
+ .tess-t-missing .tess-t-arg{background:rgba(220,38,38,.18)}
44
+ .tess-t-hidden{display:none}
37
45
  `
38
46
 
39
47
  // A file dragged in from outside the browser (block drags set editor.drag)
@@ -73,10 +81,14 @@ export class Canvas {
73
81
  doc.head.append(style)
74
82
  this.overlay = doc.createElement("div")
75
83
  this.overlay.id = "tess-overlay"
76
- doc.body.append(this.overlay)
84
+ // Outside the body, which a kit may position (a sheet of paper), so the
85
+ // overlay's coordinates are the document's
86
+ doc.documentElement.append(this.overlay)
77
87
  this.win.scrollTo(0, scrollY)
78
- if (mode === "edit") this.listen()
79
- else doc.addEventListener("click", (event) => event.target.closest("a") && event.preventDefault(), true)
88
+ if (mode === "edit") {
89
+ this.listen()
90
+ this.annotate()
91
+ } else doc.addEventListener("click", (event) => event.target.closest("a") && event.preventDefault(), true)
80
92
  this.refresh()
81
93
  }
82
94
 
@@ -97,6 +109,63 @@ export class Canvas {
97
109
  this.win.addEventListener("scroll", () => this.editor.closeMenu(), { passive: true })
98
110
  this.win.addEventListener("resize", () => this.refresh())
99
111
  for (const image of doc.images) image.addEventListener("load", () => this.refresh(), { once: true })
112
+ // Translations list every language while pointed at
113
+ doc.addEventListener("mouseover", (event) => {
114
+ const chip = event.target.closest?.("[data-tess-key]")
115
+ if (chip) this.editor.translationPopover?.show(chip.dataset.tessKey, this.toParentRect(chip.getBoundingClientRect()))
116
+ })
117
+ doc.addEventListener("mouseout", (event) => event.target.closest?.("[data-tess-key]") && this.editor.translationPopover?.scheduleHide())
118
+ }
119
+
120
+ // --- translations ----------------------------------------------------------
121
+
122
+ // Wraps every t filter in the email's text in a span that shows its text
123
+ // (showTranslations), keeping the Liquid for when there's none
124
+ annotate() {
125
+ if (!this.editor.translations?.enabled) return
126
+ const doc = this.doc
127
+ const walker = doc.createTreeWalker(doc.body, 4 /* NodeFilter.SHOW_TEXT */)
128
+ const nodes = []
129
+ while (walker.nextNode()) {
130
+ const node = walker.currentNode
131
+ if (node.nodeValue.includes("{{") && !node.parentElement?.closest("#tess-overlay, script, style, title")) nodes.push(node)
132
+ }
133
+ for (const node of nodes) {
134
+ const text = node.nodeValue
135
+ const calls = translationCalls(text)
136
+ if (!calls.length) continue
137
+ const fragment = doc.createDocumentFragment()
138
+ let at = 0
139
+ for (const call of calls) {
140
+ fragment.append(text.slice(at, call.start))
141
+ const span = doc.createElement("span")
142
+ span.className = "tess-t"
143
+ Object.assign(span.dataset, { tessKey: call.key, tessCall: call.text, tessArgs: call.args.join(",") }, call.locale ? { tessLocale: call.locale } : {})
144
+ fragment.append(span)
145
+ at = call.end
146
+ }
147
+ fragment.append(text.slice(at))
148
+ node.replaceWith(fragment)
149
+ }
150
+ this.showTranslations()
151
+ }
152
+
153
+ // The text in the editor's language (or the call's own), or the Liquid when
154
+ // there's none; red when a language is missing it
155
+ showTranslations() {
156
+ const translations = this.editor.translations
157
+ if (!translations?.enabled || !this.doc) return
158
+ for (const span of this.doc.querySelectorAll(".tess-t[data-tess-call]")) {
159
+ const key = span.dataset.tessKey
160
+ const locale = span.dataset.tessLocale || this.editor.translationLocale
161
+ const value = locale ? translations.value(key, locale) : null
162
+ const unfilled = value === null ? [] : missingArguments(value, { args: span.dataset.tessArgs ? span.dataset.tessArgs.split(",") : [] })
163
+ if (value === null) span.textContent = span.dataset.tessCall
164
+ else showText(span, value)
165
+ span.title = unfilled.length ? `No argument for ${unfilled.map((name) => `%{${name}}`).join(", ")} in the t filter` : ""
166
+ span.classList.toggle("tess-t-missing", unfilled.length > 0 || (translations.has(key) && (locale ? value === null : translations.missing(key).length > 0)))
167
+ }
168
+ this.refresh()
100
169
  }
101
170
 
102
171
  // --- mapping between DOM and blocks -------------------------------------
@@ -124,7 +193,7 @@ export class Canvas {
124
193
  rectOf(id) {
125
194
  const hit = find(this.editor.doc, id)
126
195
  if (!hit) return null
127
- if (hit.node.type === "root") {
196
+ if (hit.node === this.editor.doc) {
128
197
  const body = this.doc.body
129
198
  const rect = body.getBoundingClientRect()
130
199
  return { left: rect.left, top: rect.top, right: rect.right, bottom: rect.top + body.scrollHeight, width: rect.width, height: body.scrollHeight }
@@ -166,7 +235,7 @@ export class Canvas {
166
235
  if (this.hoverId && this.hoverId !== selectedId) {
167
236
  const hit = find(this.editor.doc, this.hoverId)
168
237
  const rect = hit && this.rectOf(this.hoverId)
169
- if (rect && hit.node.type !== "root") {
238
+ if (rect && hit.node !== this.editor.doc) {
170
239
  const box = this.box(rect, "tess-hover")
171
240
  box.append(Object.assign(this.doc.createElement("div"), { className: "tess-label", textContent: getBlock(hit.node.type)?.name || hit.node.type }))
172
241
  this.overlay.append(box)
@@ -174,12 +243,12 @@ export class Canvas {
174
243
  }
175
244
 
176
245
  const hit = selectedId && find(this.editor.doc, selectedId)
177
- if (!hit || hit.node.type === "root") return
246
+ if (!hit || hit.node === this.editor.doc) return
178
247
  const rect = this.rectOf(selectedId)
179
248
  if (!rect) return
180
249
  const box = this.box(rect, editingId === selectedId ? "tess-selected tess-editing" : "tess-selected")
181
250
  const free = this.editor.isFree(selectedId)
182
- box.append(Object.assign(this.doc.createElement("div"), { className: "tess-label", textContent: editingId === selectedId ? "Editing text · Esc to finish" : free ? label(hit.node) : `${label(hit.node)} · Layout` }))
251
+ box.append(Object.assign(this.doc.createElement("div"), { className: "tess-label", textContent: editingId === selectedId ? "Editing text · Esc to finish" : free || !this.editor.lock ? label(hit.node) : `${label(hit.node)} · Layout` }))
183
252
 
184
253
  if (editingId !== selectedId) {
185
254
  const tools = this.doc.createElement("div")
@@ -317,13 +386,14 @@ export class Canvas {
317
386
  }
318
387
 
319
388
  // The nearest block, from the one under the pointer outwards, with an image
320
- // field that can be edited
389
+ // field that can be edited. The root's (e.g. a page background) only when
390
+ // dropped on the page itself, not on a block in it.
321
391
  imageTarget(target) {
322
392
  if (!this.editor.media.enabled) return null
323
393
  const hit = this.hit(target)
324
394
  if (!hit) return null
325
395
  const doc = this.editor.doc
326
- for (const node of [find(doc, hit.id).node, ...ancestors(doc, hit.id)]) {
396
+ for (const node of [find(doc, hit.id).node, ...ancestors(doc, hit.id).filter((node) => node !== doc)]) {
327
397
  const field = imageFields(getBlock(node.type)).find((field) => this.editor.canEditField(node.id, field.key))
328
398
  if (field) return { id: node.id, field }
329
399
  }
@@ -358,7 +428,7 @@ export class Canvas {
358
428
 
359
429
  allowed(parentId, drag) {
360
430
  const doc = this.editor.doc
361
- if (!this.editor.canFill(parentId) || !canInsert(doc, parentId, drag.type)) return false
431
+ if (!this.editor.canInsert(parentId, drag.type, { moving: drag.kind !== "new" })) return false
362
432
  if (drag.kind === "move" && (parentId === drag.id || isDescendant(doc, drag.id, parentId))) return false
363
433
  return true
364
434
  }
@@ -435,3 +505,17 @@ export class Canvas {
435
505
  this.indicator = null
436
506
  }
437
507
  }
508
+
509
+ // A translation's text in an element, its %{…} placeholders apart
510
+ export function showText(element, value) {
511
+ const doc = element.ownerDocument
512
+ element.replaceChildren(
513
+ ...textParts(value).map((part) => {
514
+ if (part.text !== undefined) return doc.createTextNode(part.text)
515
+ const placeholder = doc.createElement("span")
516
+ placeholder.className = "tess-t-arg"
517
+ placeholder.textContent = part.placeholder
518
+ return placeholder
519
+ })
520
+ )
521
+ }
@@ -0,0 +1,103 @@
1
+ // Asks for a text in a dialog in the editor, not window.prompt, which some
2
+ // browsers (Electron) don't have: a link's URL, a translation key.
3
+ //
4
+ // Resolves to the text, or null when cancelled; with `remove`, a Remove
5
+ // button resolves to "". `check(value)` may say what's wrong with it (a
6
+ // string), or ask to confirm it ({ confirm, label }: saving again confirms).
7
+
8
+ import { h } from "tess_edit/ui/dom"
9
+
10
+ const BUTTON = "rounded-md px-3 py-1.5 text-xs font-medium"
11
+
12
+ export function askText(root, { title, label, value = "", hint = null, body = null, remove = false, check = async () => null }) {
13
+ return new Promise((resolve) => {
14
+ let confirmed = null
15
+ const input = h("input", {
16
+ type: "text",
17
+ value,
18
+ "aria-label": label,
19
+ class: "w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 px-2 py-1.5 font-mono text-[13px] text-gray-900 dark:text-gray-100 outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500",
20
+ oninput: () => {
21
+ confirmed = null
22
+ message.textContent = ""
23
+ save.textContent = "Save"
24
+ },
25
+ onkeydown: (event) => {
26
+ if (event.key === "Enter") {
27
+ event.preventDefault()
28
+ submit()
29
+ }
30
+ }
31
+ })
32
+ const message = h("p", { class: "min-h-4 text-xs text-red-600 dark:text-red-400", role: "alert" })
33
+ const save = h("button", { type: "button", class: `${BUTTON} bg-blue-600 text-white hover:bg-blue-700`, onclick: () => submit() }, "Save")
34
+ const close = (result) => {
35
+ dialog.remove()
36
+ resolve(result)
37
+ }
38
+
39
+ async function submit() {
40
+ const text = input.value.trim()
41
+ if (confirmed !== text) {
42
+ save.disabled = true
43
+ const problem = await check(text)
44
+ save.disabled = false
45
+ if (typeof problem === "string") {
46
+ message.textContent = problem
47
+ return
48
+ }
49
+ if (problem?.confirm) {
50
+ confirmed = text
51
+ message.textContent = problem.confirm
52
+ save.textContent = problem.label
53
+ return
54
+ }
55
+ }
56
+ close(text)
57
+ }
58
+
59
+ const dialog = h(
60
+ "div",
61
+ {
62
+ class: "absolute inset-0 z-40 flex items-center justify-center bg-gray-900/40 dark:bg-black/60 p-6",
63
+ role: "dialog",
64
+ "aria-label": title,
65
+ onmousedown: (event) => event.target === dialog && close(null),
66
+ onkeydown: (event) => {
67
+ if (event.key === "Escape") {
68
+ event.preventDefault()
69
+ event.stopPropagation()
70
+ close(null)
71
+ }
72
+ }
73
+ },
74
+ h(
75
+ "div",
76
+ { class: "flex w-full max-w-md flex-col gap-3 rounded-xl bg-white dark:bg-gray-800 p-4 text-sm text-gray-800 dark:text-gray-200 shadow-xl" },
77
+ ...[
78
+ h("h2", { class: "font-semibold text-gray-900 dark:text-gray-100" }, title),
79
+ body,
80
+ h(
81
+ "label",
82
+ { class: "block" },
83
+ h("span", { class: "mb-1 block text-xs font-medium text-gray-700 dark:text-gray-300" }, label),
84
+ input,
85
+ hint ? h("span", { class: "mt-1 block text-[11px] text-gray-500 dark:text-gray-400" }, hint) : null
86
+ ),
87
+ message,
88
+ h(
89
+ "div",
90
+ { class: "flex gap-2" },
91
+ remove ? h("button", { type: "button", class: `${BUTTON} text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/30`, onclick: () => close("") }, "Remove") : null,
92
+ h("span", { class: "flex-1" }),
93
+ h("button", { type: "button", class: `${BUTTON} border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700`, onclick: () => close(null) }, "Cancel"),
94
+ save
95
+ )
96
+ ].filter(Boolean)
97
+ )
98
+ )
99
+ root.append(dialog)
100
+ input.focus()
101
+ input.select()
102
+ })
103
+ }
@@ -10,6 +10,7 @@ const paths = {
10
10
  heading: '<path d="M6 4v16M18 4v16M6 12h12"/>',
11
11
  image: '<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="9" cy="10" r="2"/><path d="m21 16-5-5-9 9"/>',
12
12
  button: '<rect x="3" y="8" width="18" height="8" rx="4"/><path d="M9 12h6"/>',
13
+ content: '<rect x="3" y="4" width="18" height="16" rx="2" stroke-dasharray="3 2"/><path d="M7 9h10M7 13h10M7 17h6"/>',
13
14
  divider: '<path d="M3 12h18"/><path d="M8 7h8M8 17h8" opacity=".4"/>',
14
15
  spacer: '<path d="M12 4v16M8 8l4-4 4 4M8 16l4 4 4-4"/>',
15
16
  social: '<circle cx="6" cy="12" r="2.5"/><circle cx="18" cy="6" r="2.5"/><circle cx="18" cy="18" r="2.5"/><path d="m8.2 10.9 7.6-3.8M8.2 13.1l7.6 3.8"/>',
@@ -53,7 +54,10 @@ const paths = {
53
54
  "align-right": '<path d="M4 6h16M10 10h10M4 14h16M10 18h10"/>',
54
55
  "list-bullet": '<path d="M9 6h11M9 12h11M9 18h11"/><circle cx="4.5" cy="6" r="1"/><circle cx="4.5" cy="12" r="1"/><circle cx="4.5" cy="18" r="1"/>',
55
56
  "list-ordered": '<path d="M10 6h10M10 12h10M10 18h10M4 4h1v4M4 14h2l-2 3h2"/>',
56
- clear: '<path d="M5 6h12M11 6l-3 13M15 15l5 5M20 15l-5 5"/>'
57
+ clear: '<path d="M5 6h12M11 6l-3 13M15 15l5 5M20 15l-5 5"/>',
58
+ translate: '<path d="M4 5h8M8 3v2M10 5c0 4-3 7-6 8M6 9c1 2 3 4 6 4M13 21l4-9 4 9M14.5 18h5"/>',
59
+ globe: '<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/>',
60
+ external: '<path d="M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/>'
57
61
  }
58
62
 
59
63
  export function icon(name, className = "w-4 h-4") {
@@ -4,6 +4,7 @@
4
4
  import { imageSource } from "tess_edit/core/media"
5
5
  import { getBlock, label } from "tess_edit/core/registry"
6
6
  import { find, getValue } from "tess_edit/core/document"
7
+ import { translationCalls } from "tess_edit/core/translations"
7
8
  import { loopScope } from "tess_edit/core/variables"
8
9
  import { codeInput } from "tess_edit/ui/code_input"
9
10
  import { h } from "tess_edit/ui/dom"
@@ -39,6 +40,13 @@ export class Inspector {
39
40
  this.element = element
40
41
  this.openGroups = new Map()
41
42
  this.adapters = new Map()
43
+ this.inputs = new Map()
44
+ this.hints = []
45
+ }
46
+
47
+ // Again, when the translations or the editor's language change
48
+ refreshTranslations() {
49
+ this.hints.forEach((update) => update())
42
50
  }
43
51
 
44
52
  render() {
@@ -48,6 +56,8 @@ export class Inspector {
48
56
  const definition = getBlock(node.type)
49
57
  this.editor.variableMenu?.close()
50
58
  this.adapters = new Map()
59
+ this.inputs = new Map()
60
+ this.hints = []
51
61
 
52
62
  const actions =
53
63
  !this.editor.isFree(node.id)
@@ -68,7 +78,8 @@ export class Inspector {
68
78
  h("div", { class: "ml-auto flex items-center gap-0.5" }, actions)
69
79
  )
70
80
 
71
- const groups = (definition.fields || []).map((group) => this.group(node, group))
81
+ // A group shows when one of its fields applies (see visible below)
82
+ const groups = (definition.fields || []).filter((group) => group.fields.some((field) => !field.visible || field.visible(node, this.editor))).map((group) => this.group(node, group))
72
83
  const locked = this.editor.lock && node.id !== doc.id && !this.editor.isFree(node.id)
73
84
  ? h("p", { class: "mx-4 mt-3 flex items-center gap-2 rounded-md bg-amber-50 dark:bg-amber-900/30 px-3 py-2 text-xs text-amber-800 dark:text-amber-200" }, h("span", { html: icon("lock", "w-3.5 h-3.5") }), "Part of the layout")
74
85
  : null
@@ -105,19 +116,26 @@ export class Inspector {
105
116
  ? this.control(node, field, value, set)
106
117
  : h("fieldset", { disabled: true, class: "opacity-60" }, this.control(node, field, value, set))
107
118
  const expand = field.type === "code" && editable
108
- ? h("button", { type: "button", title: `Edit ${field.label} in a larger window`, class: "absolute right-0 top-0 rounded px-1 text-[11px] font-medium text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/40", onclick: () => this.expand(node, field) }, "Expand")
119
+ ? h("button", { type: "button", title: `Edit ${field.label} in a larger window`, class: "rounded px-1 text-[11px] font-medium text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/40", onclick: () => this.expand(node, field) }, "Expand")
109
120
  : null
110
- const adapter = editable && field.liquid && this.adapters.get(field.key)
121
+ const adapter = editable && field.liquid && this.editor.variables?.enabled && this.adapters.get(field.key)
111
122
  const variables = adapter
112
- ? h("button", { type: "button", title: "Insert a variable", class: "absolute right-0 top-0 whitespace-nowrap rounded px-1 font-mono text-[11px] font-medium text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/40", onclick: (event) => this.editor.variableMenu.browse(adapter, event.currentTarget) }, "{ }")
123
+ ? h("button", { type: "button", title: "Insert a variable", class: "whitespace-nowrap rounded px-1 font-mono text-[11px] font-medium text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/40", onclick: (event) => this.editor.variableMenu.browse(adapter, event.currentTarget) }, "{ }")
124
+ : null
125
+ // Liquid in text can be translated
126
+ const input = field.liquid === true && ["text", "textarea"].includes(field.type) && this.editor.translations?.enabled && this.inputs.get(field.key)
127
+ const translate = input && editable
128
+ ? h("button", { type: "button", title: "Make translatable: keep the selected text, or all of it, as a translation", class: "rounded px-1 text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/40", html: icon("translate", "w-3.5 h-3.5"), onclick: () => this.makeTranslatable(input) })
113
129
  : null
130
+ const tools = expand || variables || translate ? h("span", { class: "absolute right-0 top-0 flex items-center gap-0.5" }, expand, variables, translate) : null
114
131
  // A div, not a label: a label would forward clicks to the first button or color picker inside it.
115
132
  return h(
116
133
  "div",
117
134
  { class: "relative block" },
118
135
  h("span", { class: "mb-1 block text-xs font-medium text-gray-700 dark:text-gray-300" }, field.label),
119
- expand || variables,
136
+ tools,
120
137
  control,
138
+ input ? this.translationHint(input) : null,
121
139
  field.hint ? h("span", { class: "mt-1 block text-[11px] leading-snug text-gray-500 dark:text-gray-400" }, field.hint) : null
122
140
  )
123
141
  }
@@ -147,7 +165,8 @@ export class Inspector {
147
165
  return h(
148
166
  "select",
149
167
  { class: `${INPUT} pr-7`, onchange: (event) => set(event.target.value) },
150
- field.options.map((option) => {
168
+ // options can depend on the editor's settings: options(editor)
169
+ (typeof field.options === "function" ? field.options(this.editor) : field.options).map((option) => {
151
170
  const optionValue = typeof option === "string" ? option : option.value
152
171
  const optionLabel = typeof option === "string" ? option || "Default" : option.label
153
172
  return h("option", { value: optionValue, selected: optionValue === value }, optionLabel)
@@ -208,7 +227,8 @@ export class Inspector {
208
227
  // them: true for Liquid in text, "expression" for a condition, "collection"
209
228
  // for what a Loop goes over.
210
229
  variables(input, node, field) {
211
- if (!this.editor.variables?.enabled) return input
230
+ this.inputs.set(field.key, input)
231
+ if (!this.editor.variableMenu) return input
212
232
  const mode = field.liquid === "expression" || field.liquid === "collection" ? field.liquid : "output"
213
233
  const adapter = inputAdapter(input, { mode, scope: loopScope(this.editor.doc, node.id) })
214
234
  suggestIn(this.editor.variableMenu, input, adapter)
@@ -216,6 +236,55 @@ export class Inspector {
216
236
  return input
217
237
  }
218
238
 
239
+ // What the field's t filters say in the editor's language, each listing
240
+ // every language while pointed at
241
+ translationHint(input) {
242
+ const hint = h("span", { class: "mt-1 flex flex-wrap gap-1 empty:hidden" })
243
+ const update = () => {
244
+ const { translations, translationLocale } = this.editor
245
+ const calls = translationCalls(input.value)
246
+ translations.load(calls.map((call) => call.key))
247
+ hint.replaceChildren(
248
+ ...calls.map((call) => {
249
+ const locale = call.locale || translationLocale
250
+ const value = locale ? translations.value(call.key, locale) : null
251
+ const missing = translations.has(call.key) && (locale ? value === null : translations.missing(call.key).length > 0)
252
+ const text = value !== null ? `${locale.toUpperCase()}: ${value}` : locale && translations.has(call.key) ? `${call.key} · no ${locale.toUpperCase()} text` : call.key
253
+ const chip = h(
254
+ "span",
255
+ {
256
+ class: `max-w-full truncate rounded px-1.5 py-0.5 text-[11px] ${missing ? "bg-red-50 dark:bg-red-900/30 text-red-700 dark:text-red-300" : "bg-blue-50 dark:bg-blue-900/30 text-blue-800 dark:text-blue-200"}`,
257
+ "data-tess-key": call.key,
258
+ onmouseenter: () => this.editor.translationPopover.show(call.key, chip.getBoundingClientRect()),
259
+ onmouseleave: () => this.editor.translationPopover.scheduleHide()
260
+ },
261
+ text
262
+ )
263
+ return chip
264
+ })
265
+ )
266
+ }
267
+ input.addEventListener("input", update)
268
+ this.hints.push(update)
269
+ update()
270
+ return hint
271
+ }
272
+
273
+ // Keeps the selected text, or the whole value, as a translation and puts
274
+ // its t filter in its place
275
+ async makeTranslatable(input) {
276
+ const start = input.selectionStart ?? 0
277
+ const end = input.selectionEnd ?? 0
278
+ const whole = start === end
279
+ const text = whole ? input.value : input.value.slice(start, end)
280
+ if (!text.trim()) return this.editor.flash("Type the text to translate first.")
281
+ const tag = await this.editor.makeTranslatable(text)
282
+ if (!tag) return
283
+ if (whole) input.value = tag
284
+ else input.setRangeText(tag, start, end, "end")
285
+ input.dispatchEvent(new Event("input", { bubbles: true }))
286
+ }
287
+
219
288
  // An image URL, or with the host's images (editor.media, core/media.js) a
220
289
  // choice between one of those, a new upload, and a URL
221
290
  image(node, field, value, set) {