tess_edit 0.5.3 → 0.5.5

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: f82d8e8c56d5625f8f107f277eca46f3f925f1efd3a61c04869416f9cf22c1f0
4
- data.tar.gz: 2ae16142383df65bc903ed777e1a8e040d9a48985ec326a7bc6d63488659da20
3
+ metadata.gz: d9e9b7a64743faae5c3291e13d37a4ed05e76501a6133218aabb569681df4974
4
+ data.tar.gz: 322204628014614d615f0cad63d04acdd07d410b9ea02417287f47eaa4530919
5
5
  SHA512:
6
- metadata.gz: 02ad9420d971ac73f9d86f594ef543f55ca3778ed31626d27b781714c9ba00886db964b6d7a98ce220dabc995cec61100ca20d0fdaa0bb9aaa327bba103deb20
7
- data.tar.gz: 0c7596f3ffe417f49bee62cef20dde71c1cd9584c35df42c3dae41927442c1f209d6e3b6f4ae728b1f548b3cbff7aa46d96c043baac5f53547f470542120fc59
6
+ metadata.gz: e1163e2a6a1c06464db00540eb42b467db92d5640ae05bedf0906e2968ae9541b54439bd685084bacde1b9c4a97b4512652c4d71210e190ace96ded1628dd392
7
+ data.tar.gz: 7cbc3479b8009322508e19de37d1f2f959414d731feb9f1a87e059be3b95808b0d64b75d62ce1aee30e6a0636ab371297e7cd030383637d6b2fccfe45da801ac
data/README.md CHANGED
@@ -16,9 +16,10 @@ It completes Liquid tags and variables as you type, making it easier to work wit
16
16
  - Blocks: Section (1-4 columns), Column, Wrapper, Hero, Text, Heading, Image, Button, Divider, Spacer, Social, Navbar and raw HTML.
17
17
  - Liquid blocks: **Loop** (`{% for line in order.lines %}`) and **Condition** (`{% if order.total > 100 %}`) wrap other blocks.
18
18
  - Drag from the Blocks panel onto the canvas or into the Layers tree; move blocks on the canvas (drag handle) or in the tree; plus buttons and empty-column placeholders open an "Add block" menu.
19
- - 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.
19
+ - Rich text editing on the canvas with [Tiptap](https://tiptap.dev): bold, italic, underline, strikethrough, colour, links (Liquid allowed in the URL), alignment, lists and headings. A block can have several texts edited on the canvas, rich or a plain line, such as a question's label and its description.
20
20
  - Your app's Liquid variables suggested while typing `{{`, in text and in settings, and browsable from `{ }` buttons, including those of the Loop blocks around a block.
21
21
  - Your app's translations for Liquid's `t` filter (`{{ '.greeting' | t }}`) shown as their text in a language of your choice, with every language's text, missing ones marked, editable when pointed at, and selected text made translatable.
22
+ - 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.
22
23
  - Undo/redo, duplicate, delete, keyboard shortcuts (⌘Z, ⇧⌘Z, ⌘D, Delete, Enter to edit text, Esc).
23
24
  - Desktop and mobile preview, and a preview of the HTML as sent.
24
25
  - Panels on both sides, or combined as tabs in one sidebar on the left or right to give the canvas more room.
@@ -103,6 +104,8 @@ Every change updates the inputs and dispatches `tess-edit:change` with `{ json,
103
104
 
104
105
  Render the HTML with Liquid when sending. A host app can also store only the JSON or MJML and compile on its own with `TessEdit.compile(mjml)`.
105
106
 
107
+ The fields are written a moment after each change. A form submitted before that, such as a Save clicked right after typing, waits for them and then goes on, also with Turbo.
108
+
106
109
  ### Compiling
107
110
 
108
111
  The editor turns the JSON into MJML in the browser and has the server compile the MJML to HTML, with [MRML](https://github.com/jdrouet/mrml) (the `mrml` gem, precompiled, no Node or Rust needed). The canvas, the preview and the `html` input all come from the same compiler the host app uses when it sends:
@@ -280,6 +283,21 @@ Roles say where a block may go: `body` (in the email or a wrapper, like sections
280
283
 
281
284
  `extendBlock(type, { fields })` adds fields to a block that is registered: a group with the title of one of its groups adds to that one, any other goes last, or before the group its `before` names.
282
285
 
286
+ #### Texts edited on the canvas
287
+
288
+ A block's `richText: "data.content"` is a Tiptap value edited on the block's own element, by clicking a selected block or double-clicking it. A block with more texts, or with other content around its text, declares its parts with `inline` instead, and marks the element of each with `data-tess-edit-field` in the editor:
289
+
290
+ ```js
291
+ registerBlock({
292
+ type: "question",
293
+ inline: [{ key: "data.label", plain: true }, { key: "data.description" }],
294
+ render: { form: (node, { editor }) => `<label${editor ? ' data-tess-edit-field="data.label"' : ""}>${node.data.label}</label> <input> …` },
295
+ …
296
+ })
297
+ ```
298
+
299
+ The text editor is mounted on that element only, so the rest of the block, such as an input, stays as it is. A `plain` part is one line of text, stored as a string: no toolbar or marks, and Enter or leaving it finishes. The others are rich text as above, finished with Esc. A part can also be a field in Inspect, so both ways work. A key with a `*` stands for that part of each item of a list: `{ key: "data.options.*.label", plain: true }` makes every option's label editable, each marked with its own key (`data-tess-edit-field="data.options.0.label"`). The demo's Note kit has a Card block with both (`test/dummy/app/javascript/kits/note.js`).
300
+
283
301
  #### Your own form fields in Inspect
284
302
 
285
303
  A `slot` field shows an element of your page in Inspect, for settings that aren't part of the document, such as a template's trigger in your own form fields. Render the element inside the editor, hidden, as a `slot` target named by `data-tess-edit-slot`:
@@ -304,6 +322,24 @@ extendBlock("email", {
304
322
 
305
323
  With a `summary` the field shows collapsed to it, with a button to edit it; without one the element always shows. Its values are your form fields, submitted with the form; without the element the field doesn't show. The element moves into Inspect once and stays there, hidden while another block is selected, so your Stimulus controllers in it keep their state. Combining or splitting the panels moves it again: its controllers reconnect then, with the values typed and chosen written into the fields' attributes first. The demo has one at `/?slots=1` (`test/dummy/app/javascript/slots.js`).
306
324
 
325
+ #### Field types of your own
326
+
327
+ For a field TessEdit's types can't make, such as one whose parts depend on each other, register a type of your own and use it in a block's `fields`:
328
+
329
+ ```js
330
+ import { registerFieldType } from "tess_edit"
331
+
332
+ registerFieldType("rules", (node, field, value, set, editor) => {
333
+ const element = document.createElement("div")
334
+ // … inputs that call set(next) with the field's new value
335
+ return element
336
+ })
337
+
338
+ registerBlock({ …, fields: [{ title: "Show when", fields: [{ key: "data.rules", label: "Rules", type: "rules" }] }] })
339
+ ```
340
+
341
+ The element goes under the field's label in Inspect. `value` is the field's value (`undefined` when it has none) and `set(next)` stores a new one as an undo step. Inspect doesn't render the field again after a `set`, so the element keeps its focus and updates itself; it renders it again when another block is selected or the document changes otherwise. A locked field's element is disabled through a fieldset. TessEdit's own types can't be replaced. The demo's Card block has one, `stars`.
342
+
307
343
  A select field's `options` can be a function of the editor, `options: (editor) => [...]`, for choices from your app. Give the editor those with `data-tess-edit-options-value` (JSON), which blocks read as `editor.options`. Font family fields are a select of `editor.options.fonts`: CSS font families as text, `"Maytra"` or `"'EB Garamond', serif"`, or `{ value, label }`; without them, common web fonts (`fields.FONTS`). A font a design has that isn't among them stays selected. The field lists each font in itself, with a search box, so your page needs the fonts too, such as `@font-face` rules: a browser loads a font only once it's used, and the list shows fonts as they scroll into view.
308
344
 
309
345
  ## Kits
@@ -1,7 +1,8 @@
1
1
  // Field definitions shared by the built-in blocks, and usable by custom ones.
2
2
  // A field: { key: "attributes.padding" | "data.subject", label, type, ... }.
3
3
  // Types: text, textarea, code, size, color, select, font, segmented, toggle,
4
- // spacing, list and slot (an element of the host's); see ui/inspector.js. A
4
+ // spacing, list and slot (an element of the host's); see ui/inspector.js,
5
+ // and the host's own, registerFieldType (core/registry.js). A
5
6
  // font field is a select of the host's fonts, the editor's options.fonts, or
6
7
  // FONTS without them. A select's options can be a
7
8
  // function of the editor, options(editor), for choices the host gives. A
@@ -47,7 +47,7 @@ import { Controller } from "@hotwired/stimulus"
47
47
  import { accepted, ancestors, createDocument, createFromPalette, duplicate, find, findType, getValue, insert, itemType, misfit, move, normalize, remove, setValue, walk } from "tess_edit/core/document"
48
48
  import { History } from "tess_edit/core/history"
49
49
  import { canEditField, canFill, isFree, parseLock } from "tess_edit/core/lock"
50
- import { DEFAULT_KIT, getBlock, getKit, paletteItems, paletteSources } from "tess_edit/core/registry"
50
+ import { DEFAULT_KIT, getBlock, getKit, inlinePart, inlineParts, paletteItems, paletteSources } from "tess_edit/core/registry"
51
51
  import { COMPILE_URL } from "tess_edit/export/compile"
52
52
  import { IMAGE_FIELD, fetchMedia, uploadMedia } from "tess_edit/core/media"
53
53
  import { Translations, keysIn, suggestKey, toTranslation, translationTag } from "tess_edit/core/translations"
@@ -98,6 +98,7 @@ export default class extends Controller {
98
98
  this.doc = this.loadInitial()
99
99
  this.selectedId = this.doc.id
100
100
  this.editingId = null
101
+ this.editingPart = null
101
102
  this.drag = null
102
103
  this.mode = "edit"
103
104
  this.device = this.kit.devices?.[0]?.key || null
@@ -118,6 +119,10 @@ export default class extends Controller {
118
119
  this.build()
119
120
  this.renderAll()
120
121
  this.writeOutputs()
122
+ // The form it's in waits for the outputs still to be written (beforeSubmit)
123
+ this.form = this.element.closest("form")
124
+ this.beforeSubmit = this.beforeSubmit.bind(this)
125
+ this.form?.addEventListener("submit", this.beforeSubmit, true)
121
126
  if (this.media.enabled) this.loadMedia()
122
127
  this.loadSources()
123
128
  if (this.translations.enabled) {
@@ -286,6 +291,7 @@ export default class extends Controller {
286
291
  }
287
292
 
288
293
  disconnect() {
294
+ this.form?.removeEventListener("submit", this.beforeSubmit, true)
289
295
  this.scheduleCanvas.cancel()
290
296
  this.scheduleOutputs.cancel()
291
297
  Object.values(this.requests).forEach((request) => request.abort())
@@ -644,7 +650,34 @@ export default class extends Controller {
644
650
  this.errorBar.classList.toggle("hidden", !errors.length)
645
651
  }
646
652
 
647
- async writeOutputs() {
653
+ // A submit while the outputs are still to be written, or being written,
654
+ // waits for them and then goes on, so the form sends the document as it
655
+ // is, also right after a change
656
+ beforeSubmit(event) {
657
+ if (this.resubmitting || (!this.scheduleOutputs.pending() && !this.writing)) return
658
+ event.preventDefault()
659
+ event.stopImmediatePropagation()
660
+ const submitter = event.submitter
661
+ // Submitted again in a task of its own: during this submit event's, the
662
+ // browser ignores it
663
+ Promise.resolve(this.scheduleOutputs.flush() || this.writing).then(() => setTimeout(() => {
664
+ this.resubmitting = true
665
+ try {
666
+ this.form.requestSubmit(submitter?.form === this.form ? submitter : undefined)
667
+ } finally {
668
+ this.resubmitting = false
669
+ }
670
+ }))
671
+ }
672
+
673
+ writeOutputs() {
674
+ const writing = (this.writing = this.write().finally(() => {
675
+ if (this.writing === writing) this.writing = null
676
+ }))
677
+ return writing
678
+ }
679
+
680
+ async write() {
648
681
  this.loadTranslations()
649
682
  const json = JSON.stringify(this.doc)
650
683
  const result = await this.run("outputs", (options) => this.kit.outputs(this.doc, options))
@@ -711,23 +744,28 @@ export default class extends Controller {
711
744
  this.select(siblings[Math.min(hit.index, siblings.length - 1)]?.id || hit.parent.id)
712
745
  }
713
746
 
714
- startEditing(id) {
747
+ // Edits an inline part of a block on the canvas: the one with this key,
748
+ // or its first (see `inline` in core/registry.js)
749
+ startEditing(id, key = null) {
715
750
  const hit = find(this.doc, id)
716
- const key = hit && getBlock(hit.node.type)?.richText
717
- if (!key || this.mode !== "edit" || !this.isFree(id)) return
718
- if (this.editingId === id) return
751
+ const part = hit && (key ? inlinePart(hit.node.type, key) : inlineParts(hit.node.type)[0])
752
+ if (!part || this.mode !== "edit" || !this.canEditField(id, part.key)) return
753
+ if (this.editingId === id && this.editingPart?.key === part.key) return
719
754
  this.stopEditing()
720
755
  this.select(id)
721
- const container = this.canvas.textContainer(id)
756
+ const container = this.canvas.textContainer(id, part.key)
722
757
  if (!container) return
723
758
  this.editingId = id
759
+ this.editingPart = part
724
760
  this.editSnapshot = JSON.stringify(this.doc)
725
- this.textEditing.start(container, getValue(hit.node, key), (json) => {
726
- setValue(this.doc, id, key, json)
761
+ const update = (value) => {
762
+ setValue(this.doc, id, part.key, value)
727
763
  this.tree.render()
728
764
  this.canvas.refresh()
729
765
  this.scheduleOutputs()
730
- }, { scope: loopScope(this.doc, id) })
766
+ }
767
+ if (part.plain) this.textEditing.startPlain(container, getValue(hit.node, part.key), update, () => this.stopEditing())
768
+ else this.textEditing.start(container, getValue(hit.node, part.key), update, { scope: loopScope(this.doc, id) })
731
769
  this.canvas.refresh()
732
770
  }
733
771
 
@@ -735,6 +773,7 @@ export default class extends Controller {
735
773
  if (!this.editingId) return
736
774
  this.textEditing.stop()
737
775
  this.editingId = null
776
+ this.editingPart = null
738
777
  if (this.editSnapshot !== JSON.stringify(this.doc)) this.history.record(this.editSnapshot)
739
778
  this.editSnapshot = null
740
779
  this.renderTopBar()
@@ -823,14 +862,15 @@ export default class extends Controller {
823
862
 
824
863
  // Clicking a tile: add inside the selection when it fits, otherwise after the
825
864
  // nearest ancestor that fits, otherwise at the end of the root, or with a
826
- // lock, at the end of the first unlocked block it fits in.
865
+ // lock, at the end of the first unlocked block it fits in, or without one,
866
+ // at the end of the last block it fits in (a form's last page, say).
827
867
  addFromPalette(key) {
828
868
  const type = itemType(key)
829
869
  const place = this.placeFor((parentId) => this.accepted(parentId).includes(type))
830
870
  if (place) return this.insertAt(key, place.parentId, place.index)
831
871
  const definition = getBlock(type)
832
872
  if (definition?.unique && findType(this.doc, type)) return this.flash(`There is a ${definition.name} already; a document has one.`)
833
- this.flash(`${definition?.name || key} has to go inside a column. Select one first, or drag it onto the canvas.`)
873
+ this.flash(`${definition?.name || key} doesn't fit anywhere yet. Add a block it goes in first, or drag it onto the canvas.`)
834
874
  }
835
875
 
836
876
  // Where a click on a tile adds a block, for blocks that `fits` a parent
@@ -848,8 +888,13 @@ export default class extends Controller {
848
888
  if (this.lock.except.includes(node.type) && fits(node.id)) target = node
849
889
  })
850
890
  if (target) return { parentId: target.id, index: target.children.length }
891
+ return null
851
892
  }
852
- return null
893
+ let last = null
894
+ walk(this.doc, (node) => {
895
+ if (fits(node.id)) last = node
896
+ })
897
+ return last ? { parentId: last.id, index: last.children.length } : null
853
898
  }
854
899
 
855
900
  // Inserts what a palette source's tile creates (see core/registry.js) at a
@@ -965,7 +1010,7 @@ export default class extends Controller {
965
1010
  event.preventDefault()
966
1011
  this.remove(this.selectedId)
967
1012
  }
968
- } else if (event.key === "Enter" && getBlock(find(this.doc, this.selectedId)?.node.type)?.richText) {
1013
+ } else if (event.key === "Enter" && inlineParts(find(this.doc, this.selectedId)?.node.type).length) {
969
1014
  event.preventDefault()
970
1015
  this.startEditing(this.selectedId)
971
1016
  } else if (event.key === "Escape") {
@@ -175,14 +175,20 @@ export function duplicate(doc, id) {
175
175
  return copy
176
176
  }
177
177
 
178
- // Sets a value on a node. `key` is "attributes.padding" or "data.subject".
178
+ // Sets a value on a node. `key` is "attributes.padding" or "data.subject",
179
+ // or deeper into a list, "data.options.0.label" (an inline part of each item,
180
+ // see `inline` in core/registry.js).
179
181
  // An empty string removes an attribute, so MJML falls back to its default.
180
182
  export function setValue(doc, id, key, value) {
181
183
  const hit = find(doc, id)
182
184
  if (!hit) return
183
- const [scope, name] = key.split(".")
185
+ const [scope, name, ...rest] = key.split(".")
184
186
  hit.node[scope] ||= {}
185
- if (scope === "attributes" && (value === "" || value === null || value === undefined)) {
187
+ if (rest.length) {
188
+ let target = hit.node[scope][name]
189
+ for (const step of rest.slice(0, -1)) target = target?.[step]
190
+ if (target && typeof target === "object") target[rest.at(-1)] = value
191
+ } else if (scope === "attributes" && (value === "" || value === null || value === undefined)) {
186
192
  delete hit.node[scope][name]
187
193
  } else {
188
194
  hit.node[scope][name] = value
@@ -190,8 +196,7 @@ export function setValue(doc, id, key, value) {
190
196
  }
191
197
 
192
198
  export function getValue(node, key) {
193
- const [scope, name] = key.split(".")
194
- return node[scope]?.[name]
199
+ return key.split(".").reduce((value, step) => value?.[step], node)
195
200
  }
196
201
 
197
202
  // Light validation of a document read from storage or an import. With a
@@ -15,7 +15,13 @@
15
15
  // // a "code" field takes language: "html" (default) or "css"
16
16
  // hint: "Shown at the top of Inspect.",
17
17
  // label: (node) => `Product · ${node.data.sku}`, // optional, for Layers and the canvas
18
- // richText: "data.content", // optional: a Tiptap JSON value edited on the canvas by double-click
18
+ // richText: "data.content", // optional: a Tiptap JSON value edited on the canvas by double-click,
19
+ // // on the block's own element; the shorthand of one inline part
20
+ // inline: [{ key: "data.label", plain: true }, { key: "data.description" }],
21
+ // // optional: the parts edited on the canvas, each on the element
22
+ // // its render marks with data-tess-edit-field="<key>" in the
23
+ // // editor, so the rest of the block stays as it is. A plain part
24
+ // // is one line of text, a string; the others are Tiptap JSON
19
25
  // palette: [{ key, label, icon, category, create: ({ createNode }) => node }], // optional
20
26
  // kits: ["email"], // the kits it is part of, default ["email"]
21
27
  // unique: true, // optional: at most one per document, like Content
@@ -81,6 +87,7 @@ const definitions = new Map()
81
87
  const categoryList = new Map()
82
88
  const kitList = new Map()
83
89
  const sourceList = new Map()
90
+ const fieldTypeList = new Map()
84
91
 
85
92
  export const DEFAULT_KIT = "email"
86
93
 
@@ -156,10 +163,54 @@ export function registerBlock(definition) {
156
163
  ...item,
157
164
  type
158
165
  }))
159
- definitions.set(type, { roles: [], kits: [DEFAULT_KIT], ...definition, palette })
166
+ const inline = definition.inline ?? (definition.richText ? [{ key: definition.richText }] : [])
167
+ if (inline.some((part) => !part?.key)) throw new Error(`Block ${type} needs a key for each inline part`)
168
+ definitions.set(type, { roles: [], kits: [DEFAULT_KIT], ...definition, palette, inline })
160
169
  return definitions.get(type)
161
170
  }
162
171
 
172
+ // The parts of a block edited on the canvas (see `inline`)
173
+ export function inlineParts(type) {
174
+ return getBlock(type)?.inline || []
175
+ }
176
+
177
+ // The part with this key; a part whose key has a * stands for that part of
178
+ // each item of a list, e.g. "data.options.*.label" for "data.options.2.label"
179
+ export function inlinePart(type, key) {
180
+ const part = inlineParts(type).find((candidate) => candidate.key === key || (candidate.key.includes("*") && keyPattern(candidate.key).test(key || "")))
181
+ return part && { ...part, key }
182
+ }
183
+
184
+ function keyPattern(key) {
185
+ return new RegExp(`^${key.split("*").map((piece) => piece.replace(/[.]/g, "\\.")).join("\\d+")}$`)
186
+ }
187
+
188
+ // The field types of ui/inspector.js
189
+ export const FIELD_TYPES = ["text", "textarea", "code", "size", "color", "select", "font", "segmented", "toggle", "spacing", "list", "image", "slot"]
190
+
191
+ // A field type of the host's, for what TessEdit's own can't do, such as
192
+ // parts that depend on each other:
193
+ //
194
+ // registerFieldType("rules", (node, field, value, set, editor) => element)
195
+ //
196
+ // It renders the control under the field's label in Inspect: value is the
197
+ // field's value (undefined when it has none), set(next) stores a new one as
198
+ // an undo step. Inspect doesn't render the field again after a set, so the
199
+ // element keeps its focus and updates itself; it renders all fields again
200
+ // when another block is selected or the document changes otherwise. A
201
+ // locked field's element is disabled through a fieldset around it.
202
+ // Registering a type again replaces it; TessEdit's own can't be.
203
+ export function registerFieldType(type, render) {
204
+ if (!type || typeof type !== "string") throw new Error("A field type needs a name")
205
+ if (FIELD_TYPES.includes(type)) throw new Error(`Field type ${type} is TessEdit's own`)
206
+ if (typeof render !== "function") throw new Error(`Field type ${type} needs render(node, field, value, set, editor)`)
207
+ fieldTypeList.set(type, render)
208
+ }
209
+
210
+ export function fieldType(type) {
211
+ return fieldTypeList.get(type)
212
+ }
213
+
163
214
  // Adds kits, render hooks and field groups to a registered block. A group
164
215
  // with the title of one it has adds its fields to that one; a new group goes
165
216
  // last, or before the group its `before` names.
@@ -12,7 +12,7 @@ export { compile } from "tess_edit/export/compile"
12
12
  export { escapeAttribute, escapeText, richTextToHtml } from "tess_edit/export/richtext"
13
13
  export { contentNode, createDocument, createNode, findType, normalize, renumber, withContent } from "tess_edit/core/document"
14
14
  export { CONTENT_END, CONTENT_START } from "tess_edit/blocks/content"
15
- export { registerBlock, registerCategory, registerKit, registerPaletteSource, extendBlock, getBlock, getKit, kitOf, kits, blockTypes, paletteItems, paletteSources } from "tess_edit/core/registry"
15
+ export { registerBlock, registerCategory, registerFieldType, registerKit, registerPaletteSource, extendBlock, getBlock, getKit, kitOf, kits, blockTypes, paletteItems, paletteSources } from "tess_edit/core/registry"
16
16
  export * as fields from "tess_edit/blocks/fields"
17
17
  export { imageField } from "tess_edit/core/media"
18
18
  export { starterDocument } from "tess_edit/core/starter"
@@ -6,7 +6,7 @@
6
6
 
7
7
  import { ancestors, find, isDescendant, isHorizontal } from "tess_edit/core/document"
8
8
  import { imageFields } from "tess_edit/core/media"
9
- import { getBlock, label } from "tess_edit/core/registry"
9
+ import { getBlock, inlinePart, label } from "tess_edit/core/registry"
10
10
  import { missingArguments, textParts, translationCalls } from "tess_edit/core/translations"
11
11
  import { FREE_CSS, FreeLayout } from "tess_edit/ui/free_layout"
12
12
  import { icon } from "tess_edit/ui/icons"
@@ -22,6 +22,8 @@ body{min-height:100vh;margin:0}
22
22
  .tess-label{position:absolute;bottom:100%;left:0;background:#2563eb;color:#fff;padding:3px 6px;border-radius:4px 4px 0 0;white-space:nowrap}
23
23
  .tess-hover .tess-label{background:#60a5fa}
24
24
  .tess-editing .tess-label{background:#f59e0b}
25
+ .tess-plain{outline:none;cursor:text}
26
+ .tess-plain:empty{display:inline-block;min-width:1px}
25
27
  .tess-inside .tess-label,.tess-inside .tess-tools{bottom:auto;top:0;border-radius:0 0 4px 4px}
26
28
  .tess-tools{position:absolute;bottom:100%;right:0;display:flex;gap:1px;pointer-events:auto;background:#2563eb;border-radius:4px 4px 0 0;padding:1px}
27
29
  .tess-tools [data-tool]{cursor:pointer;color:#fff;width:22px;height:20px;display:flex;align-items:center;justify-content:center;border-radius:3px;background:none;border:0;padding:0}
@@ -218,11 +220,29 @@ export class Canvas {
218
220
  return { left, top, right, bottom, width: right - left, height: bottom - top }
219
221
  }
220
222
 
221
- textContainer(id) {
223
+ // Where an inline part is edited: the element its render marks with
224
+ // data-tess-edit-field, or for the richText shorthand the block's own
225
+ textContainer(id, key) {
222
226
  const cell = this.doc?.querySelector(`.tess-${id}`)
227
+ const part = this.partElement(cell, key)
228
+ if (part) return part
229
+ if (key !== getBlock(find(this.editor.doc, id)?.node.type)?.richText) return null
223
230
  return cell?.querySelector(":scope > div") || cell
224
231
  }
225
232
 
233
+ partElement(cell, key) {
234
+ return [...(cell?.querySelectorAll("[data-tess-edit-field]") || [])].find((element) => element.dataset.tessEditField === key)
235
+ }
236
+
237
+ // The inline part of a block at a clicked element: a marked one, or the
238
+ // richText shorthand's anywhere in the block
239
+ partAt(target, id) {
240
+ const definition = getBlock(find(this.editor.doc, id)?.node.type)
241
+ const marked = target.closest?.("[data-tess-edit-field]")
242
+ if (marked && this.hit(marked)?.id === id && definition && inlinePart(definition.type, marked.dataset.tessEditField)) return marked.dataset.tessEditField
243
+ return definition?.richText || null
244
+ }
245
+
226
246
  // --- overlay ---------------------------------------------------------------
227
247
 
228
248
  box(rect, className) {
@@ -258,7 +278,7 @@ export class Canvas {
258
278
  if (!rect) return
259
279
  const box = this.box(rect, editingId === selectedId ? "tess-selected tess-editing" : "tess-selected")
260
280
  const free = this.editor.isFree(selectedId)
261
- box.append(Object.assign(this.doc.createElement("div"), { className: "tess-label", textContent: editingId === selectedId ? "Editing text · Esc to finish" : free || !this.editor.lock ? label(hit.node) : `${label(hit.node)} · Layout` }))
281
+ box.append(Object.assign(this.doc.createElement("div"), { className: "tess-label", textContent: editingId === selectedId ? `Editing text · ${this.editor.editingPart?.plain ? "Enter" : "Esc"} to finish` : free || !this.editor.lock ? label(hit.node) : `${label(hit.node)} · Layout` }))
262
282
 
263
283
  const handle = this.free.handle(selectedId)
264
284
  if (handle) box.append(handle)
@@ -330,7 +350,7 @@ export class Canvas {
330
350
  }
331
351
 
332
352
  onClick(event) {
333
- if (this.editor.editingId && event.target.closest?.(".ProseMirror")) return
353
+ if (this.editor.editingId && event.target.closest?.(".ProseMirror, .tess-plain")) return
334
354
  if (event.target.closest?.("#tess-overlay")) return
335
355
  event.preventDefault()
336
356
  if (this.openLink(event)) return
@@ -342,8 +362,9 @@ export class Canvas {
342
362
  this.editor.openInsertMenu(hit.id, 0, rect)
343
363
  return
344
364
  }
345
- if (hit && hit.id === this.editor.selectedId && getBlock(find(this.editor.doc, hit.id).node.type)?.richText) {
346
- this.editor.startEditing(hit.id)
365
+ const part = hit && hit.id === this.editor.selectedId && this.partAt(event.target, hit.id)
366
+ if (part) {
367
+ this.editor.startEditing(hit.id, part)
347
368
  return
348
369
  }
349
370
  this.editor.select(hit ? hit.id : this.editor.doc.id, { reveal: true })
@@ -360,7 +381,8 @@ export class Canvas {
360
381
 
361
382
  onDoubleClick(event) {
362
383
  const hit = this.hit(event.target)
363
- if (hit && !hit.placeholder && getBlock(find(this.editor.doc, hit.id).node.type)?.richText) this.editor.startEditing(hit.id)
384
+ const part = hit && !hit.placeholder && this.partAt(event.target, hit.id)
385
+ if (part) this.editor.startEditing(hit.id, part)
364
386
  }
365
387
 
366
388
  onDragOver(event) {
@@ -24,13 +24,26 @@ export function h(tag, props = {}, ...children) {
24
24
  return element
25
25
  }
26
26
 
27
+ // pending() says whether a call is waiting; flush() makes it now
27
28
  export function debounce(fn, wait) {
28
- let timer
29
+ let timer = null
30
+ let waiting = null
29
31
  const debounced = (...args) => {
30
32
  clearTimeout(timer)
31
- timer = setTimeout(() => fn(...args), wait)
33
+ waiting = args
34
+ timer = setTimeout(debounced.flush, wait)
35
+ }
36
+ debounced.cancel = () => {
37
+ clearTimeout(timer)
38
+ timer = waiting = null
39
+ }
40
+ debounced.pending = () => waiting !== null
41
+ debounced.flush = () => {
42
+ if (!waiting) return undefined
43
+ const args = waiting
44
+ debounced.cancel()
45
+ return fn(...args)
32
46
  }
33
- debounced.cancel = () => clearTimeout(timer)
34
47
  return debounced
35
48
  }
36
49
 
@@ -15,7 +15,7 @@
15
15
  // in Inspect, hidden while another block is selected (see place in ui/dom.js).
16
16
 
17
17
  import { imageSource } from "tess_edit/core/media"
18
- import { getBlock, label } from "tess_edit/core/registry"
18
+ import { fieldType, getBlock, label } from "tess_edit/core/registry"
19
19
  import { fontOptions } from "tess_edit/blocks/fields"
20
20
  import { find, getValue } from "tess_edit/core/document"
21
21
  import { translationCalls } from "tess_edit/core/translations"
@@ -197,6 +197,10 @@ export class Inspector {
197
197
  }
198
198
 
199
199
  control(node, field, value, set) {
200
+ // A host's own (registerFieldType in core/registry.js)
201
+ const custom = fieldType(field.type)
202
+ if (custom) return custom(node, field, getValue(node, field.key), set, this.editor)
203
+
200
204
  switch (field.type) {
201
205
  case "textarea":
202
206
  return this.variables(h("textarea", { class: `${INPUT} min-h-32`, rows: 4, value, oninput: (event) => set(event.target.value) }), node, field)
@@ -5,6 +5,10 @@
5
5
  // translations (`editor.translations`, core/translations.js) a t filter shows
6
6
  // its text in the editor's language until the caret goes into it, and the
7
7
  // toolbar turns selected text into a translation.
8
+ //
9
+ // A plain part (a block's inline part with plain: true, see core/registry.js)
10
+ // is one line of text, edited on its element itself, with no toolbar or
11
+ // marks: Enter or leaving it finishes (finish).
8
12
 
9
13
  import { Color, Decoration, DecorationSet, Editor, Extension, Plugin, PluginKey, StarterKit, TextAlign, TextStyle } from "tess_edit/vendor/tiptap"
10
14
  import { missingArguments, translationCalls } from "tess_edit/core/translations"
@@ -23,6 +27,7 @@ export class TextEditing {
23
27
  this.menu = menu
24
28
  this.editor = editor
25
29
  this.tiptap = null
30
+ this.plain = null
26
31
  }
27
32
 
28
33
  get translating() {
@@ -30,7 +35,43 @@ export class TextEditing {
30
35
  }
31
36
 
32
37
  get active() {
33
- return !!this.tiptap
38
+ return !!this.tiptap || !!this.plain
39
+ }
40
+
41
+ // One line of text on the element itself: onUpdate gets it as it's typed,
42
+ // finish when Enter is pressed or the element left
43
+ startPlain(element, value, onUpdate, finish) {
44
+ this.stop()
45
+ const text = () => element.textContent.replace(/\s*\n\s*/g, " ")
46
+ const listeners = {
47
+ input: () => onUpdate(text()),
48
+ keydown: (event) => {
49
+ if (event.key !== "Enter") return
50
+ // Not to the editor, which would start editing again
51
+ event.preventDefault()
52
+ event.stopPropagation()
53
+ finish()
54
+ },
55
+ blur: () => finish()
56
+ }
57
+ element.textContent = value ?? ""
58
+ element.contentEditable = "plaintext-only"
59
+ element.classList.add("tess-plain")
60
+ for (const [name, listener] of Object.entries(listeners)) element.addEventListener(name, listener)
61
+ this.plain = { element, listeners, text }
62
+ // Where it is: Safari scrolls to the caret, which in an empty inline
63
+ // element it puts at the top of the page (hence also .tess-plain:empty's
64
+ // box, in canvas.js)
65
+ const win = element.ownerDocument.defaultView
66
+ const { scrollX, scrollY } = win
67
+ element.focus({ preventScroll: true })
68
+ const range = element.ownerDocument.createRange()
69
+ range.selectNodeContents(element)
70
+ range.collapse(false)
71
+ element.ownerDocument.getSelection().removeAllRanges()
72
+ element.ownerDocument.getSelection().addRange(range)
73
+ if (win.scrollX !== scrollX || win.scrollY !== scrollY) win.scrollTo(scrollX, scrollY)
74
+ return element
34
75
  }
35
76
 
36
77
  // scope: the loop variables of the block (core/variables.js loopScope)
@@ -106,6 +147,7 @@ export class TextEditing {
106
147
  }
107
148
 
108
149
  stop() {
150
+ if (this.plain) return this.stopPlain()
109
151
  if (!this.tiptap) return null
110
152
  const json = this.tiptap.getJSON()
111
153
  this.menu?.close()
@@ -116,6 +158,15 @@ export class TextEditing {
116
158
  return json
117
159
  }
118
160
 
161
+ stopPlain() {
162
+ const { element, listeners, text } = this.plain
163
+ this.plain = null
164
+ for (const [name, listener] of Object.entries(listeners)) element.removeEventListener(name, listener)
165
+ element.removeAttribute("contenteditable")
166
+ element.classList.remove("tess-plain")
167
+ return text()
168
+ }
169
+
119
170
  renderToolbar() {
120
171
  const editor = this.tiptap
121
172
  if (!editor) return
@@ -1,3 +1,3 @@
1
1
  module TessEdit
2
- VERSION = "0.5.3"
2
+ VERSION = "0.5.5"
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.3
4
+ version: 0.5.5
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tom de Grunt