Repository navigation
Expand file tree
/
Copy pathtests.js
More file actions
3432 lines (3087 loc) · 158 KB
/
Copy pathtests.js
File metadata and controls
3432 lines (3087 loc) · 158 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
// The assertions over the rendered DOM. Kept out of tests.html so that the page
// stays what it is best at being — a gallery of maps a reader can look at — and
// so that a fixture and the check that reads it are not competing for the same
// screen. Fixtures are reached by id, never by their position on the page.
// Minimal assertions over the rendered DOM.
// Errors inside timer callbacks are otherwise silent and just leave the page
// stuck on "running...", so surface them loudly.
window.addEventListener('error', function (e) {
var box = document.getElementById('results');
box.innerHTML = '<span class="fail">ERROR ' + e.message + ' @ ' +
(e.filename || '?') + ':' + e.lineno + '</span><br>' + box.innerHTML;
});
window.addEventListener('load', function () {
setTimeout(runChecks, 250);
function runChecks() {
var out = [];
var fails = 0;
/**
* Asynchronous groups register themselves here and report back through the
* function they are handed. The count used to be written out by hand, which
* was a standing trap in both directions: a group added without touching the
* number let the suite finish while that group's checks were still
* outstanding — reading as a clean pass over checks that had never run — and
* a group that forgot to report left the page on "running…" for ever.
*/
var open = [];
var registered = false; // true once every group has been reached
function group(name) {
open.push(name);
var settled = false;
return function done() {
// A group with two exits — the real-pointer lane either skips or runs —
// must release the suite once, whichever exit it takes.
if (settled) return;
settled = true;
var at = open.indexOf(name);
if (at > -1) open.splice(at, 1);
if (registered && !open.length) finish();
};
}
function check(n, label, ok) {
if (!ok) fails++;
out.push({ n: n, html: '<span class="' + (ok ? 'pass' : 'fail') + '">' +
(ok ? 'PASS' : 'FAIL') + ' ' + n + ' ' + label + '</span>' });
}
/**
* A check that could not be run at all, as against one that failed. Kept
* out of the pass count and named in the summary, so a lane that quietly
* did nothing cannot read as a lane that passed.
*/
var skipped = 0;
function skip(n, label, why) {
skipped++;
out.push({ n: n, html: '<span class="skip">SKIP ' + n + ' ' + label +
' — ' + why + '</span>' });
}
function boxRect(g) {
var m = /translate\(([-\d.]+),([-\d.]+)\)/.exec(g.getAttribute('transform')) || [0, 0, 0];
var r = g.querySelector('rect');
return { x: parseFloat(m[1]), y: parseFloat(m[2]),
w: parseFloat(r.getAttribute('width')), h: parseFloat(r.getAttribute('height')) };
}
/**
* The contrast ratio between two `rgb(...)` colours, as WCAG states it.
* Written out here rather than reached for inside the library, so a ring
* that reads only because the two of them share a mistake is not one this
* suite would call visible.
*/
function contrast(a, b) {
function light(colour) {
var p = /(\d+)[\s,]+(\d+)[\s,]+(\d+)/.exec(colour);
var weights = [0.2126, 0.7152, 0.0722];
var total = 0;
for (var i = 0; i < 3; i++) {
var c = +p[i + 1] / 255;
total += weights[i] * (c <= 0.03928 ? c / 12.92
: Math.pow((c + 0.055) / 1.055, 2.4));
}
return total;
}
var hi = light(a), lo = light(b);
if (hi < lo) { var swap = hi; hi = lo; lo = swap; }
return (hi + 0.05) / (lo + 0.05);
}
/** Whether a centre node's focus ring can be seen against its own fill. */
function readable(root) {
return contrast(
getComputedStyle(root.querySelector('.mm-root-ring')).stroke,
getComputedStyle(root.querySelector('.mm-box')).fill) >= 4.5;
}
/**
* Whether every drawn curve in one map starts on its parent's outward edge
* and finishes on its child's inward one, both at the box's vertical
* centre. Read off the path rather than recomputed, because a layout that
* placed every box correctly and drew the curves from the wrong corners
* passes every count and overlap check in the suite.
*/
// Half the indent step, which is how far in from a box's root-facing edge
// the indented shape drops its line, and the largest radius it rounds the
// turn with. Written out here rather than read off the script, which does
// not export them — copies, but ones the suite would notice going stale:
// check 246 reads the same distance off the badge, and 243 reads the whole
// step off the layout.
var SPINE_IN = 13;
var ELBOW_MAX = 6;
/**
* The two ends a curve has to meet, and where the path says it put them.
* The fanned shape sweeps from one box's outward edge to the next box's
* inward one; the indented shape drops from under the box and elbows into
* the child's root-facing edge, so what "meets its two boxes" means has to
* be read off the arrangement rather than off the string. Keyed on the
* layout and not on which form the `d` happens to be in, so an edge drawn
* in the wrong shape for its map fails here instead of being graded
* against the shape it drew.
*/
function edgeEnds(state, node, child) {
var d = child.edge.getAttribute('d');
var p = boxRect(node.el), k = boxRect(child.el);
var outward = (k.x + k.w / 2) > (p.x + p.w / 2);
if (state.opts.layout === 'indent' && child.depth > 1) {
var e = /^M([^,]+),([^ ]+) V([^ ]+) Q([^,]+),([^ ]+) ([^,]+),([^ ]+) H(.+)$/
.exec(d);
if (!e) return null;
var spine = outward ? p.x + SPINE_IN : p.x + p.w - SPINE_IN;
var from = p.y + p.h; // the underside it leaves
var centre = k.y + k.h / 2; // the line it has to arrive on
var into = outward ? k.x : k.x + k.w;
// The corner is rounded, so the drop stops short of the centre line and
// the turn ends short of the child — by the same radius, worked out the
// way the drawing works it out. Every coordinate the path carries is
// named below: an elbow that turned or ended at the wrong height used
// to pass this check, because only the ends of it were read.
var r = Math.max(0, Math.min(ELBOW_MAX,
Math.abs(centre - from) / 2, Math.abs(into - spine)));
var down = centre < from ? -1 : 1;
var out = into < spine ? -1 : 1;
return {
got: [e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8]],
want: [spine, from, // leaves the underside, on the line
centre - down * r, // drops to just short of the centre
spine, centre, // turns about the corner itself
spine + out * r, centre, // comes out of the turn on the line
into] // and runs into the child's edge
};
}
var c = /^M([^,]+),([^ ]+) C[^ ]+ [^ ]+ ([^,]+),(.+)$/.exec(d);
if (!c) return null;
return {
got: [c[1], c[2], c[3], c[4]],
want: [outward ? p.x + p.w : p.x, p.y + p.h / 2,
outward ? k.x : k.x + k.w, k.y + k.h / 2]
};
}
function edgesMeetBoxes(map) {
var state = map.mindMap;
if (!state) return false;
var ok = true;
(function walk(node) {
for (var i = 0; i < node.children.length; i++) {
var child = node.children[i];
if (child.edge && child.edge.style.display !== 'none') {
var ends = edgeEnds(state, node, child);
if (!ends) ok = false;
else {
for (var j = 0; j < ends.want.length; j++) {
// The transforms are rounded to two places and the path is not,
// so they meet to within half of the last place kept.
if (Math.abs(parseFloat(ends.got[j]) - ends.want[j]) > 0.02) ok = false;
}
}
}
walk(child);
}
})(state.root);
return ok;
}
/** Whether a selector list names `wanted` among its alternatives. */
function claims(list, wanted) {
var parts = String(list).split(',');
for (var i = 0; i < parts.length; i++) {
if (parts[i].replace(/^\s+|\s+$/g, '') === wanted) return true;
}
return false;
}
/**
* What a rule inside a media block declares for one property, or '' when
* there is no such rule. Several of the states this suite cares about
* cannot be entered to be measured in — a page cannot be asked to print,
* and a tab that reports a pointer cannot be asked to stop reporting one —
* so for those the declaration is the whole of what there is to check.
*/
function declaredIn(media, selector, prop) {
var blocks = mediaBlocks(media);
var value = '';
for (var i = 0; i < blocks.length; i++) {
var rules = blocks[i].cssRules;
for (var j = 0; j < rules.length; j++) {
var rule = rules[j];
if (!rule.selectorText || !claims(rule.selectorText, selector)) continue;
var declared = rule.style.getPropertyValue(prop);
if (declared) value = declared;
}
}
return value;
}
/** The injected media blocks whose query mentions `media`. */
function mediaBlocks(media) {
var sheet = document.getElementById('mind-maps-helper-styles').sheet;
var found = [];
for (var i = 0; i < sheet.cssRules.length; i++) {
var group = sheet.cssRules[i];
if (group.media && group.media.mediaText.indexOf(media) > -1) found.push(group);
}
return found;
}
/**
* What the page computes when a media block it cannot be made to match is
* widened to match everything. The legibility preferences and reduced
* motion are the reader's own settings, so the rules answering them would
* otherwise only ever be read off the sheet rather than seen to reach a
* drawn map. Restored in a finally: a sheet left widened would quietly
* rewrite every check after this one.
*/
function underMedia(media, read) {
var blocks = mediaBlocks(media);
if (!blocks.length) return null;
var wanted = blocks[0].media.mediaText;
try {
blocks[0].media.mediaText = 'all';
return read();
} finally {
blocks[0].media.mediaText = wanted;
}
}
/**
* Whether the injected sheet drops `selector` from a printed page. What
* this still catches, for all that it reads a declaration rather than a
* printed page: the rule dropped, or aimed at a selector nothing carries.
*/
function printHides(selector) {
return declaredIn('print', selector, 'display') === 'none';
}
// ---- reaching a fixture
//
// By name, never by position. These used to index the live `.case`
// NodeList, so inserting a fixture anywhere near the top quietly pointed a
// dozen later assertions at the wrong map — no syntax error, no clue in the
// failure. Every fixture carries an id; that id is its identity, and the
// heading numbers are only for reading.
/** A fixture by id, or an element passed straight through. */
function scopeOf(where) {
var el = typeof where === 'string' ? document.getElementById(where) : where;
if (!el) throw new Error('no fixture named "' + where + '"');
return el;
}
function svgOf(where) { return scopeOf(where).querySelector('.mm-svg'); }
function boxes(where) { return scopeOf(where).querySelectorAll('.mm-box'); }
function errOf(where) { return scopeOf(where).querySelector('.mm-error'); }
function nodesIn(where) {
return Array.prototype.slice.call(scopeOf(where).querySelectorAll('.mm-node'));
}
function labels(where) {
return Array.prototype.map.call(
scopeOf(where).querySelectorAll('.mm-label'),
function (t) { return t.textContent; });
}
/** The labels of the nodes a fold has left on screen. */
function visibleLabels(where) {
return nodesIn(where).filter(function (g) {
return g.style.display !== 'none';
}).map(function (g) { return g.querySelector('.mm-label').textContent; });
}
/** Every node whose label is exactly `label`. */
function nodesNamed(where, label) {
return nodesIn(where).filter(function (g) {
return g.querySelector('.mm-label').textContent === label;
});
}
/** The first node whose label is exactly `label`. */
function nodeIn(where, label) { return nodesNamed(where, label)[0]; }
/**
* The node whose label merely contains `part` — separate from nodeIn on
* purpose. Five copies of this helper had drifted into two different
* contracts, and which one a group got was a matter of where it sat.
*/
function nodeMatching(where, part) {
return nodesIn(where).filter(function (g) {
return g.querySelector('.mm-label').textContent.indexOf(part) > -1;
})[0];
}
/** Where a node is drawn, read off its transform. */
function posOf(g) {
var m = /translate\(([-\d.]+),([-\d.]+)\)/.exec(g.getAttribute('transform'));
return { x: parseFloat(m[1]), y: parseFloat(m[2]) };
}
/**
* A pointer-event dispatcher bound to one pointerId. Groups keep their own
* ids rather than sharing one: to the library, two groups on the same id
* are one finger in two places at once.
*/
function pointerFor(id) {
return function (el, type, x, y) {
el.dispatchEvent(new PointerEvent(type, {
bubbles: true, cancelable: true, pointerId: id, clientX: x, clientY: y, button: 0
}));
};
}
// ---- waiting for a map to stop moving
var WAIT_LIMIT = 5000;
/**
* Polls `ready` until it holds, then runs `cb` — and runs `cb` anyway once
* WAIT_LIMIT is up, so a condition that never comes true fails its own
* check rather than stalling the whole suite behind it.
*/
function until(ready, cb) {
var started = Date.now();
setTimeout(function poll() {
if (ready() || Date.now() - started > WAIT_LIMIT) cb();
else setTimeout(poll, 16);
}, 0);
}
function mapState(where) {
var el = scopeOf(where);
var box = el.mindMap ? el : el.querySelector('.mm-container');
return box ? box.mindMap : null;
}
/**
* Runs `cb` once the map has finished the re-layout it is in the middle of.
* Groups used to wait out a fixed 420ms — ANIM_MS plus a margin, a constant
* from mindmap.js copied into the suite where nothing could keep it honest.
* Changing the animation timing would have made the suite flaky rather than
* red. Reading the state the animation itself clears is both exact and
* quicker: under reduced motion there is nothing to wait for at all.
*/
function settled(where, cb) {
until(function () {
var st = mapState(where);
return !st || !st.animation.frame;
}, cb);
}
/** True once every image in the map has measured or given up on loading. */
function imagesResolved(where) {
var st = mapState(where);
if (!st) return false;
var all = true;
(function walk(n) {
for (var i = 0; i < n.runs.length; i++) {
var run = n.runs[i];
if (run.type !== 'image' || (run.askedW && run.askedH)) continue;
if (!run.natW && !run.broken) all = false;
}
for (var j = 0; j < n.children.length; j++) walk(n.children[j]);
})(st.root);
return all;
}
// The heading numbers are for the reader, not for the assertions — those
// reach a fixture by id. They are still worth keeping in order, since a
// reader matching a failure to a map on the page goes by them, and an id is
// what makes that possible at all.
(function () {
var numbered = Array.prototype.filter.call(document.querySelectorAll('h2'),
function (h) { return /^\d+\./.test(h.textContent); });
var inOrder = numbered.every(function (h, i) {
return parseInt(h.textContent, 10) === i + 1;
});
var everyCaseNamed = Array.prototype.every.call(
document.querySelectorAll('.case'), function (c) { return !!c.id; });
check(202, 'the cases are numbered in order and every one has an id',
numbered.length > 0 && inOrder && everyCaseNamed);
})();
check(1, 'single node -> 1 box', boxes('single').length === 1);
check(2, 'root+child -> 2 boxes, 1 edge',
boxes('one-child').length === 2 &&
scopeOf('one-child').querySelectorAll('.mm-edge').length === 1);
// Case 3: two branches, one each side of the root.
(function () {
var svg = svgOf('two-branches');
var rootX = boxRect(svg.querySelector('.mm-root')).x;
var xs = [];
Array.prototype.forEach.call(svg.querySelectorAll('.mm-node'), function (g) {
if (!g.classList.contains('mm-root')) xs.push(boxRect(g).x);
});
check(3, 'branches straddle the root',
xs.length === 2 && xs.some(function (x) { return x < rootX; })
&& xs.some(function (x) { return x > rootX; }));
})();
check(4, 'uneven: 10 boxes', boxes('uneven').length === 10);
// Case 4: the split goes by leaf count, so the six-leaf branch outweighs
// the two branches under it put together and crosses on its own. Asserting
// the partition rather than the box count, because a refactor that put
// every branch on one side would still draw ten boxes.
(function () {
var svg = svgOf('uneven');
var root = boxRect(svg.querySelector('.mm-root'));
function sideOf(name) {
var g = Array.prototype.filter.call(svg.querySelectorAll('.mm-node'), function (n) {
return n.querySelector('.mm-label').textContent === name;
})[0];
if (!g) return 'missing';
var r = boxRect(g);
return r.x >= root.x + root.w ? 'right' :
r.x + r.w <= root.x ? 'left' : 'astride';
}
check(158, 'the heavy branch outweighs both light ones and crosses alone',
sideOf('Heavy') === 'right' && sideOf('a') === 'right' && sideOf('f') === 'right' &&
sideOf('Light') === 'left' && sideOf('Also light') === 'left');
})();
// Every map on the page, not one fixture: the curves are what a reader
// follows, and nothing else in the suite looks at where they land.
(function () {
var maps = Array.prototype.filter.call(
document.querySelectorAll('.mm-container'),
function (map) { return !!map.mindMap; });
check(159, 'every curve meets its two boxes, in every map on the page',
maps.length >= 40 && maps.every(edgesMeetBoxes));
})();
// A named centre survives the two things that could take it away: a theme
// pinned against the machine's own, since the colour is inline on the node
// and the theme's is not; and the shape switch, which is the one re-render
// that re-runs `assignSides` and could plausibly repaint the centre with
// it. Placed after check 159 so the switch below cannot leave a map
// mid-animation while that one walks every map on the page.
(function () {
var done = group('a named centre through a re-layout');
var host = document.getElementById('rootcolourdark');
var container = host.querySelector('.mm-container');
function colours() {
var root = container.querySelector('.mm-root');
return getComputedStyle(root.querySelector('.mm-box')).fill + ' / ' +
getComputedStyle(root.querySelector('.mm-label')).fill;
}
var pinned = colours();
MindMap.setDirection(container, 'right');
settled('rootcolourdark', function () {
check(214, 'a named centre keeps its colours in a pinned theme, and ' +
'through the shape switch',
pinned === 'rgb(111, 192, 207)' + ' / ' + 'rgb(22, 27, 34)' &&
colours() === pinned);
done();
});
})();
check(5, 'deep nesting: 7 boxes', boxes('deep').length === 7);
// Case 6: no two boxes overlap.
(function () {
var rects = Array.prototype.map.call(
scopeOf('tall-short').querySelectorAll('.mm-node'), boxRect);
var overlap = false;
for (var i = 0; i < rects.length; i++) {
for (var j = i + 1; j < rects.length; j++) {
var a = rects[i], b = rects[j];
if (a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h) {
overlap = true;
}
}
}
check(6, 'no overlapping boxes', !overlap);
})();
check(7, 'mixed indent: 5 boxes', boxes('mixed-indent').length === 5);
(function () {
var l = labels('bullets');
check(8, 'bullets stripped, comment dropped',
l.length === 5 &&
l.indexOf('Bulleted root') > -1 && l.indexOf('Star bullet') > -1 &&
l.indexOf('Plus bullet') > -1 && l.indexOf('Nested dash') > -1 &&
l.join('|').indexOf('comment') === -1);
})();
check(9, 'indented source: 4 boxes', boxes('indented-source').length === 4);
(function () {
var multiline = Array.prototype.some.call(
scopeOf('long-labels').querySelectorAll('.mm-label'),
function (label) {
var ys = {};
Array.prototype.forEach.call(label.querySelectorAll('text'), function (t) {
ys[t.getAttribute('y')] = 1;
});
return Object.keys(ys).length > 1;
});
check(10, 'long label wraps to >1 line', multiline);
})();
// --- one left edge down a wrapped label ---
//
// Lines used to be centred within their box, which started every line of a
// wrapped label at a different x. What is read below is the edge itself: a
// common inset, an inset that is the padding an unwrapped node already
// gets, and a centre node held to the same rule as the branches.
(function () {
/**
* Each line of a label, as the x its ink starts at and the x it ends at.
* Lines are told apart by baseline, which every <text> on one line
* shares.
*
* A code chip is the reason this reads more than the text. The chip is
* drawn at the line's origin and its text a padding inside that, so a
* line led by a chip has text 3.5px further right than a line led by a
* word — and read off the <text> alone the two would look misaligned
* while the drawn edge was straight. What stands on the edge is the
* leftmost thing drawn, chip or word.
*/
function linesOf(g) {
var byBaseline = {};
Array.prototype.forEach.call(
g.querySelectorAll('.mm-label text'), function (t) {
var y = t.getAttribute('y');
var x = parseFloat(t.getAttribute('x'));
var line = byBaseline[y] || (byBaseline[y] = { start: x, end: x });
line.start = Math.min(line.start, x);
line.end = Math.max(line.end, x + t.getComputedTextLength());
});
// A chip belongs to the line whose baseline it encloses — read that way
// rather than from the ratios the drawing sizes it by, so the check
// does not break the day one of those ratios is tuned.
Array.prototype.forEach.call(
g.querySelectorAll('.mm-label .mm-code-chip'), function (c) {
var top = parseFloat(c.getAttribute('y'));
var bottom = top + parseFloat(c.getAttribute('height'));
var x = parseFloat(c.getAttribute('x'));
Object.keys(byBaseline).forEach(function (y) {
var baseline = parseFloat(y);
if (baseline < top || baseline > bottom) return;
byBaseline[y].start = Math.min(byBaseline[y].start, x);
byBaseline[y].end =
Math.max(byBaseline[y].end, x + parseFloat(c.getAttribute('width')));
});
});
return Object.keys(byBaseline).map(function (y) { return byBaseline[y]; });
}
function flushLeft(lines) {
return lines.every(function (l) {
return Math.abs(l.start - lines[0].start) < 0.01;
});
}
var wrapped = nodesIn('leftedge').filter(function (g) {
return linesOf(g).length > 1;
});
// Lines of the same width sit at the same x however they are aligned, so
// an edge read off a label that happens to wrap evenly proves nothing.
// At least one label has to be visibly ragged for the checks to bite.
var ragged = wrapped.some(function (g) {
var ends = linesOf(g).map(function (l) { return l.end; });
return Math.max.apply(null, ends) - Math.min.apply(null, ends) > 4;
});
check(239, 'every line of a wrapped label starts at the same x',
wrapped.length >= 2 && ragged &&
wrapped.every(function (g) { return flushLeft(linesOf(g)); }));
// The centre node is excepted from plenty — it takes no fold badge, no
// branch accent, and a focus ring of its own — so being held to the
// branches' alignment is worth stating rather than assuming.
var centre = scopeOf('leftedge').querySelector('.mm-root');
check(240, 'a wrapped centre node is no exception to the edge',
linesOf(centre).length > 1 && flushLeft(linesOf(centre)));
// Not merely *an* edge: the one an unwrapped node at the same depth
// already stands on, which is the box's own padding. Left at x=0 the
// lines would share an edge too, and sit against the side of the box.
var short = nodeIn('leftedge', 'Short');
var branches = wrapped.filter(function (g) {
return !g.classList.contains('mm-root');
});
check(241, 'that edge is the padding an unwrapped label already sits at',
branches.length > 0 && linesOf(short).length === 1 &&
branches.every(function (g) {
return Math.abs(linesOf(g)[0].start - linesOf(short)[0].start) < 0.01;
}));
// On a line led by a code span the chip is the ink at the edge and its
// text sits a padding inside — so the two disagree about where the line
// starts, and only one of them is the edge the reader sees. Stated on its
// own because it is also what keeps the reading above honest: a fixture
// that stopped wrapping a chip onto a line of its own would exercise none
// of that half of `linesOf`, and 239 would pass on the text alone.
var edge = linesOf(short)[0].start;
var chipped = nodeMatching('leftedge', 'pushing');
var chips = Array.prototype.map.call(
chipped.querySelectorAll('.mm-label .mm-code-chip'), function (c) {
var top = parseFloat(c.getAttribute('y'));
return {
x: parseFloat(c.getAttribute('x')),
top: top,
bottom: top + parseFloat(c.getAttribute('height'))
};
});
var texts = Array.prototype.map.call(
chipped.querySelectorAll('.mm-label text'), function (t) {
return {
x: parseFloat(t.getAttribute('x')),
baseline: parseFloat(t.getAttribute('y')),
code: t.classList.contains('mm-code')
};
});
// The chip and the text it holds, tied by the band the baseline falls
// in and by that text being code — not merely by sitting somewhere
// below. Paired loosely, a chip correctly on the edge could vouch for a
// text on another line entirely, and a pairing that had come apart
// would read as intact.
var ledByChip = chips.filter(function (chip) {
return Math.abs(chip.x - edge) < 0.01 && texts.some(function (t) {
return t.code && t.baseline >= chip.top && t.baseline <= chip.bottom &&
t.x > chip.x + 1;
});
});
check(242, 'a chip-led line stands the chip on the edge, not its text',
ledByChip.length > 0 &&
texts.every(function (t) { return t.x >= edge - 0.01; }));
})();
(function () {
function allOneSide(where, side) {
var svg = svgOf(where);
var root = boxRect(svg.querySelector('.mm-root'));
return Array.prototype.every.call(svg.querySelectorAll('.mm-node'), function (g) {
if (g.classList.contains('mm-root')) return true;
var x = boxRect(g).x;
return side > 0 ? x >= root.x + root.w : x <= root.x;
});
}
check(11, 'direction=right keeps all nodes right', allOneSide('dir-right', 1));
check(12, 'direction=left keeps all nodes left', allOneSide('dir-left', -1));
})();
(function () {
var wide = Array.prototype.some.call(boxes('width-gap'), function (r) {
return parseFloat(r.getAttribute('width')) > 130;
});
check(13, 'max-node-width honoured', !wide);
})();
check(14, 'fenced code block rendered',
!!svgOf('fenced') && boxes('fenced').length === 4 &&
!scopeOf('fenced').querySelector('pre'));
check(15, 'div.mindmap rendered', !!svgOf('div-form') && boxes('div-form').length === 3);
check(16, 'palette wraps: 11 boxes', boxes('palette-wrap').length === 11);
check(17, 'two roots -> error mentioning the line',
!!errOf('err-two-roots') &&
errOf('err-two-roots').textContent.indexOf('Second root') > -1);
check(18, 'empty -> error', !!errOf('err-empty') &&
errOf('err-empty').textContent.toLowerCase().indexOf('empty') > -1);
check(19, 'bare bullet -> error', !!errOf('err-bare-bullet'));
(function () {
var hidden = document.querySelectorAll('.mm-a11y a');
var visible = document.querySelectorAll('.mm-svg a.mm-link');
check(109, 'the hidden outline costs no tab stops',
hidden.length > 0 && visible.length > 0 &&
Array.prototype.every.call(hidden, function (a) {
return a.getAttribute('tabindex') === '-1';
}));
})();
(function () {
var deep = document.getElementById('toodeep');
check(99, 'nesting past the depth limit is an error, not a crash',
!!deep.querySelector('.mm-error') &&
deep.textContent.indexOf('100 deep') > -1 &&
deep.textContent.indexOf('Line ') > -1);
var viewBoxes = Array.prototype.map.call(
document.querySelectorAll('#badopts .mm-svg'),
function (svg) { return svg.getAttribute('viewBox'); });
check(105, 'an unusable dimension does not reach the drawing',
viewBoxes.length === 3 && viewBoxes.every(function (vb) {
return /^0 0 \d+(\.\d+)? \d+(\.\d+)?$/.test(vb);
}));
check(106, 'it falls back to the default, which the third map uses',
viewBoxes[0] === viewBoxes[2] && viewBoxes[1] === viewBoxes[2]);
// Rendered here rather than on load, so the rest of the gallery keeps
// the built-in accents to look at.
var saved = MindMap.palette;
MindMap.palette = [['#ff0000', '#00ff00']];
var custom = MindMap.render(document.getElementById('pal-custom'));
MindMap.palette = ['not a pair'];
var fallback = MindMap.render(document.getElementById('pal-bad'));
// A pair whose bright half is dark. Nothing stops a site assigning one,
// and the centre node is the only box that fills with a palette colour
// and writes on top of it, so it is the only one that can lose its label.
MindMap.palette = [['#ffffff', '#161b22']];
var inked = MindMap.render(document.getElementById('pal-ink'));
// The same pair written the way an author reaching for words would write
// it. `MindMap.palette` takes any colour string CSS takes, and a value
// the ink cannot read is a label — and now a focus ring — lost in its
// own box.
MindMap.palette = [['white', 'navy']];
var worded = MindMap.render(document.getElementById('pal-word'));
// A colour the page alone could work out. It reaches the box, because
// SVG resolves it where the box sits, but nothing outside the document
// can say what it came to — so the ink takes the documented fallback
// rather than a guess.
MindMap.palette = [['white', 'var(--brand, #4a2f6b)']];
var unresolved = MindMap.render(document.getElementById('pal-unresolved'));
// The other half of that: a value a canvas outside the document answers
// rather than declines, and answers with black however the page has its
// text set. Confidently wrong is worse than unreadable, so it has to be
// turned away rather than trusted.
MindMap.palette = [['white', 'currentColor']];
var inherited = MindMap.render(document.getElementById('pal-current'));
MindMap.palette = saved;
var painted = custom.querySelector('.mm-node:not(.mm-root)');
check(107, 'an assigned palette reaches the branches and a named centre',
painted.style.getPropertyValue('--mm-a') === '#ff0000' &&
painted.style.getPropertyValue('--mm-a-dark') === '#00ff00' &&
custom.querySelector('.mm-edge').style.getPropertyValue('--mm-a') === '#ff0000' &&
custom.querySelector('.mm-root').style.getPropertyValue('--mm-root-bg') ===
'#00ff00');
check(108, 'an unusable palette falls back to the built-in one',
fallback.querySelector('.mm-node:not(.mm-root)')
.style.getPropertyValue('--mm-a') === '#3b6ea5');
check(213, 'a dark colour in the bright half turns the centre ink white',
inked.querySelector('.mm-root').style.getPropertyValue('--mm-root-bg') ===
'#161b22' &&
inked.querySelector('.mm-root').style.getPropertyValue('--mm-root-text') ===
'#ffffff');
check(220, 'a colour word in the bright half is read, not guessed at',
worded.querySelector('.mm-root').style.getPropertyValue('--mm-root-bg') ===
'navy' &&
worded.querySelector('.mm-root').style.getPropertyValue('--mm-root-text') ===
'#ffffff');
check(223, 'a colour only the page could read falls back rather than guessing',
unresolved.querySelector('.mm-root').style.getPropertyValue('--mm-root-text') ===
'#161b22' &&
inherited.querySelector('.mm-root').style.getPropertyValue('--mm-root-text') ===
'#161b22');
// The centre's focus ring is drawn in that ink, so a replaced palette
// that darkens the box takes the ring along with the label rather than
// leaving it to disappear into the fill.
check(219, 'a replaced palette carries the centre focus ring with the ink',
readable(inked.querySelector('.mm-root')) &&
readable(worded.querySelector('.mm-root')) &&
readable(custom.querySelector('.mm-root')));
var refreshHost = document.getElementById('embedrefresh');
function embedText() {
return refreshHost.querySelector('.mm-embed-body').textContent.trim();
}
var before = embedText();
document.getElementById('src-editable').content.firstElementChild
.textContent = 'After, and a good deal wider than it was';
var refreshed = MindMap.refresh(refreshHost);
check(102, 'refresh re-reads the source element it was given',
before === 'Before' && refreshed === true &&
embedText().indexOf('After') === 0);
check(103, 'the branch renames itself after the content changed',
refreshHost.querySelector('.mm-node[role="button"],.mm-toggle[role="button"]')
.getAttribute('aria-label').indexOf('After') === 0);
// The outline is a copy of the labels, not a live view of them, so a
// refresh that leaves it alone leaves a screen reader on the old map
// while everyone else reads the new one.
var refreshOutline = refreshHost.querySelector('.mm-a11y');
check(191, 'the hidden outline is rebuilt with the content that changed',
refreshOutline.textContent.indexOf('After') > -1 &&
refreshOutline.textContent.indexOf('Before') === -1 &&
// Still the whole tree, not just the block that moved.
refreshOutline.textContent.indexOf('Child') > -1 &&
// And still one outline, not one per refresh.
refreshHost.querySelectorAll('.mm-a11y').length === 1);
check(104, 'a second refresh with nothing changed reports no change',
MindMap.refresh(refreshHost) === false);
var maps = document.getElementById('isolation').children;
check(100, 'a map that fails unexpectedly shows an error box',
maps.length === 3 && !!maps[1].querySelector('.mm-error') &&
!maps[1].querySelector('.mm-svg'));
check(101, 'the maps either side of it still drew',
!!maps[0].querySelector('.mm-svg') && !!maps[2].querySelector('.mm-svg'));
})();
(function () {
var l = labels('special-chars').join('|');
check(20, 'special chars kept as text',
l.indexOf('a < b > c') > -1 && l.indexOf('x --> y') > -1 &&
l.indexOf('100% "quoted"') > -1);
})();
(function () {
var track = getComputedStyle(document.getElementById('gridhost')).gridTemplateColumns;
check(21, 'grid track stays 260px (was blown out by svg min-width)',
track.indexOf('260px') === 0);
var flexhost = document.getElementById('flexhost');
var fixedSibling = flexhost.lastElementChild;
check(22, 'flex row does not overflow; fixed sibling keeps its 200px',
flexhost.scrollWidth <= flexhost.clientWidth + 1 &&
Math.round(fixedSibling.getBoundingClientRect().width) === 200);
})();
(function () {
function hostCheck(n, id, label, roots) {
var host = document.getElementById(id);
var ok = host.querySelectorAll('.mm-container').length === 1 &&
host.querySelectorAll('.mm-box').length === roots &&
!host.querySelector('pre') && !host.querySelector('code') &&
!host.querySelector('.highlight') &&
!host.querySelector('[class*="language-"]');
check(n, label, ok);
}
hostCheck(23, 'rouge', 'Rouge shape renders, wrappers removed', 3);
hostCheck(24, 'prism', 'Prism shape renders, wrappers removed', 3);
hostCheck(25, 'markbind', 'MarkBind shape renders, wrappers removed', 3);
hostCheck(26, 'nested', 'nested match renders exactly once', 2);
})();
// Theme resolution: host signals must beat the system preference, and a
// per-map data-theme must beat the host.
(function () {
var root = document.documentElement;
var saved = root.getAttribute('data-dark-mode');
var host = document.createElement('div');
host.innerHTML = '<pre class="mindmap">Theme\n child</pre>' +
'<pre class="mindmap" data-theme="dark">Theme\n child</pre>' +
'<pre class="mindmap" data-theme="light">Theme\n child</pre>';
document.body.appendChild(host);
MindMap.renderAll(host);
var maps = host.querySelectorAll('.mm-container');
function surface(el) { return getComputedStyle(el).getPropertyValue('--mm-surface').trim(); }
var LIGHT = '#ffffff', DARK = '#1b2027';
root.setAttribute('data-dark-mode', 'true');
var darkHost = surface(maps[0]) === DARK;
var ownLightWins = surface(maps[2]) === LIGHT;
root.setAttribute('data-dark-mode', 'false');
var lightHost = surface(maps[0]) === LIGHT;
var ownDarkWins = surface(maps[1]) === DARK;
if (saved === null) root.removeAttribute('data-dark-mode');
else root.setAttribute('data-dark-mode', saved);
host.remove();
check(27, 'host data-dark-mode=true makes the map dark', darkHost);
check(28, 'host data-dark-mode=false makes the map light', lightHost);
check(29, 'per-map data-theme beats the host', ownLightWins && ownDarkWins);
})();
// Collapse / expand. Animation is ~300ms, so these await settling.
(function () {
var done = group('collapse');
var host = document.getElementById('collapse');
var toggles = host.querySelectorAll('.mm-interactive');
check(30, 'a toggle on each of the 3 nodes with children', toggles.length === 3);
check(31, 'root has no toggle', !host.querySelector('.mm-root.mm-interactive'));
check(32, 'everything visible initially', visibleLabels('collapse').length === 9);
var reqs = Array.prototype.filter.call(toggles, function (g) {
return g.querySelector('.mm-label').textContent === 'Requirements';
})[0];
var before = host.querySelector('.mm-svg').getAttribute('viewBox');
reqs.dispatchEvent(new MouseEvent('click', { bubbles: true }));
settled('collapse', function () {
var after = visibleLabels('collapse');
check(33, 'collapsing hides just that subtree',
after.length === 7 && after.indexOf('Stakeholders') === -1 &&
after.indexOf('User Stories') === -1 && after.indexOf('Architecture') > -1);
check(34, 'collapsed node is marked', reqs.classList.contains('mm-collapsed') &&
reqs.getAttribute('aria-expanded') === 'false');
check(35, 'canvas shrank', host.querySelector('.mm-svg').getAttribute('viewBox') !== before);
reqs.dispatchEvent(new MouseEvent('click', { bubbles: true }));
settled('collapse', function () {
check(36, 'expanding brings it back', visibleLabels('collapse').length === 9 &&
reqs.getAttribute('aria-expanded') === 'true');
check(37, 'collapse-level=1 shows only root + branches',
visibleLabels('preset').length === 3);
check(38, 'data-interactive=false has no toggles',
document.getElementById('static').querySelectorAll('.mm-interactive').length === 0 &&
document.getElementById('static').querySelectorAll('.mm-toggle').length === 0);
MindMap.collapseAll(document.getElementById('collapse').querySelector('.mm-container'));
settled('collapse', function () {
check(39, 'collapseAll leaves root + branches',
visibleLabels('collapse').length === 4);
done();
});
});
});
})();
// Dragging.
(function () {
var done = group('drag');
var host = document.getElementById('drag');
function nodeNamed(name) { return nodeIn(host, name); }
var pos = posOf;
var pointer = pointerFor(1);
check(110, 'a draggable node leaves vertical page scrolling alone',
getComputedStyle(host.querySelector('.mm-draggable')).touchAction === 'pan-y');
check(40, 'every node including the root is draggable',
host.querySelectorAll('.mm-draggable').length === 6 &&
!!host.querySelector('.mm-root.mm-draggable'));
var req = nodeNamed('Requirements');
var kid = nodeNamed('Stakeholders');
var sibling = nodeNamed('Design');
var reqBefore = pos(req), kidBefore = pos(kid), siblingBefore = pos(sibling);
var r = req.getBoundingClientRect();
pointer(req, 'pointerdown', r.left + 5, r.top + 5);
pointer(req, 'pointermove', r.left + 45, r.top + 35);
pointer(req, 'pointerup', r.left + 45, r.top + 35);
var reqAfter = pos(req), kidAfter = pos(kid);
check(41, 'the dragged node moved',
Math.abs(reqAfter.x - reqBefore.x) > 10 && Math.abs(reqAfter.y - reqBefore.y) > 5);
check(42, 'its subtree moved by the same amount',
Math.abs((kidAfter.x - kidBefore.x) - (reqAfter.x - reqBefore.x)) < 0.6 &&
Math.abs((kidAfter.y - kidBefore.y) - (reqAfter.y - reqBefore.y)) < 0.6);
var siblingAfter = pos(sibling);
check(43, 'an unrelated branch stayed put',
Math.abs(siblingAfter.x - siblingBefore.x) < 0.001 &&
Math.abs(siblingAfter.y - siblingBefore.y) < 0.001 &&
!sibling.classList.contains('mm-dragging'));
// A drag must not fire the collapse toggle.
var visAfterDrag = Array.prototype.filter.call(
host.querySelectorAll('.mm-node'), function (g) { return g.style.display !== 'none'; }).length;
check(44, 'dragging did not collapse the node', visAfterDrag === 6);
// A press that barely moves is still a click.
var r2 = req.getBoundingClientRect();
pointer(req, 'pointerdown', r2.left + 5, r2.top + 5);
pointer(req, 'pointermove', r2.left + 6, r2.top + 6);
pointer(req, 'pointerup', r2.left + 6, r2.top + 6);
req.dispatchEvent(new MouseEvent('click', { bubbles: true }));
settled('drag', function () {
var vis = Array.prototype.filter.call(host.querySelectorAll('.mm-node'),
function (g) { return g.style.display !== 'none'; }).length;
check(45, 'a near-still press still toggles', vis === 4);
// Re-expand first: the collapse above legitimately changed the layout,
// so only a fully expanded map is comparable with the starting one.
var container = host.querySelector('.mm-container');
MindMap.expandAll(container);
MindMap.resetPositions(container);
settled('drag', function () {
var back = pos(nodeNamed('Requirements'));
var model = container.mindMap.root.children.filter(function (n) {
return n.label === 'Requirements';