tess_edit 0.5.8 → 0.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ // Values from the host app for the Liquid in a document, such as a
2
+ // contract's for {{ contract.account.name }} when the editor is a record's:
3
+ // the canvas and text being edited show an expression's value in place of
4
+ // its Liquid, and the Liquid again when the caret goes into it.
5
+ //
6
+ // The host gives them by the expression as it's written in the tag, without
7
+ // the braces, filters and all:
8
+ //
9
+ // { "contract.account.name": "sv COFA", "contract.starts_on | date: '%-d %B %Y'": "1 maart 2025" }
10
+ //
11
+ // with the kit's canvas result ({ html, errors, values }), for a canvas the
12
+ // host renders, or with the editor's setValues(values). An expression without
13
+ // one keeps its Liquid; t filters are translations (core/translations.js).
14
+ // An empty string is a value that is empty for now (the contract's sponsor
15
+ // has no chamber of commerce number yet): it keeps its Liquid, in red, as
16
+ // something to fill in where it comes from. null is no value known.
17
+
18
+ import { translationCalls } from "tess_edit/core/translations"
19
+
20
+ // An output tag, {{ … }}, with its expression
21
+ const OUTPUT = /\{\{-?\s*((?:(?!\}\}).)+?)\s*-?\}\}/g
22
+
23
+ // The expression of a tag as the host gets it: its whitespace as one space
24
+ export function normalizeExpression(expression) {
25
+ return String(expression ?? "").trim().replace(/\s+/g, " ")
26
+ }
27
+
28
+ // The output tags in a text that aren't t filters: [{ start, end, expression, text }]
29
+ export function valueCalls(text) {
30
+ if (typeof text !== "string" || !text.includes("{{")) return []
31
+ const translations = translationCalls(text)
32
+ return Array.from(text.matchAll(OUTPUT), (match) => ({
33
+ start: match.index,
34
+ end: match.index + match[0].length,
35
+ expression: normalizeExpression(match[1]),
36
+ text: match[0]
37
+ })).filter((call) => !translations.some((translation) => translation.start === call.start))
38
+ }
39
+
40
+ // Every expression in a document's texts and settings
41
+ export function expressionsIn(value, expressions = new Set()) {
42
+ if (typeof value === "string") {
43
+ for (const call of valueCalls(value)) expressions.add(call.expression)
44
+ } else if (Array.isArray(value)) {
45
+ value.forEach((item) => expressionsIn(item, expressions))
46
+ } else if (value && typeof value === "object") {
47
+ Object.values(value).forEach((item) => expressionsIn(item, expressions))
48
+ }
49
+ return expressions
50
+ }
51
+
52
+ // The values the editor has from the host app, by expression
53
+ export class Values {
54
+ constructor() {
55
+ this.entries = new Map()
56
+ this.empties = new Set()
57
+ this.listeners = new Set()
58
+ }
59
+
60
+ get enabled() {
61
+ return this.entries.size > 0 || this.empties.size > 0
62
+ }
63
+
64
+ // Calls fn whenever they change
65
+ subscribe(fn) {
66
+ this.listeners.add(fn)
67
+ return () => this.listeners.delete(fn)
68
+ }
69
+
70
+ // Replaces them all; false when nothing changed. An empty string is an
71
+ // empty value (empty), null none.
72
+ set(values) {
73
+ const entries = new Map()
74
+ const empties = new Set()
75
+ for (const [expression, value] of Object.entries(values || {})) {
76
+ if (value === null || value === undefined) continue
77
+ if (value === "") empties.add(normalizeExpression(expression))
78
+ else entries.set(normalizeExpression(expression), String(value))
79
+ }
80
+ const same = entries.size === this.entries.size && [...entries].every(([key, value]) => this.entries.get(key) === value) &&
81
+ empties.size === this.empties.size && [...empties].every((key) => this.empties.has(key))
82
+ if (same) return false
83
+ this.entries = entries
84
+ this.empties = empties
85
+ this.listeners.forEach((fn) => fn())
86
+ return true
87
+ }
88
+
89
+ // Whether the host says it's empty for now
90
+ empty(expression) {
91
+ return this.empties.has(normalizeExpression(expression))
92
+ }
93
+
94
+ // Its text, or null when there's none
95
+ value(expression) {
96
+ return this.entries.get(normalizeExpression(expression)) ?? null
97
+ }
98
+ }
@@ -0,0 +1,162 @@
1
+ // A table (blocks/table.js) as HTML, for a kit whose tables are HTML: the
2
+ // email's mj-table, which MJML copies as it is, so a cell's blocks are HTML
3
+ // too, not MJML. Its styles are inline, as mail clients need: borders,
4
+ // padding and heading rows on each cell.
5
+ //
6
+ // tableHtml(node, { editor, richText, escapeText, escapeAttribute })
7
+ // // → "<colgroup>…</colgroup><thead>…</thead><tbody>…</tbody>"
8
+ //
9
+ // A cell's blocks are rendered here (cellBlock): Text, Image, Button,
10
+ // Divider, Spacer, Loop, Condition, Assign and tables; others show nothing.
11
+ // With editor, every element has its tess-<id> class, an empty container a
12
+ // placeholder that fits there, and Liquid tags are left out, so a Loop's
13
+ // rows show once.
14
+
15
+ import { t } from "tess_edit/core/i18n"
16
+ import { span } from "tess_edit/core/table"
17
+
18
+ const ROW = "table_row"
19
+ const PLACEHOLDER = "padding:12px;text-align:center;color:#94a3b8;font-size:13px;font-family:system-ui,sans-serif"
20
+
21
+ function style(declarations) {
22
+ const css = Object.entries(declarations)
23
+ .filter(([, value]) => value !== undefined && value !== null && value !== "")
24
+ .map(([name, value]) => `${name}:${value}`)
25
+ .join(";")
26
+ return css ? ` style="${css.replace(/"/g, "&quot;")}"` : ""
27
+ }
28
+
29
+ const classes = (node, ctx) => (ctx.editor ? ` class="tess-${node.id}"` : "")
30
+
31
+ // The table's rows, also in its Loops and Conditions, for the column count
32
+ function rowsOf(node) {
33
+ return (node.children || []).flatMap((child) => (child.type === ROW ? [child] : ["table", "table_cell"].includes(child.type) ? [] : rowsOf(child)))
34
+ }
35
+
36
+ function columnsOf(table) {
37
+ const list = Array.isArray(table.data?.columns) ? table.data.columns : []
38
+ const widest = Math.max(0, ...rowsOf(table).map((row) => (row.children || []).reduce((sum, cell) => sum + span(cell), 0)))
39
+ return Array.from({ length: Math.max(list.length, widest) }, (_, i) => list[i] || {})
40
+ }
41
+
42
+ export function tableHtml(table, ctx) {
43
+ const d = table.data || {}
44
+ const columns = columnsOf(table)
45
+ const line = `${d.borderWidth || "1px"} solid ${d.borderColor || "#d1d5db"}`
46
+ const look = {
47
+ // Around every cell, or only under each row
48
+ border: d.borders === "rows" ? { "border-bottom": line } : { border: line },
49
+ lineAbove: (width) => (d.borders === "rows" ? { "border-top": `${width} solid ${d.borderColor || "#d1d5db"}` } : { "border-top-width": width }),
50
+ padding: d.cellPadding || "6px 8px",
51
+ heading: { "background-color": d.headingBackground, color: d.headingColor, "font-weight": d.headingWeight || "bold" },
52
+ stripe: d.stripe,
53
+ columns
54
+ }
55
+ const kids = table.children || []
56
+ const heading = []
57
+ for (const kid of kids) {
58
+ if (kid.type !== ROW || !kid.data?.heading) break
59
+ heading.push(kid)
60
+ }
61
+ const state = { body: 0 }
62
+ const head = heading.map((row) => rowHtml(row, ctx, look, null))
63
+ let body = kids.slice(heading.length).map((kid) => between(kid, ctx, look, state))
64
+ if (!kids.length && ctx.editor) body = [placeholderRow(table, columns.length)]
65
+ const widths = columns.some((column) => column.width) ? `<colgroup>${columns.map((column) => `<col${style({ width: column.width })}>`).join("")}</colgroup>` : ""
66
+ return [widths, head.length ? `<thead>${head.join("")}</thead>` : "", `<tbody>${body.join("\n")}</tbody>`].join("")
67
+ }
68
+
69
+ function placeholderRow(node, count) {
70
+ return `<tr><td class="tessph-${node.id}" colspan="${Math.max(count, 1)}" style="${PLACEHOLDER}">${t("Drop a row here")}</td></tr>`
71
+ }
72
+
73
+ // What is between a table's rows: a Row, or a Loop, Condition or Assign
74
+ function between(node, ctx, look, state) {
75
+ if (node.type === ROW) return rowHtml(node, ctx, look, state)
76
+ const inner = () => {
77
+ if (!(node.children || []).length && ctx.editor) return [placeholderRow(node, look.columns.length)]
78
+ return node.children.map((child) => between(child, ctx, look, state))
79
+ }
80
+ const [open, close] = liquidTags(node)
81
+ if (open === null) return ""
82
+ if (ctx.editor) return node.type === "assign" ? "" : inner().join("\n")
83
+ return node.type === "assign" ? open : [open, ...inner(), close].join("\n")
84
+ }
85
+
86
+ function liquidTags(node) {
87
+ const d = node.data || {}
88
+ if (node.type === "loop") return [`{% for ${d.variable || "item"} in ${d.collection || "items"} %}`, "{% endfor %}"]
89
+ if (node.type === "condition") return [`{% if ${d.expression || "true"} %}`, "{% endif %}"]
90
+ if (node.type === "assign") return [`{% assign ${d.variable || "value"} = ${d.expression || "nil"} %}`, ""]
91
+ return [null, null]
92
+ }
93
+
94
+ function rowHtml(row, ctx, look, state) {
95
+ const heading = !!row.data?.heading
96
+ // Stripes on every other body row; a Loop's row counts once, as it can't
97
+ // know how many it will be
98
+ const striped = state && !heading && look.stripe && state.body++ % 2 === 1
99
+ let start = 0
100
+ const cells = (row.children || []).map((cell) => {
101
+ const column = look.columns[start] || {}
102
+ start += span(cell)
103
+ return cellHtml(cell, ctx, look, { row, column, heading, striped })
104
+ })
105
+ if (!cells.length && ctx.editor) cells.push(`<td class="tessph-${row.id}" style="${PLACEHOLDER}">${t("Drop a cell here")}</td>`)
106
+ return `<tr${classes(row, ctx)}>${cells.join("")}</tr>`
107
+ }
108
+
109
+ function cellHtml(cell, ctx, look, { row, column, heading, striped }) {
110
+ const a = cell.attributes || {}
111
+ const tag = heading ? "th" : "td"
112
+ const declarations = {
113
+ ...look.border,
114
+ ...(row.data?.lineAbove ? look.lineAbove(row.data.lineAbove) : {}),
115
+ padding: a.padding || look.padding,
116
+ "text-align": a["text-align"] || column.align || "left",
117
+ "vertical-align": a["vertical-align"] || "top",
118
+ ...(heading ? look.heading : {}),
119
+ "background-color": a["background-color"] || row.attributes?.["background-color"] || (heading ? look.heading["background-color"] : striped ? look.stripe : undefined),
120
+ color: a.color || (heading ? look.heading.color : undefined)
121
+ }
122
+ const colspan = span(cell) > 1 ? ` colspan="${span(cell)}"` : ""
123
+ const kids = cell.children || []
124
+ const inner = !kids.length && ctx.editor ? `<div class="tessph-${cell.id}" style="${PLACEHOLDER}">${t("Drop content here")}</div>` : kids.map((child) => cellBlock(child, ctx)).join("")
125
+ return `<${tag}${classes(cell, ctx)}${colspan}${style(declarations)}>${inner}</${tag}>`
126
+ }
127
+
128
+ // A block in a cell, as HTML
129
+ export function cellBlock(node, ctx) {
130
+ const a = node.attributes || {}
131
+ const d = node.data || {}
132
+ const children = () => {
133
+ if (!(node.children || []).length && ctx.editor) return `<div class="tessph-${node.id}" style="${PLACEHOLDER}">${t("Drop content here")}</div>`
134
+ return node.children.map((child) => cellBlock(child, ctx)).join("")
135
+ }
136
+ switch (node.type) {
137
+ case "text":
138
+ return `<div${classes(node, ctx)}${style({ padding: a.padding, "text-align": a.align, color: a.color, "font-family": a["font-family"], "font-size": a["font-size"], "font-weight": a["font-weight"], "line-height": a["line-height"], "background-color": a["container-background-color"] })}>${ctx.richText(d.content)}</div>`
139
+ case "image": {
140
+ const image = `<img src="${ctx.escapeAttribute(a.src || "")}" alt="${ctx.escapeAttribute(a.alt || "")}"${style({ display: "block", width: a.width, "max-width": "100%", height: "auto", border: "0" })}>`
141
+ const linked = a.href ? `<a href="${ctx.escapeAttribute(a.href)}">${image}</a>` : image
142
+ return `<div${classes(node, ctx)}${style({ padding: a.padding, "text-align": a.align })}>${linked}</div>`
143
+ }
144
+ case "button":
145
+ return `<div${classes(node, ctx)}${style({ padding: a.padding, "text-align": a.align })}><a href="${ctx.escapeAttribute(a.href || "#")}"${style({ display: "inline-block", "background-color": a["background-color"] || "#414141", color: a.color || "#ffffff", padding: a["inner-padding"] || "10px 25px", "border-radius": a["border-radius"] || "3px", "font-size": a["font-size"], "font-weight": a["font-weight"], "text-decoration": "none" })}>${ctx.escapeText(d.content || "")}</a></div>`
146
+ case "divider":
147
+ return `<div${classes(node, ctx)}${style({ padding: a.padding })}><div${style({ "border-top": `${a["border-width"] || "1px"} ${a["border-style"] || "solid"} ${a["border-color"] || "#000000"}` })}></div></div>`
148
+ case "spacer":
149
+ return `<div${classes(node, ctx)}${style({ height: a.height || "20px" })}></div>`
150
+ case "table":
151
+ return `<div${classes(node, ctx)}${style({ padding: a.padding })}><table${style({ width: a.width || "100%", "border-collapse": "collapse" })}>${tableHtml(node, ctx)}</table></div>`
152
+ case "loop":
153
+ case "condition":
154
+ case "assign": {
155
+ const [open, close] = liquidTags(node)
156
+ if (node.type === "assign") return ctx.editor ? "" : open
157
+ return ctx.editor ? children() : `${open}${children()}${close}`
158
+ }
159
+ default:
160
+ return ""
161
+ }
162
+ }
@@ -16,6 +16,7 @@ export { registerBlock, registerCategory, registerFieldType, registerKit, regist
16
16
  export * as fields from "tess_edit/blocks/fields"
17
17
  export { imageField } from "tess_edit/core/media"
18
18
  export { starterDocument } from "tess_edit/core/starter"
19
+ export { cellOf, tableOf } from "tess_edit/core/table"
19
20
 
20
21
  export function registerTessEdit(application, identifier = "tess-edit") {
21
22
  application.register(identifier, EditorController)
@@ -2,13 +2,15 @@
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
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
+ // filters show their text in the editor's language, and with its values
6
+ // other Liquid output shows its value (see annotate).
6
7
 
7
8
  import { ancestors, find, isDescendant, isHorizontal } from "tess_edit/core/document"
8
9
  import { t } from "tess_edit/core/i18n"
9
10
  import { imageFields } from "tess_edit/core/media"
10
11
  import { getBlock, inlinePart, label } from "tess_edit/core/registry"
11
12
  import { missingArguments, textParts, translationCalls } from "tess_edit/core/translations"
13
+ import { valueCalls } from "tess_edit/core/values"
12
14
  import { FREE_CSS, FreeLayout } from "tess_edit/ui/free_layout"
13
15
  import { icon } from "tess_edit/ui/icons"
14
16
 
@@ -46,6 +48,10 @@ a{cursor:default}
46
48
  .tess-t-arg{border-radius:3px;padding:0 2px;background:rgba(37,99,235,.18);font-size:.9em}
47
49
  .tess-t-missing .tess-t-arg{background:rgba(220,38,38,.18)}
48
50
  .tess-t-hidden{display:none}
51
+ .tess-v-filled,.tess-v-raw{border-radius:3px;background:rgba(5,150,105,.08);box-shadow:inset 0 -1px 0 rgba(5,150,105,.55)}
52
+ .ProseMirror .tess-v-filled{cursor:text}
53
+ .tess-v-hidden{display:none}
54
+ .tess-v-empty{border-radius:3px;background:rgba(220,38,38,.08);box-shadow:inset 0 -1px 0 rgba(220,38,38,.65)}
49
55
  `
50
56
 
51
57
  // A file dragged in from outside the browser (block drags set editor.drag)
@@ -129,30 +135,42 @@ export class Canvas {
129
135
  doc.addEventListener("mouseout", (event) => event.target.closest?.("[data-tess-key]") && this.editor.translationPopover?.scheduleHide())
130
136
  }
131
137
 
132
- // --- translations ----------------------------------------------------------
138
+ // --- translations and values -----------------------------------------------
133
139
 
134
140
  // Wraps every t filter in the email's text in a span that shows its text
135
- // (showTranslations), keeping the Liquid for when there's none
141
+ // (showTranslations), and with the host's values every other output tag in
142
+ // one that shows its value (showValues), keeping the Liquid for when there's
143
+ // none. Again when the values change: what's wrapped stays as it is.
136
144
  annotate() {
137
- if (!this.editor.translations?.enabled) return
145
+ const translating = Boolean(this.editor.translations?.enabled)
146
+ const valuing = Boolean(this.editor.values?.enabled)
147
+ if (!this.doc?.body) return
148
+ // Without values any more, what shows one shows its Liquid again
149
+ if (!translating && !valuing) return this.showValues()
138
150
  const doc = this.doc
139
151
  const walker = doc.createTreeWalker(doc.body, 4 /* NodeFilter.SHOW_TEXT */)
140
152
  const nodes = []
141
153
  while (walker.nextNode()) {
142
154
  const node = walker.currentNode
143
- if (node.nodeValue.includes("{{") && !node.parentElement?.closest("#tess-overlay, script, style, title")) nodes.push(node)
155
+ if (node.nodeValue.includes("{{") && !node.parentElement?.closest("#tess-overlay, script, style, title, .tess-t, .tess-v, .ProseMirror")) nodes.push(node)
144
156
  }
145
157
  for (const node of nodes) {
146
158
  const text = node.nodeValue
147
- const calls = translationCalls(text)
159
+ const calls = [...(translating ? translationCalls(text) : []), ...(valuing ? valueCalls(text).map((call) => ({ ...call, value: true })) : [])].sort((a, b) => a.start - b.start)
148
160
  if (!calls.length) continue
149
161
  const fragment = doc.createDocumentFragment()
150
162
  let at = 0
151
163
  for (const call of calls) {
152
164
  fragment.append(text.slice(at, call.start))
153
165
  const span = doc.createElement("span")
154
- span.className = "tess-t"
155
- Object.assign(span.dataset, { tessKey: call.key, tessCall: call.text, tessArgs: call.args.join(",") }, call.locale ? { tessLocale: call.locale } : {})
166
+ if (call.value) {
167
+ span.className = "tess-v"
168
+ Object.assign(span.dataset, { tessExpression: call.expression, tessCall: call.text })
169
+ span.textContent = call.text
170
+ } else {
171
+ span.className = "tess-t"
172
+ Object.assign(span.dataset, { tessKey: call.key, tessCall: call.text, tessArgs: call.args.join(",") }, call.locale ? { tessLocale: call.locale } : {})
173
+ }
156
174
  fragment.append(span)
157
175
  at = call.end
158
176
  }
@@ -160,6 +178,23 @@ export class Canvas {
160
178
  node.replaceWith(fragment)
161
179
  }
162
180
  this.showTranslations()
181
+ this.showValues()
182
+ }
183
+
184
+ // Each output tag's value, its Liquid when pointed at, or the Liquid when
185
+ // there's none
186
+ showValues() {
187
+ const values = this.editor.values
188
+ if (!values || !this.doc?.body) return
189
+ for (const span of this.doc.querySelectorAll(".tess-v[data-tess-call]")) {
190
+ const value = values.value(span.dataset.tessExpression)
191
+ const empty = value === null && values.empty(span.dataset.tessExpression)
192
+ span.textContent = value ?? span.dataset.tessCall
193
+ span.title = empty ? t("Empty for now: fill it in where it comes from") : value === null ? "" : span.dataset.tessCall
194
+ span.classList.toggle("tess-v-filled", value !== null)
195
+ span.classList.toggle("tess-v-empty", empty)
196
+ }
197
+ this.refresh()
163
198
  }
164
199
 
165
200
  // The text in the editor's language (or the call's own), or the Liquid when
@@ -196,8 +231,33 @@ export class Canvas {
196
231
  return null
197
232
  }
198
233
 
234
+ // A block's element. A Loop's blocks can show once per item, as a Table's
235
+ // rows do with a record's values (a host's canvas), each copy with the
236
+ // block's class: the copy clicked last is the one meant, and so are the
237
+ // blocks in it and around it, until another is clicked. The copy is kept
238
+ // by its place among them, as the canvas is written again.
199
239
  elementOf(id) {
200
- return this.doc?.querySelector(`.tess-${id}`) || this.doc?.querySelector(`.tessph-${id}`)
240
+ const anchor = this.anchorElement()
241
+ const near = anchor && (anchor.closest(`.tess-${id}`) || anchor.querySelector(`.tess-${id}, .tessph-${id}`))
242
+ return near || this.doc?.querySelector(`.tess-${id}`) || this.doc?.querySelector(`.tessph-${id}`)
243
+ }
244
+
245
+ // Remembers the copy of a block that was clicked
246
+ anchorAt(hit) {
247
+ if (!hit || hit.placeholder) return
248
+ const copies = [...this.doc.querySelectorAll(`.tess-${hit.id}`)]
249
+ this.anchor = copies.length > 1 ? { id: hit.id, index: Math.max(0, copies.indexOf(hit.element)) } : null
250
+ }
251
+
252
+ anchorElement() {
253
+ if (!this.anchor || !this.doc) return null
254
+ return this.doc.querySelectorAll(`.tess-${this.anchor.id}`)[this.anchor.index] || null
255
+ }
256
+
257
+ // The rectangle of the copy of a block an element is in, else its first
258
+ hoverRect(id) {
259
+ const element = this.hoverElement?.isConnected && this.hoverElement.closest(`.tess-${id}`)
260
+ return element ? element.getBoundingClientRect() : this.rectOf(id)
201
261
  }
202
262
 
203
263
  // The rectangle of a block in viewport coordinates of the iframe. Blocks
@@ -224,7 +284,7 @@ export class Canvas {
224
284
  // Where an inline part is edited: the element its render marks with
225
285
  // data-tess-edit-field, or for the richText shorthand the block's own
226
286
  textContainer(id, key) {
227
- const cell = this.doc?.querySelector(`.tess-${id}`)
287
+ const cell = this.elementOf(id)
228
288
  const part = this.partElement(cell, key)
229
289
  if (part) return part
230
290
  if (key !== getBlock(find(this.editor.doc, id)?.node.type)?.richText) return null
@@ -265,7 +325,7 @@ export class Canvas {
265
325
 
266
326
  if (this.hoverId && this.hoverId !== selectedId) {
267
327
  const hit = find(this.editor.doc, this.hoverId)
268
- const rect = hit && this.rectOf(this.hoverId)
328
+ const rect = hit && this.hoverRect(this.hoverId)
269
329
  if (rect && hit.node !== this.editor.doc) {
270
330
  const box = this.box(rect, "tess-hover")
271
331
  box.append(Object.assign(this.doc.createElement("div"), { className: "tess-label", textContent: getBlock(hit.node.type)?.name || hit.node.type }))
@@ -347,6 +407,11 @@ export class Canvas {
347
407
  onMove(event) {
348
408
  if (this.editor.drag || this.free.dragging) return
349
409
  const hit = this.hit(event.target)
410
+ const element = hit && !hit.placeholder ? hit.element : null
411
+ if (element !== this.hoverElement) {
412
+ this.hoverElement = element
413
+ this.hoverId = null
414
+ }
350
415
  this.setHover(hit && !hit.placeholder ? hit.id : null)
351
416
  }
352
417
 
@@ -357,6 +422,7 @@ export class Canvas {
357
422
  if (this.openLink(event)) return
358
423
  if (this.free.swallowClick()) return
359
424
  const hit = this.hit(event.target)
425
+ this.anchorAt(hit)
360
426
  if (hit?.placeholder) {
361
427
  const rect = this.toParentRect(hit.element.getBoundingClientRect())
362
428
  this.editor.select(hit.id)
@@ -382,6 +448,7 @@ export class Canvas {
382
448
 
383
449
  onDoubleClick(event) {
384
450
  const hit = this.hit(event.target)
451
+ this.anchorAt(hit)
385
452
  const part = hit && !hit.placeholder && this.partAt(event.target, hit.id)
386
453
  if (part) this.editor.startEditing(hit.id, part)
387
454
  }
@@ -17,10 +17,11 @@
17
17
  import { t } from "tess_edit/core/i18n"
18
18
  import { imageSource } from "tess_edit/core/media"
19
19
  import { fieldType, getBlock, label } from "tess_edit/core/registry"
20
- import { fontOptions } from "tess_edit/blocks/fields"
20
+ import { ALIGN, fontOptions } from "tess_edit/blocks/fields"
21
21
  import { find, getValue } from "tess_edit/core/document"
22
22
  import { translationCalls } from "tess_edit/core/translations"
23
23
  import { loopScope } from "tess_edit/core/variables"
24
+ import { CELL, ROW, TABLE, addColumn, addRow, cellOf, columnCount, deleteColumn, deleteRow, position, rows, setColumn } from "tess_edit/core/table"
24
25
  import { codeInput } from "tess_edit/ui/code_input"
25
26
  import { FontPicker } from "tess_edit/ui/font_picker"
26
27
  import { freeze, h, place } from "tess_edit/ui/dom"
@@ -105,6 +106,9 @@ export class Inspector {
105
106
 
106
107
  // A group shows when one of its fields applies (see shows below)
107
108
  const groups = (definition.fields || []).filter((group) => group.fields.some((field) => this.shows(node, field))).map((group) => this.group(node, group))
109
+ // A block in a table's cell, such as its Text, has the cell's table first
110
+ const cell = ![CELL, ROW, TABLE].includes(node.type) && cellOf(doc, node.id)
111
+ if (cell) groups.unshift(this.groupElement("table_cell:Table", { title: "Table" }, this.openGroups.get("table_cell:Table") ?? true, h("div", { class: "px-4 pb-4 space-y-3" }, this.table(cell))))
108
112
  const locked = this.editor.lock && node.id !== doc.id && !this.editor.isFree(node.id)
109
113
  ? h("p", { class: "mx-4 mt-3 flex items-center gap-2 rounded-md bg-amber-50 dark:bg-amber-900/30 px-3 py-2 text-xs text-amber-800 dark:text-amber-200" }, h("span", { html: icon("lock", "w-3.5 h-3.5") }), t("Part of the layout"))
110
114
  : null
@@ -283,6 +287,9 @@ export class Inspector {
283
287
  case "list":
284
288
  return this.list(node, field, Array.isArray(value) ? value : [], set)
285
289
 
290
+ case "table":
291
+ return this.table(node)
292
+
286
293
  case "image":
287
294
  return this.image(node, field, value, set)
288
295
 
@@ -534,6 +541,62 @@ export class Inspector {
534
541
  return h("span", { class: "grid grid-cols-4 gap-1" }, inputs)
535
542
  }
536
543
 
544
+ // A Cell's table (a Row's, through its first cell): the cell's column's
545
+ // width and alignment, and adding and deleting rows and columns
546
+ // (core/table.js), each one undo step, selecting the cell it gives
547
+ table(node) {
548
+ const cellId = node.type === CELL ? node.id : node.children?.find((child) => child.type === CELL)?.id
549
+ const at = cellId && position(this.editor.doc, cellId)
550
+ if (!at) return h("p", { class: "text-xs text-gray-500 dark:text-gray-400" }, t("Not in a table"))
551
+
552
+ const change = (mutate) => {
553
+ let next = null
554
+ this.editor.commit((doc) => (next = mutate(doc, cellId)))
555
+ if (next) this.editor.select(next.id)
556
+ }
557
+ const button = (label, mutate, disabled = false) =>
558
+ h("button", { type: "button", class: "flex-1 rounded-md border border-gray-300 dark:border-gray-600 px-2 py-1 text-xs text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40", disabled, onclick: () => change(mutate) }, t(label))
559
+ const line = (title, ...buttons) => h("div", { class: "space-y-1" }, h("span", { class: "block text-xs font-medium text-gray-700 dark:text-gray-300" }, t(title)), h("div", { class: "flex gap-1" }, ...buttons))
560
+ const rowCount = rows(at.table).length
561
+ const parts = [
562
+ line("Row", button("Add above", (doc, id) => addRow(doc, id, "above")), button("Add below", (doc, id) => addRow(doc, id, "below")), button("Delete", deleteRow, rowCount < 2))
563
+ ]
564
+ if (node.type === CELL) {
565
+ const column = at.table.data?.columns?.[at.column] || {}
566
+ const setting = (key, value) => this.editor.commit((doc) => setColumn(doc, cellId, key, value), { coalesce: `${at.table.id}:column:${at.column}:${key}`, skipInspector: key === "width" })
567
+ parts.push(
568
+ line("Column", button("Add left", (doc, id) => addColumn(doc, id, "left")), button("Add right", (doc, id) => addColumn(doc, id, "right")), button("Delete", deleteColumn, columnCount(at.table) < 2)),
569
+ h(
570
+ "label",
571
+ { class: "block" },
572
+ h("span", { class: "mb-1 block text-xs font-medium text-gray-700 dark:text-gray-300" }, t("Column width")),
573
+ h("input", { type: "text", class: INPUT, value: column.width || "", placeholder: t("Auto"), oninput: (event) => setting("width", event.target.value) })
574
+ ),
575
+ h(
576
+ "div",
577
+ { class: "block" },
578
+ h("span", { class: "mb-1 block text-xs font-medium text-gray-700 dark:text-gray-300" }, t("Column align")),
579
+ h(
580
+ "div",
581
+ { class: "flex rounded-md border border-gray-300 dark:border-gray-600 overflow-hidden" },
582
+ ALIGN.map((option) =>
583
+ h(
584
+ "button",
585
+ {
586
+ type: "button",
587
+ class: `flex-1 px-2 py-1 text-xs border-l first:border-l-0 border-gray-300 dark:border-gray-600 ${column.align === option.value ? "bg-blue-600 text-white" : "bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600"}`,
588
+ onclick: () => setting("align", column.align === option.value ? "" : option.value)
589
+ },
590
+ t(option.label)
591
+ )
592
+ )
593
+ )
594
+ )
595
+ )
596
+ }
597
+ return h("div", { class: "space-y-3" }, ...parts)
598
+ }
599
+
537
600
  list(node, field, items, set) {
538
601
  const update = (next) => {
539
602
  set(next, { coalesce: false })
@@ -4,7 +4,9 @@
4
4
  // suggests them, and the toolbar's { } button browses them. With the host's
5
5
  // translations (`editor.translations`, core/translations.js) a t filter shows
6
6
  // its text in the editor's language until the caret goes into it, and the
7
- // toolbar turns selected text into a translation.
7
+ // toolbar turns selected text into a translation. With the host's values
8
+ // (`editor.values`, core/values.js) other Liquid output shows its value the
9
+ // same way.
8
10
  //
9
11
  // A plain part (a block's inline part with plain: true, see core/registry.js)
10
12
  // is one line of text, edited on its element itself, with no toolbar or
@@ -13,6 +15,7 @@
13
15
  import { Color, Decoration, DecorationSet, Editor, Extension, Plugin, PluginKey, StarterKit, TextAlign, TextStyle } from "tess_edit/vendor/tiptap"
14
16
  import { t } from "tess_edit/core/i18n"
15
17
  import { missingArguments, translationCalls } from "tess_edit/core/translations"
18
+ import { valueCalls } from "tess_edit/core/values"
16
19
  import { showText } from "tess_edit/ui/canvas"
17
20
  import { askText } from "tess_edit/ui/dialog"
18
21
  import { h } from "tess_edit/ui/dom"
@@ -21,6 +24,7 @@ import { icon } from "tess_edit/ui/icons"
21
24
  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"
22
25
  const ACTIVE = "bg-blue-50 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300"
23
26
  const TRANSLATIONS = new PluginKey("tessTranslations")
27
+ const VALUES = new PluginKey("tessValues")
24
28
 
25
29
  export class TextEditing {
26
30
  constructor(toolbar, { menu = null, editor = null } = {}) {
@@ -93,7 +97,8 @@ export class TextEditing {
93
97
  TextStyle,
94
98
  Color,
95
99
  TextAlign.configure({ types: ["heading", "paragraph"] }),
96
- ...(this.translating ? [translationsExtension(this)] : [])
100
+ ...(this.translating ? [translationsExtension(this)] : []),
101
+ ...(this.editor?.values ? [valuesExtension(this)] : [])
97
102
  ],
98
103
  autofocus: "end",
99
104
  editorProps: { handleKeyDown: (view, event) => this.menu?.key(event) || false },
@@ -115,6 +120,11 @@ export class TextEditing {
115
120
  if (this.tiptap && this.translating) this.tiptap.view.dispatch(this.tiptap.state.tr.setMeta(TRANSLATIONS, true))
116
121
  }
117
122
 
123
+ // Again, when the values change
124
+ refreshValues() {
125
+ if (this.tiptap && this.editor?.values) this.tiptap.view.dispatch(this.tiptap.state.tr.setMeta(VALUES, true))
126
+ }
127
+
118
128
  // Keeps the selected text as a translation (see the editor's
119
129
  // makeTranslatable) and puts its t filter in its place
120
130
  async makeTranslatable() {
@@ -330,3 +340,58 @@ function translationChip(view, key, value, unfilled, edit) {
330
340
  })
331
341
  return chip
332
342
  }
343
+
344
+ // Shows each output tag's value in place of its Liquid, unless the caret or
345
+ // selection is inside it or it has none: then its Liquid shows, marked when
346
+ // it has one. A click on the value puts the caret in the Liquid.
347
+ function valuesExtension(editing) {
348
+ return Extension.create({
349
+ name: "tessValues",
350
+ addProseMirrorPlugins() {
351
+ return [new Plugin({ key: VALUES, props: { decorations: (state) => valueDecorations(state, editing) } })]
352
+ }
353
+ })
354
+ }
355
+
356
+ function valueDecorations(state, editing) {
357
+ const values = editing.editor.values
358
+ if (!values?.enabled) return DecorationSet.empty
359
+ const { from, to } = state.selection
360
+ const decorations = []
361
+ state.doc.descendants((node, pos) => {
362
+ if (!node.isTextblock) return true
363
+ // Every character and inline node takes one position
364
+ const text = node.textBetween(0, node.content.size, undefined, "\ufffc")
365
+ for (const call of valueCalls(text)) {
366
+ const value = values.value(call.expression)
367
+ const start = pos + 1 + call.start
368
+ const end = pos + 1 + call.end
369
+ // Empty for now: its Liquid, in red
370
+ if (value === null && values.empty(call.expression)) decorations.push(Decoration.inline(start, end, { class: "tess-v-empty" }))
371
+ if (value === null) continue
372
+ if (from < end && to > start) {
373
+ decorations.push(Decoration.inline(start, end, { class: "tess-v-raw" }))
374
+ } else {
375
+ decorations.push(Decoration.inline(start, end, { class: "tess-v-hidden" }))
376
+ // In the expression, after its first word
377
+ const caret = start + call.text.indexOf(call.expression) + Math.max(1, call.expression.search(/[\s|]|$/))
378
+ decorations.push(Decoration.widget(start, (view) => valueChip(view, call, value, () => editing.tiptap?.chain().focus().setTextSelection(caret).run()), { side: -1, key: `v:${call.expression}:${value}`, ignoreSelection: true }))
379
+ }
380
+ }
381
+ return false
382
+ })
383
+ return DecorationSet.create(state.doc, decorations)
384
+ }
385
+
386
+ function valueChip(view, call, value, edit) {
387
+ const chip = view.dom.ownerDocument.createElement("span")
388
+ chip.className = "tess-v tess-v-filled"
389
+ chip.contentEditable = "false"
390
+ chip.title = call.text
391
+ chip.textContent = value
392
+ chip.addEventListener("mousedown", (event) => {
393
+ event.preventDefault()
394
+ edit()
395
+ })
396
+ return chip
397
+ }