tess_edit 0.5.11 → 0.5.13

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: ca98a5df42d18e55649fb75c9e3df79e3b4625f76114f362872ed8340bfdee37
4
- data.tar.gz: 25023d749d04c4ddd1e508131354632bcfa5165d9ca0a2166929a9a408ea9728
3
+ metadata.gz: d698da274caf7efb2844c8363a0ff380a4ef3670066cb4499b269764072fd47e
4
+ data.tar.gz: 5417eb85bdb830f23cad6b9f10b1eb5ea7f2657cd63f4901aa23cbda195a61e8
5
5
  SHA512:
6
- metadata.gz: 618cd69b5a1c90e4ca7d8d17882f8e73148eb753d2d3e6bce78e6418f3ff9ec0b4037280f1150bec51a3a16e0f174fa1133221ec06cd7603fe677e7618144baf
7
- data.tar.gz: '0028d406120c409203369393781af3eef1e9863f13b46c43a36168850b9a145b11af3d1e81cb83a2462e2a0a2229d4b4c8d77773572d6c6ff9d365a8cad99e07'
6
+ metadata.gz: 21786e1c39e272ae4e4277edc7781da026fa5bc1b303196e40025975dbcaf25895b0dd851d369957266ef357d319033e1cea3415ecf4a141019d596f1c4054ca
7
+ data.tar.gz: bb0f6e5f47e92ebdcfb4cc22d2881d722737d7cf8a2cf8a0fb990e9a746688911b65df8293e75432b4fdb9ca22ac7d3c4748a1965745b55d930cfd592672c7cf
data/README.md CHANGED
@@ -18,7 +18,7 @@ It completes Liquid tags and variables as you type, making it easier to work wit
18
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.
19
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.
20
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.
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.
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, after `==` the values of what's compared, after `{%` the tags, a block with its end tag, and in conditions the operators.
22
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.
23
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.
24
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.
@@ -253,9 +253,31 @@ The endpoint answers `GET` with the variables at `path` (the roots without one),
253
253
 
254
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`).
255
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 == `, `!=`, `<>` or `contains`, and after `{% when ` in a `{% case line.kind %}`, the editor suggests them, quoted, with `blank` and `empty`. Inside a Loop, or an open `{% for %}`, `forloop` is a variable too, with its `index`, `first`, `last` and the rest.
259
+
260
+ In a condition (`{% if %}`, `{% unless %}`, `{% elsif %}`, a Condition block) a space after a variable or value suggests the operators: `==`, `!=`, `>`, `contains`, `and`, `or`, ….
261
+
262
+ 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:
263
+
264
+ ```json
265
+ {"filters": [{"name": "where", "label": "Those whose property has the value", "arguments": [{"name": "property", "kind": "property"}, {"name": "value", "kind": "value"}], "keeps": "collection"}]}
266
+ ```
267
+
268
+ An argument's `kind` is `property`, `value` (one the property before it can have), `format` (a date's: the editor suggests strftime formats, each with today in it) 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.
269
+
270
+ With `data-tess-edit-tags-url-value` the editor completes tags after `{%`: first what goes in the block it's in (`elsif`, `else`, `when`, `endif`), then the tags, each with its label. Choosing a block writes its end tag too, with the caret where its arguments go: `{% if | %}{% endif %}`. The endpoint answers `GET` with:
271
+
272
+ ```json
273
+ {"tags": [{"name": "if", "label": "Only when a condition holds", "syntax": "if condition", "block": true}]}
274
+ ```
275
+
276
+ A tag whose `syntax` is more than its name takes arguments. Liquidum's `/liquidum/tags` answers this way, with your app's tags as well; the dummy app's `VariablesController#tags` is an example.
277
+
256
278
  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.
257
279
 
258
- 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.
280
+ A field of your own gets the `{ }` button with `liquid: true`, or `liquid: "expression"` (an Assign's value), `liquid: "condition"` (with its operators) or `liquid: "collection"` (what a loop goes over) for Liquid without braces.
259
281
 
260
282
  ### Translations
261
283
 
@@ -9,7 +9,7 @@ export default {
9
9
  roles: ["body", "content", "row"],
10
10
  accepts: "inherit",
11
11
  defaults: () => ({ data: { expression: "customer.vip" } }),
12
- fields: [{ title: "Condition", fields: [{ key: "data.expression", label: "Show when", type: "text", liquid: "expression", hint: "A Liquid condition, e.g. order.total > 100." }] }],
12
+ fields: [{ title: "Condition", fields: [{ key: "data.expression", label: "Show when", type: "text", liquid: "condition", hint: "A Liquid condition, e.g. order.total > 100." }] }],
13
13
  hint: "Shows its blocks only when the condition is true: {% if expression %}.",
14
14
  label: (node) => `If ${node.data.expression || "…"}`,
15
15
  render: {
@@ -23,6 +23,10 @@
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
28
+ // tagsUrl the tags, suggested after {% (a block with its end tag), e.g.
29
+ // Liquidum's /liquidum/tags
26
30
  // translationsUrl the host's translations for Liquid's t filter ({{ '.greeting' | t }}),
27
31
  // shown in a language chosen in the top bar, listed and edited
28
32
  // while pointed at, and made from selected text (see
@@ -61,7 +65,8 @@ import { COMPILE_URL } from "tess_edit/export/compile"
61
65
  import { IMAGE_FIELD, fetchMedia, uploadMedia } from "tess_edit/core/media"
62
66
  import { Translations, keysIn, suggestKey, toTranslation, translationTag } from "tess_edit/core/translations"
63
67
  import { Values } from "tess_edit/core/values"
64
- import { Variables, loopScope } from "tess_edit/core/variables"
68
+ import { Variables } from "tess_edit/core/variables"
69
+ import { liquidScope } from "tess_edit/core/liquid"
65
70
  import { addColumn, addRow, cellOf, columnCount, deleteColumn, deleteRow, nextCell, position, rows, wrapRow } from "tess_edit/core/table"
66
71
  import { Canvas } from "tess_edit/ui/canvas"
67
72
  import { freeChild, number } from "tess_edit/ui/free_layout"
@@ -93,7 +98,7 @@ function placed(node, at) {
93
98
  }
94
99
 
95
100
  export default class extends Controller {
96
- 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 }
101
+ 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, tagsUrl: String, translationsUrl: String, values: String, lock: String, blocks: String, options: String }
97
102
  static targets = ["jsonInput", "mjmlInput", "htmlInput", "slot", "translations"]
98
103
 
99
104
  connect() {
@@ -123,7 +128,7 @@ export default class extends Controller {
123
128
  this.sheetOpen = false
124
129
  this.requests = {}
125
130
  this.media = { enabled: Boolean(this.mediaUrlValue), images: [], uploading: false, error: null }
126
- this.variables = new Variables(this.variablesUrlValue)
131
+ this.variables = new Variables(this.variablesUrlValue, { filtersUrl: this.filtersUrlValue, tagsUrl: this.tagsUrlValue })
127
132
  this.translations = new Translations(this.translationsUrlValue)
128
133
  this.translationPopover = this.translations.enabled ? new TranslationPopover(this) : null
129
134
  this.values = new Values()
@@ -163,7 +168,7 @@ export default class extends Controller {
163
168
  // Points the editor at other variables (variablesUrl), once it's connected
164
169
  variablesUrlValueChanged() {
165
170
  if (!this.variables) return
166
- this.variables = new Variables(this.variablesUrlValue)
171
+ this.variables = new Variables(this.variablesUrlValue, { filtersUrl: this.filtersUrlValue, tagsUrl: this.tagsUrlValue })
167
172
  if (!this.variableMenu && this.variables.enabled) {
168
173
  this.variableMenu = new VariableMenu(this)
169
174
  this.textEditing.menu = this.variableMenu
@@ -838,7 +843,7 @@ export default class extends Controller {
838
843
  this.scheduleOutputs()
839
844
  }
840
845
  if (part.plain) this.textEditing.startPlain(container, getValue(hit.node, part.key), update, () => this.stopEditing())
841
- else this.textEditing.start(container, getValue(hit.node, part.key), update, { scope: loopScope(this.doc, id) })
846
+ else this.textEditing.start(container, getValue(hit.node, part.key), update, { scope: liquidScope(this.doc, id) })
842
847
  this.canvas.refresh()
843
848
  }
844
849
 
@@ -0,0 +1,234 @@
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
+ // "{% el" → { kind: "tag", partial: "el", open: ["if"] }
11
+ // "{% if line.party " → { kind: "operator", partial: "" }
12
+ //
13
+ // each with `start`, where what it replaces starts in the text, and `tag`
14
+ // ("{{", "{%" or null). In "output" mode (Liquid in text) only inside {{ … }}
15
+ // or {% … %}; in "expression" mode (a Loop's collection, an Assign's value)
16
+ // anywhere, and in "condition" mode (a Condition) too, with its operators as
17
+ // in {% if %}. A tag's `open` are the blocks open before it, innermost last,
18
+ // for what can go inside them (elsif, when, endfor); `blocks` says which tags
19
+ // are blocks besides Liquid's. The editor's menu (ui/variable_menu.js) asks the
20
+ // host for what fits: its variables, its filters and their arguments, the
21
+ // values a variable can have (core/variables.js).
22
+ //
23
+ // liquidScope says which variables a block has besides the host's: its Loop
24
+ // blocks' and the Assigns before it, nearest first. An Assign's variable is
25
+ // what its expression comes to; through filters that keep a collection what
26
+ // it is (where, sort, …) it's still that collection (core/variables.js).
27
+
28
+ import { find } from "tess_edit/core/document"
29
+
30
+ const PATH = /[A-Za-z_][\w]*(?:\.[\w]*)*/
31
+ const NAME = /^\w+$/
32
+ // Liquid's tags that are blocks, with an end tag
33
+ export const BLOCKS = ["capture", "case", "comment", "for", "if", "ifchanged", "raw", "tablerow", "unless"]
34
+ // Words in conditions that aren't variables
35
+ const KEYWORDS = new Set(["if", "unless", "elsif", "when", "and", "or", "contains", "in", "blank", "empty", "nil", "null", "true", "false"])
36
+ // An operand in a condition: a variable, a quoted text or a number
37
+ const OPERAND = new RegExp(`(?:${PATH.source}|"[^"]*"|'[^']*'|-?\\d+(?:\\.\\d+)?)`)
38
+
39
+ // The block tags open at the end of a text, outermost first, each { name, expression }
40
+ export function openBlocks(text, blocks = BLOCKS) {
41
+ const open = []
42
+ for (const match of text.matchAll(/\{%-?\s*(\w+)([\s\S]*?)-?%\}/g)) {
43
+ const name = match[1]
44
+ if (name.startsWith("end")) {
45
+ const at = open.map((block) => block.name).lastIndexOf(name.slice(3))
46
+ if (at >= 0) open.splice(at)
47
+ } else if (blocks.includes(name)) {
48
+ open.push({ name, expression: match[2].trim() })
49
+ }
50
+ }
51
+ return open
52
+ }
53
+
54
+ // The parts of a Liquid expression outside quotes, split at `separator`
55
+ // (| between filters, , between arguments)
56
+ export function splitOutside(text, separator) {
57
+ const parts = []
58
+ let quote = null
59
+ let current = ""
60
+ for (const char of text) {
61
+ if (quote) {
62
+ if (char === quote) quote = null
63
+ } else if (char === '"' || char === "'") {
64
+ quote = char
65
+ } else if (char === separator) {
66
+ parts.push(current)
67
+ current = ""
68
+ continue
69
+ }
70
+ current += char
71
+ }
72
+ parts.push(current)
73
+ return parts
74
+ }
75
+
76
+ // The quote a text ends inside, and where it opened, if it does
77
+ function openQuote(text) {
78
+ let quote = null
79
+ let at = -1
80
+ for (let i = 0; i < text.length; i++) {
81
+ const char = text[i]
82
+ if (quote) {
83
+ if (char === quote) quote = null
84
+ } else if (char === '"' || char === "'") {
85
+ quote = char
86
+ at = i
87
+ }
88
+ }
89
+ return quote ? { quote, at } : null
90
+ }
91
+
92
+ // A quoted argument's text, or the argument as written
93
+ export function unquote(text) {
94
+ const trimmed = text.trim()
95
+ const match = trimmed.match(/^(["'])(.*)\1$/)
96
+ return match ? match[2] : trimmed
97
+ }
98
+
99
+ export function liquidContext(before, mode = "output", { blocks = BLOCKS } = {}) {
100
+ let expression = before
101
+ let tag = null
102
+ let opened = 0
103
+ if (mode === "output") {
104
+ const output = before.lastIndexOf("{{")
105
+ const open = Math.max(output, before.lastIndexOf("{%"))
106
+ if (open < 0 || Math.max(before.lastIndexOf("}}"), before.lastIndexOf("%}")) > open) return null
107
+ tag = open === output ? "{{" : "{%"
108
+ opened = open
109
+ expression = before.slice(open + 2).replace(/^-/, "")
110
+ }
111
+ const offset = before.length - expression.length
112
+ const quoted = openQuote(expression)
113
+ const head = quoted ? expression.slice(0, quoted.at) : expression
114
+
115
+ // A tag's name: {% el
116
+ const named = tag === "{%" && !quoted && expression.match(/^\s*(\w*)$/)
117
+ if (named) return { kind: "tag", start: before.length - named[1].length, partial: named[1], open: openBlocks(before.slice(0, opened), blocks).map((block) => block.name), tag }
118
+
119
+ // A case's values: {% when "a", "b
120
+ const when = tag === "{%" && head.match(/^\s*when\s+((?:(?:"[^"]*"|'[^']*'|[\w.]+)\s*(?:,|\bor\b)\s*)*)$/)
121
+ if (when) {
122
+ const kase = openBlocks(before.slice(0, opened), blocks).filter((block) => block.name === "case").at(-1)
123
+ const of = kase?.expression.match(new RegExp(`^${PATH.source}`))?.[0]
124
+ if (!of) return null
125
+ const partial = quoted ? expression.slice(quoted.at + 1) : ""
126
+ if (!quoted && !/(?:\s|,)$/.test(expression)) return null
127
+ return { kind: "value", of, start: quoted ? offset + quoted.at : before.length, partial, quote: quoted?.quote || null, tag }
128
+ }
129
+
130
+ // In a filter's arguments: | name: a, b, …
131
+ const filters = splitOutside(head, "|")
132
+ if (filters.length > 1) {
133
+ const current = filters.at(-1)
134
+ const input = filters.slice(0, -1).join("|").trim()
135
+ const named = current.match(/^\s*(\w*)$/)
136
+ if (named && !quoted) return { kind: "filter", start: before.length - named[1].length, partial: named[1], input, tag }
137
+
138
+ const call = current.match(/^\s*(\w+)\s*:([\s\S]*)$/)
139
+ if (call) {
140
+ const args = splitOutside(call[2], ",")
141
+ const written = args.slice(0, -1).map(unquote)
142
+ if (quoted) {
143
+ const partial = expression.slice(quoted.at + 1)
144
+ return { kind: "argument", filter: call[1], index: args.length - 1, args: written, start: offset + quoted.at, partial, quote: quoted.quote, input, tag }
145
+ }
146
+ const last = args.at(-1)
147
+ const path = last.match(new RegExp(`^\\s*(${PATH.source})?$`))
148
+ if (path) {
149
+ const partial = path[1] || ""
150
+ return { kind: "argument", filter: call[1], index: args.length - 1, args: written, start: before.length - partial.length, partial, quote: null, input, tag }
151
+ }
152
+ return null
153
+ }
154
+ if (quoted) return null
155
+ }
156
+
157
+ // A value compared with a variable: line.party == "sp
158
+ // (unquoted, a word: blank, empty, or a variable's name)
159
+ const compared = quoted
160
+ ? head.match(new RegExp(`(${PATH.source})\\s*(?:==|!=|<>|\\bcontains\\b)\\s*$`))
161
+ : expression.match(new RegExp(`(${PATH.source})\\s*(?:==|!=|<>|\\bcontains)\\s*(\\w*)$`))
162
+ if (compared && !KEYWORDS.has(compared[1])) {
163
+ const partial = quoted ? expression.slice(quoted.at + 1) : compared[2]
164
+ return { kind: "value", of: compared[1], start: quoted ? offset + quoted.at : before.length - partial.length, partial, quote: quoted?.quote || null, tag }
165
+ }
166
+ if (quoted) return null
167
+
168
+ // An operator after an operand in a condition: {% if line.party co
169
+ const condition = mode === "condition" || (tag === "{%" && /^\s*(?:if|unless|elsif)\b/.test(expression))
170
+ const operator = condition && expression.match(new RegExp(`(?:^|\\s)(${OPERAND.source})\\s+([=!<>]*|[a-z]*)$`))
171
+ if (operator && !KEYWORDS.has(operator[1])) return { kind: "operator", start: before.length - operator[2].length, partial: operator[2], tag }
172
+
173
+ const match = expression.match(new RegExp(`(?:^|[^\\w.])(${PATH.source})?$`))
174
+ if (!match) return null
175
+ const path = match[1] || ""
176
+ return { kind: "variable", start: before.length - path.length, path, tag }
177
+ }
178
+
179
+ // The variable path an expression starts from, and the filters after it:
180
+ // 'contract.lines | where: "party", "account" | sort' → { path: "contract.lines", filters: ["where", "sort"] }
181
+ // In a tag, the path is the last one before the first |: "assign x = order.lines"
182
+ export function expressionParts(expression) {
183
+ const [first, ...rest] = splitOutside(expression, "|")
184
+ const paths = first.replace(/(["'])[\s\S]*?\1/g, " ").match(new RegExp(PATH.source, "g")) || []
185
+ const path = paths.filter((candidate) => !["assign", "for", "in", "if", "unless", "elsif", "and", "or", "contains"].includes(candidate)).at(-1)
186
+ if (!path) return null
187
+ return { path, filters: rest.map((filter) => filter.trim().match(/^\w+/)?.[0]).filter(Boolean) }
188
+ }
189
+
190
+ // The variables a block can use: its Loops' and the Assigns before it (in
191
+ // its container, or in one around it), nearest first
192
+ // [{ variable, collection }] a Loop's: each of a collection
193
+ // [{ variable, expression }] an Assign's: what its expression comes to
194
+ export function liquidScope(doc, id) {
195
+ const scope = []
196
+ let hit = find(doc, id)
197
+ while (hit?.parent) {
198
+ for (const sibling of hit.parent.children.slice(0, hit.index).reverse()) {
199
+ if (sibling.type !== "assign") continue
200
+ const { variable, expression } = sibling.data || {}
201
+ if (NAME.test(variable || "") && expression) scope.push({ variable, expression })
202
+ }
203
+ if (hit.parent.type === "loop") {
204
+ const variable = hit.parent.data.variable || "item"
205
+ const collection = hit.parent.data.collection || "items"
206
+ if (NAME.test(variable)) scope.push({ variable, collection })
207
+ }
208
+ hit = find(doc, hit.parent.id)
209
+ }
210
+ return scope
211
+ }
212
+
213
+ // The assigns ({% assign x = … %}) and loops ({% for x in … %}) earlier in a
214
+ // text, before the caret, nearest first, as liquidScope gives them
215
+ export function textScope(before) {
216
+ const scope = []
217
+ for (const match of before.matchAll(/\{%-?\s*(assign|for)\s+(\w+)\s*(=|in)\s*([\s\S]*?)\s*-?%\}/g)) {
218
+ if (match[1] === "assign" && match[3] === "=") scope.unshift({ variable: match[2], expression: match[4] })
219
+ if (match[1] === "for" && match[3] === "in") {
220
+ // Only while the loop is open
221
+ const after = before.slice(match.index + match[0].length)
222
+ if (!/\{%-?\s*endfor\b/.test(after)) scope.unshift({ variable: match[2], collection: match[4].split(/\s/)[0] })
223
+ }
224
+ }
225
+ return scope
226
+ }
227
+
228
+ // What replaces a quoted argument or value, in the quote it was started
229
+ // with, and how much of the text after the caret it takes: its closing quote,
230
+ // when that's there already
231
+ export function quoted(value, { quote = null, after = "" } = {}) {
232
+ const mark = quote || '"'
233
+ return { text: `${mark}${value}${mark}`, through: after.startsWith(mark) ? 1 : 0 }
234
+ }
@@ -11,10 +11,44 @@
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.
25
+ // The tags, for what follows {%, from its tagsUrl:
26
+ //
27
+ // GET → { tags: [{ name, label, syntax, block }] }
28
+ //
29
+ // as Liquidum's TagsController answers. Inside a Loop there's `forloop` too.
15
30
 
16
31
  import { ancestors } from "tess_edit/core/document"
17
32
  import { t } from "tess_edit/core/i18n"
33
+ import { expressionParts } from "tess_edit/core/liquid"
34
+
35
+ // What filters on a collection leave, without the host's: the same items, or one
36
+ export const KEEPS = {
37
+ where: "collection", where_exp: "collection", reject: "collection", sort: "collection", sort_natural: "collection",
38
+ reverse: "collection", uniq: "collection", compact: "collection", concat: "collection",
39
+ first: "item", last: "item", find: "item"
40
+ }
41
+
42
+ // What Liquid's forloop has, inside a loop
43
+ export const FORLOOP_MEMBERS = [
44
+ { name: "index", label: "Its number, from 1", type: "integer", children: false },
45
+ { name: "index0", label: "Its number, from 0", type: "integer", children: false },
46
+ { name: "rindex", label: "Its number from the end, to 1", type: "integer", children: false },
47
+ { name: "rindex0", label: "Its number from the end, to 0", type: "integer", children: false },
48
+ { name: "first", label: "Whether it's the first", type: "boolean", children: false },
49
+ { name: "last", label: "Whether it's the last", type: "boolean", children: false },
50
+ { name: "length", label: "Number of items", type: "integer", children: false }
51
+ ]
18
52
 
19
53
  // The members Liquid gives every collection
20
54
  export const COLLECTION_MEMBERS = [
@@ -26,12 +60,59 @@ export const COLLECTION_MEMBERS = [
26
60
  const ELEMENT = new Set(["first", "last"])
27
61
 
28
62
  export class Variables {
29
- constructor(url, { fetch: fetcher = (...args) => fetch(...args) } = {}) {
63
+ constructor(url, { fetch: fetcher = (...args) => fetch(...args), filtersUrl = null, tagsUrl = null } = {}) {
30
64
  this.url = url
65
+ this.filtersUrl = filtersUrl
66
+ this.tagsUrl = tagsUrl
31
67
  this.fetch = fetcher
32
68
  this.levels = new Map()
33
69
  }
34
70
 
71
+ // The host's filters, by name, cached; none without its filtersUrl
72
+ filters() {
73
+ if (!this.filtersUrl) return Promise.resolve(new Map())
74
+ this.filterList ||= this.get(this.filtersUrl, {}).then((body) => new Map((body.filters || []).map((filter) => [filter.name, filter])))
75
+ this.filterList.catch(() => (this.filterList = null))
76
+ return this.filterList
77
+ }
78
+
79
+ // The host's tags, by name, cached; none without its tagsUrl
80
+ tags() {
81
+ if (!this.tagsUrl) return Promise.resolve(new Map())
82
+ this.tagList ||= this.get(this.tagsUrl, {}).then((body) => new Map((body.tags || []).map((tag) => [tag.name, tag])))
83
+ this.tagList.catch(() => (this.tagList = null))
84
+ return this.tagList
85
+ }
86
+
87
+ async get(path, params) {
88
+ const url = new URL(path, window.location.href)
89
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value)
90
+ const response = await this.fetch(url, { headers: { Accept: "application/json" }, credentials: "same-origin" })
91
+ if (!response.ok) throw new Error(t("Loading the variables failed (%{status})", { status: `${response.status} ${response.statusText}` }))
92
+ return response.json()
93
+ }
94
+
95
+ // A scope from core/liquid.js with its Assigns made paths: a Loop's
96
+ // variable and an Assign of one item ({ variable, collection }) are each of
97
+ // a collection; an Assign of a collection or a value ({ variable, path })
98
+ // stands for its path. One that can't be followed isn't there.
99
+ async resolveScope(scope = []) {
100
+ if (!scope.some((entry) => entry.expression)) return scope
101
+ const filters = await this.filters().catch(() => new Map())
102
+ return scope.flatMap((entry) => {
103
+ if (!entry.expression) return [entry]
104
+ const parts = expressionParts(entry.expression)
105
+ if (!parts) return []
106
+ let item = false
107
+ for (const name of parts.filters) {
108
+ const keeps = filters.get(name)?.keeps ?? KEEPS[name]
109
+ if (keeps === "item" && !item) item = true
110
+ else if (keeps !== "collection") return []
111
+ }
112
+ return [item ? { variable: entry.variable, collection: parts.path } : { variable: entry.variable, path: parts.path }]
113
+ })
114
+ }
115
+
35
116
  get enabled() {
36
117
  return Boolean(this.url)
37
118
  }
@@ -59,21 +140,41 @@ export class Variables {
59
140
  // in a loop over order.order_lines, or "order.order_lines" (a collection:
60
141
  // first, last and size). scope is from loopScope.
61
142
  async options(path, scope = []) {
143
+ scope = await this.resolveScope(scope)
62
144
  const names = path ? path.split(".") : []
63
- if (!names.length) return [...scope.map(loopVariable), ...(await this.at(""))]
145
+ if (!names.length) {
146
+ const own = []
147
+ for (const [index, entry] of scope.entries()) {
148
+ if (own.some((variable) => variable.name === entry.variable)) continue
149
+ // What it stands for, of the scope around it
150
+ const target = entry.path && (await this.variable(entry.path.split("."), scope.slice(index + 1)))
151
+ own.push(entry.path ? { ...(target || { children: false }), name: entry.variable, label: t("Assigned %{path}", { path: entry.path }), assign: true } : loopVariable(entry))
152
+ }
153
+ if (scope.some((entry) => entry.collection)) own.push(FORLOOP)
154
+ return [...own, ...(await this.at(""))]
155
+ }
64
156
 
65
157
  const variable = await this.variable(names, scope)
66
158
  if (!variable?.children) return []
159
+ if (variable.forloop) return FORLOOP_MEMBERS
67
160
  if (variable.collection) return COLLECTION_MEMBERS
68
161
  return this.at(resolve(names, scope))
69
162
  }
70
163
 
164
+ // The variable a path as written comes to, with a scope from core/liquid.js
165
+ async lookup(path, scope = []) {
166
+ if (!path) return null
167
+ return this.variable(path.split("."), await this.resolveScope(scope))
168
+ }
169
+
71
170
  // What the last name of a path is: a variable with children, a collection, …
72
171
  async variable(names, scope) {
73
172
  const last = names[names.length - 1]
74
173
  const parent = names.slice(0, -1)
75
174
  if (!parent.length) {
76
175
  const own = scope.find((entry) => entry.variable === last)
176
+ if (last === "forloop" && !own && scope.some((entry) => entry.collection)) return FORLOOP
177
+ if (own?.path) return { ...(await this.variable(own.path.split("."), scope.slice(scope.indexOf(own) + 1))), name: last }
77
178
  if (own) return loopVariable(own)
78
179
  } else if (ELEMENT.has(last)) {
79
180
  const collection = await this.variable(parent, scope)
@@ -84,6 +185,8 @@ export class Variables {
84
185
  }
85
186
  }
86
187
 
188
+ const FORLOOP = { name: "forloop", label: "This loop", type: "object", children: true, forloop: true }
189
+
87
190
  function loopVariable({ variable, collection }) {
88
191
  return { name: variable, label: t("Each of %{collection}", { collection }), type: "object", children: true, loop: true }
89
192
  }
@@ -94,8 +197,8 @@ export function resolve(names, scope = []) {
94
197
  let resolved = [...names]
95
198
  // Inner loops first: their collection can start with an outer loop's variable
96
199
  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)]
200
+ for (const { variable, collection, path } of scope) {
201
+ if (resolved[0] === variable && (collection || path)) resolved = [...(collection || path).split("."), ...resolved.slice(1)]
99
202
  }
100
203
  }
101
204
  return resolved.filter((name) => !ELEMENT.has(name) && !/^\d+$/.test(name)).join(".")
@@ -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"
@@ -342,13 +342,14 @@ export class Inspector {
342
342
 
343
343
  // Suggests the host's Liquid variables (editor.variables) while typing {{ in
344
344
  // a text field. A field's `liquid` also gives it a { } button to browse
345
- // them: true for Liquid in text, "expression" for a condition, "collection"
345
+ // them: true for Liquid in text, "expression" for an expression (an
346
+ // Assign's), "condition" for a condition, with its operators, "collection"
346
347
  // for what a Loop goes over.
347
348
  variables(input, node, field) {
348
349
  this.inputs.set(field.key, input)
349
350
  if (!this.editor.variableMenu) return input
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 mode = ["expression", "condition", "collection"].includes(field.liquid) ? field.liquid : "output"
352
+ const adapter = inputAdapter(input, { mode, scope: liquidScope(this.editor.doc, node.id) })
352
353
  suggestIn(this.editor.variableMenu, input, adapter)
353
354
  this.adapters.set(field.key, adapter)
354
355
  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()
@@ -269,9 +269,11 @@ function tiptapAdapter(editor, scope) {
269
269
  const $to = editor.state.selection.$to
270
270
  return text($to, $to.parentOffset, $to.parent.content.size)
271
271
  },
272
- replace(start, end, value) {
272
+ // `caret`: where in `value` the caret goes, else after it
273
+ replace(start, end, value, { caret = null } = {}) {
273
274
  const base = editor.state.selection.$from.start()
274
275
  dispatch(base + start, base + end, value)
276
+ if (caret !== null) editor.commands.setTextSelection(base + start + caret)
275
277
  },
276
278
  insert(value) {
277
279
  const { from, to } = editor.state.selection
@@ -4,17 +4,27 @@
4
4
  //
5
5
  // before() the text before the caret (in the line or paragraph)
6
6
  // after() the text after it
7
- // replace(start, end, text) replaces part of before() + after(), by offsets in it
7
+ // replace(start, end, text, { caret }) replaces part of before() + after(), by
8
+ // offsets in it, the caret after it or at `caret` in it
8
9
  // rect() where to show the menu, in the page's viewport
9
- // mode "output" (Liquid in text: {{ … }}), "expression" (a
10
- // Condition) or "collection" (a Loop's collection)
10
+ // mode "output" (Liquid in text: {{ … }}), "expression" (an
11
+ // Assign's value), "condition" (a Condition, with its
12
+ // operators) or "collection" (a Loop's collection)
11
13
  // scope the loop variables there (core/variables.js loopScope)
12
14
  //
13
15
  // See inputAdapter below and TextEditing for Tiptap's. With the host's
14
- // translations it also suggests their keys while typing {{ '.
16
+ // translations it also suggests their keys while typing {{ '. What it
17
+ // suggests depends on what's being written (core/liquid.js liquidContext): a
18
+ // variable; after a |, the host's filters; a filter's argument, a property of
19
+ // the collection's items ("party") or a value it can have ("sponsor"); after
20
+ // == or !=, the values of the variable compared, and blank and empty; after
21
+ // {%, the tags (a block written with its end tag), and those that go in the
22
+ // blocks open there (elsif, when, endfor); in a condition, its operators; and
23
+ // a date's formats, each shown with today's date in it.
15
24
 
25
+ import { BLOCKS, expressionParts, liquidContext, quoted, textScope } from "tess_edit/core/liquid"
16
26
  import { keyCompletion, keyToken } from "tess_edit/core/translations"
17
- import { completion, liquidToken } from "tess_edit/core/variables"
27
+ import { completion } from "tess_edit/core/variables"
18
28
  import { t } from "tess_edit/core/i18n"
19
29
  import { h } from "tess_edit/ui/dom"
20
30
 
@@ -47,27 +57,153 @@ export class VariableMenu {
47
57
  const key = this.editor.translations?.enabled && adapter.mode === "output" && keyToken(before)
48
58
  if (key) return this.suggestKeys(adapter, key)
49
59
  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
60
+ const mode = adapter.mode === "output" || adapter.mode === "condition" ? adapter.mode : "expression"
61
+ const hostTags = adapter.mode === "output" && before.includes("{%") ? await this.editor.variables.tags().catch(() => new Map()) : new Map()
62
+ const blocks = [...BLOCKS, ...[...hostTags.values()].filter((tag) => tag.block).map((tag) => tag.name)]
63
+ const context = liquidContext(before, mode, { blocks })
64
+ if (!context) return this.close()
65
+ const scope = [...textScope(before), ...(adapter.scope || [])]
57
66
  const request = ++this.request
58
- let items
67
+ let found
59
68
  try {
60
- items = await this.editor.variables.options(parent, adapter.scope)
69
+ found = await this.options(context, scope)
61
70
  } catch (error) {
62
- items = []
71
+ found = null
63
72
  }
64
73
  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()
74
+ if (!found?.items.length) return this.close()
75
+ this.show({ adapter, browse: false, items: found.items, index: 0, choose: found.choose })
76
+ }
77
+
78
+ // What fits a context, those starting with what's typed first, then those
79
+ // whose label has it: { items, choose }
80
+ async options(context, scope) {
81
+ const variables = this.editor.variables
82
+ if (context.kind === "variable") return this.variableOptions(context, context.path, scope)
83
+ if (context.kind === "filter") {
84
+ const filters = [...(await variables.filters()).values()]
85
+ const items = ranked(filters.map((filter) => ({ name: filter.name, label: filter.label, hint: signature(filter), filter })), context.partial)
86
+ if (items.length === 1 && items[0].name === context.partial && !items[0].filter.arguments?.length) return null
87
+ return {
88
+ items,
89
+ choose: async (item) => {
90
+ const adapter = this.state.adapter
91
+ const more = item.filter.arguments?.length > 0
92
+ adapter.replace(context.start, adapter.before().length, more ? `${item.name}: ` : item.name)
93
+ more ? await this.suggest(adapter) : this.close()
94
+ }
95
+ }
96
+ }
97
+ if (context.kind === "argument") {
98
+ const filter = (await variables.filters()).get(context.filter)
99
+ const kind = filter?.arguments?.[context.index]?.kind
100
+ const more = filter?.arguments?.length > context.index + 1
101
+ if (kind === "format") {
102
+ const formats = DATE_FORMATS.map((format) => ({ value: format, label: strftime(new Date(), format) }))
103
+ return this.quotedOptions({ ...context, quote: context.quote || "'" }, formats, more)
104
+ }
105
+ if (kind === "property" || kind === "value") {
106
+ const elements = await this.elements(context.input, scope)
107
+ if (!elements) return null
108
+ const choices = kind === "property"
109
+ ? elements.map((variable) => ({ value: variable.name, label: variable.label }))
110
+ : elements.find((variable) => variable.name === context.args[context.index - 1])?.values || []
111
+ return this.quotedOptions(context, choices, more)
112
+ }
113
+ return context.quote ? null : this.variableOptions(context, context.partial, scope)
114
+ }
115
+ if (context.kind === "value") {
116
+ const variable = await variables.lookup(context.of, scope)
117
+ const values = this.quotedOptions(context, variable?.values || [], false, context.quote ? [] : LITERALS)
118
+ // Unquoted, it may be another variable: line.total > order.minimum
119
+ return values || context.quote || !context.partial ? values : this.variableOptions(context, context.partial, scope)
120
+ }
121
+ if (context.kind === "tag") return this.tagOptions(context, await variables.tags())
122
+ if (context.kind === "operator") {
123
+ const items = ranked(OPERATORS.map(([name, label]) => ({ name, label })), context.partial)
124
+ if (items.length === 1 && items[0].name === context.partial) return null
125
+ return {
126
+ items,
127
+ choose: async (item) => {
128
+ const adapter = this.state.adapter
129
+ adapter.replace(context.start, adapter.before().length, `${item.name} `)
130
+ await this.suggest(adapter)
131
+ }
132
+ }
133
+ }
134
+ return null
135
+ }
136
+
137
+ // After {%: what goes in the innermost open block (elsif, else, its end),
138
+ // then the tags. A block is written with its end tag, the caret where its
139
+ // arguments go; one closed already (%} after the caret) only gets its name.
140
+ tagOptions(context, tags) {
141
+ const inner = context.open.at(-1)
142
+ const inside = (INSIDE[inner] || []).map(([name, label]) => ({ name, label, inside: true }))
143
+ const end = inner ? [{ name: `end${inner}`, label: t("Ends the %{tag}", { tag: inner }), inside: true }] : []
144
+ const own = [...tags.values()].map((tag) => ({ name: tag.name, label: tag.label, hint: tag.syntax, tag }))
145
+ const items = ranked([...inside, ...end, ...own], context.partial)
146
+ if (!items.length) return null
147
+ return {
148
+ items,
149
+ choose: (item) => {
150
+ const adapter = this.state.adapter
151
+ const closed = /^\s*-?%\}/.test(adapter.after())
152
+ const before = adapter.before()
153
+ const takes = item.tag ? item.tag.syntax !== item.name : ["elsif", "when"].includes(item.name)
154
+ const block = item.tag?.block && !closed
155
+ const close = closed ? "" : " %}"
156
+ const head = takes ? `${item.name} ` : `${item.name}${close}`
157
+ const text = takes ? `${head}${close}` : head
158
+ const tail = block ? `{% end${item.name} %}` : ""
159
+ adapter.replace(context.start, before.length, `${text}${tail}`, { caret: takes ? head.length : text.length })
160
+ this.close()
161
+ }
162
+ }
163
+ }
164
+
165
+ // The variables for a path being typed, from `context.start`
166
+ async variableOptions(context, path, scope) {
167
+ const dot = path.lastIndexOf(".")
168
+ const parent = dot < 0 ? "" : path.slice(0, dot)
169
+ const partial = path.slice(dot + 1)
170
+ const start = context.start + dot + 1
171
+ const items = ranked(await this.editor.variables.options(parent, scope), partial)
172
+ if (items.length === 1 && items[0].name.toLowerCase() === partial.toLowerCase() && !items[0].children) return null
173
+ return { items, choose: (item) => this.complete(this.state.adapter, context, start, item) }
174
+ }
175
+
176
+ // The variables of a collection's items, for a filter on it: in
177
+ // `lines | where: "`, those of each line
178
+ async elements(input, scope) {
179
+ const parts = expressionParts(input)
180
+ if (!parts) return null
181
+ const [entry] = await this.editor.variables.resolveScope([{ variable: "\u0000", expression: input }])
182
+ if (!entry?.path) return null
183
+ const collection = await this.editor.variables.lookup(entry.path, scope)
184
+ if (!collection?.collection) return null
185
+ return this.editor.variables.options(`${entry.path}.first`, scope)
186
+ }
69
187
 
70
- this.show({ adapter, browse: false, items, index: 0, choose: (item) => this.complete(adapter, token, start, item) })
188
+ // Values in quotes ({ value, label }), then a comma for the next argument;
189
+ // and `literals` as they are (blank, empty)
190
+ quotedOptions(context, choices, more, literals = []) {
191
+ const mark = context.quote || '"'
192
+ const items = ranked([
193
+ ...choices.map((choice) => ({ name: `${mark}${choice.value}${mark}`, value: choice.value, label: choice.label })),
194
+ ...literals.map(([name, label]) => ({ name, value: name, label, literal: true }))
195
+ ], context.partial, (item) => item.value)
196
+ if (!items.length || (items.length === 1 && items[0].value === context.partial)) return null
197
+ return {
198
+ items,
199
+ choose: async (item) => {
200
+ const adapter = this.state.adapter
201
+ const before = adapter.before()
202
+ const { text, through } = item.literal ? { text: item.value, through: 0 } : quoted(item.value, { quote: context.quote, after: adapter.after() })
203
+ adapter.replace(context.start, before.length + through, more ? `${text}, ` : text)
204
+ more ? await this.suggest(adapter) : this.close()
205
+ }
206
+ }
71
207
  }
72
208
 
73
209
  // The translation keys with what's typed, those that start with it first,
@@ -94,6 +230,7 @@ export class VariableMenu {
94
230
  }
95
231
 
96
232
  async complete(adapter, token, start, item) {
233
+ if (!adapter) return
97
234
  const before = adapter.before()
98
235
  const { text, more } = completion(item, { tag: token.tag, before: before.slice(0, start), after: adapter.after(), collection: adapter.mode === "collection" })
99
236
  adapter.replace(start, before.length, text)
@@ -239,8 +376,9 @@ export function inputAdapter(input, { mode = "output", scope = [] } = {}) {
239
376
  scope,
240
377
  before: () => input.value.slice(0, input.selectionStart ?? input.value.length),
241
378
  after: () => input.value.slice(input.selectionEnd ?? input.value.length),
242
- replace(start, end, text) {
379
+ replace(start, end, text, { caret = null } = {}) {
243
380
  input.setRangeText(text, start, end, "end")
381
+ if (caret !== null) input.setSelectionRange(start + caret, start + caret)
244
382
  fire()
245
383
  },
246
384
  insert(text) {
@@ -259,3 +397,50 @@ export function suggestIn(menu, input, adapter) {
259
397
  input.addEventListener("keydown", (event) => menu.key(event))
260
398
  input.addEventListener("blur", () => !menu.state?.browse && menu.close())
261
399
  }
400
+
401
+ // Those whose name (or `name(item)`) starts with what's typed, then those
402
+ // whose label has it
403
+ function ranked(items, partial, name = (item) => item.name) {
404
+ const typed = (partial || "").toLowerCase()
405
+ const named = items.filter((item) => name(item).toLowerCase().startsWith(typed))
406
+ return [...named, ...items.filter((item) => !named.includes(item) && item.label?.toLowerCase().includes(typed))]
407
+ }
408
+
409
+ // A filter as it's written: date: format
410
+ function signature(filter) {
411
+ const args = (filter.arguments || []).map((argument) => argument.name)
412
+ return args.length ? `${filter.name}: ${args.join(", ")}` : filter.name
413
+ }
414
+
415
+ // The operators in a condition
416
+ const OPERATORS = [
417
+ ["==", "Equals"], ["!=", "Doesn't equal"], [">", "More than"], ["<", "Less than"], [">=", "At least"], ["<=", "At most"],
418
+ ["contains", "Contains"], ["and", "And"], ["or", "Or"]
419
+ ]
420
+
421
+ // What a value can be compared with besides its values
422
+ const LITERALS = [["blank", "Blank: nothing, or only spaces"], ["empty", "Empty: no items or text"]]
423
+
424
+ // The tags inside a block
425
+ const INSIDE = {
426
+ if: [["elsif", "Or else when a condition holds"], ["else", "Otherwise"]],
427
+ unless: [["elsif", "Or else when a condition holds"], ["else", "Otherwise"]],
428
+ case: [["when", "When it's one of these values"], ["else", "Otherwise"]],
429
+ for: [["break", "Stops the loop"], ["continue", "Goes on with the next item"], ["else", "When there are no items"]]
430
+ }
431
+
432
+ // A date's formats, as Ruby's strftime writes them
433
+ const DATE_FORMATS = ["%-d %B %Y", "%-d %b %Y", "%A %-d %B %Y", "%d-%m-%Y", "%-d-%-m-%Y", "%Y-%m-%d", "%B %Y", "%-d %B %Y %H:%M", "%H:%M"]
434
+
435
+ // A date in a strftime format, in the page's language, for a format's example
436
+ export function strftime(date, format, locale = document.documentElement?.lang || "en") {
437
+ const part = (options) => new Intl.DateTimeFormat(locale, options).format(date)
438
+ const pad = (number) => String(number).padStart(2, "0")
439
+ const codes = {
440
+ d: pad(date.getDate()), "-d": String(date.getDate()), e: String(date.getDate()).padStart(2, " "),
441
+ m: pad(date.getMonth() + 1), "-m": String(date.getMonth() + 1), Y: String(date.getFullYear()), y: pad(date.getFullYear() % 100),
442
+ B: part({ month: "long" }), b: part({ month: "short" }).replace(/\.$/, ""), A: part({ weekday: "long" }), a: part({ weekday: "short" }),
443
+ H: pad(date.getHours()), M: pad(date.getMinutes()), R: `${pad(date.getHours())}:${pad(date.getMinutes())}`
444
+ }
445
+ return format.replace(/%(-?[a-zA-Z])/g, (match, code) => codes[code] ?? match)
446
+ }
@@ -38,12 +38,17 @@ en:
38
38
  all_panels_on_the_left: "All panels on the left"
39
39
  all_panels_on_the_right: "All panels on the right"
40
40
  alt_text: "Alt text"
41
+ and: "And"
41
42
  assign: "Assign"
43
+ assigned_path: "Assigned %{path}"
44
+ at_least: "At least"
45
+ at_most: "At most"
42
46
  auto: "Auto"
43
47
  background: "Background"
44
48
  background_image: "Background image"
45
49
  below_this_width_columns_stack: "Below this width columns stack."
46
50
  between_rows: "Between rows"
51
+ blank_nothing_or_only_spaces: "Blank: nothing, or only spaces"
47
52
  blocks: "Blocks"
48
53
  blocks_on_the_left_inspect_on_the_right: "Blocks on the left, Inspect on the right"
49
54
  bold_b: "Bold (⌘B)"
@@ -72,6 +77,7 @@ en:
72
77
  column_order: "Column order"
73
78
  column_width: "Column width"
74
79
  condition: "Condition"
80
+ contains: "Contains"
75
81
  content: "Content"
76
82
  copied: "Copied."
77
83
  copied_into_the_email_as_is_liquid_works_here_too: "Copied into the email as-is. Liquid works here too."
@@ -85,6 +91,7 @@ en:
85
91
  delete_row: "Delete row"
86
92
  desktop: "Desktop"
87
93
  divider: "Divider"
94
+ doesn_t_equal: "Doesn't equal"
88
95
  done: "Done"
89
96
  dotted: "Dotted"
90
97
  double_click_the_text_on_the_canvas_to_edit_it: "Double-click the text on the canvas to edit it."
@@ -109,6 +116,9 @@ en:
109
116
  email: "Email"
110
117
  empty: "(empty)"
111
118
  empty_for_now_fill_it_in_where_it_comes_from: "Empty for now: fill it in where it comes from"
119
+ empty_no_items_or_text: "Empty: no items or text"
120
+ ends_the: "Ends the %{tag}"
121
+ equals: "Equals"
112
122
  every_other_row: "Every other row"
113
123
  expand: "Expand"
114
124
  find_in_source: "Find in %{source}"
@@ -120,6 +130,7 @@ en:
120
130
  fonts: "Fonts"
121
131
  full: "Full"
122
132
  full_width: "Full width"
133
+ goes_on_with_the_next_item: "Goes on with the next item"
123
134
  hamburger_on_mobile: "Hamburger on mobile"
124
135
  heading: "Heading"
125
136
  heading_level: "Heading %{level}"
@@ -144,6 +155,10 @@ en:
144
155
  inspect: "Inspect"
145
156
  instead_of_the_table_s_cell_padding: "Instead of the table's cell padding."
146
157
  italic_i: "Italic (⌘I)"
158
+ its_number_from_0: "Its number, from 0"
159
+ its_number_from_1: "Its number, from 1"
160
+ its_number_from_the_end_to_0: "Its number from the end, to 0"
161
+ its_number_from_the_end_to_1: "Its number from the end, to 1"
147
162
  key: "Key"
148
163
  key_already_says_current_in_locale: "%{key} already says “%{current}” in %{locale}."
149
164
  key_no_locale_text: "%{key} · no %{locale} text"
@@ -153,6 +168,7 @@ en:
153
168
  layout: "Layout"
154
169
  left: "Left"
155
170
  left_to_right: "Left to right"
171
+ less_than: "Less than"
156
172
  letter_spacing: "Letter spacing"
157
173
  line_above: "Line above"
158
174
  line_height: "Line height"
@@ -180,6 +196,7 @@ en:
180
196
  missing: "missing"
181
197
  mobile: "Mobile"
182
198
  mode: "Mode"
199
+ more_than: "More than"
183
200
  move_up: "Move up"
184
201
  name_can_t_go_here_its_type_blocks_don_t_fit: "%{name} can't go here: its %{type} blocks don't fit."
185
202
  name_canvas: "%{name} canvas"
@@ -201,6 +218,9 @@ en:
201
218
  open_in: "Open in"
202
219
  open_source: "Open %{source}"
203
220
  open_where_it_s_kept: "Open where it's kept"
221
+ or: "Or"
222
+ or_else_when_a_condition_holds: "Or else when a condition holds"
223
+ otherwise: "Otherwise"
204
224
  padding: "Padding"
205
225
  paragraph: "Paragraph"
206
226
  paragraph_style: "Paragraph style"
@@ -239,6 +259,7 @@ en:
239
259
  solid: "Solid"
240
260
  spacer: "Spacer"
241
261
  spans_columns: "Spans columns"
262
+ stops_the_loop: "Stops the loop"
242
263
  strikethrough: "Strikethrough"
243
264
  style: "Style"
244
265
  subject: "Subject"
@@ -259,6 +280,7 @@ en:
259
280
  there_s_nothing_here_yet: "There's nothing here yet."
260
281
  thickness: "Thickness"
261
282
  this: "This"
283
+ this_loop: "This loop"
262
284
  too_narrow_to_split_the_panels: "Too narrow to split the panels"
263
285
  top: "Top"
264
286
  translations: "Translations"
@@ -277,5 +299,9 @@ en:
277
299
  vertical_align: "Vertical align"
278
300
  web: "Web"
279
301
  what_to_loop_over_e_g_invoice_lines: "What to loop over, e.g. invoice.lines."
302
+ when_it_s_one_of_these_values: "When it's one of these values"
303
+ when_there_are_no_items: "When there are no items"
304
+ whether_it_s_the_first: "Whether it's the first"
305
+ whether_it_s_the_last: "Whether it's the last"
280
306
  width: "Width"
281
307
  wrapper: "Wrapper"
@@ -38,12 +38,17 @@ nl:
38
38
  all_panels_on_the_left: "Alle panelen links"
39
39
  all_panels_on_the_right: "Alle panelen rechts"
40
40
  alt_text: "Alternatieve tekst"
41
+ and: "En"
41
42
  assign: "Toekennen"
43
+ assigned_path: "Toegewezen: %{path}"
44
+ at_least: "Minstens"
45
+ at_most: "Hoogstens"
42
46
  auto: "Automatisch"
43
47
  background: "Achtergrond"
44
48
  background_image: "Achtergrondafbeelding"
45
49
  below_this_width_columns_stack: "Onder deze breedte komen kolommen onder elkaar."
46
50
  between_rows: "Tussen rijen"
51
+ blank_nothing_or_only_spaces: "Leeg: niets, of alleen spaties"
47
52
  blocks: "Blokken"
48
53
  blocks_on_the_left_inspect_on_the_right: "Blokken links, eigenschappen rechts"
49
54
  bold_b: "Vet (⌘B)"
@@ -72,6 +77,7 @@ nl:
72
77
  column_order: "Kolomvolgorde"
73
78
  column_width: "Kolombreedte"
74
79
  condition: "Voorwaarde"
80
+ contains: "Bevat"
75
81
  content: "Inhoud"
76
82
  copied: "Gekopieerd."
77
83
  copied_into_the_email_as_is_liquid_works_here_too: "Wordt ongewijzigd in de e-mail gezet. Liquid werkt hier ook."
@@ -85,6 +91,7 @@ nl:
85
91
  delete_row: "Rij verwijderen"
86
92
  desktop: "Desktop"
87
93
  divider: "Scheidingslijn"
94
+ doesn_t_equal: "Is niet gelijk aan"
88
95
  done: "Klaar"
89
96
  dotted: "Gestippeld"
90
97
  double_click_the_text_on_the_canvas_to_edit_it: "Dubbelklik op de tekst op het canvas om die te bewerken."
@@ -109,6 +116,9 @@ nl:
109
116
  email: "E-mail"
110
117
  empty: "(leeg)"
111
118
  empty_for_now_fill_it_in_where_it_comes_from: "Nog leeg: vul het in waar het vandaan komt"
119
+ empty_no_items_or_text: "Leeg: geen items of tekst"
120
+ ends_the: "Sluit de %{tag}"
121
+ equals: "Is gelijk aan"
112
122
  every_other_row: "Om de andere rij"
113
123
  expand: "Vergroten"
114
124
  find_in_source: "Zoeken in %{source}"
@@ -120,6 +130,7 @@ nl:
120
130
  fonts: "Lettertypen"
121
131
  full: "Volledig"
122
132
  full_width: "Volle breedte"
133
+ goes_on_with_the_next_item: "Gaat door met het volgende item"
123
134
  hamburger_on_mobile: "Hamburgermenu op mobiel"
124
135
  heading: "Kop"
125
136
  heading_level: "Kop %{level}"
@@ -144,6 +155,10 @@ nl:
144
155
  inspect: "Eigenschappen"
145
156
  instead_of_the_table_s_cell_padding: "In plaats van de celmarge van de tabel."
146
157
  italic_i: "Cursief (⌘I)"
158
+ its_number_from_0: "Het nummer, vanaf 0"
159
+ its_number_from_1: "Het nummer, vanaf 1"
160
+ its_number_from_the_end_to_0: "Het nummer vanaf het eind, tot 0"
161
+ its_number_from_the_end_to_1: "Het nummer vanaf het eind, tot 1"
147
162
  key: "Sleutel"
148
163
  key_already_says_current_in_locale: "%{key} is in het %{locale} al “%{current}”."
149
164
  key_no_locale_text: "%{key} · geen %{locale}-tekst"
@@ -153,6 +168,7 @@ nl:
153
168
  layout: "Layout"
154
169
  left: "Links"
155
170
  left_to_right: "Links naar rechts"
171
+ less_than: "Minder dan"
156
172
  letter_spacing: "Letterafstand"
157
173
  line_above: "Lijn erboven"
158
174
  line_height: "Regelhoogte"
@@ -180,6 +196,7 @@ nl:
180
196
  missing: "ontbreekt"
181
197
  mobile: "Mobiel"
182
198
  mode: "Modus"
199
+ more_than: "Meer dan"
183
200
  move_up: "Omhoog"
184
201
  name_can_t_go_here_its_type_blocks_don_t_fit: "%{name} kan hier niet: de blokken %{type} passen er niet in."
185
202
  name_canvas: "%{name}-canvas"
@@ -201,6 +218,9 @@ nl:
201
218
  open_in: "Openen in"
202
219
  open_source: "%{source} openen"
203
220
  open_where_it_s_kept: "Openen waar het staat"
221
+ or: "Of"
222
+ or_else_when_a_condition_holds: "Of anders als een voorwaarde geldt"
223
+ otherwise: "Anders"
204
224
  padding: "Ruimte"
205
225
  paragraph: "Alinea"
206
226
  paragraph_style: "Alineastijl"
@@ -239,6 +259,7 @@ nl:
239
259
  solid: "Doorgetrokken"
240
260
  spacer: "Witruimte"
241
261
  spans_columns: "Beslaat kolommen"
262
+ stops_the_loop: "Stopt de lus"
242
263
  strikethrough: "Doorhalen"
243
264
  style: "Stijl"
244
265
  subject: "Onderwerp"
@@ -259,6 +280,7 @@ nl:
259
280
  there_s_nothing_here_yet: "Hier staat nog niets."
260
281
  thickness: "Dikte"
261
282
  this: "Dit"
283
+ this_loop: "Deze lus"
262
284
  too_narrow_to_split_the_panels: "Te smal om de panelen te verdelen"
263
285
  top: "Boven"
264
286
  translations: "Vertalingen"
@@ -277,5 +299,9 @@ nl:
277
299
  vertical_align: "Verticale uitlijning"
278
300
  web: "Web"
279
301
  what_to_loop_over_e_g_invoice_lines: "Waarover te herhalen, bijv. invoice.lines."
302
+ when_it_s_one_of_these_values: "Als het een van deze waarden is"
303
+ when_there_are_no_items: "Als er geen items zijn"
304
+ whether_it_s_the_first: "Of het de eerste is"
305
+ whether_it_s_the_last: "Of het de laatste is"
280
306
  width: "Breedte"
281
307
  wrapper: "Kader"
@@ -1,3 +1,3 @@
1
1
  module TessEdit
2
- VERSION = "0.5.11"
2
+ VERSION = "0.5.13"
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.11
4
+ version: 0.5.13
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