-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathoscd-editor-diff.ts
More file actions
1195 lines (1081 loc) · 34.6 KB
/
oscd-editor-diff.ts
File metadata and controls
1195 lines (1081 loc) · 34.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { LitElement, html, css, nothing } from 'lit';
import { property, query, state } from 'lit/decorators.js';
import { identity } from '@openscd/scl-lib';
import '@material/web/all.js';
import type { MdDialog, MdFilledSelect, MdMenu } from '@material/web/all.js';
import { classMap } from 'lit/directives/class-map.js';
import {
Configurable,
createHashElementPredicate,
HasherOptions,
newHasher,
} from './hash.js';
import './diff-tree.js';
import './filter-dialog.js';
import './base-filter-dialog.js';
import './info-dialog.js';
import type { FilterDialog, OscdDiffFilterSaveEvent } from './filter-dialog.js';
import type { InfoDialog } from './info-dialog.js';
import {
defaultBaseFilters,
defaultFilters,
extendFilter,
} from './default-filters.js';
import { DefaultInfoDialogContent } from './default-info-dialog-content.js';
import { loadResource, nonemptyLines } from './util.js';
import type {
BaseFilterDialog,
OscdDiffBaseFilterSaveEvent,
} from './base-filter-dialog.js';
const INFO_CONTENT_URL = './oscd-diff-info-content.html';
export const HELP_CONTENT_URL = './oscd-diff-help-content.html';
export const HELP_CONTENT_BASE_URL = './oscd-diff-help-base-content.html';
export type BaseConfigurable = {
vals: string[];
except: string[];
};
export type BaseOptions = {
selectors: BaseConfigurable;
attributes: BaseConfigurable;
namespaces: BaseConfigurable;
};
export type BaseFilter = {
inclusive: BaseOptions;
exclusive: BaseOptions;
};
export type Filter = HasherOptions & {
description: string;
ourSelector: string;
theirSelector: string;
};
export type StoredFilters = {
base: BaseFilter;
filters: Record<string, Filter>;
};
function hasPropertyOfType(
obj: Record<string, unknown>,
prop: string,
type: string,
): boolean {
return (
prop in obj &&
(typeof obj[prop] === type ||
(type === 'array' && Array.isArray(obj[prop])))
);
}
async function hashElement(el: Element, hasher: ReturnType<typeof newHasher>) {
await new Promise(resolve => {
setTimeout(resolve, 0);
});
return hasher.hash(el);
}
function isValidBaseConfigurable(configurable: BaseConfigurable) {
return (
Array.isArray(configurable.vals) &&
Array.isArray(configurable.except) &&
configurable.vals.every(s => typeof s === 'string') &&
configurable.except.every(s => typeof s === 'string')
);
}
function isValidBaseOptions(options: BaseOptions) {
return (
isValidBaseConfigurable(options.selectors) &&
isValidBaseConfigurable(options.attributes) &&
isValidBaseConfigurable(options.namespaces)
);
}
export function isBaseFilter(obj: object): obj is BaseFilter {
const baseFilter = obj as BaseFilter;
if (!baseFilter.inclusive || !baseFilter.exclusive) {
return false;
}
return (
isValidBaseOptions(baseFilter.inclusive) &&
isValidBaseOptions(baseFilter.exclusive)
);
}
export function isFilter(obj: object): obj is Filter {
const filterTypes = {
description: 'string',
ourSelector: 'string',
theirSelector: 'string',
selectors: 'object',
attributes: 'object',
namespaces: 'object',
};
const configurableTypes = {
inclusive: 'boolean',
vals: 'array',
except: 'array',
};
if (
!Object.entries(filterTypes).every(([prop, type]) => {
if (!hasPropertyOfType(obj as Record<string, unknown>, prop, type)) {
return false;
}
if (type === 'string') {
return true;
}
const configurable = (obj as Filter)[prop as keyof HasherOptions];
if (
type === 'object' &&
!Object.entries(configurableTypes).every(([p, t]) => {
if (!hasPropertyOfType(configurable, p, t)) {
return false;
}
if (
t === 'array' &&
!configurable[p as 'vals' | 'except'].every(
s => typeof s === 'string',
)
) {
return false;
}
return true;
})
) {
return false;
}
return true;
})
) {
return false;
}
return true;
}
type StoredDiff = {
elements: Record<string, { ours?: Element; theirs?: Element }>;
ourHasher: ReturnType<typeof newHasher>;
theirHasher: ReturnType<typeof newHasher>;
filter: Filter;
filterName: string;
ourSelector: string;
theirSelector: string;
ourDocName: string;
theirDocName: string;
};
function describeConfigurable(
{ inclusive, vals, except }: Configurable,
name: string,
) {
const verb = inclusive ? 'Including' : 'Excluding';
const object = vals.length
? html` ${name}: <code>${vals.join(', ')}</code>`
: ` no ${name}`;
const exceptions = except.length
? html`, except: <code>${except.join(', ')}</code>`
: '';
return html`${verb}${object}${exceptions}`;
}
export default class OscdEditorDiff extends LitElement {
@property() docName = '';
@property() doc?: XMLDocument;
@property() docs: Record<string, XMLDocument> = {};
@query('#doc1') doc1?: HTMLSelectElement;
@query('#filters-import-field') filtersInputField?: HTMLInputElement;
@query('#doc2') doc2?: HTMLSelectElement;
@query('#doc1sel') doc1sel?: HTMLInputElement;
@query('#doc2sel') doc2sel?: HTMLInputElement;
@query('filter-dialog') filterDialog?: FilterDialog;
@query('base-filter-dialog') baseFilterDialog?: BaseFilterDialog;
@query('info-dialog') infoDialog?: InfoDialog;
@query('md-menu') filterMenu?: MdMenu;
@query('#diff-container') diffContainer?: HTMLDivElement;
@query('#reset-warning-dialog') resetWarningDialog?: MdDialog;
@state() filters: Record<string, Filter> = defaultFilters;
@state() baseFilter: BaseFilter = defaultBaseFilters;
@state()
selectedFilterName: string = '';
@state() lastDiff?: StoredDiff;
@state() get fullscreen() {
return (
this.diffContainer &&
this.shadowRoot &&
this.shadowRoot.fullscreenElement === this.diffContainer
);
}
@state() individuallyScoped = false;
@state() hashing = false;
@state() get allExpanded(): boolean {
const diffTrees = this.diffContainer?.querySelectorAll('diff-tree');
if (!diffTrees) {
return false;
}
let allExpanded = true;
diffTrees.forEach(tree => {
if (!tree.hasAttribute('expanded')) {
allExpanded = false;
}
});
return allExpanded;
}
setFilters(updatedFilters: Record<string, Filter>) {
this.filters = updatedFilters;
this.storeFilters();
}
setBaseFilter(updatedBaseFilter: BaseFilter) {
this.baseFilter = updatedBaseFilter;
this.storeFilters();
}
storeFilters() {
localStorage.setItem(
'oscd-diff-filters',
JSON.stringify({ base: this.baseFilter, filters: this.filters }),
);
}
async deleteFilter(filterName: string) {
const newFilters = { ...this.filters };
delete newFilters[filterName];
this.setFilters(newFilters);
if (Object.keys(newFilters).length === 0) {
this.setFilters(defaultFilters);
}
await this.updateComplete;
this.setSelectedFilterName(Object.keys(this.filters)[0]);
}
get selectedFilter() {
return this.filters[this.selectedFilterName] || defaultFilters.Complete;
}
setSelectedFilterName(name: string) {
if (!(name in this.filters)) {
console.error(`Filter ${name} not found`);
return;
}
localStorage.setItem('oscd-diff-selected-filter', name);
this.selectedFilterName = name;
}
get docName1(): string {
return this.doc1?.value || '';
}
get docName2(): string {
return this.doc2?.value || '';
}
get selector1(): string {
return (
this.doc1sel?.value ||
this.docs[this.docName1]?.documentElement.tagName ||
':root'
);
}
get selector2(): string {
return this.doc2sel?.value || this.selector1;
}
hashers = new WeakMap<XMLDocument, ReturnType<typeof newHasher>>();
firstUpdated() {
const filtersStr = localStorage.getItem('oscd-diff-filters');
if (filtersStr) {
try {
const storedFilters = JSON.parse(filtersStr) as StoredFilters;
if (
storedFilters.base &&
Object.keys(storedFilters.filters).length > 0
) {
this.filters = storedFilters.filters;
this.baseFilter = storedFilters.base;
}
} catch (e) {
console.error(e);
}
}
const selectedFilterName = localStorage.getItem(
'oscd-diff-selected-filter',
);
if (selectedFilterName && selectedFilterName in this.filters) {
this.selectedFilterName = selectedFilterName;
} else {
[this.selectedFilterName] = Object.keys(this.filters);
}
}
async handleImportFieldChanged(event: Event) {
const { files } = event.target as HTMLInputElement;
if (!files || files.length <= 0) {
return;
}
try {
const importedJson = JSON.parse(await files[0].text());
if (typeof importedJson !== 'object') {
console.error('Invalid file format', importedJson);
return;
}
let importedFilters;
let baseFilter;
if (importedJson.base && importedJson.filters) {
importedFilters = importedJson.filters;
if (!isBaseFilter(importedJson.base)) {
console.error('Invalid base filter format');
return;
}
baseFilter = importedJson.base as BaseFilter;
} else if (Object.keys(importedJson).length > 0) {
importedFilters = importedJson.filters;
baseFilter = defaultBaseFilters;
} else {
console.error('Invalid filter format', importedJson);
return;
}
const newFilters = { ...this.filters };
Object.entries(importedFilters as Record<string, unknown>).forEach(
([filterName, filter]) => {
if (filter && typeof filter === 'object' && isFilter(filter)) {
newFilters[filterName] = filter;
}
},
);
this.setBaseFilter(baseFilter);
this.setFilters(newFilters);
} catch (err) {
console.error(err);
}
}
importFilters() {
this.filtersInputField?.click();
if (this.filtersInputField) {
this.filtersInputField.value = '';
}
}
exportFilters() {
const blob = new Blob(
[
JSON.stringify(
{ base: this.baseFilter, filters: this.filters },
null,
2,
),
],
{
type: 'application/json',
},
);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `filters.json`;
a.click();
URL.revokeObjectURL(url);
}
showFilterDialog() {
if (this.filterDialog) {
this.filterDialog.open = true;
}
}
showBaseFilterDialog() {
if (this.baseFilterDialog) {
this.baseFilterDialog.open = true;
}
}
async showInfoDialog() {
if (this.infoDialog) {
try {
const infoContent = await loadResource(INFO_CONTENT_URL);
this.infoDialog.contentText = infoContent;
} catch {
this.infoDialog.contentText = DefaultInfoDialogContent;
}
this.infoDialog.open = true;
}
}
uniqueFilterName(): string {
let i = 1;
const filterName = this.selectedFilterName.replace(/\s*\d+$/, '');
let newName = `${filterName} 1`;
while (newName in this.filters) {
i += 1;
newName = `${filterName} ${i}`;
}
return newName;
}
async duplicateFilter() {
if (this.filterDialog) {
const newFilterName = this.uniqueFilterName();
this.setFilters({
...this.filters,
[newFilterName]: this.selectedFilter,
});
await this.updateComplete;
this.setSelectedFilterName(newFilterName);
}
}
printMe() {
const { diffContainer } = this;
const openSCD = document.querySelector<LitElement>('open-scd');
if (!diffContainer || !openSCD) {
return;
}
const oldDisplay = openSCD.style.display;
openSCD.style.display = 'none';
document.body.prepend(diffContainer);
window.print();
this.shadowRoot!.append(diffContainer);
openSCD.style.display = oldDisplay;
}
toggleExpandAllState() {
const diffTrees = this.diffContainer?.querySelectorAll('diff-tree');
if (diffTrees) {
const { allExpanded } = this;
diffTrees.forEach(tree => {
if (allExpanded) {
tree.removeAttribute('expanded');
} else {
tree.setAttribute('expanded', '');
}
});
this.requestUpdate();
}
}
renderFilterDescription() {
if (!this.lastDiff) {
return nothing;
}
const {
filter,
filterName,
ourSelector,
theirSelector,
ourDocName,
theirDocName,
} = this.lastDiff;
return html`
<div id="filter-description" style="margin: 16px;">
<h3 style="font-weight: 400">Comparison Rule: ${filterName}</h3>
${filter.description ? html`<em>${filter.description}</em>` : nothing}
<p>
Comparing
<span class="ours"
><code>${ourSelector}</code> elements from
<strong>${ourDocName}</strong></span
>
to
<span class="theirs"
><code>${theirSelector}</code> elements from
<strong>${theirDocName}</strong></span
>
</p>
<ul>
<li>${describeConfigurable(filter.selectors, 'elements')}</li>
<li>${describeConfigurable(filter.attributes, 'attributes')}</li>
<li>${describeConfigurable(filter.namespaces, 'namespaces')}</li>
</ul>
</div>
`;
}
renderViewButtons() {
return Object.keys(this.lastDiff?.elements ?? {}).length
? html`<div class="view-buttons">
<md-filled-icon-button
toggle
?selected=${this.allExpanded}
@click=${() => {
this.toggleExpandAllState();
}}
>
<md-icon slot="selected">collapse_all</md-icon>
<md-icon>expand_all</md-icon>
</md-filled-icon-button>
<md-filled-icon-button @click=${() => this.printMe()}>
<md-icon>print</md-icon>
</md-filled-icon-button>
<md-filled-icon-button
toggle
?selected=${this.fullscreen}
@click=${async () => {
if (this.fullscreen) {
await document.exitFullscreen();
} else {
await this.diffContainer?.requestFullscreen();
}
this.requestUpdate();
}}
>
<md-icon>fullscreen</md-icon>
<md-icon slot="selected">fullscreen_exit</md-icon>
</md-filled-icon-button>
</div>`
: nothing;
}
renderDiffTrees() {
let same = true;
const elementKeys = Object.keys(this.lastDiff?.elements ?? {});
const trees = elementKeys.map(id => {
const { ours, theirs } = this.lastDiff!.elements[id];
const { ourHasher, theirHasher } = this.lastDiff!;
const ourHash = ours && ourHasher.hash(ours);
const theirHash = theirs && theirHasher.hash(theirs);
if (ourHash !== theirHash) {
same = false;
return html`<diff-tree
.ours=${ours}
.theirs=${theirs}
.ourHasher=${ourHasher}
.theirHasher=${theirHasher}
?fullscreen=${this.fullscreen}
expanded
@diff-toggle=${() => {
this.requestUpdate();
}}
></diff-tree>`;
}
return nothing;
});
return same && trees.length !== 0
? html`<div style="margin: 16px;">No differences</div>`
: trees;
}
render() {
return html`<div>
<div class="filter-section">
<div id="filter-selector-row">
<div>
<md-filled-select
required
label="Comparison Rules"
.value=${this.selectedFilterName}
@change=${(event: Event) => {
this.setSelectedFilterName(
(event.target as MdFilledSelect).value,
);
}}
>
<md-icon slot="leading-icon">filter_list</md-icon>
${Object.keys(this.filters).map(
(filterName: string) =>
html`<md-select-option
value=${filterName}
?selected=${this.selectedFilterName === filterName}
>
<div slot="headline">${filterName}</div></md-select-option
>`,
)}
</md-filled-select>
<pre>${this.selectedFilter.description}</pre>
</div>
<span class="filter-menu-button">
<input
type="file"
accept="application/json"
id="filters-import-field"
@change=${this.handleImportFieldChanged}
/>
<md-icon-button
id="filter-menu-button"
@click=${() => {
if (this.filterMenu) {
this.filterMenu.open = !this.filterMenu.open;
}
}}
><md-icon>more_vert</md-icon></md-icon-button
>
<md-menu anchor="filter-menu-button">
<md-menu-item
type="button"
href="#"
@click=${() => this.showFilterDialog()}
>
<md-icon slot="start">edit</md-icon>
<div slot="headline">Edit</div>
</md-menu-item>
<md-menu-item
type="button"
href="#"
@click=${() => this.duplicateFilter()}
>
<md-icon slot="start">content_copy</md-icon>
<div slot="headline">Duplicate</div>
</md-menu-item>
<md-menu-item
type="button"
href="#"
@click=${() => this.showBaseFilterDialog()}
>
<md-icon slot="start">border_color</md-icon>
<div slot="headline">Edit Base Rules</div>
</md-menu-item>
<md-menu-item
type="button"
href="#"
@click=${() => this.deleteFilter(this.selectedFilterName)}
style="--md-menu-item-leading-icon-color:var(--oscd-error); --md-menu-item-label-text-color:var(--oscd-error)"
>
<md-icon slot="start">delete</md-icon>
<div slot="headline">Delete</div>
</md-menu-item>
<md-menu-item
type="button"
href="#"
@click=${() => this.resetWarningDialog?.show()}
style="--md-menu-item-leading-icon-color:var(--oscd-error); --md-menu-item-label-text-color:var(--oscd-error)"
>
<md-icon slot="start">reset_settings</md-icon>
<div slot="headline">Reset Filters</div>
</md-menu-item>
<md-divider></md-divider>
<md-menu-item
type="button"
href="#"
@click=${() => this.importFilters()}
>
<md-icon slot="start">publish</md-icon>
<div slot="headline">Import Filters</div>
</md-menu-item>
<md-menu-item
type="button"
href="#"
@click=${() => this.exportFilters()}
>
<md-icon slot="start">download</md-icon>
<div slot="headline">Export Filters</div>
</md-menu-item>
</md-menu>
</span>
</div>
<md-filled-select
required
id="doc1"
label="From document"
@change=${() => this.requestUpdate()}
>
<md-icon slot="leading-icon" class="ours">draft</md-icon>
${Object.keys(this.docs).map(
name =>
html`<md-select-option value="${name}"
><div slot="headline">${name}</div></md-select-option
>`,
)}
</md-filled-select>
<md-filled-select
required
id="doc2"
label="To document"
@change=${() => this.requestUpdate()}
style="--md-sys-color-primary: var(--oscd-secondary)"
>
<md-icon slot="leading-icon" class="theirs">draft</md-icon>
${Object.keys(this.docs).map(
name =>
html`<md-select-option value="${name}"
><div slot="headline">${name}</div></md-select-option
>`,
)}
</md-filled-select>
<md-filled-text-field
label=${this.individuallyScoped ? 'From Scope' : 'Scope'}
style=${!this.individuallyScoped ? 'grid-column: 1/3;' : ''}
type="textarea"
rows="4"
id="doc1sel"
.value=${this.selectedFilter.ourSelector}
.placeholder=${this.docs[this.docName1]?.documentElement.tagName ||
':root'}
@change=${() => {
if (this.doc2sel?.placeholder) {
this.doc2sel!.placeholder = this.selector1;
}
}}
>
<md-icon slot="leading-icon">plagiarism</md-icon>
</md-filled-text-field>
${this.individuallyScoped
? html`<md-filled-text-field
label="To Scope"
style="--md-sys-color-primary: var(--oscd-secondary);"
type="textarea"
rows="4"
id="doc2sel"
.value=${this.selectedFilter.theirSelector}
.placeholder=${this.selector1}
>
<md-icon slot="leading-icon">plagiarism</md-icon>
</md-filled-text-field>`
: nothing}
<label class="individually-scoped-checkbox-label">
<md-checkbox
touch-target="wrapper"
?checked=${this.individuallyScoped}
@change=${(event: Event) => {
this.individuallyScoped = (
event.target as HTMLInputElement
).checked;
}}
></md-checkbox>
Separate From/To scopes
</label>
<md-filled-button
?disabled=${!this.docName1 || !this.docName2 || this.hashing}
class=${classMap({ 'diff-button': true, hashing: this.hashing })}
@click=${() => {
const doc1 = this.docs[this.docName1];
const doc2 = this.docs[this.docName2];
if (!doc1 || !doc2) {
return;
}
const { selectors, attributes, namespaces } = extendFilter(
this.baseFilter,
this.selectedFilter,
);
const options = { selectors, attributes, namespaces };
const ourHasher = newHasher(options);
const theirHasher = newHasher(options);
let elements: Record<
string,
{ ours?: Element; theirs?: Element }
> = {};
const shouldDiffElement = createHashElementPredicate(options);
Array.from(
this.docs[this.docName1]?.querySelectorAll(this.selector1),
)
.filter(shouldDiffElement)
.forEach(el => {
const id = identity(el);
if (!elements[id]) {
elements[id] = {};
}
elements[id].ours = el;
});
Array.from(
this.docs[this.docName1]?.querySelectorAll(
nonemptyLines(this.selector1).join(', '),
),
)
.filter(shouldDiffElement)
.forEach(el => {
const id = identity(el);
if (!elements[id]) {
elements[id] = {};
}
elements[id].ours = el;
});
Array.from(
this.docs[this.docName2]?.querySelectorAll(this.selector2),
)
.filter(shouldDiffElement)
.forEach(el => {
const id = identity(el);
if (!elements[id]) {
elements[id] = {};
}
elements[id].theirs = el;
});
Array.from(
this.docs[this.docName2]?.querySelectorAll(
nonemptyLines(this.selector2).join(', '),
),
)
.filter(shouldDiffElement)
.forEach(el => {
const id = identity(el);
if (!elements[id]) {
elements[id] = {};
}
elements[id].theirs = el;
});
if (Object.keys(elements).length === 2) {
const [
{ ours: ours1, theirs: theirs1 },
{ ours: ours2, theirs: theirs2 },
] = Object.values(elements);
const ours = ours1 || ours2;
const theirs = theirs1 || theirs2;
const ourId = ours ? identity(ours) : false;
const theirId = theirs ? identity(theirs) : false;
if (ourId && theirId && ourId !== theirId) {
elements = {
[`${ourId} -> ${theirId}`]: {
ours: elements[ourId!]?.ours,
theirs: elements[theirId!]?.theirs,
},
};
}
}
const diff = {
elements,
ourHasher,
theirHasher,
filter: this.selectedFilter,
filterName: this.selectedFilterName,
ourSelector: this.selector1,
theirSelector: this.selector2,
ourDocName: this.docName1,
theirDocName: this.docName2,
};
this.lastDiff = undefined;
this.hashing = true;
Promise.all(
Object.values(diff.elements ?? {}).map(({ ours, theirs }) => {
const ourHash =
ours && ourHasher && hashElement(ours, ourHasher);
const theirHash =
theirs && theirHasher && hashElement(theirs, theirHasher);
return Promise.all([ourHash, theirHash]);
}),
).then(() => {
this.lastDiff = diff;
this.hashing = false;
});
}}
>
Compare
${this.hashing
? html`<md-circular-progress
style="--md-circular-progress-active-indicator-color: var(--oscd-base00);"
slot="icon"
indeterminate
></md-circular-progress>`
: html`<md-icon slot="icon">difference</md-icon>`}
</md-filled-button>
<filter-dialog
filterName="${this.selectedFilterName}"
.existingFilterNames=${Object.keys(this.filters).filter(
name => name !== this.selectedFilterName,
)}
.filter=${this.selectedFilter}
@oscd-diff-filter-save=${async (event: OscdDiffFilterSaveEvent) => {
this.setFilters({
...this.filters,
[event.detail.newName]: event.detail.filter,
});
if (event.detail.newName !== event.detail.oldName) {
this.deleteFilter(event.detail.oldName);
await this.updateComplete;
this.setSelectedFilterName(event.detail.newName);
}
}}
></filter-dialog>
<base-filter-dialog
.base=${this.baseFilter}
@oscd-diff-base-filter-save=${async (
event: OscdDiffBaseFilterSaveEvent,
) => {
this.setBaseFilter(event.detail.base);
}}
></base-filter-dialog>
<info-dialog heading="SCL Comparison Tool"></info-dialog>
</div>
<div class="aside-actions-container">
<md-icon-button @click=${() => this.showInfoDialog()}
><md-icon>info</md-icon></md-icon-button
>
${this.fullscreen ? nothing : this.renderViewButtons()}
</div>
</div>
<div
id="diff-container"
@fullscreenchange=${() => this.requestUpdate()}
class=${this.fullscreen ? 'fullscreen' : ''}
>
<style>
@media print {
html,
body,
#diff-container {
background-color: white;
color: black;
font-family: var(--oscd-theme-text-font, 'Roboto');
}
.ours {
color: darkred;
}
.theirs {
color: darkgreen;
}
md-filled-icon-button {
display: none;
}
}
</style>
${this.renderFilterDescription()}
${this.fullscreen ? this.renderViewButtons() : nothing}
${this.lastDiff ? this.renderDiffTrees() : nothing}
</div>
<md-dialog
type="alert"
id="reset-warning-dialog"
@closed=${(event: CustomEvent) => {
event.preventDefault();
event.stopImmediatePropagation();
const dialog = event.target as MdDialog;
if (dialog.returnValue === 'confirm') {
localStorage.removeItem('oscd-diff-filters');
this.setFilters(defaultFilters);
this.setBaseFilter(defaultBaseFilters);
this.setSelectedFilterName(Object.keys(defaultFilters)[0]);
}
}}
>
<div slot="headline"><md-icon>warning</md-icon>Warning</div>
<form slot="content" id="warning-dialog-form" method="dialog">
This will remove any custom filters and replace them with the latest
default filters. Do you wish to reset to defaults?
</form>
<div slot="actions">
<md-text-button form="warning-dialog-form" value="cancel"
>Cancel</md-text-button
>
<md-filled-button form="warning-dialog-form" value="confirm"
>Reset</md-filled-button
>
</div>
</md-dialog>`;