tess_edit 0.5.12 → 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: 6fbe80bedc7281410bc4d08388da4901f5371c3282edc67ef41c8fe1efd4f858
4
- data.tar.gz: 461eed20d4d3a0e860bdcf750162c08b0f31335e35e8d95b7d8554b656d69f6b
3
+ metadata.gz: d698da274caf7efb2844c8363a0ff380a4ef3670066cb4499b269764072fd47e
4
+ data.tar.gz: 5417eb85bdb830f23cad6b9f10b1eb5ea7f2657cd63f4901aa23cbda195a61e8
5
5
  SHA512:
6
- metadata.gz: e355ee3b554123245f5a8cf76ece3a6514e1376b8bc67c9d686143fcc929b2d19e7b8e9b85d98800cda6d321e5f33ed035ee894519122a328b5836fecc9456c7
7
- data.tar.gz: 0fbda871f654a364738555b7655166966f79d85dc0e88ed474cd3a49b459a72f2f4425f93346a4cb6ca0e4e6c4ea6d5f4cd598f91a53b908bd8b791eb29c5407
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 and the Assigns before it; after a `|` your app's filters, with a where's property and the values it can have, and after `==` the values of what's compared.
21
+ - 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.
@@ -255,7 +255,9 @@ The endpoint answers `GET` with the variables at `path` (the roots without one),
255
255
 
256
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
257
 
258
- A variable with `values` (`"values": [{"value": "shipping", "label": "Shipping"}]`) can only be those: after `line.kind == ` the editor suggests them, quoted.
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`, ….
259
261
 
260
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:
261
263
 
@@ -263,11 +265,19 @@ With `data-tess-edit-filters-url-value` the editor also completes filters: after
263
265
  {"filters": [{"name": "where", "label": "Those whose property has the value", "arguments": [{"name": "property", "kind": "property"}, {"name": "value", "kind": "value"}], "keeps": "collection"}]}
264
266
  ```
265
267
 
266
- An argument's `kind` is `property`, `value` (one the property before it can have) or anything else, where the editor suggests variables. `keeps` says what a filter on a collection leaves: the same items (`"collection"`) or one of them (`"item"`); without the endpoint Liquid's own are known. Liquidum's `/liquidum/filters` answers this way, with your app's filters as well; the dummy app's `VariablesController#filters` is an example.
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.
267
277
 
268
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.
269
279
 
270
- A field of your own gets the `{ }` button with `liquid: true`, or `liquid: "expression"` (a condition) or `liquid: "collection"` (what a loop goes over) for Liquid without braces.
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.
271
281
 
272
282
  ### Translations
273
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: {
@@ -25,6 +25,8 @@
25
25
  // e.g. when the class a template is for changes
26
26
  // filtersUrl the filters a template can use, suggested after a | with their
27
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
28
30
  // translationsUrl the host's translations for Liquid's t filter ({{ '.greeting' | t }}),
29
31
  // shown in a language chosen in the top bar, listed and edited
30
32
  // while pointed at, and made from selected text (see
@@ -96,7 +98,7 @@ function placed(node, at) {
96
98
  }
97
99
 
98
100
  export default class extends Controller {
99
- static values = { kit: { type: String, default: DEFAULT_KIT }, document: String, sample: { type: Boolean, default: true }, frame: { type: Boolean, default: true }, panels: { type: String, default: "split" }, compileUrl: { type: String, default: COMPILE_URL }, mediaUrl: String, variablesUrl: String, filtersUrl: String, translationsUrl: String, values: String, lock: String, blocks: String, options: String }
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 }
100
102
  static targets = ["jsonInput", "mjmlInput", "htmlInput", "slot", "translations"]
101
103
 
102
104
  connect() {
@@ -126,7 +128,7 @@ export default class extends Controller {
126
128
  this.sheetOpen = false
127
129
  this.requests = {}
128
130
  this.media = { enabled: Boolean(this.mediaUrlValue), images: [], uploading: false, error: null }
129
- this.variables = new Variables(this.variablesUrlValue, { filtersUrl: this.filtersUrlValue })
131
+ this.variables = new Variables(this.variablesUrlValue, { filtersUrl: this.filtersUrlValue, tagsUrl: this.tagsUrlValue })
130
132
  this.translations = new Translations(this.translationsUrlValue)
131
133
  this.translationPopover = this.translations.enabled ? new TranslationPopover(this) : null
132
134
  this.values = new Values()
@@ -166,7 +168,7 @@ export default class extends Controller {
166
168
  // Points the editor at other variables (variablesUrl), once it's connected
167
169
  variablesUrlValueChanged() {
168
170
  if (!this.variables) return
169
- this.variables = new Variables(this.variablesUrlValue, { filtersUrl: this.filtersUrlValue })
171
+ this.variables = new Variables(this.variablesUrlValue, { filtersUrl: this.filtersUrlValue, tagsUrl: this.tagsUrlValue })
170
172
  if (!this.variableMenu && this.variables.enabled) {
171
173
  this.variableMenu = new VariableMenu(this)
172
174
  this.textEditing.menu = this.variableMenu
@@ -7,11 +7,16 @@
7
7
  // "{{ lines | where: \"pa" → { kind: "argument", filter: "where", index: 0, partial: "pa", quote: "\"" }
8
8
  // "{{ lines | where: \"party\", " → { kind: "argument", filter: "where", index: 1, partial: "", args: ["party"] }
9
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: "" }
10
12
  //
11
13
  // each with `start`, where what it replaces starts in the text, and `tag`
12
14
  // ("{{", "{%" or null). In "output" mode (Liquid in text) only inside {{ … }}
13
- // or {% … %}; in "expression" mode (a Loop's collection, a Condition, an
14
- // Assign's value) anywhere. The editor's menu (ui/variable_menu.js) asks the
15
+ // 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
15
20
  // host for what fits: its variables, its filters and their arguments, the
16
21
  // values a variable can have (core/variables.js).
17
22
  //
@@ -24,6 +29,27 @@ import { find } from "tess_edit/core/document"
24
29
 
25
30
  const PATH = /[A-Za-z_][\w]*(?:\.[\w]*)*/
26
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
+ }
27
53
 
28
54
  // The parts of a Liquid expression outside quotes, split at `separator`
29
55
  // (| between filters, , between arguments)
@@ -70,20 +96,37 @@ export function unquote(text) {
70
96
  return match ? match[2] : trimmed
71
97
  }
72
98
 
73
- export function liquidContext(before, mode = "output") {
99
+ export function liquidContext(before, mode = "output", { blocks = BLOCKS } = {}) {
74
100
  let expression = before
75
101
  let tag = null
102
+ let opened = 0
76
103
  if (mode === "output") {
77
104
  const output = before.lastIndexOf("{{")
78
105
  const open = Math.max(output, before.lastIndexOf("{%"))
79
106
  if (open < 0 || Math.max(before.lastIndexOf("}}"), before.lastIndexOf("%}")) > open) return null
80
107
  tag = open === output ? "{{" : "{%"
108
+ opened = open
81
109
  expression = before.slice(open + 2).replace(/^-/, "")
82
110
  }
83
111
  const offset = before.length - expression.length
84
112
  const quoted = openQuote(expression)
85
113
  const head = quoted ? expression.slice(0, quoted.at) : expression
86
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
+
87
130
  // In a filter's arguments: | name: a, b, …
88
131
  const filters = splitOutside(head, "|")
89
132
  if (filters.length > 1) {
@@ -112,13 +155,21 @@ export function liquidContext(before, mode = "output") {
112
155
  }
113
156
 
114
157
  // A value compared with a variable: line.party == "sp
115
- const compared = head.match(new RegExp(`(${PATH.source})\\s*(?:==|!=)\\s*$`))
116
- if (compared && (quoted || /(?:==|!=)\s*$/.test(expression))) {
117
- const partial = quoted ? expression.slice(quoted.at + 1) : ""
118
- return { kind: "value", of: compared[1], start: quoted ? offset + quoted.at : before.length, partial, quote: quoted?.quote || null, tag }
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 }
119
165
  }
120
166
  if (quoted) return null
121
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
+
122
173
  const match = expression.match(new RegExp(`(?:^|[^\\w.])(${PATH.source})?$`))
123
174
  if (!match) return null
124
175
  const path = match[1] || ""
@@ -22,6 +22,11 @@
22
22
  //
23
23
  // as Liquidum's FiltersController answers. A variable with `values`
24
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.
25
30
 
26
31
  import { ancestors } from "tess_edit/core/document"
27
32
  import { t } from "tess_edit/core/i18n"
@@ -34,6 +39,17 @@ export const KEEPS = {
34
39
  first: "item", last: "item", find: "item"
35
40
  }
36
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
+ ]
52
+
37
53
  // The members Liquid gives every collection
38
54
  export const COLLECTION_MEMBERS = [
39
55
  { name: "first", label: "First", type: "object", children: true },
@@ -44,9 +60,10 @@ export const COLLECTION_MEMBERS = [
44
60
  const ELEMENT = new Set(["first", "last"])
45
61
 
46
62
  export class Variables {
47
- constructor(url, { fetch: fetcher = (...args) => fetch(...args), filtersUrl = null } = {}) {
63
+ constructor(url, { fetch: fetcher = (...args) => fetch(...args), filtersUrl = null, tagsUrl = null } = {}) {
48
64
  this.url = url
49
65
  this.filtersUrl = filtersUrl
66
+ this.tagsUrl = tagsUrl
50
67
  this.fetch = fetcher
51
68
  this.levels = new Map()
52
69
  }
@@ -59,6 +76,14 @@ export class Variables {
59
76
  return this.filterList
60
77
  }
61
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
+
62
87
  async get(path, params) {
63
88
  const url = new URL(path, window.location.href)
64
89
  for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value)
@@ -125,11 +150,13 @@ export class Variables {
125
150
  const target = entry.path && (await this.variable(entry.path.split("."), scope.slice(index + 1)))
126
151
  own.push(entry.path ? { ...(target || { children: false }), name: entry.variable, label: t("Assigned %{path}", { path: entry.path }), assign: true } : loopVariable(entry))
127
152
  }
153
+ if (scope.some((entry) => entry.collection)) own.push(FORLOOP)
128
154
  return [...own, ...(await this.at(""))]
129
155
  }
130
156
 
131
157
  const variable = await this.variable(names, scope)
132
158
  if (!variable?.children) return []
159
+ if (variable.forloop) return FORLOOP_MEMBERS
133
160
  if (variable.collection) return COLLECTION_MEMBERS
134
161
  return this.at(resolve(names, scope))
135
162
  }
@@ -146,6 +173,7 @@ export class Variables {
146
173
  const parent = names.slice(0, -1)
147
174
  if (!parent.length) {
148
175
  const own = scope.find((entry) => entry.variable === last)
176
+ if (last === "forloop" && !own && scope.some((entry) => entry.collection)) return FORLOOP
149
177
  if (own?.path) return { ...(await this.variable(own.path.split("."), scope.slice(scope.indexOf(own) + 1))), name: last }
150
178
  if (own) return loopVariable(own)
151
179
  } else if (ELEMENT.has(last)) {
@@ -157,6 +185,8 @@ export class Variables {
157
185
  }
158
186
  }
159
187
 
188
+ const FORLOOP = { name: "forloop", label: "This loop", type: "object", children: true, forloop: true }
189
+
160
190
  function loopVariable({ variable, collection }) {
161
191
  return { name: variable, label: t("Each of %{collection}", { collection }), type: "object", children: true, loop: true }
162
192
  }
@@ -342,12 +342,13 @@ 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 mode = ["expression", "condition", "collection"].includes(field.liquid) ? field.liquid : "output"
351
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)
@@ -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,20 +4,25 @@
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
16
  // translations it also suggests their keys while typing {{ '. What it
15
17
  // suggests depends on what's being written (core/liquid.js liquidContext): a
16
18
  // variable; after a |, the host's filters; a filter's argument, a property of
17
- // the collection's items ("party") or a value it can have ("sponsor"); and
18
- // after == or !=, the values of the variable compared.
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.
19
24
 
20
- import { expressionParts, liquidContext, quoted, textScope } from "tess_edit/core/liquid"
25
+ import { BLOCKS, expressionParts, liquidContext, quoted, textScope } from "tess_edit/core/liquid"
21
26
  import { keyCompletion, keyToken } from "tess_edit/core/translations"
22
27
  import { completion } from "tess_edit/core/variables"
23
28
  import { t } from "tess_edit/core/i18n"
@@ -52,7 +57,10 @@ export class VariableMenu {
52
57
  const key = this.editor.translations?.enabled && adapter.mode === "output" && keyToken(before)
53
58
  if (key) return this.suggestKeys(adapter, key)
54
59
  if (!this.editor.variables?.enabled) return this.close()
55
- const context = liquidContext(before, adapter.mode === "output" ? "output" : "expression")
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 })
56
64
  if (!context) return this.close()
57
65
  const scope = [...textScope(before), ...(adapter.scope || [])]
58
66
  const request = ++this.request
@@ -90,6 +98,10 @@ export class VariableMenu {
90
98
  const filter = (await variables.filters()).get(context.filter)
91
99
  const kind = filter?.arguments?.[context.index]?.kind
92
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
+ }
93
105
  if (kind === "property" || kind === "value") {
94
106
  const elements = await this.elements(context.input, scope)
95
107
  if (!elements) return null
@@ -102,11 +114,54 @@ export class VariableMenu {
102
114
  }
103
115
  if (context.kind === "value") {
104
116
  const variable = await variables.lookup(context.of, scope)
105
- return this.quotedOptions(context, variable?.values || [], false)
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
+ }
106
133
  }
107
134
  return null
108
135
  }
109
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
+
110
165
  // The variables for a path being typed, from `context.start`
111
166
  async variableOptions(context, path, scope) {
112
167
  const dot = path.lastIndexOf(".")
@@ -130,16 +185,21 @@ export class VariableMenu {
130
185
  return this.editor.variables.options(`${entry.path}.first`, scope)
131
186
  }
132
187
 
133
- // Values in quotes ({ value, label }), then a comma for the next argument
134
- quotedOptions(context, choices, more) {
135
- const items = ranked(choices.map((choice) => ({ name: `"${choice.value}"`, value: choice.value, label: choice.label })), context.partial, (item) => item.value)
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)
136
196
  if (!items.length || (items.length === 1 && items[0].value === context.partial)) return null
137
197
  return {
138
198
  items,
139
199
  choose: async (item) => {
140
200
  const adapter = this.state.adapter
141
201
  const before = adapter.before()
142
- const { text, through } = quoted(item.value, { quote: context.quote, after: adapter.after() })
202
+ const { text, through } = item.literal ? { text: item.value, through: 0 } : quoted(item.value, { quote: context.quote, after: adapter.after() })
143
203
  adapter.replace(context.start, before.length + through, more ? `${text}, ` : text)
144
204
  more ? await this.suggest(adapter) : this.close()
145
205
  }
@@ -316,8 +376,9 @@ export function inputAdapter(input, { mode = "output", scope = [] } = {}) {
316
376
  scope,
317
377
  before: () => input.value.slice(0, input.selectionStart ?? input.value.length),
318
378
  after: () => input.value.slice(input.selectionEnd ?? input.value.length),
319
- replace(start, end, text) {
379
+ replace(start, end, text, { caret = null } = {}) {
320
380
  input.setRangeText(text, start, end, "end")
381
+ if (caret !== null) input.setSelectionRange(start + caret, start + caret)
321
382
  fire()
322
383
  },
323
384
  insert(text) {
@@ -350,3 +411,36 @@ function signature(filter) {
350
411
  const args = (filter.arguments || []).map((argument) => argument.name)
351
412
  return args.length ? `${filter.name}: ${args.join(", ")}` : filter.name
352
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,13 +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"
42
43
  assigned_path: "Assigned %{path}"
44
+ at_least: "At least"
45
+ at_most: "At most"
43
46
  auto: "Auto"
44
47
  background: "Background"
45
48
  background_image: "Background image"
46
49
  below_this_width_columns_stack: "Below this width columns stack."
47
50
  between_rows: "Between rows"
51
+ blank_nothing_or_only_spaces: "Blank: nothing, or only spaces"
48
52
  blocks: "Blocks"
49
53
  blocks_on_the_left_inspect_on_the_right: "Blocks on the left, Inspect on the right"
50
54
  bold_b: "Bold (⌘B)"
@@ -73,6 +77,7 @@ en:
73
77
  column_order: "Column order"
74
78
  column_width: "Column width"
75
79
  condition: "Condition"
80
+ contains: "Contains"
76
81
  content: "Content"
77
82
  copied: "Copied."
78
83
  copied_into_the_email_as_is_liquid_works_here_too: "Copied into the email as-is. Liquid works here too."
@@ -86,6 +91,7 @@ en:
86
91
  delete_row: "Delete row"
87
92
  desktop: "Desktop"
88
93
  divider: "Divider"
94
+ doesn_t_equal: "Doesn't equal"
89
95
  done: "Done"
90
96
  dotted: "Dotted"
91
97
  double_click_the_text_on_the_canvas_to_edit_it: "Double-click the text on the canvas to edit it."
@@ -110,6 +116,9 @@ en:
110
116
  email: "Email"
111
117
  empty: "(empty)"
112
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"
113
122
  every_other_row: "Every other row"
114
123
  expand: "Expand"
115
124
  find_in_source: "Find in %{source}"
@@ -121,6 +130,7 @@ en:
121
130
  fonts: "Fonts"
122
131
  full: "Full"
123
132
  full_width: "Full width"
133
+ goes_on_with_the_next_item: "Goes on with the next item"
124
134
  hamburger_on_mobile: "Hamburger on mobile"
125
135
  heading: "Heading"
126
136
  heading_level: "Heading %{level}"
@@ -145,6 +155,10 @@ en:
145
155
  inspect: "Inspect"
146
156
  instead_of_the_table_s_cell_padding: "Instead of the table's cell padding."
147
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"
148
162
  key: "Key"
149
163
  key_already_says_current_in_locale: "%{key} already says “%{current}” in %{locale}."
150
164
  key_no_locale_text: "%{key} · no %{locale} text"
@@ -154,6 +168,7 @@ en:
154
168
  layout: "Layout"
155
169
  left: "Left"
156
170
  left_to_right: "Left to right"
171
+ less_than: "Less than"
157
172
  letter_spacing: "Letter spacing"
158
173
  line_above: "Line above"
159
174
  line_height: "Line height"
@@ -181,6 +196,7 @@ en:
181
196
  missing: "missing"
182
197
  mobile: "Mobile"
183
198
  mode: "Mode"
199
+ more_than: "More than"
184
200
  move_up: "Move up"
185
201
  name_can_t_go_here_its_type_blocks_don_t_fit: "%{name} can't go here: its %{type} blocks don't fit."
186
202
  name_canvas: "%{name} canvas"
@@ -202,6 +218,9 @@ en:
202
218
  open_in: "Open in"
203
219
  open_source: "Open %{source}"
204
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"
205
224
  padding: "Padding"
206
225
  paragraph: "Paragraph"
207
226
  paragraph_style: "Paragraph style"
@@ -240,6 +259,7 @@ en:
240
259
  solid: "Solid"
241
260
  spacer: "Spacer"
242
261
  spans_columns: "Spans columns"
262
+ stops_the_loop: "Stops the loop"
243
263
  strikethrough: "Strikethrough"
244
264
  style: "Style"
245
265
  subject: "Subject"
@@ -260,6 +280,7 @@ en:
260
280
  there_s_nothing_here_yet: "There's nothing here yet."
261
281
  thickness: "Thickness"
262
282
  this: "This"
283
+ this_loop: "This loop"
263
284
  too_narrow_to_split_the_panels: "Too narrow to split the panels"
264
285
  top: "Top"
265
286
  translations: "Translations"
@@ -278,5 +299,9 @@ en:
278
299
  vertical_align: "Vertical align"
279
300
  web: "Web"
280
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"
281
306
  width: "Width"
282
307
  wrapper: "Wrapper"
@@ -38,13 +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"
42
43
  assigned_path: "Toegewezen: %{path}"
44
+ at_least: "Minstens"
45
+ at_most: "Hoogstens"
43
46
  auto: "Automatisch"
44
47
  background: "Achtergrond"
45
48
  background_image: "Achtergrondafbeelding"
46
49
  below_this_width_columns_stack: "Onder deze breedte komen kolommen onder elkaar."
47
50
  between_rows: "Tussen rijen"
51
+ blank_nothing_or_only_spaces: "Leeg: niets, of alleen spaties"
48
52
  blocks: "Blokken"
49
53
  blocks_on_the_left_inspect_on_the_right: "Blokken links, eigenschappen rechts"
50
54
  bold_b: "Vet (⌘B)"
@@ -73,6 +77,7 @@ nl:
73
77
  column_order: "Kolomvolgorde"
74
78
  column_width: "Kolombreedte"
75
79
  condition: "Voorwaarde"
80
+ contains: "Bevat"
76
81
  content: "Inhoud"
77
82
  copied: "Gekopieerd."
78
83
  copied_into_the_email_as_is_liquid_works_here_too: "Wordt ongewijzigd in de e-mail gezet. Liquid werkt hier ook."
@@ -86,6 +91,7 @@ nl:
86
91
  delete_row: "Rij verwijderen"
87
92
  desktop: "Desktop"
88
93
  divider: "Scheidingslijn"
94
+ doesn_t_equal: "Is niet gelijk aan"
89
95
  done: "Klaar"
90
96
  dotted: "Gestippeld"
91
97
  double_click_the_text_on_the_canvas_to_edit_it: "Dubbelklik op de tekst op het canvas om die te bewerken."
@@ -110,6 +116,9 @@ nl:
110
116
  email: "E-mail"
111
117
  empty: "(leeg)"
112
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"
113
122
  every_other_row: "Om de andere rij"
114
123
  expand: "Vergroten"
115
124
  find_in_source: "Zoeken in %{source}"
@@ -121,6 +130,7 @@ nl:
121
130
  fonts: "Lettertypen"
122
131
  full: "Volledig"
123
132
  full_width: "Volle breedte"
133
+ goes_on_with_the_next_item: "Gaat door met het volgende item"
124
134
  hamburger_on_mobile: "Hamburgermenu op mobiel"
125
135
  heading: "Kop"
126
136
  heading_level: "Kop %{level}"
@@ -145,6 +155,10 @@ nl:
145
155
  inspect: "Eigenschappen"
146
156
  instead_of_the_table_s_cell_padding: "In plaats van de celmarge van de tabel."
147
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"
148
162
  key: "Sleutel"
149
163
  key_already_says_current_in_locale: "%{key} is in het %{locale} al “%{current}”."
150
164
  key_no_locale_text: "%{key} · geen %{locale}-tekst"
@@ -154,6 +168,7 @@ nl:
154
168
  layout: "Layout"
155
169
  left: "Links"
156
170
  left_to_right: "Links naar rechts"
171
+ less_than: "Minder dan"
157
172
  letter_spacing: "Letterafstand"
158
173
  line_above: "Lijn erboven"
159
174
  line_height: "Regelhoogte"
@@ -181,6 +196,7 @@ nl:
181
196
  missing: "ontbreekt"
182
197
  mobile: "Mobiel"
183
198
  mode: "Modus"
199
+ more_than: "Meer dan"
184
200
  move_up: "Omhoog"
185
201
  name_can_t_go_here_its_type_blocks_don_t_fit: "%{name} kan hier niet: de blokken %{type} passen er niet in."
186
202
  name_canvas: "%{name}-canvas"
@@ -202,6 +218,9 @@ nl:
202
218
  open_in: "Openen in"
203
219
  open_source: "%{source} openen"
204
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"
205
224
  padding: "Ruimte"
206
225
  paragraph: "Alinea"
207
226
  paragraph_style: "Alineastijl"
@@ -240,6 +259,7 @@ nl:
240
259
  solid: "Doorgetrokken"
241
260
  spacer: "Witruimte"
242
261
  spans_columns: "Beslaat kolommen"
262
+ stops_the_loop: "Stopt de lus"
243
263
  strikethrough: "Doorhalen"
244
264
  style: "Stijl"
245
265
  subject: "Onderwerp"
@@ -260,6 +280,7 @@ nl:
260
280
  there_s_nothing_here_yet: "Hier staat nog niets."
261
281
  thickness: "Dikte"
262
282
  this: "Dit"
283
+ this_loop: "Deze lus"
263
284
  too_narrow_to_split_the_panels: "Te smal om de panelen te verdelen"
264
285
  top: "Boven"
265
286
  translations: "Vertalingen"
@@ -278,5 +299,9 @@ nl:
278
299
  vertical_align: "Verticale uitlijning"
279
300
  web: "Web"
280
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"
281
306
  width: "Breedte"
282
307
  wrapper: "Kader"
@@ -1,3 +1,3 @@
1
1
  module TessEdit
2
- VERSION = "0.5.12"
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.12
4
+ version: 0.5.13
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tom de Grunt