@mdzip/editor 2.4.2 → 2.5.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/AGENTS.md +8 -0
- package/README.md +266 -5
- package/dist/diff-rendered.d.ts +54 -0
- package/dist/diff-rendered.d.ts.map +1 -0
- package/dist/diff-rendered.js +462 -0
- package/dist/diff-rendered.js.map +1 -0
- package/dist/diff-view-css.d.ts +2 -0
- package/dist/diff-view-css.d.ts.map +1 -1
- package/dist/diff-view-css.js +106 -43
- package/dist/diff-view-css.js.map +1 -1
- package/dist/diff-view.d.ts +112 -9
- package/dist/diff-view.d.ts.map +1 -1
- package/dist/diff-view.js +419 -33
- package/dist/diff-view.js.map +1 -1
- package/dist/front-matter-extension.d.ts.map +1 -1
- package/dist/front-matter-extension.js +2 -8
- package/dist/front-matter-extension.js.map +1 -1
- package/dist/heading-outline.d.ts +66 -0
- package/dist/heading-outline.d.ts.map +1 -0
- package/dist/heading-outline.js +208 -0
- package/dist/heading-outline.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/json-validation.d.ts +97 -0
- package/dist/json-validation.d.ts.map +1 -0
- package/dist/json-validation.js +496 -0
- package/dist/json-validation.js.map +1 -0
- package/dist/library-info.d.ts +7 -2
- package/dist/library-info.d.ts.map +1 -1
- package/dist/library-info.js +8 -2
- package/dist/library-info.js.map +1 -1
- package/dist/manifest-form.d.ts +40 -0
- package/dist/manifest-form.d.ts.map +1 -0
- package/dist/manifest-form.js +318 -0
- package/dist/manifest-form.js.map +1 -0
- package/dist/merge-conflicts.d.ts +56 -0
- package/dist/merge-conflicts.d.ts.map +1 -0
- package/dist/merge-conflicts.js +130 -0
- package/dist/merge-conflicts.js.map +1 -0
- package/dist/merge-regions.d.ts +92 -0
- package/dist/merge-regions.d.ts.map +1 -0
- package/dist/merge-regions.js +416 -0
- package/dist/merge-regions.js.map +1 -0
- package/dist/merge-view.d.ts +267 -0
- package/dist/merge-view.d.ts.map +1 -0
- package/dist/merge-view.js +2039 -0
- package/dist/merge-view.js.map +1 -0
- package/dist/preview-find.d.ts +30 -0
- package/dist/preview-find.d.ts.map +1 -0
- package/dist/preview-find.js +172 -0
- package/dist/preview-find.js.map +1 -0
- package/dist/rendering.d.ts +17 -52
- package/dist/rendering.d.ts.map +1 -1
- package/dist/rendering.js +21 -324
- package/dist/rendering.js.map +1 -1
- package/dist/scroll-anchors.d.ts +33 -0
- package/dist/scroll-anchors.d.ts.map +1 -0
- package/dist/scroll-anchors.js +80 -0
- package/dist/scroll-anchors.js.map +1 -0
- package/dist/view-css.d.ts.map +1 -1
- package/dist/view-css.js +2859 -2306
- package/dist/view-css.js.map +1 -1
- package/dist/view.d.ts +314 -7
- package/dist/view.d.ts.map +1 -1
- package/dist/view.js +1975 -419
- package/dist/view.js.map +1 -1
- package/dist/workspace-view.d.ts +2 -0
- package/dist/workspace-view.d.ts.map +1 -1
- package/dist/workspace-view.js +25 -2
- package/dist/workspace-view.js.map +1 -1
- package/dist/workspace.d.ts +29 -0
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +124 -9
- package/dist/workspace.js.map +1 -1
- package/package.json +93 -83
|
@@ -0,0 +1,2039 @@
|
|
|
1
|
+
import { MdzArchiveCore } from '@mdzip/core-js';
|
|
2
|
+
import { markdown as markdownLanguage } from '@codemirror/lang-markdown';
|
|
3
|
+
import { Chunk } from '@codemirror/merge';
|
|
4
|
+
import { search, searchKeymap } from '@codemirror/search';
|
|
5
|
+
import { EditorState, RangeSet, StateEffect, StateField, Text } from '@codemirror/state';
|
|
6
|
+
import { Decoration, EditorView, GutterMarker, WidgetType, gutter, keymap, lineNumbers } from '@codemirror/view';
|
|
7
|
+
import { ChevronDown, ChevronUp, Eye, SquarePen } from 'lucide';
|
|
8
|
+
import { MergeModel } from './merge-regions.js';
|
|
9
|
+
import { mapScrollPosition, matchSequences } from './scroll-anchors.js';
|
|
10
|
+
import { removeFilesFromArchive, updateBinaryInArchive } from './archive-utils.js';
|
|
11
|
+
import { markBlockChanges, renderSideFragment } from './diff-rendered.js';
|
|
12
|
+
import { injectDiffViewStyles, injectPreviewStyles } from './diff-view-css.js';
|
|
13
|
+
import { findMergeConflicts, mergeConflictReplacement } from './merge-conflicts.js';
|
|
14
|
+
const MERGE_STYLE_ID = 'mdzip-merge-view-styles';
|
|
15
|
+
const MANIFEST_PATH = 'manifest.json';
|
|
16
|
+
const TEXT_EXTENSIONS = new Set([
|
|
17
|
+
'md', 'markdown', 'json', 'txt', 'svg', 'drawio', 'css', 'csv', 'tsv',
|
|
18
|
+
'html', 'htm', 'xml', 'yml', 'yaml', 'js', 'mjs', 'ts', 'toml', 'ini', 'mmd'
|
|
19
|
+
]);
|
|
20
|
+
/** `images/chart.theirs.png` or `images/chart.theirs-2.png` → `images/chart.png`. */
|
|
21
|
+
const THEIRS_COPY_RE = /^(.*)\.theirs(?:-\d+)?(\.[^./]+)?$/;
|
|
22
|
+
/** Text files sharing at least this much (Dice coefficient of their lines) count as renamed, as `mdz merge` does. */
|
|
23
|
+
const RENAME_SIMILARITY = 0.6;
|
|
24
|
+
/** Manifest fields the merge always settles itself. */
|
|
25
|
+
const MANIFEST_SETTLED = new Set(['created', 'modified', 'files']);
|
|
26
|
+
const COMMIT_DELAY_MS = 300;
|
|
27
|
+
const MARKERS = {
|
|
28
|
+
conflict: '●', decision: '◐', review: '↺', merged: '✓', unchanged: ''
|
|
29
|
+
};
|
|
30
|
+
const setCurrentConflict = StateEffect.define();
|
|
31
|
+
export class MdzipMergeView {
|
|
32
|
+
constructor(container, options) {
|
|
33
|
+
this.showUnchanged = false;
|
|
34
|
+
this.plain = false;
|
|
35
|
+
this.resultBytes = null;
|
|
36
|
+
this.resultFiles = new Map();
|
|
37
|
+
this.resultManifest = null;
|
|
38
|
+
this.versionFiles = null;
|
|
39
|
+
this.texts = new Map();
|
|
40
|
+
this.entries = [];
|
|
41
|
+
this.items = [];
|
|
42
|
+
this.cursor = 0;
|
|
43
|
+
this.selectedPath = null;
|
|
44
|
+
/** The current conflict within the selected text entry. */
|
|
45
|
+
this.currentInEntry = 0;
|
|
46
|
+
this.resultEditor = null;
|
|
47
|
+
this.sideEditors = {};
|
|
48
|
+
/** Each text entry's merge regions, kept in step with its text. */
|
|
49
|
+
this.models = new Map();
|
|
50
|
+
/** The region of the current conflict in the shown file, or -1. */
|
|
51
|
+
this.currentRegion = -1;
|
|
52
|
+
this.takeAllBoxes = {};
|
|
53
|
+
this.resultStatus = null;
|
|
54
|
+
this.stopScrollSync = null;
|
|
55
|
+
this.pendingCommits = new Set();
|
|
56
|
+
this.generation = 0;
|
|
57
|
+
this.renderGeneration = 0;
|
|
58
|
+
this.busy = Promise.resolve();
|
|
59
|
+
this.objectUrls = [];
|
|
60
|
+
this.lastRemaining = -1;
|
|
61
|
+
this.destroyed = false;
|
|
62
|
+
this.busyCommit = Promise.resolve();
|
|
63
|
+
this.options = options;
|
|
64
|
+
this.rendered = options.rendered ?? false;
|
|
65
|
+
this.colorScheme = options.colorScheme ?? 'light';
|
|
66
|
+
this.density = options.toolbarDensity ?? 'comfortable';
|
|
67
|
+
const doc = container.ownerDocument;
|
|
68
|
+
injectDiffViewStyles(doc);
|
|
69
|
+
injectMergeStyles(doc);
|
|
70
|
+
container.replaceChildren();
|
|
71
|
+
this.root = doc.createElement('div');
|
|
72
|
+
this.applyRootClass();
|
|
73
|
+
this.root.innerHTML = `
|
|
74
|
+
<div class="mdzip-diff-toolbar" role="toolbar" aria-label="Conflict controls">
|
|
75
|
+
<button class="mdzip-diff-toolbar-button" type="button" data-ref="prev-conflict" title="Previous conflict" aria-label="Previous conflict"></button>
|
|
76
|
+
<button class="mdzip-diff-toolbar-button" type="button" data-ref="next-conflict" title="Next conflict" aria-label="Next conflict"></button>
|
|
77
|
+
<span class="mdzip-diff-change-count" data-ref="conflict-count" aria-live="polite"></span>
|
|
78
|
+
<div class="mdzip-diff-toolbar-group" role="group" aria-label="Markdown view">
|
|
79
|
+
<button class="mdzip-diff-toolbar-button" type="button" data-ref="source" title="Edit Markdown source" aria-label="Edit Markdown source"></button>
|
|
80
|
+
<button class="mdzip-diff-toolbar-button" type="button" data-ref="rendered" title="Show rendered Markdown" aria-label="Show rendered Markdown"></button>
|
|
81
|
+
</div>
|
|
82
|
+
<button class="mdzip-merge-complete" type="button" data-ref="complete" hidden>Complete Merge</button>
|
|
83
|
+
</div>
|
|
84
|
+
<div class="mdzip-merge-workspace">
|
|
85
|
+
<nav class="mdzip-diff-nav mdzip-merge-nav" aria-label="Files">
|
|
86
|
+
<div class="mdzip-diff-summary mdzip-merge-nav-summary" data-ref="nav-summary"></div>
|
|
87
|
+
<div class="mdzip-diff-list" role="listbox" aria-label="Files" data-ref="nav-list"></div>
|
|
88
|
+
</nav>
|
|
89
|
+
<section class="mdzip-merge-content" data-ref="content"><div class="mdzip-diff-message">Loading the merge...</div></section>
|
|
90
|
+
</div>`;
|
|
91
|
+
container.append(this.root);
|
|
92
|
+
const ref = (name) => this.root.querySelector(`[data-ref="${name}"]`);
|
|
93
|
+
this.nav = this.root.querySelector('.mdzip-merge-nav');
|
|
94
|
+
this.navList = ref('nav-list');
|
|
95
|
+
this.navSummary = ref('nav-summary');
|
|
96
|
+
this.content = ref('content');
|
|
97
|
+
this.prevButton = ref('prev-conflict');
|
|
98
|
+
this.nextButton = ref('next-conflict');
|
|
99
|
+
this.countLabel = ref('conflict-count');
|
|
100
|
+
this.sourceButton = ref('source');
|
|
101
|
+
this.renderedButton = ref('rendered');
|
|
102
|
+
this.completeButton = ref('complete');
|
|
103
|
+
this.completeButton.addEventListener('click', () => {
|
|
104
|
+
this.completeButton.disabled = true;
|
|
105
|
+
this.complete().catch((cause) => this.fail(cause)).finally(() => { this.completeButton.disabled = false; });
|
|
106
|
+
});
|
|
107
|
+
this.prevButton.innerHTML = iconHtml(ChevronUp);
|
|
108
|
+
this.nextButton.innerHTML = iconHtml(ChevronDown);
|
|
109
|
+
this.sourceButton.innerHTML = iconHtml(SquarePen);
|
|
110
|
+
this.renderedButton.innerHTML = iconHtml(Eye);
|
|
111
|
+
this.prevButton.addEventListener('click', () => this.openPreviousConflict());
|
|
112
|
+
this.nextButton.addEventListener('click', () => this.openNextConflict());
|
|
113
|
+
this.sourceButton.addEventListener('click', () => { void this.setRendered(false); });
|
|
114
|
+
this.renderedButton.addEventListener('click', () => { void this.setRendered(true); });
|
|
115
|
+
void this.open(options);
|
|
116
|
+
}
|
|
117
|
+
// ------------------------------------------------------------ public API
|
|
118
|
+
/** Loads a merge (again), replacing what the view had. */
|
|
119
|
+
async open(options) {
|
|
120
|
+
this.flushCommits();
|
|
121
|
+
this.options = options;
|
|
122
|
+
this.rendered = options.rendered ?? this.rendered;
|
|
123
|
+
this.colorScheme = options.colorScheme ?? this.colorScheme;
|
|
124
|
+
this.density = options.toolbarDensity ?? this.density;
|
|
125
|
+
this.applyRootClass();
|
|
126
|
+
const generation = ++this.generation;
|
|
127
|
+
this.texts.clear();
|
|
128
|
+
this.models.clear();
|
|
129
|
+
this.resultBytes = null;
|
|
130
|
+
this.resultFiles = new Map();
|
|
131
|
+
this.resultManifest = null;
|
|
132
|
+
this.versionFiles = null;
|
|
133
|
+
this.lastRemaining = -1;
|
|
134
|
+
try {
|
|
135
|
+
if (options.markdown !== undefined) {
|
|
136
|
+
this.plain = true;
|
|
137
|
+
this.entries = [this.plainEntry(options.markdown)];
|
|
138
|
+
}
|
|
139
|
+
else if (options.bytes) {
|
|
140
|
+
this.plain = false;
|
|
141
|
+
const entries = await this.loadArchive(options.bytes, options.versions);
|
|
142
|
+
if (generation !== this.generation)
|
|
143
|
+
return;
|
|
144
|
+
this.entries = entries;
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
throw new Error('Pass an archive (bytes) or a Markdown document (markdown) to resolve.');
|
|
148
|
+
}
|
|
149
|
+
this.refreshItems();
|
|
150
|
+
this.lastRemaining = this.items.length;
|
|
151
|
+
this.cursor = 0;
|
|
152
|
+
const first = this.items[0];
|
|
153
|
+
const start = first?.path
|
|
154
|
+
?? this.entries.find((entry) => entry.state() !== 'unchanged' && entry.state() !== 'merged')?.path
|
|
155
|
+
?? this.visibleEntries()[0]?.path
|
|
156
|
+
?? null;
|
|
157
|
+
this.selectedPath = start;
|
|
158
|
+
this.currentInEntry = 0;
|
|
159
|
+
this.renderNav();
|
|
160
|
+
await this.renderEntry();
|
|
161
|
+
}
|
|
162
|
+
catch (cause) {
|
|
163
|
+
if (generation !== this.generation)
|
|
164
|
+
return;
|
|
165
|
+
const error = cause instanceof Error ? cause : new Error(String(cause));
|
|
166
|
+
this.options.onFailed?.(error);
|
|
167
|
+
this.content.innerHTML = `<div class="mdzip-diff-message mdzip-diff-error">${escapeHtml(error.message)}</div>`;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/** What's left to resolve, in the tree's order. */
|
|
171
|
+
get conflicts() {
|
|
172
|
+
return this.items;
|
|
173
|
+
}
|
|
174
|
+
get conflictCount() {
|
|
175
|
+
return this.items.length;
|
|
176
|
+
}
|
|
177
|
+
/** Every file the merge touched (and, with `versions`, the unchanged ones), in the tree's order. */
|
|
178
|
+
get files() {
|
|
179
|
+
return this.entries.map((entry) => ({
|
|
180
|
+
path: entry.path,
|
|
181
|
+
state: entry.state(),
|
|
182
|
+
summary: entry.summaryText(),
|
|
183
|
+
conflicts: entry.text && entry.inResult ? findMergeConflicts(this.texts.get(entry.path) ?? '').length : 0,
|
|
184
|
+
inResult: entry.inResult
|
|
185
|
+
}));
|
|
186
|
+
}
|
|
187
|
+
get isRendered() {
|
|
188
|
+
return this.rendered;
|
|
189
|
+
}
|
|
190
|
+
/** The file the view shows. */
|
|
191
|
+
get selectedFile() {
|
|
192
|
+
return this.selectedPath;
|
|
193
|
+
}
|
|
194
|
+
/** A text entry's current text (the plain document's when `path` is omitted). */
|
|
195
|
+
getText(path) {
|
|
196
|
+
return this.texts.get(path ?? (this.plain ? this.entries[0]?.path : this.selectedPath) ?? '');
|
|
197
|
+
}
|
|
198
|
+
/** The archive as resolved so far (pending edits included), or null for a plain document. */
|
|
199
|
+
getArchiveBytes() {
|
|
200
|
+
return this.resultBytes;
|
|
201
|
+
}
|
|
202
|
+
async setRendered(rendered) {
|
|
203
|
+
if (this.rendered === rendered)
|
|
204
|
+
return;
|
|
205
|
+
this.flushCommits();
|
|
206
|
+
this.rendered = rendered;
|
|
207
|
+
this.updateToolbar();
|
|
208
|
+
await this.renderEntry();
|
|
209
|
+
}
|
|
210
|
+
/** Shows a file. */
|
|
211
|
+
async selectFile(path) {
|
|
212
|
+
if (!this.entries.some((entry) => entry.path === path))
|
|
213
|
+
return;
|
|
214
|
+
this.flushCommits();
|
|
215
|
+
this.selectedPath = path;
|
|
216
|
+
this.currentInEntry = 0;
|
|
217
|
+
const index = this.items.findIndex((item) => item.path === path);
|
|
218
|
+
if (index >= 0)
|
|
219
|
+
this.cursor = index;
|
|
220
|
+
this.renderNav();
|
|
221
|
+
await this.renderEntry();
|
|
222
|
+
}
|
|
223
|
+
openNextConflict() {
|
|
224
|
+
if (this.cursor >= this.items.length - 1)
|
|
225
|
+
return false;
|
|
226
|
+
void this.goTo(this.cursor + 1);
|
|
227
|
+
return true;
|
|
228
|
+
}
|
|
229
|
+
openPreviousConflict() {
|
|
230
|
+
if (this.cursor <= 0)
|
|
231
|
+
return false;
|
|
232
|
+
void this.goTo(this.cursor - 1);
|
|
233
|
+
return true;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Resolves item `index` (in {@link conflicts}). A text conflict takes a
|
|
237
|
+
* {@link MergeConflictResolution}; a binary one `'ours'` or `'theirs'`.
|
|
238
|
+
*/
|
|
239
|
+
resolve(index, resolution) {
|
|
240
|
+
return this.queue(async () => {
|
|
241
|
+
const item = this.items[index];
|
|
242
|
+
if (!item)
|
|
243
|
+
throw new RangeError(`There is no conflict ${index + 1} to resolve.`);
|
|
244
|
+
if (item.kind === 'text') {
|
|
245
|
+
const conflicts = findMergeConflicts(this.texts.get(item.path) ?? '');
|
|
246
|
+
const within = conflicts.findIndex((conflict) => conflict.start === item.conflict.start);
|
|
247
|
+
await this.resolveTextConflict(item.path, within < 0 ? item.conflict.index : within, resolution);
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
await this.resolveBinary(item, resolution);
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Settles a file the merge kept although one side deleted it: keep it, or
|
|
256
|
+
* delete it.
|
|
257
|
+
*/
|
|
258
|
+
resolveFile(path, action) {
|
|
259
|
+
return this.queue(async () => {
|
|
260
|
+
const entry = this.entries.find((candidate) => candidate.path === path);
|
|
261
|
+
if (!entry)
|
|
262
|
+
throw new RangeError(`${path} isn't part of this merge.`);
|
|
263
|
+
if (action === 'delete' && entry.inResult) {
|
|
264
|
+
this.flushCommits();
|
|
265
|
+
if (this.resultBytes)
|
|
266
|
+
this.resultBytes = await removeFilesFromArchive(this.resultBytes, [path]);
|
|
267
|
+
this.resultFiles.delete(path);
|
|
268
|
+
this.texts.delete(path);
|
|
269
|
+
entry.inResult = false;
|
|
270
|
+
}
|
|
271
|
+
entry.reviewed = true;
|
|
272
|
+
await this.afterChange({ path });
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
/** Sets a manifest field both sides changed to current (ours) or incoming (theirs). */
|
|
276
|
+
chooseManifestField(key, side) {
|
|
277
|
+
return this.queue(async () => {
|
|
278
|
+
const entry = this.entries.find((candidate) => candidate.manifestFields);
|
|
279
|
+
const field = entry?.manifestFields?.find((candidate) => candidate.key === key);
|
|
280
|
+
if (!entry || !field || !this.resultBytes)
|
|
281
|
+
throw new RangeError(`The manifest has no conflicting field "${key}".`);
|
|
282
|
+
const manifest = parseJson(this.resultFiles.get(MANIFEST_PATH)) ?? {};
|
|
283
|
+
const value = side === 'ours' ? field.ours : field.theirs;
|
|
284
|
+
if (value === undefined)
|
|
285
|
+
delete manifest[key];
|
|
286
|
+
else
|
|
287
|
+
manifest[key] = value;
|
|
288
|
+
const bytes = encode(`${JSON.stringify(manifest, null, 2)}\n`);
|
|
289
|
+
this.resultBytes = await updateBinaryInArchive(this.resultBytes, MANIFEST_PATH, bytes);
|
|
290
|
+
this.resultFiles.set(MANIFEST_PATH, bytes);
|
|
291
|
+
field.chosen = side;
|
|
292
|
+
entry.reviewed = true;
|
|
293
|
+
await this.afterChange({ path: MANIFEST_PATH });
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Sets which sides a text file's change takes, as its checkboxes do: `index`
|
|
298
|
+
* counts the file's changes (conflicts and one-sided changes alike) from the
|
|
299
|
+
* top, `sides` in the order they go in. No sides takes the original text, or
|
|
300
|
+
* for a conflict brings its markers back.
|
|
301
|
+
*/
|
|
302
|
+
chooseChange(path, index, sides) {
|
|
303
|
+
return this.queue(async () => {
|
|
304
|
+
const entry = this.entry(path);
|
|
305
|
+
const model = entry ? this.modelFor(entry) : null;
|
|
306
|
+
const region = model?.regions[index];
|
|
307
|
+
if (!model || !region)
|
|
308
|
+
throw new RangeError(`${path} has no change ${index + 1}.`);
|
|
309
|
+
const choice = sides.length ? [...sides] : region.kind === 'conflict' ? 'unresolved' : [];
|
|
310
|
+
await this.setChoices(path, [[index, choice]]);
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
/** Reports every change, then calls `onComplete` (the Complete Merge button). */
|
|
314
|
+
async complete() {
|
|
315
|
+
this.flushCommits();
|
|
316
|
+
await this.busyCommit;
|
|
317
|
+
await this.busy;
|
|
318
|
+
await this.options.onComplete?.({ remaining: this.items.length });
|
|
319
|
+
}
|
|
320
|
+
destroy() {
|
|
321
|
+
this.flushCommits();
|
|
322
|
+
this.destroyed = true;
|
|
323
|
+
this.generation += 1;
|
|
324
|
+
this.renderGeneration += 1;
|
|
325
|
+
this.destroyEditors();
|
|
326
|
+
this.revokeUrls();
|
|
327
|
+
this.root.remove();
|
|
328
|
+
}
|
|
329
|
+
// ------------------------------------------------------------ loading
|
|
330
|
+
documentPath() {
|
|
331
|
+
return this.options.fileName?.split(/[\\/]/).pop() || 'document.md';
|
|
332
|
+
}
|
|
333
|
+
plainEntry(text) {
|
|
334
|
+
const path = this.documentPath();
|
|
335
|
+
this.texts.set(path, text);
|
|
336
|
+
const versions = this.options.versions;
|
|
337
|
+
const side = (source) => source?.markdown !== undefined ? encode(source.markdown) : null;
|
|
338
|
+
const base = versions ? side(versions.base) : null;
|
|
339
|
+
const ours = versions ? side(versions.ours) : null;
|
|
340
|
+
const theirs = versions ? side(versions.theirs) : null;
|
|
341
|
+
const entry = this.makeEntry({
|
|
342
|
+
path, text: true, base, ours, theirs, basePath: base ? path : null, oursPath: ours ? path : null,
|
|
343
|
+
theirsPath: theirs ? path : null, inResult: true
|
|
344
|
+
});
|
|
345
|
+
entry.summary = versions ? describeChange(entry) : '';
|
|
346
|
+
return entry;
|
|
347
|
+
}
|
|
348
|
+
async loadArchive(bytes, versions) {
|
|
349
|
+
const result = await readVersion(bytes);
|
|
350
|
+
this.resultBytes = bytes;
|
|
351
|
+
this.resultFiles = result.files;
|
|
352
|
+
const archive = await MdzArchiveCore.open(bytes);
|
|
353
|
+
this.resultManifest = await archive.readManifest().catch(() => null);
|
|
354
|
+
if (versions) {
|
|
355
|
+
const read = async (source) => (source?.bytes ? readVersion(source.bytes).catch(() => null) : null);
|
|
356
|
+
const [base, ours, theirs] = await Promise.all([read(versions.base), read(versions.ours), read(versions.theirs)]);
|
|
357
|
+
this.versionFiles = { base, ours, theirs };
|
|
358
|
+
}
|
|
359
|
+
const entries = this.versionFiles ? this.classify(this.versionFiles) : this.classifyFromResult();
|
|
360
|
+
for (const entry of entries) {
|
|
361
|
+
if (entry.text && entry.inResult) {
|
|
362
|
+
const bytesNow = this.resultFiles.get(entry.path);
|
|
363
|
+
if (bytesNow)
|
|
364
|
+
this.texts.set(entry.path, decode(bytesNow));
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
return this.sortEntries(entries);
|
|
368
|
+
}
|
|
369
|
+
/** Without the versions: the texts with conflict markers, and the images kept from both sides. */
|
|
370
|
+
classifyFromResult() {
|
|
371
|
+
const entries = [];
|
|
372
|
+
for (const [path, bytes] of this.resultFiles) {
|
|
373
|
+
if (isTextPath(path) && findMergeConflicts(decode(bytes)).length > 0) {
|
|
374
|
+
entries.push(this.makeEntry({ path, text: true, inResult: true }));
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
for (const [copyPath] of this.resultFiles) {
|
|
378
|
+
const original = theirsCopyOriginal(copyPath);
|
|
379
|
+
if (original && this.resultFiles.has(original) && !isTextPath(original)) {
|
|
380
|
+
entries.push(this.makeEntry({ path: original, text: false, inResult: true, copyPath }));
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return entries;
|
|
384
|
+
}
|
|
385
|
+
/** With the versions: every file, how each side changed it, renames, and the merge's own choices. */
|
|
386
|
+
classify(versions) {
|
|
387
|
+
const base = versions.base?.files ?? new Map();
|
|
388
|
+
const ours = versions.ours?.files ?? new Map();
|
|
389
|
+
const theirs = versions.theirs?.files ?? new Map();
|
|
390
|
+
const oursRenames = findRenames(base, ours);
|
|
391
|
+
const theirsRenames = findRenames(base, theirs);
|
|
392
|
+
// Each file under one path: where a side renamed it, under the new name (current first).
|
|
393
|
+
const logical = new Map();
|
|
394
|
+
const renamedFrom = new Set();
|
|
395
|
+
for (const basePath of base.keys()) {
|
|
396
|
+
const oursPath = oursRenames.get(basePath) ?? (ours.has(basePath) ? basePath : null);
|
|
397
|
+
const theirsPath = theirsRenames.get(basePath) ?? (theirs.has(basePath) ? basePath : null);
|
|
398
|
+
const path = oursRenames.get(basePath) ?? theirsRenames.get(basePath) ?? basePath;
|
|
399
|
+
if (path !== basePath)
|
|
400
|
+
renamedFrom.add(basePath);
|
|
401
|
+
logical.set(path, { basePath, oursPath, theirsPath });
|
|
402
|
+
}
|
|
403
|
+
const renameTargets = new Set([...oursRenames.values(), ...theirsRenames.values()]);
|
|
404
|
+
for (const path of ours.keys()) {
|
|
405
|
+
if (logical.has(path) || renameTargets.has(path) || base.has(path))
|
|
406
|
+
continue;
|
|
407
|
+
logical.set(path, { basePath: null, oursPath: path, theirsPath: theirs.has(path) ? path : null });
|
|
408
|
+
}
|
|
409
|
+
for (const path of theirs.keys()) {
|
|
410
|
+
if (logical.has(path) || renameTargets.has(path) || base.has(path) || ours.has(path))
|
|
411
|
+
continue;
|
|
412
|
+
logical.set(path, { basePath: null, oursPath: null, theirsPath: path });
|
|
413
|
+
}
|
|
414
|
+
// Copies `mdz merge` made of theirs beside an image both replaced.
|
|
415
|
+
const copies = new Map();
|
|
416
|
+
for (const path of this.resultFiles.keys()) {
|
|
417
|
+
const original = theirsCopyOriginal(path);
|
|
418
|
+
if (original && !logical.has(path) && this.resultFiles.has(original))
|
|
419
|
+
copies.set(original, path);
|
|
420
|
+
}
|
|
421
|
+
const entries = [];
|
|
422
|
+
for (const [path, where] of logical) {
|
|
423
|
+
if (path === MANIFEST_PATH)
|
|
424
|
+
continue;
|
|
425
|
+
const entry = this.makeEntry({
|
|
426
|
+
path,
|
|
427
|
+
text: isTextPath(path),
|
|
428
|
+
base: where.basePath ? base.get(where.basePath) ?? null : null,
|
|
429
|
+
ours: where.oursPath ? ours.get(where.oursPath) ?? null : null,
|
|
430
|
+
theirs: where.theirsPath ? theirs.get(where.theirsPath) ?? null : null,
|
|
431
|
+
basePath: where.basePath,
|
|
432
|
+
oursPath: where.oursPath,
|
|
433
|
+
theirsPath: where.theirsPath,
|
|
434
|
+
inResult: this.resultFiles.has(path),
|
|
435
|
+
copyPath: copies.get(path)
|
|
436
|
+
});
|
|
437
|
+
if (entry.base && !entry.copyPath) {
|
|
438
|
+
if (!entry.ours && entry.theirs && !bytesEqual(entry.theirs, entry.base) && entry.inResult)
|
|
439
|
+
entry.deleteVsChange = 'ours-deleted';
|
|
440
|
+
if (!entry.theirs && entry.ours && !bytesEqual(entry.ours, entry.base) && entry.inResult)
|
|
441
|
+
entry.deleteVsChange = 'theirs-deleted';
|
|
442
|
+
}
|
|
443
|
+
entry.summary = describeChange(entry);
|
|
444
|
+
entries.push(entry);
|
|
445
|
+
}
|
|
446
|
+
// Anything else in the result (added by hand, or by the merge).
|
|
447
|
+
for (const path of this.resultFiles.keys()) {
|
|
448
|
+
if (path === MANIFEST_PATH || logical.has(path) || [...copies.values()].includes(path) || renamedFrom.has(path))
|
|
449
|
+
continue;
|
|
450
|
+
const entry = this.makeEntry({ path, text: isTextPath(path), inResult: true });
|
|
451
|
+
entry.summary = 'In the result only';
|
|
452
|
+
entries.push(entry);
|
|
453
|
+
}
|
|
454
|
+
const fields = manifestConflicts(versions.base?.manifest ?? null, versions.ours?.manifest ?? null, versions.theirs?.manifest ?? null, parseJson(this.resultFiles.get(MANIFEST_PATH)));
|
|
455
|
+
if (fields.length) {
|
|
456
|
+
const entry = this.makeEntry({ path: MANIFEST_PATH, text: false, inResult: true });
|
|
457
|
+
entry.manifestFields = fields;
|
|
458
|
+
entry.summary = `${fields.length === 1 ? 'A field' : `${fields.length} fields`} changed on both sides`;
|
|
459
|
+
entries.push(entry);
|
|
460
|
+
}
|
|
461
|
+
return entries;
|
|
462
|
+
}
|
|
463
|
+
makeEntry(init) {
|
|
464
|
+
const entry = {
|
|
465
|
+
base: null, ours: null, theirs: null, basePath: null, oursPath: null, theirsPath: null,
|
|
466
|
+
reviewed: false, summary: '',
|
|
467
|
+
...init,
|
|
468
|
+
state: () => {
|
|
469
|
+
if (entry.text && entry.inResult && findMergeConflicts(this.texts.get(entry.path) ?? '').length > 0)
|
|
470
|
+
return 'conflict';
|
|
471
|
+
if (entry.copyPath && this.resultFiles.has(entry.copyPath))
|
|
472
|
+
return 'decision';
|
|
473
|
+
if ((entry.deleteVsChange || entry.manifestFields) && !entry.reviewed)
|
|
474
|
+
return 'review';
|
|
475
|
+
if (this.versionFiles && !entry.manifestFields && bytesEqual(entry.ours, entry.base) && bytesEqual(entry.theirs, entry.base)
|
|
476
|
+
&& entry.basePath === entry.path && entry.inResult === Boolean(entry.base)
|
|
477
|
+
&& (!entry.inResult || bytesEqual(this.currentBytes(entry.path), entry.base))) {
|
|
478
|
+
return 'unchanged';
|
|
479
|
+
}
|
|
480
|
+
return 'merged';
|
|
481
|
+
},
|
|
482
|
+
summaryText: () => entry.summary
|
|
483
|
+
};
|
|
484
|
+
return entry;
|
|
485
|
+
}
|
|
486
|
+
/** Entry point first, then by folder and name. */
|
|
487
|
+
sortEntries(entries) {
|
|
488
|
+
const entryPoint = this.resultManifest?.entryPoint;
|
|
489
|
+
return entries.sort((a, b) => {
|
|
490
|
+
if (a.path === entryPoint)
|
|
491
|
+
return -1;
|
|
492
|
+
if (b.path === entryPoint)
|
|
493
|
+
return 1;
|
|
494
|
+
const da = dirname(a.path);
|
|
495
|
+
const db = dirname(b.path);
|
|
496
|
+
if (da !== db)
|
|
497
|
+
return da.localeCompare(db);
|
|
498
|
+
return a.path.localeCompare(b.path);
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
currentBytes(path) {
|
|
502
|
+
const text = this.texts.get(path);
|
|
503
|
+
if (text !== undefined)
|
|
504
|
+
return encode(text);
|
|
505
|
+
return this.resultFiles.get(path) ?? null;
|
|
506
|
+
}
|
|
507
|
+
// ------------------------------------------------------------ state
|
|
508
|
+
entry(path) {
|
|
509
|
+
return this.entries.find((entry) => entry.path === path);
|
|
510
|
+
}
|
|
511
|
+
visibleEntries() {
|
|
512
|
+
return this.entries
|
|
513
|
+
.filter((entry) => this.showUnchanged || entry.state() !== 'unchanged' || entry.path === this.selectedPath);
|
|
514
|
+
}
|
|
515
|
+
refreshItems() {
|
|
516
|
+
const items = [];
|
|
517
|
+
for (const entry of this.entries) {
|
|
518
|
+
if (entry.text && entry.inResult) {
|
|
519
|
+
for (const conflict of findMergeConflicts(this.texts.get(entry.path) ?? '')) {
|
|
520
|
+
items.push({ kind: 'text', path: entry.path, conflict });
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
if (entry.copyPath && this.resultFiles.has(entry.copyPath)) {
|
|
524
|
+
items.push({ kind: 'binary', path: entry.path, copyPath: entry.copyPath });
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
this.items = items;
|
|
528
|
+
this.cursor = Math.min(this.cursor, Math.max(0, items.length - 1));
|
|
529
|
+
}
|
|
530
|
+
queue(run) {
|
|
531
|
+
const next = this.busy.then(run);
|
|
532
|
+
this.busy = next.catch(() => undefined);
|
|
533
|
+
return next;
|
|
534
|
+
}
|
|
535
|
+
/** The merge regions of a text entry in the result: from the versions when they line up, else from its conflict markers. */
|
|
536
|
+
modelFor(entry) {
|
|
537
|
+
if (!entry.text || !entry.inResult)
|
|
538
|
+
return null;
|
|
539
|
+
const text = normalize(this.texts.get(entry.path) ?? '');
|
|
540
|
+
const cached = this.models.get(entry.path);
|
|
541
|
+
if (cached && cached.text === text)
|
|
542
|
+
return cached;
|
|
543
|
+
let model = null;
|
|
544
|
+
if (this.hasVersions() && entry.ours && entry.theirs) {
|
|
545
|
+
model = MergeModel.fromVersions(text, entry.base ? normalize(decode(entry.base)) : '', normalize(decode(entry.ours)), normalize(decode(entry.theirs)));
|
|
546
|
+
}
|
|
547
|
+
model ??= MergeModel.fromMarkers(text);
|
|
548
|
+
this.models.set(entry.path, model);
|
|
549
|
+
return model;
|
|
550
|
+
}
|
|
551
|
+
hasVersions() {
|
|
552
|
+
return Boolean(this.versionFiles || (this.plain && this.options.versions));
|
|
553
|
+
}
|
|
554
|
+
/** Sets regions of a text entry to choices: through its editor when it's open (so undo works), else directly. */
|
|
555
|
+
async setChoices(path, choices) {
|
|
556
|
+
const entry = this.entry(path);
|
|
557
|
+
const model = entry ? this.modelFor(entry) : null;
|
|
558
|
+
if (!entry || !model)
|
|
559
|
+
throw new Error(`${path} has no merge to resolve.`);
|
|
560
|
+
const changes = choices
|
|
561
|
+
.map(([index, choice]) => model.change(index, choice))
|
|
562
|
+
.filter((change) => model.text.slice(change.from, change.to) !== change.insert)
|
|
563
|
+
.sort((a, b) => b.from - a.from);
|
|
564
|
+
if (!changes.length)
|
|
565
|
+
return;
|
|
566
|
+
const editor = this.resultEditor && this.selectedPath === path ? this.resultEditor : null;
|
|
567
|
+
if (editor) {
|
|
568
|
+
editor.dispatch({ changes, userEvent: 'input.merge' });
|
|
569
|
+
this.flushCommits();
|
|
570
|
+
await this.busyCommit;
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
// Last first, so the earlier changes' positions still hold.
|
|
574
|
+
for (const change of changes)
|
|
575
|
+
model.apply(change);
|
|
576
|
+
const raw = this.texts.get(path) ?? '';
|
|
577
|
+
this.texts.set(path, raw.includes('\r\n') ? model.text.replace(/\n/g, '\r\n') : model.text);
|
|
578
|
+
await this.commitText(path);
|
|
579
|
+
if (this.selectedPath === path)
|
|
580
|
+
await this.renderEntry();
|
|
581
|
+
}
|
|
582
|
+
async resolveTextConflict(path, index, resolution) {
|
|
583
|
+
const entry = this.entry(path);
|
|
584
|
+
const model = entry ? this.modelFor(entry) : null;
|
|
585
|
+
const editor = this.resultEditor && this.selectedPath === path ? this.resultEditor : null;
|
|
586
|
+
const conflict = findMergeConflicts(editor ? editor.state.doc.toString() : normalize(this.texts.get(path) ?? ''))[index];
|
|
587
|
+
if (!conflict)
|
|
588
|
+
throw new RangeError(`There is no conflict ${index + 1} in ${path}.`);
|
|
589
|
+
const regionIndex = model ? model.regionAt(conflict.start) : -1;
|
|
590
|
+
const choice = resolutionChoice(resolution);
|
|
591
|
+
if (model && regionIndex >= 0 && choice && model.regions[regionIndex].from === conflict.start) {
|
|
592
|
+
await this.setChoices(path, [[regionIndex, choice]]);
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
if (editor) {
|
|
596
|
+
editor.dispatch({ changes: { from: conflict.start, to: conflict.end, insert: mergeConflictReplacement(conflict, resolution) } });
|
|
597
|
+
this.flushCommits();
|
|
598
|
+
await this.busyCommit;
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
const raw = this.texts.get(path) ?? '';
|
|
602
|
+
const text = normalize(raw);
|
|
603
|
+
const resolved = text.slice(0, conflict.start) + mergeConflictReplacement(conflict, resolution) + text.slice(conflict.end);
|
|
604
|
+
this.texts.set(path, raw.includes('\r\n') ? resolved.replace(/\n/g, '\r\n') : resolved);
|
|
605
|
+
await this.commitText(path);
|
|
606
|
+
if (this.selectedPath === path)
|
|
607
|
+
await this.renderEntry();
|
|
608
|
+
}
|
|
609
|
+
async resolveBinary(item, resolution) {
|
|
610
|
+
if (!this.resultBytes)
|
|
611
|
+
throw new Error('Only an archive has image conflicts.');
|
|
612
|
+
this.flushCommits();
|
|
613
|
+
let bytes = this.resultBytes;
|
|
614
|
+
if (resolution === 'theirs') {
|
|
615
|
+
const theirs = this.resultFiles.get(item.copyPath);
|
|
616
|
+
if (!theirs)
|
|
617
|
+
throw new Error(`${item.copyPath} is missing.`);
|
|
618
|
+
bytes = await updateBinaryInArchive(bytes, item.path, theirs);
|
|
619
|
+
this.resultFiles.set(item.path, theirs);
|
|
620
|
+
}
|
|
621
|
+
else if (resolution !== 'ours') {
|
|
622
|
+
throw new Error('Keep current ("ours") or take incoming ("theirs") for an image.');
|
|
623
|
+
}
|
|
624
|
+
this.resultBytes = await removeFilesFromArchive(bytes, [item.copyPath]);
|
|
625
|
+
this.resultFiles.delete(item.copyPath);
|
|
626
|
+
await this.afterChange({ path: item.path });
|
|
627
|
+
}
|
|
628
|
+
/** A text entry changed in the editor: refresh markers now, write the archive shortly. */
|
|
629
|
+
textEdited(path, text) {
|
|
630
|
+
this.texts.set(path, text);
|
|
631
|
+
this.refreshItems();
|
|
632
|
+
this.updateToolbar();
|
|
633
|
+
this.renderNav();
|
|
634
|
+
this.updateConflictBar();
|
|
635
|
+
if (path === this.selectedPath)
|
|
636
|
+
this.refreshMergeUi();
|
|
637
|
+
this.pendingCommits.add(path);
|
|
638
|
+
if (this.commitTimer)
|
|
639
|
+
clearTimeout(this.commitTimer);
|
|
640
|
+
this.commitTimer = setTimeout(() => this.flushCommits(), COMMIT_DELAY_MS);
|
|
641
|
+
}
|
|
642
|
+
/** Writes edited texts into the archive and reports them now. */
|
|
643
|
+
flushCommits() {
|
|
644
|
+
if (this.commitTimer)
|
|
645
|
+
clearTimeout(this.commitTimer);
|
|
646
|
+
this.commitTimer = undefined;
|
|
647
|
+
if (!this.pendingCommits.size)
|
|
648
|
+
return;
|
|
649
|
+
const paths = [...this.pendingCommits];
|
|
650
|
+
this.pendingCommits.clear();
|
|
651
|
+
this.busyCommit = this.busyCommit.then(async () => {
|
|
652
|
+
for (const path of paths)
|
|
653
|
+
await this.commitText(path);
|
|
654
|
+
}).catch((cause) => this.fail(cause));
|
|
655
|
+
}
|
|
656
|
+
async commitText(path) {
|
|
657
|
+
const text = this.texts.get(path);
|
|
658
|
+
if (text === undefined)
|
|
659
|
+
return;
|
|
660
|
+
if (this.resultBytes) {
|
|
661
|
+
const bytes = encode(text);
|
|
662
|
+
this.resultBytes = await updateBinaryInArchive(this.resultBytes, path, bytes);
|
|
663
|
+
this.resultFiles.set(path, bytes);
|
|
664
|
+
}
|
|
665
|
+
await this.afterChange({ path, text }, false);
|
|
666
|
+
}
|
|
667
|
+
/** Refreshes the tree and counts, and reports the change. */
|
|
668
|
+
async afterChange(change, rerender = true) {
|
|
669
|
+
if (this.destroyed)
|
|
670
|
+
return;
|
|
671
|
+
this.refreshItems();
|
|
672
|
+
this.updateToolbar();
|
|
673
|
+
this.renderNav();
|
|
674
|
+
if (rerender && change.path === this.selectedPath)
|
|
675
|
+
await this.renderEntry();
|
|
676
|
+
else
|
|
677
|
+
this.updateConflictBar();
|
|
678
|
+
const remaining = this.items.length;
|
|
679
|
+
this.options.onChange?.({
|
|
680
|
+
path: change.path,
|
|
681
|
+
text: change.text ?? this.texts.get(change.path),
|
|
682
|
+
bytes: this.resultBytes ?? undefined,
|
|
683
|
+
remaining
|
|
684
|
+
});
|
|
685
|
+
if (remaining === 0 && this.lastRemaining !== 0)
|
|
686
|
+
this.options.onResolved?.();
|
|
687
|
+
this.lastRemaining = remaining;
|
|
688
|
+
}
|
|
689
|
+
fail(cause) {
|
|
690
|
+
const error = cause instanceof Error ? cause : new Error(String(cause));
|
|
691
|
+
this.options.onFailed?.(error);
|
|
692
|
+
}
|
|
693
|
+
async goTo(index) {
|
|
694
|
+
this.flushCommits();
|
|
695
|
+
const item = this.items[index];
|
|
696
|
+
if (!item)
|
|
697
|
+
return;
|
|
698
|
+
this.cursor = index;
|
|
699
|
+
const within = item.kind === 'text'
|
|
700
|
+
? this.items.filter((candidate) => candidate.path === item.path && candidate.kind === 'text').indexOf(item)
|
|
701
|
+
: 0;
|
|
702
|
+
if (this.selectedPath !== item.path) {
|
|
703
|
+
this.selectedPath = item.path;
|
|
704
|
+
this.currentInEntry = within;
|
|
705
|
+
this.renderNav();
|
|
706
|
+
await this.renderEntry();
|
|
707
|
+
}
|
|
708
|
+
else {
|
|
709
|
+
this.setCurrentInEntry(within, true);
|
|
710
|
+
}
|
|
711
|
+
this.updateToolbar();
|
|
712
|
+
}
|
|
713
|
+
// ------------------------------------------------------------ toolbar and tree
|
|
714
|
+
applyRootClass() {
|
|
715
|
+
this.root.className = `mdzip-diff-root mdzip-merge-root mdzip-diff-density-${this.density} mdzip-diff-scheme-${this.colorScheme}`;
|
|
716
|
+
}
|
|
717
|
+
updateToolbar() {
|
|
718
|
+
const count = this.items.length;
|
|
719
|
+
this.countLabel.textContent = count === 0
|
|
720
|
+
? 'No conflicts'
|
|
721
|
+
: `${Math.min(this.cursor, count - 1) + 1} of ${count} conflict${count === 1 ? '' : 's'}`;
|
|
722
|
+
this.prevButton.disabled = this.cursor <= 0 || count === 0;
|
|
723
|
+
this.nextButton.disabled = this.cursor >= count - 1;
|
|
724
|
+
this.sourceButton.classList.toggle('active', !this.rendered);
|
|
725
|
+
this.sourceButton.setAttribute('aria-pressed', String(!this.rendered));
|
|
726
|
+
this.renderedButton.classList.toggle('active', this.rendered);
|
|
727
|
+
this.renderedButton.setAttribute('aria-pressed', String(this.rendered));
|
|
728
|
+
this.completeButton.hidden = !this.options.onComplete;
|
|
729
|
+
this.completeButton.classList.toggle('ready', count === 0);
|
|
730
|
+
this.completeButton.title = count === 0
|
|
731
|
+
? 'Save the result and mark the conflict resolved'
|
|
732
|
+
: `${count} still to resolve`;
|
|
733
|
+
}
|
|
734
|
+
renderNav() {
|
|
735
|
+
const doc = this.root.ownerDocument;
|
|
736
|
+
this.nav.hidden = this.plain;
|
|
737
|
+
this.root.classList.toggle('mdzip-merge-single', this.plain);
|
|
738
|
+
if (this.plain)
|
|
739
|
+
return;
|
|
740
|
+
const states = this.entries.map((entry) => entry.state());
|
|
741
|
+
const count = (state) => states.filter((candidate) => candidate === state).length;
|
|
742
|
+
const unchanged = count('unchanged');
|
|
743
|
+
const parts = [
|
|
744
|
+
count('conflict') ? `${count('conflict')} with conflicts` : '',
|
|
745
|
+
count('decision') ? `${count('decision')} to decide` : '',
|
|
746
|
+
count('review') ? `${count('review')} to review` : '',
|
|
747
|
+
count('merged') ? `${count('merged')} merged` : ''
|
|
748
|
+
].filter(Boolean);
|
|
749
|
+
this.navSummary.innerHTML = `
|
|
750
|
+
<div class="mdzip-diff-labels">${escapeHtml(this.documentPath())}</div>
|
|
751
|
+
<div class="mdzip-diff-counts">${escapeHtml(parts.join(' · ') || 'Nothing to resolve')}</div>
|
|
752
|
+
${unchanged ? `<label class="mdzip-diff-filter"><input type="checkbox" data-ref="show-unchanged"${this.showUnchanged ? ' checked' : ''}> Show ${unchanged} unchanged</label>` : ''}`;
|
|
753
|
+
this.navSummary.querySelector('[data-ref="show-unchanged"]')?.addEventListener('change', (event) => {
|
|
754
|
+
this.showUnchanged = event.target.checked;
|
|
755
|
+
this.renderNav();
|
|
756
|
+
});
|
|
757
|
+
const rows = [];
|
|
758
|
+
let lastDir = null;
|
|
759
|
+
for (const entry of this.visibleEntries()) {
|
|
760
|
+
const dir = dirname(entry.path);
|
|
761
|
+
if (dir !== lastDir) {
|
|
762
|
+
if (dir) {
|
|
763
|
+
const segments = dir.split('/');
|
|
764
|
+
const heading = doc.createElement('div');
|
|
765
|
+
heading.className = 'mdzip-diff-directory';
|
|
766
|
+
heading.style.setProperty('--mdzip-diff-depth', String(segments.length - 1));
|
|
767
|
+
heading.textContent = segments[segments.length - 1];
|
|
768
|
+
rows.push(heading);
|
|
769
|
+
}
|
|
770
|
+
lastDir = dir;
|
|
771
|
+
}
|
|
772
|
+
const state = entry.state();
|
|
773
|
+
const conflicts = entry.text && entry.inResult ? findMergeConflicts(this.texts.get(entry.path) ?? '').length : 0;
|
|
774
|
+
const row = doc.createElement('button');
|
|
775
|
+
row.type = 'button';
|
|
776
|
+
row.className = `mdzip-diff-entry mdzip-merge-entry mdzip-merge-state-${state}${entry.path === this.selectedPath ? ' active' : ''}${entry.inResult ? '' : ' mdzip-merge-gone'}`;
|
|
777
|
+
row.setAttribute('role', 'option');
|
|
778
|
+
row.setAttribute('aria-selected', String(entry.path === this.selectedPath));
|
|
779
|
+
row.dataset.path = entry.path;
|
|
780
|
+
row.style.setProperty('--mdzip-diff-depth', String(dir ? dir.split('/').length : 0));
|
|
781
|
+
row.title = entry.summaryText() || entry.path;
|
|
782
|
+
const name = entry.path.slice(entry.path.lastIndexOf('/') + 1);
|
|
783
|
+
row.innerHTML = `<span class="mdzip-merge-marker" aria-hidden="true">${MARKERS[state]}</span>`
|
|
784
|
+
+ `<span class="mdzip-diff-path">${escapeHtml(name)}${conflicts ? ` <span class="mdzip-merge-entry-count">${conflicts}</span>` : ''}</span>`;
|
|
785
|
+
row.setAttribute('aria-label', `${entry.path}: ${stateLabel(state)}${conflicts ? `, ${conflicts} conflict${conflicts === 1 ? '' : 's'}` : ''}`);
|
|
786
|
+
row.addEventListener('click', () => { void this.selectFile(entry.path); });
|
|
787
|
+
rows.push(row);
|
|
788
|
+
}
|
|
789
|
+
this.navList.replaceChildren(...rows);
|
|
790
|
+
}
|
|
791
|
+
// ------------------------------------------------------------ the selected file
|
|
792
|
+
destroyEditors() {
|
|
793
|
+
this.resultEditor?.destroy();
|
|
794
|
+
this.resultEditor = null;
|
|
795
|
+
for (const editor of Object.values(this.sideEditors))
|
|
796
|
+
editor?.destroy();
|
|
797
|
+
this.sideEditors = {};
|
|
798
|
+
this.takeAllBoxes = {};
|
|
799
|
+
this.resultStatus = null;
|
|
800
|
+
this.stopScrollSync?.();
|
|
801
|
+
}
|
|
802
|
+
async renderEntry() {
|
|
803
|
+
const generation = ++this.renderGeneration;
|
|
804
|
+
this.destroyEditors();
|
|
805
|
+
this.revokeUrls();
|
|
806
|
+
this.updateToolbar();
|
|
807
|
+
const doc = this.root.ownerDocument;
|
|
808
|
+
const entry = this.entry(this.selectedPath);
|
|
809
|
+
if (!entry) {
|
|
810
|
+
this.content.innerHTML = `<div class="mdzip-diff-message">${this.entries.length ? 'Choose a file.' : 'Nothing to resolve.'}</div>`;
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
injectPreviewStyles(doc);
|
|
814
|
+
const panel = doc.createElement('div');
|
|
815
|
+
panel.className = 'mdzip-merge-panel';
|
|
816
|
+
panel.append(this.renderHeader(entry));
|
|
817
|
+
// In the page before any editor is made, so CodeMirror can measure.
|
|
818
|
+
this.content.replaceChildren(panel);
|
|
819
|
+
if (entry.manifestFields) {
|
|
820
|
+
panel.append(this.renderManifestFields(entry));
|
|
821
|
+
}
|
|
822
|
+
else if (!entry.inResult) {
|
|
823
|
+
panel.append(this.message(entry.summaryText() || 'Not in the result.'));
|
|
824
|
+
if (entry.text || isImagePath(entry.path))
|
|
825
|
+
await this.renderSides(entry, false, panel, generation);
|
|
826
|
+
}
|
|
827
|
+
else if (entry.copyPath && this.resultFiles.has(entry.copyPath)) {
|
|
828
|
+
panel.append(this.renderImageDecision(entry));
|
|
829
|
+
}
|
|
830
|
+
else if (entry.text || isImagePath(entry.path)) {
|
|
831
|
+
await this.renderSides(entry, true, panel, generation);
|
|
832
|
+
}
|
|
833
|
+
else {
|
|
834
|
+
panel.append(this.message('A binary file: nothing to show.'));
|
|
835
|
+
}
|
|
836
|
+
if (generation !== this.renderGeneration)
|
|
837
|
+
return;
|
|
838
|
+
this.updateConflictBar();
|
|
839
|
+
this.setCurrentInEntry(this.currentInEntry, true);
|
|
840
|
+
}
|
|
841
|
+
renderHeader(entry) {
|
|
842
|
+
const doc = this.root.ownerDocument;
|
|
843
|
+
const header = doc.createElement('div');
|
|
844
|
+
header.className = 'mdzip-merge-header';
|
|
845
|
+
const state = entry.state();
|
|
846
|
+
header.innerHTML = `<div class="mdzip-merge-title"><span class="mdzip-merge-marker mdzip-merge-state-${state}" aria-hidden="true">${MARKERS[state]}</span> ${escapeHtml(entry.path)}</div>`
|
|
847
|
+
+ (entry.summaryText() ? `<div class="mdzip-merge-summary">${escapeHtml(entry.summaryText())}</div>` : '');
|
|
848
|
+
if (entry.deleteVsChange && entry.inResult) {
|
|
849
|
+
const [deleter, changer] = entry.deleteVsChange === 'ours-deleted' ? ['Current', 'incoming'] : ['Incoming', 'current'];
|
|
850
|
+
const note = doc.createElement('div');
|
|
851
|
+
note.className = 'mdzip-merge-review';
|
|
852
|
+
note.innerHTML = `<span>${deleter} deleted this file and ${changer} changed it. The merge kept the changed version.</span>`;
|
|
853
|
+
note.append(this.actionButton(entry.reviewed ? 'Kept' : 'Keep it', () => this.resolveFile(entry.path, 'keep'), entry.reviewed), this.actionButton('Delete it', () => this.resolveFile(entry.path, 'delete')));
|
|
854
|
+
header.append(note);
|
|
855
|
+
}
|
|
856
|
+
return header;
|
|
857
|
+
}
|
|
858
|
+
message(text) {
|
|
859
|
+
const element = this.root.ownerDocument.createElement('div');
|
|
860
|
+
element.className = 'mdzip-diff-message';
|
|
861
|
+
element.textContent = text;
|
|
862
|
+
return element;
|
|
863
|
+
}
|
|
864
|
+
/** Incoming and current on top (as VS Code and Visual Studio place them); the result below. */
|
|
865
|
+
async renderSides(entry, withResult, parent, generation) {
|
|
866
|
+
const doc = this.root.ownerDocument;
|
|
867
|
+
const layout = doc.createElement('div');
|
|
868
|
+
layout.className = 'mdzip-merge-layout';
|
|
869
|
+
const top = doc.createElement('div');
|
|
870
|
+
top.className = 'mdzip-merge-top';
|
|
871
|
+
layout.append(top);
|
|
872
|
+
parent.append(layout);
|
|
873
|
+
const model = this.modelFor(entry);
|
|
874
|
+
const sides = model ? model.sides : this.sideTexts(entry);
|
|
875
|
+
for (const side of ['theirs', 'ours']) {
|
|
876
|
+
const pane = this.paneShell(sideTitle(side), side === 'ours' ? this.options.oursLabel : this.options.theirsLabel, `mdzip-merge-pane-${side}`);
|
|
877
|
+
if (model?.regions.some((region) => region.kind !== 'same' && (region.kind === side || region.kind === 'conflict'))) {
|
|
878
|
+
pane.heading.append(this.takeAllBox(entry.path, side));
|
|
879
|
+
}
|
|
880
|
+
top.append(pane.pane);
|
|
881
|
+
await this.fillSide(pane.body, entry, side, sides);
|
|
882
|
+
if (generation !== this.renderGeneration)
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
if (withResult) {
|
|
886
|
+
if (this.rendered) {
|
|
887
|
+
const bar = doc.createElement('div');
|
|
888
|
+
bar.className = 'mdzip-merge-bar';
|
|
889
|
+
bar.dataset.ref = 'conflict-bar';
|
|
890
|
+
layout.append(bar);
|
|
891
|
+
}
|
|
892
|
+
const result = this.paneShell('Result', entry.text && !this.rendered ? 'edit here' : '', 'mdzip-merge-pane-result');
|
|
893
|
+
if (model) {
|
|
894
|
+
this.resultStatus = doc.createElement('span');
|
|
895
|
+
this.resultStatus.className = 'mdzip-merge-remaining';
|
|
896
|
+
this.resultStatus.setAttribute('aria-live', 'polite');
|
|
897
|
+
result.heading.append(this.resultStatus);
|
|
898
|
+
}
|
|
899
|
+
layout.append(result.pane);
|
|
900
|
+
await this.fillResult(result.body, entry);
|
|
901
|
+
}
|
|
902
|
+
if (generation !== this.renderGeneration)
|
|
903
|
+
return;
|
|
904
|
+
layout.classList.toggle('mdzip-merge-aligned', Boolean(model));
|
|
905
|
+
this.refreshMergeUi();
|
|
906
|
+
this.syncScrolling(layout, Boolean(model) && Boolean(this.resultEditor));
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
909
|
+
* Scrolls the panes together, as the Visual Studio and VS Code merge
|
|
910
|
+
* editors do. Lined up (source view), the same scroll position shows the
|
|
911
|
+
* same lines in each; otherwise each pane scrolls to the same proportion.
|
|
912
|
+
*/
|
|
913
|
+
syncScrolling(layout, aligned) {
|
|
914
|
+
this.stopScrollSync?.();
|
|
915
|
+
const scrollers = [this.sideEditors.theirs, this.sideEditors.ours, this.resultEditor]
|
|
916
|
+
.map((editor) => editor?.scrollDOM)
|
|
917
|
+
.filter((element) => Boolean(element));
|
|
918
|
+
// Rendered: the pane bodies scroll.
|
|
919
|
+
if (!scrollers.length) {
|
|
920
|
+
scrollers.push(...Array.from(layout.querySelectorAll('.mdzip-merge-pane-body')));
|
|
921
|
+
}
|
|
922
|
+
if (scrollers.length < 2)
|
|
923
|
+
return;
|
|
924
|
+
// Rendered panes: the same heading (level and text) in two panes is an anchor.
|
|
925
|
+
const headings = new Map();
|
|
926
|
+
const matches = new Map();
|
|
927
|
+
const headingsIn = (scroller) => {
|
|
928
|
+
let list = headings.get(scroller);
|
|
929
|
+
if (!list) {
|
|
930
|
+
list = Array.from(scroller.querySelectorAll('h1, h2, h3, h4, h5, h6'));
|
|
931
|
+
headings.set(scroller, list);
|
|
932
|
+
}
|
|
933
|
+
return list;
|
|
934
|
+
};
|
|
935
|
+
const offsetIn = (scroller, element) => element.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop;
|
|
936
|
+
const headingAnchors = (source, target) => {
|
|
937
|
+
const from = headingsIn(source);
|
|
938
|
+
const to = headingsIn(target);
|
|
939
|
+
const key = `${scrollers.indexOf(source)}:${scrollers.indexOf(target)}`;
|
|
940
|
+
let pairs = matches.get(key);
|
|
941
|
+
if (!pairs) {
|
|
942
|
+
const label = (heading) => `${heading.tagName}:${(heading.textContent ?? '').trim()}`;
|
|
943
|
+
pairs = matchSequences(from.map(label), to.map(label));
|
|
944
|
+
matches.set(key, pairs);
|
|
945
|
+
}
|
|
946
|
+
return pairs.map(([i, j]) => [offsetIn(source, from[i]), offsetIn(target, to[j])]);
|
|
947
|
+
};
|
|
948
|
+
const expected = new Map();
|
|
949
|
+
const listeners = scrollers.map((source) => {
|
|
950
|
+
const listener = () => {
|
|
951
|
+
const wanted = expected.get(source);
|
|
952
|
+
if (wanted !== undefined) {
|
|
953
|
+
expected.delete(source);
|
|
954
|
+
// A scroll this sync set off, not the user.
|
|
955
|
+
if (Math.abs(source.scrollTop - wanted) < 2)
|
|
956
|
+
return;
|
|
957
|
+
}
|
|
958
|
+
for (const target of scrollers) {
|
|
959
|
+
if (target === source)
|
|
960
|
+
continue;
|
|
961
|
+
const max = target.scrollHeight - target.clientHeight;
|
|
962
|
+
const top = aligned ? source.scrollTop : mapScrollPosition(source.scrollTop, headingAnchors(source, target), source, target);
|
|
963
|
+
const clamped = Math.max(0, Math.min(top, max));
|
|
964
|
+
if (Math.abs(target.scrollTop - clamped) < 1)
|
|
965
|
+
continue;
|
|
966
|
+
expected.set(target, clamped);
|
|
967
|
+
target.scrollTop = clamped;
|
|
968
|
+
}
|
|
969
|
+
};
|
|
970
|
+
source.addEventListener('scroll', listener, { passive: true });
|
|
971
|
+
return () => source.removeEventListener('scroll', listener);
|
|
972
|
+
});
|
|
973
|
+
this.stopScrollSync = () => {
|
|
974
|
+
for (const stop of listeners)
|
|
975
|
+
stop();
|
|
976
|
+
this.stopScrollSync = null;
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
/** "Take All Incoming" / "Take All Current": every change on that side, every conflict that side's way. */
|
|
980
|
+
takeAllBox(path, side) {
|
|
981
|
+
const doc = this.root.ownerDocument;
|
|
982
|
+
const label = doc.createElement('label');
|
|
983
|
+
label.className = 'mdzip-merge-take-all';
|
|
984
|
+
const box = doc.createElement('input');
|
|
985
|
+
box.type = 'checkbox';
|
|
986
|
+
box.addEventListener('change', () => {
|
|
987
|
+
const take = box.checked;
|
|
988
|
+
void this.queue(async () => {
|
|
989
|
+
const entry = this.entry(path);
|
|
990
|
+
const model = entry ? this.modelFor(entry) : null;
|
|
991
|
+
if (!model)
|
|
992
|
+
return;
|
|
993
|
+
const choices = [];
|
|
994
|
+
model.regions.forEach((region, index) => {
|
|
995
|
+
if (!regionOnSide(region, side))
|
|
996
|
+
return;
|
|
997
|
+
const has = sideChecked(region, side);
|
|
998
|
+
if (take && !has)
|
|
999
|
+
choices.push([index, region.kind === 'same' ? ['ours', 'theirs'] : [side]]);
|
|
1000
|
+
if (!take && has)
|
|
1001
|
+
choices.push([index, model.toggled(index, side)]);
|
|
1002
|
+
});
|
|
1003
|
+
await this.setChoices(path, choices);
|
|
1004
|
+
}).catch((cause) => this.fail(cause));
|
|
1005
|
+
});
|
|
1006
|
+
this.takeAllBoxes[side] = box;
|
|
1007
|
+
label.append(box, ` Take All ${sideTitle(side)}`);
|
|
1008
|
+
return label;
|
|
1009
|
+
}
|
|
1010
|
+
/** Brings the checkboxes, Take All boxes and remaining count of the shown file up to date. */
|
|
1011
|
+
refreshMergeUi() {
|
|
1012
|
+
const entry = this.entry(this.selectedPath);
|
|
1013
|
+
const model = entry ? this.models.get(entry.path) : undefined;
|
|
1014
|
+
if (!entry || !model)
|
|
1015
|
+
return;
|
|
1016
|
+
if (this.resultStatus) {
|
|
1017
|
+
const remaining = model.remaining;
|
|
1018
|
+
this.resultStatus.textContent = remaining === 0 ? 'No conflicts remaining' : `${remaining} conflict${remaining === 1 ? '' : 's'} remaining`;
|
|
1019
|
+
this.resultStatus.classList.toggle('done', remaining === 0);
|
|
1020
|
+
}
|
|
1021
|
+
const aligned = this.sideEditors.ours || this.sideEditors.theirs
|
|
1022
|
+
? alignment(model, this.resultEditor?.state.doc ?? Text.of(model.text.split('\n')))
|
|
1023
|
+
: null;
|
|
1024
|
+
for (const side of ['ours', 'theirs']) {
|
|
1025
|
+
const regions = model.regions.filter((region) => regionOnSide(region, side));
|
|
1026
|
+
const box = this.takeAllBoxes[side];
|
|
1027
|
+
if (box) {
|
|
1028
|
+
const checked = regions.filter((region) => sideChecked(region, side)).length;
|
|
1029
|
+
box.checked = regions.length > 0 && checked === regions.length;
|
|
1030
|
+
box.indeterminate = checked > 0 && checked < regions.length;
|
|
1031
|
+
}
|
|
1032
|
+
const editor = this.sideEditors[side];
|
|
1033
|
+
if (!editor)
|
|
1034
|
+
continue;
|
|
1035
|
+
const marks = [];
|
|
1036
|
+
model.regions.forEach((region, index) => {
|
|
1037
|
+
if (!regionOnSide(region, side))
|
|
1038
|
+
return;
|
|
1039
|
+
const [start, end] = side === 'ours' ? region.oursLines : region.theirsLines;
|
|
1040
|
+
marks.push({
|
|
1041
|
+
index, start, end,
|
|
1042
|
+
checked: sideChecked(region, side),
|
|
1043
|
+
conflict: region.kind === 'conflict',
|
|
1044
|
+
manual: region.choice === 'manual' || region.choice === 'base',
|
|
1045
|
+
current: index === this.currentRegion
|
|
1046
|
+
});
|
|
1047
|
+
});
|
|
1048
|
+
editor.dispatch({ effects: [setSideMarks.of(marks), setSideSpacers.of(aligned?.[side] ?? [])] });
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
/** A checkbox beside a change was clicked. */
|
|
1052
|
+
toggleRegion(side, index) {
|
|
1053
|
+
const path = this.selectedPath ?? '';
|
|
1054
|
+
void this.queue(async () => {
|
|
1055
|
+
const entry = this.entry(path);
|
|
1056
|
+
const model = entry ? this.modelFor(entry) : null;
|
|
1057
|
+
if (!model?.regions[index])
|
|
1058
|
+
return;
|
|
1059
|
+
await this.setChoices(path, [[index, model.toggled(index, side)]]);
|
|
1060
|
+
}).catch((cause) => this.fail(cause));
|
|
1061
|
+
}
|
|
1062
|
+
paneShell(title, label, className) {
|
|
1063
|
+
const doc = this.root.ownerDocument;
|
|
1064
|
+
const pane = doc.createElement('div');
|
|
1065
|
+
pane.className = `mdzip-merge-pane ${className}`;
|
|
1066
|
+
const heading = doc.createElement('div');
|
|
1067
|
+
heading.className = 'mdzip-merge-pane-heading';
|
|
1068
|
+
const names = doc.createElement('div');
|
|
1069
|
+
names.className = 'mdzip-merge-pane-names';
|
|
1070
|
+
const name = doc.createElement('span');
|
|
1071
|
+
name.className = 'mdzip-merge-pane-title';
|
|
1072
|
+
name.textContent = title;
|
|
1073
|
+
names.append(name);
|
|
1074
|
+
if (label) {
|
|
1075
|
+
const small = doc.createElement('span');
|
|
1076
|
+
small.className = 'mdzip-merge-pane-label';
|
|
1077
|
+
small.textContent = label;
|
|
1078
|
+
names.append(small);
|
|
1079
|
+
}
|
|
1080
|
+
heading.append(names);
|
|
1081
|
+
const body = doc.createElement('div');
|
|
1082
|
+
body.className = 'mdzip-merge-pane-body';
|
|
1083
|
+
pane.append(heading, body);
|
|
1084
|
+
return { pane, heading, body };
|
|
1085
|
+
}
|
|
1086
|
+
/** Each side's full text: from the versions, or from the result's conflict markers. */
|
|
1087
|
+
sideTexts(entry) {
|
|
1088
|
+
if (!entry.text)
|
|
1089
|
+
return { base: null, ours: null, theirs: null };
|
|
1090
|
+
if (this.versionFiles || (this.plain && this.options.versions)) {
|
|
1091
|
+
return {
|
|
1092
|
+
base: entry.base ? normalize(decode(entry.base)) : null,
|
|
1093
|
+
ours: entry.ours ? normalize(decode(entry.ours)) : null,
|
|
1094
|
+
theirs: entry.theirs ? normalize(decode(entry.theirs)) : null
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
const text = normalize(this.texts.get(entry.path) ?? '');
|
|
1098
|
+
const all = (resolution) => replaceAllConflicts(text, resolution);
|
|
1099
|
+
const hasBase = findMergeConflicts(text).every((conflict) => conflict.base !== null);
|
|
1100
|
+
return { base: hasBase ? all('base') : null, ours: all('ours'), theirs: all('theirs') };
|
|
1101
|
+
}
|
|
1102
|
+
async fillSide(body, entry, side, texts) {
|
|
1103
|
+
const doc = this.root.ownerDocument;
|
|
1104
|
+
const bytes = this.versionFiles || (this.plain && this.options.versions) ? entry[side] : this.resultFiles.get(side === 'ours' ? entry.path : entry.copyPath ?? entry.path) ?? null;
|
|
1105
|
+
if (!entry.text) {
|
|
1106
|
+
if (!bytes) {
|
|
1107
|
+
body.append(this.placeholder(`Not in ${sideName(side)}`));
|
|
1108
|
+
return;
|
|
1109
|
+
}
|
|
1110
|
+
body.append(this.imageElement(bytes, entry.path));
|
|
1111
|
+
return;
|
|
1112
|
+
}
|
|
1113
|
+
const text = texts[side];
|
|
1114
|
+
if (text === null) {
|
|
1115
|
+
body.append(this.placeholder(`Deleted in ${sideName(side)}, or never added`));
|
|
1116
|
+
return;
|
|
1117
|
+
}
|
|
1118
|
+
if (this.rendered && isMarkdownPath(entry.path)) {
|
|
1119
|
+
const article = await this.renderMarkdown(text, entry.path, side);
|
|
1120
|
+
if (texts.base !== null && article) {
|
|
1121
|
+
const baseArticle = await this.renderMarkdown(texts.base, entry.path, 'base');
|
|
1122
|
+
if (baseArticle)
|
|
1123
|
+
markBlockChanges(baseArticle, article);
|
|
1124
|
+
}
|
|
1125
|
+
if (article) {
|
|
1126
|
+
body.append(this.previewScope(article));
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
const view = new EditorView({
|
|
1131
|
+
parent: body,
|
|
1132
|
+
root: doc,
|
|
1133
|
+
state: EditorState.create({
|
|
1134
|
+
doc: text,
|
|
1135
|
+
extensions: [
|
|
1136
|
+
...this.editorBase(entry.path, !this.models.has(entry.path)),
|
|
1137
|
+
EditorState.readOnly.of(true),
|
|
1138
|
+
EditorView.editable.of(false),
|
|
1139
|
+
this.models.has(entry.path)
|
|
1140
|
+
? sideRegions(side, (index) => this.toggleRegion(side, index))
|
|
1141
|
+
: changedLines(texts.base, text, `mdzip-merge-line-${side}`)
|
|
1142
|
+
]
|
|
1143
|
+
})
|
|
1144
|
+
});
|
|
1145
|
+
this.sideEditors[side] = view;
|
|
1146
|
+
}
|
|
1147
|
+
async fillResult(body, entry) {
|
|
1148
|
+
if (!entry.text) {
|
|
1149
|
+
const bytes = this.resultFiles.get(entry.path);
|
|
1150
|
+
body.append(bytes ? this.imageElement(bytes, entry.path) : this.placeholder('Not in the result'));
|
|
1151
|
+
return;
|
|
1152
|
+
}
|
|
1153
|
+
const raw = this.texts.get(entry.path) ?? '';
|
|
1154
|
+
if (this.rendered && isMarkdownPath(entry.path)) {
|
|
1155
|
+
// Unresolved conflicts show the current version, marked where incoming differs.
|
|
1156
|
+
const current = await this.renderMarkdown(replaceAllConflicts(raw, 'ours'), entry.path, 'result');
|
|
1157
|
+
const incoming = await this.renderMarkdown(replaceAllConflicts(raw, 'theirs'), entry.path, 'result');
|
|
1158
|
+
if (current) {
|
|
1159
|
+
if (incoming)
|
|
1160
|
+
markBlockChanges(incoming, current);
|
|
1161
|
+
const scope = this.previewScope(current);
|
|
1162
|
+
scope.classList.add('mdzip-merge-result-preview');
|
|
1163
|
+
if (findMergeConflicts(raw).length) {
|
|
1164
|
+
body.append(this.placeholder('Unresolved conflicts show the current version, marked. Switch to the source view to edit the result.'));
|
|
1165
|
+
}
|
|
1166
|
+
body.append(scope);
|
|
1167
|
+
return;
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
const crlf = raw.includes('\r\n');
|
|
1171
|
+
const path = entry.path;
|
|
1172
|
+
const model = this.modelFor(entry);
|
|
1173
|
+
const view = new EditorView({
|
|
1174
|
+
parent: body,
|
|
1175
|
+
root: this.root.ownerDocument,
|
|
1176
|
+
state: EditorState.create({
|
|
1177
|
+
doc: raw,
|
|
1178
|
+
extensions: [
|
|
1179
|
+
// Lines level with the panes above: no wrapping.
|
|
1180
|
+
...this.editorBase(path, !model),
|
|
1181
|
+
crlf ? EditorState.lineSeparator.of('\r\n') : [],
|
|
1182
|
+
resultDecorations(model, (resolution, index) => {
|
|
1183
|
+
void this.queue(() => this.resolveTextConflict(path, index, resolution)).catch((cause) => this.fail(cause));
|
|
1184
|
+
}),
|
|
1185
|
+
EditorView.updateListener.of((update) => {
|
|
1186
|
+
if (update.docChanged)
|
|
1187
|
+
this.textEdited(path, update.state.sliceDoc(0));
|
|
1188
|
+
if (update.selectionSet && !update.docChanged) {
|
|
1189
|
+
const head = update.state.selection.main.head;
|
|
1190
|
+
const conflicts = findMergeConflicts(update.state.doc.toString());
|
|
1191
|
+
const at = conflicts.findIndex((conflict) => head >= conflict.start && head < conflict.end);
|
|
1192
|
+
if (at >= 0 && at !== this.currentInEntry)
|
|
1193
|
+
setTimeout(() => this.setCurrentInEntry(at, false), 0);
|
|
1194
|
+
}
|
|
1195
|
+
})
|
|
1196
|
+
]
|
|
1197
|
+
})
|
|
1198
|
+
});
|
|
1199
|
+
this.resultEditor = view;
|
|
1200
|
+
}
|
|
1201
|
+
editorBase(path, wrap = true) {
|
|
1202
|
+
const extensions = [lineNumbers(), wrap ? EditorView.lineWrapping : [], search({ top: true }), keymap.of(searchKeymap)];
|
|
1203
|
+
if (isMarkdownPath(path))
|
|
1204
|
+
extensions.push(markdownLanguage());
|
|
1205
|
+
return extensions;
|
|
1206
|
+
}
|
|
1207
|
+
async renderMarkdown(text, path, version) {
|
|
1208
|
+
const doc = this.root.ownerDocument;
|
|
1209
|
+
const fragment = await renderSideFragment(doc, this.renderedSource(text, path, version), new AbortController().signal)
|
|
1210
|
+
.catch(() => null);
|
|
1211
|
+
if (!fragment)
|
|
1212
|
+
return null;
|
|
1213
|
+
const article = doc.createElement('article');
|
|
1214
|
+
article.className = 'preview-content mdzip-diff-preview mdzip-merge-preview';
|
|
1215
|
+
article.append(fragment);
|
|
1216
|
+
article.addEventListener('click', (event) => {
|
|
1217
|
+
if (event.target?.closest?.('a'))
|
|
1218
|
+
event.preventDefault();
|
|
1219
|
+
});
|
|
1220
|
+
return article;
|
|
1221
|
+
}
|
|
1222
|
+
previewScope(article) {
|
|
1223
|
+
const scope = this.root.ownerDocument.createElement('div');
|
|
1224
|
+
scope.className = `mdzip-root mdzip-diff-preview-scope${this.colorScheme === 'dark' ? ' mdzip-theme-dark' : ''}`;
|
|
1225
|
+
scope.append(article);
|
|
1226
|
+
return scope;
|
|
1227
|
+
}
|
|
1228
|
+
renderedSource(markdown, path, version) {
|
|
1229
|
+
const createUrl = (bytes, mime) => this.createUrl(bytes, mime);
|
|
1230
|
+
if (this.plain) {
|
|
1231
|
+
const readResource = this.options.readResource;
|
|
1232
|
+
return {
|
|
1233
|
+
markdown, path, manifest: null, colorScheme: this.colorScheme, sourceFormat: 'markdown',
|
|
1234
|
+
readBytes: async (linked) => (readResource ? (await readResource(linked)) ?? null : null),
|
|
1235
|
+
hashOf: () => undefined,
|
|
1236
|
+
createUrl
|
|
1237
|
+
};
|
|
1238
|
+
}
|
|
1239
|
+
const files = version === 'result' ? this.resultFiles : this.versionFiles?.[version]?.files ?? this.resultFiles;
|
|
1240
|
+
return {
|
|
1241
|
+
markdown, path, manifest: this.resultManifest, colorScheme: this.colorScheme,
|
|
1242
|
+
readBytes: async (entryPath) => files.get(entryPath) ?? this.resultFiles.get(entryPath) ?? null,
|
|
1243
|
+
hashOf: () => undefined,
|
|
1244
|
+
createUrl
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
renderImageDecision(entry) {
|
|
1248
|
+
const doc = this.root.ownerDocument;
|
|
1249
|
+
const layout = doc.createElement('div');
|
|
1250
|
+
layout.className = 'mdzip-merge-layout';
|
|
1251
|
+
const note = this.placeholder('Both sides replaced this image. The merge kept the current one and saved the incoming one beside it; choose one.');
|
|
1252
|
+
const top = doc.createElement('div');
|
|
1253
|
+
top.className = 'mdzip-merge-top';
|
|
1254
|
+
const incoming = this.paneShell('Incoming', [this.options.theirsLabel, entry.copyPath].filter(Boolean).join(' · '), 'mdzip-merge-pane-theirs');
|
|
1255
|
+
const current = this.paneShell('Current', this.options.oursLabel, 'mdzip-merge-pane-ours');
|
|
1256
|
+
incoming.heading.append(this.actionButton('Take Incoming', () => this.resolveImage(entry, 'theirs')));
|
|
1257
|
+
current.heading.append(this.actionButton('Keep Current', () => this.resolveImage(entry, 'ours')));
|
|
1258
|
+
const oursBytes = this.resultFiles.get(entry.path);
|
|
1259
|
+
const theirsBytes = entry.copyPath ? this.resultFiles.get(entry.copyPath) : undefined;
|
|
1260
|
+
current.body.append(oursBytes ? this.imageElement(oursBytes, entry.path) : this.placeholder('Missing'));
|
|
1261
|
+
incoming.body.append(theirsBytes ? this.imageElement(theirsBytes, entry.copyPath ?? entry.path) : this.placeholder('Missing'));
|
|
1262
|
+
top.append(incoming.pane, current.pane);
|
|
1263
|
+
layout.append(note, top);
|
|
1264
|
+
if (entry.base) {
|
|
1265
|
+
const original = this.paneShell('Original', '', 'mdzip-merge-pane-base');
|
|
1266
|
+
original.body.append(this.imageElement(entry.base, entry.path));
|
|
1267
|
+
layout.append(original.pane);
|
|
1268
|
+
}
|
|
1269
|
+
return layout;
|
|
1270
|
+
}
|
|
1271
|
+
resolveImage(entry, resolution) {
|
|
1272
|
+
const index = this.items.findIndex((item) => item.kind === 'binary' && item.path === entry.path);
|
|
1273
|
+
return this.resolve(index, resolution);
|
|
1274
|
+
}
|
|
1275
|
+
renderManifestFields(entry) {
|
|
1276
|
+
const doc = this.root.ownerDocument;
|
|
1277
|
+
const wrap = doc.createElement('div');
|
|
1278
|
+
wrap.className = 'mdzip-merge-fields';
|
|
1279
|
+
wrap.append(this.placeholder('Both sides changed these document properties. The merge kept the current values; choose for each.'));
|
|
1280
|
+
const table = doc.createElement('table');
|
|
1281
|
+
table.className = 'mdzip-merge-field-table';
|
|
1282
|
+
table.innerHTML = '<thead><tr><th>Property</th><th>Incoming</th><th>Current</th><th></th></tr></thead>';
|
|
1283
|
+
const body = doc.createElement('tbody');
|
|
1284
|
+
for (const field of entry.manifestFields ?? []) {
|
|
1285
|
+
const row = doc.createElement('tr');
|
|
1286
|
+
const cell = (value, chosen) => {
|
|
1287
|
+
const td = doc.createElement('td');
|
|
1288
|
+
td.className = chosen ? 'mdzip-merge-field-chosen' : '';
|
|
1289
|
+
td.textContent = value === undefined ? '(not set)' : typeof value === 'string' ? value : JSON.stringify(value);
|
|
1290
|
+
return td;
|
|
1291
|
+
};
|
|
1292
|
+
const name = doc.createElement('td');
|
|
1293
|
+
name.textContent = field.key;
|
|
1294
|
+
const action = doc.createElement('td');
|
|
1295
|
+
action.append(field.chosen === 'ours'
|
|
1296
|
+
? this.actionButton('Take Incoming', () => this.chooseManifestField(field.key, 'theirs'))
|
|
1297
|
+
: this.actionButton('Take Current', () => this.chooseManifestField(field.key, 'ours')));
|
|
1298
|
+
row.append(name, cell(field.theirs, field.chosen === 'theirs'), cell(field.ours, field.chosen === 'ours'), action);
|
|
1299
|
+
body.append(row);
|
|
1300
|
+
}
|
|
1301
|
+
table.append(body);
|
|
1302
|
+
wrap.append(table);
|
|
1303
|
+
return wrap;
|
|
1304
|
+
}
|
|
1305
|
+
// ------------------------------------------------------------ the current conflict
|
|
1306
|
+
currentConflicts() {
|
|
1307
|
+
const entry = this.entry(this.selectedPath);
|
|
1308
|
+
if (!entry?.text || !entry.inResult)
|
|
1309
|
+
return [];
|
|
1310
|
+
return findMergeConflicts(this.resultEditor ? this.resultEditor.state.doc.toString() : normalize(this.texts.get(entry.path) ?? ''));
|
|
1311
|
+
}
|
|
1312
|
+
updateConflictBar() {
|
|
1313
|
+
const bar = this.content.querySelector('[data-ref="conflict-bar"]');
|
|
1314
|
+
if (!bar)
|
|
1315
|
+
return;
|
|
1316
|
+
const conflicts = this.currentConflicts();
|
|
1317
|
+
const doc = this.root.ownerDocument;
|
|
1318
|
+
if (!conflicts.length) {
|
|
1319
|
+
bar.replaceChildren(Object.assign(doc.createElement('span'), {
|
|
1320
|
+
className: 'mdzip-merge-bar-text',
|
|
1321
|
+
textContent: 'No conflicts in this file.'
|
|
1322
|
+
}));
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1325
|
+
// Resolving the last conflict in the file leaves the current one past the end.
|
|
1326
|
+
const index = Math.min(this.currentInEntry, conflicts.length - 1);
|
|
1327
|
+
this.currentInEntry = index;
|
|
1328
|
+
const conflict = conflicts[index];
|
|
1329
|
+
const label = Object.assign(doc.createElement('span'), {
|
|
1330
|
+
className: 'mdzip-merge-bar-text',
|
|
1331
|
+
textContent: `Conflict ${index + 1} of ${conflicts.length} in this file · line ${conflict.line}`
|
|
1332
|
+
});
|
|
1333
|
+
const path = this.selectedPath ?? '';
|
|
1334
|
+
const run = (resolution) => () => this.queue(() => this.resolveTextConflict(path, this.currentInEntry, resolution));
|
|
1335
|
+
bar.replaceChildren(label, this.actionButton('Accept Incoming', run('theirs')), this.actionButton('Accept Current', run('ours')), this.actionButton('Accept Both', run('both')), ...(conflict.base !== null ? [this.actionButton('Use Original', run('base'))] : []));
|
|
1336
|
+
}
|
|
1337
|
+
/** Marks conflict `index` of the shown file as current: the bar, both sides and the result follow. */
|
|
1338
|
+
setCurrentInEntry(index, scroll) {
|
|
1339
|
+
const conflicts = this.currentConflicts();
|
|
1340
|
+
this.currentInEntry = conflicts.length ? Math.max(0, Math.min(index, conflicts.length - 1)) : 0;
|
|
1341
|
+
const conflict = conflicts[this.currentInEntry];
|
|
1342
|
+
const globalIndex = conflict ? this.items.findIndex((item) => item.kind === 'text' && item.path === this.selectedPath && item.conflict.start === conflict.start) : -1;
|
|
1343
|
+
if (globalIndex >= 0)
|
|
1344
|
+
this.cursor = globalIndex;
|
|
1345
|
+
this.updateToolbar();
|
|
1346
|
+
this.updateConflictBar();
|
|
1347
|
+
if (this.resultEditor) {
|
|
1348
|
+
this.resultEditor.dispatch({
|
|
1349
|
+
effects: [
|
|
1350
|
+
setCurrentConflict.of(this.currentInEntry),
|
|
1351
|
+
...(scroll && conflict ? [EditorView.scrollIntoView(conflict.start, { y: 'start', yMargin: 40 })] : [])
|
|
1352
|
+
]
|
|
1353
|
+
});
|
|
1354
|
+
}
|
|
1355
|
+
const model = this.selectedPath ? this.models.get(this.selectedPath) : undefined;
|
|
1356
|
+
this.currentRegion = conflict && model ? model.regionAt(conflict.start) : -1;
|
|
1357
|
+
this.refreshMergeUi();
|
|
1358
|
+
const region = model?.regions[this.currentRegion];
|
|
1359
|
+
// Lined up, the side panes follow the result's scrolling.
|
|
1360
|
+
if (!scroll || !region || (this.resultEditor && this.stopScrollSync))
|
|
1361
|
+
return;
|
|
1362
|
+
for (const side of ['ours', 'theirs']) {
|
|
1363
|
+
const editor = this.sideEditors[side];
|
|
1364
|
+
if (!editor)
|
|
1365
|
+
continue;
|
|
1366
|
+
const doc = editor.state.doc;
|
|
1367
|
+
const line = Math.min(doc.lines, (side === 'ours' ? region.oursLines : region.theirsLines)[0] + 1);
|
|
1368
|
+
editor.dispatch({ effects: EditorView.scrollIntoView(doc.line(line).from, { y: 'start', yMargin: 40 }) });
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
// ------------------------------------------------------------ helpers
|
|
1372
|
+
placeholder(text) {
|
|
1373
|
+
const element = this.root.ownerDocument.createElement('div');
|
|
1374
|
+
element.className = 'mdzip-merge-note';
|
|
1375
|
+
element.textContent = text;
|
|
1376
|
+
return element;
|
|
1377
|
+
}
|
|
1378
|
+
imageElement(bytes, path) {
|
|
1379
|
+
const image = this.root.ownerDocument.createElement('img');
|
|
1380
|
+
image.className = 'mdzip-merge-image';
|
|
1381
|
+
image.alt = path;
|
|
1382
|
+
image.src = this.createUrl(bytes, mimeFromPath(path));
|
|
1383
|
+
return image;
|
|
1384
|
+
}
|
|
1385
|
+
actionButton(label, run, disabled = false) {
|
|
1386
|
+
const button = this.root.ownerDocument.createElement('button');
|
|
1387
|
+
button.type = 'button';
|
|
1388
|
+
button.className = 'mdzip-merge-action';
|
|
1389
|
+
button.textContent = label;
|
|
1390
|
+
button.disabled = disabled;
|
|
1391
|
+
button.addEventListener('click', () => {
|
|
1392
|
+
button.disabled = true;
|
|
1393
|
+
run().catch((cause) => this.fail(cause)).finally(() => { button.disabled = disabled; });
|
|
1394
|
+
});
|
|
1395
|
+
return button;
|
|
1396
|
+
}
|
|
1397
|
+
createUrl(bytes, mime) {
|
|
1398
|
+
const url = URL.createObjectURL(new Blob([bytes], { type: mime }));
|
|
1399
|
+
this.objectUrls.push(url);
|
|
1400
|
+
return url;
|
|
1401
|
+
}
|
|
1402
|
+
revokeUrls() {
|
|
1403
|
+
for (const url of this.objectUrls)
|
|
1404
|
+
URL.revokeObjectURL(url);
|
|
1405
|
+
this.objectUrls = [];
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
const setSideMarks = StateEffect.define();
|
|
1409
|
+
class CheckMarker extends GutterMarker {
|
|
1410
|
+
constructor(mark, side, onToggle) {
|
|
1411
|
+
super();
|
|
1412
|
+
this.mark = mark;
|
|
1413
|
+
this.side = side;
|
|
1414
|
+
this.onToggle = onToggle;
|
|
1415
|
+
}
|
|
1416
|
+
eq(other) {
|
|
1417
|
+
return other.mark?.index === this.mark?.index && other.mark?.checked === this.mark?.checked
|
|
1418
|
+
&& other.mark?.manual === this.mark?.manual && other.side === this.side;
|
|
1419
|
+
}
|
|
1420
|
+
toDOM(view) {
|
|
1421
|
+
const box = view.dom.ownerDocument.createElement('input');
|
|
1422
|
+
box.type = 'checkbox';
|
|
1423
|
+
box.className = 'mdzip-merge-check';
|
|
1424
|
+
const mark = this.mark;
|
|
1425
|
+
if (!mark) {
|
|
1426
|
+
box.style.visibility = 'hidden';
|
|
1427
|
+
return box;
|
|
1428
|
+
}
|
|
1429
|
+
box.checked = mark.checked;
|
|
1430
|
+
box.indeterminate = mark.manual && !mark.checked;
|
|
1431
|
+
const what = mark.conflict ? 'this conflict' : 'this change';
|
|
1432
|
+
box.title = mark.manual ? `The result has other text here. Tick to use ${sideName(this.side)} for ${what}.`
|
|
1433
|
+
: `${mark.checked ? 'Leave out' : 'Take'} ${sideName(this.side)} for ${what}`;
|
|
1434
|
+
box.setAttribute('aria-label', `${sideTitle(this.side)}: ${what} (line ${mark.start + 1})`);
|
|
1435
|
+
box.addEventListener('mousedown', (event) => event.preventDefault());
|
|
1436
|
+
box.addEventListener('click', (event) => {
|
|
1437
|
+
event.preventDefault();
|
|
1438
|
+
this.onToggle(mark.index);
|
|
1439
|
+
});
|
|
1440
|
+
return box;
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
/** Each pane's filler, from the model's regions and the result's current text. */
|
|
1444
|
+
function alignment(model, result) {
|
|
1445
|
+
const spacers = { ours: [], theirs: [], result: [] };
|
|
1446
|
+
const panes = ['ours', 'theirs', 'result'];
|
|
1447
|
+
const pad = (from, to, region) => {
|
|
1448
|
+
const counts = panes.map((pane) => to[pane] - from[pane]);
|
|
1449
|
+
const most = Math.max(...counts);
|
|
1450
|
+
panes.forEach((pane, index) => {
|
|
1451
|
+
const lines = most - counts[index];
|
|
1452
|
+
const removed = region && counts[index] === 0;
|
|
1453
|
+
if (lines > 0 || removed)
|
|
1454
|
+
spacers[pane].push({ line: to[pane], lines, removed, links: false, order: region ? -3 : -2 });
|
|
1455
|
+
});
|
|
1456
|
+
};
|
|
1457
|
+
const resultLine = (pos) => result.lineAt(Math.min(pos, result.length)).number - 1;
|
|
1458
|
+
let previous = { ours: 0, theirs: 0, result: 0 };
|
|
1459
|
+
for (const region of model.regions) {
|
|
1460
|
+
const start = { ours: region.oursLines[0], theirs: region.theirsLines[0], result: resultLine(region.from) };
|
|
1461
|
+
const end = {
|
|
1462
|
+
ours: region.oursLines[1],
|
|
1463
|
+
theirs: region.theirsLines[1],
|
|
1464
|
+
result: region.to > region.from ? result.lineAt(Math.min(region.to, result.length + 1) - 1).number : start.result
|
|
1465
|
+
};
|
|
1466
|
+
pad(previous, start, false);
|
|
1467
|
+
if (region.choice === 'unresolved') {
|
|
1468
|
+
for (const pane of ['ours', 'theirs'])
|
|
1469
|
+
spacers[pane].push({ line: start[pane], lines: 0, removed: false, links: true, order: -1 });
|
|
1470
|
+
}
|
|
1471
|
+
pad(start, end, true);
|
|
1472
|
+
previous = end;
|
|
1473
|
+
}
|
|
1474
|
+
pad(previous, {
|
|
1475
|
+
ours: model.sides.ours.split('\n').length,
|
|
1476
|
+
theirs: model.sides.theirs.split('\n').length,
|
|
1477
|
+
result: result.lines
|
|
1478
|
+
}, false);
|
|
1479
|
+
return spacers;
|
|
1480
|
+
}
|
|
1481
|
+
/** Height of a line in an aligned pane, and of the accept links above a conflict (CSS sets the same). */
|
|
1482
|
+
const ALIGNED_LINE_PX = 20;
|
|
1483
|
+
class SpacerWidget extends WidgetType {
|
|
1484
|
+
constructor(spacer) {
|
|
1485
|
+
super();
|
|
1486
|
+
this.spacer = spacer;
|
|
1487
|
+
}
|
|
1488
|
+
eq(other) {
|
|
1489
|
+
return other.spacer.lines === this.spacer.lines && other.spacer.removed === this.spacer.removed && other.spacer.links === this.spacer.links;
|
|
1490
|
+
}
|
|
1491
|
+
get estimatedHeight() {
|
|
1492
|
+
return (this.spacer.lines + (this.spacer.links ? 1 : 0)) * ALIGNED_LINE_PX;
|
|
1493
|
+
}
|
|
1494
|
+
toDOM(view) {
|
|
1495
|
+
const element = view.dom.ownerDocument.createElement('div');
|
|
1496
|
+
element.className = `mdzip-merge-spacer${this.spacer.removed ? ' removed' : ''}${this.spacer.links ? ' links' : ''}`;
|
|
1497
|
+
element.style.height = `${this.estimatedHeight}px`;
|
|
1498
|
+
if (this.spacer.removed)
|
|
1499
|
+
element.title = 'No lines here for this change';
|
|
1500
|
+
element.setAttribute('aria-hidden', 'true');
|
|
1501
|
+
return element;
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
function spacerDecorations(doc, spacers) {
|
|
1505
|
+
return spacers.map((spacer) => {
|
|
1506
|
+
const atEnd = spacer.line >= doc.lines;
|
|
1507
|
+
return Decoration.widget({ widget: new SpacerWidget(spacer), block: true, side: atEnd ? 1 + spacer.order + 3 : spacer.order })
|
|
1508
|
+
.range(atEnd ? doc.length : doc.line(spacer.line + 1).from);
|
|
1509
|
+
});
|
|
1510
|
+
}
|
|
1511
|
+
const setSideSpacers = StateEffect.define();
|
|
1512
|
+
/** The incoming or current pane's changes: tinted, each with a checkbox in the gutter. */
|
|
1513
|
+
function sideRegions(side, onToggle) {
|
|
1514
|
+
const build = (state, marks, spacers) => {
|
|
1515
|
+
const doc = state.doc;
|
|
1516
|
+
const decorations = spacerDecorations(doc, spacers);
|
|
1517
|
+
const markers = [];
|
|
1518
|
+
for (const mark of marks) {
|
|
1519
|
+
const first = Math.min(mark.start + 1, doc.lines);
|
|
1520
|
+
markers.push(new CheckMarker(mark, side, onToggle).range(doc.line(first).from));
|
|
1521
|
+
const classes = `mdzip-merge-line-${side}${mark.conflict ? ' mdzip-merge-line-conflict' : ''}${mark.checked ? ' mdzip-merge-line-taken' : ''}${mark.current ? ' mdzip-merge-line-current' : ''}`;
|
|
1522
|
+
for (let line = mark.start + 1; line <= Math.min(mark.end, doc.lines); line++) {
|
|
1523
|
+
decorations.push(Decoration.line({ class: classes }).range(doc.line(line).from));
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
return { marks, spacers, decorations: Decoration.set(decorations, true), markers: RangeSet.of(markers, true) };
|
|
1527
|
+
};
|
|
1528
|
+
const field = StateField.define({
|
|
1529
|
+
create: () => ({ marks: [], spacers: [], decorations: Decoration.none, markers: RangeSet.empty }),
|
|
1530
|
+
update(value, transaction) {
|
|
1531
|
+
let { marks, spacers } = value;
|
|
1532
|
+
let changed = false;
|
|
1533
|
+
for (const effect of transaction.effects) {
|
|
1534
|
+
if (effect.is(setSideMarks)) {
|
|
1535
|
+
marks = effect.value;
|
|
1536
|
+
changed = true;
|
|
1537
|
+
}
|
|
1538
|
+
if (effect.is(setSideSpacers)) {
|
|
1539
|
+
spacers = effect.value;
|
|
1540
|
+
changed = true;
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
return changed ? build(transaction.state, marks, spacers) : value;
|
|
1544
|
+
},
|
|
1545
|
+
provide: (f) => EditorView.decorations.from(f, (value) => value.decorations)
|
|
1546
|
+
});
|
|
1547
|
+
return [
|
|
1548
|
+
field,
|
|
1549
|
+
gutter({
|
|
1550
|
+
class: 'mdzip-merge-check-gutter',
|
|
1551
|
+
markers: (view) => view.state.field(field).markers,
|
|
1552
|
+
initialSpacer: () => new CheckMarker(null, side, onToggle)
|
|
1553
|
+
})
|
|
1554
|
+
];
|
|
1555
|
+
}
|
|
1556
|
+
/** Lines a side changed from the original. */
|
|
1557
|
+
function changedLines(base, text, className) {
|
|
1558
|
+
if (base === null)
|
|
1559
|
+
return [];
|
|
1560
|
+
const doc = Text.of(text.split('\n'));
|
|
1561
|
+
const chunks = Chunk.build(Text.of(base.split('\n')), doc);
|
|
1562
|
+
const ranges = [];
|
|
1563
|
+
const decoration = Decoration.line({ class: className });
|
|
1564
|
+
for (const chunk of chunks) {
|
|
1565
|
+
if (chunk.toB <= chunk.fromB)
|
|
1566
|
+
continue;
|
|
1567
|
+
const first = doc.lineAt(chunk.fromB).number;
|
|
1568
|
+
const last = doc.lineAt(Math.max(chunk.fromB, Math.min(doc.length, chunk.toB - 1))).number;
|
|
1569
|
+
for (let line = first; line <= last; line++)
|
|
1570
|
+
ranges.push(decoration.range(doc.line(line).from));
|
|
1571
|
+
}
|
|
1572
|
+
return EditorView.decorations.of(Decoration.set(ranges, true));
|
|
1573
|
+
}
|
|
1574
|
+
class ConflictActionsWidget extends WidgetType {
|
|
1575
|
+
constructor(index, count, hasBase, current, onAction) {
|
|
1576
|
+
super();
|
|
1577
|
+
this.index = index;
|
|
1578
|
+
this.count = count;
|
|
1579
|
+
this.hasBase = hasBase;
|
|
1580
|
+
this.current = current;
|
|
1581
|
+
this.onAction = onAction;
|
|
1582
|
+
}
|
|
1583
|
+
eq(other) {
|
|
1584
|
+
return other.index === this.index && other.count === this.count && other.hasBase === this.hasBase && other.current === this.current;
|
|
1585
|
+
}
|
|
1586
|
+
get estimatedHeight() {
|
|
1587
|
+
return ALIGNED_LINE_PX;
|
|
1588
|
+
}
|
|
1589
|
+
toDOM(view) {
|
|
1590
|
+
const doc = view.dom.ownerDocument;
|
|
1591
|
+
const bar = doc.createElement('div');
|
|
1592
|
+
bar.className = `mdzip-merge-inline-actions${this.current ? ' current' : ''}`;
|
|
1593
|
+
const label = doc.createElement('span');
|
|
1594
|
+
label.className = 'mdzip-merge-inline-label';
|
|
1595
|
+
label.textContent = `Conflict ${this.index + 1} of ${this.count}`;
|
|
1596
|
+
bar.append(label);
|
|
1597
|
+
const links = [
|
|
1598
|
+
['Accept Incoming', 'theirs'], ['Accept Current', 'ours'], ['Accept Both', 'both']
|
|
1599
|
+
];
|
|
1600
|
+
if (this.hasBase)
|
|
1601
|
+
links.push(['Use Original', 'base']);
|
|
1602
|
+
for (const [text, resolution] of links) {
|
|
1603
|
+
const link = doc.createElement('button');
|
|
1604
|
+
link.type = 'button';
|
|
1605
|
+
link.className = 'mdzip-merge-inline-link';
|
|
1606
|
+
link.textContent = text;
|
|
1607
|
+
link.addEventListener('mousedown', (event) => event.preventDefault());
|
|
1608
|
+
link.addEventListener('click', () => this.onAction(resolution, this.index));
|
|
1609
|
+
bar.append(link);
|
|
1610
|
+
}
|
|
1611
|
+
return bar;
|
|
1612
|
+
}
|
|
1613
|
+
ignoreEvent() {
|
|
1614
|
+
return true;
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
/**
|
|
1618
|
+
* The result: tints each conflict block's sections and puts the accept links
|
|
1619
|
+
* above it, and tints each settled change by where its text came from. Keeps
|
|
1620
|
+
* `model` in step with every edit.
|
|
1621
|
+
*/
|
|
1622
|
+
function resultDecorations(model, onAction) {
|
|
1623
|
+
const build = (state, current) => {
|
|
1624
|
+
const doc = state.doc;
|
|
1625
|
+
const conflicts = findMergeConflicts(doc.toString());
|
|
1626
|
+
const ranges = [];
|
|
1627
|
+
for (const region of model?.regions ?? []) {
|
|
1628
|
+
if (region.from >= region.to || region.to > doc.length + 1)
|
|
1629
|
+
continue;
|
|
1630
|
+
const className = settledClass(region);
|
|
1631
|
+
if (!className)
|
|
1632
|
+
continue;
|
|
1633
|
+
const first = doc.lineAt(region.from).number;
|
|
1634
|
+
const last = doc.lineAt(Math.max(region.from, Math.min(doc.length, region.to - 1))).number;
|
|
1635
|
+
for (let number = first; number <= last; number++)
|
|
1636
|
+
ranges.push(Decoration.line({ class: className }).range(doc.line(number).from));
|
|
1637
|
+
}
|
|
1638
|
+
conflicts.forEach((conflict, index) => {
|
|
1639
|
+
ranges.push(Decoration.widget({
|
|
1640
|
+
widget: new ConflictActionsWidget(index, conflicts.length, conflict.base !== null, index === current, onAction),
|
|
1641
|
+
block: true,
|
|
1642
|
+
side: -1
|
|
1643
|
+
}).range(conflict.start));
|
|
1644
|
+
const oursStart = doc.lineAt(conflict.start).to + 1;
|
|
1645
|
+
const oursEnd = oursStart + conflict.ours.length;
|
|
1646
|
+
let baseStart = -1;
|
|
1647
|
+
let baseEnd = -1;
|
|
1648
|
+
let separator = oursEnd;
|
|
1649
|
+
if (conflict.base !== null) {
|
|
1650
|
+
baseStart = doc.lineAt(oursEnd).to + 1;
|
|
1651
|
+
baseEnd = baseStart + conflict.base.length;
|
|
1652
|
+
separator = baseEnd;
|
|
1653
|
+
}
|
|
1654
|
+
const theirsStart = doc.lineAt(separator).to + 1;
|
|
1655
|
+
const theirsEnd = theirsStart + conflict.theirs.length;
|
|
1656
|
+
const first = doc.lineAt(conflict.start).number;
|
|
1657
|
+
const last = doc.lineAt(Math.max(conflict.start, conflict.end - 1)).number;
|
|
1658
|
+
for (let number = first; number <= last; number++) {
|
|
1659
|
+
const line = doc.line(number);
|
|
1660
|
+
let className = 'mdzip-merge-line-marker';
|
|
1661
|
+
if (line.from >= oursStart && line.from < oursEnd)
|
|
1662
|
+
className = 'mdzip-merge-line-ours';
|
|
1663
|
+
else if (baseStart >= 0 && line.from >= baseStart && line.from < baseEnd)
|
|
1664
|
+
className = 'mdzip-merge-line-base';
|
|
1665
|
+
else if (line.from >= theirsStart && line.from < theirsEnd)
|
|
1666
|
+
className = 'mdzip-merge-line-theirs';
|
|
1667
|
+
if (index === current)
|
|
1668
|
+
className += ' mdzip-merge-line-in-current';
|
|
1669
|
+
ranges.push(Decoration.line({ class: className }).range(line.from));
|
|
1670
|
+
}
|
|
1671
|
+
});
|
|
1672
|
+
if (model && model.text === doc.toString())
|
|
1673
|
+
ranges.push(...spacerDecorations(doc, alignment(model, doc).result));
|
|
1674
|
+
return Decoration.set(ranges, true);
|
|
1675
|
+
};
|
|
1676
|
+
const field = StateField.define({
|
|
1677
|
+
create: (state) => ({ current: 0, decorations: build(state, 0) }),
|
|
1678
|
+
update(value, transaction) {
|
|
1679
|
+
let current = value.current;
|
|
1680
|
+
for (const effect of transaction.effects)
|
|
1681
|
+
if (effect.is(setCurrentConflict))
|
|
1682
|
+
current = effect.value;
|
|
1683
|
+
if (transaction.docChanged && model && model.text === transaction.startState.doc.toString()) {
|
|
1684
|
+
model.update(transaction.newDoc.toString(), (pos, assoc) => transaction.changes.mapPos(pos, assoc));
|
|
1685
|
+
}
|
|
1686
|
+
if (!transaction.docChanged && current === value.current)
|
|
1687
|
+
return value;
|
|
1688
|
+
return { current, decorations: build(transaction.state, current) };
|
|
1689
|
+
},
|
|
1690
|
+
provide: (f) => EditorView.decorations.from(f, (value) => value.decorations)
|
|
1691
|
+
});
|
|
1692
|
+
return field;
|
|
1693
|
+
}
|
|
1694
|
+
/** A settled change's tint in the result: from incoming, current, both, or other text. */
|
|
1695
|
+
function settledClass(region) {
|
|
1696
|
+
const choice = region.choice;
|
|
1697
|
+
if (choice === 'unresolved' || choice === 'base')
|
|
1698
|
+
return null;
|
|
1699
|
+
if (choice === 'manual')
|
|
1700
|
+
return 'mdzip-merge-line-manual';
|
|
1701
|
+
if (!choice.length)
|
|
1702
|
+
return null;
|
|
1703
|
+
if (region.kind === 'same' || choice.length > 1)
|
|
1704
|
+
return 'mdzip-merge-line-both';
|
|
1705
|
+
return `mdzip-merge-line-${choice[0]}`;
|
|
1706
|
+
}
|
|
1707
|
+
/** Whether `side` has a checkbox for this region: the side changed it. */
|
|
1708
|
+
function regionOnSide(region, side) {
|
|
1709
|
+
return region.kind === side || region.kind === 'same' || region.kind === 'conflict';
|
|
1710
|
+
}
|
|
1711
|
+
function sideChecked(region, side) {
|
|
1712
|
+
return Array.isArray(region.choice) && region.choice.includes(side);
|
|
1713
|
+
}
|
|
1714
|
+
function sideTitle(side) {
|
|
1715
|
+
return side === 'ours' ? 'Current' : 'Incoming';
|
|
1716
|
+
}
|
|
1717
|
+
function sideName(side) {
|
|
1718
|
+
return side === 'ours' ? 'current' : 'incoming';
|
|
1719
|
+
}
|
|
1720
|
+
function resolutionChoice(resolution) {
|
|
1721
|
+
switch (resolution) {
|
|
1722
|
+
case 'ours': return ['ours'];
|
|
1723
|
+
case 'theirs': return ['theirs'];
|
|
1724
|
+
case 'both': return ['ours', 'theirs'];
|
|
1725
|
+
case 'base': return 'base';
|
|
1726
|
+
default: return null;
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
// ------------------------------------------------------------ versions
|
|
1730
|
+
async function readVersion(bytes) {
|
|
1731
|
+
const archive = await MdzArchiveCore.open(bytes);
|
|
1732
|
+
const files = new Map();
|
|
1733
|
+
for (const entry of archive.listEntries()) {
|
|
1734
|
+
if (entry.isDirectory)
|
|
1735
|
+
continue;
|
|
1736
|
+
files.set(entry.path, await archive.readBytes(entry.path));
|
|
1737
|
+
}
|
|
1738
|
+
return { files, manifest: parseJson(files.get(MANIFEST_PATH)) };
|
|
1739
|
+
}
|
|
1740
|
+
/** Old path → new path for the files `side` renamed, as `mdz merge` finds them. */
|
|
1741
|
+
function findRenames(base, side) {
|
|
1742
|
+
const removed = [...base.keys()].filter((path) => path !== MANIFEST_PATH && !side.has(path));
|
|
1743
|
+
const added = [...side.keys()].filter((path) => path !== MANIFEST_PATH && !base.has(path) && !theirsCopyOriginal(path));
|
|
1744
|
+
const candidates = [];
|
|
1745
|
+
for (const from of removed) {
|
|
1746
|
+
const original = base.get(from);
|
|
1747
|
+
for (const to of added) {
|
|
1748
|
+
const bytes = side.get(to);
|
|
1749
|
+
if (bytesEqual(original, bytes)) {
|
|
1750
|
+
candidates.push({ score: 2, from, to });
|
|
1751
|
+
continue;
|
|
1752
|
+
}
|
|
1753
|
+
if (extensionOf(from) !== extensionOf(to) || !isTextPath(from))
|
|
1754
|
+
continue;
|
|
1755
|
+
const score = lineSimilarity(decode(original), decode(bytes));
|
|
1756
|
+
if (score >= RENAME_SIMILARITY)
|
|
1757
|
+
candidates.push({ score, from, to });
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
candidates.sort((a, b) => b.score - a.score || a.from.localeCompare(b.from));
|
|
1761
|
+
const renames = new Map();
|
|
1762
|
+
const taken = new Set();
|
|
1763
|
+
for (const { from, to } of candidates) {
|
|
1764
|
+
if (renames.has(from) || taken.has(to))
|
|
1765
|
+
continue;
|
|
1766
|
+
renames.set(from, to);
|
|
1767
|
+
taken.add(to);
|
|
1768
|
+
}
|
|
1769
|
+
return renames;
|
|
1770
|
+
}
|
|
1771
|
+
function lineSimilarity(a, b) {
|
|
1772
|
+
const count = (text) => {
|
|
1773
|
+
const counts = new Map();
|
|
1774
|
+
for (const raw of text.split('\n')) {
|
|
1775
|
+
const line = raw.replace(/\r$/, '');
|
|
1776
|
+
if (!line.trim())
|
|
1777
|
+
continue;
|
|
1778
|
+
counts.set(line, (counts.get(line) ?? 0) + 1);
|
|
1779
|
+
}
|
|
1780
|
+
return counts;
|
|
1781
|
+
};
|
|
1782
|
+
const linesA = count(a);
|
|
1783
|
+
const linesB = count(b);
|
|
1784
|
+
let total = 0;
|
|
1785
|
+
for (const value of linesA.values())
|
|
1786
|
+
total += value;
|
|
1787
|
+
for (const value of linesB.values())
|
|
1788
|
+
total += value;
|
|
1789
|
+
if (!total)
|
|
1790
|
+
return 0;
|
|
1791
|
+
let shared = 0;
|
|
1792
|
+
for (const [line, value] of linesA)
|
|
1793
|
+
shared += Math.min(value, linesB.get(line) ?? 0);
|
|
1794
|
+
return (2 * shared) / total;
|
|
1795
|
+
}
|
|
1796
|
+
function describeChange(entry) {
|
|
1797
|
+
const parts = [];
|
|
1798
|
+
if (entry.basePath && entry.basePath !== entry.path) {
|
|
1799
|
+
const who = entry.oursPath === entry.path && entry.theirsPath !== entry.path ? 'current'
|
|
1800
|
+
: entry.theirsPath === entry.path && entry.oursPath !== entry.path ? 'incoming' : 'both';
|
|
1801
|
+
parts.push(`Renamed from ${entry.basePath} in ${who}`);
|
|
1802
|
+
}
|
|
1803
|
+
const oursChanged = !bytesEqual(entry.ours, entry.base);
|
|
1804
|
+
const theirsChanged = !bytesEqual(entry.theirs, entry.base);
|
|
1805
|
+
if (!entry.base) {
|
|
1806
|
+
if (entry.ours && entry.theirs)
|
|
1807
|
+
parts.push('Added in both');
|
|
1808
|
+
else if (entry.ours)
|
|
1809
|
+
parts.push('Added in current');
|
|
1810
|
+
else if (entry.theirs)
|
|
1811
|
+
parts.push('Added in incoming');
|
|
1812
|
+
}
|
|
1813
|
+
else if (!entry.ours && !entry.theirs) {
|
|
1814
|
+
parts.push('Deleted in both');
|
|
1815
|
+
}
|
|
1816
|
+
else if (!entry.ours) {
|
|
1817
|
+
parts.push(theirsChanged ? 'Deleted in current, changed in incoming' : 'Deleted in current');
|
|
1818
|
+
}
|
|
1819
|
+
else if (!entry.theirs) {
|
|
1820
|
+
parts.push(oursChanged ? 'Deleted in incoming, changed in current' : 'Deleted in incoming');
|
|
1821
|
+
}
|
|
1822
|
+
else if (oursChanged && theirsChanged) {
|
|
1823
|
+
parts.push(bytesEqual(entry.ours, entry.theirs) ? 'Changed the same way in both' : 'Changed in both');
|
|
1824
|
+
}
|
|
1825
|
+
else if (oursChanged) {
|
|
1826
|
+
parts.push('Changed in current');
|
|
1827
|
+
}
|
|
1828
|
+
else if (theirsChanged) {
|
|
1829
|
+
parts.push('Changed in incoming');
|
|
1830
|
+
}
|
|
1831
|
+
if (entry.copyPath)
|
|
1832
|
+
parts.push(`incoming saved as ${entry.copyPath}`);
|
|
1833
|
+
const text = parts.join('; ');
|
|
1834
|
+
return text ? text[0].toUpperCase() + text.slice(1) : '';
|
|
1835
|
+
}
|
|
1836
|
+
/** Top-level manifest fields both sides changed, differently. */
|
|
1837
|
+
function manifestConflicts(base, ours, theirs, result) {
|
|
1838
|
+
if (!ours || !theirs)
|
|
1839
|
+
return [];
|
|
1840
|
+
const keys = new Set([...Object.keys(base ?? {}), ...Object.keys(ours), ...Object.keys(theirs)]);
|
|
1841
|
+
const fields = [];
|
|
1842
|
+
for (const key of keys) {
|
|
1843
|
+
if (MANIFEST_SETTLED.has(key))
|
|
1844
|
+
continue;
|
|
1845
|
+
const b = JSON.stringify(base?.[key]);
|
|
1846
|
+
const o = JSON.stringify(ours[key]);
|
|
1847
|
+
const t = JSON.stringify(theirs[key]);
|
|
1848
|
+
if (o === b || t === b || o === t)
|
|
1849
|
+
continue;
|
|
1850
|
+
const now = JSON.stringify(result?.[key]);
|
|
1851
|
+
fields.push({ key, ours: ours[key], theirs: theirs[key], chosen: now === t ? 'theirs' : 'ours' });
|
|
1852
|
+
}
|
|
1853
|
+
return fields;
|
|
1854
|
+
}
|
|
1855
|
+
// ------------------------------------------------------------ small helpers
|
|
1856
|
+
function replaceAllConflicts(text, resolution) {
|
|
1857
|
+
let output = '';
|
|
1858
|
+
let at = 0;
|
|
1859
|
+
for (const conflict of findMergeConflicts(text)) {
|
|
1860
|
+
output += text.slice(at, conflict.start) + mergeConflictReplacement(conflict, resolution);
|
|
1861
|
+
at = conflict.end;
|
|
1862
|
+
}
|
|
1863
|
+
return output + text.slice(at);
|
|
1864
|
+
}
|
|
1865
|
+
function theirsCopyOriginal(path) {
|
|
1866
|
+
const match = THEIRS_COPY_RE.exec(path);
|
|
1867
|
+
return match ? match[1] + (match[2] ?? '') : null;
|
|
1868
|
+
}
|
|
1869
|
+
function parseJson(bytes) {
|
|
1870
|
+
if (!bytes)
|
|
1871
|
+
return null;
|
|
1872
|
+
try {
|
|
1873
|
+
const value = JSON.parse(decode(bytes));
|
|
1874
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
|
|
1875
|
+
}
|
|
1876
|
+
catch {
|
|
1877
|
+
return null;
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
function bytesEqual(a, b) {
|
|
1881
|
+
if (!a || !b)
|
|
1882
|
+
return !a && !b;
|
|
1883
|
+
if (a.length !== b.length)
|
|
1884
|
+
return false;
|
|
1885
|
+
for (let i = 0; i < a.length; i++)
|
|
1886
|
+
if (a[i] !== b[i])
|
|
1887
|
+
return false;
|
|
1888
|
+
return true;
|
|
1889
|
+
}
|
|
1890
|
+
function encode(text) {
|
|
1891
|
+
return new TextEncoder().encode(text);
|
|
1892
|
+
}
|
|
1893
|
+
function decode(bytes) {
|
|
1894
|
+
return new TextDecoder().decode(bytes);
|
|
1895
|
+
}
|
|
1896
|
+
function normalize(text) {
|
|
1897
|
+
return text.replace(/\r\n/g, '\n');
|
|
1898
|
+
}
|
|
1899
|
+
function dirname(path) {
|
|
1900
|
+
const slash = path.lastIndexOf('/');
|
|
1901
|
+
return slash < 0 ? '' : path.slice(0, slash);
|
|
1902
|
+
}
|
|
1903
|
+
function extensionOf(path) {
|
|
1904
|
+
const name = path.slice(path.lastIndexOf('/') + 1);
|
|
1905
|
+
const dot = name.lastIndexOf('.');
|
|
1906
|
+
return dot > 0 ? name.slice(dot + 1).toLowerCase() : '';
|
|
1907
|
+
}
|
|
1908
|
+
function isTextPath(path) {
|
|
1909
|
+
return TEXT_EXTENSIONS.has(extensionOf(path));
|
|
1910
|
+
}
|
|
1911
|
+
function isMarkdownPath(path) {
|
|
1912
|
+
const extension = extensionOf(path);
|
|
1913
|
+
return extension === 'md' || extension === 'markdown';
|
|
1914
|
+
}
|
|
1915
|
+
function isImagePath(path) {
|
|
1916
|
+
return /^(png|jpe?g|gif|webp|svg|avif|bmp)$/.test(extensionOf(path));
|
|
1917
|
+
}
|
|
1918
|
+
function stateLabel(state) {
|
|
1919
|
+
switch (state) {
|
|
1920
|
+
case 'conflict': return 'conflicts to resolve';
|
|
1921
|
+
case 'decision': return 'choose a version';
|
|
1922
|
+
case 'review': return 'the merge chose; review it';
|
|
1923
|
+
case 'merged': return 'merged';
|
|
1924
|
+
case 'unchanged': return 'unchanged';
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
function mimeFromPath(path) {
|
|
1928
|
+
switch (extensionOf(path)) {
|
|
1929
|
+
case 'png': return 'image/png';
|
|
1930
|
+
case 'jpg':
|
|
1931
|
+
case 'jpeg': return 'image/jpeg';
|
|
1932
|
+
case 'gif': return 'image/gif';
|
|
1933
|
+
case 'webp': return 'image/webp';
|
|
1934
|
+
case 'svg': return 'image/svg+xml';
|
|
1935
|
+
case 'avif': return 'image/avif';
|
|
1936
|
+
case 'bmp': return 'image/bmp';
|
|
1937
|
+
default: return 'application/octet-stream';
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
function iconHtml(icon) {
|
|
1941
|
+
return `<svg class="mdzip-diff-toolbar-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${icon.map(([tag, attributes]) => {
|
|
1942
|
+
const attrs = Object.entries(attributes).map(([name, value]) => `${name}="${String(value)}"`).join(' ');
|
|
1943
|
+
return `<${tag} ${attrs}></${tag}>`;
|
|
1944
|
+
}).join('')}</svg>`;
|
|
1945
|
+
}
|
|
1946
|
+
function escapeHtml(value) {
|
|
1947
|
+
return value.replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char] ?? char);
|
|
1948
|
+
}
|
|
1949
|
+
function injectMergeStyles(doc) {
|
|
1950
|
+
if (doc.getElementById(MERGE_STYLE_ID))
|
|
1951
|
+
return;
|
|
1952
|
+
const style = doc.createElement('style');
|
|
1953
|
+
style.id = MERGE_STYLE_ID;
|
|
1954
|
+
style.textContent = `
|
|
1955
|
+
.mdzip-merge-root{--mdzip-merge-ours:rgba(26,127,55,.13);--mdzip-merge-ours-strong:#1a7f37;--mdzip-merge-theirs:rgba(9,105,218,.13);--mdzip-merge-theirs-strong:#0969da;--mdzip-merge-base:rgba(110,119,129,.12);--mdzip-merge-attention:#bf8700}
|
|
1956
|
+
.mdzip-merge-root.mdzip-diff-scheme-dark{--mdzip-merge-ours:rgba(63,185,80,.18);--mdzip-merge-ours-strong:#3fb950;--mdzip-merge-theirs:rgba(56,139,253,.2);--mdzip-merge-theirs-strong:#58a6ff;--mdzip-merge-base:rgba(139,148,158,.16);--mdzip-merge-attention:#d29922}
|
|
1957
|
+
.mdzip-merge-workspace{flex:1;min-height:0;display:flex}
|
|
1958
|
+
.mdzip-merge-nav[hidden]{display:none}
|
|
1959
|
+
.mdzip-merge-content{flex:1;min-width:0;display:flex;flex-direction:column;overflow:hidden}
|
|
1960
|
+
.mdzip-merge-entry{grid-template-columns:18px 1fr}
|
|
1961
|
+
.mdzip-merge-marker{font-size:12px;text-align:center}
|
|
1962
|
+
.mdzip-merge-state-conflict .mdzip-merge-marker,.mdzip-merge-marker.mdzip-merge-state-conflict,.mdzip-merge-state-decision .mdzip-merge-marker,.mdzip-merge-marker.mdzip-merge-state-decision{color:var(--mdzip-merge-attention)}
|
|
1963
|
+
.mdzip-merge-state-review .mdzip-merge-marker,.mdzip-merge-marker.mdzip-merge-state-review{color:var(--mdzip-merge-theirs-strong)}
|
|
1964
|
+
.mdzip-merge-state-merged .mdzip-merge-marker,.mdzip-merge-marker.mdzip-merge-state-merged,.mdzip-merge-state-unchanged{color:var(--mdzip-muted-foreground-color,#57606a)}
|
|
1965
|
+
.mdzip-merge-state-unchanged{opacity:.65}
|
|
1966
|
+
.mdzip-merge-gone .mdzip-diff-path{text-decoration:line-through}
|
|
1967
|
+
.mdzip-merge-entry-count{display:inline-block;min-width:16px;padding:0 5px;border-radius:8px;font-size:11px;text-align:center;background:var(--mdzip-diff-active-background);color:var(--mdzip-merge-attention)}
|
|
1968
|
+
.mdzip-merge-panel{flex:1;min-height:0;display:flex;flex-direction:column}
|
|
1969
|
+
.mdzip-merge-header{padding:8px 14px;border-bottom:1px solid var(--mdzip-border-color,#d0d7de)}
|
|
1970
|
+
.mdzip-merge-title{font-weight:600;overflow-wrap:anywhere}
|
|
1971
|
+
.mdzip-merge-summary{margin-top:2px;font-size:12px;color:var(--mdzip-muted-foreground-color,#57606a)}
|
|
1972
|
+
.mdzip-merge-review{display:flex;flex-wrap:wrap;align-items:center;gap:6px 8px;margin-top:6px;font-size:13px}
|
|
1973
|
+
.mdzip-merge-layout{flex:1;min-height:0;display:flex;flex-direction:column}
|
|
1974
|
+
.mdzip-merge-top{flex:1 1 45%;min-height:80px;display:grid;grid-template-columns:1fr 1fr;border-bottom:1px solid var(--mdzip-border-color,#d0d7de)}
|
|
1975
|
+
.mdzip-merge-top>.mdzip-merge-pane+.mdzip-merge-pane{border-left:1px solid var(--mdzip-border-color,#d0d7de)}
|
|
1976
|
+
.mdzip-merge-pane{min-width:0;min-height:0;display:flex;flex-direction:column}
|
|
1977
|
+
.mdzip-merge-pane-result{flex:1 1 55%;min-height:100px}
|
|
1978
|
+
.mdzip-merge-pane-base{flex:0 0 auto;border-top:1px solid var(--mdzip-border-color,#d0d7de)}
|
|
1979
|
+
.mdzip-merge-pane-heading{display:flex;align-items:center;gap:8px;min-height:28px;padding:2px 10px;font-size:12px;background:var(--mdzip-diff-group-background);border-bottom:1px solid var(--mdzip-border-color,#d0d7de)}
|
|
1980
|
+
.mdzip-merge-pane-title{font-weight:600}
|
|
1981
|
+
.mdzip-merge-pane-ours .mdzip-merge-pane-title::before,.mdzip-merge-pane-theirs .mdzip-merge-pane-title::before{content:"";display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px;vertical-align:middle}
|
|
1982
|
+
.mdzip-merge-pane-ours .mdzip-merge-pane-title::before{background:var(--mdzip-merge-ours-strong)}
|
|
1983
|
+
.mdzip-merge-pane-theirs .mdzip-merge-pane-title::before{background:var(--mdzip-merge-theirs-strong)}
|
|
1984
|
+
.mdzip-merge-pane-names{display:flex;flex-direction:column;flex:1;min-width:0;line-height:1.3;padding:2px 0}
|
|
1985
|
+
.mdzip-merge-pane-label{color:var(--mdzip-muted-foreground-color,#57606a);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px}
|
|
1986
|
+
.mdzip-merge-pane-heading .mdzip-merge-action{padding:1px 8px;font-size:12px}
|
|
1987
|
+
.mdzip-merge-take-all{display:flex;align-items:center;gap:4px;white-space:nowrap;cursor:pointer}
|
|
1988
|
+
.mdzip-merge-remaining{font-weight:600;color:var(--mdzip-merge-attention)}.mdzip-merge-remaining.done{font-weight:400;color:var(--mdzip-muted-foreground-color,#57606a)}
|
|
1989
|
+
.mdzip-merge-complete{margin-left:auto;border:1px solid var(--mdzip-border-color,#d0d7de);border-radius:5px;padding:3px 12px;background:transparent;color:inherit;font:inherit;font-size:12px;cursor:pointer;white-space:nowrap}
|
|
1990
|
+
.mdzip-merge-complete[hidden]{display:none}
|
|
1991
|
+
.mdzip-merge-complete.ready{background:var(--mdzip-accent-color,#0969da);border-color:var(--mdzip-accent-color,#0969da);color:#fff;font-weight:600}
|
|
1992
|
+
.mdzip-merge-complete:hover:not(:disabled){filter:brightness(1.08)}.mdzip-merge-complete:disabled{opacity:.5;cursor:default}
|
|
1993
|
+
.mdzip-merge-complete:focus-visible{outline:2px solid var(--mdzip-accent-color,#0969da);outline-offset:1px}
|
|
1994
|
+
.mdzip-merge-root .mdzip-merge-check-gutter .cm-gutterElement{display:flex;align-items:flex-start;justify-content:center;padding:0 2px}
|
|
1995
|
+
.mdzip-merge-check{margin:3px 0 0;cursor:pointer;accent-color:var(--mdzip-merge-attention)}
|
|
1996
|
+
.mdzip-merge-aligned .cm-editor .cm-line{line-height:20px}
|
|
1997
|
+
.mdzip-merge-aligned .cm-editor .cm-gutterElement{line-height:20px}
|
|
1998
|
+
.mdzip-merge-spacer{position:relative;box-sizing:border-box;background:repeating-linear-gradient(135deg,transparent 0 6px,var(--mdzip-merge-base) 6px 7px)}
|
|
1999
|
+
.mdzip-merge-spacer.links{background:none}
|
|
2000
|
+
.mdzip-merge-spacer.removed::before{content:"";position:absolute;left:0;right:0;top:-1px;border-top:2px dashed var(--mdzip-muted-foreground-color,#8c959f)}
|
|
2001
|
+
.mdzip-merge-root .cm-line.mdzip-merge-line-conflict:not(.mdzip-merge-line-taken){box-shadow:inset 2px 0 0 var(--mdzip-merge-attention)}
|
|
2002
|
+
.mdzip-merge-root .cm-line.mdzip-merge-line-both{background:linear-gradient(90deg,var(--mdzip-merge-theirs),var(--mdzip-merge-ours))}
|
|
2003
|
+
.mdzip-merge-root .cm-line.mdzip-merge-line-manual{background:var(--mdzip-merge-base)}
|
|
2004
|
+
.mdzip-merge-pane-body{flex:1;min-height:0;overflow:auto}
|
|
2005
|
+
.mdzip-merge-pane-body .cm-editor{height:100%;font-size:13px}.mdzip-merge-pane-body .cm-scroller{overflow:auto}
|
|
2006
|
+
.mdzip-merge-root .mdzip-merge-pane-body .cm-editor .cm-content{caret-color:var(--mdzip-foreground-color,currentColor)}
|
|
2007
|
+
.mdzip-merge-root .mdzip-merge-pane-body .cm-editor .cm-gutters{background:transparent;border-right:1px solid var(--mdzip-border-color,#d0d7de);color:var(--mdzip-muted-foreground-color,#57606a)}
|
|
2008
|
+
.mdzip-merge-pane-body .mdzip-diff-preview-scope{--mdzip-preview-content-padding:10px 18px 20px}
|
|
2009
|
+
.mdzip-merge-root .cm-line.mdzip-merge-line-ours{background:var(--mdzip-merge-ours)}
|
|
2010
|
+
.mdzip-merge-root .cm-line.mdzip-merge-line-theirs{background:var(--mdzip-merge-theirs)}
|
|
2011
|
+
.mdzip-merge-root .cm-line.mdzip-merge-line-base{background:var(--mdzip-merge-base)}
|
|
2012
|
+
.mdzip-merge-root .cm-line.mdzip-merge-line-marker{color:var(--mdzip-muted-foreground-color,#57606a);background:var(--mdzip-merge-base)}
|
|
2013
|
+
.mdzip-merge-root .cm-line.mdzip-merge-line-in-current,.mdzip-merge-root .cm-line.mdzip-merge-line-current,.mdzip-merge-root .cm-line.mdzip-merge-line-current.mdzip-merge-line-conflict{box-shadow:inset 3px 0 0 var(--mdzip-merge-attention)}
|
|
2014
|
+
.mdzip-merge-inline-actions{display:flex;flex-wrap:nowrap;align-items:center;gap:0 10px;box-sizing:border-box;height:20px;overflow:hidden;white-space:nowrap;padding:0 6px;font:12px system-ui,sans-serif;color:var(--mdzip-muted-foreground-color,#57606a)}
|
|
2015
|
+
.mdzip-merge-inline-actions.current .mdzip-merge-inline-label{color:var(--mdzip-merge-attention);font-weight:600}
|
|
2016
|
+
.mdzip-merge-inline-link{border:0;padding:0;background:none;color:var(--mdzip-link-color,var(--mdzip-accent-color,#0969da));font:inherit;cursor:pointer}
|
|
2017
|
+
.mdzip-merge-inline-link:hover{text-decoration:underline}
|
|
2018
|
+
.mdzip-merge-inline-link:focus-visible{outline:2px solid var(--mdzip-accent-color,#0969da);outline-offset:1px}
|
|
2019
|
+
.mdzip-merge-bar{display:flex;flex-wrap:wrap;align-items:center;gap:6px 8px;padding:5px 10px;border-bottom:1px solid var(--mdzip-border-color,#d0d7de);font-size:12px}
|
|
2020
|
+
.mdzip-merge-bar-text{margin-right:4px;color:var(--mdzip-muted-foreground-color,#57606a)}
|
|
2021
|
+
.mdzip-merge-action{border:1px solid var(--mdzip-border-color,#d0d7de);border-radius:5px;padding:3px 10px;background:transparent;color:inherit;font:inherit;font-size:12px;cursor:pointer;white-space:nowrap}
|
|
2022
|
+
.mdzip-merge-action:hover:not(:disabled){background:var(--mdzip-diff-active-background)}
|
|
2023
|
+
.mdzip-merge-action:focus-visible{outline:2px solid var(--mdzip-accent-color,#0969da);outline-offset:1px}
|
|
2024
|
+
.mdzip-merge-action:disabled{opacity:.5;cursor:default}
|
|
2025
|
+
.mdzip-merge-note{padding:8px 14px;font-size:12px;color:var(--mdzip-muted-foreground-color,#57606a)}
|
|
2026
|
+
.mdzip-merge-image{display:block;max-width:calc(100% - 24px);height:auto;margin:12px auto}
|
|
2027
|
+
.mdzip-merge-result-preview .mdzip-diff-preview .mdzip-diff-block-added{background:rgba(191,135,0,.16);box-shadow:0 0 0 6px rgba(191,135,0,.16)}
|
|
2028
|
+
.mdzip-merge-result-preview .mdzip-diff-preview .mdzip-diff-block-added::before{background:var(--mdzip-merge-attention)}
|
|
2029
|
+
.mdzip-merge-result-preview .mdzip-diff-preview .mdzip-diff-word-added{background:rgba(191,135,0,.38)}
|
|
2030
|
+
.mdzip-merge-fields{flex:1;overflow:auto;padding-bottom:12px}
|
|
2031
|
+
.mdzip-merge-field-table{border-collapse:collapse;margin:0 14px;font-size:13px}
|
|
2032
|
+
.mdzip-merge-field-table th,.mdzip-merge-field-table td{padding:6px 10px;border-bottom:1px solid var(--mdzip-border-color,#d0d7de);text-align:left;vertical-align:top;overflow-wrap:anywhere}
|
|
2033
|
+
.mdzip-merge-field-table th{font-size:12px;color:var(--mdzip-muted-foreground-color,#57606a);font-weight:600}
|
|
2034
|
+
.mdzip-merge-field-chosen{font-weight:600}
|
|
2035
|
+
@media (max-width:640px){.mdzip-merge-top{grid-template-columns:1fr}.mdzip-merge-top>.mdzip-merge-pane+.mdzip-merge-pane{border-left:0;border-top:1px solid var(--mdzip-border-color,#d0d7de)}}
|
|
2036
|
+
`;
|
|
2037
|
+
doc.head.append(style);
|
|
2038
|
+
}
|
|
2039
|
+
//# sourceMappingURL=merge-view.js.map
|