@portone/docx-editor 0.6.4 → 0.6.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # @portone/docx-editor
2
2
 
3
+ ## 0.6.5
4
+
5
+ ### Patch Changes
6
+
7
+ - [#182](https://github.com/portone-io/docx-editor/pull/182) [`13e5f9f`](https://github.com/portone-io/docx-editor/commit/13e5f9f42d27c047144f3fb22c00b2ac26dae168) Thanks [@Deea222](https://github.com/Deea222)! - Tell the application when an edit is refused, and let it theme locked content.
8
+
9
+ `DocxEditor` takes `onEditRefused`, called when typing, deleting, pasting,
10
+ dropping or formatting in the document body is turned down. It is handed an
11
+ `EditRefusal`: the rule that refused the edit (`lock`, `protection`,
12
+ `controlEdge`, `preserved` or `section`), what the edit would have done, and,
13
+ for a lock, the controls it reached with their `tag`, `alias`, `id`, lock and
14
+ level. Before this a refused keystroke did nothing at all and said nothing.
15
+
16
+ The right-click menus now say "Locked content can't be edited." when the
17
+ selection, or the table under it, holds locked content, which is why their
18
+ editing entries stand disabled.
19
+
20
+ Four custom properties theme how controls are drawn:
21
+ `--docx-editor-locked-background` and `--docx-editor-locked-outline` for locked
22
+ content, which keeps its yellow tint and orange outline by default, and
23
+ `--docx-editor-control-background` and `--docx-editor-control-outline` for a
24
+ content control that stays editable, which is not marked by default.
25
+
26
+ The yellow now shows over a locked table cell or row whose shading the
27
+ document states as `auto`, which used to hide it, and a cell's own shading
28
+ shows through the tint rather than hiding it.
29
+
30
+ - [#183](https://github.com/portone-io/docx-editor/pull/183) [`2423668`](https://github.com/portone-io/docx-editor/commit/242366886c89e96d633d2bc31312f42aaf37e4fd) Thanks [@Deea222](https://github.com/Deea222)! - Keep an inline content control when everything it holds is written over or deleted.
31
+
32
+ Selecting all of the text inside a content control that stands in a paragraph - a bracketed placeholder a template leaves to be filled in, say - and typing over it used to take the control away: the new text landed beside it as ordinary text, and the tag and id a server looks for when it fills the document in were gone. The same happened with a drag carried past the end of the line, a Shift-click, a triple click, a composition, and a paste. The new text now goes into the control, which keeps its tag, its id, and everything else it states, and what is typed next goes on into it.
33
+
34
+ Deleting everything the control holds now leaves the control in the file with nothing inside it, and text typed right after goes back into it. A control locked against deletion alone (`sdtLocked`) takes all of this, since its contents may be edited; before, deleting or retyping everything it held was refused. A selection that also takes in text outside the control still removes the control with that text, and a control locked against deletion still refuses it.
35
+
3
36
  ## 0.6.4
4
37
 
5
38
  ### Patch Changes
@@ -13,6 +13,7 @@ import { type CSSProperties, type ReactNode } from "react";
13
13
  import { type DocxSource } from "./docx/importDocx";
14
14
  import { type ExportProblem } from "./docx/invariants";
15
15
  import type { CommentAuthor } from "./editor/commands/commentCommands";
16
+ import type { EditRefusal } from "./editor/editRefusal";
16
17
  import { DocxImportError } from "./ooxml/errors";
17
18
  import type { EditableComments } from "./schema/protection";
18
19
  import type { FontFallbacks } from "./styles/fontStack";
@@ -145,6 +146,16 @@ export interface DocxEditorProps {
145
146
  onReady?: (view: EditorView) => void;
146
147
  /** Called every time the editor state changes. This covers cursor and selection moves, not just text edits */
147
148
  onChange?: () => void;
149
+ /**
150
+ * Called when the editor turns down an edit made in the document body: typing, deleting,
151
+ * pasting or dropping into locked content, or anything the `mode` does not take.
152
+ *
153
+ * The editor itself only leaves the document as it was, so this is where an application says
154
+ * why - a toast, a status line - in its own words. It is called once per refused edit, so a key
155
+ * held down calls it repeatedly. A command reporting `false` dispatches nothing and calls
156
+ * nothing.
157
+ */
158
+ onEditRefused?: (refusal: EditRefusal) => void;
148
159
  }
149
160
  /**
150
161
  * `forwardRef` rather than a `ref` prop: React 18 hands a function component no `ref`
@@ -178,7 +178,8 @@ function DocxEditorSurface({
178
178
  className,
179
179
  style,
180
180
  onReady,
181
- onChange
181
+ onChange,
182
+ onEditRefused
182
183
  }, ref) {
183
184
  const { protection, author, editableComments, toolbar, locking } = affordancesOf(mode);
184
185
  const bytes = useDocumentBytes(source);
@@ -209,6 +210,7 @@ function DocxEditorSurface({
209
210
  );
210
211
  const latestOnReady = useLatest(onReady);
211
212
  const latestOnChange = useLatest(onChange);
213
+ const latestOnEditRefused = useLatest(onEditRefused);
212
214
  const selectedZoom = normalizeZoom(zoom ?? uncontrolledZoom);
213
215
  const page = opened?.status === "opened" ? pagePixels(opened.session.geometry) : A4_PAGE_PIXELS;
214
216
  const fitWidth = useFitWidthZoom(rootRef, page.pageWidth);
@@ -237,7 +239,8 @@ function DocxEditorSurface({
237
239
  keptState.current = { of: opened, state };
238
240
  setLive({ view, state });
239
241
  latestOnChange.current?.();
240
- }
242
+ },
243
+ onEditRefused: (refusal) => latestOnEditRefused.current?.(refusal)
241
244
  });
242
245
  viewRef.current = view;
243
246
  keptState.current = { of: opened, state: view.state };
@@ -254,7 +257,8 @@ function DocxEditorSurface({
254
257
  mountedFontFallbacks,
255
258
  mountedPlugins,
256
259
  latestOnReady,
257
- latestOnChange
260
+ latestOnChange,
261
+ latestOnEditRefused
258
262
  ]);
259
263
  const authorId = author?.id ?? null;
260
264
  const mounted = live !== null;
@@ -9,6 +9,7 @@ import type { EditableComments, EditingProtection } from "../schema/protection";
9
9
  import { type FontFallbacks } from "../styles/fontStack";
10
10
  import type { CommentAuthor } from "./commands/comments/model";
11
11
  import { type EditorDocument } from "./editorDocument";
12
+ import { type EditRefusal } from "./editRefusal";
12
13
  export interface EditorStateOptions {
13
14
  /**
14
15
  * What the opened document laid down: its styles, its list definitions, the paper it is
@@ -53,5 +54,7 @@ export interface EditorOptions {
53
54
  /** The fonts stood in for the ones the document declares. The built-in set when none is given */
54
55
  fontFallbacks?: FontFallbacks;
55
56
  onStateChange: (state: EditorState) => void;
57
+ /** Told about every edit the guards turn down (`./editRefusal`) */
58
+ onEditRefused?: (refusal: EditRefusal) => void;
56
59
  }
57
- export declare function createEditorView({ mount, state, fontFallbacks, onStateChange, }: EditorOptions): EditorView;
60
+ export declare function createEditorView({ mount, state, fontFallbacks, onStateChange, onEditRefused, }: EditorOptions): EditorView;
@@ -23,12 +23,14 @@ import {
23
23
  editorDocumentOf,
24
24
  NO_DOCUMENT
25
25
  } from "./editorDocument.js";
26
+ import { editRefusal } from "./editRefusal.js";
26
27
  import { imageFiles } from "./imageFiles.js";
27
28
  import { columnResize } from "./plugins/columnResize.js";
28
29
  import { commentComposer } from "./plugins/commentComposer.js";
29
30
  import { commentDecorations } from "./plugins/commentDecorations.js";
30
31
  import { commentRestoration } from "./plugins/commentRestoration.js";
31
32
  import { compositionSelection } from "./plugins/compositionSelection.js";
33
+ import { controlContents } from "./plugins/controlContents.js";
32
34
  import { controlLifecycle } from "./plugins/controlLifecycle.js";
33
35
  import {
34
36
  displayDerivation,
@@ -87,6 +89,10 @@ function createEditorState(doc, options = {}) {
87
89
  // Ahead of the keys and the clipboard: the plugin registered first sees a DOM event first,
88
90
  // and this one hands every composition on
89
91
  compositionSelection(),
92
+ // Keeps an inline control through an edit of everything it holds. It stands ahead of every
93
+ // plugin appending to an edit, which then sees the control it kept, and behind the one above,
94
+ // whose deletion it keeps the control through before a composition opens
95
+ controlContents(),
90
96
  history(),
91
97
  keymap(docxKeymap),
92
98
  historyKeys(),
@@ -163,7 +169,8 @@ function createEditorView({
163
169
  mount,
164
170
  state,
165
171
  fontFallbacks = DEFAULT_FONT_FALLBACKS,
166
- onStateChange
172
+ onStateChange,
173
+ onEditRefused
167
174
  }) {
168
175
  const view = new EditorView(mount, {
169
176
  state,
@@ -190,9 +197,14 @@ function createEditorView({
190
197
  image: (node, imageView, getPos) => new ImageNodeView(node, imageView, getPos)
191
198
  },
192
199
  dispatchTransaction(transaction) {
193
- const next = view.state.apply(transaction);
200
+ const before = view.state;
201
+ const next = before.apply(transaction);
194
202
  view.updateState(next);
195
203
  onStateChange(next);
204
+ if (next === before && onEditRefused) {
205
+ const refusal = editRefusal(transaction, before);
206
+ if (refusal) onEditRefused(refusal);
207
+ }
196
208
  }
197
209
  });
198
210
  return view;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * What an application is told when the editor turns an edit down, so that it can say why.
3
+ *
4
+ * The guards (`schema/guards`) decide; this only reads a refused transaction back into terms a
5
+ * host can act on: which rule refused it, what the edit would have done, and, for a lock, which
6
+ * controls it reached, named by what the template wrote on them.
7
+ *
8
+ * The controls are read off the stretches the refused steps rewrite, which is the same reach the
9
+ * lock guard judges by, but it is a report rather than a second judgement: every control carrying a
10
+ * lock that the edit met is named, whichever of them the guard found first.
11
+ */
12
+ import type { EditorState, Transaction } from "prosemirror-state";
13
+ /**
14
+ * The rule that turned an edit down.
15
+ *
16
+ * - `protection`: the editor's `mode` takes no such edit, such as a body edit in a comment editor.
17
+ * - `lock`: the edit reaches a content control that the document locked, or a group control.
18
+ * - `controlEdge`: a keystroke would join text across the edge of a content control around blocks.
19
+ * - `preserved`: the edit would take away or reorder content the editor keeps without editing it,
20
+ * such as a bookmark's ends or the pieces of a field.
21
+ * - `section`: the edit would take a section break away.
22
+ *
23
+ * It is written out rather than read off the guard list, so that a guard added there has to be
24
+ * named here before it can be reported.
25
+ */
26
+ export type EditRefusalReason = "protection" | "lock" | "controlEdge" | "preserved" | "section";
27
+ /**
28
+ * What the refused edit would have done: put content in, take it away, both at once, or change
29
+ * formatting or structure while leaving the content where it stands.
30
+ */
31
+ export type EditRefusalAction = "insert" | "delete" | "replace" | "format";
32
+ /** The `w:lock` value a control carries (§17.18.49), `unlocked` when it carries none */
33
+ export type ControlLock = "unlocked" | "sdtLocked" | "contentLocked" | "sdtContentLocked";
34
+ /** What a content control stands around: text in a paragraph, whole blocks, a cell, or a row */
35
+ export type ControlLevel = "inline" | "block" | "cell" | "row";
36
+ /** A content control that refuses edits to its contents or its own removal */
37
+ export interface LockedControl {
38
+ /** The control's `w:tag`, which is how a template names it for software */
39
+ tag: string | null;
40
+ /** The control's `w:alias`, which is the name Word shows a reader */
41
+ alias: string | null;
42
+ /** The control's `w:id` */
43
+ id: number | null;
44
+ /** What its `w:lock` says about editing and removing it */
45
+ lock: ControlLock;
46
+ /** Whether it is a group control, which shuts its contents without a lock */
47
+ group: boolean;
48
+ /** What it stands around */
49
+ level: ControlLevel;
50
+ /** Where the control starts in the editor's document */
51
+ pos: number;
52
+ }
53
+ /** An edit the editor turned down, as `onEditRefused` is handed it */
54
+ export interface EditRefusal {
55
+ /** The rule that refused it */
56
+ reason: EditRefusalReason;
57
+ /** What it would have done */
58
+ action: EditRefusalAction;
59
+ /** Where the refused edit starts in the editor's document */
60
+ pos: number;
61
+ /** The locked controls the edit reached, innermost first. Empty unless `reason` is `lock` */
62
+ controls: readonly LockedControl[];
63
+ }
64
+ /**
65
+ * What the guards say about a transaction they turn down, or null when they let it through, which
66
+ * also leaves out a transaction a plugin of the application's own filtered.
67
+ */
68
+ export declare function editRefusal(tr: Transaction, state: EditorState): EditRefusal | null;
@@ -0,0 +1,177 @@
1
+ // src/editor/editRefusal.ts
2
+ import {
3
+ AddMarkStep,
4
+ AddNodeMarkStep,
5
+ AttrStep,
6
+ RemoveMarkStep,
7
+ RemoveNodeMarkStep,
8
+ ReplaceAroundStep,
9
+ ReplaceStep
10
+ } from "prosemirror-transform";
11
+ import { childElement, parseProps, propsChild } from "../ooxml/props.js";
12
+ import { localPart } from "../ooxml/xml.js";
13
+ import {
14
+ controlAttrsOf,
15
+ controlFactsOf,
16
+ isEmptyBlockControl,
17
+ isEmptyInlineControl,
18
+ OWN_CONTROL_ATTRS
19
+ } from "../schema/controlAttrs.js";
20
+ import { transactionRefusal } from "../schema/guards.js";
21
+ import { controlSpans, emptyControlsIn } from "../schema/locks.js";
22
+ function reachesOf(step, doc) {
23
+ if (step instanceof ReplaceAroundStep) {
24
+ return [
25
+ { from: step.from, to: step.gapFrom },
26
+ { from: step.gapTo, to: step.to }
27
+ ];
28
+ }
29
+ if (step instanceof ReplaceStep || step instanceof AddMarkStep || step instanceof RemoveMarkStep) {
30
+ return [{ from: step.from, to: step.to }];
31
+ }
32
+ if (step instanceof AttrStep || step instanceof AddNodeMarkStep || step instanceof RemoveNodeMarkStep) {
33
+ const node = doc.nodeAt(step.pos);
34
+ return node ? [{ from: step.pos, to: step.pos + node.nodeSize }] : [];
35
+ }
36
+ return [];
37
+ }
38
+ function actionOf(tr) {
39
+ const replaced = tr.steps.filter((step) => step instanceof ReplaceStep);
40
+ const takes = replaced.some((step) => step.from < step.to);
41
+ const puts = replaced.some((step) => step.slice.size > 0);
42
+ if (takes && puts) return "replace";
43
+ if (takes) return "delete";
44
+ if (puts) return "insert";
45
+ return "format";
46
+ }
47
+ function lockOf(facts) {
48
+ if (facts.contentsLocked && facts.deletionLocked) return "sdtContentLocked";
49
+ if (facts.contentsLocked) return "contentLocked";
50
+ if (facts.deletionLocked) return "sdtLocked";
51
+ return "unlocked";
52
+ }
53
+ function refuses(facts) {
54
+ return facts.contentsLocked || facts.deletionLocked || facts.group;
55
+ }
56
+ function sdtPrValue(prefix, name) {
57
+ const sdt = parseProps(`${prefix}</w:sdt>`);
58
+ const child = sdt && propsChild(sdt.children, "sdtPr");
59
+ const sdtPr = child ? parseProps(child.xml) : null;
60
+ const element = sdtPr ? childElement(sdtPr, name) : null;
61
+ const val = element?.attrs.find(([attr]) => localPart(attr) === "val");
62
+ return val ? val[1] : null;
63
+ }
64
+ function idOf(prefix) {
65
+ const value = sdtPrValue(prefix, "id");
66
+ const id = value === null ? Number.NaN : Number.parseInt(value, 10);
67
+ return Number.isNaN(id) ? null : id;
68
+ }
69
+ function lockedControl(facts, level, pos) {
70
+ const prefix = facts.prefix ?? "";
71
+ return {
72
+ tag: sdtPrValue(prefix, "tag"),
73
+ alias: sdtPrValue(prefix, "alias"),
74
+ id: idOf(prefix),
75
+ lock: lockOf(facts),
76
+ group: facts.group,
77
+ level,
78
+ pos
79
+ };
80
+ }
81
+ function containerLevel(node) {
82
+ if (isEmptyInlineControl(node)) return "inline";
83
+ if (isEmptyBlockControl(node)) return "block";
84
+ const role = node.type.spec.tableRole;
85
+ if (role === "row") return "row";
86
+ if (role === "cell") return "cell";
87
+ return "block";
88
+ }
89
+ function containerFound(node, pos, depth) {
90
+ const names = controlAttrsOf(node);
91
+ if (!names) return null;
92
+ const facts = controlFactsOf(names, node.attrs);
93
+ if (facts.prefix === null || !refuses(facts)) return null;
94
+ return {
95
+ control: lockedControl(facts, containerLevel(node), pos),
96
+ depth
97
+ };
98
+ }
99
+ function markFacts(mark) {
100
+ return controlFactsOf(OWN_CONTROL_ATTRS, mark.attrs);
101
+ }
102
+ function meets(reach, span) {
103
+ return reach.from === reach.to ? span.from < reach.from && reach.from < span.to : reach.from < span.to && reach.to > span.from;
104
+ }
105
+ function inlineFound(block, start, depth, reach) {
106
+ const textblock = { node: block, start };
107
+ const marked = controlSpans(textblock).filter((span) => meets(reach, span)).filter((span) => refuses(markFacts(span.mark))).map((span) => ({
108
+ control: lockedControl(markFacts(span.mark), "inline", span.from),
109
+ depth: depth + 1 + Number(span.mark.attrs.depth ?? 0)
110
+ }));
111
+ const empty = emptyControlsIn(textblock).filter((control) => meets(reach, control.span)).map((control) => containerFound(control.node, control.span.from, depth)).filter((found) => found !== null);
112
+ return [...marked, ...empty];
113
+ }
114
+ function controlsReached(doc, reach) {
115
+ const found = [];
116
+ for (const at of [reach.from, reach.to]) {
117
+ const $pos = doc.resolve(at);
118
+ for (let depth = 1; depth <= $pos.depth; depth += 1) {
119
+ const container = containerFound(
120
+ $pos.node(depth),
121
+ $pos.before(depth),
122
+ depth
123
+ );
124
+ if (container) found.push(container);
125
+ }
126
+ if ($pos.parent.isTextblock) {
127
+ found.push(...inlineFound($pos.parent, $pos.start(), $pos.depth, reach));
128
+ }
129
+ }
130
+ doc.nodesBetween(reach.from, reach.to, (node, pos) => {
131
+ const depth = doc.resolve(pos).depth + 1;
132
+ const container = containerFound(node, pos, depth);
133
+ if (container) found.push(container);
134
+ if (!node.isTextblock) return true;
135
+ found.push(...inlineFound(node, pos + 1, depth, reach));
136
+ return false;
137
+ });
138
+ return found;
139
+ }
140
+ function sameControl(a, b) {
141
+ return a.pos === b.pos && a.level === b.level && a.id === b.id;
142
+ }
143
+ function controlsOf(tr, state) {
144
+ const found = tr.steps.flatMap((step, index) => {
145
+ const doc = tr.docs[index] ?? state.doc;
146
+ const back = tr.mapping.slice(0, index).invert();
147
+ return reachesOf(step, doc).flatMap((reach) => controlsReached(doc, reach)).map(({ control, depth }) => ({
148
+ control: { ...control, pos: back.map(control.pos, 1) },
149
+ depth
150
+ }));
151
+ });
152
+ const unique = [];
153
+ for (const entry of found) {
154
+ if (!unique.some((kept) => sameControl(kept.control, entry.control))) {
155
+ unique.push(entry);
156
+ }
157
+ }
158
+ return unique.sort((a, b) => b.depth - a.depth || a.control.pos - b.control.pos).map((entry) => entry.control);
159
+ }
160
+ function startOf(tr, state) {
161
+ const [first] = tr.steps;
162
+ const reach = first ? reachesOf(first, state.doc)[0] : void 0;
163
+ return reach?.from ?? state.selection.from;
164
+ }
165
+ function editRefusal(tr, state) {
166
+ const reason = transactionRefusal(tr, state);
167
+ if (reason === null) return null;
168
+ return {
169
+ reason,
170
+ action: actionOf(tr),
171
+ pos: startOf(tr, state),
172
+ controls: reason === "lock" ? controlsOf(tr, state) : []
173
+ };
174
+ }
175
+ export {
176
+ editRefusal
177
+ };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Keeps an inline content control standing through an edit of what it holds
3
+ * (`spec/notes/contentControls.md`).
4
+ *
5
+ * An inline control is a mark, and the mark is not inclusive, so ProseMirror carries it over a
6
+ * replacement only where it stands on both sides of it. Nothing of the control stands past its
7
+ * end, so typing, a composition or a paste over everything the control holds, or over its end,
8
+ * would write the new text beside the control, and a deletion of everything it holds would take
9
+ * the control away with its text.
10
+ *
11
+ * The lock guard reads such a replacement as an edit of the contents (`schema/locks`), and this
12
+ * appends what makes it one: the control laid back over what the edit wrote or, where the edit
13
+ * wrote nothing, the control left standing as one holding nothing (`docx/wrappers`).
14
+ *
15
+ * The caret such an edit leaves at the end of the control stays inside it, and so does the one
16
+ * left beside a control the edit emptied: what is typed, composed or pasted there next goes into
17
+ * the control rather than beside it, until the caret moves. A caret the user places against the
18
+ * edge of a control still stands outside it.
19
+ */
20
+ import { Plugin } from "prosemirror-state";
21
+ /** Where the caret keeps writing into the controls it wrote into, while it stays there */
22
+ type Continuing = number | null;
23
+ export declare function controlContents(): Plugin<Continuing>;
24
+ export {};