aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/MenuItem.mjs
blob: 7e509910a69e1982a71af25d49b5f2ef2c9eed4f (plain)
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
import { shiftByWindow } from './utils.mjs'
import { addMarkerByPoint } from './dumbyUtils.mjs'
/* eslint-disable-next-line no-unused-vars */
import { GeoLink, getMarkersFromMaps, removeLeaderLines } from './Link.mjs'
import * as markers from './marker.mjs'

/**
 * @typedef {Object} RefLink
 * @property {string} ref - name of link
 * @property {string} link - content of link
 * @property {string|null} title - title of link
 */

/**
 * Basic Element for menu item
 *
 * @extends {window.HTMLDivElement}
 */
export class Item extends window.HTMLDivElement {
  /**
   * Creates a new Item instance
   *
   * @param {Object} options - The options for the item
   * @param {string} [options.text] - The text content of the item
   * @param {string} [options.innerHTML] - The HTML content of the item
   * @param {string} [options.title] - The title attribute for the item
   * @param {Function} [options.onclick] - The click event handler
   * @param {string} [options.style] - The CSS style string
   * @param {string[]} [options.className] - Additional CSS classes
   */
  constructor ({ id, text, innerHTML, title, onclick, style, className }) {
    super()
    if (id) this.id = id
    if (title) this.title = title
    this.innerHTML = innerHTML ?? text
    this.onclick = onclick
    this.style.cssText = style
    this.classList.add('menu-item')
    className?.forEach(c => this.classList.add(c))

    this.onmouseover = () => {
      this.parentElement
        .querySelectorAll('.sub-menu')
        .forEach(sub => sub.remove())
    }
  }
}
if (!window.customElements.get('dumby-menu-item')) {
  window.customElements.define('dumby-menu-item', Item, { extends: 'div' })
}

/**
 * Basic Element for menu item that generates a submenu on hover
 *
 * @extends {window.HTMLDivElement}
 */
export class Folder extends window.HTMLDivElement {
  /**
   * Creates a new Folder instance
   *
   * @param {Object} options - The options for the folder
   * @param {string} [options.text] - The text content of the folder
   * @param {string} [options.innerHTML] - The HTML content of the folder
   * @param {Item[]} options.items - The submenu items
   */
  constructor ({ id, text, innerHTML, items, style }) {
    super()
    if (id) this.id = id
    this.innerHTML = innerHTML ?? text
    this.classList.add('folder', 'menu-item')
    this.items = items
    this.onmouseover = () => {
      if (this.querySelector('.sub-menu')) return
      // Prepare submenu
      const submenu = document.createElement('div')
      submenu.className = 'sub-menu'
      const offset = this.items.length > 1 ? '-20px' : '0px'
      submenu.style.cssText = `${style ?? ''}position: absolute; left: 105%; top: ${offset};`
      this.items.forEach(item => submenu.appendChild(item))
      submenu.onmouseleave = () => submenu.remove()

      // hover effect
      this.parentElement
        .querySelectorAll('.sub-menu')
        .forEach(sub => sub.remove())
      this.appendChild(submenu)
      shiftByWindow(submenu)
    }
  }
}
if (!window.customElements.get('menu-folder')) {
  window.customElements.define('menu-folder', Folder, { extends: 'div' })
}

export const simplePlaceholder = (text) => new Item({
  text,
  style: 'width: fit-content; margin: 0 auto; color: gray; pointer-events: none; font-size: 0.8rem; line-height: 1; font-weight: bolder;',
})

/**
 * Creates a menu item for picking a map
 *
 * @param {Object} options - The options object
 * @param {Object} options.utils - Utility functions
 * @returns {Folder} A Folder instance for picking a map
 */
export const pickMapItem = ({ utils }) =>
  new Folder({
    innerHTML: '<span>Maps<span><span class="info">(Tab)</span>',
    items: utils.renderedMaps().map(
      map =>
        new Item({
          text: map.id,
          onclick: () => {
            map.classList.add('focus')
            map.scrollIntoView({ behavior: 'smooth' })
          },
        }),
    ),
  })

/**
 * pickBlockItem.
 *
 * @param {HTMLElement[]} options.blocks
 * @param {Function[]} options.utils
 */
export const pickBlockItem = ({ blocks, utils }) =>
  new Folder({
    innerHTML: '<span>Blocks<span><span class="info">(n/p)</span>',
    items: blocks.map(
      (block, index) => {
        const focus = block.classList.contains('focus')
        const preview = block.querySelector('p')
          ?.textContent.substring(0, 15)
          ?.concat(' ', '...  ') ?? ''

        return new Item({
          className: ['keep-menu', focus ? 'checked' : 'unchecked'],
          innerHTML:
            `<strong>(${index})</strong><span style='display: inline-block; margin-inline: 1.2em;'>${preview}</span>`,
          onclick: (e) => {
            block.classList.toggle('focus')

            const focus = block.classList.contains('focus')
            if (focus) utils.scrollToBlock(block)
            const item = e.target.closest('.menu-item.keep-menu')
            item.classList.add(focus ? 'checked' : 'unchecked')
            item.classList.remove(focus ? 'unchecked' : 'checked')

            // UX: remove menu after user select/deselect blocks
            const submenu = e.target.closest('.sub-menu')
            submenu.onmouseleave = () => { submenu.closest('.menu').style.display = 'none' }
          },
        })
      },
    ),
  })

/**
 * pickLayoutItem.
 *
 * @param {HTEMElement} options.container
 * @param {String[]} options.layouts
 */
export const pickLayoutItem = ({ container, layouts }) =>
  new Folder({
    innerHTML: '<span>Layouts<span><span class="info">(x)</span>',
    items: [
      ...layouts.map(
        layout =>
          new Item({
            text: layout.name,
            onclick: () => container.setAttribute('data-layout', layout.name),
          }),
      ),
      new Item({
        innerHTML: '<a href="https://github.com/outdoorsafetylab/dumbymap#layouts" class="external" style="display: block; padding: 0.5rem;">More...</a>',
        style: 'padding: 0;',
      }),
    ],
  })

/**
 * addGeoLink.
 *
 * @param {Function[]} options.utils
 * @param {Range} range
 */
export const addGeoLink = ({ utils }, range) =>
  new Item({
    text: 'Add GeoLink',
    onclick: () => {
      const content = range.toString()
      // FIXME Apply geolink only on matching sub-range
      const match = content.match(/(^\D*[\d.]+)\D+([\d.]+)\D*$/)
      if (!match) return false

      const [x, y] = match.slice(1)
      const anchor = document.createElement('a')
      anchor.textContent = content
      // FIXME apply WGS84
      anchor.href = `geo:${y},${x}?xy=${x},${y}`

      // FIXME
      if (utils.createGeoLink(anchor)) {
        range.deleteContents()
        range.insertNode(anchor)
      }
    },
  })

/**
 * Suggestion. Menu Item for editor suggestion
 *
 * @extends {Item}
 */
export class Suggestion extends Item {
  /**
   * constructor.
   *
   * @param {String} options.text
   * @param {String} options.replace - new text content
   * @param {CodeMirror} options.cm
   */
  constructor ({ text, replace, cm }) {
    super({ text })
    this.replace = replace
    this.classList.add('suggestion')

    this.onmouseover = () => {
      Array.from(this.parentElement?.children)?.forEach(s =>
        s.classList.remove('focus'),
      )
      this.classList.add('focus')
    }
    this.onmouseout = () => {
      this.classList.remove('focus')
    }
    this.onclick = () => {
      const anchor = cm.getCursor()
      cm.setSelection(anchor, { ...anchor, ch: 0 })
      cm.replaceSelection(this.replace)
      cm.focus()
      const newAnchor = { ...anchor, ch: this.replace.length }
      cm.setCursor(newAnchor)
    }
  }
}
if (!window.customElements.get('menu-item-suggestion')) {
  window.customElements.define('menu-item-suggestion', Suggestion, { extends: 'div' })
}

/**
 * renderResults. return a menu item for reporting render results
 *
 * @param {Object} options.modal - Ojbect of plain-modal
 * @param {HTMLElement} options.modalContent
 * @param {HTMLElement} map - Rendered map element
 */
export const renderResults = ({ modal, modalContent }, map) =>
  new Item({
    text: 'Render Results',
    onclick: () => {
      modal.open()
      modal.overlayBlur = 3
      modal.closeByEscKey = false
      // HACK find another way to override inline style
      document.querySelector('.plainmodal-overlay-force').style.position =
        'relative'

      modalContent.innerHTML = ''
      const sourceCode = document.createElement('div')
      sourceCode.innerHTML = `<a href="${map.renderer.url ?? map.renderer.use}">Source Code</a>`
      modalContent.appendChild(sourceCode)
      const printDetails = result => {
        // const funcBody = result.func.toString()
        // const loc = funcBody.split('\n').length
        const color =
          {
            success: 'green',
            fail: 'red',
            skip: 'black',
            stop: 'chocolate',
          }[result.state] ?? 'black'
        printObject(
          result,
          modalContent,
          `${result.func.name} <span style='float: right;'><span style='display: inline-block; width: 100px; color: ${color};'>${result.state}</span></span>`,
        )
      }

      // Add contents about prepare steps
      const prepareHeading = document.createElement('h3')
      prepareHeading.textContent = 'Prepare Steps'
      modalContent.appendChild(prepareHeading)
      const prepareSteps = map.renderer.results.filter(
        r => r.type === 'prepare',
      )
      prepareSteps.forEach(printDetails)

      // Add contents about render steps
      const renderHeading = document.createElement('h3')
      renderHeading.textContent = 'Render Steps'
      modalContent.appendChild(renderHeading)
      const renderSteps = map.renderer.results.filter(r => r.type === 'render')
      renderSteps.forEach(printDetails)
    },
  })

/**
 * printObject. Generate <details> in parent element based on Ojbect properties
 *
 * @param {Object} obj
 * @param {HTMLElement} parentElement
 * @param {String} name
 */
function printObject (obj, parentElement, name = null) {
  // Create <details> and <summary> inside
  const detailsEle = document.createElement('details')
  const details = name ?? (obj instanceof Error ? obj.name : Object.values(obj)[0])
  detailsEle.innerHTML = `<summary>${details}</summary>`
  parentElement.appendChild(detailsEle)

  detailsEle.onclick = () => {
    // Don't add items if it has contents
    if (detailsEle.querySelector(':scope > :not(summary)')) return

    if (obj instanceof Error) {
      // Handle Error objects specially
      const errorProps = ['name', 'message', 'stack', ...Object.keys(obj)]
      errorProps.forEach(key => {
        const value = obj[key]
        const valueString = key === 'stack' ? `<pre>${value}</pre>` : value
        const propertyElement = document.createElement('p')
        propertyElement.innerHTML = `<strong>${key}</strong>: ${valueString}`
        detailsEle.appendChild(propertyElement)
      })
    } else {
      // Handle regular objects
      Object.entries(obj).forEach(([key, value]) => {
        if (typeof value === 'object' && value !== null) {
          printObject(value, detailsEle, key)
        } else {
          const valueString =
            typeof value === 'function'
              ? `<pre>${value}</pre>`
              : value ?? typeof value
          const propertyElement = document.createElement('p')
          propertyElement.innerHTML = `<strong>${key}</strong>: ${valueString}`
          detailsEle.appendChild(propertyElement)
        }
      })
    }
  }
}

/**
 * toggleBlockFocus. Menu Item for toggling focus on a block
 *
 * @param {HTMLElement} block
 */
export const toggleBlockFocus = block =>
  new Item({
    text: 'Toggle Focus',
    onclick: () => block.classList.toggle('focus'),
  })

/**
 * toggleMapFocus. Menu Item for toggling focus on a map
 *
 * @param {HTMLElement} map
 */
export const toggleMapFocus = map =>
  new Item({
    text: 'Toggle Focus',
    onclick: () => {
      if (map.classList.toggle('focus')) {
        map.classList.add('focus-manual')
      }
    },
  })

/**
 * getCoordinatesByPixels.
 *
 * @param {HTMLElement} map instance
 * @param {Number[]} xy - pixel of window
 */
export const getCoordinatesByPixels = (map, xy) =>
  new Item({
    text: 'Get Coordinates',
    onclick: () => {
      const [x, y] = map.renderer.unproject(xy)
      const xyString = `[${x.toFixed(7)}, ${y.toFixed(7)}]`
      navigator.clipboard.writeText(xyString)
      window.alert(`${xyString} copied to clipboard`)
    },
  })

/**
 * restoreCamera.
 *
 * @param {HTMLElement} map
 */
export const restoreCamera = map =>
  new Item({
    text: 'Restore Camera',
    onclick: () => map.renderer.restoreCamera(),
  })

/**
 * addRefLink. replace selected text into markdown link by reference style links
 *
 * @param {CodeMirror} cm
 * @param {RefLink[]} refLinks
 */
export const addRefLink = (cm, refLinks) =>
  new Folder({
    text: 'Add Link',
    items: refLinks.map(refLink => {
      let text = refLink.ref
      if (refLink.link.startsWith('geo:')) text = `@ ${text}`
      if (refLink.title?.match(/^=>/)) text = `=> ${text}`

      return new Item({
        text,
        title: refLink.link,
        onclick: () => {
          const selection = cm.getSelection()
          if (selection === refLink.ref) {
            cm.replaceSelection(`[${selection}]`)
          } else {
            cm.replaceSelection(`[${selection}][${refLink.ref}]`)
          }
        },
      })
    }),
  })

/**
 * setGeoLinkTypeItem.
 *
 * @param {GeoLink} link
 * @param {String} text
 * @param {String} type
 */
export const setGeoLinkTypeItem = ({ link, type, ...others }) => {
  const params = new URLSearchParams(link.search)
  return new Item({
    ...others,
    className: ['keep-menu'],
    onclick: () => {
      params.set('type', type)
      link.search = params
      removeLeaderLines(link)
      getMarkersFromMaps(link)
        .forEach(marker => marker.remove())
      getMarkersFromMaps(link)
    },
  })
}

/**
 * setGeoLinkType.
 *
 * @param {HTMLAnchorElement} link
 */
export const setGeoLinkType = (link) => new Folder({
  text: 'Marker Type',
  style: 'min-width: unset; display: grid; grid-template-columns: repeat(5, 1fr);',
  items: Object.entries(markers)
    .sort(([, a], [, b]) => (a.order ?? 9999) > (b.order ?? 9999))
    .map(([key, value]) => {
      return setGeoLinkTypeItem({
        link,
        title: value.name ?? key.at(0).toUpperCase() + key.slice(1),
        innerHTML: value.html,
        type: key,
        style: 'min-width: unset; width: fit-content; padding: 10px; margin: auto auto;',
      })
    }),
})

/**
 * set type of leader-line
 *
 * @param {GeoLink | DocLink} link
 */
export const setLeaderLineType = (link) => new Folder({
  text: 'Line Type',
  items: ['magnet', 'straight', 'grid', 'fluid']
    .map(path => new Item({
      text: path,
      className: ['keep-menu'],
      onclick: () => {
        link.dataset.linePath = path
        removeLeaderLines(link)
        link.onmouseover()
      },
    })),
})

/**
 * addMarker.
 *
 * @param {Object} options
 * @param {HTMLElement} options.map - map element
 * @param {Number[]} options.point - xy values in pixel
 * @param {Function} options.isNameValid - check marker name is valid
 * @param {Function} options.callback
 */
export const addMarker = ({
  map,
  point,
  isNameValid = () => true,
  callback = null,
}) => new Item({
  text: 'Add Marker',
  onclick: () => {
    let markerName
    do {
      markerName = window.prompt(markerName ? 'Name exists' : 'Marker Name')
    } while (markerName && !isNameValid(markerName))
    if (markerName === null) return

    const marker = addMarkerByPoint({ point, map, title: markerName })
    callback?.(marker)
  },
})

/**
 * editByRawText.
 *
 * @param {HTMLElement} ele
 */
export const editMapByRawText = (ele) => new Item({
  text: 'Edit by Raw Text',
  onclick: () => {
    const maps = Array.from(ele.querySelectorAll('.mapclay'))
    if (!maps) return false

    const rect = ele.getBoundingClientRect()
    const textArea = document.createElement('textarea')
    textArea.className = 'edit-map'
    textArea.style.cssText = `width: ${rect.width}px; height: ${rect.height}px;`
    textArea.value = maps.map(map => map.dataset.mapclay ?? '')
      .join('---')
      .replaceAll(',', '\n')
      .replaceAll(/["{}]/g, '')
      .replaceAll(/:(\w)/g, ': $1')

    textArea.addEventListener('focusout', () => {
      const code = document.createElement('code')
      code.className = 'map'
      code.textContent = textArea.value
      textArea.replaceWith(code)
    })
    ele.replaceChildren(textArea)

    return true
  },
})