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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
|
/* global EasyMDE */
/* eslint no-undef: "error" */
import { markdown2HTML, generateMaps } from './dumbymap'
import { defaultAliases, parseConfigsFromYaml } from 'mapclay'
import * as menuItem from './MenuItem'
import { addAnchorByPoint } from './dumbyUtils.mjs'
import { shiftByWindow } from './utils.mjs'
import LeaderLine from 'leader-line'
// Set up Containers {{{
/** Variables about dumbymap and editor **/
const url = new URL(window.location)
const context = document.querySelector('[data-mode]')
const dumbyContainer = document.querySelector('.DumbyMap')
const textArea = document.querySelector('.editor textarea')
let dumbymap
const refLinkPattern = /\[([^\x5B\x5D]+)\]:\s+(.+)/
let refLinks = []
const validateAnchorName = anchorName =>
!refLinks.find(obj => obj.ref === anchorName)
const appendRefLink = ({ cm, ref, link }) => {
let refLinkString = `\n[${ref}]: ${link}`
const lastLineIsRefLink = cm.getLine(cm.lastLine()).match(refLinkPattern)
if (!lastLineIsRefLink) refLinkString = '\n' + refLinkString
cm.replaceRange(refLinkString, { line: Infinity })
refLinks.push({ ref, link })
}
/**
* Watch for changes of editing mode
*
* For 'data-mode' attribute of the context element, if the mode is 'editing'
* and the layout is not 'normal', it sets the layout to 'normal' and switch to editing mode
*/
new window.MutationObserver(() => {
const mode = context.getAttribute('data-mode')
const layout = dumbyContainer.getAttribute('data-layout')
if (mode === 'editing' && layout !== 'normal') {
dumbyContainer.setAttribute('data-layout', 'normal')
}
}).observe(context, {
attributes: true,
attributeFilter: ['data-mode'],
attributeOldValue: true,
})
/**
* toggleEditing: toggle editing mode
*/
const toggleEditing = () => {
const mode = context.getAttribute('data-mode')
context.setAttribute('data-mode', mode === 'editing' ? '' : 'editing')
}
// }}}
// Set up EasyMDE {{{
/** Contents for tutorial **/
const defaultContent =
`<br>
> <big>Hello My Friend! This is DumbyMap!</big>
<br>
\`\`\`map
use: Leaflet
height: 120px
XYZ: https://tile.openstreetmap.jp/styles/osm-bright/512/{z}/{x}/{y}.png
\`\`\`
DumbyMap generates **interactive document with maps** from raw texts.
You can use it to:
1. [Roll a Dice] for a new map
2. Hover on [GeoLink][example-geolink] to show point in maps.
3. Add GeoLink by dragging **selected text**
4. Change contents by [Editor] with [Markdown] text
5. **Right click** to call context menu, you can:
+ Change focus between maps
+ Select a block for browsing
+ Switch layouts for various use cases
If you want know more, take a look at subjects below:
1. [How to write Markdown text?](https://www.markdownguide.org/basic-syntax/)
1. <details>
<summary>How can I save contents for next use?</summary>
Since All contents come from raw texts, you can:
1. Save current page as bookmark by [hash button](#create-hash "=>.mde-hash")
2. Copy texts in editor and save as \`.txt\` file
3. Use online service for hosting Markdown, for example: [HackMD](https://hackmd.io)
</details>
1. <details>
<summary>I want more features in map!</summary>
DumbyMap use [mapclay](https://github.com/outdoorsafetylab/mapclay) to render maps.
1. You can use \`eval\` options to add custom scripts, see [tutoria](https://github.com/outdoorsafetylab/mapclay?tab=readme-ov-file#run-scripts-after-map-is-created) for more details
2. You can use custom Renderer indtead of default ones, see [tutoria](https://github.com/outdoorsafetylab/mapclay?tab=readme-ov-file#renderer) for more details
</details>
1. [I am an experienced developer, show me what you got!](https://github.com/outdoorsafetylab/dumbymap)
<br>
> <big>Have Fun ~<big>
<br>
[Roll a dice]: #Click%20it! "=>.mde-roll"
[example-geolink]: geo:24,121?xy=121,24&text=Use%20yellow%20link%20point%20to%20map
[Markdown]: https://www.markdownguide.org/basic-syntax/
[Editor]: #This%20is%20editor! "=>.editor"`
/** Editor from EasyMDE **/
const editor = new EasyMDE({
element: textArea,
initialValue: defaultContent,
autosave: {
enabled: true,
uniqueId: 'dumbymap',
},
indentWithTabs: false,
lineNumbers: true,
promptURLs: true,
uploadImage: true,
spellChecker: false,
toolbarButtonClassPrefix: 'mde',
status: false,
shortcuts: {
map: 'Ctrl-Alt-M',
debug: 'Ctrl-Alt-D',
toggleUnorderedList: null,
toggleOrderedList: null,
},
toolbar: [
{
name: 'roll',
title: 'Roll a Dice',
text: '\u{2684}',
action: () => addMapRandomlyByPreset(),
},
{
name: 'export',
title: 'Export current page',
text: '\u{1F4BE}',
action: () => {
},
},
{
name: 'hash',
title: 'Save content as URL',
// text: '\u{1F4BE}',
text: '#',
action: () => {
const state = { content: editor.value() }
window.location.hash = encodeURIComponent(JSON.stringify(state))
window.location.search = ''
navigator.clipboard.writeText(window.location.href)
window.alert('URL updated in address bar, you can save current page as bookmark')
},
},
'|',
{
name: 'undo',
title: 'Undo last editing',
text: '\u27F2',
action: EasyMDE.undo,
},
{
name: 'redo',
text: '\u27F3',
title: 'Redo editing',
action: EasyMDE.redo,
},
'|',
{
name: 'heading-1',
text: 'H1',
title: 'Big Heading',
action: EasyMDE['heading-1'],
},
{
name: 'heading-2',
text: 'H2',
title: 'Medium Heading',
action: EasyMDE['heading-2'],
},
'|',
{
name: 'link',
text: '\u{1F517}',
title: 'Create Link',
action: EasyMDE.drawLink,
},
{
name: 'image',
text: '\u{1F5BC}',
title: 'Create Image',
action: EasyMDE.drawImage,
},
'|',
{
name: 'Bold',
text: '\u{1D401}',
title: 'Bold',
action: EasyMDE.toggleBold,
},
{
name: 'Italic',
text: '\u{1D43C}',
title: 'Italic',
action: EasyMDE.toggleItalic,
},
'|',
{
name: 'tutorial',
text: '\u{2753}',
title: 'Reset for content for tutorial',
action: () => {
editor.value(defaultContent)
refLinks = getRefLinks()
updateDumbyMap()
},
},
],
})
/** CodeMirror Instance **/
const cm = editor.codemirror
/** Ref Links **/
const getRefLinks = () => editor.value()
.split('\n')
.map(line => {
const [, ref, link] = line.match(refLinkPattern) ?? []
return { ref, link }
})
.filter(({ ref, link }) => ref && link)
refLinks = getRefLinks()
/**
* get state of website from hash string
*
* @param {String} hash
*/
const getStateFromHash = hash => {
const hashValue = hash.substring(1)
const stateString = decodeURIComponent(hashValue)
try {
return JSON.parse(stateString) ?? {}
} catch (_) {
return {}
}
}
/**
* get editor content from hash string
*
* @param {String} hash
*/
const getContentFromHash = hash => {
const state = getStateFromHash(hash)
return state.content
}
/** Hash and Query Parameters in URL **/
const contentFromHash = getContentFromHash(window.location.hash)
window.location.hash = ''
if (url.searchParams.get('content') === 'tutorial') {
editor.value(defaultContent)
} else if (contentFromHash) {
// Seems like autosave would overwrite initialValue, set content from hash here
editor.cleanup()
editor.value(contentFromHash)
}
// }}}
// Set up logic about editor content {{{
/** Sync scroll from HTML to CodeMirror **/
const htmlOnScroll = (ele) => () => {
if (textArea.dataset.scrollLine) return
const threshold = ele.scrollTop + window.innerHeight / 2 + 30
const block = Array.from(ele.children)
.findLast(e => e.offsetTop < threshold) ??
ele.firstChild
const line = Array.from(block.querySelectorAll('p'))
.findLast(e => e.offsetTop + block.offsetTop < threshold)
const linenumber = line?.dataset?.sourceLine
if (!linenumber) return
const offset = (line.offsetTop + block.offsetTop - ele.scrollTop)
if (linenumber) {
dumbyContainer.dataset.scrollLine = linenumber + '/' + offset
}
}
new window.MutationObserver(() => {
clearTimeout(dumbyContainer.timer)
dumbyContainer.timer = setTimeout(
() => delete dumbyContainer.dataset.scrollLine,
50,
)
const line = dumbyContainer.dataset.scrollLine
if (line) {
const [lineNumber, offset] = line.split('/')
if (!isNaN(lineNumber)) {
cm.scrollIntoView({ line: lineNumber, ch: 0 }, offset)
}
}
}).observe(dumbyContainer, {
attributes: true,
attributeFilter: ['data-scroll-line'],
})
const setScrollLine = () => {
if (dumbyContainer.dataset.scrollLine) return
const lineNumber = cm.getCursor()?.line ??
cm.lineAtHeight(cm.getScrollInfo().top, 'local')
textArea.dataset.scrollLine = lineNumber
}
cm.on('scroll', () => {
if (cm.hasFocus()) setScrollLine()
})
/** Sync scroll from CodeMirror to HTML **/
new window.MutationObserver(() => {
clearTimeout(textArea.timer)
textArea.timer = setTimeout(
() => delete textArea.dataset.scrollLine,
1000,
)
const line = textArea.dataset.scrollLine
let lineNumber = Number(line)
let p
if (isNaN(lineNumber)) return
const paragraphs = Array.from(dumbymap.htmlHolder.querySelectorAll('p'))
do {
p = paragraphs.find(p => Number(p.dataset.sourceLine) === lineNumber)
lineNumber++
} while (!p && lineNumber < cm.doc.size)
p = p ?? paragraphs.at(-1)
if (!p) return
const coords = cm.charCoords({ line: lineNumber, ch: 0 })
p.scrollIntoView({ inline: 'start' })
const top = p.getBoundingClientRect().top
dumbymap.htmlHolder.scrollBy(0, top - coords.top + 30)
}).observe(textArea, {
attributes: true,
attributeFilter: ['data-scroll-line'],
})
/**
* addClassToCodeLines. Quick hack to style lines inside code block
*/
const addClassToCodeLines = () => {
const lines = cm.getLineHandle(0).parent.lines
let insideCodeBlock = false
lines.forEach((line, index) => {
if (line.text.match(/^[\u0060]{3}/)) {
insideCodeBlock = !insideCodeBlock
} else if (insideCodeBlock) {
cm.addLineClass(index, 'text', 'inside-code-block')
} else {
cm.removeLineClass(index, 'text', 'inside-code-block')
}
})
}
addClassToCodeLines()
/**
* completeForCodeBlock.
*
* @param {Object} change -- codemirror change object
*/
const completeForCodeBlock = change => {
const line = change.to.line
if (change.origin === '+input') {
const text = change.text[0]
// Completion for YAML doc separator
if (
text === '-' &&
change.to.ch === 0 &&
insideCodeblockForMap(cm.getCursor())
) {
cm.setSelection({ line, ch: 0 }, { line, ch: 1 })
cm.replaceSelection(text.repeat(3) + '\n')
}
// Completion for Code fence
if (text === '`' && change.to.ch === 0) {
cm.setSelection({ line, ch: 0 }, { line, ch: 1 })
cm.replaceSelection(text.repeat(3))
const numberOfFences = cm
.getValue()
.split('\n')
.filter(line => line.match(/[\u0060]{3}/)).length
if (numberOfFences % 2 === 1) {
cm.replaceSelection('map\n\n```')
cm.setCursor({ line: line + 1 })
}
}
}
// For YAML doc separator, <hr> and code fence
// Auto delete to start of line
if (change.origin === '+delete') {
const match = change.removed[0].match(/^[-\u0060]$/)?.at(0)
if (match && cm.getLine(line) === match.repeat(2) && match) {
cm.setSelection({ line, ch: 0 }, { line, ch: 2 })
cm.replaceSelection('')
}
}
}
/* Disable debounce temporarily */
// const debounceForMap = (() => {
// const timer = null
//
// return function (...args) {
// dumbymap = generateMaps.apply(this, args)
// clearTimeout(timer);
// timer = setTimeout(() => {
// dumbymap = generateMaps.apply(this, args)
// }, 10);
// }
// })()
/**
* menuForEditor.
*
* @param {Event} event -- Event for context menu
* @param {HTMLElement} menu -- menu of dumbymap
*/
const menuForEditor = (event, menu) => {
event.preventDefault()
if (document.getSelection().type === 'Range' && cm.getSelection() && refLinks.length > 0) {
menu.replaceChildren()
menu.appendChild(menuItem.addRefLink(cm, refLinks))
}
if (context.dataset.mode !== 'editing') {
const switchToEditingMode = new menuItem.Item({
innerHTML: '<strong>EDIT</strong>',
onclick: () => (context.dataset.mode = 'editing'),
})
menu.appendChild(switchToEditingMode)
}
const map = event.target.closest('.mapclay')
if (map) {
const item = new menuItem.Item({
text: 'Add Anchor',
onclick: (event) => {
const { ref, link } = addAnchorByPoint({ point: event, map, validateAnchorName })
appendRefLink({ cm, ref, link })
},
})
menu.insertBefore(item, menu.firstChild)
}
}
/**
* update content of HTML about Dumbymap
*/
const updateDumbyMap = (callback = null) => {
markdown2HTML(dumbyContainer, editor.value())
// debounceForMap(dumbyContainer, afterMapRendered)
dumbymap = generateMaps(dumbyContainer, { layouts: ['sticky'] })
// Set onscroll callback
const htmlHolder = dumbymap.htmlHolder
htmlHolder.onscroll = htmlOnScroll(htmlHolder)
// Set oncontextmenu callback
dumbymap.utils.setContextMenu(menuForEditor)
callback?.(dumbymap)
}
updateDumbyMap()
// Re-render HTML by editor content
cm.on('change', (_, change) => {
updateDumbyMap(() => {
setScrollLine()
})
addClassToCodeLines()
completeForCodeBlock(change)
})
// Set class for focus
cm.on('focus', () => {
cm.getWrapperElement().classList.add('focus')
dumbyContainer.classList.remove('focus')
})
cm.on('beforeChange', (_, change) => {
textArea.dataset.scrollLine = cm.getCursor().line
// Don't allow more content after YAML doc separator
if (change.origin && change.origin.match(/^(\+input|paste)$/)) {
const line = change.to.line
if (cm.getLine(line) === '---' && change.text[0] !== '') {
change.cancel()
}
}
})
// Reload editor content by hash value
window.onhashchange = () => {
const content = getContentFromHash(window.location.hash)
if (content) editor.value(content)
}
// }}}
// Completion in Code Blok {{{
// Elements about suggestions {{{
const menu = document.createElement('div')
menu.className = 'menu editor-menu'
menu.style.display = 'none'
menu.onclick = () => (menu.style.display = 'none')
new window.MutationObserver(() => {
if (menu.style.display === 'none') {
menu.replaceChildren()
}
}).observe(menu, {
attributes: true,
attributeFilter: ['style'],
})
document.body.append(menu)
const rendererOptions = {}
// }}}
// Aliases for map options {{{
const aliasesForMapOptions = {}
const defaultApply = './assets/default.yml'
fetch(defaultApply)
.then(res => res.text())
.then(rawText => {
const config = parseConfigsFromYaml(rawText)?.at(0)
Object.assign(aliasesForMapOptions, config.aliases ?? {})
})
.catch(err => console.warn(`Fail to get aliases from ${defaultApply}`, err))
// }}}
/**
* insideCodeblockForMap. Check if current token is inside code block {{{
*
* @param {Anchor} anchor
*/
const insideCodeblockForMap = anchor => {
const token = cm.getTokenAt(anchor)
const insideCodeBlock =
token.state.overlay.codeBlock &&
!cm.getLine(anchor.line).match(/^[\u0060]{3}/)
if (!insideCodeBlock) return false
let line = anchor.line - 1
while (line >= 0) {
const content = cm.getLine(line)
if (content === '```map') {
return true
} else if (content === '```') {
return false
}
line = line - 1
}
return false
}
// }}}
/**
* getLineWithRenderer. Get Renderer by cursor position in code block {{{
*
* @param {Object} anchor -- Codemirror Anchor Object
*/
const getLineWithRenderer = anchor => {
const currentLine = anchor.line
if (!cm.getLine) return null
const match = line => cm.getLine(line).match(/^use: /)
if (match(currentLine)) return currentLine
// Look backward/forward for pattern of used renderer: /use: .+/
let pl = currentLine - 1
while (pl > 0 && insideCodeblockForMap(anchor)) {
const text = cm.getLine(pl)
if (match(pl)) {
return pl
} else if (text.match(/^---|^[\u0060]{3}/)) {
break
}
pl = pl - 1
}
let nl = currentLine + 1
while (insideCodeblockForMap(anchor)) {
const text = cm.getLine(nl)
if (match(nl)) {
return nl
} else if (text.match(/^---|^[\u0060]{3}/)) {
return null
}
nl = nl + 1
}
return null
}
// }}}
/**
* getSuggestionsForOptions. Return suggestions for valid options {{{
*
* @param {Boolean} optionTyped
* @param {Object[]} validOptions
*/
const getSuggestionsForOptions = (optionTyped, validOptions) => {
let suggestOptions = []
const matchedOptions = validOptions.filter(o =>
o.valueOf().toLowerCase().includes(optionTyped.toLowerCase()),
)
if (matchedOptions.length > 0) {
suggestOptions = matchedOptions
} else {
suggestOptions = validOptions
}
return suggestOptions.map(
o =>
new menuItem.Suggestion({
text: `<span>${o.valueOf()}</span><span class='info' title="${o.desc ?? ''}">ⓘ</span>`,
replace: `${o.valueOf()}: `,
cm,
}),
)
}
// }}}
/**
* getSuggestionFromMapOption. Return suggestion for example of option value {{{
*
* @param {Object} option
*/
const getSuggestionFromMapOption = option => {
if (!option.example) return null
const text = option.example_desc
? `<span>${option.example_desc}</span><span class="truncate"style="color: gray">${option.example}</span>`
: `<span>${option.example}</span>`
return new menuItem.Suggestion({
text,
replace: `${option.valueOf()}: ${option.example ?? ''}`,
cm,
})
}
// }}}
/**
* getSuggestionsFromAliases. Return suggestions from aliases {{{
*
* @param {Object} option
*/
const getSuggestionsFromAliases = option =>
Object.entries(aliasesForMapOptions[option.valueOf()] ?? {})?.map(record => {
const [alias, value] = record
const valueString = JSON.stringify(value).replaceAll('"', '')
return new menuItem.Suggestion({
text: `<span>${alias}</span><span class="truncate" style="color: gray">${valueString}</span>`,
replace: `${option.valueOf()}: ${valueString}`,
cm,
})
}) ?? []
// }}}
/**
* handleTypingInCodeBlock. Handler for map codeblock {{{
*
* @param {Object} anchor -- Codemirror Anchor Object
*/
const handleTypingInCodeBlock = anchor => {
const text = cm.getLine(anchor.line)
if (text.match(/^\s\+$/) && text.length % 2 !== 0) {
// TODO Completion for even number of spaces
} else if (text.match(/^-/)) {
// TODO Completion for YAML doc separator
} else {
const suggestions = getSuggestions(anchor)
addSuggestions(anchor, suggestions)
}
}
// }}}
/**
* getSuggestions. Get suggestions by current input {{{
*
* @param {Object} anchor -- Codemirror Anchor Object
*/
const getSuggestions = anchor => {
const text = cm.getLine(anchor.line)
// Clear marks on text
cm.findMarks({ ...anchor, ch: 0 }, { ...anchor, ch: text.length }).forEach(
m => m.clear(),
)
// Mark user input invalid by case
const markInputIsInvalid = () =>
cm
.getDoc()
.markText(
{ ...anchor, ch: 0 },
{ ...anchor, ch: text.length },
{ className: 'invalid-input' },
)
// Check if "use: <renderer>" is set
const lineWithRenderer = getLineWithRenderer(anchor)
const renderer = lineWithRenderer
? cm.getLine(lineWithRenderer).split(' ')[1]
: null
if (renderer && anchor.line !== lineWithRenderer) {
// Do not check properties
if (text.startsWith(' ')) return []
// If no valid options for current used renderer, go get it!
const validOptions = rendererOptions[renderer]
if (!validOptions) {
// Get list of valid options for current renderer
const rendererUrl = defaultAliases.use[renderer]?.value
import(rendererUrl)
.then(rendererModule => {
rendererOptions[renderer] = rendererModule.default.validOptions
const currentAnchor = cm.getCursor()
if (insideCodeblockForMap(currentAnchor)) {
handleTypingInCodeBlock(currentAnchor)
}
})
.catch(_ => {
markInputIsInvalid(lineWithRenderer)
console.warn(
`Fail to get valid options from Renderer typed: ${renderer}`,
)
})
return []
}
// If input is "key:value" (no space left after colon), then it is invalid
const isKeyFinished = text.includes(':')
const isValidKeyValue = text.match(/^[^:]+:\s+/)
if (isKeyFinished && !isValidKeyValue) {
markInputIsInvalid()
return []
}
// If user is typing option
const keyTyped = text.split(':')[0].trim()
if (!isKeyFinished) {
markInputIsInvalid()
return getSuggestionsForOptions(keyTyped, validOptions)
}
// If user is typing value
const matchedOption = validOptions.find(o => o.name === keyTyped)
if (isKeyFinished && !matchedOption) {
markInputIsInvalid()
}
if (isKeyFinished && matchedOption) {
const valueTyped = text.substring(text.indexOf(':') + 1).trim()
const isValidValue = matchedOption.isValid(valueTyped)
if (!valueTyped) {
return [
getSuggestionFromMapOption(matchedOption),
...getSuggestionsFromAliases(matchedOption),
].filter(s => s instanceof menuItem.Suggestion)
}
if (valueTyped && !isValidValue) {
markInputIsInvalid()
return []
}
}
} else {
// Suggestion for "use"
const rendererSuggestions = Object.entries(defaultAliases.use)
.filter(([renderer]) => {
const suggestion = `use: ${renderer}`
const suggestionPattern = suggestion.replace(' ', '').toLowerCase()
const textPattern = text.replace(' ', '').toLowerCase()
return suggestion !== text && suggestionPattern.includes(textPattern)
})
.map(
([renderer, info]) =>
new menuItem.Suggestion({
text: `<span>use: ${renderer}</span><span class='info' title="${info.desc}">ⓘ</span>`,
replace: `use: ${renderer}`,
cm,
}),
)
return rendererSuggestions.length === 0
? []
: [
...rendererSuggestions,
new menuItem.Item({
innerHTML: '<a href="https://github.com/outdoorsafetylab/mapclay#renderer" class="external" style="display: block;">More...</a>',
className: ['suggestion'],
onclick: () => window.open('https://github.com/outdoorsafetylab/mapclay#renderer', '_blank'),
}),
]
}
return []
}
// }}}
/**
* addSuggestions. Show element about suggestions {{{
*
* @param {Object} anchor -- Codemirror Anchor Object
* @param {Suggestion[]} suggestions
*/
const addSuggestions = (anchor, suggestions) => {
if (suggestions.length === 0) {
menu.style.display = 'none'
return
} else {
menu.style.display = 'block'
}
menu.innerHTML = ''
suggestions
.forEach(option => menu.appendChild(option))
const widgetAnchor = document.createElement('div')
cm.addWidget(anchor, widgetAnchor, true)
const rect = widgetAnchor.getBoundingClientRect()
menu.style.left = `calc(${rect.left}px + 2rem)`
menu.style.top = `calc(${rect.bottom}px + 1rem)`
menu.style.display = 'block'
shiftByWindow(menu)
}
// }}}
// EVENT: Suggests for current selection {{{
// FIXME Dont show suggestion when selecting multiple chars
cm.on('cursorActivity', _ => {
menu.style.display = 'none'
const anchor = cm.getCursor()
if (insideCodeblockForMap(anchor)) {
handleTypingInCodeBlock(anchor)
}
})
cm.on('blur', () => {
refLinks = getRefLinks()
if (menu.checkVisibility()) {
cm.focus()
} else {
cm.getWrapperElement().classList.remove('focus')
dumbyContainer.classList.add('focus')
}
})
// }}}
// EVENT: keydown for suggestions {{{
const keyForSuggestions = ['Tab', 'Enter', 'Escape']
cm.on('keydown', (_, e) => {
if (
!cm.hasFocus ||
!keyForSuggestions.includes(e.key) ||
menu.style.display === 'none'
) { return }
// Directly add a newline when no suggestion is selected
const currentSuggestion = menu.querySelector('.menu-item.focus')
if (!currentSuggestion && e.key === 'Enter') return
// Override default behavior
e.preventDefault()
// Suggestion when pressing Tab or Shift + Tab
const nextSuggestion =
currentSuggestion?.nextSibling ??
menu.querySelector('.menu-item:first-child')
const previousSuggestion =
currentSuggestion?.previousSibling ??
menu.querySelector('.menu-item:last-child')
const focusSuggestion = e.shiftKey ? previousSuggestion : nextSuggestion
// Current editor selection state
switch (e.key) {
case 'Tab':
Array.from(menu.children).forEach(s => s.classList.remove('focus'))
focusSuggestion.classList.add('focus')
focusSuggestion.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
break
case 'Enter':
currentSuggestion.onclick()
break
case 'Escape':
if (!menu.checkVisibility()) break
// HACK delay menu display change for blur event, mark cm focus should keep
setTimeout(() => (menu.style.display = 'none'), 50)
break
}
})
document.onkeydown = e => {
if (e.altKey && e.ctrlKey && e.key === 'm') {
toggleEditing()
e.preventDefault()
return null
}
if (!cm.hasFocus()) {
if (e.key === 'F1') {
e.preventDefault()
cm.focus()
}
if (e.key === 'Tab') {
e.preventDefault()
dumbymap.utils.focusNextMap(e.shiftKey)
}
if (e.key === 'x' || e.key === 'X') {
e.preventDefault()
dumbymap.utils.switchToNextLayout(e.shiftKey)
}
if (e.key === 'n') {
e.preventDefault()
dumbymap.utils.focusNextBlock()
}
if (e.key === 'p') {
e.preventDefault()
dumbymap.utils.focusNextBlock(true)
}
if (e.key === 'Escape') {
e.preventDefault()
dumbymap.utils.removeBlockFocus()
}
}
}
// }}}
// }}}
// Layout Switch {{{
new window.MutationObserver(mutaions => {
const mutation = mutaions.at(-1)
const layout = dumbyContainer.getAttribute('data-layout')
if (layout !== 'normal' || mutation.oldValue === 'normal') {
context.setAttribute('data-mode', '')
}
}).observe(dumbyContainer, {
attributes: true,
attributeFilter: ['data-layout'],
attributeOldValue: true,
})
// }}}
/**
* addMapRandomlyByPreset. insert random text of valid mapclay yaml into editor
*/
const addMapRandomlyByPreset = () => {
const yamlText = [
'apply: ./assets/default.yml',
'width: 85%',
'height: 200px',
]
const order = [
'id',
'apply',
'use',
'width',
'height',
'center',
'XYZ',
'zoom',
]
const aliasesEntries = Object.entries(aliasesForMapOptions)
.filter(([key, _]) =>
order.includes(key) &&
!yamlText.find(text => text.startsWith(key)),
)
if (aliasesEntries.length === 0) return
aliasesEntries.forEach(([option, aliases]) => {
const entries = Object.entries(aliases)
const validEntries = entries
.filter(([alias, value]) => {
// FIXME logic about picking XYZ data
if (option === 'XYZ') {
const inTaiwan = yamlText.find(text => text.match(/center: TAIWAN/))
if (!inTaiwan) return !alias.includes('TAIWAN')
}
if (option === 'zoom') {
return value > 6 && value < 15
}
return true
})
const randomValue = validEntries
.at((Math.random() * validEntries.length) | 0)
.at(0)
yamlText.push(`${option}: ${typeof randomValue === 'object' ? randomValue.value : randomValue}`)
if (option === 'center') yamlText.push(`id: ${randomValue}`)
})
yamlText.sort((a, b) =>
order.indexOf(a.split(':')[0]) > order.indexOf(b.split(':')[0]),
)
const anchor = cm.getCursor()
cm.replaceRange(
'\n```map\n' + yamlText.join('\n') + '\n```\n',
anchor,
)
}
cm.getWrapperElement().oncontextmenu = e => {
if (insideCodeblockForMap(cm.getCursor())) return
e.preventDefault()
if (cm.getSelection() && refLinks.length > 0) {
menu.appendChild(menuItem.addRefLink(cm, refLinks))
}
if (menu.children.length > 0) {
menu.style.cssText = `display: block; transform: translate(${e.x}px, ${e.y}px); overflow: visible;`
}
}
/** HACK Sync selection from HTML to CodeMirror */
document.addEventListener('selectionchange', () => {
if (cm.hasFocus() || dumbyContainer.onmousemove) {
return
}
const selection = document.getSelection()
if (selection.type === 'Range') {
const content = selection.getRangeAt(0).toString()
const parentWithSourceLine = selection.anchorNode.parentElement.closest('.source-line')
const lineStart = Number(parentWithSourceLine?.dataset?.sourceLine ?? NaN)
const lineEnd = Number(parentWithSourceLine?.nextSibling?.dataset?.sourceLine ?? NaN)
// TODO Also return when range contains anchor element
if (content.includes('\n') || isNaN(lineStart)) {
cm.setSelection(cm.getCursor())
return
}
const texts = [content]
let sibling = selection.anchorNode.previousSibling
while (sibling) {
texts.push(sibling.textContent)
sibling = sibling.previousSibling
}
const anchor = { line: lineStart, ch: 0 }
texts
.filter(t => t && t !== '\n')
.map(t => t.replace('\n', ''))
.reverse()
.forEach(text => {
let index = cm.getLine(anchor.line)?.indexOf(text, anchor.ch)
while (index === -1) {
anchor.line += 1
anchor.ch = 0
if (anchor.line >= lineEnd) {
cm.setSelection(cm.setCursor())
return
}
index = cm.getLine(anchor.line)?.indexOf(text)
}
anchor.ch = index + text.length
})
cm.setSelection({ line: anchor.line, ch: anchor.ch - content.length }, anchor)
}
})
/** Drag/Drop on map for new reference style link */
dumbyContainer.onmousedown = (e) => {
// Check should start drag event for GeoLink
if (e.which !== 1) return
const selection = document.getSelection()
if (cm.getSelection() === '' || selection.type !== 'Range') return
const range = selection.getRangeAt(0)
const rect = range.getBoundingClientRect()
const mouseInRange = e.x < rect.right && e.x > rect.left && e.y < rect.bottom && e.y > rect.top
if (!mouseInRange) return
const geoLink = document.createElement('a')
geoLink.textContent = range.toString()
geoLink.classList.add('with-leader-line', 'geolink', 'drag')
range.deleteContents()
range.insertNode(geoLink)
const lineEnd = document.createElement('div')
lineEnd.style.cssText = `position: absolute; left: ${e.clientX}px; top: ${e.clientY}px;`
document.body.appendChild(lineEnd)
const line = new LeaderLine({
start: geoLink,
end: lineEnd,
path: 'magnet',
})
function onMouseMove (event) {
lineEnd.style.left = event.clientX + 'px'
lineEnd.style.top = event.clientY + 'px'
line.position()
}
context.classList.add('dragging-geolink')
dumbyContainer.onmousemove = onMouseMove
dumbymap.utils.renderedMaps().forEach(map => { map.style.cursor = 'crosshair' })
dumbyContainer.onmouseup = function (e) {
context.classList.remove('dragging-geolink')
dumbyContainer.onmousemove = null
dumbyContainer.onmouseup = null
line?.remove()
lineEnd.remove()
dumbymap.utils.renderedMaps().forEach(map => map.style.removeProperty('cursor'))
const resumeContent = () => updateDumbyMap(newDumbymap => {
const scrollTop = dumbymap.htmlHolder.scrollTop
newDumbymap.htmlHolder.scrollBy(0, scrollTop)
})
const map = document.elementFromPoint(e.clientX, e.clientY).closest('.mapclay')
const selection = cm.getSelection()
if (!map || !selection) {
resumeContent()
return
}
const refLink = addAnchorByPoint({ point: e, map, validateAnchorName })
if (!refLink) {
resumeContent()
return
}
const { ref, link } = refLink
appendRefLink({ cm, ref, link })
if (selection === ref) {
cm.replaceSelection(`[${selection}]`)
} else {
cm.replaceSelection(`[${selection}][${ref}]`)
}
}
}
dumbyContainer.ondragstart = () => false
|