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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f5e9015e98be0b0280dc53ce49d3528de50af68e9479328d206048f81546674b
4
- data.tar.gz: abadfcc22502656a619a4d9a87d5cff62f03c4213a5c8edcdc9c6bd0948937e6
3
+ metadata.gz: 2f6042f88897f04e6d501d19ca8401a2ea70148a4414538a496b8162f328d49f
4
+ data.tar.gz: cb820e8b65766ec830db06e612fa9bb5bbf686f95319bfe0c7e5a9bcf6b2437f
5
5
  SHA512:
6
- metadata.gz: '08087b10cc444b2e3024254c6a2f033fb6195a96611bb7ed2b296416f9a43190dedbc45f96d2421db2cc8868d5f4cbbf66f2eee8f3e3978d9499e5425b4d70b3'
7
- data.tar.gz: 451ae59588c137dc70c0ee87986ab24e48cf9a2a8f0aa00ca6e22454e5733bda927d4d65d20f79cc9c1574864eb6a81a7d316dc44d68f9673c84ee1b6ad1e700
6
+ metadata.gz: 2319bc7fb805278335b0a2cdfb7746b90ad69fef7cb61f339b4363655b5c7a9ed5e8dc7ba23460f53ad6ab55f6cede811b1b40e3096f8cf3d9f110cc2338af35
7
+ data.tar.gz: be46f4863517eba03f9b28387ed0799ffd30b3f6909fd727cdf3d7322930a08dafc7fae3c091f21a979621e1c5233bcea787c2791b4f51954103077366c04d89
data/README.md CHANGED
@@ -19,6 +19,7 @@ It completes Liquid tags and variables as you type, making it easier to work wit
19
19
  - 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. A block can have several texts edited on the canvas, rich or a plain line, such as a question's label and its description.
20
20
  - 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.
21
21
  - 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.
22
+ - Your app's values for the Liquid in a document (`{{ customer.first_name }}` as "Ada"), shown in its place until the caret goes into it.
22
23
  - Clicking a tile in the Blocks panel adds the block in or after the selection, or else at the end of the last block it fits in.
23
24
  - Undo/redo, duplicate, delete, keyboard shortcuts (⌘Z, ⇧⌘Z, ⌘D, Delete, Enter to edit text, Esc).
24
25
  - Desktop and mobile preview, and a preview of the HTML as sent.
@@ -279,6 +280,19 @@ The endpoint answers, as JSON:
279
280
 
280
281
  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`).
281
282
 
283
+ ### Values
284
+
285
+ When the editor is for a record, such as an order's confirmation or a contract's text, your app can show what its Liquid comes to: give the values by expression, as it's written between the braces, filters and all, with its whitespace as one space:
286
+
287
+ ```erb
288
+ <div data-controller="tess-edit" data-tess-edit-values-value='<%= {"customer.first_name" => "Ada", "order.total | money" => "€ 12,50"}.to_json %>'>
289
+ ```
290
+
291
+ - The canvas shows each output tag with a value as that value, marked, with its Liquid when pointed at. One without a value, or with an empty one, shows its Liquid; `t` filters are translations.
292
+ - In text being edited on the canvas a value shows until the caret goes into its Liquid; a click on it does that.
293
+
294
+ A kit whose canvas your app renders can give them with the canvas, `{ html, errors, values }`, as they depend on the record as it's being edited, and `editor.setValues(values)` (on the element's `tessEdit`) sets them from anywhere; each replaces them all. `core/values.js` finds the expressions in a document (`expressionsIn`), to ask for theirs. The demo has some at `/?values=1`.
295
+
282
296
  ### Blocks and custom blocks
283
297
 
284
298
  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:
@@ -415,7 +429,7 @@ cd test/dummy && bin/dev
415
429
 
416
430
  `/?blocks=text,image` only offers those blocks.
417
431
 
418
- `/?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`.
432
+ `/?values=1` gives it values for the sample's customer and order. `/?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`.
419
433
 
420
434
  Tests:
421
435
 
@@ -0,0 +1,33 @@
1
+ // {% assign variable = expression %}: a Liquid variable for the blocks after
2
+ // it, such as a collection filtered before a Loop goes over it (Liquid's for
3
+ // and if take no filters):
4
+ //
5
+ // {% assign lines = contract.lines | where: "party", "account" %}
6
+ //
7
+ // It shows nothing; in the editor, Layers shows it. In a table it goes
8
+ // between rows.
9
+
10
+ const assignTag = (node) => `{% assign ${node.data.variable || "value"} = ${node.data.expression || "nil"} %}`
11
+
12
+ export default {
13
+ type: "assign",
14
+ name: "Assign",
15
+ icon: '<path d="M5 9h6M5 15h6"/><path d="M14 7l5 5-5 5"/>',
16
+ category: "liquid",
17
+ roles: ["body", "content", "row"],
18
+ defaults: () => ({ data: { variable: "items", expression: "" } }),
19
+ fields: [
20
+ {
21
+ title: "Assign",
22
+ fields: [
23
+ { key: "data.variable", label: "Variable", type: "text", hint: "The name the blocks after it use, e.g. lines." },
24
+ { key: "data.expression", label: "Value", type: "text", liquid: "expression", hint: "A Liquid expression, with filters, e.g. order.lines | where: \"kind\", \"product\"." }
25
+ ]
26
+ }
27
+ ],
28
+ hint: "Sets a Liquid variable for the blocks after it: {% assign variable = value %}.",
29
+ label: (node) => `${node.data.variable || "…"} = ${node.data.expression || "…"}`,
30
+ render: {
31
+ mjml: (node, { editor }) => (editor ? "" : `<mj-raw>${assignTag(node)}</mj-raw>`)
32
+ }
33
+ }
@@ -17,6 +17,8 @@ import navbar from "tess_edit/blocks/navbar"
17
17
  import raw from "tess_edit/blocks/raw"
18
18
  import loop from "tess_edit/blocks/loop"
19
19
  import condition from "tess_edit/blocks/condition"
20
+ import assign from "tess_edit/blocks/assign"
21
+ import { table, tableCell, tableRow } from "tess_edit/blocks/table"
20
22
 
21
23
  export const builtinCategories = [
22
24
  { key: "layout", label: "Layout", order: 10 },
@@ -24,4 +26,4 @@ export const builtinCategories = [
24
26
  { key: "liquid", label: "Liquid", order: 30 }
25
27
  ]
26
28
 
27
- export const builtinBlocks = [email, section, column, wrapper, hero, content, text, image, button, divider, spacer, social, navbar, raw, loop, condition]
29
+ export const builtinBlocks = [email, section, column, wrapper, hero, content, text, image, button, divider, spacer, social, navbar, raw, loop, condition, assign, table, tableRow, tableCell]
@@ -5,7 +5,8 @@ export default {
5
5
  name: "Condition",
6
6
  icon: "condition",
7
7
  category: "liquid",
8
- roles: ["body", "content"],
8
+ // "row": between a table's rows (blocks/table.js)
9
+ roles: ["body", "content", "row"],
9
10
  accepts: "inherit",
10
11
  defaults: () => ({ data: { expression: "customer.vip" } }),
11
12
  fields: [{ title: "Condition", fields: [{ key: "data.expression", label: "Show when", type: "text", liquid: "expression", hint: "A Liquid condition, e.g. order.total > 100." }] }],
@@ -5,7 +5,8 @@ export default {
5
5
  name: "Loop",
6
6
  icon: "loop",
7
7
  category: "liquid",
8
- roles: ["body", "content"],
8
+ // "row": between a table's rows (blocks/table.js)
9
+ roles: ["body", "content", "row"],
9
10
  accepts: "inherit",
10
11
  defaults: () => ({ data: { variable: "item", collection: "items" } }),
11
12
  fields: [
@@ -0,0 +1,112 @@
1
+ // A table: Table › Row › Cell › content, as Section › Column › content, so
2
+ // a cell holds any block (Text, Image, …). Rows can be in a Loop or a
3
+ // Condition in the table, which take rows there ("inherit"): a Loop around a
4
+ // Row prints it for each item, with the item's values in its cells.
5
+ //
6
+ // The table's columns are data.columns ({ width, align } each), set from a
7
+ // selected cell, whose Table group also adds and deletes rows and columns
8
+ // (core/table.js, the "table" field in ui/inspector.js).
9
+ //
10
+ // In an email the table is an mj-table, which MJML copies as it is, so its
11
+ // cells' blocks are HTML (export/table.js), not MJML. Another kit takes them
12
+ // in with extendBlock and its own render hook, as a host's PDF kit does.
13
+
14
+ import { ALIGN, VERTICAL_ALIGN, background, padding } from "tess_edit/blocks/fields"
15
+ import { plainText } from "tess_edit/blocks/text"
16
+ import { newTable } from "tess_edit/core/table"
17
+ import { tableHtml } from "tess_edit/export/table"
18
+
19
+ const tableActions = { key: "data", label: "", type: "table" }
20
+
21
+ export const table = {
22
+ type: "table",
23
+ name: "Table",
24
+ icon: '<rect x="3" y="5" width="18" height="14" rx="1"/><path d="M3 10h18M3 15h18M9 10v9M15 10v9"/>',
25
+ category: "layout",
26
+ // Content, as Text is: in an email inside a column, as an mj-table must be
27
+ roles: ["content"],
28
+ accepts: ["row"],
29
+ defaults: () => ({ attributes: { padding: "10px 25px" }, data: { columns: [], borderColor: "#d1d5db", borderWidth: "1px", cellPadding: "6px 8px", headingBackground: "#f3f4f6" } }),
30
+ palette: [{ key: "table", label: "Table", category: "layout", create: () => newTable(3, 3, { headings: ["Heading", "Heading", "Heading"] }) }],
31
+ fields: [
32
+ {
33
+ title: "Table",
34
+ fields: [
35
+ { key: "attributes.width", label: "Width", type: "size", placeholder: "100%" },
36
+ { key: "data.borders", label: "Lines", type: "segmented", options: [{ value: "", label: "All" }, { value: "rows", label: "Between rows" }], hint: "Lines around every cell, or only under each row." },
37
+ { key: "data.borderColor", label: "Border color", type: "color" },
38
+ { key: "data.borderWidth", label: "Border width", type: "size", placeholder: "1px", hint: "0 for no borders." },
39
+ { key: "data.cellPadding", label: "Cell padding", type: "spacing" },
40
+ { key: "data.stripe", label: "Every other row", type: "color", hint: "A background for every other row, from the second." },
41
+ padding
42
+ ]
43
+ },
44
+ {
45
+ title: "Heading rows",
46
+ fields: [
47
+ { key: "data.headingBackground", label: "Background", type: "color" },
48
+ { key: "data.headingColor", label: "Text color", type: "color" },
49
+ { key: "data.headingWeight", label: "Font weight", type: "select", options: ["", "400", "500", "600", "700"] }
50
+ ]
51
+ }
52
+ ],
53
+ hint: "Rows of cells. Select a cell to add rows and columns. Put rows in a Loop to repeat them for each item.",
54
+ render: {
55
+ mjml: (node, ctx) => ctx.element("mj-table", node, tableHtml(node, ctx))
56
+ }
57
+ }
58
+
59
+ export const tableRow = {
60
+ type: "table_row",
61
+ name: "Row",
62
+ icon: '<rect x="3" y="9" width="18" height="6" rx="1"/><path d="M9 9v6M15 9v6"/>',
63
+ roles: ["row"],
64
+ accepts: ["cell"],
65
+ horizontal: true,
66
+ palette: [],
67
+ defaults: () => ({ attributes: {}, data: {} }),
68
+ fields: [
69
+ { title: "Table", fields: [tableActions] },
70
+ {
71
+ title: "Row",
72
+ fields: [
73
+ { key: "data.heading", label: "Heading row", type: "toggle", on: "heading", off: "", hint: "In the heading rows' style. Heading rows at the top repeat on every page." },
74
+ background,
75
+ { key: "data.lineAbove", label: "Line above", type: "size", hint: "A heavier line above the row, e.g. 3pt above a total." }
76
+ ]
77
+ }
78
+ ],
79
+ label: (node) => (node.data.heading ? "Heading row" : "Row"),
80
+ // In its table's (export/table.js)
81
+ render: { mjml: () => "" }
82
+ }
83
+
84
+ export const tableCell = {
85
+ type: "table_cell",
86
+ name: "Cell",
87
+ icon: '<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M8 10h8M8 14h5"/>',
88
+ roles: ["cell"],
89
+ accepts: ["content"],
90
+ palette: [],
91
+ defaults: () => ({ attributes: {}, data: {} }),
92
+ fields: [
93
+ { title: "Table", fields: [tableActions] },
94
+ {
95
+ title: "Cell",
96
+ fields: [
97
+ { key: "attributes.text-align", label: "Align", type: "segmented", options: ALIGN },
98
+ { key: "attributes.vertical-align", label: "Vertical align", type: "segmented", options: VERTICAL_ALIGN },
99
+ background,
100
+ { key: "attributes.color", label: "Text color", type: "color" },
101
+ { ...padding, hint: "Instead of the table's cell padding." },
102
+ { key: "data.colspan", label: "Spans columns", type: "text", placeholder: "1", hint: "How many columns the cell takes, merging it with the cells to its right." }
103
+ ]
104
+ }
105
+ ],
106
+ label(node) {
107
+ const text = (node.children || []).map((child) => plainText(child.data?.content)).join(" ").trim()
108
+ return text ? `Cell · ${text.slice(0, 32)}` : "Cell"
109
+ },
110
+ // In its table's (export/table.js)
111
+ render: { mjml: () => "" }
112
+ }
@@ -32,6 +32,10 @@
32
32
  // (see core/lock.js)
33
33
  // blocks JSON: the only block types that can be added, e.g. ["text", "image"];
34
34
  // without it, all of the kit's
35
+ // values JSON: the host's values for the document's Liquid, by expression
36
+ // ({"customer.first_name": "Ada"}), shown in place of it until the
37
+ // caret goes into it (see core/values.js); also from the kit's
38
+ // canvas result, or set with setValues
35
39
  // options JSON: anything a host's blocks need from the page, as
36
40
  // editor.options, e.g. the choices of a select field
37
41
  // (options: (editor) => editor.options.parties)
@@ -56,6 +60,7 @@ import { DEFAULT_KIT, getBlock, getKit, inlinePart, inlineParts, paletteItems, p
56
60
  import { COMPILE_URL } from "tess_edit/export/compile"
57
61
  import { IMAGE_FIELD, fetchMedia, uploadMedia } from "tess_edit/core/media"
58
62
  import { Translations, keysIn, suggestKey, toTranslation, translationTag } from "tess_edit/core/translations"
63
+ import { Values } from "tess_edit/core/values"
59
64
  import { Variables, loopScope } from "tess_edit/core/variables"
60
65
  import { Canvas } from "tess_edit/ui/canvas"
61
66
  import { freeChild, number } from "tess_edit/ui/free_layout"
@@ -87,7 +92,7 @@ function placed(node, at) {
87
92
  }
88
93
 
89
94
  export default class extends Controller {
90
- static values = { kit: { type: String, default: DEFAULT_KIT }, document: String, sample: { type: Boolean, default: true }, frame: { type: Boolean, default: true }, panels: { type: String, default: "split" }, compileUrl: { type: String, default: COMPILE_URL }, mediaUrl: String, variablesUrl: String, translationsUrl: String, lock: String, blocks: String, options: String }
95
+ static values = { kit: { type: String, default: DEFAULT_KIT }, document: String, sample: { type: Boolean, default: true }, frame: { type: Boolean, default: true }, panels: { type: String, default: "split" }, compileUrl: { type: String, default: COMPILE_URL }, mediaUrl: String, variablesUrl: String, translationsUrl: String, values: String, lock: String, blocks: String, options: String }
91
96
  static targets = ["jsonInput", "mjmlInput", "htmlInput", "slot", "translations"]
92
97
 
93
98
  connect() {
@@ -120,6 +125,8 @@ export default class extends Controller {
120
125
  this.variables = new Variables(this.variablesUrlValue)
121
126
  this.translations = new Translations(this.translationsUrlValue)
122
127
  this.translationPopover = this.translations.enabled ? new TranslationPopover(this) : null
128
+ this.values = new Values()
129
+ this.values.set(this.parseJson(this.valuesValue, "values"))
123
130
  this.translationLocaleChoice = this.stored(TRANSLATION_LOCALE_KEY)
124
131
  this.variableMenu = this.variables.enabled || this.translations.enabled ? new VariableMenu(this) : null
125
132
 
@@ -139,9 +146,19 @@ export default class extends Controller {
139
146
  this.translations.subscribe(() => this.showTranslations())
140
147
  this.loadTranslations()
141
148
  }
149
+ // Values show on the canvas and in text being edited
150
+ this.values.subscribe(() => {
151
+ this.canvas.annotate()
152
+ this.textEditing.refreshValues()
153
+ })
142
154
  this.element.tessEdit = this
143
155
  }
144
156
 
157
+ // Other values from the host, once it's connected
158
+ valuesValueChanged() {
159
+ if (this.values) this.values.set(this.parseJson(this.valuesValue, "values"))
160
+ }
161
+
145
162
  // Points the editor at other variables (variablesUrl), once it's connected
146
163
  variablesUrlValueChanged() {
147
164
  if (!this.variables) return
@@ -335,6 +352,11 @@ export default class extends Controller {
335
352
  return JSON.parse(JSON.stringify(this.doc))
336
353
  }
337
354
 
355
+ // The host's values for the document's Liquid, by expression (core/values.js)
356
+ setValues(values) {
357
+ this.values.set(values)
358
+ }
359
+
338
360
  setDocument(input) {
339
361
  this.stopEditing()
340
362
  this.history.record(JSON.stringify(this.doc))
@@ -686,6 +708,8 @@ export default class extends Controller {
686
708
  if (this.editingId) return
687
709
  const result = await this.run("canvas", (options) => this.kit.canvas(this.doc, { ...options, editor: this.mode === "edit" }))
688
710
  if (!result || this.editingId) return
711
+ // A canvas the host renders can give the values it has
712
+ if (result.values) this.values.set(result.values)
689
713
  this.showErrors(result.errors)
690
714
  // Without HTML the canvas keeps the last document that rendered.
691
715
  if (result.html !== null) this.canvas.write(result.html, this.mode)
@@ -23,7 +23,8 @@
23
23
  // // editor, so the rest of the block stays as it is. A plain part
24
24
  // // is one line of text, a string; the others are Tiptap JSON
25
25
  // palette: [{ key, label, icon, category, create: ({ createNode }) => node }], // optional
26
- // kits: ["email"], // the kits it is part of, default ["email"]
26
+ // kits: ["email"], // the kits it is part of, default ["email"]; [] for none
27
+ // // yet: a kit takes it in with extendBlock, and its render hook
27
28
  // unique: true, // optional: at most one per document, like Content
28
29
  // layout: "free", // optional, on a container: its children are placed by
29
30
  // // data.x and data.y, dragged on the canvas (ui/free_layout.js)
@@ -37,7 +38,8 @@
37
38
  // })
38
39
  //
39
40
  // Roles: "body" (inside the page or a wrapper: sections, heroes), "wrapper",
40
- // "column" (inside a section) and "content" (inside a column or hero). A
41
+ // "column" (inside a section), "content" (inside a column or hero), and
42
+ // "row" (inside a table) and "cell" (inside a row), see blocks/table.js. A
41
43
  // container accepts the roles in its `accepts`; Loop and Condition use
42
44
  // "inherit" and accept what their nearest other container accepts.
43
45
  //
@@ -157,7 +159,10 @@ export function registerBlock(definition) {
157
159
  const { type, name, render } = definition || {}
158
160
  if (!type || typeof type !== "string") throw new Error("A block needs a type")
159
161
  if (!name) throw new Error(`Block ${type} needs a name`)
160
- if (!Object.values(render || {}).some((hook) => typeof hook === "function")) throw new Error(`Block ${type} needs render.mjml(node, ctx) or render.html(node, ctx)`)
162
+ // A block of no kit yet (kits: []), such as a Table, gets its render hook
163
+ // from the kit that takes it in (extendBlock)
164
+ const ownKits = definition.kits ?? [DEFAULT_KIT]
165
+ if (ownKits.length && !Object.values(render || {}).some((hook) => typeof hook === "function")) throw new Error(`Block ${type} needs render.mjml(node, ctx) or render.html(node, ctx)`)
161
166
  if (!kits().some((kit) => kit.root === type) && !(definition.roles || []).length) throw new Error(`Block ${type} needs roles, e.g. ["content"]`)
162
167
 
163
168
  const palette = (definition.palette ?? (definition.category ? [{ key: type, label: name, icon: definition.icon, category: definition.category }] : [])).map((item) => ({
@@ -190,7 +195,7 @@ function keyPattern(key) {
190
195
  }
191
196
 
192
197
  // The field types of ui/inspector.js
193
- export const FIELD_TYPES = ["text", "textarea", "code", "size", "color", "select", "font", "segmented", "toggle", "spacing", "list", "image", "slot"]
198
+ export const FIELD_TYPES = ["text", "textarea", "code", "size", "color", "select", "font", "segmented", "toggle", "spacing", "list", "image", "slot", "table"]
194
199
 
195
200
  // A field type of the host's, for what TessEdit's own can't do, such as
196
201
  // parts that depend on each other:
@@ -215,15 +220,17 @@ export function fieldType(type) {
215
220
  return fieldTypeList.get(type)
216
221
  }
217
222
 
218
- // Adds kits, render hooks and field groups to a registered block. A group
219
- // with the title of one it has adds its fields to that one; a new group goes
220
- // last, or before the group its `before` names.
221
- export function extendBlock(type, { kits = [], render = {}, fields = [] } = {}) {
223
+ // Adds kits, roles, render hooks and field groups to a registered block. A
224
+ // group with the title of one it has adds its fields to that one; a new group
225
+ // goes last, or before the group its `before` names. Roles let it go where
226
+ // another kit's blocks take it.
227
+ export function extendBlock(type, { kits = [], roles = [], render = {}, fields = [] } = {}) {
222
228
  const definition = definitions.get(type)
223
229
  if (!definition) throw new Error(`No block ${type} to extend`)
224
230
  definitions.set(type, {
225
231
  ...definition,
226
232
  kits: [...new Set([...definition.kits, ...kits])],
233
+ roles: [...new Set([...definition.roles, ...roles])],
227
234
  render: { ...definition.render, ...render },
228
235
  fields: fields.reduce(addGroup, definition.fields || [])
229
236
  })
@@ -0,0 +1,228 @@
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
+ const list = columns(at.table)
227
+ list[at.column] = { ...list[at.column], [key]: value }
228
+ }