-
-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathmd-editor-edit-integ-test.js
More file actions
1530 lines (1269 loc) · 66.3 KB
/
Copy pathmd-editor-edit-integ-test.js
File metadata and controls
1530 lines (1269 loc) · 66.3 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
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
/*global describe, beforeAll, beforeEach, afterAll, awaitsFor, it, awaitsForDone, expect*/
define(function (require, exports, module) {
const SpecRunnerUtils = require("spec/SpecRunnerUtils");
const mdTestFolder = SpecRunnerUtils.getTestPath("/spec/LiveDevelopment-Markdown-test-files");
let testWindow, brackets, CommandManager, Commands, EditorManager, WorkspaceManager,
LiveDevMultiBrowser;
function _getMdPreviewIFrame() {
return testWindow.document.getElementById("panel-md-preview-frame");
}
function _getMdIFrameDoc() {
const mdIFrame = _getMdPreviewIFrame();
return mdIFrame && mdIFrame.contentDocument;
}
function _getMdIFrameWin() {
const mdIFrame = _getMdPreviewIFrame();
return mdIFrame && mdIFrame.contentWindow;
}
async function _enterEditMode() {
const win = _getMdIFrameWin();
// Force reader→edit transition to ensure enterEditMode runs in editor.js
// (attaches checkboxHandler, inputHandler, etc.)
if (win && win.__setEditModeForTest) {
win.__setEditModeForTest(false);
win.__setEditModeForTest(true);
}
await awaitsFor(() => {
const mdDoc = _getMdIFrameDoc();
if (!mdDoc) { return false; }
const content = mdDoc.getElementById("viewer-content");
return content && content.classList.contains("editing");
}, "edit mode to activate");
}
async function _enterReaderMode() {
const win = _getMdIFrameWin();
if (win && win.__setEditModeForTest) {
win.__setEditModeForTest(false);
}
await awaitsFor(() => {
const mdDoc = _getMdIFrameDoc();
if (!mdDoc) { return false; }
const content = mdDoc.getElementById("viewer-content");
return content && !content.classList.contains("editing");
}, "reader mode to activate");
}
async function _waitForMdPreviewReady(editor) {
await awaitsFor(() => {
const mdIFrame = _getMdPreviewIFrame();
if (!mdIFrame || mdIFrame.style.display === "none") { return false; }
if (!mdIFrame.src || !mdIFrame.src.includes("mdViewer")) { return false; }
const win = mdIFrame.contentWindow;
if (!win || typeof win.__setEditModeForTest !== "function") { return false; }
if (win.__isSuppressingContentChange && win.__isSuppressingContentChange()) { return false; }
const content = mdIFrame.contentDocument && mdIFrame.contentDocument.getElementById("viewer-content");
if (!content || content.children.length === 0) { return false; }
const activeEditor = EditorManager.getActiveEditor();
if (!activeEditor) { return false; }
// Re-read editor content each iteration — content sync from a previous
// test's DOM edit can modify the document asynchronously (debounced postMessage).
const expectedSrc = activeEditor.document.getText();
if (expectedSrc) {
const viewerSrc = win.__getCurrentContent && win.__getCurrentContent();
if (viewerSrc !== expectedSrc) { return false; }
}
return true;
}, "md preview synced with editor content", 5000);
}
describe("livepreview:Markdown Editor Edit Mode", function () {
if (Phoenix.browser.desktop.isFirefox ||
(Phoenix.isTestWindowPlaywright && !Phoenix.browser.desktop.isChromeBased)) {
it("Markdown edit mode tests are disabled in Firefox/non-Chrome playwright", function () {});
return;
}
beforeAll(async function () {
if (!testWindow) {
const useWindowInsteadOfIframe = Phoenix.browser.desktop.isFirefox;
testWindow = await SpecRunnerUtils.createTestWindowAndRun({
forceReload: false, useWindowInsteadOfIframe
});
brackets = testWindow.brackets;
CommandManager = brackets.test.CommandManager;
Commands = brackets.test.Commands;
EditorManager = brackets.test.EditorManager;
WorkspaceManager = brackets.test.WorkspaceManager;
LiveDevMultiBrowser = brackets.test.LiveDevMultiBrowser;
await SpecRunnerUtils.loadProjectInTestWindow(mdTestFolder);
await SpecRunnerUtils.deletePathAsync(mdTestFolder + "/.phcode.json", true);
if (!WorkspaceManager.isPanelVisible("live-preview-panel")) {
await awaitsForDone(CommandManager.execute(Commands.FILE_LIVE_FILE_PREVIEW));
}
// Open HTML first to start live dev
await awaitsForDone(SpecRunnerUtils.openProjectFiles(["simple.html"]),
"open simple.html");
LiveDevMultiBrowser.open();
await awaitsFor(() =>
LiveDevMultiBrowser.status === LiveDevMultiBrowser.STATUS_ACTIVE,
"live dev to open", 20000);
}
}, 30000);
afterAll(async function () {
if (LiveDevMultiBrowser) {
LiveDevMultiBrowser.close();
}
if (CommandManager) {
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE_ALL, { _forceClose: true }),
"final close all files");
}
testWindow = null;
brackets = null;
CommandManager = null;
Commands = null;
EditorManager = null;
WorkspaceManager = null;
LiveDevMultiBrowser = null;
}, 30000);
describe("Checkbox (Task List) Sync", function () {
beforeAll(async function () {
// Ensure clean md state by switching HTML→MD
await awaitsForDone(SpecRunnerUtils.openProjectFiles(["simple.html"]),
"open simple.html to reset md state");
}, 10000);
async function _openMdFile(fileName) {
await awaitsForDone(SpecRunnerUtils.openProjectFiles([fileName]),
"open " + fileName);
await _waitForMdPreviewReady(EditorManager.getActiveEditor());
}
function _getCheckboxes() {
const mdDoc = _getMdIFrameDoc();
const content = mdDoc && mdDoc.getElementById("viewer-content");
if (!content) { return []; }
return Array.from(content.querySelectorAll('input[type="checkbox"]'));
}
it("should clicking checkbox in edit mode toggle it and sync to CM source", async function () {
await _openMdFile("checkbox-test.md");
await _enterEditMode();
const checkboxes = _getCheckboxes();
expect(checkboxes.length).toBeGreaterThan(1);
// Find first unchecked checkbox ("Incomplete task")
let uncheckedIdx = -1;
for (let i = 0; i < checkboxes.length; i++) {
if (!checkboxes[i].checked) {
uncheckedIdx = i;
break;
}
}
expect(uncheckedIdx).toBeGreaterThanOrEqual(0);
// Click the checkbox using the iframe-context helper
const win = _getMdIFrameWin();
const checkedResult = win.__clickCheckboxForTest(uncheckedIdx);
expect(checkedResult).toBeTrue();
// Verify DOM checkbox is now checked
expect(checkboxes[uncheckedIdx].checked).toBeTrue();
// Click again to uncheck
const uncheckedResult = win.__clickCheckboxForTest(uncheckedIdx);
expect(uncheckedResult).toBeFalse();
// Verify DOM checkbox is now unchecked
expect(checkboxes[uncheckedIdx].checked).toBeFalse();
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close checkbox-test.md");
}, 15000);
it("should checkboxes be enabled in edit mode and disabled in reader mode", async function () {
await _openMdFile("checkbox-test.md");
// In reader mode: checkboxes should be disabled
await _enterReaderMode();
await awaitsFor(() => _getCheckboxes().length > 0,
"checkboxes to appear in reader mode");
let checkboxes = _getCheckboxes();
expect(checkboxes.length).toBeGreaterThan(0);
for (const cb of checkboxes) {
expect(cb.disabled).toBeTrue();
}
// In edit mode: checkboxes should be enabled
await _enterEditMode();
await awaitsFor(() => _getCheckboxes().length > 0,
"checkboxes to appear in edit mode");
checkboxes = _getCheckboxes();
expect(checkboxes.length).toBeGreaterThan(0);
for (const cb of checkboxes) {
expect(cb.disabled).toBeFalse();
}
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close checkbox-test.md");
}, 15000);
});
describe("Code Block Editing", function () {
beforeAll(async function () {
await awaitsForDone(SpecRunnerUtils.openProjectFiles(["simple.html"]),
"open simple.html to reset md state");
}, 10000);
async function _openMdFile(fileName) {
await awaitsForDone(SpecRunnerUtils.openProjectFiles([fileName]),
"open " + fileName);
await _waitForMdPreviewReady(EditorManager.getActiveEditor());
}
function _getCodeBlocks() {
const mdDoc = _getMdIFrameDoc();
const content = mdDoc && mdDoc.getElementById("viewer-content");
if (!content) { return []; }
return Array.from(content.querySelectorAll("pre"));
}
function _placeCursorInCodeBlock(pre, atEnd) {
const mdDoc = _getMdIFrameDoc();
const win = _getMdIFrameWin();
const code = pre.querySelector("code") || pre;
const range = mdDoc.createRange();
if (atEnd) {
// Place cursor at end of last text node
const tw = mdDoc.createTreeWalker(code, NodeFilter.SHOW_TEXT);
let lastText = null;
let n;
while ((n = tw.nextNode())) { lastText = n; }
if (lastText) {
range.setStart(lastText, lastText.textContent.length);
range.collapse(true);
}
} else {
// Place cursor at start of first line
const tw = mdDoc.createTreeWalker(code, NodeFilter.SHOW_TEXT);
const firstText = tw.nextNode();
if (firstText) {
range.setStart(firstText, 0);
range.collapse(true);
}
}
const sel = win.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
function _placeCursorOnMiddleLine(pre) {
const mdDoc = _getMdIFrameDoc();
const win = _getMdIFrameWin();
const code = pre.querySelector("code") || pre;
const textContent = code.textContent || "";
const lines = textContent.split("\n");
if (lines.length < 3) { return; }
// Place cursor at the start of the second line
const firstLineLen = lines[0].length + 1; // +1 for \n
const tw = mdDoc.createTreeWalker(code, NodeFilter.SHOW_TEXT);
let offset = 0;
let n;
while ((n = tw.nextNode())) {
if (offset + n.textContent.length >= firstLineLen) {
const localOffset = firstLineLen - offset;
const range = mdDoc.createRange();
range.setStart(n, Math.min(localOffset, n.textContent.length));
range.collapse(true);
const sel = win.getSelection();
sel.removeAllRanges();
sel.addRange(range);
return;
}
offset += n.textContent.length;
}
}
function _dispatchKey(key, options) {
const mdDoc = _getMdIFrameDoc();
const content = mdDoc.getElementById("viewer-content");
content.dispatchEvent(new KeyboardEvent("keydown", {
key: key,
code: options && options.code || key,
shiftKey: !!(options && options.shiftKey),
ctrlKey: false,
metaKey: false,
bubbles: true,
cancelable: true
}));
}
function _getCursorElement() {
const win = _getMdIFrameWin();
const sel = win.getSelection();
if (!sel || !sel.rangeCount) { return null; }
let node = sel.anchorNode;
if (node && node.nodeType === Node.TEXT_NODE) { node = node.parentElement; }
return node;
}
it("should ArrowDown on last line of code block exit to paragraph below", async function () {
await _openMdFile("code-block-test.md");
await _enterEditMode();
const blocks = _getCodeBlocks();
expect(blocks.length).toBeGreaterThan(0);
const firstPre = blocks[0];
// Place cursor at end of code block (last line)
_placeCursorInCodeBlock(firstPre, true);
// Verify cursor is in the pre
let curEl = _getCursorElement();
expect(curEl && curEl.closest("pre")).toBe(firstPre);
// Press ArrowDown
_dispatchKey("ArrowDown");
// Cursor should now be outside the pre, in the next sibling
await awaitsFor(() => {
const el = _getCursorElement();
return el && !el.closest("pre");
}, "cursor to exit code block on ArrowDown");
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should ArrowDown on non-last line navigate within code block", async function () {
await _openMdFile("code-block-test.md");
await _enterEditMode();
const blocks = _getCodeBlocks();
expect(blocks.length).toBeGreaterThan(0);
const firstPre = blocks[0];
// Place cursor on a middle line
_placeCursorOnMiddleLine(firstPre);
let curEl = _getCursorElement();
expect(curEl && curEl.closest("pre")).toBe(firstPre);
// Press ArrowDown — should stay in code block
_dispatchKey("ArrowDown");
// Cursor should still be in the pre
const afterEl = _getCursorElement();
expect(afterEl && afterEl.closest("pre")).toBe(firstPre);
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should ArrowDown on last line move to existing next sibling", async function () {
await _openMdFile("code-block-test.md");
await _enterEditMode();
const blocks = _getCodeBlocks();
expect(blocks.length).toBeGreaterThan(0);
const firstPre = blocks[0];
// There should be a paragraph after the first code block
const nextSibling = firstPre.nextElementSibling;
expect(nextSibling).not.toBeNull();
expect(nextSibling.tagName).toBe("P");
// Place cursor at end of code block
_placeCursorInCodeBlock(firstPre, true);
// Press ArrowDown
_dispatchKey("ArrowDown");
// Cursor should be in the next paragraph
await awaitsFor(() => {
const el = _getCursorElement();
return el && el.closest("p") === nextSibling;
}, "cursor to move to existing next sibling paragraph");
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should Shift+Enter on last line of code block exit to paragraph below", async function () {
await _openMdFile("code-block-test.md");
await _enterEditMode();
const blocks = _getCodeBlocks();
expect(blocks.length).toBeGreaterThan(0);
const firstPre = blocks[0];
// Place cursor at end of code block
_placeCursorInCodeBlock(firstPre, true);
// Press Shift+Enter
_dispatchKey("Enter", { shiftKey: true });
// Cursor should exit to paragraph below
await awaitsFor(() => {
const el = _getCursorElement();
return el && !el.closest("pre");
}, "cursor to exit code block on Shift+Enter");
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should Shift+Enter on non-last line NOT exit code block", async function () {
await _openMdFile("code-block-test.md");
await _enterEditMode();
const blocks = _getCodeBlocks();
expect(blocks.length).toBeGreaterThan(0);
const firstPre = blocks[0];
// Place cursor on middle line
_placeCursorOnMiddleLine(firstPre);
// Press Shift+Enter — should NOT exit
_dispatchKey("Enter", { shiftKey: true });
// Cursor should still be in the pre
const afterEl = _getCursorElement();
expect(afterEl && afterEl.closest("pre")).toBe(firstPre);
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should Enter inside code block create new line within the block", async function () {
await _openMdFile("code-block-test.md");
await _enterEditMode();
const blocks = _getCodeBlocks();
expect(blocks.length).toBeGreaterThan(0);
const firstPre = blocks[0];
const code = firstPre.querySelector("code") || firstPre;
const linesBefore = (code.textContent || "").split("\n").length;
// Place cursor at end of last line (Enter on last line should still add a line)
_placeCursorInCodeBlock(firstPre, true);
// Press Enter (no shift) — should add a newline within the code block
_dispatchKey("Enter");
// Cursor should still be inside the pre
const afterEl = _getCursorElement();
expect(afterEl && afterEl.closest("pre")).toBe(firstPre);
// Code block should have one more line
const linesAfter = (code.textContent || "").split("\n").length;
expect(linesAfter).toBeGreaterThanOrEqual(linesBefore);
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should code block exit sync new paragraph to CM source", async function () {
await _openMdFile("code-block-test.md");
await _enterEditMode();
const editor = EditorManager.getActiveEditor();
const blocks = _getCodeBlocks();
const lastPre = blocks[blocks.length - 1];
// Remove next sibling if exists to force <p> creation
let nextEl = lastPre.nextElementSibling;
if (nextEl && nextEl.tagName === "P") {
nextEl.remove();
}
// Place cursor at end of last code block
_placeCursorInCodeBlock(lastPre, true);
// Press ArrowDown — should create new <p> and exit
_dispatchKey("ArrowDown");
// Verify new paragraph was created
await awaitsFor(() => {
const next = lastPre.nextElementSibling;
return next && next.tagName === "P";
}, "new paragraph to be created below last code block");
// Verify cursor is in the new paragraph
const curEl = _getCursorElement();
expect(curEl && !curEl.closest("pre")).toBeTrue();
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should last code block ArrowDown create new paragraph and exit", async function () {
await _openMdFile("code-block-test.md");
await _enterEditMode();
const blocks = _getCodeBlocks();
const lastPre = blocks[blocks.length - 1];
// Remove everything after last code block
while (lastPre.nextElementSibling) {
lastPre.nextElementSibling.remove();
}
// Place cursor at end of last code block
_placeCursorInCodeBlock(lastPre, true);
// Press ArrowDown
_dispatchKey("ArrowDown");
// New <p> should be created
await awaitsFor(() => {
const next = lastPre.nextElementSibling;
return next && next.tagName === "P";
}, "new <p> to be created after last code block");
// Cursor should be in the new paragraph
const curEl = _getCursorElement();
expect(curEl && !curEl.closest("pre")).toBeTrue();
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should editing code block content in CM sync to viewer", async function () {
await _openMdFile("code-block-test.md");
await _enterEditMode();
const editor = EditorManager.getActiveEditor();
const cmText = editor.document.getText();
// Replace content inside the first code block
const newText = cmText.replace(
'console.log("hello")',
'console.log("world")'
);
editor.document.setText(newText);
// Verify the viewer code block updated
const mdDoc = _getMdIFrameDoc();
await awaitsFor(() => {
const blocks = mdDoc.querySelectorAll("#viewer-content pre code");
return blocks.length > 0 && blocks[0].textContent.includes("world");
}, "viewer code block to reflect CM edit");
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should changing code block language in CM update viewer syntax class", async function () {
await _openMdFile("code-block-test.md");
await _enterEditMode();
const editor = EditorManager.getActiveEditor();
const cmText = editor.document.getText();
// Verify initial language class
const mdDoc = _getMdIFrameDoc();
await awaitsFor(() => {
const code = mdDoc.querySelector("#viewer-content pre code");
return code && (code.className.includes("javascript") ||
code.className.includes("js"));
}, "initial code block to have javascript class");
// Change ```javascript to ```html in CM
const newText = cmText.replace("```javascript", "```html");
editor.document.setText(newText);
// Verify the viewer code block updated its language class
await awaitsFor(() => {
const code = mdDoc.querySelector("#viewer-content pre code");
return code && code.className.includes("html") &&
!code.className.includes("javascript");
}, "viewer code block to reflect language change to html");
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
});
describe("List Editing", function () {
beforeAll(async function () {
await awaitsForDone(SpecRunnerUtils.openProjectFiles(["simple.html"]),
"open simple.html to reset md state");
}, 10000);
async function _openMdFile(fileName) {
await awaitsForDone(SpecRunnerUtils.openProjectFiles([fileName]),
"open " + fileName);
await _waitForMdPreviewReady(EditorManager.getActiveEditor());
}
function _getListItems(selector) {
const mdDoc = _getMdIFrameDoc();
const content = mdDoc && mdDoc.getElementById("viewer-content");
if (!content) { return []; }
return Array.from(content.querySelectorAll(selector || "li"));
}
function _placeCursorInElement(el, offset) {
const mdDoc = _getMdIFrameDoc();
const win = _getMdIFrameWin();
const range = mdDoc.createRange();
const textNode = el.firstChild && el.firstChild.nodeType === Node.TEXT_NODE
? el.firstChild : el;
if (textNode.nodeType === Node.TEXT_NODE) {
range.setStart(textNode, Math.min(offset || 0, textNode.textContent.length));
} else {
range.setStart(textNode, 0);
}
range.collapse(true);
const sel = win.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
function _placeCursorAtEnd(el) {
const mdDoc = _getMdIFrameDoc();
const win = _getMdIFrameWin();
const range = mdDoc.createRange();
range.selectNodeContents(el);
range.collapse(false);
const sel = win.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
function _dispatchKey(key, options) {
const mdDoc = _getMdIFrameDoc();
const content = mdDoc.getElementById("viewer-content");
content.dispatchEvent(new KeyboardEvent("keydown", {
key: key,
code: options && options.code || key,
keyCode: options && options.keyCode || 0,
shiftKey: !!(options && options.shiftKey),
ctrlKey: false,
metaKey: false,
bubbles: true,
cancelable: true
}));
}
function _getCursorElement() {
const win = _getMdIFrameWin();
const sel = win.getSelection();
if (!sel || !sel.rangeCount) { return null; }
let node = sel.anchorNode;
if (node && node.nodeType === Node.TEXT_NODE) { node = node.parentElement; }
return node;
}
it("should Enter in list item split content into two li elements", async function () {
await _openMdFile("list-test.md");
await _enterEditMode();
// Find "Second item with some text"
const items = _getListItems("ul > li");
let targetLi = null;
for (const li of items) {
if (li.textContent.includes("Second item")) {
targetLi = li;
break;
}
}
expect(targetLi).not.toBeNull();
const parentUl = targetLi.closest("ul");
const itemCountBefore = parentUl.querySelectorAll(":scope > li").length;
// Place cursor in the middle of "Second item with some text"
_placeCursorInElement(targetLi, 7); // after "Second "
// Press Enter
_dispatchKey("Enter");
// Should have one more li with content split correctly
await awaitsFor(() => {
const lis = Array.from(parentUl.querySelectorAll(":scope > li"));
if (lis.length <= itemCountBefore) { return false; }
// The original li should no longer contain the full unsplit text
if (targetLi.textContent.includes("Second item with some text")) {
return false;
}
// Find two consecutive lis: one ending with "Second" and next starting with "item"
for (let i = 0; i < lis.length - 1; i++) {
const cur = lis[i].textContent.trim();
const next = lis[i + 1].textContent.trim();
if (cur === "Second" && next.startsWith("item with some text")) {
return true;
}
}
return false;
}, "li to split into consecutive 'Second' and 'item with some text'");
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should Enter on empty list item exit list and create paragraph below", async function () {
await _openMdFile("list-test.md");
await _enterEditMode();
const mdDoc = _getMdIFrameDoc();
const content = mdDoc.getElementById("viewer-content");
// Find a list and add an empty li at the end
const ul = content.querySelector("ul");
expect(ul).not.toBeNull();
const emptyLi = mdDoc.createElement("li");
emptyLi.innerHTML = "<br>";
ul.appendChild(emptyLi);
// Place cursor in the empty li
_placeCursorInElement(emptyLi, 0);
// Press Enter — should exit list
_dispatchKey("Enter");
// Cursor should now be in a paragraph after the list
await awaitsFor(() => {
const el = _getCursorElement();
return el && el.closest("p") && !el.closest("li");
}, "cursor to exit list to paragraph below");
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should Shift+Enter in list item insert line break without creating new bullet", async function () {
await _openMdFile("list-test.md");
await _enterEditMode();
const items = _getListItems("ul > li");
let targetLi = null;
for (const li of items) {
if (li.textContent.includes("First item")) {
targetLi = li;
break;
}
}
expect(targetLi).not.toBeNull();
const parentUl = targetLi.closest("ul");
const itemCountBefore = parentUl.querySelectorAll(":scope > li").length;
// Place cursor at end of first item
_placeCursorAtEnd(targetLi);
// Press Shift+Enter
_dispatchKey("Enter", { shiftKey: true });
// Li count should NOT increase (no new bullet created)
expect(parentUl.querySelectorAll(":scope > li").length).toBe(itemCountBefore);
// Should still be in the same li
const curEl = _getCursorElement();
expect(curEl && curEl.closest("li")).toBe(targetLi);
// The li should contain a <br> (line break within same bullet)
expect(targetLi.querySelector("br")).not.toBeNull();
// The text content should still be in one li (not split)
expect(targetLi.textContent).toContain("First item");
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should Tab indent list item under previous sibling", async function () {
await _openMdFile("list-test.md");
await _enterEditMode();
const items = _getListItems("ul > li");
// Find "Third item" which has a previous sibling
let targetLi = null;
for (const li of items) {
if (li.textContent.trim().startsWith("Third item")) {
targetLi = li;
break;
}
}
expect(targetLi).not.toBeNull();
const prevLi = targetLi.previousElementSibling;
expect(prevLi).not.toBeNull();
// Place cursor in the target li
_placeCursorInElement(targetLi, 0);
// Press Tab
_dispatchKey("Tab", { code: "Tab", keyCode: 9 });
// The li should now be nested inside the previous sibling
await awaitsFor(() => {
return targetLi.parentElement && targetLi.parentElement.closest("li") === prevLi;
}, "li to be indented under previous sibling");
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should Shift+Tab outdent nested list item to parent level", async function () {
await _openMdFile("list-test.md");
await _enterEditMode();
const mdDoc = _getMdIFrameDoc();
// Find a nested li (child under "Parent one")
const nestedItems = mdDoc.querySelectorAll("#viewer-content ul ul > li, #viewer-content ol ol > li");
expect(nestedItems.length).toBeGreaterThan(0);
const nestedLi = nestedItems[0];
const parentList = nestedLi.parentElement;
const grandLi = parentList.closest("li");
expect(grandLi).not.toBeNull();
const outerList = grandLi.parentElement;
// Place cursor in nested li
_placeCursorInElement(nestedLi, 0);
// Press Shift+Tab
_dispatchKey("Tab", { code: "Tab", keyCode: 9, shiftKey: true });
// The li should now be at the parent level (sibling of grandLi)
await awaitsFor(() => {
return nestedLi.parentElement === outerList;
}, "nested li to be outdented to parent level");
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should Shift+Tab preserve trailing siblings as sub-list", async function () {
await _openMdFile("list-test.md");
await _enterEditMode();
const mdDoc = _getMdIFrameDoc();
// Find nested list with multiple children
const nestedLists = mdDoc.querySelectorAll("#viewer-content ul ul, #viewer-content ol ol");
let targetList = null;
for (const nl of nestedLists) {
if (nl.children.length >= 2) {
targetList = nl;
break;
}
}
expect(targetList).not.toBeNull();
// Outdent the first child — remaining siblings should become sub-list
const firstChild = targetList.children[0];
const siblingCount = targetList.children.length - 1;
_placeCursorInElement(firstChild, 0);
// Press Shift+Tab
_dispatchKey("Tab", { code: "Tab", keyCode: 9, shiftKey: true });
// The outdented item should have a sub-list with the trailing siblings
await awaitsFor(() => {
const subList = firstChild.querySelector("ul, ol");
return subList && subList.children.length === siblingCount;
}, "trailing siblings to be preserved as sub-list");
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should Tab on first list item with no previous sibling do nothing", async function () {
await _openMdFile("list-test.md");
await _enterEditMode();
const items = _getListItems("ul > li");
expect(items.length).toBeGreaterThan(0);
const firstLi = items[0];
const parentBefore = firstLi.parentElement;
// Place cursor in first li
_placeCursorInElement(firstLi, 0);
// Press Tab — should do nothing (no previous sibling)
_dispatchKey("Tab", { code: "Tab", keyCode: 9 });
// Li should still be at the same level
expect(firstLi.parentElement).toBe(parentBefore);
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should cursor position be preserved after Tab indent", async function () {
await _openMdFile("list-test.md");
await _enterEditMode();
const items = _getListItems("ul > li");
let targetLi = null;
for (const li of items) {
if (li.textContent.trim().startsWith("Third item")) {
targetLi = li;
break;
}
}
expect(targetLi).not.toBeNull();
// Place cursor at offset 3 in the li
_placeCursorInElement(targetLi, 3);
// Press Tab
_dispatchKey("Tab", { code: "Tab", keyCode: 9 });
// Cursor should still be in the same li
await awaitsFor(() => {
const el = _getCursorElement();
return el && el.closest("li") === targetLi;
}, "cursor to remain in indented li");
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
it("should Enter in list create li that syncs to markdown bullet in CM", async function () {
await _openMdFile("list-test.md");
await _enterEditMode();
const editor = EditorManager.getActiveEditor();
const items = _getListItems("ul > li");
let targetLi = null;
for (const li of items) {
if (li.textContent.includes("First item")) {
targetLi = li;
break;
}
}
expect(targetLi).not.toBeNull();
// Place cursor at end of first item
_placeCursorAtEnd(targetLi);
// Press Enter to split/create new li
_dispatchKey("Enter");
// Wait for CM to have an additional bullet line
await awaitsFor(() => {
const cmText = editor.document.getText();
// Count bullet lines (- ) — should have more than original
const bullets = cmText.match(/^-\s+/gm) || [];
return bullets.length > 4; // original has 4 unordered items
}, "new bullet to appear in CM source");
await awaitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }),
"force close");
}, 10000);
});
describe("UL/OL Toggle (List Type Switching)", function () {
const ORIGINAL_LIST_MD = "# List Test\n\n## Unordered List\n\n" +
"- First item\n- Second item with some text\n- Third item\n- Fourth item\n\n" +
"## Nested List\n\n- Parent one\n - Child one\n - Child two\n - Child three\n" +
"- Parent two\n\n## Ordered List\n\n1. First ordered\n2. Second ordered\n3. Third ordered\n\n" +
"End of list test.\n";
beforeAll(async function () {
// Reset md state then open file
await awaitsForDone(SpecRunnerUtils.openProjectFiles(["simple.html"]),
"open simple.html to reset md state");
await awaitsForDone(SpecRunnerUtils.openProjectFiles(["list-test.md"]),
"open list-test.md");