summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/pipeline_wizard/components/input.vue
blob: 5efae2471e57b9bd1ebdf287a3bd97bdefbd0943 (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
<script>
import { isNode, isDocument, isSeq, visit } from 'yaml';
import { capitalize } from 'lodash';
import TextWidget from '~/pipeline_wizard/components/widgets/text.vue';
import ListWidget from '~/pipeline_wizard/components/widgets/list.vue';

const widgets = {
  TextWidget,
  ListWidget,
};

function isNullOrUndefined(v) {
  return [undefined, null].includes(v);
}

export default {
  components: {
    ...widgets,
  },
  props: {
    template: {
      type: Object,
      required: true,
      validator: (v) => isNode(v),
    },
    compiled: {
      type: Object,
      required: true,
      validator: (v) => isDocument(v) || isNode(v),
    },
    target: {
      type: String,
      required: true,
      validator: (v) => /^\$.*/g.test(v),
    },
    widget: {
      type: String,
      required: true,
      validator: (v) => {
        return Object.keys(widgets).includes(`${capitalize(v)}Widget`);
      },
    },
    validate: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  computed: {
    path() {
      let res;
      visit(this.template, (seqKey, node, path) => {
        if (node && node.value === this.target) {
          // `path` is an array of objects (all the node's parents)
          // So this reducer will reduce it to an array of the path's keys,
          // e.g. `[ 'foo', 'bar', '0' ]`
          res = path.reduce((p, { key }) => (key ? [...p, `${key}`] : p), []);
          const parent = path[path.length - 1];
          if (isSeq(parent)) {
            res.push(seqKey);
          }
        }
      });
      return res;
    },
  },
  methods: {
    compile(v) {
      if (!this.path) return;
      if (isNullOrUndefined(v)) {
        this.compiled.deleteIn(this.path);
      }
      this.compiled.setIn(this.path, v);
    },
    onModelChange(v) {
      this.$emit('beforeUpdate:compiled');
      this.compile(v);
      this.$emit('update:compiled', this.compiled);
      this.$emit('highlight', this.path);
    },
    onValidationStateChange(v) {
      this.$emit('update:valid', v);
    },
  },
};
</script>

<template>
  <div>
    <component
      :is="`${widget}-widget`"
      ref="widget"
      :validate="validate"
      v-bind="$attrs"
      :data-input-target="target"
      @input="onModelChange"
      @update:valid="onValidationStateChange"
    />
  </div>
</template>