tess_edit 0.5.10 → 0.5.12

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: 2f6042f88897f04e6d501d19ca8401a2ea70148a4414538a496b8162f328d49f
4
- data.tar.gz: cb820e8b65766ec830db06e612fa9bb5bbf686f95319bfe0c7e5a9bcf6b2437f
3
+ metadata.gz: 6fbe80bedc7281410bc4d08388da4901f5371c3282edc67ef41c8fe1efd4f858
4
+ data.tar.gz: 461eed20d4d3a0e860bdcf750162c08b0f31335e35e8d95b7d8554b656d69f6b
5
5
  SHA512:
6
- metadata.gz: 2319bc7fb805278335b0a2cdfb7746b90ad69fef7cb61f339b4363655b5c7a9ed5e8dc7ba23460f53ad6ab55f6cede811b1b40e3096f8cf3d9f110cc2338af35
7
- data.tar.gz: be46f4863517eba03f9b28387ed0799ffd30b3f6909fd727cdf3d7322930a08dafc7fae3c091f21a979621e1c5233bcea787c2791b4f51954103077366c04d89
6
+ metadata.gz: e355ee3b554123245f5a8cf76ece3a6514e1376b8bc67c9d686143fcc929b2d19e7b8e9b85d98800cda6d321e5f33ed035ee894519122a328b5836fecc9456c7
7
+ data.tar.gz: 0fbda871f654a364738555b7655166966f79d85dc0e88ed474cd3a49b459a72f2f4425f93346a4cb6ca0e4e6c4ea6d5f4cd598f91a53b908bd8b791eb29c5407
data/README.md CHANGED
@@ -15,13 +15,14 @@ It completes Liquid tags and variables as you type, making it easier to work wit
15
15
 
16
16
  - Blocks: Section (1-4 columns), Column, Wrapper, Hero, Text, Heading, Image, Button, Divider, Spacer, Social, Navbar and raw HTML.
17
17
  - Liquid blocks: **Loop** (`{% for line in order.lines %}`) and **Condition** (`{% if order.total > 100 %}`) wrap other blocks.
18
+ - **Tables**: Table, Row and Cell blocks, a cell holding any blocks, with Loops and Conditions (and Assigns) between the rows. On the canvas a cell's menu adds and deletes rows and columns and puts its row in a Loop or Condition, a column's border is dragged to set its width, Tab goes from cell to cell (adding a row after the last), and a bracket by a Loop's or Condition's rows shows what they are.
18
19
  - Drag from the Blocks panel onto the canvas or into the Layers tree; move blocks on the canvas (drag handle) or in the tree; plus buttons and empty-column placeholders open an "Add block" menu.
19
20
  - 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
- - 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
+ - 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 and the Assigns before it; after a `|` your app's filters, with a where's property and the values it can have, and after `==` the values of what's compared.
21
22
  - 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
23
  - 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.
23
24
  - 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.
24
- - Undo/redo, duplicate, delete, keyboard shortcuts (⌘Z, ⇧⌘Z, ⌘D, Delete, Enter to edit text, Esc).
25
+ - Undo/redo, duplicate, delete, keyboard shortcuts (⌘Z, ⇧⌘Z, ⌘D, Delete, Enter to edit text, Tab to the next table cell, Esc).
25
26
  - Desktop and mobile preview, and a preview of the HTML as sent.
26
27
  - Panels on both sides, or combined as tabs in one sidebar on the left or right to give the canvas more room.
27
28
  - Dark mode that follows the host app's.
@@ -252,6 +253,18 @@ The endpoint answers `GET` with the variables at `path` (the roots without one),
252
253
 
253
254
  `children` says a variable has variables of its own, at the path with its name added; a `collection` is a list of them, and its path goes into its elements (`order.order_lines.product`). The editor offers a collection's `first`, `last` and `size`, and inside a Loop block (`{% for line in order.order_lines %}`) its variable, `line`, asking for `order.order_lines.…` for it. An unknown path answers 404. [Liquidum](https://github.com/entdec/liquidum)'s `/liquidum/variables` answers this way from your drops; the dummy app's `VariablesController` is a fixed example (`/?variables=1`).
254
255
 
256
+ An Assign block before a block (in its container, or in one around it), and `{% assign %}` or an open `{% for %}` earlier in the same text, are variables there too. An Assign's variable is what its expression comes to: `{% assign lines = order.order_lines | where: "kind", "product" %}` is still order lines, through filters that keep a collection (`where`, `sort`, `reverse`, …), and `| first` makes it one of them, so `{% for line in lines %}` completes `line.` as a line.
257
+
258
+ A variable with `values` (`"values": [{"value": "shipping", "label": "Shipping"}]`) can only be those: after `line.kind == ` the editor suggests them, quoted.
259
+
260
+ With `data-tess-edit-filters-url-value` the editor also completes filters: after a `|` the filters, each with its label, and choosing one writes `| where: `, going on with its arguments: a property of the collection's items (`"kind"`) and the values it can have (`"shipping"`). The endpoint answers `GET` with:
261
+
262
+ ```json
263
+ {"filters": [{"name": "where", "label": "Those whose property has the value", "arguments": [{"name": "property", "kind": "property"}, {"name": "value", "kind": "value"}], "keeps": "collection"}]}
264
+ ```
265
+
266
+ An argument's `kind` is `property`, `value` (one the property before it can have) or anything else, where the editor suggests variables. `keeps` says what a filter on a collection leaves: the same items (`"collection"`) or one of them (`"item"`); without the endpoint Liquid's own are known. Liquidum's `/liquidum/filters` answers this way, with your app's filters as well; the dummy app's `VariablesController#filters` is an example.
267
+
255
268
  The endpoint can change while the editor is open, say when the record a template is for changes: set `data-tess-edit-variables-url-value` again and the editor asks the new one.
256
269
 
257
270
  A field of your own gets the `{ }` button with `liquid: true`, or `liquid: "expression"` (a condition) or `liquid: "collection"` (what a loop goes over) for Liquid without braces.
@@ -23,6 +23,8 @@
23
23
  // and browsed with { } buttons (see core/variables.js), e.g.
24
24
  // Liquidum's /liquidum/variables?roots=…; a host can change it,
25
25
  // e.g. when the class a template is for changes
26
+ // filtersUrl the filters a template can use, suggested after a | with their
27
+ // arguments (see core/variables.js), e.g. Liquidum's /liquidum/filters
26
28
  // translationsUrl the host's translations for Liquid's t filter ({{ '.greeting' | t }}),
27
29
  // shown in a language chosen in the top bar, listed and edited
28
30
  // while pointed at, and made from selected text (see
@@ -61,7 +63,9 @@ import { COMPILE_URL } from "tess_edit/export/compile"
61
63
  import { IMAGE_FIELD, fetchMedia, uploadMedia } from "tess_edit/core/media"
62
64
  import { Translations, keysIn, suggestKey, toTranslation, translationTag } from "tess_edit/core/translations"
63
65
  import { Values } from "tess_edit/core/values"
64
- import { Variables, loopScope } from "tess_edit/core/variables"
66
+ import { Variables } from "tess_edit/core/variables"
67
+ import { liquidScope } from "tess_edit/core/liquid"
68
+ import { addColumn, addRow, cellOf, columnCount, deleteColumn, deleteRow, nextCell, position, rows, wrapRow } from "tess_edit/core/table"
65
69
  import { Canvas } from "tess_edit/ui/canvas"
66
70
  import { freeChild, number } from "tess_edit/ui/free_layout"
67
71
  import { Tree } from "tess_edit/ui/tree"
@@ -92,7 +96,7 @@ function placed(node, at) {
92
96
  }
93
97
 
94
98
  export default class extends Controller {
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 }
99
+ 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, filtersUrl: String, translationsUrl: String, values: String, lock: String, blocks: String, options: String }
96
100
  static targets = ["jsonInput", "mjmlInput", "htmlInput", "slot", "translations"]
97
101
 
98
102
  connect() {
@@ -122,7 +126,7 @@ export default class extends Controller {
122
126
  this.sheetOpen = false
123
127
  this.requests = {}
124
128
  this.media = { enabled: Boolean(this.mediaUrlValue), images: [], uploading: false, error: null }
125
- this.variables = new Variables(this.variablesUrlValue)
129
+ this.variables = new Variables(this.variablesUrlValue, { filtersUrl: this.filtersUrlValue })
126
130
  this.translations = new Translations(this.translationsUrlValue)
127
131
  this.translationPopover = this.translations.enabled ? new TranslationPopover(this) : null
128
132
  this.values = new Values()
@@ -162,7 +166,7 @@ export default class extends Controller {
162
166
  // Points the editor at other variables (variablesUrl), once it's connected
163
167
  variablesUrlValueChanged() {
164
168
  if (!this.variables) return
165
- this.variables = new Variables(this.variablesUrlValue)
169
+ this.variables = new Variables(this.variablesUrlValue, { filtersUrl: this.filtersUrlValue })
166
170
  if (!this.variableMenu && this.variables.enabled) {
167
171
  this.variableMenu = new VariableMenu(this)
168
172
  this.textEditing.menu = this.variableMenu
@@ -837,7 +841,7 @@ export default class extends Controller {
837
841
  this.scheduleOutputs()
838
842
  }
839
843
  if (part.plain) this.textEditing.startPlain(container, getValue(hit.node, part.key), update, () => this.stopEditing())
840
- else this.textEditing.start(container, getValue(hit.node, part.key), update, { scope: loopScope(this.doc, id) })
844
+ else this.textEditing.start(container, getValue(hit.node, part.key), update, { scope: liquidScope(this.doc, id) })
841
845
  this.canvas.refresh()
842
846
  }
843
847
 
@@ -995,9 +999,43 @@ export default class extends Controller {
995
999
  }
996
1000
 
997
1001
  openInsertMenu(parentId, index, rect) {
998
- const anchor = `${parentId}:${index}`
999
- // A second click on the same plus button or placeholder closes the menu.
1000
- // Its mousedown already closed it as an outside click, so check for that.
1002
+ const allowed = this.accepted(parentId)
1003
+ const items = this.paletteItems().filter((item) => allowed.includes(item.type))
1004
+ if (!items.length) return this.closeMenu()
1005
+ this.showMenu(`${parentId}:${index}`, "insert", t("Add block"), rect,
1006
+ items.map((item) => ({ label: t(item.label), icon: icon(item.icon), action: () => this.insertAt(item.key, parentId, index) })))
1007
+ }
1008
+
1009
+ // A cell's rows and columns (core/table.js), as on the Cell in Inspect, and
1010
+ // wrapping its row in a Loop or Condition, selected to fill in
1011
+ openTableMenu(cellId, rect) {
1012
+ const at = position(this.doc, cellId)
1013
+ if (!at) return
1014
+ const rowParent = find(this.doc, at.row.id)?.parent
1015
+ const change = (mutate) => () => {
1016
+ let next = null
1017
+ this.commit((doc) => (next = mutate(doc, cellId)))
1018
+ if (next) this.select(next.id)
1019
+ }
1020
+ const entries = [
1021
+ { label: t("Add row above"), action: change((doc, id) => addRow(doc, id, "above")) },
1022
+ { label: t("Add row below"), action: change((doc, id) => addRow(doc, id, "below")) },
1023
+ { label: t("Add column left"), action: change((doc, id) => addColumn(doc, id, "left")) },
1024
+ { label: t("Add column right"), action: change((doc, id) => addColumn(doc, id, "right")) },
1025
+ { label: t("Delete row"), disabled: rows(at.table).length < 2, action: change(deleteRow) },
1026
+ { label: t("Delete column"), disabled: columnCount(at.table) < 2, action: change(deleteColumn) }
1027
+ ]
1028
+ for (const type of ["loop", "condition"]) {
1029
+ if (!rowParent || !this.allows(type) || !this.accepted(rowParent.id).includes(type)) continue
1030
+ entries.push({ label: t(type === "loop" ? "Repeat the row in a Loop" : "Show the row in a Condition"), icon: icon(type), separator: entries.every((entry) => !entry.separator), action: change((doc, id) => wrapRow(doc, id, type)) })
1031
+ }
1032
+ this.showMenu(`table:${cellId}`, "table", t("Rows and columns"), rect, entries)
1033
+ }
1034
+
1035
+ // A menu below (or above) `rect`, in the page's coordinates; a second click
1036
+ // on what opened it (`anchor`) closes it. Its mousedown already closed it
1037
+ // as an outside click, so that's checked too.
1038
+ showMenu(anchor, kind, title, rect, entries) {
1001
1039
  const closed = this.menuClosed
1002
1040
  if (this.menu?.dataset.anchor === anchor || (closed?.anchor === anchor && Date.now() - closed.at < 500)) {
1003
1041
  this.closeMenu()
@@ -1005,29 +1043,28 @@ export default class extends Controller {
1005
1043
  return
1006
1044
  }
1007
1045
  this.closeMenu()
1008
- const allowed = this.accepted(parentId)
1009
- const items = this.paletteItems().filter((item) => allowed.includes(item.type))
1010
- if (!items.length) return
1011
1046
  this.menu = h(
1012
1047
  "div",
1013
- { class: "fixed z-50 w-56 max-h-80 overflow-y-auto rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-1 shadow-lg", role: "menu", "data-anchor": anchor, "data-tess-edit-menu": "insert" },
1014
- h("div", { class: "px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400" }, t("Add block")),
1015
- items.map((item) =>
1048
+ { class: "fixed z-50 w-56 max-h-80 overflow-y-auto rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-1 shadow-lg", role: "menu", "data-anchor": anchor, "data-tess-edit-menu": kind },
1049
+ h("div", { class: "px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400" }, title),
1050
+ entries.flatMap((entry) => [
1051
+ ...(entry.separator ? [h("div", { class: "my-1 border-t border-gray-200 dark:border-gray-700" })] : []),
1016
1052
  h(
1017
1053
  "button",
1018
1054
  {
1019
1055
  type: "button",
1020
1056
  role: "menuitem",
1021
- class: "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[13px] text-gray-700 dark:text-gray-300 hover:bg-blue-50 dark:hover:bg-blue-900/40 hover:text-blue-700 dark:hover:text-blue-300",
1057
+ disabled: !!entry.disabled,
1058
+ class: "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[13px] text-gray-700 dark:text-gray-300 hover:bg-blue-50 dark:hover:bg-blue-900/40 hover:text-blue-700 dark:hover:text-blue-300 disabled:opacity-40 disabled:pointer-events-none",
1022
1059
  onclick: () => {
1023
1060
  this.closeMenu()
1024
- this.insertAt(item.key, parentId, index)
1061
+ entry.action()
1025
1062
  }
1026
1063
  },
1027
- h("span", { class: "text-gray-400 dark:text-gray-500", html: icon(item.icon) }),
1028
- t(item.label)
1064
+ ...(entry.icon ? [h("span", { class: "text-gray-400 dark:text-gray-500", html: entry.icon })] : []),
1065
+ entry.label
1029
1066
  )
1030
- )
1067
+ ])
1031
1068
  )
1032
1069
  document.body.append(this.menu)
1033
1070
  const width = 224
@@ -1062,6 +1099,13 @@ export default class extends Controller {
1062
1099
  this.closeMenu()
1063
1100
  return
1064
1101
  }
1102
+ // Tab to the next cell of a table (Shift+Tab to the one before), from the
1103
+ // text being edited in one or the block selected in one; unless the
1104
+ // variable menu took it
1105
+ if (event.key === "Tab" && !mod && !event.altKey && !event.defaultPrevented && (this.editingId || !typing) && this.tabToCell(event.shiftKey)) {
1106
+ event.preventDefault()
1107
+ return
1108
+ }
1065
1109
  if (this.editingId) {
1066
1110
  if (event.key === "Escape") {
1067
1111
  event.preventDefault()
@@ -1096,6 +1140,39 @@ export default class extends Controller {
1096
1140
  }
1097
1141
  }
1098
1142
 
1143
+ // Edits the next cell's first text, or selects the cell when it has none;
1144
+ // from the last cell it adds a row and goes to its first, once the canvas
1145
+ // has it. False when the block isn't in a table's cell, or there's no cell
1146
+ // before the first
1147
+ tabToCell(backwards) {
1148
+ const id = this.editingId || this.selectedId
1149
+ const cell = id && cellOf(this.doc, id)
1150
+ if (!cell) return false
1151
+ let next = nextCell(this.doc, cell.id, { backwards })
1152
+ const added = !next && !backwards
1153
+ if (added) {
1154
+ this.stopEditing()
1155
+ this.commit((doc) => addRow(doc, cell.id, "below") && (next = nextCell(doc, cell.id)))
1156
+ }
1157
+ if (!next) return false
1158
+ let text = null
1159
+ walk(next, (node) => {
1160
+ if (text) return false
1161
+ const part = node !== next && inlineParts(node.type)[0]
1162
+ if (part && this.canEditField(node.id, part.key)) text = node
1163
+ })
1164
+ if (!text) {
1165
+ this.select(next.id)
1166
+ } else if (added) {
1167
+ this.select(text.id)
1168
+ this.scheduleCanvas.cancel()
1169
+ this.renderCanvas().then(() => this.selectedId === text.id && this.startEditing(text.id))
1170
+ } else {
1171
+ this.startEditing(text.id)
1172
+ }
1173
+ return true
1174
+ }
1175
+
1099
1176
  // --- code dialog ----------------------------------------------------------------
1100
1177
 
1101
1178
  async openCodeDialog(tab = "json") {
@@ -0,0 +1,183 @@
1
+ // What's being written in Liquid at the caret, and what a block can use there.
2
+ //
3
+ // liquidContext reads the text before the caret and says what goes there:
4
+ //
5
+ // "{{ order.cus" → { kind: "variable", path: "order.cus" }
6
+ // "{{ order.placed_at | da" → { kind: "filter", partial: "da", input: "order.placed_at" }
7
+ // "{{ lines | where: \"pa" → { kind: "argument", filter: "where", index: 0, partial: "pa", quote: "\"" }
8
+ // "{{ lines | where: \"party\", " → { kind: "argument", filter: "where", index: 1, partial: "", args: ["party"] }
9
+ // "{% if line.party == \"sp" → { kind: "value", of: "line.party", partial: "sp", quote: "\"" }
10
+ //
11
+ // each with `start`, where what it replaces starts in the text, and `tag`
12
+ // ("{{", "{%" or null). In "output" mode (Liquid in text) only inside {{ … }}
13
+ // or {% … %}; in "expression" mode (a Loop's collection, a Condition, an
14
+ // Assign's value) anywhere. The editor's menu (ui/variable_menu.js) asks the
15
+ // host for what fits: its variables, its filters and their arguments, the
16
+ // values a variable can have (core/variables.js).
17
+ //
18
+ // liquidScope says which variables a block has besides the host's: its Loop
19
+ // blocks' and the Assigns before it, nearest first. An Assign's variable is
20
+ // what its expression comes to; through filters that keep a collection what
21
+ // it is (where, sort, …) it's still that collection (core/variables.js).
22
+
23
+ import { find } from "tess_edit/core/document"
24
+
25
+ const PATH = /[A-Za-z_][\w]*(?:\.[\w]*)*/
26
+ const NAME = /^\w+$/
27
+
28
+ // The parts of a Liquid expression outside quotes, split at `separator`
29
+ // (| between filters, , between arguments)
30
+ export function splitOutside(text, separator) {
31
+ const parts = []
32
+ let quote = null
33
+ let current = ""
34
+ for (const char of text) {
35
+ if (quote) {
36
+ if (char === quote) quote = null
37
+ } else if (char === '"' || char === "'") {
38
+ quote = char
39
+ } else if (char === separator) {
40
+ parts.push(current)
41
+ current = ""
42
+ continue
43
+ }
44
+ current += char
45
+ }
46
+ parts.push(current)
47
+ return parts
48
+ }
49
+
50
+ // The quote a text ends inside, and where it opened, if it does
51
+ function openQuote(text) {
52
+ let quote = null
53
+ let at = -1
54
+ for (let i = 0; i < text.length; i++) {
55
+ const char = text[i]
56
+ if (quote) {
57
+ if (char === quote) quote = null
58
+ } else if (char === '"' || char === "'") {
59
+ quote = char
60
+ at = i
61
+ }
62
+ }
63
+ return quote ? { quote, at } : null
64
+ }
65
+
66
+ // A quoted argument's text, or the argument as written
67
+ export function unquote(text) {
68
+ const trimmed = text.trim()
69
+ const match = trimmed.match(/^(["'])(.*)\1$/)
70
+ return match ? match[2] : trimmed
71
+ }
72
+
73
+ export function liquidContext(before, mode = "output") {
74
+ let expression = before
75
+ let tag = null
76
+ if (mode === "output") {
77
+ const output = before.lastIndexOf("{{")
78
+ const open = Math.max(output, before.lastIndexOf("{%"))
79
+ if (open < 0 || Math.max(before.lastIndexOf("}}"), before.lastIndexOf("%}")) > open) return null
80
+ tag = open === output ? "{{" : "{%"
81
+ expression = before.slice(open + 2).replace(/^-/, "")
82
+ }
83
+ const offset = before.length - expression.length
84
+ const quoted = openQuote(expression)
85
+ const head = quoted ? expression.slice(0, quoted.at) : expression
86
+
87
+ // In a filter's arguments: | name: a, b, …
88
+ const filters = splitOutside(head, "|")
89
+ if (filters.length > 1) {
90
+ const current = filters.at(-1)
91
+ const input = filters.slice(0, -1).join("|").trim()
92
+ const named = current.match(/^\s*(\w*)$/)
93
+ if (named && !quoted) return { kind: "filter", start: before.length - named[1].length, partial: named[1], input, tag }
94
+
95
+ const call = current.match(/^\s*(\w+)\s*:([\s\S]*)$/)
96
+ if (call) {
97
+ const args = splitOutside(call[2], ",")
98
+ const written = args.slice(0, -1).map(unquote)
99
+ if (quoted) {
100
+ const partial = expression.slice(quoted.at + 1)
101
+ return { kind: "argument", filter: call[1], index: args.length - 1, args: written, start: offset + quoted.at, partial, quote: quoted.quote, input, tag }
102
+ }
103
+ const last = args.at(-1)
104
+ const path = last.match(new RegExp(`^\\s*(${PATH.source})?$`))
105
+ if (path) {
106
+ const partial = path[1] || ""
107
+ return { kind: "argument", filter: call[1], index: args.length - 1, args: written, start: before.length - partial.length, partial, quote: null, input, tag }
108
+ }
109
+ return null
110
+ }
111
+ if (quoted) return null
112
+ }
113
+
114
+ // A value compared with a variable: line.party == "sp
115
+ const compared = head.match(new RegExp(`(${PATH.source})\\s*(?:==|!=)\\s*$`))
116
+ if (compared && (quoted || /(?:==|!=)\s*$/.test(expression))) {
117
+ const partial = quoted ? expression.slice(quoted.at + 1) : ""
118
+ return { kind: "value", of: compared[1], start: quoted ? offset + quoted.at : before.length, partial, quote: quoted?.quote || null, tag }
119
+ }
120
+ if (quoted) return null
121
+
122
+ const match = expression.match(new RegExp(`(?:^|[^\\w.])(${PATH.source})?$`))
123
+ if (!match) return null
124
+ const path = match[1] || ""
125
+ return { kind: "variable", start: before.length - path.length, path, tag }
126
+ }
127
+
128
+ // The variable path an expression starts from, and the filters after it:
129
+ // 'contract.lines | where: "party", "account" | sort' → { path: "contract.lines", filters: ["where", "sort"] }
130
+ // In a tag, the path is the last one before the first |: "assign x = order.lines"
131
+ export function expressionParts(expression) {
132
+ const [first, ...rest] = splitOutside(expression, "|")
133
+ const paths = first.replace(/(["'])[\s\S]*?\1/g, " ").match(new RegExp(PATH.source, "g")) || []
134
+ const path = paths.filter((candidate) => !["assign", "for", "in", "if", "unless", "elsif", "and", "or", "contains"].includes(candidate)).at(-1)
135
+ if (!path) return null
136
+ return { path, filters: rest.map((filter) => filter.trim().match(/^\w+/)?.[0]).filter(Boolean) }
137
+ }
138
+
139
+ // The variables a block can use: its Loops' and the Assigns before it (in
140
+ // its container, or in one around it), nearest first
141
+ // [{ variable, collection }] a Loop's: each of a collection
142
+ // [{ variable, expression }] an Assign's: what its expression comes to
143
+ export function liquidScope(doc, id) {
144
+ const scope = []
145
+ let hit = find(doc, id)
146
+ while (hit?.parent) {
147
+ for (const sibling of hit.parent.children.slice(0, hit.index).reverse()) {
148
+ if (sibling.type !== "assign") continue
149
+ const { variable, expression } = sibling.data || {}
150
+ if (NAME.test(variable || "") && expression) scope.push({ variable, expression })
151
+ }
152
+ if (hit.parent.type === "loop") {
153
+ const variable = hit.parent.data.variable || "item"
154
+ const collection = hit.parent.data.collection || "items"
155
+ if (NAME.test(variable)) scope.push({ variable, collection })
156
+ }
157
+ hit = find(doc, hit.parent.id)
158
+ }
159
+ return scope
160
+ }
161
+
162
+ // The assigns ({% assign x = … %}) and loops ({% for x in … %}) earlier in a
163
+ // text, before the caret, nearest first, as liquidScope gives them
164
+ export function textScope(before) {
165
+ const scope = []
166
+ for (const match of before.matchAll(/\{%-?\s*(assign|for)\s+(\w+)\s*(=|in)\s*([\s\S]*?)\s*-?%\}/g)) {
167
+ if (match[1] === "assign" && match[3] === "=") scope.unshift({ variable: match[2], expression: match[4] })
168
+ if (match[1] === "for" && match[3] === "in") {
169
+ // Only while the loop is open
170
+ const after = before.slice(match.index + match[0].length)
171
+ if (!/\{%-?\s*endfor\b/.test(after)) scope.unshift({ variable: match[2], collection: match[4].split(/\s/)[0] })
172
+ }
173
+ }
174
+ return scope
175
+ }
176
+
177
+ // What replaces a quoted argument or value, in the quote it was started
178
+ // with, and how much of the text after the caret it takes: its closing quote,
179
+ // when that's there already
180
+ export function quoted(value, { quote = null, after = "" } = {}) {
181
+ const mark = quote || '"'
182
+ return { text: `${mark}${value}${mark}`, through: after.startsWith(mark) ? 1 : 0 }
183
+ }
@@ -223,6 +223,40 @@ export function hasTable(doc) {
223
223
  export function setColumn(doc, cellId, key, value) {
224
224
  const at = position(doc, cellId)
225
225
  if (!at) return
226
- const list = columns(at.table)
227
- list[at.column] = { ...list[at.column], [key]: value }
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
228
262
  }
@@ -11,10 +11,28 @@
11
11
  // In Liquid a collection's elements are reached through a Loop block's
12
12
  // variable ({% for line in order.order_lines %} → line.product) or with
13
13
  // first and last (order.order_lines.first.product), so those are resolved to
14
- // such a path before asking.
14
+ // such a path before asking. An Assign's variable is what its expression
15
+ // comes to: through filters that keep a collection what it is (the host's
16
+ // filtersUrl says which, `keeps`), `lines = order.order_lines | where: …` is
17
+ // those lines still.
18
+ //
19
+ // The filters, for what follows a |, come from the editor's filtersUrl:
20
+ //
21
+ // GET → { filters: [{ name, label, arguments: [{ name, kind }], keeps }] }
22
+ //
23
+ // as Liquidum's FiltersController answers. A variable with `values`
24
+ // ([{ value, label }]) has those only, for a comparison or a where filter.
15
25
 
16
26
  import { ancestors } from "tess_edit/core/document"
17
27
  import { t } from "tess_edit/core/i18n"
28
+ import { expressionParts } from "tess_edit/core/liquid"
29
+
30
+ // What filters on a collection leave, without the host's: the same items, or one
31
+ export const KEEPS = {
32
+ where: "collection", where_exp: "collection", reject: "collection", sort: "collection", sort_natural: "collection",
33
+ reverse: "collection", uniq: "collection", compact: "collection", concat: "collection",
34
+ first: "item", last: "item", find: "item"
35
+ }
18
36
 
19
37
  // The members Liquid gives every collection
20
38
  export const COLLECTION_MEMBERS = [
@@ -26,12 +44,50 @@ export const COLLECTION_MEMBERS = [
26
44
  const ELEMENT = new Set(["first", "last"])
27
45
 
28
46
  export class Variables {
29
- constructor(url, { fetch: fetcher = (...args) => fetch(...args) } = {}) {
47
+ constructor(url, { fetch: fetcher = (...args) => fetch(...args), filtersUrl = null } = {}) {
30
48
  this.url = url
49
+ this.filtersUrl = filtersUrl
31
50
  this.fetch = fetcher
32
51
  this.levels = new Map()
33
52
  }
34
53
 
54
+ // The host's filters, by name, cached; none without its filtersUrl
55
+ filters() {
56
+ if (!this.filtersUrl) return Promise.resolve(new Map())
57
+ this.filterList ||= this.get(this.filtersUrl, {}).then((body) => new Map((body.filters || []).map((filter) => [filter.name, filter])))
58
+ this.filterList.catch(() => (this.filterList = null))
59
+ return this.filterList
60
+ }
61
+
62
+ async get(path, params) {
63
+ const url = new URL(path, window.location.href)
64
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value)
65
+ const response = await this.fetch(url, { headers: { Accept: "application/json" }, credentials: "same-origin" })
66
+ if (!response.ok) throw new Error(t("Loading the variables failed (%{status})", { status: `${response.status} ${response.statusText}` }))
67
+ return response.json()
68
+ }
69
+
70
+ // A scope from core/liquid.js with its Assigns made paths: a Loop's
71
+ // variable and an Assign of one item ({ variable, collection }) are each of
72
+ // a collection; an Assign of a collection or a value ({ variable, path })
73
+ // stands for its path. One that can't be followed isn't there.
74
+ async resolveScope(scope = []) {
75
+ if (!scope.some((entry) => entry.expression)) return scope
76
+ const filters = await this.filters().catch(() => new Map())
77
+ return scope.flatMap((entry) => {
78
+ if (!entry.expression) return [entry]
79
+ const parts = expressionParts(entry.expression)
80
+ if (!parts) return []
81
+ let item = false
82
+ for (const name of parts.filters) {
83
+ const keeps = filters.get(name)?.keeps ?? KEEPS[name]
84
+ if (keeps === "item" && !item) item = true
85
+ else if (keeps !== "collection") return []
86
+ }
87
+ return [item ? { variable: entry.variable, collection: parts.path } : { variable: entry.variable, path: parts.path }]
88
+ })
89
+ }
90
+
35
91
  get enabled() {
36
92
  return Boolean(this.url)
37
93
  }
@@ -59,8 +115,18 @@ export class Variables {
59
115
  // in a loop over order.order_lines, or "order.order_lines" (a collection:
60
116
  // first, last and size). scope is from loopScope.
61
117
  async options(path, scope = []) {
118
+ scope = await this.resolveScope(scope)
62
119
  const names = path ? path.split(".") : []
63
- if (!names.length) return [...scope.map(loopVariable), ...(await this.at(""))]
120
+ if (!names.length) {
121
+ const own = []
122
+ for (const [index, entry] of scope.entries()) {
123
+ if (own.some((variable) => variable.name === entry.variable)) continue
124
+ // What it stands for, of the scope around it
125
+ const target = entry.path && (await this.variable(entry.path.split("."), scope.slice(index + 1)))
126
+ own.push(entry.path ? { ...(target || { children: false }), name: entry.variable, label: t("Assigned %{path}", { path: entry.path }), assign: true } : loopVariable(entry))
127
+ }
128
+ return [...own, ...(await this.at(""))]
129
+ }
64
130
 
65
131
  const variable = await this.variable(names, scope)
66
132
  if (!variable?.children) return []
@@ -68,12 +134,19 @@ export class Variables {
68
134
  return this.at(resolve(names, scope))
69
135
  }
70
136
 
137
+ // The variable a path as written comes to, with a scope from core/liquid.js
138
+ async lookup(path, scope = []) {
139
+ if (!path) return null
140
+ return this.variable(path.split("."), await this.resolveScope(scope))
141
+ }
142
+
71
143
  // What the last name of a path is: a variable with children, a collection, …
72
144
  async variable(names, scope) {
73
145
  const last = names[names.length - 1]
74
146
  const parent = names.slice(0, -1)
75
147
  if (!parent.length) {
76
148
  const own = scope.find((entry) => entry.variable === last)
149
+ if (own?.path) return { ...(await this.variable(own.path.split("."), scope.slice(scope.indexOf(own) + 1))), name: last }
77
150
  if (own) return loopVariable(own)
78
151
  } else if (ELEMENT.has(last)) {
79
152
  const collection = await this.variable(parent, scope)
@@ -94,8 +167,8 @@ export function resolve(names, scope = []) {
94
167
  let resolved = [...names]
95
168
  // Inner loops first: their collection can start with an outer loop's variable
96
169
  for (let i = 0; i < scope.length; i++) {
97
- for (const { variable, collection } of scope) {
98
- if (resolved[0] === variable) resolved = [...collection.split("."), ...resolved.slice(1)]
170
+ for (const { variable, collection, path } of scope) {
171
+ if (resolved[0] === variable && (collection || path)) resolved = [...(collection || path).split("."), ...resolved.slice(1)]
99
172
  }
100
173
  }
101
174
  return resolved.filter((name) => !ELEMENT.has(name) && !/^\d+$/.test(name)).join(".")
@@ -11,6 +11,7 @@ import { imageFields } from "tess_edit/core/media"
11
11
  import { getBlock, inlinePart, label } from "tess_edit/core/registry"
12
12
  import { missingArguments, textParts, translationCalls } from "tess_edit/core/translations"
13
13
  import { valueCalls } from "tess_edit/core/values"
14
+ import { cellOf, columnCount, rowGroups, rows, setColumnAt, span, tableOf } from "tess_edit/core/table"
14
15
  import { FREE_CSS, FreeLayout } from "tess_edit/ui/free_layout"
15
16
  import { icon } from "tess_edit/ui/icons"
16
17
 
@@ -34,6 +35,12 @@ body{min-height:100vh;margin:0}
34
35
  .tess-tools [data-tool="drag"]{cursor:grab}
35
36
  .tess-plus{position:absolute;left:50%;top:100%;transform:translate(-50%,-50%);pointer-events:auto;width:20px;height:20px;border-radius:999px;background:#2563eb;color:#fff;display:flex;align-items:center;justify-content:center;cursor:pointer;border:2px solid #fff;padding:0;box-shadow:0 1px 3px rgba(0,0,0,.25)}
36
37
  .tess-plus:hover{background:#1d4ed8}
38
+ .tess-bracket{position:absolute;box-sizing:border-box;width:6px;border:2px solid #8b5cf6;border-right:0;border-radius:3px 0 0 3px;pointer-events:auto;cursor:pointer}
39
+ .tess-bracket:hover,.tess-bracket.tess-on{border-color:#6d28d9}
40
+ .tess-bracket span{position:absolute;right:calc(100% + 4px);top:-2px;color:#6d28d9;white-space:nowrap;max-width:160px;overflow:hidden;text-overflow:ellipsis}
41
+ .tess-column{position:absolute;width:9px;margin-left:-4px;pointer-events:auto;cursor:col-resize}
42
+ .tess-column::after{content:"";position:absolute;left:4px;top:0;bottom:0;width:1px;background:#2563eb;opacity:0}
43
+ .tess-column:hover::after,.tess-column.tess-on::after{opacity:1}
37
44
  .tess-indicator{position:absolute;background:#2563eb;border-radius:2px;pointer-events:none;box-shadow:0 0 0 2px rgba(37,99,235,.2)}
38
45
  .tess-indicator.tess-fill{background:rgba(37,99,235,.08);outline:2px dashed #2563eb;outline-offset:-2px;box-shadow:none}
39
46
  [class*="tessph-"]{cursor:pointer}
@@ -59,6 +66,7 @@ function isFileDrag(event, editor) {
59
66
  return !editor.drag && Array.from(event.dataTransfer?.types || []).includes("Files")
60
67
  }
61
68
 
69
+ const TABLE_ICON = '<rect x="3" y="5" width="18" height="14" rx="1"/><path d="M3 10h18M3 15h18M9 10v9M15 10v9"/>'
62
70
  const CLASS = /\btess-(b[a-z0-9]+)\b/
63
71
  const PLACEHOLDER = /\btessph-(b[a-z0-9]+)\b/
64
72
 
@@ -81,6 +89,8 @@ export class Canvas {
81
89
 
82
90
  // Replaces the iframe's content, keeping the scroll position.
83
91
  write(html, mode) {
92
+ // A column being dragged is let go: its listeners were the old document's
93
+ this.resizing = false
84
94
  const scrollY = this.win?.scrollY || 0
85
95
  this.mode = mode
86
96
  const doc = this.doc
@@ -317,7 +327,7 @@ export class Canvas {
317
327
  }
318
328
 
319
329
  refresh() {
320
- if (!this.overlay) return
330
+ if (!this.overlay || this.resizing) return
321
331
  this.overlay.replaceChildren()
322
332
  if (this.mode !== "edit") return
323
333
  this.free.drawGuides(this.overlay)
@@ -335,6 +345,7 @@ export class Canvas {
335
345
 
336
346
  const hit = selectedId && find(this.editor.doc, selectedId)
337
347
  if (!hit || hit.node === this.editor.doc) return
348
+ this.drawTable(selectedId, editingId)
338
349
  const rect = this.rectOf(selectedId)
339
350
  if (!rect) return
340
351
  const box = this.box(rect, editingId === selectedId ? "tess-selected tess-editing" : "tess-selected")
@@ -345,13 +356,16 @@ export class Canvas {
345
356
  if (handle) box.append(handle)
346
357
 
347
358
  if (editingId !== selectedId && !this.free.dragging) {
359
+ // In a table's cell (the cell, or its text): its rows and columns
360
+ const cell = free && cellOf(this.editor.doc, selectedId)
348
361
  const tools = this.doc.createElement("div")
349
362
  tools.className = "tess-tools"
350
363
  tools.innerHTML = [
351
364
  ["parent", t("Select parent")],
365
+ ...(cell ? [["table", t("Rows and columns")]] : []),
352
366
  ...(free ? [["drag", t("Drag to move")], ["duplicate", t("Duplicate")], ["delete", t("Delete")]] : [])
353
367
  ]
354
- .map(([tool, title]) => `<span data-tool="${tool}" title="${title}" ${tool === "drag" ? 'draggable="true"' : ""}>${icon({ parent: "parent", drag: "move", duplicate: "copy", delete: "trash" }[tool], "tess-icon")}</span>`)
368
+ .map(([tool, title]) => `<span data-tool="${tool}" title="${title}" ${tool === "drag" ? 'draggable="true"' : ""}>${icon({ parent: "parent", drag: "move", duplicate: "copy", delete: "trash", table: TABLE_ICON }[tool], "tess-icon")}</span>`)
355
369
  .join("")
356
370
  tools.querySelectorAll("svg").forEach((svg) => svg.setAttribute("style", "width:14px;height:14px"))
357
371
  tools.addEventListener("mousedown", (event) => event.stopPropagation())
@@ -360,6 +374,7 @@ export class Canvas {
360
374
  event.preventDefault()
361
375
  event.stopPropagation()
362
376
  if (tool === "parent") this.editor.selectParent()
377
+ if (tool === "table") this.editor.openTableMenu(cell.id, this.toParentRect(event.target.closest("[data-tool]").getBoundingClientRect()))
363
378
  if (tool === "duplicate") this.editor.duplicate(selectedId)
364
379
  if (tool === "delete") this.editor.remove(selectedId)
365
380
  })
@@ -390,6 +405,78 @@ export class Canvas {
390
405
  this.overlay.append(box)
391
406
  }
392
407
 
408
+ // The table the selection is in: a bracket at its side by each Loop's and
409
+ // Condition's rows, labelled as the block, which a click selects; and, when
410
+ // not editing text, a handle on each column's right border, dragged to set
411
+ // its width (in pt when it was in pt, else px)
412
+ drawTable(selectedId, editingId) {
413
+ const table = tableOf(this.editor.doc, selectedId)
414
+ // The table element itself, not a wrapper with its padding
415
+ const element = table && this.elementOf(table.id)
416
+ const inner = element && (element.tagName === "TABLE" ? element : element.querySelector("table"))
417
+ const tableRect = inner ? inner.getBoundingClientRect() : table && this.rectOf(table.id)
418
+ if (!tableRect) return
419
+ for (const { node, depth } of rowGroups(table)) {
420
+ const rect = this.rectOf(node.id)
421
+ if (!rect) continue
422
+ const bracket = this.box({ left: tableRect.left - 10 - depth * 10, top: rect.top, width: 6, height: rect.height }, "tess-bracket")
423
+ if (node.id === selectedId) bracket.classList.add("tess-on")
424
+ bracket.dataset.tessBracket = node.id
425
+ bracket.title = label(node)
426
+ bracket.append(Object.assign(this.doc.createElement("span"), { textContent: label(node) }))
427
+ bracket.addEventListener("mousedown", (event) => event.stopPropagation())
428
+ bracket.addEventListener("click", (event) => {
429
+ event.preventDefault()
430
+ event.stopPropagation()
431
+ this.editor.select(node.id, { reveal: true })
432
+ })
433
+ this.overlay.append(bracket)
434
+ }
435
+ if (editingId || !this.editor.isFree(table.id)) return
436
+ for (const handle of this.columnHandles(table, tableRect)) this.overlay.append(handle)
437
+ }
438
+
439
+ // A row of single cells shows where the columns are
440
+ columnHandles(table, tableRect) {
441
+ const count = columnCount(table)
442
+ const row = rows(table).find((candidate) => candidate.children.length === count && candidate.children.every((cell) => span(cell) === 1))
443
+ const cells = row ? [...(this.elementOf(row.id)?.children || [])].filter((element) => /^T[DH]$/.test(element.tagName)) : []
444
+ if (cells.length !== count) return []
445
+ return cells.map((cell, column) => {
446
+ const right = cell.getBoundingClientRect().right
447
+ const handle = this.box({ left: right, top: tableRect.top, width: 9, height: tableRect.height }, "tess-column")
448
+ handle.title = t("Drag to set the column's width")
449
+ handle.addEventListener("mousedown", (event) => this.resizeColumn(event, table, column, cell, handle))
450
+ return handle
451
+ })
452
+ }
453
+
454
+ resizeColumn(event, table, column, cell, handle) {
455
+ event.preventDefault()
456
+ event.stopPropagation()
457
+ const startX = event.clientX
458
+ const startLeft = parseFloat(handle.style.left)
459
+ const startWidth = cell.getBoundingClientRect().width
460
+ const inPt = /pt$/.test(table.data?.columns?.[column]?.width || "")
461
+ const width = (clientX) => Math.max(12, startWidth + clientX - startX)
462
+ this.resizing = true
463
+ handle.classList.add("tess-on")
464
+ const move = (moved) => (handle.style.left = `${startLeft + width(moved.clientX) - startWidth}px`)
465
+ const up = (released) => {
466
+ this.doc.removeEventListener("mousemove", move)
467
+ this.doc.removeEventListener("mouseup", up)
468
+ this.resizing = false
469
+ this.resized = true
470
+ setTimeout(() => (this.resized = false))
471
+ const px = width(released.clientX)
472
+ if (Math.abs(px - startWidth) < 1) return this.refresh()
473
+ const value = inPt ? `${Math.round(px * 0.75)}pt` : `${Math.round(px)}px`
474
+ this.editor.commit((doc) => setColumnAt(doc, table.id, column, "width", value))
475
+ }
476
+ this.doc.addEventListener("mousemove", move)
477
+ this.doc.addEventListener("mouseup", up)
478
+ }
479
+
393
480
  setHover(id) {
394
481
  if (this.hoverId === id) return
395
482
  this.hoverId = id
@@ -405,7 +492,7 @@ export class Canvas {
405
492
  // --- events ---------------------------------------------------------------
406
493
 
407
494
  onMove(event) {
408
- if (this.editor.drag || this.free.dragging) return
495
+ if (this.editor.drag || this.free.dragging || this.resizing) return
409
496
  const hit = this.hit(event.target)
410
497
  const element = hit && !hit.placeholder ? hit.element : null
411
498
  if (element !== this.hoverElement) {
@@ -419,6 +506,7 @@ export class Canvas {
419
506
  if (this.editor.editingId && event.target.closest?.(".ProseMirror, .tess-plain")) return
420
507
  if (event.target.closest?.("#tess-overlay")) return
421
508
  event.preventDefault()
509
+ if (this.resized) return
422
510
  if (this.openLink(event)) return
423
511
  if (this.free.swallowClick()) return
424
512
  const hit = this.hit(event.target)
@@ -20,7 +20,7 @@ import { fieldType, getBlock, label } from "tess_edit/core/registry"
20
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
- import { loopScope } from "tess_edit/core/variables"
23
+ import { liquidScope } from "tess_edit/core/liquid"
24
24
  import { CELL, ROW, TABLE, addColumn, addRow, cellOf, columnCount, deleteColumn, deleteRow, position, rows, setColumn } from "tess_edit/core/table"
25
25
  import { codeInput } from "tess_edit/ui/code_input"
26
26
  import { FontPicker } from "tess_edit/ui/font_picker"
@@ -348,7 +348,7 @@ export class Inspector {
348
348
  this.inputs.set(field.key, input)
349
349
  if (!this.editor.variableMenu) return input
350
350
  const mode = field.liquid === "expression" || field.liquid === "collection" ? field.liquid : "output"
351
- const adapter = inputAdapter(input, { mode, scope: loopScope(this.editor.doc, node.id) })
351
+ const adapter = inputAdapter(input, { mode, scope: liquidScope(this.editor.doc, node.id) })
352
352
  suggestIn(this.editor.variableMenu, input, adapter)
353
353
  this.adapters.set(field.key, adapter)
354
354
  return input
@@ -79,7 +79,7 @@ export class TextEditing {
79
79
  return element
80
80
  }
81
81
 
82
- // scope: the loop variables of the block (core/variables.js loopScope)
82
+ // scope: the Loops' and Assigns' variables of the block (core/liquid.js liquidScope)
83
83
  start(container, content, onUpdate, { scope = [] } = {}) {
84
84
  this.stop()
85
85
  container.replaceChildren()
@@ -11,10 +11,15 @@
11
11
  // scope the loop variables there (core/variables.js loopScope)
12
12
  //
13
13
  // See inputAdapter below and TextEditing for Tiptap's. With the host's
14
- // translations it also suggests their keys while typing {{ '.
14
+ // translations it also suggests their keys while typing {{ '. What it
15
+ // suggests depends on what's being written (core/liquid.js liquidContext): a
16
+ // variable; after a |, the host's filters; a filter's argument, a property of
17
+ // the collection's items ("party") or a value it can have ("sponsor"); and
18
+ // after == or !=, the values of the variable compared.
15
19
 
20
+ import { expressionParts, liquidContext, quoted, textScope } from "tess_edit/core/liquid"
16
21
  import { keyCompletion, keyToken } from "tess_edit/core/translations"
17
- import { completion, liquidToken } from "tess_edit/core/variables"
22
+ import { completion } from "tess_edit/core/variables"
18
23
  import { t } from "tess_edit/core/i18n"
19
24
  import { h } from "tess_edit/ui/dom"
20
25
 
@@ -47,27 +52,98 @@ export class VariableMenu {
47
52
  const key = this.editor.translations?.enabled && adapter.mode === "output" && keyToken(before)
48
53
  if (key) return this.suggestKeys(adapter, key)
49
54
  if (!this.editor.variables?.enabled) return this.close()
50
- const token = liquidToken(before, adapter.mode === "output" ? "output" : "expression")
51
- if (!token) return this.close()
52
-
53
- const dot = token.path.lastIndexOf(".")
54
- const parent = dot < 0 ? "" : token.path.slice(0, dot)
55
- const partial = token.path.slice(dot + 1).toLowerCase()
56
- const start = token.start + dot + 1
55
+ const context = liquidContext(before, adapter.mode === "output" ? "output" : "expression")
56
+ if (!context) return this.close()
57
+ const scope = [...textScope(before), ...(adapter.scope || [])]
57
58
  const request = ++this.request
58
- let items
59
+ let found
59
60
  try {
60
- items = await this.editor.variables.options(parent, adapter.scope)
61
+ found = await this.options(context, scope)
61
62
  } catch (error) {
62
- items = []
63
+ found = null
63
64
  }
64
65
  if (request !== this.request) return
65
- // Names that start with what's typed first, then labels that have it
66
- const named = items.filter((item) => item.name.toLowerCase().startsWith(partial))
67
- items = [...named, ...items.filter((item) => !named.includes(item) && item.label?.toLowerCase().includes(partial))]
68
- if (!items.length || (items.length === 1 && items[0].name.toLowerCase() === partial && !items[0].children)) return this.close()
66
+ if (!found?.items.length) return this.close()
67
+ this.show({ adapter, browse: false, items: found.items, index: 0, choose: found.choose })
68
+ }
69
+
70
+ // What fits a context, those starting with what's typed first, then those
71
+ // whose label has it: { items, choose }
72
+ async options(context, scope) {
73
+ const variables = this.editor.variables
74
+ if (context.kind === "variable") return this.variableOptions(context, context.path, scope)
75
+ if (context.kind === "filter") {
76
+ const filters = [...(await variables.filters()).values()]
77
+ const items = ranked(filters.map((filter) => ({ name: filter.name, label: filter.label, hint: signature(filter), filter })), context.partial)
78
+ if (items.length === 1 && items[0].name === context.partial && !items[0].filter.arguments?.length) return null
79
+ return {
80
+ items,
81
+ choose: async (item) => {
82
+ const adapter = this.state.adapter
83
+ const more = item.filter.arguments?.length > 0
84
+ adapter.replace(context.start, adapter.before().length, more ? `${item.name}: ` : item.name)
85
+ more ? await this.suggest(adapter) : this.close()
86
+ }
87
+ }
88
+ }
89
+ if (context.kind === "argument") {
90
+ const filter = (await variables.filters()).get(context.filter)
91
+ const kind = filter?.arguments?.[context.index]?.kind
92
+ const more = filter?.arguments?.length > context.index + 1
93
+ if (kind === "property" || kind === "value") {
94
+ const elements = await this.elements(context.input, scope)
95
+ if (!elements) return null
96
+ const choices = kind === "property"
97
+ ? elements.map((variable) => ({ value: variable.name, label: variable.label }))
98
+ : elements.find((variable) => variable.name === context.args[context.index - 1])?.values || []
99
+ return this.quotedOptions(context, choices, more)
100
+ }
101
+ return context.quote ? null : this.variableOptions(context, context.partial, scope)
102
+ }
103
+ if (context.kind === "value") {
104
+ const variable = await variables.lookup(context.of, scope)
105
+ return this.quotedOptions(context, variable?.values || [], false)
106
+ }
107
+ return null
108
+ }
69
109
 
70
- this.show({ adapter, browse: false, items, index: 0, choose: (item) => this.complete(adapter, token, start, item) })
110
+ // The variables for a path being typed, from `context.start`
111
+ async variableOptions(context, path, scope) {
112
+ const dot = path.lastIndexOf(".")
113
+ const parent = dot < 0 ? "" : path.slice(0, dot)
114
+ const partial = path.slice(dot + 1)
115
+ const start = context.start + dot + 1
116
+ const items = ranked(await this.editor.variables.options(parent, scope), partial)
117
+ if (items.length === 1 && items[0].name.toLowerCase() === partial.toLowerCase() && !items[0].children) return null
118
+ return { items, choose: (item) => this.complete(this.state.adapter, context, start, item) }
119
+ }
120
+
121
+ // The variables of a collection's items, for a filter on it: in
122
+ // `lines | where: "`, those of each line
123
+ async elements(input, scope) {
124
+ const parts = expressionParts(input)
125
+ if (!parts) return null
126
+ const [entry] = await this.editor.variables.resolveScope([{ variable: "\u0000", expression: input }])
127
+ if (!entry?.path) return null
128
+ const collection = await this.editor.variables.lookup(entry.path, scope)
129
+ if (!collection?.collection) return null
130
+ return this.editor.variables.options(`${entry.path}.first`, scope)
131
+ }
132
+
133
+ // Values in quotes ({ value, label }), then a comma for the next argument
134
+ quotedOptions(context, choices, more) {
135
+ const items = ranked(choices.map((choice) => ({ name: `"${choice.value}"`, value: choice.value, label: choice.label })), context.partial, (item) => item.value)
136
+ if (!items.length || (items.length === 1 && items[0].value === context.partial)) return null
137
+ return {
138
+ items,
139
+ choose: async (item) => {
140
+ const adapter = this.state.adapter
141
+ const before = adapter.before()
142
+ const { text, through } = quoted(item.value, { quote: context.quote, after: adapter.after() })
143
+ adapter.replace(context.start, before.length + through, more ? `${text}, ` : text)
144
+ more ? await this.suggest(adapter) : this.close()
145
+ }
146
+ }
71
147
  }
72
148
 
73
149
  // The translation keys with what's typed, those that start with it first,
@@ -94,6 +170,7 @@ export class VariableMenu {
94
170
  }
95
171
 
96
172
  async complete(adapter, token, start, item) {
173
+ if (!adapter) return
97
174
  const before = adapter.before()
98
175
  const { text, more } = completion(item, { tag: token.tag, before: before.slice(0, start), after: adapter.after(), collection: adapter.mode === "collection" })
99
176
  adapter.replace(start, before.length, text)
@@ -259,3 +336,17 @@ export function suggestIn(menu, input, adapter) {
259
336
  input.addEventListener("keydown", (event) => menu.key(event))
260
337
  input.addEventListener("blur", () => !menu.state?.browse && menu.close())
261
338
  }
339
+
340
+ // Those whose name (or `name(item)`) starts with what's typed, then those
341
+ // whose label has it
342
+ function ranked(items, partial, name = (item) => item.name) {
343
+ const typed = (partial || "").toLowerCase()
344
+ const named = items.filter((item) => name(item).toLowerCase().startsWith(typed))
345
+ return [...named, ...items.filter((item) => !named.includes(item) && item.label?.toLowerCase().includes(typed))]
346
+ }
347
+
348
+ // A filter as it's written: date: format
349
+ function signature(filter) {
350
+ const args = (filter.arguments || []).map((argument) => argument.name)
351
+ return args.length ? `${filter.name}: ${args.join(", ")}` : filter.name
352
+ }
@@ -22,9 +22,13 @@ en:
22
22
  add_above: "Add above"
23
23
  add_below: "Add below"
24
24
  add_block: "Add block"
25
+ add_column_left: "Add column left"
26
+ add_column_right: "Add column right"
25
27
  add_left: "Add left"
26
28
  add_link: "Add link"
27
29
  add_right: "Add right"
30
+ add_row_above: "Add row above"
31
+ add_row_below: "Add row below"
28
32
  added_to_the_email_s_style_block: "Added to the email's <style> block."
29
33
  align: "Align"
30
34
  align_center: "Align center"
@@ -35,6 +39,7 @@ en:
35
39
  all_panels_on_the_right: "All panels on the right"
36
40
  alt_text: "Alt text"
37
41
  assign: "Assign"
42
+ assigned_path: "Assigned %{path}"
38
43
  auto: "Auto"
39
44
  background: "Background"
40
45
  background_image: "Background image"
@@ -77,6 +82,8 @@ en:
77
82
  dashed: "Dashed"
78
83
  default: "Default"
79
84
  delete: "Delete"
85
+ delete_column: "Delete column"
86
+ delete_row: "Delete row"
80
87
  desktop: "Desktop"
81
88
  divider: "Divider"
82
89
  done: "Done"
@@ -87,6 +94,7 @@ en:
87
94
  drag_onto_the_canvas_or_click_to_add: "Drag onto the canvas, or click to add"
88
95
  drag_to_move: "Drag to move"
89
96
  drag_to_resize: "Drag to resize"
97
+ drag_to_set_the_column_s_width: "Drag to set the column's width"
90
98
  drop_a_cell_here: "Drop a cell here"
91
99
  drop_a_column_here: "Drop a column here"
92
100
  drop_a_row_here: "Drop a row here"
@@ -206,11 +214,13 @@ en:
206
214
  redo_z: "Redo (⇧⌘Z)"
207
215
  remove: "Remove"
208
216
  remove_link: "Remove link"
217
+ repeat_the_row_in_a_loop: "Repeat the row in a Loop"
209
218
  repeats_its_blocks_for_each_item_for_variable_in_collection: "Repeats its blocks for each item: {% for variable in collection %}."
210
219
  replace: "Replace"
211
220
  right: "Right"
212
221
  right_to_left: "Right to left"
213
222
  row: "Row"
223
+ rows_and_columns: "Rows and columns"
214
224
  rows_of_cells_select_a_cell_to_add_rows_and_columns_put_rows: "Rows of cells. Select a cell to add rows and columns. Put rows in a Loop to repeat them for each item."
215
225
  same_tab: "Same tab"
216
226
  save: "Save"
@@ -221,6 +231,7 @@ en:
221
231
  select_the_text_to_translate_first: "Select the text to translate first."
222
232
  sets_a_liquid_variable_for_the_blocks_after_it_assign_variab: "Sets a Liquid variable for the blocks after it: {% assign variable = value %}."
223
233
  show_panels: "Show panels"
234
+ show_the_row_in_a_condition: "Show the row in a Condition"
224
235
  show_translations_in: "Show translations in"
225
236
  show_when: "Show when"
226
237
  shown_after_the_subject_in_most_inboxes: "Shown after the subject in most inboxes."
@@ -22,9 +22,13 @@ nl:
22
22
  add_above: "Erboven toevoegen"
23
23
  add_below: "Eronder toevoegen"
24
24
  add_block: "Blok toevoegen"
25
+ add_column_left: "Kolom links toevoegen"
26
+ add_column_right: "Kolom rechts toevoegen"
25
27
  add_left: "Links toevoegen"
26
28
  add_link: "Link toevoegen"
27
29
  add_right: "Rechts toevoegen"
30
+ add_row_above: "Rij erboven toevoegen"
31
+ add_row_below: "Rij eronder toevoegen"
28
32
  added_to_the_email_s_style_block: "Wordt toegevoegd aan het <style>-blok van de e-mail."
29
33
  align: "Uitlijning"
30
34
  align_center: "Centreren"
@@ -35,6 +39,7 @@ nl:
35
39
  all_panels_on_the_right: "Alle panelen rechts"
36
40
  alt_text: "Alternatieve tekst"
37
41
  assign: "Toekennen"
42
+ assigned_path: "Toegewezen: %{path}"
38
43
  auto: "Automatisch"
39
44
  background: "Achtergrond"
40
45
  background_image: "Achtergrondafbeelding"
@@ -77,6 +82,8 @@ nl:
77
82
  dashed: "Gestreept"
78
83
  default: "Standaard"
79
84
  delete: "Verwijderen"
85
+ delete_column: "Kolom verwijderen"
86
+ delete_row: "Rij verwijderen"
80
87
  desktop: "Desktop"
81
88
  divider: "Scheidingslijn"
82
89
  done: "Klaar"
@@ -87,6 +94,7 @@ nl:
87
94
  drag_onto_the_canvas_or_click_to_add: "Sleep naar het canvas, of klik om toe te voegen"
88
95
  drag_to_move: "Sleep om te verplaatsen"
89
96
  drag_to_resize: "Sleep om het formaat te wijzigen"
97
+ drag_to_set_the_column_s_width: "Sleep om de kolombreedte in te stellen"
90
98
  drop_a_cell_here: "Zet hier een cel neer"
91
99
  drop_a_column_here: "Zet hier een kolom neer"
92
100
  drop_a_row_here: "Zet hier een rij neer"
@@ -206,11 +214,13 @@ nl:
206
214
  redo_z: "Opnieuw (⇧⌘Z)"
207
215
  remove: "Verwijderen"
208
216
  remove_link: "Link verwijderen"
217
+ repeat_the_row_in_a_loop: "Rij herhalen in een Loop"
209
218
  repeats_its_blocks_for_each_item_for_variable_in_collection: "Herhaalt zijn blokken voor elk item: {% for variable in collection %}."
210
219
  replace: "Vervangen"
211
220
  right: "Rechts"
212
221
  right_to_left: "Rechts naar links"
213
222
  row: "Rij"
223
+ rows_and_columns: "Rijen en kolommen"
214
224
  rows_of_cells_select_a_cell_to_add_rows_and_columns_put_rows: "Rijen met cellen. Selecteer een cel om rijen en kolommen toe te voegen. Zet rijen in een Loop om ze voor elk item te herhalen."
215
225
  same_tab: "Zelfde tabblad"
216
226
  save: "Opslaan"
@@ -221,6 +231,7 @@ nl:
221
231
  select_the_text_to_translate_first: "Selecteer eerst de tekst om te vertalen."
222
232
  sets_a_liquid_variable_for_the_blocks_after_it_assign_variab: "Zet een Liquid-variabele voor de blokken erna: {% assign variable = value %}."
223
233
  show_panels: "Panelen tonen"
234
+ show_the_row_in_a_condition: "Rij tonen in een Condition"
224
235
  show_translations_in: "Vertalingen tonen in"
225
236
  show_when: "Tonen als"
226
237
  shown_after_the_subject_in_most_inboxes: "In de meeste inboxen getoond na het onderwerp."
@@ -1,3 +1,3 @@
1
1
  module TessEdit
2
- VERSION = "0.5.10"
2
+ VERSION = "0.5.12"
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: tess_edit
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.10
4
+ version: 0.5.12
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tom de Grunt
@@ -105,6 +105,7 @@ files:
105
105
  - app/javascript/tess_edit/core/document.js
106
106
  - app/javascript/tess_edit/core/history.js
107
107
  - app/javascript/tess_edit/core/i18n.js
108
+ - app/javascript/tess_edit/core/liquid.js
108
109
  - app/javascript/tess_edit/core/lock.js
109
110
  - app/javascript/tess_edit/core/media.js
110
111
  - app/javascript/tess_edit/core/registry.js