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,10 +1,13 @@
1
1
  // The document is a plain JSON tree:
2
2
  // { id, type, attributes: {}, data: {}, children: [] }
3
- // `attributes` map one-to-one onto MJML attributes, `data` holds everything else
4
- // (rich text, Liquid expressions, link lists). All functions here are pure apart
3
+ // `attributes` hold a block's styling, named after MJML's attributes (a kit
4
+ // with other output maps them onto its own), `data` holds everything else
5
+ // (rich text, Liquid expressions, link lists). A block copied from elsewhere,
6
+ // such as a host's reusable content, may also have `origin`: the id of the
7
+ // block it is a copy of (see renumber). All functions here are pure apart
5
8
  // from the mutating helpers, which change the tree they are given in place.
6
9
 
7
- import { getBlock, paletteItem, typesForRoles } from "tess_edit/core/registry"
10
+ import { DEFAULT_KIT, getBlock, getKit, kitOf, paletteItem, typesForRoles } from "tess_edit/core/registry"
8
11
 
9
12
  export const VERSION = 1
10
13
 
@@ -30,8 +33,11 @@ export function createNode(type, overrides = {}) {
30
33
  }
31
34
  }
32
35
 
33
- export function createDocument() {
34
- return { version: VERSION, ...createNode("root") }
36
+ // An empty document of a kit (see core/registry.js), an email by default.
37
+ export function createDocument(kit = DEFAULT_KIT) {
38
+ const definition = getKit(kit)
39
+ if (!definition) throw new Error(`Unknown kit: ${kit}`)
40
+ return { version: VERSION, ...createNode(definition.root) }
35
41
  }
36
42
 
37
43
  // Calls fn(node, parent, index, depth) for every node, depth first.
@@ -79,12 +85,34 @@ export function acceptedRoles(doc, parentId) {
79
85
  const accepts = getBlock(hit.node.type)?.accepts
80
86
  if (accepts !== "inherit") return accepts || []
81
87
  const owner = ancestors(doc, parentId).find((node) => getBlock(node.type)?.accepts !== "inherit")
82
- return (owner ? getBlock(owner.type).accepts : getBlock("root").accepts).filter((role) => role !== "column")
88
+ return (owner ? getBlock(owner.type).accepts : getBlock(doc.type).accepts).filter((role) => role !== "column")
83
89
  }
84
90
 
85
- // The block types that may be placed directly inside the node with `parentId`.
86
- export function accepted(doc, parentId) {
87
- return typesForRoles(acceptedRoles(doc, parentId))
91
+ // The block types of the document's kit that may be placed directly inside
92
+ // the node with `parentId`. A block that is `unique`, such as the Content
93
+ // block, can't be added when the document has one, but it can be moved.
94
+ export function accepted(doc, parentId, { moving = false } = {}) {
95
+ const types = typesForRoles(acceptedRoles(doc, parentId), kitOf(doc)?.key)
96
+ return moving ? types : types.filter((type) => !getBlock(type).unique || !findType(doc, type))
97
+ }
98
+
99
+ // The first node of a type, depth first
100
+ export function findType(doc, type) {
101
+ let result = null
102
+ walk(doc, (node) => {
103
+ if (result) return false
104
+ if (node.type === type) result = node
105
+ })
106
+ return result
107
+ }
108
+
109
+ // The first type that keeps a node from going inside `parentId`, where the
110
+ // types in `allowed` can go, or null when it fits: the node's own, or for a
111
+ // container that takes what its parent takes ("inherit"), one of its children's.
112
+ export function misfit(node, allowed) {
113
+ if (!allowed.includes(node.type)) return node.type
114
+ if (getBlock(node.type)?.accepts !== "inherit") return null
115
+ return node.children.find((child) => !allowed.includes(child.type))?.type || null
88
116
  }
89
117
 
90
118
  export function canInsert(doc, parentId, type) {
@@ -97,10 +125,14 @@ export function isHorizontal(doc, parentId) {
97
125
  return hit ? !!getBlock(hit.node.type)?.horizontal : false
98
126
  }
99
127
 
100
- // Gives a node and all of its descendants fresh ids, for duplicating and pasting.
101
- export function renumber(node) {
128
+ // Gives a node and all of its descendants fresh ids, for duplicating and
129
+ // pasting. The copy is new content, so it has no origin; with `origin` each
130
+ // block's origin is the id of the block it is a copy of instead.
131
+ export function renumber(node, { origin = false } = {}) {
102
132
  const copy = clone(node)
103
133
  walk(copy, (n) => {
134
+ if (origin) n.origin = n.id
135
+ else delete n.origin
104
136
  n.id = uid()
105
137
  })
106
138
  return copy
@@ -162,12 +194,15 @@ export function getValue(node, key) {
162
194
  return node[scope]?.[name]
163
195
  }
164
196
 
165
- // Light validation of a document read from storage or an import.
166
- export function normalize(input) {
197
+ // Light validation of a document read from storage or an import. With a
198
+ // `kit`, the document has to be one of that kit's.
199
+ export function normalize(input, { kit } = {}) {
167
200
  const doc = typeof input === "string" ? JSON.parse(input) : clone(input)
168
- // The root block was called "page" before; such documents still load.
169
- if (doc?.type === "page") doc.type = "root"
170
- if (!doc || doc.type !== "root") throw new Error("Not a TessEdit document: the top node must be the root block")
201
+ // The email's root block was called "page", then "root"; such documents still load.
202
+ if (doc?.type === "page" || doc?.type === "root") doc.type = "email"
203
+ const own = kitOf(doc)
204
+ if (!own) throw new Error("Not a TessEdit document: the top node must be a root block")
205
+ if (kit && own.key !== kit) throw new Error(`This is a document for the ${own.name} editor, not the ${getKit(kit)?.name || kit} one`)
171
206
  walk(doc, (node) => {
172
207
  if (!getBlock(node.type)) throw new Error(`Unknown block type: ${node.type}`)
173
208
  node.id ||= uid()
@@ -179,6 +214,21 @@ export function normalize(input) {
179
214
  return doc
180
215
  }
181
216
 
217
+ // The Content block of a layout (see blocks/content.js): where the documents
218
+ // using the layout put their own blocks.
219
+ export function contentNode(doc) {
220
+ return findType(doc, "content")
221
+ }
222
+
223
+ // The layout with these blocks in its Content block, as a new document
224
+ export function withContent(layout, nodes) {
225
+ const doc = clone(layout)
226
+ const content = contentNode(doc)
227
+ if (!content) throw new Error("The layout has no Content block")
228
+ content.children = clone(nodes || [])
229
+ return doc
230
+ }
231
+
182
232
  // The node (or small tree) a Blocks panel tile creates.
183
233
  export function createFromPalette(key) {
184
234
  const item = paletteItem(key)
@@ -9,14 +9,18 @@
9
9
  // accepts: undefined, // roles it takes as children, "inherit", or undefined for a leaf
10
10
  // defaults: () => ({ attributes: {}, data: {} }),
11
11
  // fields: [{ title: "Product", fields: [{ key: "data.sku", label: "SKU", type: "text" }] }],
12
- // // a field's visible: (node, editor) => boolean shows it only when it applies;
12
+ // // a field's visible: (node, editor) => boolean shows it only when it applies,
13
+ // // and a group only when one of its fields does;
13
14
  // // imageField(key, label, idKey) (core/media.js) makes an image field;
14
15
  // // a "code" field takes language: "html" (default) or "css"
15
16
  // hint: "Shown at the top of Inspect.",
16
17
  // label: (node) => `Product · ${node.data.sku}`, // optional, for Layers and the canvas
17
18
  // richText: "data.content", // optional: a Tiptap JSON value edited on the canvas by double-click
18
19
  // palette: [{ key, label, icon, category, create: ({ createNode }) => node }], // optional
19
- // render: { mjml: (node, ctx) => "<mj-text …>" } // ctx: see export/mjml.js
20
+ // kits: ["email"], // the kits it is part of, default ["email"]
21
+ // unique: true, // optional: at most one per document, like Content
22
+ // render: { mjml: (node, ctx) => "<mj-text …>" } // one per format of its kits:
23
+ // // mjml (export/mjml.js), html (export/html.js)
20
24
  // })
21
25
  //
22
26
  // Roles: "body" (inside the page or a wrapper: sections, heroes), "wrapper",
@@ -26,11 +30,99 @@
26
30
  //
27
31
  // Without a `palette`, a block with a `category` gets one tile in the Blocks
28
32
  // panel; `palette: []` gives it none. Registering a type again replaces it.
33
+ //
34
+ // Kits: what the editor makes. A kit has its own root block and the blocks
35
+ // that name it in their `kits`, and decides what the canvas shows and what
36
+ // the editor outputs:
37
+ //
38
+ // registerKit({
39
+ // key: "note", // data-tess-edit-kit-value; blocks name it in `kits`
40
+ // name: "Note", // shown in the top bar
41
+ // root: "note", // the type of its root block, unique to the kit
42
+ // starter: () => doc, // the sample document
43
+ // devices: [{ key, icon, title, width }], // optional: canvas widths in the top bar
44
+ // previewTitle: "…", // the Preview button's title
45
+ // canvas: async (doc, { editor, compileUrl, signal }) => ({ html, errors }),
46
+ // // the canvas's HTML, with the tess-<id> and tessph-<id>
47
+ // // classes when editor is true; null when aborted
48
+ // outputs: async (doc, { compileUrl, signal }) => ({ outputs: { html: "…" }, errors }),
49
+ // // what the editor stores besides the JSON (the inputs,
50
+ // // the change event and the Code dialog); null when aborted
51
+ // notes: { html: "…" }, // optional: what each output is, in the Code dialog
52
+ // errors: "The email could not be compiled" // shown before the reasons
53
+ // })
54
+ //
55
+ // The built-in kit is "email" (MJML, compiled to HTML on the server, see
56
+ // kits/email.js). A host adds its own kit with its root block and blocks,
57
+ // and brings TessEdit's blocks into it with extendBlock:
58
+ //
59
+ // extendBlock("text", { kits: ["note"], render: { note: (node, ctx) => "<div>…</div>" } })
60
+ //
61
+ // which adds the kits and render hooks (and any fields, in groups of their
62
+ // own) to the block as it is registered, also when another gem replaced it.
29
63
 
30
64
  import { builtinBlocks, builtinCategories } from "tess_edit/blocks/builtin"
65
+ import { builtinKits } from "tess_edit/kits/builtin"
31
66
 
32
67
  const definitions = new Map()
33
68
  const categoryList = new Map()
69
+ const kitList = new Map()
70
+ const sourceList = new Map()
71
+
72
+ export const DEFAULT_KIT = "email"
73
+
74
+ export function registerKit(kit) {
75
+ const { key, name, root, canvas, outputs } = kit || {}
76
+ if (!key || !name) throw new Error("A kit needs a key and a name")
77
+ if (!root) throw new Error(`Kit ${key} needs a root block type`)
78
+ if (typeof canvas !== "function" || typeof outputs !== "function") throw new Error(`Kit ${key} needs canvas(doc, options) and outputs(doc, options)`)
79
+ kitList.set(key, { devices: null, notes: {}, errors: `The ${name} could not be rendered`, ...kit })
80
+ return kitList.get(key)
81
+ }
82
+
83
+ export function getKit(key = DEFAULT_KIT) {
84
+ return kitList.get(key)
85
+ }
86
+
87
+ export function kits() {
88
+ return [...kitList.values()]
89
+ }
90
+
91
+ // The kit a document belongs to, from its root block
92
+ export function kitOf(doc) {
93
+ return kits().find((kit) => kit.root === doc?.type)
94
+ }
95
+
96
+ function inKit(definition, kit) {
97
+ return !kit || definition.kits.includes(kit)
98
+ }
99
+
100
+ // Tiles the host app gives at run time, such as reusable content from its
101
+ // server, in a section of their own at the bottom of the Blocks panel:
102
+ //
103
+ // registerPaletteSource({
104
+ // key: "snippets",
105
+ // label: "Snippets",
106
+ // items: async (editor) => [{ key, label, type, description, version }],
107
+ // // null leaves the section out (e.g. not for this editor);
108
+ // // `type` is the block type create gives, to show where it fits
109
+ // create: async (item, editor) => node // the node inserted, e.g. with renumber(block, { origin: true })
110
+ // })
111
+ //
112
+ // A tile is dragged onto the canvas or clicked like any other. Its node goes
113
+ // where its type fits; a container that takes what its parent takes
114
+ // ("inherit") also needs its children to fit there.
115
+ export function registerPaletteSource(source) {
116
+ const { key, label, items, create } = source || {}
117
+ if (!key || !label) throw new Error("A palette source needs a key and a label")
118
+ if (typeof items !== "function" || typeof create !== "function") throw new Error(`Palette source ${key} needs items(editor) and create(item, editor)`)
119
+ sourceList.set(key, { ...source })
120
+ return sourceList.get(key)
121
+ }
122
+
123
+ export function paletteSources() {
124
+ return [...sourceList.values()]
125
+ }
34
126
 
35
127
  export function registerCategory({ key, label, order = 100 }) {
36
128
  if (!key || !label) throw new Error("A category needs a key and a label")
@@ -41,8 +133,8 @@ export function registerBlock(definition) {
41
133
  const { type, name, render } = definition || {}
42
134
  if (!type || typeof type !== "string") throw new Error("A block needs a type")
43
135
  if (!name) throw new Error(`Block ${type} needs a name`)
44
- if (typeof render?.mjml !== "function") throw new Error(`Block ${type} needs render.mjml(node, ctx)`)
45
- if (type !== "root" && !(definition.roles || []).length) throw new Error(`Block ${type} needs roles, e.g. ["content"]`)
136
+ if (!Object.values(render || {}).some((hook) => typeof hook === "function")) throw new Error(`Block ${type} needs render.mjml(node, ctx) or render.html(node, ctx)`)
137
+ if (!kits().some((kit) => kit.root === type) && !(definition.roles || []).length) throw new Error(`Block ${type} needs roles, e.g. ["content"]`)
46
138
 
47
139
  const palette = (definition.palette ?? (definition.category ? [{ key: type, label: name, icon: definition.icon, category: definition.category }] : [])).map((item) => ({
48
140
  icon: definition.icon,
@@ -51,7 +143,20 @@ export function registerBlock(definition) {
51
143
  ...item,
52
144
  type
53
145
  }))
54
- definitions.set(type, { roles: [], ...definition, palette })
146
+ definitions.set(type, { roles: [], kits: [DEFAULT_KIT], ...definition, palette })
147
+ return definitions.get(type)
148
+ }
149
+
150
+ // Adds kits, render hooks and field groups to a registered block
151
+ export function extendBlock(type, { kits = [], render = {}, fields = [] } = {}) {
152
+ const definition = definitions.get(type)
153
+ if (!definition) throw new Error(`No block ${type} to extend`)
154
+ definitions.set(type, {
155
+ ...definition,
156
+ kits: [...new Set([...definition.kits, ...kits])],
157
+ render: { ...definition.render, ...render },
158
+ fields: [...(definition.fields || []), ...fields]
159
+ })
55
160
  return definitions.get(type)
56
161
  }
57
162
 
@@ -67,18 +172,20 @@ export function isContainer(type) {
67
172
  return !!getBlock(type)?.accepts
68
173
  }
69
174
 
70
- // The block types that may go where the given roles are accepted.
71
- export function typesForRoles(roles) {
72
- return [...definitions.values()].filter((definition) => definition.roles.some((role) => roles.includes(role))).map((definition) => definition.type)
175
+ // The block types that may go where the given roles are accepted, of a kit's
176
+ // blocks when one is given.
177
+ export function typesForRoles(roles, kit) {
178
+ return [...definitions.values()].filter((definition) => inKit(definition, kit) && definition.roles.some((role) => roles.includes(role))).map((definition) => definition.type)
73
179
  }
74
180
 
75
181
  export function categories() {
76
182
  return [...categoryList.values()].sort((a, b) => a.order - b.order)
77
183
  }
78
184
 
79
- // Tiles for the Blocks panel, in registration order.
80
- export function paletteItems() {
81
- return [...definitions.values()].flatMap((definition) => definition.palette)
185
+ // Tiles for the Blocks panel, in registration order, of a kit's blocks when
186
+ // one is given.
187
+ export function paletteItems(kit) {
188
+ return [...definitions.values()].filter((definition) => inKit(definition, kit)).flatMap((definition) => definition.palette)
82
189
  }
83
190
 
84
191
  export function paletteItem(key) {
@@ -90,5 +197,6 @@ export function label(node) {
90
197
  return definition?.label?.(node) || definition?.name || node.type
91
198
  }
92
199
 
200
+ builtinKits.forEach(registerKit)
93
201
  builtinCategories.forEach(registerCategory)
94
202
  builtinBlocks.forEach(registerBlock)
@@ -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
+ }
@@ -9,9 +9,10 @@ import EditorController from "tess_edit/controllers/editor_controller"
9
9
  export { EditorController }
10
10
  export { toMjml } from "tess_edit/export/mjml"
11
11
  export { compile } from "tess_edit/export/compile"
12
- export { richTextToHtml } from "tess_edit/export/richtext"
13
- export { createDocument, createNode, normalize } from "tess_edit/core/document"
14
- export { registerBlock, registerCategory, getBlock, blockTypes, paletteItems } from "tess_edit/core/registry"
12
+ export { escapeAttribute, escapeText, richTextToHtml } from "tess_edit/export/richtext"
13
+ export { contentNode, createDocument, createNode, findType, normalize, renumber, withContent } from "tess_edit/core/document"
14
+ export { CONTENT_END, CONTENT_START } from "tess_edit/blocks/content"
15
+ export { registerBlock, registerCategory, registerKit, registerPaletteSource, extendBlock, getBlock, getKit, kitOf, kits, blockTypes, paletteItems, paletteSources } from "tess_edit/core/registry"
15
16
  export * as fields from "tess_edit/blocks/fields"
16
17
  export { imageField } from "tess_edit/core/media"
17
18
  export { starterDocument } from "tess_edit/core/starter"
@@ -0,0 +1,5 @@
1
+ // The built-in kit, registered by core/registry.js before the blocks.
2
+
3
+ import email from "tess_edit/kits/email"
4
+
5
+ export const builtinKits = [email]
@@ -0,0 +1,28 @@
1
+ // The email kit: the document becomes MJML in the browser, which the server
2
+ // compiles to HTML with MRML (export/compile.js), for the canvas and the
3
+ // html output alike. Liquid stays in both, for rendering at send time.
4
+
5
+ import { toMjml } from "tess_edit/export/mjml"
6
+ import { compile } from "tess_edit/export/compile"
7
+ import { starterDocument } from "tess_edit/core/starter"
8
+
9
+ export default {
10
+ key: "email",
11
+ name: "Email",
12
+ root: "email",
13
+ starter: starterDocument,
14
+ devices: [
15
+ { key: "desktop", icon: "desktop", title: "Desktop" },
16
+ { key: "mobile", icon: "mobile", title: "Mobile", width: "375px" }
17
+ ],
18
+ previewTitle: "Preview the email as sent, with Liquid tags",
19
+ canvas: (doc, { editor, compileUrl, signal }) => compile(toMjml(doc, { editor }), { url: compileUrl, signal }),
20
+ async outputs(doc, { compileUrl, signal }) {
21
+ const mjml = toMjml(doc)
22
+ const result = await compile(mjml, { url: compileUrl, signal })
23
+ if (!result) return null
24
+ return { outputs: { mjml, html: result.html || "" }, errors: result.errors }
25
+ },
26
+ notes: { mjml: "Liquid loops and conditions are in <mj-raw> tags.", html: "Liquid is left in place for rendering at send time." },
27
+ errors: "The email could not be compiled"
28
+ }