vue-codemirror6 1.1.15 → 1.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,67 +8,46 @@ import {
8
8
  shallowRef,
9
9
  watch,
10
10
  type ComputedRef,
11
- type ObjectEmitsOptions,
12
11
  type PropType,
13
12
  type Ref,
14
- type SetupContext,
15
13
  type ShallowRef,
16
14
  type WritableComputedRef,
17
15
  } from 'vue-demi';
18
16
 
19
17
  // Helpers
20
18
  import h, { slot } from '@/helpers/h-demi';
21
- import { compact, trim } from 'lodash';
22
19
 
23
20
  // CodeMirror
24
21
  import { basicSetup, minimalSetup } from 'codemirror';
25
22
  import {
23
+ EditorView,
24
+ keymap,
25
+ placeholder,
26
+ type ViewUpdate,
27
+ } from '@codemirror/view';
28
+ import {
29
+ Compartment,
26
30
  EditorSelection,
27
31
  EditorState,
28
32
  StateEffect,
33
+ type Transaction,
29
34
  type Extension,
30
35
  type SelectionRange,
36
+ type StateField,
31
37
  type Text,
32
38
  } from '@codemirror/state';
33
39
  import {
34
- EditorView,
35
- keymap,
36
- placeholder,
37
- type ViewUpdate,
38
- } from '@codemirror/view';
39
- import { indentWithTab } from '@codemirror/commands';
40
- import {
40
+ diagnosticCount as linterDagnosticCount,
41
41
  forceLinting,
42
42
  linter,
43
43
  lintGutter,
44
+ type Diagnostic,
44
45
  type LintSource,
45
46
  } from '@codemirror/lint';
47
+ import { indentWithTab } from '@codemirror/commands';
46
48
  import type { LanguageSupport } from '@codemirror/language';
47
49
  import type { StyleSpec } from 'style-mod';
48
50
 
49
- /** Emit Interface */
50
- export interface CodeMirrorEmitsOptions extends ObjectEmitsOptions {
51
- /** Model Update */
52
- (e: 'update:modelValue', value: string | Text): void;
53
- /** CodeMirror ViewUpdate */
54
- (e: 'update', value: ViewUpdate): void;
55
- /** CodeMirror onFocus */
56
- (e: 'focus', value: boolean): void;
57
- /** CodeMirror onReady */
58
- (
59
- e: 'ready',
60
- value: {
61
- view: EditorView;
62
- state: EditorState;
63
- container: HTMLElement;
64
- }
65
- ): void;
66
- /** CodeMirror onDestroy */
67
- (e: 'destroy'): void;
68
- /** State Changed */
69
- (e: 'change', value: EditorState): void;
70
- }
71
-
72
51
  /** CodeMirror Component */
73
52
  export default defineComponent({
74
53
  /** Component Name */
@@ -91,7 +70,7 @@ export default defineComponent({
91
70
  * @see {@link https://codemirror.net/docs/ref/#view.EditorView^theme}
92
71
  */
93
72
  theme: {
94
- type: Object as PropType<{ [selector: string]: StyleSpec }>,
73
+ type: Object as PropType<Record<string, StyleSpec>>,
95
74
  default: () => {},
96
75
  },
97
76
  /** Dark Mode */
@@ -239,7 +218,9 @@ export default defineComponent({
239
218
  */
240
219
  linterConfig: {
241
220
  type: Object,
242
- default: () => undefined,
221
+ default: () => {
222
+ return { needsRefresh: true };
223
+ },
243
224
  },
244
225
  /**
245
226
  * Forces any linters configured to run when the editor is idle to run right away.
@@ -280,15 +261,31 @@ export default defineComponent({
280
261
  },
281
262
  },
282
263
  /** Emits */
283
- emits: ['update:modelValue', 'update', 'ready', 'focus', 'change', 'destroy'],
264
+ emits: {
265
+ /** Model Update */
266
+ 'update:modelValue': (value: string | Text) => true,
267
+ /** CodeMirror ViewUpdate */
268
+ update: (value: ViewUpdate) => true,
269
+ /** CodeMirror onReady */
270
+ ready: (value: {
271
+ view: EditorView;
272
+ state: EditorState;
273
+ container: HTMLElement;
274
+ }) => true,
275
+ /** CodeMirror onFocus */
276
+ focus: (value: boolean) => true,
277
+ /** State Changed */
278
+ change: (value: EditorState) => true,
279
+ /** CodeMirror onDestroy */
280
+ destroy: () => true,
281
+ },
284
282
  /**
285
283
  * Setup
286
284
  *
287
285
  * @param props - Props
288
286
  * @param context - Context
289
287
  */
290
- // @ts-ignore
291
- setup(props, context: SetupContext<CodeMirrorEmitsOptions>) {
288
+ setup(props, context) {
292
289
  /** Editor DOM */
293
290
  const editor: Ref<HTMLElement | undefined> = ref();
294
291
 
@@ -303,62 +300,87 @@ export default defineComponent({
303
300
  const view: ShallowRef<EditorView> = shallowRef(new EditorView());
304
301
 
305
302
  /**
306
- * Editor Selection
303
+ * Focus
307
304
  *
308
- * @see {@link https://codemirror.net/docs/ref/#state.EditorSelection}
305
+ * @see {@link https://codemirror.net/docs/ref/#view.EditorView.hasFocus}
309
306
  */
310
- const selection: WritableComputedRef<EditorSelection> = computed({
311
- get: () => view.value.state.selection,
312
- set: s => view.value.dispatch({ selection: s }),
307
+ const focus: WritableComputedRef<boolean> = computed({
308
+ get: () => view.value.hasFocus,
309
+ set: f => {
310
+ if (f) {
311
+ view.value.focus();
312
+ }
313
+ },
313
314
  });
314
315
 
315
316
  /**
316
- * Editor State
317
+ * Editor Selection
317
318
  *
318
- * @see {@link https://codemirror.net/docs/ref/#state.EditorState}
319
+ * @see {@link https://codemirror.net/docs/ref/#state.EditorSelection}
319
320
  */
320
- const state: WritableComputedRef<EditorState> = computed({
321
- get: () => view.value.state,
322
- set: s => view.value.setState(s),
321
+ const selection: WritableComputedRef<EditorSelection> = computed({
322
+ get: () => view.value.state.selection,
323
+ set: s => view.value.dispatch({ selection: s }),
323
324
  });
324
325
 
325
326
  /** Cursor Position */
326
327
  const cursor: WritableComputedRef<number> = computed({
327
- get: () => view.value.state.selection.main.head || 0,
328
+ get: () => view.value.state.selection.main.head,
328
329
  set: a => view.value.dispatch({ selection: { anchor: a } }),
329
330
  });
330
331
 
332
+ /** JSON */
333
+ const json: WritableComputedRef<Record<string, StateField<any>>> = computed(
334
+ {
335
+ get: () => view.value.state.toJSON(),
336
+ set: j => view.value.setState(EditorState.fromJSON(j)),
337
+ }
338
+ );
339
+
340
+ /** Text length */
341
+ const length: Ref<number> = ref(0);
342
+
331
343
  /**
332
- * Focus
344
+ * Returns the number of active lint diagnostics in the given state.
333
345
  *
334
- * @see {@link https://codemirror.net/docs/ref/#view.EditorView.hasFocus}
346
+ * @see {@link https://codemirror.net/docs/ref/#lint.diagnosticCount}
335
347
  */
336
- const focus: WritableComputedRef<boolean> = computed({
337
- get: () => view.value.hasFocus,
338
- set: f => {
339
- if (f) {
340
- view.value.focus();
341
- }
342
- },
343
- });
348
+ const diagnosticCount: Ref<number> = ref(0);
344
349
 
345
- /** Text length */
346
- const length: ComputedRef<number> = computed(
347
- () => view.value.state.doc.length
348
- );
350
+ // Synamic Reconfiguration
351
+ // @see https://codemirror.net/examples/config/
352
+
353
+ const language = new Compartment();
354
+ const tabSize = new Compartment();
349
355
 
350
356
  /** Get CodeMirror Extension */
351
357
  const extensions: ComputedRef<Extension[]> = computed(() =>
352
358
  // TODO: Ignore previous prop was not changed.
353
- compact<Extension>([
359
+ [
354
360
  // Toggle basic setup
355
361
  props.basic ? basicSetup : undefined,
356
362
  // Toggle minimal setup
357
363
  props.minimal && !props.basic ? minimalSetup : undefined,
358
364
  // ViewUpdate event listener
359
- EditorView.updateListener.of((update: ViewUpdate) =>
360
- context.emit('update', update)
361
- ),
365
+ EditorView.updateListener.of((update: ViewUpdate): void => {
366
+ if (update.changes.empty || !update.docChanged) {
367
+ // Suppress event firing if no change
368
+ return;
369
+ }
370
+ if (props.linter) {
371
+ // Linter process
372
+ if (props.forceLinting) {
373
+ // If forceLinting enabled, first liting.
374
+ forceLinting(view.value);
375
+ }
376
+ // Count diagnostics.
377
+ diagnosticCount.value = (
378
+ props.linter(view.value) as readonly Diagnostic[]
379
+ ).length;
380
+ }
381
+
382
+ context.emit('update', update);
383
+ }),
362
384
  // Toggle light/dark mode.
363
385
  EditorView.theme(props.theme, { dark: props.dark }),
364
386
  // Toggle line wrapping
@@ -368,7 +390,9 @@ export default defineComponent({
368
390
  // Allow Multiple Selections
369
391
  EditorState.allowMultipleSelections.of(props.allowMultipleSelections),
370
392
  // Indent tab size
371
- props.tabSize ? EditorState.tabSize.of(props.tabSize) : undefined,
393
+ props.tabSize
394
+ ? tabSize.of(EditorState.tabSize.of(props.tabSize))
395
+ : undefined,
372
396
  // locale settings
373
397
  props.phrases ? EditorState.phrases.of(props.phrases) : undefined,
374
398
  // Readonly option
@@ -380,7 +404,7 @@ export default defineComponent({
380
404
  ? EditorState.lineSeparator.of(props.lineSeparator)
381
405
  : undefined,
382
406
  // Lang
383
- props.lang ? props.lang.extension : undefined,
407
+ props.lang ? language.of(props.lang) : undefined,
384
408
  // Append Linter settings
385
409
  props.linter ? linter(props.linter, props.linterConfig) : undefined,
386
410
  // Show 🔴 to error line when linter enabled.
@@ -391,43 +415,41 @@ export default defineComponent({
391
415
  props.placeholder ? placeholder(props.placeholder) : undefined,
392
416
  // Append Extensions
393
417
  ...props.extensions,
394
- ])
418
+ ].filter((extension): extension is Extension => !!extension)
419
+ );
420
+
421
+ // Extension (mostly props) Changed
422
+ watch(
423
+ extensions,
424
+ exts => {
425
+ view.value?.dispatch({
426
+ effects: StateEffect.reconfigure.of(exts),
427
+ });
428
+ },
429
+ { immediate: true }
395
430
  );
396
431
 
397
432
  // for parent-to-child binding.
398
433
  watch(
399
434
  () => props.modelValue,
400
- value => {
435
+ async value => {
401
436
  if (view.value.composing) {
402
437
  // IME fix
403
438
  return;
404
439
  }
405
440
 
406
- // Enable Force Linting
407
- if (props.linter && props.forceLinting) {
408
- forceLinting(view.value);
409
- }
410
-
411
441
  // Update
412
442
  view.value.dispatch({
413
443
  changes: { from: 0, to: view.value.state.doc.length, insert: value },
414
444
  selection: view.value.state.selection,
415
445
  scrollIntoView: true,
416
446
  });
447
+ // Update count
448
+ length.value = view.value.state.doc.length;
417
449
  },
418
450
  { immediate: true }
419
451
  );
420
452
 
421
- // Extension (mostly props) Changed
422
- watch(
423
- () => extensions.value,
424
- exts => {
425
- view.value.dispatch({
426
- effects: StateEffect.reconfigure.of(exts),
427
- });
428
- }
429
- );
430
-
431
453
  // focus changed
432
454
  watch(focus, isFocus => context.emit('focus', isFocus));
433
455
 
@@ -435,36 +457,43 @@ export default defineComponent({
435
457
  onMounted(async () => {
436
458
  /** Initial value */
437
459
  let value: string | Text = doc.value;
438
- if (editor.value && editor.value.childNodes[0]) {
460
+ if (!editor.value) {
461
+ return;
462
+ }
463
+ if (editor.value.childNodes[0]) {
439
464
  // when slot mode, overwrite initial value
440
465
  if (doc.value !== '') {
441
466
  console.warn(
442
467
  '[CodeMirror.vue] The <code-mirror> tag contains child elements that overwrite the `v-model` values.'
443
468
  );
444
469
  }
445
- value = trim((editor.value.childNodes[0] as HTMLElement).innerText);
470
+ value = (editor.value.childNodes[0] as HTMLElement).innerText.trim();
446
471
  }
447
472
 
448
473
  // Register Codemirror
449
474
  view.value = new EditorView({
450
- doc: value,
451
- extensions: extensions.value,
452
475
  parent: editor.value,
453
- dispatch: tr => {
476
+ state: EditorState.create({ doc: value, extensions: extensions.value }),
477
+ dispatch: (tr: Transaction) => {
454
478
  view.value.update([tr]);
455
- // TODO: Emit lint error event
479
+
480
+ if (tr.changes.empty || !tr.docChanged) {
481
+ // if not change value, no fire emit event
482
+ return;
483
+ }
484
+
456
485
  // console.log(view.state.doc.toString(), tr);
457
- if (tr.changes.empty) return;
458
- // child-to-parent binding
459
- const v = view.value.state.doc.toString();
460
- context.emit('update:modelValue', v);
461
- context.emit('change', view.value.state);
486
+ // state.toString() is not defined, so use toJSON and toText function to convert string.
487
+ context.emit('update:modelValue', (tr.state.doc as any).toString());
488
+ // Emit EditorState
489
+ context.emit('change', tr.state);
462
490
  },
463
491
  });
464
492
 
465
493
  await nextTick();
494
+
466
495
  context.emit('ready', {
467
- view: view,
496
+ view: view.value,
468
497
  state: view.value.state,
469
498
  container: editor.value,
470
499
  });
@@ -472,10 +501,8 @@ export default defineComponent({
472
501
 
473
502
  /** Destroy */
474
503
  onUnmounted(() => {
475
- if (view.value) {
476
- view.value.destroy();
477
- context.emit('destroy');
478
- }
504
+ view.value.destroy();
505
+ context.emit('destroy');
479
506
  });
480
507
 
481
508
  /**
@@ -483,10 +510,14 @@ export default defineComponent({
483
510
  *
484
511
  * @see {@link https://codemirror.net/docs/ref/#lint.forceLinting}
485
512
  */
486
- const lint = () => {
487
- if (props.linter) {
513
+ const lint = (): void => {
514
+ if (!props.linter || !view.value) {
515
+ return;
516
+ }
517
+ if (props.forceLinting) {
488
518
  forceLinting(view.value);
489
519
  }
520
+ diagnosticCount.value = linterDagnosticCount(view.value.state);
490
521
  };
491
522
 
492
523
  /**
@@ -494,13 +525,13 @@ export default defineComponent({
494
525
  *
495
526
  * @see {@link https://codemirror.net/examples/config/#top-level-reconfiguration}
496
527
  */
497
- const forceReconfigure = () => {
528
+ const forceReconfigure = (): void => {
498
529
  // Deconfigure all Extensions
499
- view.value.dispatch({
530
+ view.value?.dispatch({
500
531
  effects: StateEffect.reconfigure.of([]),
501
532
  });
502
533
  // Register extensions
503
- view.value.dispatch({
534
+ view.value?.dispatch({
504
535
  effects: StateEffect.appendConfig.of(extensions.value),
505
536
  });
506
537
  };
@@ -513,7 +544,7 @@ export default defineComponent({
513
544
  * @param from - start line number
514
545
  * @param to - end line number
515
546
  */
516
- const getRange = (from?: number, to?: number): string =>
547
+ const getRange = (from?: number, to?: number): string | undefined =>
517
548
  view.value.state.sliceDoc(from, to);
518
549
  /**
519
550
  * Get the content of line.
@@ -525,24 +556,30 @@ export default defineComponent({
525
556
  /** Get the number of lines in the editor. */
526
557
  const lineCount = (): number => view.value.state.doc.lines;
527
558
  /** Retrieve one end of the primary selection. */
528
- const getCursor = (): number => cursor.value;
559
+ const getCursor = (): number => view.value.state.selection.main.head;
529
560
  /** Retrieves a list of all current selections. */
530
561
  const listSelections = (): readonly SelectionRange[] =>
531
- view.value.state.selection.ranges;
562
+ view.value.state.selection.ranges ?? [];
532
563
  /** Get the currently selected code. */
533
564
  const getSelection = (): string =>
534
565
  view.value.state.sliceDoc(
535
566
  view.value.state.selection.main.from,
536
567
  view.value.state.selection.main.to
537
- );
568
+ ) ?? '';
538
569
  /**
539
570
  * The length of the given array should be the same as the number of active selections.
540
571
  * Replaces the content of the selections with the strings in the array.
541
572
  */
542
- const getSelections = (): string[] =>
543
- view.value.state.selection.ranges.map((r: { from: number; to: number }) =>
544
- view.value.state.sliceDoc(r.from, r.to)
573
+ const getSelections = (): string[] => {
574
+ const s = view.value.state;
575
+ if (!s) {
576
+ return [];
577
+ }
578
+
579
+ return s.selection.ranges.map((r: { from: number; to: number }) =>
580
+ s.sliceDoc(r.from, r.to)
545
581
  );
582
+ };
546
583
  /** Return true if any text is selected. */
547
584
  const somethingSelected = (): boolean =>
548
585
  view.value.state.selection.ranges.some(
@@ -560,7 +597,7 @@ export default defineComponent({
560
597
  replacement: string | Text,
561
598
  from: number,
562
599
  to: number
563
- ) =>
600
+ ): void =>
564
601
  view.value.dispatch({
565
602
  changes: { from, to, insert: replacement },
566
603
  });
@@ -570,21 +607,22 @@ export default defineComponent({
570
607
  *
571
608
  * @param replacement - replacement text
572
609
  */
573
- const replaceSelection = (replacement: string | Text) =>
610
+ const replaceSelection = (replacement: string | Text): void =>
574
611
  view.value.dispatch(view.value.state.replaceSelection(replacement));
575
612
  /**
576
613
  * Set the cursor position.
577
614
  *
578
615
  * @param position - position.
579
616
  */
580
- const setCursor = (position: number): number => (cursor.value = position);
617
+ const setCursor = (position: number): void =>
618
+ view.value.dispatch({ selection: { anchor: position } });
581
619
  /**
582
620
  * Set a single selection range.
583
621
  *
584
622
  * @param anchor - anchor position
585
623
  * @param head -
586
624
  */
587
- const setSelection = (anchor: number, head?: number) =>
625
+ const setSelection = (anchor: number, head?: number): void =>
588
626
  view.value.dispatch({ selection: { anchor, head } });
589
627
  /**
590
628
  * Sets a new set of selections. There must be at least one selection in the given array.
@@ -595,7 +633,7 @@ export default defineComponent({
595
633
  const setSelections = (
596
634
  ranges: readonly SelectionRange[],
597
635
  primary?: number
598
- ) =>
636
+ ): void =>
599
637
  view.value.dispatch({
600
638
  selection: EditorSelection.create(ranges, primary),
601
639
  });
@@ -604,7 +642,7 @@ export default defineComponent({
604
642
  *
605
643
  * @param f - function
606
644
  */
607
- const extendSelectionsBy = (f: Function) =>
645
+ const extendSelectionsBy = (f: any): void =>
608
646
  view.value.dispatch({
609
647
  selection: EditorSelection.create(
610
648
  selection.value.ranges.map((r: SelectionRange) => r.extend(f(r)))
@@ -614,11 +652,13 @@ export default defineComponent({
614
652
  /** Export properties and functions */
615
653
  context.expose({
616
654
  editor,
655
+ view,
617
656
  cursor,
618
657
  selection,
619
- state,
620
658
  focus,
621
659
  length,
660
+ json,
661
+ diagnosticCount,
622
662
  lint,
623
663
  forceReconfigure,
624
664
  // Bellow is CodeMirror5's function
@@ -649,19 +689,16 @@ export default defineComponent({
649
689
  // </div>
650
690
  // </template>
651
691
  return h(
652
- // @ts-ignore
653
692
  this.$props.tag,
654
693
  {
655
694
  ref: 'editor',
656
695
  class: 'vue-codemirror',
657
696
  },
658
- // @ts-ignore
659
697
  this.$slots.default
660
698
  ? // Hide original content
661
699
  h(
662
700
  'aside',
663
701
  { style: 'display: none;', 'aria-hidden': 'true' },
664
- // @ts-ignore
665
702
  slot(this.$slots.default)
666
703
  )
667
704
  : undefined