@scriba-editor/plugin-revisions 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Mario Trombino
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,10 @@
1
+ Scriba
2
+ Copyright 2026 Mario Trombino
3
+
4
+ This product includes Scriba, a rich text editor created by Mario Trombino
5
+ (https://github.com/mariotrombino76/scriba), licensed under the Apache License,
6
+ Version 2.0.
7
+
8
+ Section 4(d) of the License requires every redistribution of this software, or
9
+ of a work derived from it, to include a readable copy of the attribution notices
10
+ in this NOTICE file.
package/README.md CHANGED
@@ -1,3 +1,56 @@
1
- # Temporary Holding Version
1
+ # @scriba-editor/plugin-revisions
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Cronologia delle versioni, come "Revision History" di TinyMCE: elenco delle versioni salvate, anteprima, confronto con il documento attuale (aggiunto in verde, tolto barrato in rosso) e ripristino con un solo passo annullabile.
4
+
5
+ ```bash
6
+ pnpm add @scriba-editor/plugin-revisions
7
+ ```
8
+
9
+ ## Uso
10
+
11
+ Le versioni le conserva il **tuo server**: il plugin chiede solo l'elenco e, quando l'utente ne sceglie una, il contenuto.
12
+
13
+ ```ts
14
+ import { revisionsToolbarItem, type RevisionOptions } from '@scriba-editor/plugin-revisions'
15
+
16
+ const revisionOptions: RevisionOptions = {
17
+ locale: 'it',
18
+ revisions: () => fetch('/api/versioni').then((r) => r.json()), // più recente per prima
19
+ content: (revision) => fetch(`/api/versioni/${revision.id}`).then((r) => r.text()), // HTML o JSON
20
+ }
21
+
22
+ // nel menu File o nella toolbar:
23
+ revisionsToolbarItem(t, revisionOptions)
24
+ ```
25
+
26
+ Una `Revision` ha la forma `{ id, createdAt, author?, label? }` (`createdAt` può essere `Date`, stringa ISO o timestamp).
27
+
28
+ ## Esportazioni
29
+
30
+ | Nome | Cosa fa |
31
+ | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
32
+ | `revisionsToolbarItem(t, options)` | Pulsante "Cronologia versioni…"; disponibile anche in sola lettura (si può guardare e confrontare, "Ripristina" è disattivato) |
33
+ | `openRevisionDialog(view, t, options)` | Apre il dialogo da codice e restituisce l'handle |
34
+ | `RevisionOptions` | `revisions()`, `content(revision)`, `locale?` (predefinito: quello del browser) |
35
+ | `Revision` | Tipo di una versione |
36
+ | `parseRevision(schema, source)` | Legge il contenuto di una versione attraverso lo schema; lancia errore se lo schema la rifiuta |
37
+ | `MAX_REVISION_LENGTH` | 5 000 000 caratteri: un HTML più grande viene rifiutato, non tagliato |
38
+ | `formatRevisionDate(value, locale?)` | Data breve (stringa vuota se non valida) |
39
+ | `diffDocs(old, new)`, `diffSequence`, `slideEdits`, `MAX_COMPARISONS`, `DocDiff`, `Change`, `ChangeKind`, `Highlight` | Il confronto tra documenti, riusabile da solo |
40
+
41
+ ## Come si usa il dialogo
42
+
43
+ Le versioni sono un gruppo di radio (frecce per muoversi); quella scelta si carica in un'anteprima di sola lettura. "Evidenzia le differenze con il documento attuale" mostra cosa è stato aggiunto o tolto _dopo_ quella versione, con "Differenza precedente/successiva" per scorrerle. "Ripristina questa versione" sostituisce il documento con un solo passo di undo.
44
+
45
+ ## Accessibilità
46
+
47
+ Il dialogo ha focus trap e restituisce il focus all'editor. Caricamenti, errori e conteggio delle differenze sono in regioni `role="status"` / `role="alert"`; ogni differenza raggiunta con Precedente/Successiva è letta ("Differenza 2 di 5, aggiunto dopo: «...»", testo tagliato a 120 caratteri); dopo il ripristino un messaggio "Versione ripristinata" è annunciato.
48
+
49
+ ## Sicurezza
50
+
51
+ - Il contenuto delle versioni arriva dal server ed è **input non fidato**: l'HTML è letto in un documento inerte e passa dal parser dello schema, il JSON è validato dallo schema (deve essere un documento intero); oltre `MAX_REVISION_LENGTH` viene rifiutato. Una versione illeggibile mostra un errore, non rompe l'editor.
52
+ - Autore ed etichetta sono mostrati **come testo**, mai come HTML.
53
+ - Una risposta lenta per una versione non più selezionata viene ignorata.
54
+ - Chi salva versioni deve comunque sanificarle sul server con `@scriba-editor/sanitize-server`.
55
+
56
+ Vedi [sicurezza](../../../docs/sicurezza.md), [accessibilità](../../../docs/accessibilita.md) e [plugin](../../../docs/plugin.md). Si abbina bene a [@scriba-editor/plugin-save](../save/README.md).
@@ -0,0 +1,29 @@
1
+ import { type Node, type NodeJSON, type Schema } from '@scriba-editor/core';
2
+ /** A saved version of the document, as your server lists it. */
3
+ export interface Revision {
4
+ /** Your id for it: passed back to `content`. */
5
+ readonly id: string;
6
+ /** When it was saved (a Date, an ISO string or a timestamp). */
7
+ readonly createdAt: Date | string | number;
8
+ /** Who saved it. Shown as text. */
9
+ readonly author?: string;
10
+ /** An optional name ("Sent to the client"). Shown as text. */
11
+ readonly label?: string;
12
+ }
13
+ export interface RevisionOptions {
14
+ /** The saved versions, newest first (e.g. fetched from your server). */
15
+ revisions: () => Promise<readonly Revision[]>;
16
+ /**
17
+ * A version's content: HTML, or the JSON of `doc.toJSON()`. Untrusted: it
18
+ * goes through the schema (parser or JSON validation), like `setContent`.
19
+ */
20
+ content: (revision: Revision) => Promise<string | NodeJSON>;
21
+ /** Locale of the dates (default: the browser's). */
22
+ locale?: string;
23
+ }
24
+ /** Longest version HTML accepted (characters): bigger ones are refused, not cut. */
25
+ export declare const MAX_REVISION_LENGTH = 5000000;
26
+ /** Reads a version's content through the schema. Throws if the schema refuses it. */
27
+ export declare function parseRevision(schema: Schema, source: string | NodeJSON): Node;
28
+ /** "12 nov 2026, 10:30", in the given locale. Invalid dates give an empty string. */
29
+ export declare function formatRevisionDate(value: Revision['createdAt'], locale?: string): string;
@@ -0,0 +1,24 @@
1
+ import { parseHTML } from '@scriba-editor/core';
2
+ import { parseInertHTML } from '@scriba-editor/view';
3
+ /** Longest version HTML accepted (characters): bigger ones are refused, not cut. */
4
+ export const MAX_REVISION_LENGTH = 5_000_000;
5
+ /** Reads a version's content through the schema. Throws if the schema refuses it. */
6
+ export function parseRevision(schema, source) {
7
+ if (typeof source !== 'string') {
8
+ const doc = schema.nodeFromJSON(source);
9
+ if (doc.type !== schema.topNodeType)
10
+ throw new RangeError('A version must be a whole document');
11
+ return doc;
12
+ }
13
+ if (source.length > MAX_REVISION_LENGTH)
14
+ throw new RangeError(`Version longer than ${MAX_REVISION_LENGTH} characters`);
15
+ return parseHTML(schema, parseInertHTML(source).body);
16
+ }
17
+ /** "12 nov 2026, 10:30", in the given locale. Invalid dates give an empty string. */
18
+ export function formatRevisionDate(value, locale) {
19
+ const date = value instanceof Date ? value : new Date(value);
20
+ if (Number.isNaN(date.getTime()))
21
+ return '';
22
+ return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }).format(date);
23
+ }
24
+ //# sourceMappingURL=content.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"content.js","sourceRoot":"","sources":["../src/content.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAyC,MAAM,qBAAqB,CAAA;AACtF,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AA0BpD,oFAAoF;AACpF,MAAM,CAAC,MAAM,mBAAmB,GAAG,SAAS,CAAA;AAE5C,qFAAqF;AACrF,MAAM,UAAU,aAAa,CAAC,MAAc,EAAE,MAAyB;IACrE,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC/B,MAAM,GAAG,GAAG,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,CAAA;QACvC,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,CAAC,WAAW;YAAE,MAAM,IAAI,UAAU,CAAC,oCAAoC,CAAC,CAAA;QAC/F,OAAO,GAAG,CAAA;IACZ,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,GAAG,mBAAmB;QACrC,MAAM,IAAI,UAAU,CAAC,uBAAuB,mBAAmB,aAAa,CAAC,CAAA;IAC/E,OAAO,SAAS,CAAC,MAAM,EAAE,cAAc,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAA;AACvD,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,kBAAkB,CAAC,KAA4B,EAAE,MAAe;IAC9E,MAAM,IAAI,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAA;IAC5D,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;QAAE,OAAO,EAAE,CAAA;IAC3C,OAAO,IAAI,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;AAClG,CAAC","sourcesContent":["import { parseHTML, type Node, type NodeJSON, type Schema } from '@scriba-editor/core'\nimport { parseInertHTML } from '@scriba-editor/view'\n\n/** A saved version of the document, as your server lists it. */\nexport interface Revision {\n /** Your id for it: passed back to `content`. */\n readonly id: string\n /** When it was saved (a Date, an ISO string or a timestamp). */\n readonly createdAt: Date | string | number\n /** Who saved it. Shown as text. */\n readonly author?: string\n /** An optional name (\"Sent to the client\"). Shown as text. */\n readonly label?: string\n}\n\nexport interface RevisionOptions {\n /** The saved versions, newest first (e.g. fetched from your server). */\n revisions: () => Promise<readonly Revision[]>\n /**\n * A version's content: HTML, or the JSON of `doc.toJSON()`. Untrusted: it\n * goes through the schema (parser or JSON validation), like `setContent`.\n */\n content: (revision: Revision) => Promise<string | NodeJSON>\n /** Locale of the dates (default: the browser's). */\n locale?: string\n}\n\n/** Longest version HTML accepted (characters): bigger ones are refused, not cut. */\nexport const MAX_REVISION_LENGTH = 5_000_000\n\n/** Reads a version's content through the schema. Throws if the schema refuses it. */\nexport function parseRevision(schema: Schema, source: string | NodeJSON): Node {\n if (typeof source !== 'string') {\n const doc = schema.nodeFromJSON(source)\n if (doc.type !== schema.topNodeType) throw new RangeError('A version must be a whole document')\n return doc\n }\n if (source.length > MAX_REVISION_LENGTH)\n throw new RangeError(`Version longer than ${MAX_REVISION_LENGTH} characters`)\n return parseHTML(schema, parseInertHTML(source).body)\n}\n\n/** \"12 nov 2026, 10:30\", in the given locale. Invalid dates give an empty string. */\nexport function formatRevisionDate(value: Revision['createdAt'], locale?: string): string {\n const date = value instanceof Date ? value : new Date(value)\n if (Number.isNaN(date.getTime())) return ''\n return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }).format(date)\n}\n"]}
@@ -0,0 +1,13 @@
1
+ import type { Translate } from '@scriba-editor/i18n';
2
+ import { type DialogHandle } from '@scriba-editor/ui';
3
+ import { EditorView } from '@scriba-editor/view';
4
+ import { type RevisionOptions } from './content.js';
5
+ /**
6
+ * The "Version history" dialog (TinyMCE's Revision History): the saved
7
+ * versions as a radio list; the selected one in a read-only preview, compared
8
+ * with the current document (what was added since in green, what was removed
9
+ * since struck through in red); Previous / Next change, read out for screen
10
+ * readers; "Restore this version", one undoable step. Versions load when
11
+ * selected; a slow answer for a version no longer selected is ignored.
12
+ */
13
+ export declare function openRevisionDialog(view: EditorView, t: Translate, options: RevisionOptions): DialogHandle;
package/dist/dialog.js ADDED
@@ -0,0 +1,254 @@
1
+ import { EditorState, Plugin, Selection } from '@scriba-editor/core';
2
+ import { openDialog } from '@scriba-editor/ui';
3
+ import { EditorView } from '@scriba-editor/view';
4
+ import { formatRevisionDate, parseRevision, } from './content.js';
5
+ import { diffDocs } from './diff.js';
6
+ let dialogCount = 0;
7
+ const announcers = new WeakMap();
8
+ /** Tells screen readers what happened once the dialog is closed (a polite live region). */
9
+ function announce(view, message) {
10
+ let region = announcers.get(view);
11
+ if (!region) {
12
+ region = view.document.createElement('div');
13
+ region.className = 'scriba-visually-hidden';
14
+ region.setAttribute('role', 'status');
15
+ view.dom.after(region);
16
+ announcers.set(view, region);
17
+ }
18
+ region.textContent = message;
19
+ }
20
+ /** Longest change text read out; the rest is cut with an ellipsis. */
21
+ const SAY_LENGTH = 120;
22
+ /**
23
+ * The "Version history" dialog (TinyMCE's Revision History): the saved
24
+ * versions as a radio list; the selected one in a read-only preview, compared
25
+ * with the current document (what was added since in green, what was removed
26
+ * since struck through in red); Previous / Next change, read out for screen
27
+ * readers; "Restore this version", one undoable step. Versions load when
28
+ * selected; a slow answer for a version no longer selected is ignored.
29
+ */
30
+ export function openRevisionDialog(view, t, options) {
31
+ const doc = view.document;
32
+ const id = `scriba-revisions-${++dialogCount}`;
33
+ const parsed = new Map();
34
+ let preview = null;
35
+ let closed = false;
36
+ let focusFirst = () => { };
37
+ const handle = openDialog(doc, {
38
+ title: t('revisions.title'),
39
+ returnFocus: () => {
40
+ closed = true;
41
+ preview?.destroy();
42
+ view.focus();
43
+ },
44
+ build(form, handle) {
45
+ handle.dialog.classList.add('scriba-revisions');
46
+ const el = (tag, cls) => {
47
+ const e = doc.createElement(tag);
48
+ if (cls)
49
+ e.className = cls;
50
+ return e;
51
+ };
52
+ const button = (key, onClick) => {
53
+ const b = el('button');
54
+ b.type = 'button';
55
+ b.textContent = t(key);
56
+ b.addEventListener('click', onClick);
57
+ return b;
58
+ };
59
+ const status = el('p', 'scriba-revisions-status');
60
+ status.setAttribute('role', 'status');
61
+ const body = el('div', 'scriba-revisions-body');
62
+ const list = el('fieldset', 'scriba-radio-group scriba-revisions-list');
63
+ const legend = el('legend');
64
+ legend.textContent = t('revisions.list');
65
+ list.append(legend);
66
+ const side = el('div', 'scriba-revisions-side');
67
+ const compareLabel = el('label', 'scriba-check');
68
+ const compare = el('input');
69
+ compare.type = 'checkbox';
70
+ compare.checked = true;
71
+ compareLabel.append(compare, t('revisions.compare'));
72
+ const legendBox = el('p', 'scriba-revisions-legend');
73
+ const ins = el('span', 'scriba-diff-insert');
74
+ ins.textContent = t('revisions.inserted');
75
+ const del = el('span', 'scriba-diff-delete');
76
+ del.textContent = t('revisions.deleted');
77
+ legendBox.append(ins, ' ', del);
78
+ const box = el('div', 'scriba-revisions-preview');
79
+ box.setAttribute('role', 'region');
80
+ box.setAttribute('aria-label', t('revisions.preview'));
81
+ const nav = el('div', 'scriba-revisions-nav');
82
+ const summary = el('span', 'scriba-revisions-summary');
83
+ const prev = button('revisions.prev', () => go(-1));
84
+ const next = button('revisions.next', () => go(1));
85
+ nav.append(summary, prev, next);
86
+ const say = el('p', 'scriba-revisions-current');
87
+ say.setAttribute('aria-live', 'polite');
88
+ side.append(compareLabel, legendBox, box, nav, say);
89
+ body.append(list, side);
90
+ const error = el('p', 'scriba-dialog-error');
91
+ error.setAttribute('role', 'alert');
92
+ const actions = el('div', 'scriba-dialog-actions');
93
+ const close = button('revisions.close', () => handle.close());
94
+ const restore = el('button');
95
+ restore.type = 'submit';
96
+ restore.textContent = t('revisions.restore');
97
+ restore.disabled = true;
98
+ actions.append(close, restore);
99
+ form.append(status, body, error, actions);
100
+ // --- Preview ---
101
+ let version = null;
102
+ let diff = null;
103
+ let index = -1;
104
+ const decorations = () => {
105
+ if (!diff || !compare.checked)
106
+ return [];
107
+ const current = diff.changes[index];
108
+ return diff.highlights.map((h) => ({
109
+ from: h.from,
110
+ to: h.to,
111
+ class: `scriba-diff-${h.kind}` +
112
+ (current && h.from >= current.from && h.to <= current.to ? ' scriba-diff-current' : ''),
113
+ }));
114
+ };
115
+ const decorator = new Plugin({ props: { decorations } });
116
+ const show = () => {
117
+ preview?.destroy();
118
+ preview = null;
119
+ box.replaceChildren();
120
+ say.textContent = '';
121
+ index = -1;
122
+ nav.hidden = legendBox.hidden = !version || !compare.checked;
123
+ restore.disabled = !version || !view.editable;
124
+ if (!version)
125
+ return;
126
+ diff = compare.checked ? diffDocs(version, view.state.doc) : null;
127
+ preview = new EditorView(box, {
128
+ state: EditorState.create({ doc: diff ? diff.doc : version, plugins: [decorator] }),
129
+ editable: () => false,
130
+ label: t('revisions.preview'),
131
+ ...(view.options.nodeViews ? { nodeViews: view.options.nodeViews } : {}),
132
+ });
133
+ const count = diff?.changes.length ?? 0;
134
+ summary.textContent = count ? t('revisions.count', { count }) : t('revisions.none');
135
+ prev.disabled = next.disabled = !count;
136
+ };
137
+ compare.addEventListener('change', show);
138
+ const describe = (change, n, count) => {
139
+ const kind = t(change.kind === 'insert' ? 'revisions.kind.insert' : 'revisions.kind.delete');
140
+ const text = change.text.trim();
141
+ if (!text)
142
+ return t('revisions.currentEmpty', { n, count, kind });
143
+ const cut = text.length > SAY_LENGTH ? `${text.slice(0, SAY_LENGTH)}…` : text;
144
+ return t('revisions.current', { n, count, kind, text: cut });
145
+ };
146
+ const go = (step) => {
147
+ if (!diff || !preview || !diff.changes.length)
148
+ return;
149
+ const count = diff.changes.length;
150
+ index = index < 0 ? (step === 1 ? 0 : count - 1) : (index + step + count) % count;
151
+ const change = diff.changes[index];
152
+ // redraws the decorations and moves the (invisible) selection there for scrolling
153
+ const state = preview.state;
154
+ const at = Math.min(change.from + 1, state.doc.content.size);
155
+ preview.dispatch(state.tr.setSelection(Selection.near(state.doc.resolve(at))));
156
+ preview.dom
157
+ .querySelector('.scriba-diff-current')
158
+ ?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
159
+ say.textContent = describe(change, index + 1, count);
160
+ };
161
+ // --- Versions ---
162
+ let selection = 0;
163
+ const contentOf = (revision) => {
164
+ let result = parsed.get(revision.id);
165
+ if (!result) {
166
+ result = options
167
+ .content(revision)
168
+ .then((source) => parseRevision(view.state.schema, source));
169
+ parsed.set(revision.id, result);
170
+ // a failed load can be tried again by selecting the version again
171
+ result.catch(() => parsed.delete(revision.id));
172
+ }
173
+ return result;
174
+ };
175
+ const select = (revision) => {
176
+ const ticket = ++selection;
177
+ error.textContent = '';
178
+ version = null;
179
+ show();
180
+ status.textContent = t('revisions.loadingVersion');
181
+ contentOf(revision).then((content) => {
182
+ if (closed || ticket !== selection)
183
+ return;
184
+ status.textContent = '';
185
+ version = content;
186
+ show();
187
+ }, () => {
188
+ if (closed || ticket !== selection)
189
+ return;
190
+ status.textContent = '';
191
+ error.textContent = t('revisions.versionError');
192
+ });
193
+ };
194
+ const fill = (revisions) => {
195
+ status.textContent = revisions.length ? '' : t('revisions.empty');
196
+ list.hidden = side.hidden = !revisions.length;
197
+ const radios = revisions.map((revision, i) => {
198
+ const radio = el('input');
199
+ radio.type = 'radio';
200
+ radio.name = `${id}-version`;
201
+ radio.value = String(i);
202
+ radio.checked = i === 0;
203
+ radio.addEventListener('change', () => radio.checked && select(revision));
204
+ const label = el('label', 'scriba-check scriba-revisions-item');
205
+ const text = el('span');
206
+ const date = el('span', 'scriba-revisions-date');
207
+ date.textContent = formatRevisionDate(revision.createdAt, options.locale);
208
+ text.append(date);
209
+ for (const extra of [revision.label, revision.author]) {
210
+ if (!extra)
211
+ continue;
212
+ const span = el('span', 'scriba-revisions-meta');
213
+ // names come from the server: always text, never markup
214
+ span.textContent = extra;
215
+ text.append(span);
216
+ }
217
+ label.append(radio, text);
218
+ list.append(label);
219
+ return radio;
220
+ });
221
+ focusFirst = () => (radios[0] ?? close).focus();
222
+ if (revisions[0])
223
+ select(revisions[0]);
224
+ };
225
+ form.addEventListener('submit', (event) => {
226
+ event.preventDefault();
227
+ if (!version || !view.editable)
228
+ return;
229
+ const state = view.state;
230
+ const tr = state.tr.replaceWith(0, state.doc.content.size, version.content);
231
+ tr.setSelection(Selection.near(tr.doc.resolve(0)));
232
+ view.dispatch(tr.scrollIntoView());
233
+ handle.close();
234
+ announce(view, t('revisions.restored'));
235
+ });
236
+ list.hidden = side.hidden = true;
237
+ status.textContent = t('revisions.loading');
238
+ options.revisions().then((revisions) => {
239
+ if (closed)
240
+ return;
241
+ fill(revisions);
242
+ focusFirst();
243
+ }, () => {
244
+ if (closed)
245
+ return;
246
+ status.textContent = '';
247
+ error.textContent = t('revisions.listError');
248
+ close.focus();
249
+ });
250
+ },
251
+ });
252
+ return handle;
253
+ }
254
+ //# sourceMappingURL=dialog.js.map
@@ -0,0 +1 @@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C,qBAAqB,CAAC,CAAA;gBAC5C,KAAK,CAAC,KAAK,EAAE,CAAA;YACf,CAAC,CACF,CAAA;QACH,CAAC;KACF,CAAC,CAAA;IACF,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { EditorState, Plugin, Selection, type Node } from '@scriba-editor/core'\nimport type { Translate } from '@scriba-editor/i18n'\nimport { openDialog, type DialogHandle } from '@scriba-editor/ui'\nimport { EditorView, type InlineDecoration } from '@scriba-editor/view'\nimport {\n formatRevisionDate,\n parseRevision,\n type Revision,\n type RevisionOptions,\n} from './content.js'\nimport { diffDocs, type Change, type DocDiff } from './diff.js'\n\nlet dialogCount = 0\nconst announcers = new WeakMap<EditorView, HTMLElement>()\n\n/** Tells screen readers what happened once the dialog is closed (a polite live region). */\nfunction announce(view: EditorView, message: string): void {\n let region = announcers.get(view)\n if (!region) {\n region = view.document.createElement('div')\n region.className = 'scriba-visually-hidden'\n region.setAttribute('role', 'status')\n view.dom.after(region)\n announcers.set(view, region)\n }\n region.textContent = message\n}\n/** Longest change text read out; the rest is cut with an ellipsis. */\nconst SAY_LENGTH = 120\n\n/**\n * The \"Version history\" dialog (TinyMCE's Revision History): the saved\n * versions as a radio list; the selected one in a read-only preview, compared\n * with the current document (what was added since in green, what was removed\n * since struck through in red); Previous / Next change, read out for screen\n * readers; \"Restore this version\", one undoable step. Versions load when\n * selected; a slow answer for a version no longer selected is ignored.\n */\nexport function openRevisionDialog(\n view: EditorView,\n t: Translate,\n options: RevisionOptions,\n): DialogHandle {\n const doc = view.document\n const id = `scriba-revisions-${++dialogCount}`\n const parsed = new Map<string, Promise<Node>>()\n let preview: EditorView | null = null\n let closed = false\n let focusFirst = () => {}\n\n const handle = openDialog(doc, {\n title: t('revisions.title'),\n returnFocus: () => {\n closed = true\n preview?.destroy()\n view.focus()\n },\n build(form, handle) {\n handle.dialog.classList.add('scriba-revisions')\n const el = <K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string) => {\n const e = doc.createElement(tag)\n if (cls) e.className = cls\n return e\n }\n const button = (key: Parameters<Translate>[0], onClick: () => void) => {\n const b = el('button')\n b.type = 'button'\n b.textContent = t(key)\n b.addEventListener('click', onClick)\n return b\n }\n\n const status = el('p', 'scriba-revisions-status')\n status.setAttribute('role', 'status')\n const body = el('div', 'scriba-revisions-body')\n const list = el('fieldset', 'scriba-radio-group scriba-revisions-list')\n const legend = el('legend')\n legend.textContent = t('revisions.list')\n list.append(legend)\n\n const side = el('div', 'scriba-revisions-side')\n const compareLabel = el('label', 'scriba-check')\n const compare = el('input')\n compare.type = 'checkbox'\n compare.checked = true\n compareLabel.append(compare, t('revisions.compare'))\n const legendBox = el('p', 'scriba-revisions-legend')\n const ins = el('span', 'scriba-diff-insert')\n ins.textContent = t('revisions.inserted')\n const del = el('span', 'scriba-diff-delete')\n del.textContent = t('revisions.deleted')\n legendBox.append(ins, ' ', del)\n const box = el('div', 'scriba-revisions-preview')\n box.setAttribute('role', 'region')\n box.setAttribute('aria-label', t('revisions.preview'))\n const nav = el('div', 'scriba-revisions-nav')\n const summary = el('span', 'scriba-revisions-summary')\n const prev = button('revisions.prev', () => go(-1))\n const next = button('revisions.next', () => go(1))\n nav.append(summary, prev, next)\n const say = el('p', 'scriba-revisions-current')\n say.setAttribute('aria-live', 'polite')\n side.append(compareLabel, legendBox, box, nav, say)\n body.append(list, side)\n\n const error = el('p', 'scriba-dialog-error')\n error.setAttribute('role', 'alert')\n const actions = el('div', 'scriba-dialog-actions')\n const close = button('revisions.close', () => handle.close())\n const restore = el('button')\n restore.type = 'submit'\n restore.textContent = t('revisions.restore')\n restore.disabled = true\n actions.append(close, restore)\n form.append(status, body, error, actions)\n\n // --- Preview ---\n let version: Node | null = null\n let diff: DocDiff | null = null\n let index = -1\n const decorations = (): InlineDecoration[] => {\n if (!diff || !compare.checked) return []\n const current = diff.changes[index]\n return diff.highlights.map((h) => ({\n from: h.from,\n to: h.to,\n class:\n `scriba-diff-${h.kind}` +\n (current && h.from >= current.from && h.to <= current.to ? ' scriba-diff-current' : ''),\n }))\n }\n const decorator = new Plugin({ props: { decorations } })\n\n const show = () => {\n preview?.destroy()\n preview = null\n box.replaceChildren()\n say.textContent = ''\n index = -1\n nav.hidden = legendBox.hidden = !version || !compare.checked\n restore.disabled = !version || !view.editable\n if (!version) return\n diff = compare.checked ? diffDocs(version, view.state.doc) : null\n preview = new EditorView(box, {\n state: EditorState.create({ doc: diff ? diff.doc : version, plugins: [decorator] }),\n editable: () => false,\n label: t('revisions.preview'),\n ...(view.options.nodeViews ? { nodeViews: view.options.nodeViews } : {}),\n })\n const count = diff?.changes.length ?? 0\n summary.textContent = count ? t('revisions.count', { count }) : t('revisions.none')\n prev.disabled = next.disabled = !count\n }\n compare.addEventListener('change', show)\n\n const describe = (change: Change, n: number, count: number) => {\n const kind = t(change.kind === 'insert' ? 'revisions.kind.insert' : 'revisions.kind.delete')\n const text = change.text.trim()\n if (!text) return t('revisions.currentEmpty', { n, count, kind })\n const cut = text.length > SAY_LENGTH ? `${text.slice(0, SAY_LENGTH)}…` : text\n return t('revisions.current', { n, count, kind, text: cut })\n }\n const go = (step: 1 | -1) => {\n if (!diff || !preview || !diff.changes.length) return\n const count = diff.changes.length\n index = index < 0 ? (step === 1 ? 0 : count - 1) : (index + step + count) % count\n const change = diff.changes[index]!\n // redraws the decorations and moves the (invisible) selection there for scrolling\n const state = preview.state\n const at = Math.min(change.from + 1, state.doc.content.size)\n preview.dispatch(state.tr.setSelection(Selection.near(state.doc.resolve(at))))\n preview.dom\n .querySelector('.scriba-diff-current')\n ?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' })\n say.textContent = describe(change, index + 1, count)\n }\n\n // --- Versions ---\n let selection = 0\n const contentOf = (revision: Revision): Promise<Node> => {\n let result = parsed.get(revision.id)\n if (!result) {\n result = options\n .content(revision)\n .then((source) => parseRevision(view.state.schema, source))\n parsed.set(revision.id, result)\n // a failed load can be tried again by selecting the version again\n result.catch(() => parsed.delete(revision.id))\n }\n return result\n }\n const select = (revision: Revision) => {\n const ticket = ++selection\n error.textContent = ''\n version = null\n show()\n status.textContent = t('revisions.loadingVersion')\n contentOf(revision).then(\n (content) => {\n if (closed || ticket !== selection) return\n status.textContent = ''\n version = content\n show()\n },\n () => {\n if (closed || ticket !== selection) return\n status.textContent = ''\n error.textContent = t('revisions.versionError')\n },\n )\n }\n\n const fill = (revisions: readonly Revision[]) => {\n status.textContent = revisions.length ? '' : t('revisions.empty')\n list.hidden = side.hidden = !revisions.length\n const radios = revisions.map((revision, i) => {\n const radio = el('input')\n radio.type = 'radio'\n radio.name = `${id}-version`\n radio.value = String(i)\n radio.checked = i === 0\n radio.addEventListener('change', () => radio.checked && select(revision))\n const label = el('label', 'scriba-check scriba-revisions-item')\n const text = el('span')\n const date = el('span', 'scriba-revisions-date')\n date.textContent = formatRevisionDate(revision.createdAt, options.locale)\n text.append(date)\n for (const extra of [revision.label, revision.author]) {\n if (!extra) continue\n const span = el('span', 'scriba-revisions-meta')\n // names come from the server: always text, never markup\n span.textContent = extra\n text.append(span)\n }\n label.append(radio, text)\n list.append(label)\n return radio\n })\n focusFirst = () => (radios[0] ?? close).focus()\n if (revisions[0]) select(revisions[0])\n }\n\n form.addEventListener('submit', (event) => {\n event.preventDefault()\n if (!version || !view.editable) return\n const state = view.state\n const tr = state.tr.replaceWith(0, state.doc.content.size, version.content)\n tr.setSelection(Selection.near(tr.doc.resolve(0)))\n view.dispatch(tr.scrollIntoView())\n handle.close()\n announce(view, t('revisions.restored'))\n })\n\n list.hidden = side.hidden = true\n status.textContent = t('revisions.loading')\n options.revisions().then(\n (revisions) => {\n if (closed) return\n fill(revisions)\n focusFirst()\n },\n () => {\n if (closed) return\n status.textContent = ''\n error.textContent = t('revisions.listError')\n close.focus()\n },\n )\n },\n })\n return handle\n}\n"]}
package/dist/diff.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { type Node } from '@scriba-editor/core';
2
+ /**
3
+ * Document comparison, pure (no DOM). The result is one merged document
4
+ * holding the content of both versions: what only the old one has is marked
5
+ * "delete", what only the new one has is marked "insert". Blocks are matched
6
+ * first; matched paragraphs are then compared word by word.
7
+ */
8
+ export type ChangeKind = 'insert' | 'delete';
9
+ /** A range of the merged document to highlight (always inside a textblock). */
10
+ export interface Highlight {
11
+ readonly kind: ChangeKind;
12
+ readonly from: number;
13
+ readonly to: number;
14
+ }
15
+ /** One change to step through: some words, or a whole block. */
16
+ export interface Change {
17
+ readonly kind: ChangeKind;
18
+ readonly from: number;
19
+ readonly to: number;
20
+ /** Its text (empty for an image or another element without text). */
21
+ readonly text: string;
22
+ }
23
+ export interface DocDiff {
24
+ readonly doc: Node;
25
+ readonly highlights: readonly Highlight[];
26
+ readonly changes: readonly Change[];
27
+ }
28
+ /** Above this many comparisons a range is shown as replaced, not compared in detail. */
29
+ export declare const MAX_COMPARISONS = 4000000;
30
+ type Op = readonly ['equal', number, number] | readonly ['delete', number] | readonly ['insert', number];
31
+ /**
32
+ * Edit script between two sequences (longest common subsequence). The common
33
+ * start and end are skipped first, so the usual small edit is cheap; a middle
34
+ * part too big to compare becomes "delete all, insert all".
35
+ */
36
+ export declare function diffSequence<T>(a: readonly T[], b: readonly T[], eq: (x: T, y: T) => boolean): Op[];
37
+ /**
38
+ * Moves each run of only insertions (or only deletions) to the right while
39
+ * the result is the same: "dorme[. Sogna]." becomes "dorme[ Sogna.]", which
40
+ * is how a person reads the change. Equal tokens on both sides are swapped,
41
+ * never changed.
42
+ */
43
+ export declare function slideEdits<T>(ops: Op[], a: readonly T[], b: readonly T[], eq: (x: T, y: T) => boolean): Op[];
44
+ /**
45
+ * Compares two versions of a document. The merged document is for showing
46
+ * only: it may not follow every rule of the schema (two versions of a block
47
+ * side by side), so it is never put back into an editor that can change it.
48
+ */
49
+ export declare function diffDocs(oldDoc: Node, newDoc: Node): DocDiff;
50
+ export {};
package/dist/diff.js ADDED
@@ -0,0 +1,257 @@
1
+ import { Fragment, Mark } from '@scriba-editor/core';
2
+ /** Above this many comparisons a range is shown as replaced, not compared in detail. */
3
+ export const MAX_COMPARISONS = 4_000_000;
4
+ /**
5
+ * Edit script between two sequences (longest common subsequence). The common
6
+ * start and end are skipped first, so the usual small edit is cheap; a middle
7
+ * part too big to compare becomes "delete all, insert all".
8
+ */
9
+ export function diffSequence(a, b, eq) {
10
+ let start = 0;
11
+ while (start < a.length && start < b.length && eq(a[start], b[start]))
12
+ start++;
13
+ let endA = a.length;
14
+ let endB = b.length;
15
+ while (endA > start && endB > start && eq(a[endA - 1], b[endB - 1])) {
16
+ endA--;
17
+ endB--;
18
+ }
19
+ const ops = [];
20
+ for (let i = 0; i < start; i++)
21
+ ops.push(['equal', i, i]);
22
+ const n = endA - start;
23
+ const m = endB - start;
24
+ if (n && m && n * m <= MAX_COMPARISONS) {
25
+ // lengths of the common subsequences of the suffixes
26
+ const w = m + 1;
27
+ const table = new Uint32Array((n + 1) * w);
28
+ for (let i = n - 1; i >= 0; i--)
29
+ for (let j = m - 1; j >= 0; j--)
30
+ table[i * w + j] = eq(a[start + i], b[start + j])
31
+ ? table[(i + 1) * w + j + 1] + 1
32
+ : Math.max(table[(i + 1) * w + j], table[i * w + j + 1]);
33
+ let i = 0;
34
+ let j = 0;
35
+ while (i < n && j < m) {
36
+ if (eq(a[start + i], b[start + j]))
37
+ ops.push(['equal', start + i++, start + j++]);
38
+ else if (table[(i + 1) * w + j] >= table[i * w + j + 1])
39
+ ops.push(['delete', start + i++]);
40
+ else
41
+ ops.push(['insert', start + j++]);
42
+ }
43
+ while (i < n)
44
+ ops.push(['delete', start + i++]);
45
+ while (j < m)
46
+ ops.push(['insert', start + j++]);
47
+ }
48
+ else {
49
+ for (let i = start; i < endA; i++)
50
+ ops.push(['delete', i]);
51
+ for (let j = start; j < endB; j++)
52
+ ops.push(['insert', j]);
53
+ }
54
+ for (let i = endA, j = endB; i < a.length; i++, j++)
55
+ ops.push(['equal', i, j]);
56
+ return ops;
57
+ }
58
+ /**
59
+ * Moves each run of only insertions (or only deletions) to the right while
60
+ * the result is the same: "dorme[. Sogna]." becomes "dorme[ Sogna.]", which
61
+ * is how a person reads the change. Equal tokens on both sides are swapped,
62
+ * never changed.
63
+ */
64
+ export function slideEdits(ops, a, b, eq) {
65
+ const out = [...ops];
66
+ for (let k = 0; k < out.length; k++) {
67
+ const kind = out[k][0];
68
+ if (kind === 'equal')
69
+ continue;
70
+ let end = k;
71
+ while (end + 1 < out.length && out[end + 1][0] === kind)
72
+ end++;
73
+ const mixed = (end + 1 < out.length && out[end + 1][0] !== 'equal') ||
74
+ (k > 0 && out[k - 1][0] !== 'equal');
75
+ if (mixed) {
76
+ k = end;
77
+ continue;
78
+ }
79
+ const seq = kind === 'insert' ? b : a;
80
+ // the run is seq[first..last]; the equal op after it pairs seq[last + 1]
81
+ while (end + 1 < out.length) {
82
+ const after = out[end + 1];
83
+ const first = out[k][1];
84
+ const next = kind === 'insert' ? after[2] : after[1];
85
+ if (!eq(seq[first], seq[next]))
86
+ break;
87
+ // seq[first] takes the place of seq[next] in the equal pair; the run moves one step right
88
+ const equal = kind === 'insert' ? ['equal', after[1], first] : ['equal', first, after[2]];
89
+ out.splice(k, 1);
90
+ out.splice(end, 1, kind === 'insert' ? ['insert', next] : ['delete', next]);
91
+ out.splice(k, 0, equal);
92
+ k++;
93
+ end++;
94
+ if (end + 1 < out.length && out[end + 1][0] !== 'equal')
95
+ break;
96
+ }
97
+ k = end;
98
+ }
99
+ return out;
100
+ }
101
+ const WORDS = /\s+|[\p{L}\p{N}\p{M}_]+|[^\s\p{L}\p{N}\p{M}_]/gu;
102
+ function tokens(block) {
103
+ const out = [];
104
+ block.forEach((child) => {
105
+ if (!child.isText)
106
+ out.push({ text: '', marks: child.marks, node: child });
107
+ else
108
+ for (const [text] of child.text.matchAll(WORDS))
109
+ out.push({ text, marks: child.marks, node: null });
110
+ });
111
+ return out;
112
+ }
113
+ const sameToken = (x, y) => x.node || y.node
114
+ ? !!x.node && !!y.node && x.node.eq(y.node)
115
+ : x.text === y.text && Mark.sameSet(x.marks, y.marks);
116
+ const tokenNode = (block, token) => token.node ?? block.type.schema.text(token.text, token.marks);
117
+ /**
118
+ * Word by word comparison of two textblocks, merged into the new one's type.
119
+ * `base` is the position where the block's content will start.
120
+ */
121
+ function mergeInline(a, b, base) {
122
+ const ta = tokens(a);
123
+ const tb = tokens(b);
124
+ const nodes = [];
125
+ const highlights = [];
126
+ const changes = [];
127
+ let pos = base;
128
+ for (const op of slideEdits(diffSequence(ta, tb, sameToken), ta, tb, sameToken)) {
129
+ const kind = op[0] === 'equal' ? null : op[0];
130
+ const token = op[0] === 'insert' ? tb[op[1]] : ta[op[1]];
131
+ const node = tokenNode(op[0] === 'insert' ? b : a, token);
132
+ nodes.push(node);
133
+ const to = pos + node.nodeSize;
134
+ if (kind) {
135
+ const last = highlights[highlights.length - 1];
136
+ // one change per run of the same kind: spaces between changed words do not split it
137
+ if (last && last.kind === kind && last.to === pos) {
138
+ highlights[highlights.length - 1] = { ...last, to };
139
+ const c = changes[changes.length - 1];
140
+ changes[changes.length - 1] = { ...c, to, text: c.text + token.text };
141
+ }
142
+ else {
143
+ highlights.push({ kind, from: pos, to });
144
+ changes.push({ kind, from: pos, to, text: token.text });
145
+ }
146
+ }
147
+ pos = to;
148
+ }
149
+ return { block: b.copy(Fragment.fromArray(nodes)), highlights, changes };
150
+ }
151
+ /** A whole block only in one version: every text inside it is highlighted, one change. */
152
+ function wholeBlock(node, kind, pos) {
153
+ const highlights = [];
154
+ if (node.isTextblock) {
155
+ if (node.content.size)
156
+ highlights.push({ kind, from: pos + 1, to: pos + 1 + node.content.size });
157
+ }
158
+ else
159
+ node.descendants((child, at) => {
160
+ if (!child.isTextblock)
161
+ return true;
162
+ if (child.content.size) {
163
+ const from = pos + 1 + at + 1;
164
+ highlights.push({ kind, from, to: from + child.content.size });
165
+ }
166
+ return false;
167
+ });
168
+ return {
169
+ nodes: [node],
170
+ highlights,
171
+ changes: [{ kind, from: pos, to: pos + node.nodeSize, text: node.textContent }],
172
+ };
173
+ }
174
+ /** Rows are compared whole: merging the cells of two rows would not make a table. */
175
+ const comparesChildren = (a, b) => !a.isTextblock && !a.isLeaf && a.type.spec.tableRole !== 'row' && a.sameMarkup(b);
176
+ /** Two blocks in the same place that differ: compared inside, or replaced. */
177
+ function mergeChanged(a, b, pos) {
178
+ if (a.isTextblock && b.isTextblock) {
179
+ // another type or other attributes (heading level, alignment…): shown as replaced
180
+ if (!a.sameMarkup(b))
181
+ return null;
182
+ const inline = mergeInline(a, b, pos + 1);
183
+ return { nodes: [inline.block], highlights: inline.highlights, changes: inline.changes };
184
+ }
185
+ if (comparesChildren(a, b)) {
186
+ const inner = mergeChildren(a, b, pos + 1);
187
+ return {
188
+ nodes: [b.copy(Fragment.fromArray(inner.nodes))],
189
+ highlights: inner.highlights,
190
+ changes: inner.changes,
191
+ };
192
+ }
193
+ return null;
194
+ }
195
+ function mergeChildren(a, b, base) {
196
+ const ca = [];
197
+ const cb = [];
198
+ a.forEach((n) => ca.push(n));
199
+ b.forEach((n) => cb.push(n));
200
+ const ops = diffSequence(ca, cb, (x, y) => x.eq(y));
201
+ const out = { nodes: [], highlights: [], changes: [] };
202
+ let pos = base;
203
+ const add = (m) => {
204
+ out.nodes.push(...m.nodes);
205
+ out.highlights.push(...m.highlights);
206
+ out.changes.push(...m.changes);
207
+ for (const node of m.nodes)
208
+ pos += node.nodeSize;
209
+ };
210
+ for (let k = 0; k < ops.length;) {
211
+ const op = ops[k];
212
+ if (op[0] === 'equal') {
213
+ add({ nodes: [cb[op[2]]], highlights: [], changes: [] });
214
+ k++;
215
+ continue;
216
+ }
217
+ // a run of deletions and insertions: pair them in order, the rest is removed or added
218
+ const deleted = [];
219
+ const inserted = [];
220
+ for (; k < ops.length && ops[k][0] !== 'equal'; k++) {
221
+ const o = ops[k];
222
+ if (o[0] === 'delete')
223
+ deleted.push(ca[o[1]]);
224
+ else
225
+ inserted.push(cb[o[1]]);
226
+ }
227
+ const pairs = Math.min(deleted.length, inserted.length);
228
+ for (let i = 0; i < pairs; i++) {
229
+ const merged = mergeChanged(deleted[i], inserted[i], pos);
230
+ if (merged)
231
+ add(merged);
232
+ else {
233
+ add(wholeBlock(deleted[i], 'delete', pos));
234
+ add(wholeBlock(inserted[i], 'insert', pos));
235
+ }
236
+ }
237
+ for (const node of deleted.slice(pairs))
238
+ add(wholeBlock(node, 'delete', pos));
239
+ for (const node of inserted.slice(pairs))
240
+ add(wholeBlock(node, 'insert', pos));
241
+ }
242
+ return out;
243
+ }
244
+ /**
245
+ * Compares two versions of a document. The merged document is for showing
246
+ * only: it may not follow every rule of the schema (two versions of a block
247
+ * side by side), so it is never put back into an editor that can change it.
248
+ */
249
+ export function diffDocs(oldDoc, newDoc) {
250
+ const merged = mergeChildren(oldDoc, newDoc, 0);
251
+ return {
252
+ doc: newDoc.copy(Fragment.fromArray(merged.nodes)),
253
+ highlights: merged.highlights,
254
+ changes: merged.changes,
255
+ };
256
+ }
257
+ //# sourceMappingURL=diff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diff.js","sourceRoot":"","sources":["../src/diff.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAa,MAAM,qBAAqB,CAAA;AAiC/D,wFAAwF;AACxF,MAAM,CAAC,MAAM,eAAe,GAAG,SAAS,CAAA;AAKxC;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAC1B,CAAe,EACf,CAAe,EACf,EAA2B;IAE3B,IAAI,KAAK,GAAG,CAAC,CAAA;IACb,OAAO,KAAK,GAAG,CAAC,CAAC,MAAM,IAAI,KAAK,GAAG,CAAC,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,KAAK,CAAE,EAAE,CAAC,CAAC,KAAK,CAAE,CAAC;QAAE,KAAK,EAAE,CAAA;IAChF,IAAI,IAAI,GAAG,CAAC,CAAC,MAAM,CAAA;IACnB,IAAI,IAAI,GAAG,CAAC,CAAC,MAAM,CAAA;IACnB,OAAO,IAAI,GAAG,KAAK,IAAI,IAA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AM,UAAU,QAAQ,CAAC,MAAY,EAAE,MAAY;IACjD,MAAM,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC,CAAA;IAC/C,OAAO;QACL,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAClD,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,OAAO,EAAE,MAAM,CAAC,OAAO;KACxB,CAAA;AACH,CAAC","sourcesContent":["import { Fragment, Mark, type Node } from '@scriba-editor/core'\n\n/**\n * Document comparison, pure (no DOM). The result is one merged document\n * holding the content of both versions: what only the old one has is marked\n * \"delete\", what only the new one has is marked \"insert\". Blocks are matched\n * first; matched paragraphs are then compared word by word.\n */\n\nexport type ChangeKind = 'insert' | 'delete'\n\n/** A range of the merged document to highlight (always inside a textblock). */\nexport interface Highlight {\n readonly kind: ChangeKind\n readonly from: number\n readonly to: number\n}\n\n/** One change to step through: some words, or a whole block. */\nexport interface Change {\n readonly kind: ChangeKind\n readonly from: number\n readonly to: number\n /** Its text (empty for an image or another element without text). */\n readonly text: string\n}\n\nexport interface DocDiff {\n readonly doc: Node\n readonly highlights: readonly Highlight[]\n readonly changes: readonly Change[]\n}\n\n/** Above this many comparisons a range is shown as replaced, not compared in detail. */\nexport const MAX_COMPARISONS = 4_000_000\n\ntype Op =\n readonly ['equal', number, number] | readonly ['delete', number] | readonly ['insert', number]\n\n/**\n * Edit script between two sequences (longest common subsequence). The common\n * start and end are skipped first, so the usual small edit is cheap; a middle\n * part too big to compare becomes \"delete all, insert all\".\n */\nexport function diffSequence<T>(\n a: readonly T[],\n b: readonly T[],\n eq: (x: T, y: T) => boolean,\n): Op[] {\n let start = 0\n while (start < a.length && start < b.length && eq(a[start]!, b[start]!)) start++\n let endA = a.length\n let endB = b.length\n while (endA > start && endB > start && eq(a[endA - 1]!, b[endB - 1]!)) {\n endA--\n endB--\n }\n const ops: Op[] = []\n for (let i = 0; i < start; i++) ops.push(['equal', i, i])\n const n = endA - start\n const m = endB - start\n if (n && m && n * m <= MAX_COMPARISONS) {\n // lengths of the common subsequences of the suffixes\n const w = m + 1\n const table = new Uint32Array((n + 1) * w)\n for (let i = n - 1; i >= 0; i--)\n for (let j = m - 1; j >= 0; j--)\n table[i * w + j] = eq(a[start + i]!, b[start + j]!)\n ? table[(i + 1) * w + j + 1]! + 1\n : Math.max(table[(i + 1) * w + j]!, table[i * w + j + 1]!)\n let i = 0\n let j = 0\n while (i < n && j < m) {\n if (eq(a[start + i]!, b[start + j]!)) ops.push(['equal', start + i++, start + j++])\n else if (table[(i + 1) * w + j]! >= table[i * w + j + 1]!) ops.push(['delete', start + i++])\n else ops.push(['insert', start + j++])\n }\n while (i < n) ops.push(['delete', start + i++])\n while (j < m) ops.push(['insert', start + j++])\n } else {\n for (let i = start; i < endA; i++) ops.push(['delete', i])\n for (let j = start; j < endB; j++) ops.push(['insert', j])\n }\n for (let i = endA, j = endB; i < a.length; i++, j++) ops.push(['equal', i, j])\n return ops\n}\n\n/**\n * Moves each run of only insertions (or only deletions) to the right while\n * the result is the same: \"dorme[. Sogna].\" becomes \"dorme[ Sogna.]\", which\n * is how a person reads the change. Equal tokens on both sides are swapped,\n * never changed.\n */\nexport function slideEdits<T>(\n ops: Op[],\n a: readonly T[],\n b: readonly T[],\n eq: (x: T, y: T) => boolean,\n): Op[] {\n const out = [...ops]\n for (let k = 0; k < out.length; k++) {\n const kind = out[k]![0]\n if (kind === 'equal') continue\n let end = k\n while (end + 1 < out.length && out[end + 1]![0] === kind) end++\n const mixed =\n (end + 1 < out.length && out[end + 1]![0] !== 'equal') ||\n (k > 0 && out[k - 1]![0] !== 'equal')\n if (mixed) {\n k = end\n continue\n }\n const seq = kind === 'insert' ? b : a\n // the run is seq[first..last]; the equal op after it pairs seq[last + 1]\n while (end + 1 < out.length) {\n const after = out[end + 1] as readonly ['equal', number, number]\n const first = out[k]![1] as number\n const next = kind === 'insert' ? after[2] : after[1]\n if (!eq(seq[first]!, seq[next]!)) break\n // seq[first] takes the place of seq[next] in the equal pair; the run moves one step right\n const equal: Op = kind === 'insert' ? ['equal', after[1], first] : ['equal', first, after[2]]\n out.splice(k, 1)\n out.splice(end, 1, kind === 'insert' ? ['insert', next] : ['delete', next])\n out.splice(k, 0, equal)\n k++\n end++\n if (end + 1 < out.length && out[end + 1]![0] !== 'equal') break\n }\n k = end\n }\n return out\n}\n\n/** A word, a space run, a punctuation sign, or an inline element (image, mention…). */\ninterface Token {\n readonly text: string\n readonly marks: readonly Mark[]\n readonly node: Node | null\n}\n\nconst WORDS = /\\s+|[\\p{L}\\p{N}\\p{M}_]+|[^\\s\\p{L}\\p{N}\\p{M}_]/gu\n\nfunction tokens(block: Node): Token[] {\n const out: Token[] = []\n block.forEach((child) => {\n if (!child.isText) out.push({ text: '', marks: child.marks, node: child })\n else\n for (const [text] of child.text.matchAll(WORDS))\n out.push({ text, marks: child.marks, node: null })\n })\n return out\n}\n\nconst sameToken = (x: Token, y: Token) =>\n x.node || y.node\n ? !!x.node && !!y.node && x.node.eq(y.node)\n : x.text === y.text && Mark.sameSet(x.marks, y.marks)\n\nconst tokenNode = (block: Node, token: Token): Node =>\n token.node ?? block.type.schema.text(token.text, token.marks)\n\n/** What a merge adds at some position: nodes, ranges to highlight, changes. */\ninterface Merged {\n nodes: Node[]\n highlights: Highlight[]\n changes: Change[]\n}\n\n/**\n * Word by word comparison of two textblocks, merged into the new one's type.\n * `base` is the position where the block's content will start.\n */\nfunction mergeInline(\n a: Node,\n b: Node,\n base: number,\n): { block: Node; highlights: Highlight[]; changes: Change[] } {\n const ta = tokens(a)\n const tb = tokens(b)\n const nodes: Node[] = []\n const highlights: Highlight[] = []\n const changes: Change[] = []\n let pos = base\n for (const op of slideEdits(diffSequence(ta, tb, sameToken), ta, tb, sameToken)) {\n const kind = op[0] === 'equal' ? null : op[0]\n const token = op[0] === 'insert' ? tb[op[1]]! : ta[op[1]]!\n const node = tokenNode(op[0] === 'insert' ? b : a, token)\n nodes.push(node)\n const to = pos + node.nodeSize\n if (kind) {\n const last = highlights[highlights.length - 1]\n // one change per run of the same kind: spaces between changed words do not split it\n if (last && last.kind === kind && last.to === pos) {\n highlights[highlights.length - 1] = { ...last, to }\n const c = changes[changes.length - 1]!\n changes[changes.length - 1] = { ...c, to, text: c.text + token.text }\n } else {\n highlights.push({ kind, from: pos, to })\n changes.push({ kind, from: pos, to, text: token.text })\n }\n }\n pos = to\n }\n return { block: b.copy(Fragment.fromArray(nodes)), highlights, changes }\n}\n\n/** A whole block only in one version: every text inside it is highlighted, one change. */\nfunction wholeBlock(node: Node, kind: ChangeKind, pos: number): Merged {\n const highlights: Highlight[] = []\n if (node.isTextblock) {\n if (node.content.size) highlights.push({ kind, from: pos + 1, to: pos + 1 + node.content.size })\n } else\n node.descendants((child, at) => {\n if (!child.isTextblock) return true\n if (child.content.size) {\n const from = pos + 1 + at + 1\n highlights.push({ kind, from, to: from + child.content.size })\n }\n return false\n })\n return {\n nodes: [node],\n highlights,\n changes: [{ kind, from: pos, to: pos + node.nodeSize, text: node.textContent }],\n }\n}\n\n/** Rows are compared whole: merging the cells of two rows would not make a table. */\nconst comparesChildren = (a: Node, b: Node) =>\n !a.isTextblock && !a.isLeaf && a.type.spec.tableRole !== 'row' && a.sameMarkup(b)\n\n/** Two blocks in the same place that differ: compared inside, or replaced. */\nfunction mergeChanged(a: Node, b: Node, pos: number): Merged | null {\n if (a.isTextblock && b.isTextblock) {\n // another type or other attributes (heading level, alignment…): shown as replaced\n if (!a.sameMarkup(b)) return null\n const inline = mergeInline(a, b, pos + 1)\n return { nodes: [inline.block], highlights: inline.highlights, changes: inline.changes }\n }\n if (comparesChildren(a, b)) {\n const inner = mergeChildren(a, b, pos + 1)\n return {\n nodes: [b.copy(Fragment.fromArray(inner.nodes))],\n highlights: inner.highlights,\n changes: inner.changes,\n }\n }\n return null\n}\n\nfunction mergeChildren(a: Node, b: Node, base: number): Merged {\n const ca: Node[] = []\n const cb: Node[] = []\n a.forEach((n) => ca.push(n))\n b.forEach((n) => cb.push(n))\n const ops = diffSequence(ca, cb, (x, y) => x.eq(y))\n const out: Merged = { nodes: [], highlights: [], changes: [] }\n let pos = base\n const add = (m: Merged) => {\n out.nodes.push(...m.nodes)\n out.highlights.push(...m.highlights)\n out.changes.push(...m.changes)\n for (const node of m.nodes) pos += node.nodeSize\n }\n for (let k = 0; k < ops.length;) {\n const op = ops[k]!\n if (op[0] === 'equal') {\n add({ nodes: [cb[op[2]]!], highlights: [], changes: [] })\n k++\n continue\n }\n // a run of deletions and insertions: pair them in order, the rest is removed or added\n const deleted: Node[] = []\n const inserted: Node[] = []\n for (; k < ops.length && ops[k]![0] !== 'equal'; k++) {\n const o = ops[k]!\n if (o[0] === 'delete') deleted.push(ca[o[1]]!)\n else inserted.push(cb[o[1]]!)\n }\n const pairs = Math.min(deleted.length, inserted.length)\n for (let i = 0; i < pairs; i++) {\n const merged = mergeChanged(deleted[i]!, inserted[i]!, pos)\n if (merged) add(merged)\n else {\n add(wholeBlock(deleted[i]!, 'delete', pos))\n add(wholeBlock(inserted[i]!, 'insert', pos))\n }\n }\n for (const node of deleted.slice(pairs)) add(wholeBlock(node, 'delete', pos))\n for (const node of inserted.slice(pairs)) add(wholeBlock(node, 'insert', pos))\n }\n return out\n}\n\n/**\n * Compares two versions of a document. The merged document is for showing\n * only: it may not follow every rule of the schema (two versions of a block\n * side by side), so it is never put back into an editor that can change it.\n */\nexport function diffDocs(oldDoc: Node, newDoc: Node): DocDiff {\n const merged = mergeChildren(oldDoc, newDoc, 0)\n return {\n doc: newDoc.copy(Fragment.fromArray(merged.nodes)),\n highlights: merged.highlights,\n changes: merged.changes,\n }\n}\n"]}
@@ -0,0 +1,11 @@
1
+ import type { Translate } from '@scriba-editor/i18n';
2
+ import type { ToolbarButton } from '@scriba-editor/ui';
3
+ import type { RevisionOptions } from './content.js';
4
+ export { MAX_REVISION_LENGTH, formatRevisionDate, parseRevision, type Revision, type RevisionOptions, } from './content.js';
5
+ export { MAX_COMPARISONS, diffDocs, diffSequence, slideEdits, type Change, type ChangeKind, type DocDiff, type Highlight, } from './diff.js';
6
+ export { openRevisionDialog } from './dialog.js';
7
+ /**
8
+ * Menu or toolbar entry "Version history…". Also available when read-only:
9
+ * versions can be looked at and compared, only "Restore" is disabled.
10
+ */
11
+ export declare function revisionsToolbarItem(t: Translate, options: RevisionOptions): ToolbarButton;
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ import { openRevisionDialog } from './dialog.js';
2
+ export { MAX_REVISION_LENGTH, formatRevisionDate, parseRevision, } from './content.js';
3
+ export { MAX_COMPARISONS, diffDocs, diffSequence, slideEdits, } from './diff.js';
4
+ export { openRevisionDialog } from './dialog.js';
5
+ /**
6
+ * Menu or toolbar entry "Version history…". Also available when read-only:
7
+ * versions can be looked at and compared, only "Restore" is disabled.
8
+ */
9
+ export function revisionsToolbarItem(t, options) {
10
+ return {
11
+ type: 'button',
12
+ id: 'revisions',
13
+ icon: 'history',
14
+ label: (tr) => tr('revisions.label'),
15
+ command: () => true,
16
+ readOnly: true,
17
+ run: (view) => void openRevisionDialog(view, t, options),
18
+ };
19
+ }
20
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAEhD,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,aAAa,GAGd,MAAM,cAAc,CAAA;AACrB,OAAO,EACL,eAAe,EACf,QAAQ,EACR,YAAY,EACZ,UAAU,GAKX,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAEhD;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAAC,CAAY,EAAE,OAAwB;IACzE,OAAO;QACL,IAAI,EAAE,QAAQ;QACd,EAAE,EAAE,WAAW;QACf,IAAI,EAAE,SAAS;QACf,KAAK,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,iBAAiB,CAAC;QACpC,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI;QACnB,QAAQ,EAAE,IAAI;QACd,GAAG,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,kBAAkB,CAAC,IAAkB,EAAE,CAAC,EAAE,OAAO,CAAC;KACvE,CAAA;AACH,CAAC","sourcesContent":["import type { Translate } from '@scriba-editor/i18n'\nimport type { ToolbarButton } from '@scriba-editor/ui'\nimport type { EditorView } from '@scriba-editor/view'\nimport type { RevisionOptions } from './content.js'\nimport { openRevisionDialog } from './dialog.js'\n\nexport {\n MAX_REVISION_LENGTH,\n formatRevisionDate,\n parseRevision,\n type Revision,\n type RevisionOptions,\n} from './content.js'\nexport {\n MAX_COMPARISONS,\n diffDocs,\n diffSequence,\n slideEdits,\n type Change,\n type ChangeKind,\n type DocDiff,\n type Highlight,\n} from './diff.js'\nexport { openRevisionDialog } from './dialog.js'\n\n/**\n * Menu or toolbar entry \"Version history…\". Also available when read-only:\n * versions can be looked at and compared, only \"Restore\" is disabled.\n */\nexport function revisionsToolbarItem(t: Translate, options: RevisionOptions): ToolbarButton {\n return {\n type: 'button',\n id: 'revisions',\n icon: 'history',\n label: (tr) => tr('revisions.label'),\n command: () => true,\n readOnly: true,\n run: (view) => void openRevisionDialog(view as EditorView, t, options),\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@scriba-editor/plugin-revisions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "sideEffects": false,
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "NOTICE"
17
+ ],
18
+ "license": "Apache-2.0",
19
+ "description": "Version history for the Scriba editor: list the saved versions, compare one with the current document, restore it.",
20
+ "dependencies": {
21
+ "@scriba-editor/core": "0.1.0",
22
+ "@scriba-editor/view": "0.1.0",
23
+ "@scriba-editor/i18n": "0.1.0",
24
+ "@scriba-editor/ui": "0.1.0"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "keywords": [
30
+ "scriba",
31
+ "editor",
32
+ "rich-text",
33
+ "wysiwyg"
34
+ ],
35
+ "author": "Mario Trombino",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/mariotrombino76/scriba.git",
39
+ "directory": "packages/plugins/revisions"
40
+ },
41
+ "homepage": "https://github.com/mariotrombino76/scriba/tree/main/packages/plugins/revisions#readme",
42
+ "bugs": {
43
+ "url": "https://github.com/mariotrombino76/scriba/issues"
44
+ },
45
+ "scripts": {
46
+ "build": "node ../../../node_modules/typescript7/bin/tsc -p tsconfig.build.json"
47
+ }
6
48
  }