tess_edit 0.5.9 → 0.5.11

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,262 @@
1
+ // Tables (blocks/table.js): a Table holds Rows, a Row holds Cells, a Cell
2
+ // holds content. Between a Table and its Rows there can be Loops and
3
+ // Conditions (and Assigns), which take rows there: a Loop around a Row
4
+ // prints it for each item. So a table's rows are its Rows wherever they are
5
+ // under it, in order (rows).
6
+ //
7
+ // Its columns are the Table's data.columns, each { width, align }; a Cell
8
+ // spanning columns has data.colspan. Adding or deleting a column does it in
9
+ // every Row, inside Loops and Conditions too, and in data.columns.
10
+ //
11
+ // Like core/document.js these change the document they're given in place;
12
+ // the editor calls them in a commit (ui/inspector.js, the Cell's Table
13
+ // field), and selects the cell they return.
14
+
15
+ import { createNode, find, insert, remove, walk } from "tess_edit/core/document"
16
+
17
+ export const TABLE = "table"
18
+ export const ROW = "table_row"
19
+ export const CELL = "table_cell"
20
+
21
+ const EMPTY_TEXT = { type: "doc", content: [{ type: "paragraph" }] }
22
+
23
+ // A Cell with an empty Text, which has the table's padding
24
+ export function newCell(text = null) {
25
+ const content = text ? { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text }] }] } : EMPTY_TEXT
26
+ return createNode(CELL, { children: [createNode("text", { attributes: { padding: "0px" }, data: { content } })] })
27
+ }
28
+
29
+ export function newRow(count, { heading = false, texts = [] } = {}) {
30
+ return createNode(ROW, { data: heading ? { heading: "heading" } : {}, children: Array.from({ length: count }, (_, i) => newCell(texts[i] || null)) })
31
+ }
32
+
33
+ // A table of `columns` columns and `rows` rows, the first a heading row
34
+ export function newTable(columns = 3, rows = 3, { headings = [] } = {}) {
35
+ return createNode(TABLE, {
36
+ data: { columns: Array.from({ length: columns }, () => ({ width: "", align: "" })) },
37
+ children: Array.from({ length: rows }, (_, i) => newRow(columns, i === 0 ? { heading: true, texts: headings } : {}))
38
+ })
39
+ }
40
+
41
+ // The Table a block is in, or is
42
+ export function tableOf(doc, id) {
43
+ let table = null
44
+ let found = false
45
+ const visit = (node, tables) => {
46
+ if (found) return
47
+ const inside = node.type === TABLE ? [...tables, node] : tables
48
+ if (node.id === id) {
49
+ table = inside.at(-1) || null
50
+ found = true
51
+ return
52
+ }
53
+ for (const child of node.children || []) visit(child, inside)
54
+ }
55
+ visit(doc, [])
56
+ return table
57
+ }
58
+
59
+ // The Table's Rows in order, also those in its Loops and Conditions, not
60
+ // those of a table in a cell
61
+ export function rows(table) {
62
+ const found = []
63
+ const visit = (node) => {
64
+ for (const child of node.children || []) {
65
+ if (child.type === ROW) found.push(child)
66
+ else if (child.type !== TABLE && child.type !== CELL) visit(child)
67
+ }
68
+ }
69
+ visit(table)
70
+ return found
71
+ }
72
+
73
+ export function span(cell) {
74
+ const value = parseInt(cell?.data?.colspan, 10)
75
+ return value > 1 ? value : 1
76
+ }
77
+
78
+ export function columnCount(table) {
79
+ const widest = Math.max(0, ...rows(table).map((row) => row.children.reduce((sum, cell) => sum + span(cell), 0)))
80
+ return Math.max(table.data?.columns?.length || 0, widest)
81
+ }
82
+
83
+ // The columns a Row's cells start at: [{ cell, index, start }]
84
+ function starts(row) {
85
+ let start = 0
86
+ return row.children.map((cell, index) => {
87
+ const entry = { cell, index, start }
88
+ start += span(cell)
89
+ return entry
90
+ })
91
+ }
92
+
93
+ // Where a Cell is: its table, row, the column it starts at
94
+ export function position(doc, cellId) {
95
+ const hit = find(doc, cellId)
96
+ if (!hit || hit.node.type !== CELL || hit.parent?.type !== ROW) return null
97
+ const table = tableOf(doc, cellId)
98
+ if (!table) return null
99
+ const row = hit.parent
100
+ const { start } = starts(row)[hit.index]
101
+ return { table, row, cell: hit.node, column: start }
102
+ }
103
+
104
+ // The cell in `row` that covers `column`, or the last one when the row is short
105
+ function covering(row, column) {
106
+ const entries = starts(row)
107
+ return entries.find(({ cell, start }) => start <= column && column < start + span(cell)) || entries.at(-1) || null
108
+ }
109
+
110
+ function columns(table) {
111
+ table.data ||= {}
112
+ const count = columnCount(table)
113
+ const list = Array.isArray(table.data.columns) ? table.data.columns : []
114
+ table.data.columns = Array.from({ length: count }, (_, i) => list[i] || { width: "", align: "" })
115
+ return table.data.columns
116
+ }
117
+
118
+ // Adds a row above or below the cell's, of as many cells as there are
119
+ // columns; returns its cell in the same column
120
+ export function addRow(doc, cellId, where = "below") {
121
+ const at = position(doc, cellId)
122
+ if (!at) return null
123
+ const hit = find(doc, at.row.id)
124
+ const row = newRow(columnCount(at.table))
125
+ insert(doc, hit.parent.id, hit.index + (where === "above" ? 0 : 1), row)
126
+ return covering(row, at.column)?.cell || null
127
+ }
128
+
129
+ // Adds a column left or right of the cell's, in every row; a cell spanning
130
+ // the place gets wider instead. Returns the new cell in the cell's row.
131
+ export function addColumn(doc, cellId, where = "right") {
132
+ const at = position(doc, cellId)
133
+ if (!at) return null
134
+ const column = where === "left" ? at.column : at.column + span(at.cell)
135
+ // Its columns as they are, before the rows have one more
136
+ const list = columns(at.table)
137
+ let added = null
138
+ for (const row of rows(at.table)) {
139
+ const entries = starts(row)
140
+ const across = entries.find(({ cell, start }) => start < column && column < start + span(cell))
141
+ if (across) {
142
+ across.cell.data.colspan = String(span(across.cell) + 1)
143
+ continue
144
+ }
145
+ const before = entries.find(({ start }) => start >= column)
146
+ const cell = newCell()
147
+ row.children.splice(before ? before.index : row.children.length, 0, cell)
148
+ if (row === at.row) added = cell
149
+ }
150
+ list.splice(column, 0, { width: "", align: "" })
151
+ return added
152
+ }
153
+
154
+ // Deletes the cell's row; returns the cell to select next, in the row after
155
+ // it or else before it, or null when it was the table's last row
156
+ export function deleteRow(doc, cellId) {
157
+ const at = position(doc, cellId)
158
+ if (!at) return null
159
+ const all = rows(at.table)
160
+ if (all.length < 2) return null
161
+ const index = all.indexOf(at.row)
162
+ const next = all[index + 1] || all[index - 1]
163
+ remove(doc, at.row.id)
164
+ return covering(next, at.column)?.cell || null
165
+ }
166
+
167
+ // Deletes the cell's column in every row: a cell spanning it gets narrower.
168
+ // Returns the cell to select next, or null when it was the last column.
169
+ export function deleteColumn(doc, cellId) {
170
+ const at = position(doc, cellId)
171
+ if (!at || columnCount(at.table) < 2) return null
172
+ const column = at.column
173
+ const list = columns(at.table)
174
+ for (const row of rows(at.table)) {
175
+ const target = covering(row, column)
176
+ if (!target || target.start + span(target.cell) <= column) continue
177
+ if (span(target.cell) > 1) target.cell.data.colspan = span(target.cell) === 2 ? "" : String(span(target.cell) - 1)
178
+ else row.children.splice(target.index, 1)
179
+ }
180
+ list.splice(column, 1)
181
+ return covering(at.row, Math.min(column, columnCount(at.table) - 1))?.cell || null
182
+ }
183
+
184
+ // The cell after (or before) this one, row by row
185
+ export function nextCell(doc, cellId, { backwards = false } = {}) {
186
+ const table = tableOf(doc, cellId)
187
+ if (!table) return null
188
+ const cells = rows(table).flatMap((row) => row.children)
189
+ const index = cells.findIndex((cell) => cell.id === cellId)
190
+ if (index < 0) return null
191
+ return cells[index + (backwards ? -1 : 1)] || null
192
+ }
193
+
194
+ // The cell a block is in, if any: the nearest Cell around it
195
+ export function cellOf(doc, id) {
196
+ let cell = null
197
+ let found = false
198
+ const visit = (node, cells) => {
199
+ if (found) return
200
+ const inside = node.type === CELL ? [...cells, node] : cells
201
+ if (node.id === id) {
202
+ cell = inside.at(-1) || null
203
+ found = true
204
+ return
205
+ }
206
+ for (const child of node.children || []) visit(child, inside)
207
+ }
208
+ visit(doc, [])
209
+ return cell
210
+ }
211
+
212
+ // Whether a document has a table, for a kit that wants to know
213
+ export function hasTable(doc) {
214
+ let found = false
215
+ walk(doc, (node) => {
216
+ if (found) return false
217
+ if (node.type === TABLE) found = true
218
+ })
219
+ return found
220
+ }
221
+
222
+ // Sets the width or align of the cell's column
223
+ export function setColumn(doc, cellId, key, value) {
224
+ const at = position(doc, cellId)
225
+ if (!at) return
226
+ setColumnAt(doc, at.table.id, at.column, key, value)
227
+ }
228
+
229
+ // Sets the width or align of a table's column by its index, as dragging its
230
+ // border on the canvas does
231
+ export function setColumnAt(doc, tableId, column, key, value) {
232
+ const table = find(doc, tableId)?.node
233
+ if (table?.type !== TABLE) return
234
+ const list = columns(table)
235
+ if (column < 0 || column >= list.length) return
236
+ list[column] = { ...list[column], [key]: value }
237
+ }
238
+
239
+ // Wraps the cell's row in a new Loop or Condition (`type`), in the row's
240
+ // place; returns it
241
+ export function wrapRow(doc, cellId, type) {
242
+ const at = position(doc, cellId)
243
+ if (!at) return null
244
+ const hit = find(doc, at.row.id)
245
+ remove(doc, at.row.id)
246
+ return insert(doc, hit.parent.id, hit.index, createNode(type, { children: [at.row] }))
247
+ }
248
+
249
+ // The Loops and Conditions among a table's rows, each with the rows it holds,
250
+ // for the canvas to mark them: [{ node, depth }], outer ones first
251
+ export function rowGroups(table) {
252
+ const found = []
253
+ const visit = (node, depth) => {
254
+ for (const child of node.children || []) {
255
+ if (child.type === ROW || child.type === TABLE || child.type === CELL) continue
256
+ if (rows(child).length) found.push({ node: child, depth })
257
+ visit(child, depth + 1)
258
+ }
259
+ }
260
+ visit(table, 0)
261
+ return found
262
+ }
@@ -11,6 +11,9 @@
11
11
  // with the kit's canvas result ({ html, errors, values }), for a canvas the
12
12
  // host renders, or with the editor's setValues(values). An expression without
13
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.
14
17
 
15
18
  import { translationCalls } from "tess_edit/core/translations"
16
19
 
@@ -50,11 +53,12 @@ export function expressionsIn(value, expressions = new Set()) {
50
53
  export class Values {
51
54
  constructor() {
52
55
  this.entries = new Map()
56
+ this.empties = new Set()
53
57
  this.listeners = new Set()
54
58
  }
55
59
 
56
60
  get enabled() {
57
- return this.entries.size > 0
61
+ return this.entries.size > 0 || this.empties.size > 0
58
62
  }
59
63
 
60
64
  // Calls fn whenever they change
@@ -63,19 +67,30 @@ export class Values {
63
67
  return () => this.listeners.delete(fn)
64
68
  }
65
69
 
66
- // Replaces them all; false when nothing changed. Empty values are none.
70
+ // Replaces them all; false when nothing changed. An empty string is an
71
+ // empty value (empty), null none.
67
72
  set(values) {
68
73
  const entries = new Map()
74
+ const empties = new Set()
69
75
  for (const [expression, value] of Object.entries(values || {})) {
70
- if (value === null || value === undefined || value === "") continue
71
- entries.set(normalizeExpression(expression), String(value))
76
+ if (value === null || value === undefined) continue
77
+ if (value === "") empties.add(normalizeExpression(expression))
78
+ else entries.set(normalizeExpression(expression), String(value))
72
79
  }
73
- if (entries.size === this.entries.size && [...entries].every(([key, value]) => this.entries.get(key) === value)) return false
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
74
83
  this.entries = entries
84
+ this.empties = empties
75
85
  this.listeners.forEach((fn) => fn())
76
86
  return true
77
87
  }
78
88
 
89
+ // Whether the host says it's empty for now
90
+ empty(expression) {
91
+ return this.empties.has(normalizeExpression(expression))
92
+ }
93
+
79
94
  // Its text, or null when there's none
80
95
  value(expression) {
81
96
  return this.entries.get(normalizeExpression(expression)) ?? null
@@ -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)