tess_edit 0.2.1 → 0.3.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.
@@ -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
+ }
@@ -53,7 +53,10 @@ const paths = {
53
53
  "align-right": '<path d="M4 6h16M10 10h10M4 14h16M10 18h10"/>',
54
54
  "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
55
  "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"/>'
56
+ clear: '<path d="M5 6h12M11 6l-3 13M15 15l5 5M20 15l-5 5"/>',
57
+ translate: '<path d="M4 5h8M8 3v2M10 5c0 4-3 7-6 8M6 9c1 2 3 4 6 4M13 21l4-9 4 9M14.5 18h5"/>',
58
+ 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"/>',
59
+ 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
60
  }
58
61
 
59
62
  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)
@@ -105,19 +115,26 @@ export class Inspector {
105
115
  ? this.control(node, field, value, set)
106
116
  : h("fieldset", { disabled: true, class: "opacity-60" }, this.control(node, field, value, set))
107
117
  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")
118
+ ? 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
119
  : null
110
- const adapter = editable && field.liquid && this.adapters.get(field.key)
120
+ const adapter = editable && field.liquid && this.editor.variables?.enabled && this.adapters.get(field.key)
111
121
  const variables = adapter
112
- ? h("button", { type: "button", title: "Insert a variable", class: "absolute right-0 top-0 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) }, "{ }")
122
+ ? 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) }, "{ }")
123
+ : null
124
+ // Liquid in text can be translated
125
+ const input = field.liquid === true && ["text", "textarea"].includes(field.type) && this.editor.translations?.enabled && this.inputs.get(field.key)
126
+ const translate = input && editable
127
+ ? 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
128
  : null
129
+ const tools = expand || variables || translate ? h("span", { class: "absolute right-0 top-0 flex items-center gap-0.5" }, expand, variables, translate) : null
114
130
  // A div, not a label: a label would forward clicks to the first button or color picker inside it.
115
131
  return h(
116
132
  "div",
117
133
  { class: "relative block" },
118
134
  h("span", { class: "mb-1 block text-xs font-medium text-gray-700 dark:text-gray-300" }, field.label),
119
- expand || variables,
135
+ tools,
120
136
  control,
137
+ input ? this.translationHint(input) : null,
121
138
  field.hint ? h("span", { class: "mt-1 block text-[11px] leading-snug text-gray-500 dark:text-gray-400" }, field.hint) : null
122
139
  )
123
140
  }
@@ -146,7 +163,7 @@ export class Inspector {
146
163
  case "select":
147
164
  return h(
148
165
  "select",
149
- { class: INPUT, onchange: (event) => set(event.target.value) },
166
+ { class: `${INPUT} pr-7`, onchange: (event) => set(event.target.value) },
150
167
  field.options.map((option) => {
151
168
  const optionValue = typeof option === "string" ? option : option.value
152
169
  const optionLabel = typeof option === "string" ? option || "Default" : option.label
@@ -208,7 +225,8 @@ export class Inspector {
208
225
  // them: true for Liquid in text, "expression" for a condition, "collection"
209
226
  // for what a Loop goes over.
210
227
  variables(input, node, field) {
211
- if (!this.editor.variables?.enabled) return input
228
+ this.inputs.set(field.key, input)
229
+ if (!this.editor.variableMenu) return input
212
230
  const mode = field.liquid === "expression" || field.liquid === "collection" ? field.liquid : "output"
213
231
  const adapter = inputAdapter(input, { mode, scope: loopScope(this.editor.doc, node.id) })
214
232
  suggestIn(this.editor.variableMenu, input, adapter)
@@ -216,6 +234,55 @@ export class Inspector {
216
234
  return input
217
235
  }
218
236
 
237
+ // What the field's t filters say in the editor's language, each listing
238
+ // every language while pointed at
239
+ translationHint(input) {
240
+ const hint = h("span", { class: "mt-1 flex flex-wrap gap-1 empty:hidden" })
241
+ const update = () => {
242
+ const { translations, translationLocale } = this.editor
243
+ const calls = translationCalls(input.value)
244
+ translations.load(calls.map((call) => call.key))
245
+ hint.replaceChildren(
246
+ ...calls.map((call) => {
247
+ const locale = call.locale || translationLocale
248
+ const value = locale ? translations.value(call.key, locale) : null
249
+ const missing = translations.has(call.key) && (locale ? value === null : translations.missing(call.key).length > 0)
250
+ const text = value !== null ? `${locale.toUpperCase()}: ${value}` : locale && translations.has(call.key) ? `${call.key} · no ${locale.toUpperCase()} text` : call.key
251
+ const chip = h(
252
+ "span",
253
+ {
254
+ 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"}`,
255
+ "data-tess-key": call.key,
256
+ onmouseenter: () => this.editor.translationPopover.show(call.key, chip.getBoundingClientRect()),
257
+ onmouseleave: () => this.editor.translationPopover.scheduleHide()
258
+ },
259
+ text
260
+ )
261
+ return chip
262
+ })
263
+ )
264
+ }
265
+ input.addEventListener("input", update)
266
+ this.hints.push(update)
267
+ update()
268
+ return hint
269
+ }
270
+
271
+ // Keeps the selected text, or the whole value, as a translation and puts
272
+ // its t filter in its place
273
+ async makeTranslatable(input) {
274
+ const start = input.selectionStart ?? 0
275
+ const end = input.selectionEnd ?? 0
276
+ const whole = start === end
277
+ const text = whole ? input.value : input.value.slice(start, end)
278
+ if (!text.trim()) return this.editor.flash("Type the text to translate first.")
279
+ const tag = await this.editor.makeTranslatable(text)
280
+ if (!tag) return
281
+ if (whole) input.value = tag
282
+ else input.setRangeText(tag, start, end, "end")
283
+ input.dispatchEvent(new Event("input", { bubbles: true }))
284
+ }
285
+
219
286
  // An image URL, or with the host's images (editor.media, core/media.js) a
220
287
  // choice between one of those, a new upload, and a URL
221
288
  image(node, field, value, set) {
@@ -244,7 +311,7 @@ export class Inspector {
244
311
  const select = h(
245
312
  "select",
246
313
  {
247
- class: `${INPUT} min-w-0 flex-1`,
314
+ class: `${INPUT} min-w-0 flex-1 pr-7`,
248
315
  onchange: (event) => {
249
316
  const image = images.find((option) => option.id === event.target.value)
250
317
  if (image) this.editor.chooseImage(node.id, image, field)
@@ -361,7 +428,7 @@ export class Inspector {
361
428
  part.type === "select"
362
429
  ? h(
363
430
  "select",
364
- { class: INPUT, onchange: (event) => update(items.map((it, i) => (i === index ? { ...it, [part.name]: event.target.value } : it))) },
431
+ { class: `${INPUT} pr-7`, onchange: (event) => update(items.map((it, i) => (i === index ? { ...it, [part.name]: event.target.value } : it))) },
365
432
  part.options.map((option) => h("option", { value: option, selected: option === item[part.name] }, option))
366
433
  )
367
434
  : this.variables(h("input", {
@@ -1,22 +1,34 @@
1
1
  // Inline rich-text editing with Tiptap, mounted inside the canvas iframe on the
2
2
  // text block's own element, plus the formatting toolbar above the canvas. With
3
3
  // the host's variables (`menu`, a ui/variable_menu.js VariableMenu) typing {{
4
- // suggests them, and the toolbar's { } button browses them.
4
+ // suggests them, and the toolbar's { } button browses them. With the host's
5
+ // translations (`editor.translations`, core/translations.js) a t filter shows
6
+ // its text in the editor's language until the caret goes into it, and the
7
+ // toolbar turns selected text into a translation.
5
8
 
6
- import { Color, Editor, StarterKit, TextAlign, TextStyle } from "tess_edit/vendor/tiptap"
9
+ import { Color, Decoration, DecorationSet, Editor, Extension, Plugin, PluginKey, StarterKit, TextAlign, TextStyle } from "tess_edit/vendor/tiptap"
10
+ import { missingArguments, translationCalls } from "tess_edit/core/translations"
11
+ import { showText } from "tess_edit/ui/canvas"
12
+ import { askText } from "tess_edit/ui/dialog"
7
13
  import { h } from "tess_edit/ui/dom"
8
14
  import { icon } from "tess_edit/ui/icons"
9
15
 
10
16
  const BUTTON = "w-7 h-7 flex items-center justify-center rounded-md text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-gray-100"
11
17
  const ACTIVE = "bg-blue-50 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300"
18
+ const TRANSLATIONS = new PluginKey("tessTranslations")
12
19
 
13
20
  export class TextEditing {
14
- constructor(toolbar, { menu = null } = {}) {
21
+ constructor(toolbar, { menu = null, editor = null } = {}) {
15
22
  this.toolbar = toolbar
16
23
  this.menu = menu
24
+ this.editor = editor
17
25
  this.tiptap = null
18
26
  }
19
27
 
28
+ get translating() {
29
+ return Boolean(this.editor?.translations?.enabled)
30
+ }
31
+
20
32
  get active() {
21
33
  return !!this.tiptap
22
34
  }
@@ -38,7 +50,8 @@ export class TextEditing {
38
50
  }),
39
51
  TextStyle,
40
52
  Color,
41
- TextAlign.configure({ types: ["heading", "paragraph"] })
53
+ TextAlign.configure({ types: ["heading", "paragraph"] }),
54
+ ...(this.translating ? [translationsExtension(this)] : [])
42
55
  ],
43
56
  autofocus: "end",
44
57
  editorProps: { handleKeyDown: (view, event) => this.menu?.key(event) || false },
@@ -55,6 +68,43 @@ export class TextEditing {
55
68
  return this.tiptap
56
69
  }
57
70
 
71
+ // Again, when the translations or the editor's language change
72
+ refreshTranslations() {
73
+ if (this.tiptap && this.translating) this.tiptap.view.dispatch(this.tiptap.state.tr.setMeta(TRANSLATIONS, true))
74
+ }
75
+
76
+ // Keeps the selected text as a translation (see the editor's
77
+ // makeTranslatable) and puts its t filter in its place
78
+ async makeTranslatable() {
79
+ const tiptap = this.tiptap
80
+ const { selection, doc } = tiptap.state
81
+ if (selection.empty) return this.editor.flash("Select the text to translate first.")
82
+ // Inside the text: a selection of everything starts before the first paragraph
83
+ const from = Math.max(selection.from, 1)
84
+ const to = Math.min(selection.to, doc.content.size - 1)
85
+ const tag = await this.editor.makeTranslatable(doc.textBetween(from, to, " "))
86
+ if (!tag || this.tiptap !== tiptap) return
87
+ tiptap.view.dispatch(tiptap.state.tr.insertText(tag, from, to))
88
+ // After it, so its text shows
89
+ tiptap.chain().focus().setTextSelection(from + tag.length).run()
90
+ }
91
+
92
+ // The selected text's link, in a dialog: an empty URL removes it
93
+ async editLink() {
94
+ const tiptap = this.tiptap
95
+ const previous = tiptap.getAttributes("link").href
96
+ const href = await askText(this.editor.root, {
97
+ title: previous ? "Edit link" : "Add link",
98
+ label: "URL",
99
+ value: previous || "https://",
100
+ hint: "Liquid is allowed, e.g. {{ order.url }}",
101
+ remove: Boolean(previous)
102
+ })
103
+ if (href === null || this.tiptap !== tiptap) return tiptap.commands.focus()
104
+ const chain = tiptap.chain().focus().extendMarkRange("link")
105
+ href ? chain.setLink({ href }).run() : chain.unsetLink().run()
106
+ }
107
+
58
108
  stop() {
59
109
  if (!this.tiptap) return null
60
110
  const json = this.tiptap.getJSON()
@@ -85,7 +135,7 @@ export class TextEditing {
85
135
  const style = h(
86
136
  "select",
87
137
  {
88
- class: "h-7 rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-1.5 text-xs text-gray-800 dark:text-gray-200",
138
+ 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",
89
139
  title: "Paragraph style",
90
140
  onchange: (event) => {
91
141
  const value = Number(event.target.value)
@@ -114,12 +164,7 @@ export class TextEditing {
114
164
  button("strike", "Strikethrough", editor.isActive("strike"), () => chain().toggleStrike().run()),
115
165
  color,
116
166
  separator(),
117
- button("link", "Link", editor.isActive("link"), () => {
118
- const previous = editor.getAttributes("link").href || "https://"
119
- const href = window.prompt("Link URL (Liquid allowed, e.g. {{ order.url }})", previous)
120
- if (href === null) return
121
- href ? chain().extendMarkRange("link").setLink({ href }).run() : chain().extendMarkRange("link").unsetLink().run()
122
- }),
167
+ button("link", "Link", editor.isActive("link"), () => this.editLink()),
123
168
  editor.isActive("link") ? button("unlink", "Remove link", false, () => chain().extendMarkRange("link").unsetLink().run()) : null,
124
169
  separator(),
125
170
  button("align-left", "Align left", editor.isActive({ textAlign: "left" }), () => chain().setTextAlign("left").run()),
@@ -130,11 +175,12 @@ export class TextEditing {
130
175
  button("list-ordered", "Numbered list", editor.isActive("orderedList"), () => chain().toggleOrderedList().run()),
131
176
  separator(),
132
177
  button("clear", "Clear formatting", false, () => chain().unsetAllMarks().clearNodes().run()),
133
- this.menu
178
+ this.translating ? button("translate", "Make translatable: keep the selected text as a translation", false, () => this.makeTranslatable()) : null,
179
+ this.menu && this.editor?.variables?.enabled
134
180
  ? h("button", {
135
181
  type: "button",
136
182
  title: "Insert a variable",
137
- class: `${BUTTON} w-auto px-1.5 font-mono text-xs`,
183
+ class: `${BUTTON.replace("w-7", "px-1.5")} whitespace-nowrap font-mono text-xs`,
138
184
  onmousedown: (event) => event.preventDefault(),
139
185
  onclick: (event) => this.menu.browse(this.adapter, event.currentTarget)
140
186
  }, "{ }")
@@ -177,3 +223,58 @@ function tiptapAdapter(editor, scope) {
177
223
  }
178
224
  }
179
225
  }
226
+
227
+ // Shows each t filter's text in the editor's language, in place of its Liquid,
228
+ // unless the caret or selection is inside it or it has no text there: then
229
+ // the Liquid shows, marked (red when a language is missing). Pointing at
230
+ // either lists every language (TranslationPopover, see Canvas#listen).
231
+ function translationsExtension(editing) {
232
+ return Extension.create({
233
+ name: "tessTranslations",
234
+ addProseMirrorPlugins() {
235
+ return [new Plugin({ key: TRANSLATIONS, props: { decorations: (state) => translationDecorations(state, editing) } })]
236
+ }
237
+ })
238
+ }
239
+
240
+ function translationDecorations(state, editing) {
241
+ const { translations, translationLocale } = editing.editor
242
+ const { from, to } = state.selection
243
+ const decorations = []
244
+ state.doc.descendants((node, pos) => {
245
+ if (!node.isTextblock) return true
246
+ // Every character and inline node takes one position
247
+ const text = node.textBetween(0, node.content.size, undefined, "\ufffc")
248
+ for (const call of translationCalls(text)) {
249
+ const start = pos + 1 + call.start
250
+ const end = pos + 1 + call.end
251
+ const locale = call.locale || translationLocale
252
+ const value = locale ? translations.value(call.key, locale) : null
253
+ const unfilled = value === null ? [] : missingArguments(value, call)
254
+ const missing = unfilled.length > 0 || (translations.has(call.key) && (locale ? value === null : translations.missing(call.key).length > 0))
255
+ if ((from < end && to > start) || value === null) {
256
+ decorations.push(Decoration.inline(start, end, { class: `tess-t-raw${missing ? " tess-t-missing" : ""}`, "data-tess-key": call.key }))
257
+ } else {
258
+ decorations.push(Decoration.inline(start, end, { class: "tess-t-hidden" }))
259
+ const caret = start + call.text.indexOf(call.key) + call.key.length
260
+ decorations.push(Decoration.widget(start, (view) => translationChip(view, call.key, value, unfilled, () => editing.tiptap?.chain().focus().setTextSelection(caret).run()), { side: -1, key: `t:${call.key}:${value}:${unfilled}`, ignoreSelection: true }))
261
+ }
262
+ }
263
+ return false
264
+ })
265
+ return DecorationSet.create(state.doc, decorations)
266
+ }
267
+
268
+ function translationChip(view, key, value, unfilled, edit) {
269
+ const chip = view.dom.ownerDocument.createElement("span")
270
+ chip.className = unfilled.length ? "tess-t tess-t-missing" : "tess-t"
271
+ chip.contentEditable = "false"
272
+ chip.dataset.tessKey = key
273
+ if (unfilled.length) chip.title = `No argument for ${unfilled.map((name) => `%{${name}}`).join(", ")} in the t filter`
274
+ showText(chip, value)
275
+ chip.addEventListener("mousedown", (event) => {
276
+ event.preventDefault()
277
+ edit()
278
+ })
279
+ return chip
280
+ }
@@ -0,0 +1,30 @@
1
+ // Asks for the key to keep a text under (the editor's makeTranslatable),
2
+ // showing the text as it's saved, its placeholders apart.
3
+ //
4
+ // Resolves to the key, or null when cancelled. `existing(key)` resolves to
5
+ // what the key already says in the language, if anything: the dialog then
6
+ // asks to replace it.
7
+
8
+ import { textParts, validKey } from "tess_edit/core/translations"
9
+ import { askText } from "tess_edit/ui/dialog"
10
+ import { h } from "tess_edit/ui/dom"
11
+
12
+ export function askTranslationKey(root, { text, locale, suggested, existing }) {
13
+ return askText(root, {
14
+ title: "Make translatable",
15
+ label: "Key",
16
+ value: suggested,
17
+ hint: "A key starting with a dot belongs to this template.",
18
+ body: h(
19
+ "div",
20
+ { class: "rounded-md bg-gray-50 dark:bg-gray-700/50 px-3 py-2" },
21
+ h("span", { class: "mb-1 block text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400" }, `${locale.toUpperCase()} text`),
22
+ h("span", { class: "block", "data-tess-edit-translation-text": "" }, textParts(text).map((part) => part.text ?? h("span", { class: "rounded bg-blue-100 dark:bg-blue-900/50 px-1 text-[12px] text-blue-800 dark:text-blue-200" }, part.placeholder)))
23
+ ),
24
+ check: async (key) => {
25
+ if (!validKey(key)) return "A key is made of letters, digits, _ and -, separated by dots, e.g. .order.thanks"
26
+ const current = await existing(key)
27
+ return current !== null && current !== text ? { confirm: `${key} already says “${current}” in ${locale.toUpperCase()}.`, label: "Replace" } : null
28
+ }
29
+ }).then((key) => key || null)
30
+ }
@@ -0,0 +1,165 @@
1
+ // What a translation key says in every language (core/translations.js), shown
2
+ // when the pointer is on it in the canvas, the text being edited or a field's
3
+ // hint: missing ones stand out, each can be edited in place, and the arrow
4
+ // opens where the host app keeps it.
5
+
6
+ import { textParts } from "tess_edit/core/translations"
7
+ import { h } from "tess_edit/ui/dom"
8
+ import { icon } from "tess_edit/ui/icons"
9
+
10
+ const ACTION = "w-6 h-6 shrink-0 flex items-center justify-center rounded text-gray-400 dark:text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-gray-100"
11
+
12
+ export class TranslationPopover {
13
+ constructor(editor) {
14
+ this.editor = editor
15
+ this.element = null
16
+ this.key = null
17
+ this.editing = null
18
+ this.error = null
19
+ this.timer = null
20
+ }
21
+
22
+ get translations() {
23
+ return this.editor.translations
24
+ }
25
+
26
+ // rect: what it's for, in the page's viewport
27
+ show(key, rect) {
28
+ this.cancelHide()
29
+ if (this.key === key && this.element) return
30
+ if (this.editing) return
31
+ this.key = key
32
+ this.rect = rect
33
+ this.error = null
34
+ if (!this.element) {
35
+ this.element = h("div", {
36
+ class: "absolute z-50 w-80 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 py-1.5 text-[13px] shadow-lg",
37
+ role: "dialog",
38
+ "aria-label": "Translations",
39
+ "data-tess-edit-translations": "",
40
+ onmouseenter: () => this.cancelHide(),
41
+ onmouseleave: () => this.scheduleHide()
42
+ })
43
+ this.editor.root.append(this.element)
44
+ }
45
+ this.render()
46
+ if (!this.translations.has(key)) this.translations.load([key])
47
+ }
48
+
49
+ // Lets the pointer move from what it's for into the popover
50
+ scheduleHide(delay = 250) {
51
+ this.cancelHide()
52
+ this.timer = setTimeout(() => this.hide(), delay)
53
+ }
54
+
55
+ cancelHide() {
56
+ clearTimeout(this.timer)
57
+ }
58
+
59
+ hide({ force = false } = {}) {
60
+ if (this.editing && !force) return
61
+ this.cancelHide()
62
+ this.element?.remove()
63
+ this.element = null
64
+ this.key = null
65
+ this.editing = null
66
+ }
67
+
68
+ // Again, when the translations change
69
+ refresh() {
70
+ if (this.element) this.render()
71
+ }
72
+
73
+ render() {
74
+ const key = this.key
75
+ const { locales } = this.translations
76
+ const current = this.editor.translationLocale
77
+ const rows = locales.map((locale) => {
78
+ const entry = this.translations.get(key, locale)
79
+ const value = this.translations.value(key, locale)
80
+ const editing = this.editing === locale
81
+ const text = editing
82
+ ? this.input(locale, value)
83
+ : h(
84
+ "span",
85
+ { class: `min-w-0 flex-1 truncate ${value === null ? "italic text-red-600 dark:text-red-400" : "text-gray-800 dark:text-gray-200"}`, title: entry?.source ? `${value ?? ""}\n${entry.source}` : value || "" },
86
+ value === null ? "missing" : value ? textParts(value).map((part) => part.text ?? h("span", { class: "rounded bg-blue-100 dark:bg-blue-900/50 px-1 text-[12px] text-blue-800 dark:text-blue-200" }, part.placeholder)) : "(empty)"
87
+ )
88
+ return h(
89
+ "div",
90
+ { class: `flex items-center gap-2 px-3 py-1 ${locale === current ? "bg-blue-50/60 dark:bg-blue-900/20" : ""}`, "data-locale": locale },
91
+ h("span", { class: "w-12 shrink-0 font-semibold uppercase text-gray-900 dark:text-gray-100" }, locale),
92
+ text,
93
+ editing ? null : h("button", { type: "button", title: `Edit the ${locale.toUpperCase()} text`, class: ACTION, html: icon("edit", "w-3.5 h-3.5"), onclick: () => this.edit(locale) }),
94
+ !editing && entry?.url ? h("a", { href: entry.url, target: "_blank", rel: "noopener", title: entry.source ? `Open ${entry.source}` : "Open where it's kept", class: ACTION, html: icon("external", "w-3.5 h-3.5") }) : null
95
+ )
96
+ })
97
+ const empty = !locales.length
98
+ ? h("p", { class: "px-3 py-1 text-xs text-gray-500 dark:text-gray-400" }, this.translations.error || (this.translations.loaded ? "No languages yet" : "Loading…"))
99
+ : null
100
+ // replaceChildren would turn a null into the text "null", so only pass real elements.
101
+ this.element.replaceChildren(...[
102
+ h("div", { class: "flex items-center gap-2 border-b border-gray-100 dark:border-gray-700 px-3 pb-1.5 mb-1 text-xs text-gray-500 dark:text-gray-400" }, h("span", { html: icon("translate", "w-3.5 h-3.5") }), h("span", { class: "truncate font-mono" }, key)),
103
+ ...rows,
104
+ empty,
105
+ this.error ? h("p", { class: "px-3 pt-1 text-xs text-red-600 dark:text-red-400", role: "alert" }, this.error) : null
106
+ ].filter(Boolean))
107
+ this.place()
108
+ }
109
+
110
+ input(locale, value) {
111
+ const input = h("input", {
112
+ type: "text",
113
+ class: "min-w-0 flex-1 rounded border border-blue-500 bg-white dark:bg-gray-700 px-1.5 py-0.5 text-[13px] text-gray-900 dark:text-gray-100 outline-none",
114
+ value: value ?? "",
115
+ "aria-label": `${locale.toUpperCase()} text`,
116
+ onkeydown: (event) => {
117
+ if (event.key === "Enter") {
118
+ event.preventDefault()
119
+ event.stopPropagation()
120
+ this.save(locale, input.value)
121
+ } else if (event.key === "Escape") {
122
+ event.preventDefault()
123
+ event.stopPropagation()
124
+ this.editing = null
125
+ this.render()
126
+ }
127
+ }
128
+ })
129
+ setTimeout(() => input.focus())
130
+ return h(
131
+ "span",
132
+ { class: "flex min-w-0 flex-1 items-center gap-1" },
133
+ input,
134
+ h("button", { type: "button", class: "shrink-0 rounded bg-blue-600 px-2 py-0.5 text-xs font-medium text-white hover:bg-blue-700", onclick: () => this.save(locale, input.value) }, "Save")
135
+ )
136
+ }
137
+
138
+ edit(locale) {
139
+ this.editing = locale
140
+ this.error = null
141
+ this.render()
142
+ }
143
+
144
+ async save(locale, value) {
145
+ try {
146
+ await this.translations.save(this.key, locale, value)
147
+ this.editing = null
148
+ this.error = null
149
+ } catch (error) {
150
+ this.error = error.message
151
+ }
152
+ this.refresh()
153
+ }
154
+
155
+ // Below the rect, or above it when there's no room, inside the editor.
156
+ place() {
157
+ const rect = this.rect
158
+ const root = this.editor.root.getBoundingClientRect()
159
+ const height = this.element.offsetHeight
160
+ const below = rect.bottom - root.top + 4
161
+ const top = below + height > root.height && rect.top - root.top - height - 4 > 0 ? rect.top - root.top - height - 4 : below
162
+ const left = Math.max(4, Math.min(rect.left - root.left, root.width - this.element.offsetWidth - 4))
163
+ Object.assign(this.element.style, { top: `${top}px`, left: `${left}px` })
164
+ }
165
+ }