tess_edit 0.5.14 → 0.5.15

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: 97bb49e864a1f6b6a2160a031885aa9243b3777539ebc2ee8539514790607a5e
4
- data.tar.gz: db45bf62fb64f47d1ad1232fa0b92c524946d2f286112749a09495965a49381a
3
+ metadata.gz: 2c654049e87e3662224ddb773e9efaf0dd26a2859adfae9fdf19e1939e7bc6fc
4
+ data.tar.gz: a9cb5adaf4965eb613f61a0853ebeb1e2cd97d5fe0fa1a0fa3bfcdcff4c3213f
5
5
  SHA512:
6
- metadata.gz: daedafe40b1d4e09904ac960a3a62305fc6155606ba487483137a70ff0ee37e53d9085f0ce04f28f587951d28e0a43c9e61edd4ec70a64513f8fa093bfb86171
7
- data.tar.gz: 3575c9541577ec1915579308e6a46e85ae6d5935130dc6bc53b9c6a0651cb022ae0016c8929ab7778b7f34e5b572d4e75f150c8e700aa6a45a10beb394460a2e
6
+ metadata.gz: 6f10b1aafa30420f47b3af255166f6e9665b5c1baa689f399196495cb34913103d009df6972205e61cd571bd0ce9cbb25f8dd593cdbbbb1e163c3470a4437d0c
7
+ data.tar.gz: 44c9f3bceafe310d0b73e1f067be40c9fa8555cff266d44dff5ec7723d30b0d67b0680054135afa7b385b464d21ad0b7b98dcdb57bb9857d0b8b7153e87cf529
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 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.
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; and what's wrong with it, underlined.
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.
@@ -279,6 +279,8 @@ The endpoint can change while the editor is open, say when the record a template
279
279
 
280
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.
281
281
 
282
+ The editor also says what's wrong with the Liquid, a moment after it's typed: a block left open (`{% if %}` without `{% endif %}`) or closed without being opened, `elsif`, `else`, `when`, `break` where they can't be, and, with the endpoints above, a variable, filter or tag that isn't there (`order.numbr`), a filter given more arguments than it takes, and a compared value a variable can't have (`line.kind == "shiping"`). Text being edited gets a wavy line under it, the reason on hover; a field the reason under it; the block a red dot in Layers (on a closed block also for the blocks in it). What only rendering can tell, a value of the wrong type or nil, isn't checked, nor what your own tags take. `core/liquid_check.js` has the checks.
283
+
282
284
  ### Translations
283
285
 
284
286
  To show and edit translations for Liquid's `t` filter, as [Liquidum](https://github.com/entdec/liquidum) has it (`{{ '.greeting' | t }}`, `{{ "order.shipped" | t: name: order.name }}`), give the editor an endpoint with `data-tess-edit-translations-url-value`. Then:
@@ -67,6 +67,7 @@ import { Translations, keysIn, suggestKey, toTranslation, translationTag } from
67
67
  import { Values } from "tess_edit/core/values"
68
68
  import { Variables } from "tess_edit/core/variables"
69
69
  import { liquidScope } from "tess_edit/core/liquid"
70
+ import { LiquidChecker } from "tess_edit/core/liquid_check"
70
71
  import { addColumn, addRow, cellOf, columnCount, deleteColumn, deleteRow, nextCell, position, rows, wrapRow } from "tess_edit/core/table"
71
72
  import { Canvas } from "tess_edit/ui/canvas"
72
73
  import { freeChild, number } from "tess_edit/ui/free_layout"
@@ -135,6 +136,9 @@ export default class extends Controller {
135
136
  this.values.set(this.parseJson(this.valuesValue, "values"))
136
137
  this.translationLocaleChoice = this.stored(TRANSLATION_LOCALE_KEY)
137
138
  this.variableMenu = this.variables.enabled || this.translations.enabled ? new VariableMenu(this) : null
139
+ // What's wrong with the Liquid: marked in Layers, under a field, in the text being edited
140
+ this.liquidChecker = new LiquidChecker(this)
141
+ this.liquidChecker.subscribe(() => this.showLiquidProblems())
138
142
 
139
143
  this.scheduleCanvas = debounce(() => this.renderCanvas(), 60)
140
144
  this.scheduleOutputs = debounce(() => this.writeOutputs(), 300)
@@ -160,6 +164,12 @@ export default class extends Controller {
160
164
  this.element.tessEdit = this
161
165
  }
162
166
 
167
+ showLiquidProblems() {
168
+ this.tree.render()
169
+ this.inspector.showLiquidProblems()
170
+ this.textEditing.refreshProblems()
171
+ }
172
+
163
173
  // Other values from the host, once it's connected
164
174
  valuesValueChanged() {
165
175
  if (this.values) this.values.set(this.parseJson(this.valuesValue, "values"))
@@ -174,6 +184,7 @@ export default class extends Controller {
174
184
  this.textEditing.menu = this.variableMenu
175
185
  }
176
186
  this.inspector.render()
187
+ this.liquidChecker?.schedule()
177
188
  // A kit's canvas may depend on them, like a preview with sample values
178
189
  this.scheduleCanvas()
179
190
  }
@@ -329,6 +340,7 @@ export default class extends Controller {
329
340
  this.scheduleOutputs.cancel()
330
341
  Object.values(this.requests).forEach((request) => request.abort())
331
342
  this.textEditing?.stop()
343
+ this.liquidChecker?.stop()
332
344
  this.variableMenu?.close()
333
345
  this.translationPopover?.hide({ force: true })
334
346
  this.closeMenu()
@@ -584,6 +596,7 @@ export default class extends Controller {
584
596
  }
585
597
 
586
598
  renderAll() {
599
+ this.liquidChecker?.schedule()
587
600
  this.renderTopBar()
588
601
  this.renderLeftTabs()
589
602
  this.tree.render()
@@ -771,6 +784,7 @@ export default class extends Controller {
771
784
  mutate(this.doc)
772
785
  if (JSON.stringify(this.doc) === before) return
773
786
  this.history.record(before, coalesce)
787
+ this.liquidChecker?.schedule()
774
788
  this.renderTopBar()
775
789
  this.tree.render()
776
790
  if (!skipInspector) this.inspector.render()
@@ -841,9 +855,10 @@ export default class extends Controller {
841
855
  this.tree.render()
842
856
  this.canvas.refresh()
843
857
  this.scheduleOutputs()
858
+ this.liquidChecker?.schedule()
844
859
  }
845
860
  if (part.plain) this.textEditing.startPlain(container, getValue(hit.node, part.key), update, () => this.stopEditing())
846
- else this.textEditing.start(container, getValue(hit.node, part.key), update, { scope: liquidScope(this.doc, id) })
861
+ else this.textEditing.start(container, getValue(hit.node, part.key), update, { scope: liquidScope(this.doc, id), problems: () => this.liquidChecker?.field(id, part.key) })
847
862
  this.canvas.refresh()
848
863
  }
849
864
 
@@ -0,0 +1,397 @@
1
+ // What's wrong with the Liquid in a text, as far as the editor can tell
2
+ // without rendering it: each problem { start, end, message }, where it is in
3
+ // the text.
4
+ //
5
+ // checkStructure(text) blocks left open ({% if %} without {% endif %}),
6
+ // closed without being opened, and elsif, else,
7
+ // when, break and continue where they can't be
8
+ // checkLiquid(text, { mode, variables, scope })
9
+ // those, and with the host's variables, filters and
10
+ // tags (core/variables.js): a variable, filter or tag
11
+ // that isn't there, a filter given more arguments
12
+ // than it takes, a compared value that the variable
13
+ // can't have ({% if line.party == "sponsr" %})
14
+ //
15
+ // In "output" mode (Liquid in text) only what's in {{ … }} and {% … %}; in
16
+ // "expression", "condition" and "collection" mode (an Assign's value, a
17
+ // Condition, a Loop's collection) the whole text is one expression. What
18
+ // only rendering can tell (a value of the wrong type, nil) isn't checked,
19
+ // nor what the host's own tags take (their arguments aren't Liquid's).
20
+
21
+ import { walk } from "tess_edit/core/document"
22
+ import { t } from "tess_edit/core/i18n"
23
+ import { BLOCKS, liquidScope, splitOutside, unquote } from "tess_edit/core/liquid"
24
+ import { getBlock } from "tess_edit/core/registry"
25
+
26
+ // The tags in a text: [{ start, end, kind: "output" | "tag", inner, innerStart, name }]
27
+ const TAG = /\{\{-?([\s\S]*?)-?\}\}|\{%-?([\s\S]*?)-?%\}/g
28
+
29
+ export function liquidParts(text) {
30
+ const parts = []
31
+ let skip = null
32
+ for (const match of String(text ?? "").matchAll(TAG)) {
33
+ const output = match[1] !== undefined
34
+ const inner = output ? match[1] : match[2]
35
+ const innerStart = match.index + match[0].indexOf(inner, 2)
36
+ const name = output ? null : inner.match(/^\s*(\w+)/)?.[1] || ""
37
+ // Nothing in raw or a comment is Liquid
38
+ if (skip) {
39
+ if (name === `end${skip}`) skip = null
40
+ else continue
41
+ } else if (name === "raw" || name === "comment") {
42
+ skip = name
43
+ }
44
+ parts.push({ start: match.index, end: match.index + match[0].length, kind: output ? "output" : "tag", inner, innerStart, name })
45
+ }
46
+ return parts
47
+ }
48
+
49
+ // Where each tag can be: inside these blocks
50
+ const INSIDE = { elsif: ["if", "unless"], else: ["if", "unless", "case", "for"], when: ["case"] }
51
+ const IN_LOOP = new Set(["break", "continue"])
52
+
53
+ export function checkStructure(text, { blocks = BLOCKS } = {}) {
54
+ const problems = []
55
+ const open = []
56
+ for (const part of liquidParts(text)) {
57
+ if (part.kind !== "tag") continue
58
+ const { name } = part
59
+ if (name.startsWith("end") && name.length > 3) {
60
+ const block = name.slice(3)
61
+ const at = open.map((tag) => tag.name).lastIndexOf(block)
62
+ if (at < 0) {
63
+ if (blocks.includes(block)) problems.push(problem(part, t("{% %{tag} %} without {% %{block} %}", { tag: name, block })))
64
+ continue
65
+ }
66
+ for (const inner of open.splice(at).slice(1)) problems.push(problem(inner, t("{% %{tag} %} isn't closed", { tag: inner.name })))
67
+ } else if (INSIDE[name]) {
68
+ if (!INSIDE[name].includes(open.at(-1)?.name)) problems.push(problem(part, t("{% %{tag} %} can only be inside {% %{blocks} %}", { tag: name, blocks: INSIDE[name].join(" %}, {% ") })))
69
+ } else if (IN_LOOP.has(name)) {
70
+ if (!open.some((tag) => tag.name === "for" || tag.name === "tablerow")) problems.push(problem(part, t("{% %{tag} %} can only be inside {% for %}", { tag: name })))
71
+ } else if (blocks.includes(name)) {
72
+ open.push(part)
73
+ }
74
+ }
75
+ for (const tag of open) problems.push(problem(tag, t("{% %{tag} %} isn't closed", { tag: tag.name })))
76
+ return problems
77
+ }
78
+
79
+ function problem({ start, end }, message) {
80
+ return { start, end, message }
81
+ }
82
+
83
+ // Words that aren't variables
84
+ const WORDS = new Set(["and", "or", "contains", "in", "blank", "empty", "nil", "null", "true", "false", "reversed", "limit", "offset", "cols", "with", "as", "for"])
85
+ // Variables Liquid has in a loop, besides the host's
86
+ const LOOPS = new Set(["forloop", "tablerowloop"])
87
+ // Tags that aren't blocks of their own, but parts of one, and Liquid's own that are always there
88
+ const PARTS = new Set(["else", "elsif", "when", "break", "continue", "liquid"])
89
+ // A variable path, with [0] or ["key"] in it
90
+ const PATH = /[A-Za-z_][\w-]*\??(?:\.[A-Za-z_][\w-]*\??|\[[^\]]*\])*/g
91
+
92
+ export async function checkLiquid(text, { mode = "output", variables = null, scope = [] } = {}) {
93
+ text = String(text ?? "")
94
+ const tags = variables ? await variables.tags().catch(() => new Map()) : new Map()
95
+ const filters = variables ? await variables.filters().catch(() => new Map()) : new Map()
96
+ const blocks = [...new Set([...BLOCKS, ...[...tags.values()].filter((tag) => tag.block).map((tag) => tag.name)])]
97
+ const context = { variables: variables?.enabled ? variables : null, filters, scope, roots: null }
98
+
99
+ if (mode !== "output") {
100
+ const expression = mode === "collection" ? text.replace(/\s+(?:reversed|(?:limit|offset):\s*\S+)/g, (gap) => " ".repeat(gap.length)) : text
101
+ return checkExpression(expression, 0, mode === "condition", context, [])
102
+ }
103
+
104
+ const problems = checkStructure(text, { blocks })
105
+ const local = []
106
+ const cases = []
107
+ for (const part of liquidParts(text)) {
108
+ const at = part.innerStart
109
+ if (part.kind === "output") {
110
+ problems.push(...(await checkExpression(part.inner, at, false, context, local)))
111
+ continue
112
+ }
113
+ const { name, inner } = part
114
+ const args = inner.replace(/^\s*\w+/, "")
115
+ const argsAt = at + inner.length - args.length
116
+ if (name.startsWith("end")) {
117
+ if (name === "endfor" || name === "endtablerow") removeLast(local, (entry) => entry.loop)
118
+ if (name === "endcase") cases.pop()
119
+ continue
120
+ }
121
+ if (tags.size && !tags.has(name) && !PARTS.has(name) && !BLOCKS.includes(name)) {
122
+ problems.push({ start: part.start, end: part.end, message: t("There's no tag %{tag}", { tag: name }) })
123
+ continue
124
+ }
125
+ if (["if", "elsif", "unless"].includes(name)) {
126
+ problems.push(...(await checkExpression(args, argsAt, true, context, local)))
127
+ } else if (name === "case") {
128
+ problems.push(...(await checkExpression(args, argsAt, false, context, local)))
129
+ cases.push(args.trim().match(/^[\w.]+/)?.[0] || null)
130
+ } else if (name === "when") {
131
+ problems.push(...(await checkExpression(args.replace(/\bor\b|,/g, (gap) => " ".repeat(gap.length)), argsAt, false, context, local)))
132
+ const of = cases.at(-1)
133
+ if (of) problems.push(...(await checkValues(args, argsAt, of, context, local)))
134
+ } else if (name === "for" || name === "tablerow") {
135
+ const loop = args.match(/^(\s*)(\w+)(\s+in\s+)([\s\S]*)$/)
136
+ if (loop) {
137
+ const collection = loop[4].replace(/\s+(?:reversed|(?:limit|offset|cols):\s*\S+)/g, (gap) => " ".repeat(gap.length))
138
+ problems.push(...(await checkExpression(collection, argsAt + loop[1].length + loop[2].length + loop[3].length, false, context, local)))
139
+ local.push({ variable: loop[2], collection: loop[4].trim().split(/\s/)[0], loop: true })
140
+ }
141
+ } else if (name === "assign") {
142
+ const assign = args.match(/^(\s*)(\w+)(\s*=\s*)([\s\S]*)$/)
143
+ if (assign) {
144
+ problems.push(...(await checkExpression(assign[4], argsAt + assign[1].length + assign[2].length + assign[3].length, false, context, local)))
145
+ local.push({ variable: assign[2], expression: assign[4].trim() })
146
+ }
147
+ } else if (["capture", "increment", "decrement"].includes(name)) {
148
+ const variable = args.match(/^\s*["']?(\w+)/)?.[1]
149
+ if (variable) local.push({ variable, captured: name === "capture" })
150
+ } else if (name === "echo") {
151
+ problems.push(...(await checkExpression(args, argsAt, false, context, local)))
152
+ }
153
+ }
154
+ return problems.sort((a, b) => a.start - b.start)
155
+ }
156
+
157
+ function removeLast(list, test) {
158
+ for (let i = list.length - 1; i >= 0; i--) {
159
+ if (test(list[i])) return list.splice(i, 1)
160
+ }
161
+ }
162
+
163
+ // Blanks out what's quoted, keeping where everything is
164
+ function blankQuotes(text) {
165
+ return text.replace(/(["'])[\s\S]*?\1/g, (quoted) => quoted[0] + " ".repeat(quoted.length - 2) + quoted[0])
166
+ }
167
+
168
+ // An expression's variables and filters: `order.lines | where: "kind", "x" | first`
169
+ async function checkExpression(expression, offset, condition, context, local) {
170
+ const problems = []
171
+ const pieces = splitOutside(expression, "|")
172
+ let at = offset
173
+ for (const [index, piece] of pieces.entries()) {
174
+ if (index === 0) {
175
+ problems.push(...(await checkPaths(piece, at, context, local)))
176
+ if (condition) problems.push(...(await checkComparisons(piece, at, context, local)))
177
+ } else {
178
+ problems.push(...(await checkFilter(piece, at, context, local)))
179
+ }
180
+ at += piece.length + 1
181
+ }
182
+ return problems
183
+ }
184
+
185
+ async function checkFilter(piece, offset, context, local) {
186
+ const named = piece.match(/^(\s*)(\w+)/)
187
+ if (!named) return []
188
+ const start = offset + named[1].length
189
+ const name = named[2]
190
+ const filter = context.filters.get(name)
191
+ if (context.filters.size && !filter) return [{ start, end: start + name.length, message: t("There's no filter %{filter}", { filter: name }) }]
192
+
193
+ const problems = []
194
+ const call = piece.slice(named[0].length).match(/^(\s*:)([\s\S]*)$/)
195
+ if (!call) return problems
196
+ const argsAt = offset + named[0].length + call[1].length
197
+ const args = splitOutside(call[2], ",")
198
+ // Named arguments (t: name: user.name) aren't counted
199
+ const positional = args.filter((arg) => arg.trim() && !/^\s*\w+\s*:/.test(arg))
200
+ const takes = filter?.arguments?.length || 0
201
+ if (takes && positional.length > takes) {
202
+ problems.push({ start, end: start + name.length, message: t("%{filter} takes %{count} arguments, not %{given}", { filter: name, count: takes, given: positional.length }) })
203
+ }
204
+ let at = argsAt
205
+ for (const arg of args) {
206
+ problems.push(...(await checkPaths(arg.replace(/^\s*\w+\s*:/, (key) => " ".repeat(key.length)), at, context, local)))
207
+ at += arg.length + 1
208
+ }
209
+ return problems
210
+ }
211
+
212
+ // The variables in a piece of an expression, outside quotes
213
+ async function checkPaths(piece, offset, context, local) {
214
+ if (!context.variables) return []
215
+ const problems = []
216
+ const blank = blankQuotes(piece)
217
+ for (const match of blank.matchAll(PATH)) {
218
+ const before = blank.slice(0, match.index)
219
+ // Part of a number (1.5) or a named argument's key (limit: 3)
220
+ if (/[\w"']$/.test(before) || /^\s*:/.test(blank.slice(match.index + match[0].length))) continue
221
+ const found = await checkPath(match[0], context, local)
222
+ if (found) problems.push({ start: offset + match.index + found.at, end: offset + match.index + found.at + found.length, message: found.message })
223
+ }
224
+ return problems
225
+ }
226
+
227
+ // The text's own variables before the scope around it, nearest first
228
+ function scopeOf(context, local) {
229
+ return [...local].reverse().filter((entry) => entry.collection || entry.expression || entry.captured).concat(context.scope)
230
+ }
231
+
232
+ // What's wrong with a path: the first name that isn't there
233
+ async function checkPath(path, context, local) {
234
+ const { variables } = context
235
+ const scope = scopeOf(context, local)
236
+ const names = path.split(/\[/)[0].split(".")
237
+ const root = names[0].replace(/\?$/, "")
238
+ if (WORDS.has(root)) return null
239
+ // Only in a loop: a Loop block's, or one in the text
240
+ if (LOOPS.has(root)) {
241
+ if (local.some((entry) => entry.loop) || context.scope.some((entry) => entry.collection)) return null
242
+ return { at: 0, length: root.length, message: t("There's no variable %{name}", { name: root }) }
243
+ }
244
+ // A variable of the text's own ({% assign %}, {% for %}) or of the blocks around it
245
+ const own = local.some((entry) => entry.variable === root) || context.scope.some((entry) => entry.variable === root)
246
+ if (!own) {
247
+ context.roots ||= await variables.options("", context.scope).catch(() => [])
248
+ if (!context.roots.length) return null
249
+ if (!context.roots.some((variable) => variable.name === root)) return { at: 0, length: root.length, message: t("There's no variable %{name}", { name: root }) }
250
+ }
251
+ // Each name after it, as far as its parent's variables are known
252
+ let at = names[0].length + 1
253
+ for (let i = 1; i < names.length; i++) {
254
+ const parent = names.slice(0, i).join(".")
255
+ const variable = await variables.lookup(parent, scope).catch(() => null)
256
+ if (!variable?.children) return null
257
+ const options = await variables.options(parent, scope).catch(() => [])
258
+ if (!options.length) return null
259
+ const name = names[i].replace(/\?$/, "")
260
+ if (name !== "size" && !options.some((option) => option.name === name)) return { at, length: names[i].length, message: t("%{path} has no %{name}", { path: parent, name }) }
261
+ at += names[i].length + 1
262
+ }
263
+ return null
264
+ }
265
+
266
+ // A comparison with a quoted value the variable can't have
267
+ async function checkComparisons(piece, offset, context, local) {
268
+ const problems = []
269
+ for (const match of piece.matchAll(/([A-Za-z_][\w.]*)\s*(?:==|!=|<>)\s*(["'])([^"']*)\2/g)) {
270
+ const at = offset + match.index + match[0].length - match[3].length - 2
271
+ problems.push(...(await checkValues(`${match[2]}${match[3]}${match[2]}`, at, match[1], context, local)))
272
+ }
273
+ return problems
274
+ }
275
+
276
+ // Quoted values, separated by , or or, that a variable can't have
277
+ async function checkValues(text, offset, path, context, local) {
278
+ if (!context.variables) return []
279
+ const variable = await context.variables.lookup(path, scopeOf(context, local)).catch(() => null)
280
+ const values = variable?.values?.map((value) => String(value.value))
281
+ if (!values?.length) return []
282
+ const problems = []
283
+ for (const match of text.matchAll(/(["'])([^"']*)\1/g)) {
284
+ if (!values.includes(unquote(match[0]))) problems.push({ start: offset + match.index, end: offset + match.index + match[0].length, message: t("%{path} is never %{value}", { path, value: match[0] }) })
285
+ }
286
+ return problems
287
+ }
288
+
289
+ // The text of a Tiptap document as checked: its paragraphs and headings one
290
+ // to a line, an inline node (a line break) one character, as
291
+ // ProseMirror's textBetween gives them (ui/text_editing.js)
292
+ const TEXTBLOCKS = new Set(["paragraph", "heading"])
293
+
294
+ export function richText(content) {
295
+ const lines = []
296
+ const collect = (node) => {
297
+ if (TEXTBLOCKS.has(node?.type)) lines.push((node.content || []).map((inline) => (inline.type === "text" ? inline.text : "\ufffc")).join(""))
298
+ else (node?.content || []).forEach(collect)
299
+ }
300
+ collect(content)
301
+ return lines.join("\n")
302
+ }
303
+
304
+ // The Liquid in a document's blocks: [{ id, key, mode, text, scope }], from
305
+ // their fields with a liquid mode, their rich texts, and any other text with
306
+ // {{ or {% in it
307
+ export function liquidTexts(doc) {
308
+ const texts = []
309
+ walk(doc, (node) => {
310
+ const modes = new Map()
311
+ for (const group of getBlock(node.type)?.fields || []) {
312
+ for (const field of group.fields || []) {
313
+ if (field.liquid) modes.set(field.key, typeof field.liquid === "string" ? field.liquid : "output")
314
+ }
315
+ }
316
+ const found = []
317
+ const visit = (value, key) => {
318
+ if (typeof value === "string") {
319
+ const mode = modes.get(key)
320
+ if (mode && mode !== "output" ? value.trim() : /\{\{|\{%/.test(value)) found.push({ key, mode: mode || "output", text: value })
321
+ } else if (value?.type === "doc" && Array.isArray(value.content)) {
322
+ const text = richText(value)
323
+ if (/\{\{|\{%/.test(text)) found.push({ key, mode: "output", text, rich: true })
324
+ } else if (value && typeof value === "object") {
325
+ for (const [name, item] of Object.entries(value)) visit(item, `${key}.${name}`)
326
+ }
327
+ }
328
+ visit(node.data || {}, "data")
329
+ visit(node.attributes || {}, "attributes")
330
+ if (found.length) {
331
+ const scope = liquidScope(doc, node.id)
332
+ for (const entry of found) texts.push({ id: node.id, scope, ...entry })
333
+ }
334
+ })
335
+ return texts
336
+ }
337
+
338
+ // The problems in a document, checked again a moment after it changes,
339
+ // for the editor to show: by block, and by block and key
340
+ //
341
+ // checker.schedule() after a change
342
+ // checker.subscribe(fn) fn() when there are new ones
343
+ // checker.problems(id) [{ key, text, problems }] of a block
344
+ // checker.field(id, key) { text, problems } of one of its texts, or null
345
+ export class LiquidChecker {
346
+ constructor(editor, { delay = 400 } = {}) {
347
+ this.editor = editor
348
+ this.delay = delay
349
+ this.results = new Map()
350
+ this.listeners = new Set()
351
+ this.runs = 0
352
+ // None to start with
353
+ this.key = "[]"
354
+ }
355
+
356
+ subscribe(fn) {
357
+ this.listeners.add(fn)
358
+ return () => this.listeners.delete(fn)
359
+ }
360
+
361
+ schedule() {
362
+ clearTimeout(this.timer)
363
+ this.timer = setTimeout(() => this.check(), this.delay)
364
+ }
365
+
366
+ async check() {
367
+ const run = ++this.runs
368
+ const results = new Map()
369
+ for (const entry of liquidTexts(this.editor.doc)) {
370
+ const problems = await checkLiquid(entry.text, { mode: entry.mode, variables: this.editor.variables, scope: entry.scope })
371
+ // A newer check has started
372
+ if (run !== this.runs) return
373
+ if (!problems.length) continue
374
+ if (!results.has(entry.id)) results.set(entry.id, [])
375
+ results.get(entry.id).push({ key: entry.key, text: entry.text, problems })
376
+ }
377
+ // Only when they're other than they were: showing them renders Layers again
378
+ const key = JSON.stringify([...results])
379
+ if (key === this.key) return
380
+ this.key = key
381
+ this.results = results
382
+ this.listeners.forEach((fn) => fn())
383
+ }
384
+
385
+ problems(id) {
386
+ return this.results.get(id) || []
387
+ }
388
+
389
+ field(id, key) {
390
+ return this.problems(id).find((entry) => entry.key === key) || null
391
+ }
392
+
393
+ stop() {
394
+ clearTimeout(this.timer)
395
+ this.runs++
396
+ }
397
+ }
@@ -59,6 +59,7 @@ a{cursor:default}
59
59
  .ProseMirror .tess-v-filled{cursor:text}
60
60
  .tess-v-hidden{display:none}
61
61
  .tess-v-empty{border-radius:3px;background:rgba(220,38,38,.08);box-shadow:inset 0 -1px 0 rgba(220,38,38,.65)}
62
+ .tess-liquid-error{text-decoration:underline wavy rgba(220,38,38,.9);text-decoration-skip-ink:none;text-underline-offset:3px}
62
63
  `
63
64
 
64
65
  // A file dragged in from outside the browser (block drags set editor.drag)
@@ -86,6 +86,8 @@ export class Inspector {
86
86
  this.adapters = new Map()
87
87
  this.inputs = new Map()
88
88
  this.hints = []
89
+ this.problemHints = new Map()
90
+ this.problemNode = node.id
89
91
 
90
92
  const actions =
91
93
  !this.editor.isFree(node.id)
@@ -116,6 +118,25 @@ export class Inspector {
116
118
  const hint = definition.hint && !locked ? h("p", { class: "mx-4 mt-3 rounded-md bg-gray-50 dark:bg-gray-700/50 px-3 py-2 text-xs text-gray-600 dark:text-gray-300" }, t(definition.hint)) : null
117
119
 
118
120
  place(this.body, [locked, hint, ...groups].filter(Boolean), new Set([...this.keptGroups.values()].map((kept) => kept.details)))
121
+ this.showLiquidProblems()
122
+ }
123
+
124
+ // Under a field with Liquid, what's wrong with it (core/liquid_check.js),
125
+ // while its value is the one that was checked
126
+ showLiquidProblems() {
127
+ const checker = this.editor.liquidChecker
128
+ const node = find(this.editor.doc, this.problemNode)?.node
129
+ for (const [key, { element, control }] of this.problemHints || []) {
130
+ const entry = node && checker?.field(node.id, key)
131
+ const current = entry && entry.text === String(getValue(node, key) ?? "") ? entry.problems : []
132
+ element.replaceChildren(...current.map((problem) => h("span", { class: "block" }, problem.message)))
133
+ element.hidden = !current.length
134
+ for (const input of control.matches("input, textarea") ? [control] : control.querySelectorAll("input, textarea")) {
135
+ for (const name of ["tess-liquid-invalid", "border-red-500!", "dark:border-red-400!"]) input.classList.toggle(name, current.length > 0)
136
+ if (current.length) input.setAttribute("aria-invalid", "true")
137
+ else input.removeAttribute("aria-invalid")
138
+ }
139
+ }
119
140
  }
120
141
 
121
142
  // A field's visible(node, editor) shows it only when it applies; a slot
@@ -189,6 +210,8 @@ export class Inspector {
189
210
  hint.textContent = typeof field.hint === "function" ? field.hint(getValue(current, field.key) ?? "", current) : t(field.hint)
190
211
  }
191
212
  if (hint) showHint()
213
+ const problems = field.liquid ? h("span", { class: "tess-liquid-problems mt-1 block text-[11px] leading-snug text-red-600 dark:text-red-400", hidden: true, role: "alert" }) : null
214
+ if (problems) this.problemHints.set(field.key, { element: problems, control })
192
215
  // A div, not a label: a label would forward clicks to the first button or color picker inside it.
193
216
  return h(
194
217
  "div",
@@ -197,6 +220,7 @@ export class Inspector {
197
220
  tools,
198
221
  control,
199
222
  input ? this.translationHint(input) : null,
223
+ problems,
200
224
  hint
201
225
  )
202
226
  }
@@ -25,6 +25,7 @@ const BUTTON = "w-7 h-7 flex items-center justify-center rounded-md text-gray-60
25
25
  const ACTIVE = "bg-blue-50 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300"
26
26
  const TRANSLATIONS = new PluginKey("tessTranslations")
27
27
  const VALUES = new PluginKey("tessValues")
28
+ const PROBLEMS = new PluginKey("tessLiquidProblems")
28
29
 
29
30
  export class TextEditing {
30
31
  constructor(toolbar, { menu = null, editor = null } = {}) {
@@ -79,8 +80,10 @@ export class TextEditing {
79
80
  return element
80
81
  }
81
82
 
82
- // scope: the Loops' and Assigns' variables of the block (core/liquid.js liquidScope)
83
- start(container, content, onUpdate, { scope = [] } = {}) {
83
+ // scope: the Loops' and Assigns' variables of the block (core/liquid.js liquidScope);
84
+ // problems: () => what's wrong with its Liquid ({ text, problems }, core/liquid_check.js)
85
+ start(container, content, onUpdate, { scope = [], problems = null } = {}) {
86
+ this.problems = problems
84
87
  this.stop()
85
88
  container.replaceChildren()
86
89
  this.tiptap = new Editor({
@@ -98,7 +101,8 @@ export class TextEditing {
98
101
  Color,
99
102
  TextAlign.configure({ types: ["heading", "paragraph"] }),
100
103
  ...(this.translating ? [translationsExtension(this)] : []),
101
- ...(this.editor?.values ? [valuesExtension(this)] : [])
104
+ ...(this.editor?.values ? [valuesExtension(this)] : []),
105
+ problemsExtension(this)
102
106
  ],
103
107
  autofocus: "end",
104
108
  editorProps: { handleKeyDown: (view, event) => this.menu?.key(event) || false },
@@ -120,6 +124,11 @@ export class TextEditing {
120
124
  if (this.tiptap && this.translating) this.tiptap.view.dispatch(this.tiptap.state.tr.setMeta(TRANSLATIONS, true))
121
125
  }
122
126
 
127
+ // Again, when the Liquid's been checked
128
+ refreshProblems() {
129
+ if (this.tiptap) this.tiptap.view.dispatch(this.tiptap.state.tr.setMeta(PROBLEMS, true))
130
+ }
131
+
123
132
  // Again, when the values change
124
133
  refreshValues() {
125
134
  if (this.tiptap && this.editor?.values) this.tiptap.view.dispatch(this.tiptap.state.tr.setMeta(VALUES, true))
@@ -397,3 +406,42 @@ function valueChip(view, call, value, edit) {
397
406
  })
398
407
  return chip
399
408
  }
409
+
410
+ function problemsExtension(editing) {
411
+ return Extension.create({
412
+ name: "tessLiquidProblems",
413
+ addProseMirrorPlugins() {
414
+ return [new Plugin({ key: PROBLEMS, props: { decorations: (state) => problemDecorations(state, editing) } })]
415
+ }
416
+ })
417
+ }
418
+
419
+ // A wavy line under what's wrong, its message on hover, while the text is
420
+ // the one checked (its paragraphs a line each, as core/liquid_check.js's
421
+ // richText has them)
422
+ function problemDecorations(state, editing) {
423
+ const entry = editing.problems?.()
424
+ if (!entry?.problems?.length) return DecorationSet.empty
425
+ const lines = []
426
+ let offset = 0
427
+ state.doc.descendants((node, pos) => {
428
+ if (!node.isTextblock) return true
429
+ const text = node.textBetween(0, node.content.size, undefined, "\ufffc")
430
+ lines.push({ offset, pos: pos + 1, text })
431
+ offset += text.length + 1
432
+ return false
433
+ })
434
+ if (lines.map((line) => line.text).join("\n") !== entry.text) return DecorationSet.empty
435
+ // Where problems overlap ({% if order.numbr %} not closed, numbr not
436
+ // there), a piece each, with the messages of all of them, innermost first
437
+ const cuts = [...new Set(entry.problems.flatMap((problem) => [problem.start, problem.end]).concat(lines.map((line) => line.offset + line.text.length)))].sort((a, b) => a - b)
438
+ const decorations = []
439
+ for (let i = 0; i < cuts.length - 1; i++) {
440
+ const [start, end] = [cuts[i], cuts[i + 1]]
441
+ const line = lines.find((candidate) => start >= candidate.offset && end <= candidate.offset + candidate.text.length)
442
+ const covering = entry.problems.filter((problem) => problem.start <= start && problem.end >= end).sort((a, b) => (a.end - a.start) - (b.end - b.start))
443
+ if (!line || !covering.length) continue
444
+ decorations.push(Decoration.inline(line.pos + start - line.offset, line.pos + end - line.offset, { class: "tess-liquid-error", title: covering.map((problem) => problem.message).join("\n") }))
445
+ }
446
+ return DecorationSet.create(state.doc, decorations)
447
+ }
@@ -1,7 +1,7 @@
1
1
  // The Layers panel: the document as a collapsible tree that can be reordered by
2
2
  // dragging. Rows also take blocks dragged from the Blocks panel.
3
3
 
4
- import { find, isDescendant } from "tess_edit/core/document"
4
+ import { find, isDescendant, walk } from "tess_edit/core/document"
5
5
  import { t } from "tess_edit/core/i18n"
6
6
  import { getBlock, isContainer, label } from "tess_edit/core/registry"
7
7
  import { h } from "tess_edit/ui/dom"
@@ -82,6 +82,7 @@ export class Tree {
82
82
  toggle,
83
83
  h("span", { class: `shrink-0 ${getBlock(node.type)?.accepts === "inherit" ? "text-amber-600 dark:text-amber-400" : "text-gray-400 dark:text-gray-500"}`, html: icon(getBlock(node.type)?.icon, "w-4 h-4") }),
84
84
  h("span", { class: `truncate text-[13px] ${locked ? "text-gray-400 dark:text-gray-500" : ""}` }, label(node)),
85
+ this.problemMark(node, open),
85
86
  locked ? h("span", { class: "ml-auto shrink-0 text-gray-300 dark:text-gray-600", title: t("Part of the layout"), html: icon("lock", "w-3.5 h-3.5") }) : add,
86
87
  h("div", { class: "tess-tree-marker pointer-events-none absolute left-1 right-1 hidden" })
87
88
  )
@@ -132,6 +133,19 @@ export class Tree {
132
133
  this.editor.endDrag()
133
134
  }
134
135
 
136
+ // A red dot on a block with Liquid that's wrong (core/liquid_check.js), its
137
+ // messages on hover; on a closed one, also for those of the blocks in it
138
+ problemMark(node, open) {
139
+ const checker = this.editor.liquidChecker
140
+ if (!checker) return null
141
+ const messages = checker.problems(node.id).flatMap((entry) => entry.problems.map((problem) => problem.message))
142
+ let inside = false
143
+ if (!open) walk(node, (child) => (inside ||= child !== node && checker.problems(child.id).length > 0) ? false : undefined)
144
+ if (!messages.length && !inside) return null
145
+ const title = messages.length ? messages.join("\n") : t("A block in it has Liquid that's wrong")
146
+ return h("span", { class: "tess-liquid-mark shrink-0 w-1.5 h-1.5 rounded-full bg-red-500", title, "aria-label": title, role: "img" })
147
+ }
148
+
135
149
  clearMarker() {
136
150
  if (this.markerElement) this.markerElement.className = "tess-tree-marker pointer-events-none absolute left-1 right-1 hidden"
137
151
  this.markerElement = null
@@ -10,6 +10,7 @@ en:
10
10
  3_columns: "3 columns"
11
11
  4_columns: "4 columns"
12
12
  a_background_for_every_other_row_from_the_second: "A background for every other row, from the second."
13
+ a_block_in_it_has_liquid_that_s_wrong: "A block in it has Liquid that's wrong"
13
14
  a_heavier_line_above_the_row_e_g_3pt_above_a_total: "A heavier line above the row, e.g. 3pt above a total."
14
15
  a_key_is_made_of_letters_digits_and_separated_by_dots_e_g_or: "A key is made of letters, digits, _ and -, separated by dots, e.g. .order.thanks"
15
16
  a_key_starting_with_a_dot_belongs_to_this_template: "A key starting with a dot belongs to this template."
@@ -60,6 +61,8 @@ en:
60
61
  bulleted_list: "Bulleted list"
61
62
  button: "Button"
62
63
  button_color: "Button color"
64
+ can_only_be_inside: "{% %{tag} %} can only be inside {% %{blocks} %}"
65
+ can_only_be_inside_for: "{% %{tag} %} can only be inside {% for %}"
63
66
  cancel: "Cancel"
64
67
  captured_text: "Captured text"
65
68
  cell: "Cell"
@@ -133,6 +136,7 @@ en:
133
136
  full_width: "Full width"
134
137
  goes_on_with_the_next_item: "Goes on with the next item"
135
138
  hamburger_on_mobile: "Hamburger on mobile"
139
+ has_no: "%{path} has no %{name}"
136
140
  heading: "Heading"
137
141
  heading_level: "Heading %{level}"
138
142
  heading_row: "Heading row"
@@ -155,6 +159,8 @@ en:
155
159
  insert_a_variable: "Insert a variable"
156
160
  inspect: "Inspect"
157
161
  instead_of_the_table_s_cell_padding: "Instead of the table's cell padding."
162
+ is_never: "%{path} is never %{value}"
163
+ isn_t_closed: "{% %{tag} %} isn't closed"
158
164
  italic_i: "Italic (⌘I)"
159
165
  its_number_from_0: "Its number, from 0"
160
166
  its_number_from_1: "Its number, from 1"
@@ -265,6 +271,7 @@ en:
265
271
  style: "Style"
266
272
  subject: "Subject"
267
273
  table: "Table"
274
+ takes_arguments_not: "%{filter} takes %{count} arguments, not %{given}"
268
275
  text: "Text"
269
276
  text_color: "Text color"
270
277
  the_content_of_the_documents_using_this_layout_goes_here_wha: "The content of the documents using this layout goes here. What you put inside is example content for designing the layout."
@@ -278,6 +285,9 @@ en:
278
285
  theme: "Theme"
279
286
  there_are_no_languages_to_translate_into_yet: "There are no languages to translate into yet."
280
287
  there_is_a_name_already_a_document_has_one: "There is a %{name} already; a document has one."
288
+ there_s_no_filter: "There's no filter %{filter}"
289
+ there_s_no_tag: "There's no tag %{tag}"
290
+ there_s_no_variable: "There's no variable %{name}"
281
291
  there_s_nothing_here_yet: "There's nothing here yet."
282
292
  thickness: "Thickness"
283
293
  this: "This"
@@ -305,4 +315,5 @@ en:
305
315
  whether_it_s_the_first: "Whether it's the first"
306
316
  whether_it_s_the_last: "Whether it's the last"
307
317
  width: "Width"
318
+ without: "{% %{tag} %} without {% %{block} %}"
308
319
  wrapper: "Wrapper"
@@ -10,6 +10,7 @@ nl:
10
10
  3_columns: "3 kolommen"
11
11
  4_columns: "4 kolommen"
12
12
  a_background_for_every_other_row_from_the_second: "Een achtergrond voor om de andere rij, vanaf de tweede."
13
+ a_block_in_it_has_liquid_that_s_wrong: "Een blok erin heeft Liquid dat niet klopt"
13
14
  a_heavier_line_above_the_row_e_g_3pt_above_a_total: "Een dikkere lijn boven de rij, bijv. 3pt boven een totaal."
14
15
  a_key_is_made_of_letters_digits_and_separated_by_dots_e_g_or: "Een sleutel bestaat uit letters, cijfers, _ en -, gescheiden door punten, bijv. .order.thanks"
15
16
  a_key_starting_with_a_dot_belongs_to_this_template: "Een sleutel die met een punt begint, hoort bij deze template."
@@ -60,6 +61,8 @@ nl:
60
61
  bulleted_list: "Opsomming"
61
62
  button: "Knop"
62
63
  button_color: "Knopkleur"
64
+ can_only_be_inside: "{% %{tag} %} kan alleen binnen {% %{blocks} %}"
65
+ can_only_be_inside_for: "{% %{tag} %} kan alleen binnen {% for %}"
63
66
  cancel: "Annuleren"
64
67
  captured_text: "Vastgelegde tekst"
65
68
  cell: "Cel"
@@ -133,6 +136,7 @@ nl:
133
136
  full_width: "Volle breedte"
134
137
  goes_on_with_the_next_item: "Gaat door met het volgende item"
135
138
  hamburger_on_mobile: "Hamburgermenu op mobiel"
139
+ has_no: "%{path} heeft geen %{name}"
136
140
  heading: "Kop"
137
141
  heading_level: "Kop %{level}"
138
142
  heading_row: "Kopregel"
@@ -155,6 +159,8 @@ nl:
155
159
  insert_a_variable: "Variabele invoegen"
156
160
  inspect: "Eigenschappen"
157
161
  instead_of_the_table_s_cell_padding: "In plaats van de celmarge van de tabel."
162
+ is_never: "%{path} is nooit %{value}"
163
+ isn_t_closed: "{% %{tag} %} wordt niet afgesloten"
158
164
  italic_i: "Cursief (⌘I)"
159
165
  its_number_from_0: "Het nummer, vanaf 0"
160
166
  its_number_from_1: "Het nummer, vanaf 1"
@@ -265,6 +271,7 @@ nl:
265
271
  style: "Stijl"
266
272
  subject: "Onderwerp"
267
273
  table: "Tabel"
274
+ takes_arguments_not: "%{filter} neemt %{count} argumenten, niet %{given}"
268
275
  text: "Tekst"
269
276
  text_color: "Tekstkleur"
270
277
  the_content_of_the_documents_using_this_layout_goes_here_wha: "Hier komt de inhoud van wat deze layout gebruikt. Wat je erin zet, is voorbeeldinhoud om de layout te ontwerpen."
@@ -278,6 +285,9 @@ nl:
278
285
  theme: "Thema"
279
286
  there_are_no_languages_to_translate_into_yet: "Er zijn nog geen talen om naar te vertalen."
280
287
  there_is_a_name_already_a_document_has_one: "Er is al een %{name}; een document heeft er één."
288
+ there_s_no_filter: "Er is geen filter %{filter}"
289
+ there_s_no_tag: "Er is geen tag %{tag}"
290
+ there_s_no_variable: "Er is geen variabele %{name}"
281
291
  there_s_nothing_here_yet: "Hier staat nog niets."
282
292
  thickness: "Dikte"
283
293
  this: "Dit"
@@ -305,4 +315,5 @@ nl:
305
315
  whether_it_s_the_first: "Of het de eerste is"
306
316
  whether_it_s_the_last: "Of het de laatste is"
307
317
  width: "Breedte"
318
+ without: "{% %{tag} %} zonder {% %{block} %}"
308
319
  wrapper: "Kader"
@@ -1,3 +1,3 @@
1
1
  module TessEdit
2
- VERSION = "0.5.14"
2
+ VERSION = "0.5.15"
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.14
4
+ version: 0.5.15
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tom de Grunt
@@ -106,6 +106,7 @@ files:
106
106
  - app/javascript/tess_edit/core/history.js
107
107
  - app/javascript/tess_edit/core/i18n.js
108
108
  - app/javascript/tess_edit/core/liquid.js
109
+ - app/javascript/tess_edit/core/liquid_check.js
109
110
  - app/javascript/tess_edit/core/lock.js
110
111
  - app/javascript/tess_edit/core/media.js
111
112
  - app/javascript/tess_edit/core/registry.js