Welcome to mirror list, hosted at ThFree Co, Russian Federation.

source_editor_yaml_ext.js « extensions « editor « javascripts « assets « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 212e09c8724d727524cde3f776681770d0a126ef (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
import { toPath } from 'lodash';
import { parseDocument, Document, visit, isScalar, isCollection, isMap } from 'yaml';
import { findPair } from 'yaml/util';
import { SourceEditorExtension } from '~/editor/extensions/source_editor_extension_base';

export class YamlEditorExtension extends SourceEditorExtension {
  /**
   * Extends the source editor with capabilities for yaml files.
   *
   * @param { Instance } instance Source Editor Instance
   * @param { boolean } enableComments Convert model nodes with the comment
   * pattern to comments?
   * @param { string } highlightPath Add a line highlight to the
   * node specified by this e.g. `"foo.bar[0]"`
   * @param { * } model Any JS Object that will be stringified and used as the
   * editor's value. Equivalent to using `setDataModel()`
   * @param options SourceEditorExtension Options
   */
  constructor({
    instance,
    enableComments = false,
    highlightPath = null,
    model = null,
    ...options
  } = {}) {
    super({
      instance,
      options: {
        ...options,
        enableComments,
        highlightPath,
      },
    });

    if (model) {
      YamlEditorExtension.initFromModel(instance, model);
    }

    instance.onDidChangeModelContent(() => instance.onUpdate());
  }

  /**
   * @private
   */
  static initFromModel(instance, model) {
    const doc = new Document(model);
    if (instance.options.enableComments) {
      YamlEditorExtension.transformComments(doc);
    }
    instance.setValue(doc.toString());
  }

  /**
   * @private
   * This wraps long comments to a maximum line length of 80 chars.
   *
   * The `yaml` package does not currently wrap comments. This function
   * is a local workaround and should be deprecated if
   * https://github.com/eemeli/yaml/issues/322
   * is resolved.
   */
  static wrapCommentString(string, level = 0) {
    if (!string) {
      return null;
    }
    if (level < 0 || Number.isNaN(parseInt(level, 10))) {
      throw Error(`Invalid value "${level}" for variable \`level\``);
    }
    const maxLineWidth = 80;
    const indentWidth = 2;
    const commentMarkerWidth = '# '.length;
    const maxLength = maxLineWidth - commentMarkerWidth - level * indentWidth;
    const lines = [[]];
    string.split(' ').forEach((word) => {
      const currentLine = lines.length - 1;
      if ([...lines[currentLine], word].join(' ').length <= maxLength) {
        lines[currentLine].push(word);
      } else {
        lines.push([word]);
      }
    });
    return lines.map((line) => ` ${line.join(' ')}`).join('\n');
  }

  /**
   * @private
   *
   * This utilizes `yaml`'s `visit` function to transform nodes with a
   * comment key pattern to actual comments.
   *
   * In Objects, a key of '#' will be converted to a comment at the top of a
   * property. Any key following the pattern `#|<some key>` will be placed
   * right before `<some key>`.
   *
   * In Arrays, any string that starts with #  (including the space), will
   * be converted to a comment at the position it was in.
   *
   * @param { Document } doc
   * @returns { Document }
   */
  static transformComments(doc) {
    const getLevel = (path) => {
      const { length } = path.filter((x) => isCollection(x));
      return length ? length - 1 : 0;
    };

    visit(doc, {
      Pair(_, pair, path) {
        const key = pair.key.value;
        // If the key is = '#', we add the value as a comment to the parent
        // We can then remove the node.
        if (key === '#') {
          Object.assign(path[path.length - 1], {
            commentBefore: YamlEditorExtension.wrapCommentString(pair.value.value, getLevel(path)),
          });
          return visit.REMOVE;
        }
        // If the key starts with `#|`, we want to add a comment to the
        // corresponding property. We can then remove the node.
        if (key.startsWith('#|')) {
          const targetProperty = key.split('|')[1];
          const target = findPair(path[path.length - 1].items, targetProperty);
          if (target) {
            target.key.commentBefore = YamlEditorExtension.wrapCommentString(
              pair.value.value,
              getLevel(path),
            );
          }
          return visit.REMOVE;
        }
        return undefined; // If the node is not a comment, do nothing with it
      },
      // Sequence is basically an array
      Seq(_, node, path) {
        let comment = null;
        const items = node.items.flatMap((child) => {
          if (comment) {
            Object.assign(child, { commentBefore: comment });
            comment = null;
          }
          if (
            isScalar(child) &&
            child.value &&
            child.value.startsWith &&
            child.value.startsWith('#')
          ) {
            const commentValue = child.value.replace(/^#\s?/, '');
            comment = YamlEditorExtension.wrapCommentString(commentValue, getLevel(path));
            return [];
          }
          return child;
        });
        Object.assign(node, { items });
        // Adding a comment in case the last one is a comment
        if (comment) {
          Object.assign(node, { comment });
        }
      },
    });
    return doc;
  }

  /**
   * Get the editor's value parsed as a `Document` as defined by the `yaml`
   * package
   * @returns {Document}
   */
  getDoc() {
    return parseDocument(this.getValue());
  }

  /**
   * Accepts a `Document` as defined by the `yaml` package and
   * sets the Editor's value to a stringified version of it.
   * @param { Document } doc
   */
  setDoc(doc) {
    if (this.options.enableComments) {
      YamlEditorExtension.transformComments(doc);
    }

    if (!this.getValue()) {
      this.setValue(doc.toString());
    } else {
      this.updateValue(doc.toString());
    }
  }

  /**
   * Returns the parsed value of the Editor's content as JS.
   * @returns {*}
   */
  getDataModel() {
    return this.getDoc().toJS();
  }

  /**
   * Accepts any JS Object and sets the Editor's value to a stringified version
   * of that value.
   *
   * @param value
   */
  setDataModel(value) {
    this.setDoc(new Document(value));
  }

  /**
   * Method to be executed when the Editor's <TextModel> was updated
   */
  onUpdate() {
    if (this.options.highlightPath) {
      this.highlight(this.options.highlightPath);
    }
  }

  /**
   * Set the editors content to the input without recreating the content model.
   *
   * @param blob
   */
  updateValue(blob) {
    // Using applyEdits() instead of setValue() ensures that tokens such as
    // highlighted lines aren't deleted/recreated which causes a flicker.
    const model = this.getModel();
    model.applyEdits([
      {
        // A nice improvement would be to replace getFullModelRange() with
        // a range of the actual diff, avoiding re-formatting the document,
        // but that's something for a later iteration.
        range: model.getFullModelRange(),
        text: blob,
      },
    ]);
  }

  /**
   * Add a line highlight style to the node specified by the path.
   *
   * @param {string|null|false} path A path to a node of the Editor's value,
   * e.g. `"foo.bar[0]"`. If the value is falsy, this will remove all
   * highlights.
   */
  highlight(path) {
    if (this.options.highlightPath === path) return;
    if (!path) {
      SourceEditorExtension.removeHighlights(this);
    } else {
      const res = this.locate(path);
      SourceEditorExtension.highlightLines(this, res);
    }
    this.options.highlightPath = path || null;
  }

  /**
   * Return the line numbers of a certain node identified by `path` within
   * the yaml.
   *
   * @param {string} path A path to a node, eg. `foo.bar[0]`
   * @returns {number[]} Array following the schema `[firstLine, lastLine]`
   * (both inclusive)
   *
   * @throws {Error} Will throw if the path is not found inside the document
   */
  locate(path) {
    if (!path) throw Error(`No path provided.`);
    const blob = this.getValue();
    const doc = parseDocument(blob);
    const pathArray = toPath(path);

    if (!doc.getIn(pathArray)) {
      throw Error(`The node ${path} could not be found inside the document.`);
    }

    const parentNode = doc.getIn(pathArray.slice(0, pathArray.length - 1));
    let startChar;
    let endChar;
    if (isMap(parentNode)) {
      const node = parentNode.items.find(
        (item) => item.key.value === pathArray[pathArray.length - 1],
      );
      [startChar] = node.key.range;
      [, , endChar] = node.value.range;
    } else {
      const node = doc.getIn(pathArray);
      [startChar, , endChar] = node.range;
    }
    const startSlice = blob.slice(0, startChar);
    const endSlice = blob.slice(0, endChar);
    const startLine = (startSlice.match(/\n/g) || []).length + 1;
    const endLine = (endSlice.match(/\n/g) || []).length;
    return [startLine, endLine];
  }
}