aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/components/keyboard-picker.vue
blob: c3b6383b6adaf4acc1523cebb3a971fb0120f7e6 (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
<template>
  <div>
    <selector
      v-model="source"
      label="Source"
      :id="source"
      :choices="sourceChoices"
    />

    <github-picker
      v-if="source == 'github'"
      @select="handleKeyboardSelected"
    />
  </div>
</template>

<script>
import compact from 'lodash/compact'

import * as config from '../config'
import { loadLayout } from '../layout.js'
import { loadKeymap } from '../keymap.js'

import GithubPicker from './github/picker.vue'
import Selector from './selector.vue'

export default {
  name: 'KeyboardPicker',
  components: { GithubPicker, Selector },
  emits: ['select'],
  data() {
    const sourceChoices = compact([
      config.enableLocal ? { id: 'local', name: 'Local' } : null,
      config.enableGitHub ? { id: 'github', name: 'GitHub' } : null
    ])

    const selectedSource = localStorage.getItem('selectedSource')
    const onlySource = sourceChoices.length === 1 ? sourceChoices[0].id : null

    return {
      sourceChoices,
      source: onlySource || (
        sourceChoices.find(source => source.id === selectedSource)
          ? selectedSource.id
          : null
      )
    }
  },
  mounted() {
    if (this.source === 'local') {
      this.fetchLocalKeyboard()
    }
  },
  watch: {
    source(value) {
      localStorage.setItem('selectedSource', value)
      if (value === 'local') {
        this.fetchLocalKeyboard()
      }
    }
  },
  methods: {
    async fetchLocalKeyboard() {
      const { source } = this
      const [layout, keymap] = await Promise.all([
        loadLayout(),
        loadKeymap()
      ])

      this.handleKeyboardSelected({ source, layout, keymap })
    },
    handleKeyboardSelected(event) {
      const { source } = this
      const { layout, keymap, ...rest } = event

      const layerNames = keymap.layer_names || keymap.layers.map((_, i) => `Layer ${i}`)
      Object.assign(keymap, {
        layer_names: layerNames
      })

      this.$emit('select', { source, layout, keymap, ...rest })
    }
  }
}
</script>