aboutsummaryrefslogtreecommitdiff
path: root/src/lib/contextMenu.ts
blob: 6edd567818ccd928693e27f4c9c2270503369e00 (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
import { h } from 'lib/h'

interface Action {
  label: string,
  action: () => void
}

export function show(event: MouseEvent, actions: Action[]) {
  const menu = h('div',
    { id: 'g-ContextMenu',
      style: `left: ${event.pageX.toString()}px; top: ${event.pageY.toString()}px`
    },
    ...actions.map(({ label, action }) =>
      h('div',
        { className: 'g-ContextMenu__Entry',
          onclick: () => action()
        },
        label
      )
    )
  )

  document.body.appendChild(menu)

  // Remove on click or context menu
  setTimeout(() => {
    const f = () => {
      document.body.removeChild(menu)
      document.body.removeEventListener('click', f)
      document.body.removeEventListener('contextmenu', f)
    }
    document.body.addEventListener('click', f)
    document.body.addEventListener('contextmenu', f)
  }, 0)
}