tess_edit 0.2.2 → 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.
- checksums.yaml +4 -4
- data/README.md +31 -3
- data/app/javascript/tess_edit/controllers/editor_controller.js +115 -5
- data/app/javascript/tess_edit/core/translations.js +229 -0
- data/app/javascript/tess_edit/ui/canvas.js +84 -3
- data/app/javascript/tess_edit/ui/dialog.js +103 -0
- data/app/javascript/tess_edit/ui/icons.js +4 -1
- data/app/javascript/tess_edit/ui/inspector.js +72 -5
- data/app/javascript/tess_edit/ui/text_editing.js +112 -11
- data/app/javascript/tess_edit/ui/translate_dialog.js +30 -0
- data/app/javascript/tess_edit/ui/translation_popover.js +165 -0
- data/app/javascript/tess_edit/ui/variable_menu.js +29 -1
- data/lib/tess_edit/version.rb +1 -1
- data/vendor/javascript/tess_edit/tiptap.js +13 -13
- metadata +5 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: daa06d2ede42eac7f2f25875e0b91f7694a917bbeb49ef674cc36e7bf92ba92c
|
|
4
|
+
data.tar.gz: 9d3ca9a21d6fcfa3dffe6891c72b86db197ef322d78fe49977ffc0203e969ee8
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 2a4e727b8a4da2050b83902f08513cb1a4034e56c070f02964de408d04efeb59be3d03c58e14b80f232950f0cd43c268bab7824763b4db0868bf217769df7b3c
|
|
7
|
+
data.tar.gz: 24112a3299bf75b1595be478ecf5ea6b47ce8cf408e9f3525cde257bbeaf7a19da32a79620b1edc7e3ba3156c9f72f241ad4be17ac403f44c168df2b5ae4936b
|
data/README.md
CHANGED
|
@@ -16,6 +16,7 @@ It completes Liquid tags and variables as you type, making it easier to work wit
|
|
|
16
16
|
- Drag from the Blocks panel onto the canvas or into the Layers tree; move blocks on the canvas (drag handle) or in the tree; plus buttons and empty-column placeholders open an "Add block" menu.
|
|
17
17
|
- Rich text editing on the canvas with [Tiptap](https://tiptap.dev): bold, italic, underline, strikethrough, colour, links (Liquid allowed in the URL), alignment, lists and headings.
|
|
18
18
|
- Your app's Liquid variables suggested while typing `{{`, in text and in settings, and browsable from `{ }` buttons, including those of the Loop blocks around a block.
|
|
19
|
+
- Your app's translations for Liquid's `t` filter (`{{ '.greeting' | t }}`) shown as their text in a language of your choice, with every language's text, missing ones marked, editable when pointed at, and selected text made translatable.
|
|
19
20
|
- Undo/redo, duplicate, delete, keyboard shortcuts (⌘Z, ⇧⌘Z, ⌘D, Delete, Enter to edit text, Esc).
|
|
20
21
|
- Desktop and mobile preview, and a preview of the HTML as sent.
|
|
21
22
|
- Panels on both sides, or combined as tabs in one sidebar on the left or right to give the canvas more room.
|
|
@@ -173,6 +174,30 @@ The endpoint answers `GET` with the variables at `path` (the roots without one),
|
|
|
173
174
|
|
|
174
175
|
A field of your own gets the `{ }` button with `liquid: true`, or `liquid: "expression"` (a condition) or `liquid: "collection"` (what a loop goes over) for Liquid without braces.
|
|
175
176
|
|
|
177
|
+
### Translations
|
|
178
|
+
|
|
179
|
+
To show and edit translations for Liquid's `t` filter, as [Liquidum](https://github.com/entdec/liquidum) has it (`{{ '.greeting' | t }}`, `{{ "order.shipped" | t: name: order.name }}`), give the editor an endpoint with `data-tess-edit-translations-url-value`. Then:
|
|
180
|
+
|
|
181
|
+
- The top bar has a language menu. The canvas shows each `t` filter on a quoted key as its text in that language, or the Liquid when it has none (marked red when a language is missing it). "Keys" shows the Liquid everywhere. A filter that names a locale (`t: locale: 'nl'`) shows that one.
|
|
182
|
+
- Pointing at one lists its text in every language. Each can be edited there, and the arrow opens where your app keeps it.
|
|
183
|
+
- In text being edited on the canvas a filter shows as its text until the caret goes into it; a click on it does that.
|
|
184
|
+
- The text toolbar, and settings that usually hold Liquid text, have a "Make translatable" button: it asks for a key (suggested from the text), saves the selected text (or the whole setting) as that key's text in the chosen language, and puts `{{ '<key>' | t }}` in its place. Variables in the text become placeholders, given as the filter's arguments: "Hi {{ user.first_name }}" is saved as `Hi %{first_name}`, with `{{ '<key>' | t: first_name: user.first_name }}`; Liquid tags and filters can't go into a translation. Below such a setting its filters show their text.
|
|
185
|
+
- Placeholders (`%{name}`) show apart in a text; one the filter has no argument for is marked.
|
|
186
|
+
- Typing `{{ '` suggests the keys, with their text.
|
|
187
|
+
|
|
188
|
+
The endpoint answers, as JSON:
|
|
189
|
+
|
|
190
|
+
- `GET` with the keys in the document, comma-separated in `keys`: the languages, the translations of those keys and of the keys to suggest, and the keys to suggest
|
|
191
|
+
```json
|
|
192
|
+
{"locales": ["en", "nl"],
|
|
193
|
+
"translations": {".greeting": {"en": {"value": "Hello", "source": "Account › en", "url": "/locales/1/edit"}, "nl": null}},
|
|
194
|
+
"suggestions": [".greeting"]}
|
|
195
|
+
```
|
|
196
|
+
A missing text is `null`; `source` says where a text comes from (shown when pointed at) and `url` where to edit it (both optional).
|
|
197
|
+
- `PATCH` with `{"key": "…", "locale": "nl", "value": "…"}` (JSON, with the page's CSRF token): `{"key": "…", "translation": {"en": …, "nl": …}}`, or `{"errors": ["…"]}` with an error status
|
|
198
|
+
|
|
199
|
+
Where the texts are kept, and what a key starting with a dot is relative to, is up to your app. The dummy app's `TranslationsController` keeps them in memory (`/?translations=1`).
|
|
200
|
+
|
|
176
201
|
### Blocks and custom blocks
|
|
177
202
|
|
|
178
203
|
Every block is a plugin: one module in `app/javascript/tess_edit/blocks/` with its defaults, its Inspect fields, its Blocks panel tiles and a `render.mjml` hook. The built-in blocks are registered the same way a host app registers its own, so register yours before the editor connects:
|
|
@@ -215,7 +240,9 @@ cd test/dummy && bin/dev
|
|
|
215
240
|
|
|
216
241
|
`/?media=1` gives the editor the demo's image endpoint (`MediaController`), so images can be chosen from a list, uploaded, or dragged onto the canvas from the desktop; uploads go to `test/dummy/tmp/media`. Without it, images are URLs only.
|
|
217
242
|
|
|
218
|
-
`/?variables=1` gives the editor the demo's variables (`VariablesController`), an order's, to try the suggestions.
|
|
243
|
+
`/?variables=1` gives the editor the demo's variables (`VariablesController`), an order's, to try the suggestions.
|
|
244
|
+
|
|
245
|
+
`/?translations=1` gives the editor the demo's translations (`TranslationsController`, in memory, in English, Dutch and German). The options combine, e.g. `/?lock=1&media=1&variables=1&translations=1`.
|
|
219
246
|
|
|
220
247
|
Tests:
|
|
221
248
|
|
|
@@ -245,8 +272,9 @@ Ideas for later, not planned yet:
|
|
|
245
272
|
|
|
246
273
|
- **Importing MJML.** Turn an existing MJML template into a TessEdit document, so designs made elsewhere can be edited here. Parts without a matching block could become HTML blocks.
|
|
247
274
|
- **Images whose address is Liquid.** An image with a `src` like `{{ product.image_url }}` shows as a broken image on the canvas. It should show a placeholder there instead, and in Inspect say that the address is filled in when the email is sent.
|
|
248
|
-
- **A translation block.** Text that differs per language in one design, e.g. a block with a version of its text per locale, so a host app doesn't need a design per language.
|
|
249
|
-
- **
|
|
275
|
+
- **A translation block.** Text that differs per language in one design, e.g. a block with a version of its text per locale, so a host app doesn't need a design per language. (Translations through the `t` filter are there, see Translations.)
|
|
276
|
+
- **Translating with a service.** Fill in a key's missing languages with DeepL or an LLM, from the translations popover.
|
|
277
|
+
- **Text extensions from the host app.** Tiptap (the vendored bundle exports `Node`, `Mark` and `Extension`) can be extended, but the editor's extensions, the email HTML of rich text (`export/richtext.js`) and the text toolbar are fixed. A call like `registerTextExtension({ extension, toHtml(node, children), button })` would add all three, as `registerBlock` does for blocks. A Liquid variable shown as a chip (`{{ customer.first_name }}`) would be a first example; a translation could be one too. The bundle exports ProseMirror's `Plugin`, `PluginKey`, `Decoration` and `DecorationSet` (used for translations); node views would need more.
|
|
250
278
|
- **Dropping an image file where there's no image.** A file dropped on an empty spot in the canvas could add a new Image block there with the upload, instead of being refused.
|
|
251
279
|
|
|
252
280
|
## License
|
|
@@ -15,6 +15,10 @@
|
|
|
15
15
|
// variablesUrl the variables a template can use, suggested while typing {{
|
|
16
16
|
// and browsed with { } buttons (see core/variables.js), e.g.
|
|
17
17
|
// Liquidum's /liquidum/variables?roots=…
|
|
18
|
+
// translationsUrl the host's translations for Liquid's t filter ({{ '.greeting' | t }}),
|
|
19
|
+
// shown in a language chosen in the top bar, listed and edited
|
|
20
|
+
// while pointed at, and made from selected text (see
|
|
21
|
+
// core/translations.js)
|
|
18
22
|
// lock JSON: only the insides of some blocks and some root fields can
|
|
19
23
|
// change, e.g. {"except": ["content"], "fields": ["data.subject"]}
|
|
20
24
|
// (see core/lock.js)
|
|
@@ -33,12 +37,15 @@ import { starterDocument } from "tess_edit/core/starter"
|
|
|
33
37
|
import { toMjml } from "tess_edit/export/mjml"
|
|
34
38
|
import { COMPILE_URL, compile } from "tess_edit/export/compile"
|
|
35
39
|
import { IMAGE_FIELD, fetchMedia, uploadMedia } from "tess_edit/core/media"
|
|
40
|
+
import { Translations, keysIn, suggestKey, toTranslation, translationTag } from "tess_edit/core/translations"
|
|
36
41
|
import { Variables, loopScope } from "tess_edit/core/variables"
|
|
37
42
|
import { Canvas } from "tess_edit/ui/canvas"
|
|
38
43
|
import { Tree } from "tess_edit/ui/tree"
|
|
39
44
|
import { Inspector } from "tess_edit/ui/inspector"
|
|
40
45
|
import { TextEditing } from "tess_edit/ui/text_editing"
|
|
41
46
|
import { VariableMenu } from "tess_edit/ui/variable_menu"
|
|
47
|
+
import { TranslationPopover } from "tess_edit/ui/translation_popover"
|
|
48
|
+
import { askTranslationKey } from "tess_edit/ui/translate_dialog"
|
|
42
49
|
import { renderBlocksPanel } from "tess_edit/ui/blocks_panel"
|
|
43
50
|
import { debounce, h } from "tess_edit/ui/dom"
|
|
44
51
|
import { icon } from "tess_edit/ui/icons"
|
|
@@ -47,11 +54,12 @@ const TOOL = "w-8 h-8 flex items-center justify-center rounded-md text-gray-600
|
|
|
47
54
|
const TAB = "px-3 h-12 text-[13px] font-medium border-b-2 -mb-px"
|
|
48
55
|
const PANELS = ["left", "split", "right"]
|
|
49
56
|
const PANELS_KEY = "tess_edit:panels"
|
|
57
|
+
const TRANSLATION_LOCALE_KEY = "tess_edit:translation_locale"
|
|
50
58
|
// Two sidebars (256px + 320px) leave too little canvas below this editor width.
|
|
51
59
|
const NARROW_WIDTH = 1000
|
|
52
60
|
|
|
53
61
|
export default class extends Controller {
|
|
54
|
-
static values = { document: String, sample: { type: Boolean, default: true }, panels: { type: String, default: "split" }, compileUrl: { type: String, default: COMPILE_URL }, mediaUrl: String, variablesUrl: String, lock: String }
|
|
62
|
+
static values = { document: String, sample: { type: Boolean, default: true }, panels: { type: String, default: "split" }, compileUrl: { type: String, default: COMPILE_URL }, mediaUrl: String, variablesUrl: String, translationsUrl: String, lock: String }
|
|
55
63
|
static targets = ["jsonInput", "mjmlInput", "htmlInput"]
|
|
56
64
|
|
|
57
65
|
connect() {
|
|
@@ -69,7 +77,10 @@ export default class extends Controller {
|
|
|
69
77
|
this.requests = {}
|
|
70
78
|
this.media = { enabled: Boolean(this.mediaUrlValue), images: [], uploading: false, error: null }
|
|
71
79
|
this.variables = new Variables(this.variablesUrlValue)
|
|
72
|
-
this.
|
|
80
|
+
this.translations = new Translations(this.translationsUrlValue)
|
|
81
|
+
this.translationPopover = this.translations.enabled ? new TranslationPopover(this) : null
|
|
82
|
+
this.translationLocaleChoice = this.stored(TRANSLATION_LOCALE_KEY)
|
|
83
|
+
this.variableMenu = this.variables.enabled || this.translations.enabled ? new VariableMenu(this) : null
|
|
73
84
|
|
|
74
85
|
this.scheduleCanvas = debounce(() => this.renderCanvas(), 60)
|
|
75
86
|
this.scheduleOutputs = debounce(() => this.writeOutputs(), 300)
|
|
@@ -78,9 +89,80 @@ export default class extends Controller {
|
|
|
78
89
|
this.renderAll()
|
|
79
90
|
this.writeOutputs()
|
|
80
91
|
if (this.media.enabled) this.loadMedia()
|
|
92
|
+
if (this.translations.enabled) {
|
|
93
|
+
this.translations.subscribe(() => this.showTranslations())
|
|
94
|
+
this.loadTranslations()
|
|
95
|
+
}
|
|
81
96
|
this.element.tessEdit = this
|
|
82
97
|
}
|
|
83
98
|
|
|
99
|
+
// --- translations -------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
// The language translations show in: the one chosen in the top bar, else
|
|
102
|
+
// the host's first; null shows their Liquid ("Keys")
|
|
103
|
+
get translationLocale() {
|
|
104
|
+
const { locales } = this.translations
|
|
105
|
+
if (this.translationLocaleChoice === "") return null
|
|
106
|
+
return locales.includes(this.translationLocaleChoice) ? this.translationLocaleChoice : locales[0] || null
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
setTranslationLocale(locale) {
|
|
110
|
+
this.translationLocaleChoice = locale
|
|
111
|
+
try {
|
|
112
|
+
localStorage.setItem(TRANSLATION_LOCALE_KEY, locale)
|
|
113
|
+
} catch {}
|
|
114
|
+
this.showTranslations()
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// The keys in the document the editor doesn't have yet
|
|
118
|
+
loadTranslations() {
|
|
119
|
+
if (this.translations.enabled) this.translations.load(keysIn(this.doc))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
showTranslations() {
|
|
123
|
+
this.renderTopBar()
|
|
124
|
+
this.canvas.showTranslations()
|
|
125
|
+
this.textEditing.refreshTranslations()
|
|
126
|
+
this.inspector.refreshTranslations()
|
|
127
|
+
this.translationPopover?.refresh()
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Keeps a text as a translation in the editor's language (the host's first
|
|
131
|
+
// in "Keys"), under a key the user confirms, and gives its t filter; null
|
|
132
|
+
// when it isn't. Its Liquid variables become placeholders, given as the
|
|
133
|
+
// filter's arguments: "Hi {{ user.name }}" is kept as "Hi %{name}", in
|
|
134
|
+
// {{ '.hi' | t: name: user.name }}.
|
|
135
|
+
async makeTranslatable(text) {
|
|
136
|
+
const translations = this.translations
|
|
137
|
+
const locale = this.translationLocale || translations.locales[0]
|
|
138
|
+
if (!locale) {
|
|
139
|
+
this.flash(translations.error || "There are no languages to translate into yet.")
|
|
140
|
+
return null
|
|
141
|
+
}
|
|
142
|
+
const translation = toTranslation(text)
|
|
143
|
+
if (translation.error) {
|
|
144
|
+
this.flash(translation.error)
|
|
145
|
+
return null
|
|
146
|
+
}
|
|
147
|
+
const key = await askTranslationKey(this.root, {
|
|
148
|
+
text: translation.text,
|
|
149
|
+
locale,
|
|
150
|
+
suggested: suggestKey(text),
|
|
151
|
+
existing: async (key) => {
|
|
152
|
+
await translations.load([key])
|
|
153
|
+
return translations.value(key, locale)
|
|
154
|
+
}
|
|
155
|
+
})
|
|
156
|
+
if (!key) return null
|
|
157
|
+
try {
|
|
158
|
+
await translations.save(key, locale, translation.text)
|
|
159
|
+
} catch (error) {
|
|
160
|
+
this.flash(error.message)
|
|
161
|
+
return null
|
|
162
|
+
}
|
|
163
|
+
return translationTag(key, translation.args)
|
|
164
|
+
}
|
|
165
|
+
|
|
84
166
|
async loadMedia() {
|
|
85
167
|
try {
|
|
86
168
|
this.media.images = await fetchMedia(this.mediaUrlValue)
|
|
@@ -135,6 +217,7 @@ export default class extends Controller {
|
|
|
135
217
|
Object.values(this.requests).forEach((request) => request.abort())
|
|
136
218
|
this.textEditing?.stop()
|
|
137
219
|
this.variableMenu?.close()
|
|
220
|
+
this.translationPopover?.hide({ force: true })
|
|
138
221
|
this.closeMenu()
|
|
139
222
|
this.resizeObserver?.disconnect()
|
|
140
223
|
document.removeEventListener("mousedown", this.outsideClick)
|
|
@@ -224,7 +307,7 @@ export default class extends Controller {
|
|
|
224
307
|
this.canvas = new Canvas(this, this.frame)
|
|
225
308
|
this.tree = new Tree(this, this.treeElement)
|
|
226
309
|
this.inspector = new Inspector(this, this.inspectorElement)
|
|
227
|
-
this.textEditing = new TextEditing(this.textToolbar, { menu: this.variableMenu })
|
|
310
|
+
this.textEditing = new TextEditing(this.textToolbar, { menu: this.variableMenu, editor: this })
|
|
228
311
|
renderBlocksPanel(this, this.blocksElement)
|
|
229
312
|
this.observeWidth()
|
|
230
313
|
|
|
@@ -302,8 +385,12 @@ export default class extends Controller {
|
|
|
302
385
|
}
|
|
303
386
|
|
|
304
387
|
storedPanels() {
|
|
388
|
+
return this.stored(PANELS_KEY)
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
stored(key) {
|
|
305
392
|
try {
|
|
306
|
-
return localStorage.getItem(
|
|
393
|
+
return localStorage.getItem(key)
|
|
307
394
|
} catch {
|
|
308
395
|
return null
|
|
309
396
|
}
|
|
@@ -339,10 +426,12 @@ export default class extends Controller {
|
|
|
339
426
|
)
|
|
340
427
|
)
|
|
341
428
|
|
|
342
|
-
|
|
429
|
+
// replaceChildren would turn a null into the text "null", so only pass real elements.
|
|
430
|
+
this.topBar.replaceChildren(...[
|
|
343
431
|
h("span", { class: "font-semibold text-gray-900 dark:text-gray-100 mr-3" }, "Email"),
|
|
344
432
|
toggle(this.mode, [["edit", "edit", "Edit"], ["preview", "eye", "Preview the email as sent, with Liquid tags"]], (mode) => this.setMode(mode)),
|
|
345
433
|
toggle(this.device, [["desktop", "desktop", "Desktop"], ["mobile", "mobile", "Mobile"]], (device) => this.setDevice(device)),
|
|
434
|
+
this.translations.enabled ? this.translationLocaleMenu() : null,
|
|
346
435
|
h("div", { class: "flex-1" }),
|
|
347
436
|
toggle(
|
|
348
437
|
this.layout,
|
|
@@ -362,6 +451,26 @@ export default class extends Controller {
|
|
|
362
451
|
h("span", { html: icon("export") }),
|
|
363
452
|
"Code"
|
|
364
453
|
)
|
|
454
|
+
].filter(Boolean))
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// Which language translations show in on the canvas
|
|
458
|
+
translationLocaleMenu() {
|
|
459
|
+
const current = this.translationLocale || ""
|
|
460
|
+
return h(
|
|
461
|
+
"label",
|
|
462
|
+
{ class: "ml-1 flex items-center gap-1 text-gray-500 dark:text-gray-400", title: "Show translations in" },
|
|
463
|
+
h("span", { html: icon("globe") }),
|
|
464
|
+
h(
|
|
465
|
+
"select",
|
|
466
|
+
{
|
|
467
|
+
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",
|
|
468
|
+
"aria-label": "Show translations in",
|
|
469
|
+
onchange: (event) => this.setTranslationLocale(event.target.value)
|
|
470
|
+
},
|
|
471
|
+
this.translations.locales.map((locale) => h("option", { value: locale, selected: locale === current }, locale.toUpperCase())),
|
|
472
|
+
h("option", { value: "", selected: current === "" }, "Keys")
|
|
473
|
+
)
|
|
365
474
|
)
|
|
366
475
|
}
|
|
367
476
|
|
|
@@ -426,6 +535,7 @@ export default class extends Controller {
|
|
|
426
535
|
}
|
|
427
536
|
|
|
428
537
|
async writeOutputs() {
|
|
538
|
+
this.loadTranslations()
|
|
429
539
|
const json = JSON.stringify(this.doc)
|
|
430
540
|
const mjml = toMjml(this.doc)
|
|
431
541
|
const result = await this.compileMjml(mjml, "outputs")
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
// Translations from the host app, for Liquid's t filter (as Liquidum has it):
|
|
2
|
+
//
|
|
3
|
+
// {{ '.greeting' | t }} {{ "order.shipped" | t: name: order.customer.name }}
|
|
4
|
+
//
|
|
5
|
+
// The editor shows what they say in a language chosen in its top bar, lists
|
|
6
|
+
// every language's text, edits them, and turns selected text into one. The
|
|
7
|
+
// editor's translationsUrl answers:
|
|
8
|
+
//
|
|
9
|
+
// GET ?keys=.greeting,order.shipped →
|
|
10
|
+
// { locales: ["en", "nl"],
|
|
11
|
+
// translations: { ".greeting": { en: { value: "Hello", source: "…", url: "…" }, nl: null }, … },
|
|
12
|
+
// suggestions: [".greeting", ".signature", …] }
|
|
13
|
+
//
|
|
14
|
+
// with the keys asked for and the ones suggested while typing {{ ' (those
|
|
15
|
+
// with their translations too, to show them as the suggestions). A source
|
|
16
|
+
// says where a text comes from and url where to edit it; a missing text is
|
|
17
|
+
// null. Saving one:
|
|
18
|
+
//
|
|
19
|
+
// PATCH { key, locale, value } → { key, translation: { en: …, nl: … } }
|
|
20
|
+
//
|
|
21
|
+
// which answers 422 with { errors: [...] } when it can't be saved.
|
|
22
|
+
|
|
23
|
+
// A t filter on a quoted key, with what follows it in the tag (its arguments)
|
|
24
|
+
const CALL = /\{\{-?\s*(["'])([^"'{}|]+?)\1\s*\|\s*t(?:ranslate)?\b((?:(?!\}\}).)*?)-?\}\}/g
|
|
25
|
+
|
|
26
|
+
// The t filters in a text: [{ start, end, key, locale, args, text }]; locale
|
|
27
|
+
// when the call names one (t: locale: 'nl'), args the names of its other
|
|
28
|
+
// arguments, which fill the text's %{…} placeholders (t: name: user.name)
|
|
29
|
+
export function translationCalls(text) {
|
|
30
|
+
if (typeof text !== "string" || !text.includes("{{")) return []
|
|
31
|
+
return Array.from(text.matchAll(CALL), (match) => {
|
|
32
|
+
const names = Array.from(match[3].matchAll(/(?:^\s*:|,)\s*(\w+)\s*:/g), (name) => name[1])
|
|
33
|
+
return {
|
|
34
|
+
start: match.index,
|
|
35
|
+
end: match.index + match[0].length,
|
|
36
|
+
key: match[2].trim(),
|
|
37
|
+
locale: match[3].match(/\blocale:\s*["']([\w-]+)["']/)?.[1] || null,
|
|
38
|
+
args: names.filter((name) => name !== "locale"),
|
|
39
|
+
text: match[0]
|
|
40
|
+
}
|
|
41
|
+
})
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// The %{…} placeholders in a translation's text
|
|
45
|
+
export function placeholders(value) {
|
|
46
|
+
return Array.from(String(value ?? "").matchAll(/%\{(\w+)\}/g), (match) => match[1])
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// The placeholders a call doesn't give an argument for
|
|
50
|
+
export function missingArguments(value, call) {
|
|
51
|
+
return [...new Set(placeholders(value))].filter((name) => !call.args?.includes(name))
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// A text in parts: [{ text }, { placeholder: "name" }, …], to show the placeholders apart
|
|
55
|
+
export function textParts(value) {
|
|
56
|
+
return String(value ?? "").split(/(%\{\w+\})/).filter(Boolean).map((part) => {
|
|
57
|
+
const placeholder = part.match(/^%\{(\w+)\}$/)
|
|
58
|
+
return placeholder ? { placeholder: placeholder[1] } : { text: part }
|
|
59
|
+
})
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Options of I18n's t, which can't be arguments' names
|
|
63
|
+
const RESERVED = new Set(["locale", "scope", "default", "separator", "resolve", "object", "fallback", "fallback_in_progress", "format", "cascade", "throw", "raise", "deep_interpolation", "count"])
|
|
64
|
+
|
|
65
|
+
// A text with Liquid in it, as a translation: its variables become
|
|
66
|
+
// placeholders, given as arguments of the t filter.
|
|
67
|
+
// "Hi {{ customer.first_name }}!" → { text: "Hi %{first_name}!", args: [["first_name", "customer.first_name"]] }
|
|
68
|
+
// Gives { error } for Liquid a translation can't hold: tags ({% … %}) and
|
|
69
|
+
// filters ({{ total | money }}).
|
|
70
|
+
export function toTranslation(text) {
|
|
71
|
+
if (/\{%/.test(text)) return { error: "Liquid tags ({% … %}) can't go into a translation. Select the text around them." }
|
|
72
|
+
const args = []
|
|
73
|
+
let error = null
|
|
74
|
+
const converted = String(text).replace(/\{\{-?\s*(.*?)\s*-?\}\}/g, (tag, expression) => {
|
|
75
|
+
if (!/^[A-Za-z_][\w]*(\.[\w]+|\[\d+\])*$/.test(expression)) {
|
|
76
|
+
error = `${tag} can't go into a translation, only variables like {{ customer.name }} can. Select the text around it.`
|
|
77
|
+
return tag
|
|
78
|
+
}
|
|
79
|
+
const existing = args.find(([, value]) => value === expression)
|
|
80
|
+
if (existing) return `%{${existing[0]}}`
|
|
81
|
+
const base = expression.split(".").pop().replace(/\W/g, "_")
|
|
82
|
+
let name = RESERVED.has(base) ? `${base}_value` : base
|
|
83
|
+
for (let n = 2; args.some(([other]) => other === name); n++) name = `${base}_${n}`
|
|
84
|
+
args.push([name, expression])
|
|
85
|
+
return `%{${name}}`
|
|
86
|
+
})
|
|
87
|
+
return error ? { error } : { text: converted, args }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Every key in a document's texts and settings
|
|
91
|
+
export function keysIn(value, keys = new Set()) {
|
|
92
|
+
if (typeof value === "string") {
|
|
93
|
+
for (const call of translationCalls(value)) keys.add(call.key)
|
|
94
|
+
} else if (Array.isArray(value)) {
|
|
95
|
+
value.forEach((item) => keysIn(item, keys))
|
|
96
|
+
} else if (value && typeof value === "object") {
|
|
97
|
+
Object.values(value).forEach((item) => keysIn(item, keys))
|
|
98
|
+
}
|
|
99
|
+
return keys
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// A key for a text, in the template's own scope: "Thanks for your order!" → ".thanks_for_your_order"
|
|
103
|
+
export function suggestKey(text) {
|
|
104
|
+
const words = String(text)
|
|
105
|
+
.normalize("NFKD")
|
|
106
|
+
.replace(/[̀-ͯ]/g, "")
|
|
107
|
+
.toLowerCase()
|
|
108
|
+
.replace(/\{\{.*?\}\}|\{%.*?%\}/g, " ")
|
|
109
|
+
.match(/[a-z0-9]+/g) || []
|
|
110
|
+
return `.${words.slice(0, 5).join("_") || "text"}`
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function validKey(key) {
|
|
114
|
+
return /^\.?[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/.test(key || "")
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// The tag that translates a key, with arguments for its placeholders: [[name, expression]]
|
|
118
|
+
export function translationTag(key, args = []) {
|
|
119
|
+
return `{{ '${key}' | t${args.map(([name, expression], i) => `${i ? "," : ":"} ${name}: ${expression}`).join("")} }}`
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// The key being typed at the caret, in a t filter to be: "Hi {{ '.gr" →
|
|
123
|
+
// { start: 7, partial: ".gr", quote: "'" }, with start where the key begins
|
|
124
|
+
export function keyToken(before) {
|
|
125
|
+
const match = before.match(/\{\{-?\s*(["'])([\w.-]*)$/)
|
|
126
|
+
if (!match) return null
|
|
127
|
+
return { start: before.length - match[2].length, partial: match[2], quote: match[1] }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// The text that replaces the key being typed for a chosen key: the key, its
|
|
131
|
+
// closing quote and the t filter, unless they're there already
|
|
132
|
+
export function keyCompletion(key, quote, after = "") {
|
|
133
|
+
if (after.startsWith(quote)) return key
|
|
134
|
+
return `${key}${quote} | t${/^\s*-?\}\}/.test(after) ? "" : " }}"}`
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// The translations the editor has from the host app, by key
|
|
138
|
+
export class Translations {
|
|
139
|
+
constructor(url, { fetch: fetcher = (...args) => fetch(...args) } = {}) {
|
|
140
|
+
this.url = url
|
|
141
|
+
this.fetch = fetcher
|
|
142
|
+
this.locales = []
|
|
143
|
+
this.entries = new Map()
|
|
144
|
+
this.suggestions = []
|
|
145
|
+
this.loaded = false
|
|
146
|
+
this.started = false
|
|
147
|
+
this.requested = new Set()
|
|
148
|
+
this.error = null
|
|
149
|
+
this.listeners = new Set()
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
get enabled() {
|
|
153
|
+
return Boolean(this.url)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Calls fn whenever translations arrive or change
|
|
157
|
+
subscribe(fn) {
|
|
158
|
+
this.listeners.add(fn)
|
|
159
|
+
return () => this.listeners.delete(fn)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
changed() {
|
|
163
|
+
this.listeners.forEach((fn) => fn())
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Asks for the keys it doesn't have yet (the first time, for the suggestions too)
|
|
167
|
+
async load(keys = []) {
|
|
168
|
+
if (!this.enabled) return
|
|
169
|
+
const missing = [...keys].filter((key) => !this.entries.has(key) && !this.requested.has(key))
|
|
170
|
+
if (this.started && !missing.length) return
|
|
171
|
+
this.started = true
|
|
172
|
+
missing.forEach((key) => this.requested.add(key))
|
|
173
|
+
const url = new URL(this.url, window.location.href)
|
|
174
|
+
if (missing.length) url.searchParams.set("keys", missing.join(","))
|
|
175
|
+
try {
|
|
176
|
+
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})`)
|
|
178
|
+
const result = await response.json()
|
|
179
|
+
this.locales = result.locales || []
|
|
180
|
+
for (const [key, entry] of Object.entries(result.translations || {})) this.entries.set(key, entry || {})
|
|
181
|
+
// Keys asked for that the host doesn't answer are missing in every language
|
|
182
|
+
for (const key of missing) if (!this.entries.has(key)) this.entries.set(key, {})
|
|
183
|
+
this.suggestions = result.suggestions || this.suggestions
|
|
184
|
+
this.loaded = true
|
|
185
|
+
this.error = null
|
|
186
|
+
} catch (error) {
|
|
187
|
+
this.error = error.message
|
|
188
|
+
// Asked for again next time
|
|
189
|
+
this.started = false
|
|
190
|
+
this.requested.clear()
|
|
191
|
+
}
|
|
192
|
+
this.changed()
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
has(key) {
|
|
196
|
+
return this.entries.has(key)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// { value, source, url } or null when it's missing
|
|
200
|
+
get(key, locale) {
|
|
201
|
+
return this.entries.get(key)?.[locale] || null
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
value(key, locale) {
|
|
205
|
+
const value = this.get(key, locale)?.value
|
|
206
|
+
return typeof value === "string" ? value : null
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// The languages without a text for the key
|
|
210
|
+
missing(key) {
|
|
211
|
+
return this.locales.filter((locale) => this.value(key, locale) === null)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async save(key, locale, value) {
|
|
215
|
+
const token = document.querySelector("meta[name='csrf-token']")?.content
|
|
216
|
+
const response = await this.fetch(new URL(this.url, window.location.href), {
|
|
217
|
+
method: "PATCH",
|
|
218
|
+
headers: { "Content-Type": "application/json", Accept: "application/json", ...(token ? { "X-CSRF-Token": token } : {}) },
|
|
219
|
+
body: JSON.stringify({ key, locale, value }),
|
|
220
|
+
credentials: "same-origin"
|
|
221
|
+
})
|
|
222
|
+
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})`)
|
|
224
|
+
this.entries.set(key, result.translation || {})
|
|
225
|
+
if (!this.suggestions.includes(key) && key.startsWith(".")) this.suggestions = [...this.suggestions, key].sort()
|
|
226
|
+
this.changed()
|
|
227
|
+
return result.translation
|
|
228
|
+
}
|
|
229
|
+
}
|
|
@@ -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
7
|
import { ancestors, canInsert, 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)
|
|
@@ -75,8 +83,10 @@ export class Canvas {
|
|
|
75
83
|
this.overlay.id = "tess-overlay"
|
|
76
84
|
doc.body.append(this.overlay)
|
|
77
85
|
this.win.scrollTo(0, scrollY)
|
|
78
|
-
if (mode === "edit")
|
|
79
|
-
|
|
86
|
+
if (mode === "edit") {
|
|
87
|
+
this.listen()
|
|
88
|
+
this.annotate()
|
|
89
|
+
} else doc.addEventListener("click", (event) => event.target.closest("a") && event.preventDefault(), true)
|
|
80
90
|
this.refresh()
|
|
81
91
|
}
|
|
82
92
|
|
|
@@ -97,6 +107,63 @@ export class Canvas {
|
|
|
97
107
|
this.win.addEventListener("scroll", () => this.editor.closeMenu(), { passive: true })
|
|
98
108
|
this.win.addEventListener("resize", () => this.refresh())
|
|
99
109
|
for (const image of doc.images) image.addEventListener("load", () => this.refresh(), { once: true })
|
|
110
|
+
// Translations list every language while pointed at
|
|
111
|
+
doc.addEventListener("mouseover", (event) => {
|
|
112
|
+
const chip = event.target.closest?.("[data-tess-key]")
|
|
113
|
+
if (chip) this.editor.translationPopover?.show(chip.dataset.tessKey, this.toParentRect(chip.getBoundingClientRect()))
|
|
114
|
+
})
|
|
115
|
+
doc.addEventListener("mouseout", (event) => event.target.closest?.("[data-tess-key]") && this.editor.translationPopover?.scheduleHide())
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// --- translations ----------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
// Wraps every t filter in the email's text in a span that shows its text
|
|
121
|
+
// (showTranslations), keeping the Liquid for when there's none
|
|
122
|
+
annotate() {
|
|
123
|
+
if (!this.editor.translations?.enabled) return
|
|
124
|
+
const doc = this.doc
|
|
125
|
+
const walker = doc.createTreeWalker(doc.body, 4 /* NodeFilter.SHOW_TEXT */)
|
|
126
|
+
const nodes = []
|
|
127
|
+
while (walker.nextNode()) {
|
|
128
|
+
const node = walker.currentNode
|
|
129
|
+
if (node.nodeValue.includes("{{") && !node.parentElement?.closest("#tess-overlay, script, style, title")) nodes.push(node)
|
|
130
|
+
}
|
|
131
|
+
for (const node of nodes) {
|
|
132
|
+
const text = node.nodeValue
|
|
133
|
+
const calls = translationCalls(text)
|
|
134
|
+
if (!calls.length) continue
|
|
135
|
+
const fragment = doc.createDocumentFragment()
|
|
136
|
+
let at = 0
|
|
137
|
+
for (const call of calls) {
|
|
138
|
+
fragment.append(text.slice(at, call.start))
|
|
139
|
+
const span = doc.createElement("span")
|
|
140
|
+
span.className = "tess-t"
|
|
141
|
+
Object.assign(span.dataset, { tessKey: call.key, tessCall: call.text, tessArgs: call.args.join(",") }, call.locale ? { tessLocale: call.locale } : {})
|
|
142
|
+
fragment.append(span)
|
|
143
|
+
at = call.end
|
|
144
|
+
}
|
|
145
|
+
fragment.append(text.slice(at))
|
|
146
|
+
node.replaceWith(fragment)
|
|
147
|
+
}
|
|
148
|
+
this.showTranslations()
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// The text in the editor's language (or the call's own), or the Liquid when
|
|
152
|
+
// there's none; red when a language is missing it
|
|
153
|
+
showTranslations() {
|
|
154
|
+
const translations = this.editor.translations
|
|
155
|
+
if (!translations?.enabled || !this.doc) return
|
|
156
|
+
for (const span of this.doc.querySelectorAll(".tess-t[data-tess-call]")) {
|
|
157
|
+
const key = span.dataset.tessKey
|
|
158
|
+
const locale = span.dataset.tessLocale || this.editor.translationLocale
|
|
159
|
+
const value = locale ? translations.value(key, locale) : null
|
|
160
|
+
const unfilled = value === null ? [] : missingArguments(value, { args: span.dataset.tessArgs ? span.dataset.tessArgs.split(",") : [] })
|
|
161
|
+
if (value === null) span.textContent = span.dataset.tessCall
|
|
162
|
+
else showText(span, value)
|
|
163
|
+
span.title = unfilled.length ? `No argument for ${unfilled.map((name) => `%{${name}}`).join(", ")} in the t filter` : ""
|
|
164
|
+
span.classList.toggle("tess-t-missing", unfilled.length > 0 || (translations.has(key) && (locale ? value === null : translations.missing(key).length > 0)))
|
|
165
|
+
}
|
|
166
|
+
this.refresh()
|
|
100
167
|
}
|
|
101
168
|
|
|
102
169
|
// --- mapping between DOM and blocks -------------------------------------
|
|
@@ -435,3 +502,17 @@ export class Canvas {
|
|
|
435
502
|
this.indicator = null
|
|
436
503
|
}
|
|
437
504
|
}
|
|
505
|
+
|
|
506
|
+
// A translation's text in an element, its %{…} placeholders apart
|
|
507
|
+
export function showText(element, value) {
|
|
508
|
+
const doc = element.ownerDocument
|
|
509
|
+
element.replaceChildren(
|
|
510
|
+
...textParts(value).map((part) => {
|
|
511
|
+
if (part.text !== undefined) return doc.createTextNode(part.text)
|
|
512
|
+
const placeholder = doc.createElement("span")
|
|
513
|
+
placeholder.className = "tess-t-arg"
|
|
514
|
+
placeholder.textContent = part.placeholder
|
|
515
|
+
return placeholder
|
|
516
|
+
})
|
|
517
|
+
)
|
|
518
|
+
}
|