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,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()
@@ -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,7 +175,8 @@ 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",
@@ -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
+ }
@@ -1,7 +1,7 @@
1
1
  // The Layers panel: the document as a collapsible tree that can be reordered by
2
2
  // dragging. Rows also take blocks dragged from the Blocks panel.
3
3
 
4
- import { canInsert, find, isDescendant } from "tess_edit/core/document"
4
+ import { find, isDescendant } from "tess_edit/core/document"
5
5
  import { getBlock, isContainer, label } from "tess_edit/core/registry"
6
6
  import { h } from "tess_edit/ui/dom"
7
7
  import { icon } from "tess_edit/ui/icons"
@@ -93,7 +93,7 @@ export class Tree {
93
93
  const drag = this.editor.drag
94
94
  if (!drag) return null
95
95
  const doc = this.editor.doc
96
- const ok = (parentId) => this.editor.canFill(parentId) && canInsert(doc, parentId, drag.type) && !(drag.kind === "move" && (parentId === drag.id || isDescendant(doc, drag.id, parentId)))
96
+ const ok = (parentId) => this.editor.canInsert(parentId, drag.type, { moving: drag.kind !== "new" }) && !(drag.kind === "move" && (parentId === drag.id || isDescendant(doc, drag.id, parentId)))
97
97
  const rect = event.currentTarget.getBoundingClientRect()
98
98
  const ratio = (event.clientY - rect.top) / rect.height
99
99
  const hit = find(doc, node.id)
@@ -10,8 +10,10 @@
10
10
  // Condition) or "collection" (a Loop's collection)
11
11
  // scope the loop variables there (core/variables.js loopScope)
12
12
  //
13
- // See inputAdapter below and TextEditing for Tiptap's.
13
+ // See inputAdapter below and TextEditing for Tiptap's. With the host's
14
+ // translations it also suggests their keys while typing {{ '.
14
15
 
16
+ import { keyCompletion, keyToken } from "tess_edit/core/translations"
15
17
  import { completion, liquidToken } from "tess_edit/core/variables"
16
18
  import { h } from "tess_edit/ui/dom"
17
19
 
@@ -41,6 +43,9 @@ export class VariableMenu {
41
43
 
42
44
  async suggesting(adapter) {
43
45
  const before = adapter.before()
46
+ const key = this.editor.translations?.enabled && adapter.mode === "output" && keyToken(before)
47
+ if (key) return this.suggestKeys(adapter, key)
48
+ if (!this.editor.variables?.enabled) return this.close()
44
49
  const token = liquidToken(before, adapter.mode === "output" ? "output" : "expression")
45
50
  if (!token) return this.close()
46
51
 
@@ -64,6 +69,29 @@ export class VariableMenu {
64
69
  this.show({ adapter, browse: false, items, index: 0, choose: (item) => this.complete(adapter, token, start, item) })
65
70
  }
66
71
 
72
+ // The translation keys with what's typed, those that start with it first,
73
+ // labelled with their text in the editor's language
74
+ suggestKeys(adapter, token) {
75
+ const translations = this.editor.translations
76
+ const locale = this.editor.translationLocale || translations.locales[0]
77
+ const partial = token.partial.toLowerCase()
78
+ const keys = translations.suggestions.filter((key) => key.toLowerCase().includes(partial))
79
+ const sorted = [...keys.filter((key) => key.toLowerCase().startsWith(partial)), ...keys.filter((key) => !key.toLowerCase().startsWith(partial))]
80
+ if (!sorted.length || (sorted.length === 1 && sorted[0] === token.partial)) return this.close()
81
+ this.request++
82
+ const items = sorted.slice(0, 50).map((key) => ({ name: key, label: (locale && translations.value(key, locale)) || key }))
83
+ this.show({
84
+ adapter,
85
+ browse: false,
86
+ items,
87
+ index: 0,
88
+ choose: (item) => {
89
+ adapter.replace(token.start, adapter.before().length, keyCompletion(item.name, token.quote, adapter.after()))
90
+ this.close()
91
+ }
92
+ })
93
+ }
94
+
67
95
  async complete(adapter, token, start, item) {
68
96
  const before = adapter.before()
69
97
  const { text, more } = completion(item, { tag: token.tag, before: before.slice(0, start), after: adapter.after(), collection: adapter.mode === "collection" })
@@ -0,0 +1,62 @@
1
+ module TessEdit
2
+ # A document's own content in its layout. The layout's Content block marks
3
+ # its place in the MJML or HTML with two comments (in <mj-raw> tags in MJML):
4
+ #
5
+ # <!-- tess-edit:content --> … the blocks inside the Content block … <!-- /tess-edit:content -->
6
+ #
7
+ # A document stores its own blocks; the host puts them in the layout's
8
+ # document for the editor (document_with), and takes them out again when it
9
+ # saves (nodes). The layout's output with the document's output between the
10
+ # markers (merge) is the whole document, also after the layout changed.
11
+ module Content
12
+ START = "<!-- tess-edit:content -->"
13
+ FINISH = "<!-- /tess-edit:content -->"
14
+ MJML_START = "<mj-raw>#{START}</mj-raw>"
15
+ MJML_FINISH = "<mj-raw>#{FINISH}</mj-raw>"
16
+ MARKED = /(#{Regexp.escape(MJML_START)}|#{Regexp.escape(START)})(.*?)(#{Regexp.escape(MJML_FINISH)}|#{Regexp.escape(FINISH)})/m
17
+
18
+ class Error < StandardError; end
19
+
20
+ module_function
21
+
22
+ # What is between the markers
23
+ def content_of(output)
24
+ matches = output.to_s.scan(MARKED)
25
+ raise Error, "The output has #{matches.size} Content blocks, it needs exactly one" unless matches.size == 1
26
+
27
+ matches.first[1]
28
+ end
29
+
30
+ # The layout's output with this content between its markers
31
+ def merge(layout_output, content)
32
+ content_of(layout_output)
33
+ layout_output.sub(MARKED) { "#{$1}#{content}#{$3}" }
34
+ end
35
+
36
+ # The children of the document's Content block, nil when it has none
37
+ def nodes(document)
38
+ content_node(document)&.fetch("children", [])
39
+ end
40
+
41
+ # The layout's document with these nodes in its Content block
42
+ def document_with(layout_document, nodes)
43
+ document = layout_document.deep_dup
44
+ content = content_node(document)
45
+ raise Error, "The layout has no Content block" unless content
46
+
47
+ content["children"] = nodes || []
48
+ document
49
+ end
50
+
51
+ def content_node(node)
52
+ return nil unless node.is_a?(Hash)
53
+ return node if node["type"] == "content"
54
+
55
+ Array(node["children"]).each do |child|
56
+ found = content_node(child)
57
+ return found if found
58
+ end
59
+ nil
60
+ end
61
+ end
62
+ end
@@ -1,3 +1,3 @@
1
1
  module TessEdit
2
- VERSION = "0.2.2"
2
+ VERSION = "0.4.0"
3
3
  end
data/lib/tess_edit.rb CHANGED
@@ -3,6 +3,7 @@ require "stimulus-rails"
3
3
  require "mrml"
4
4
  require "tess_edit/version"
5
5
  require "tess_edit/engine"
6
+ require "tess_edit/content"
6
7
 
7
8
  module TessEdit
8
9
  Result = Data.define(:html, :errors)