From ad9ced92ac613ec80e2c25df24d741003ba3b0fa Mon Sep 17 00:00:00 2001 From: clfreville2 Date: Wed, 24 Jan 2024 15:17:42 +0100 Subject: [PATCH] Force state redraw when editing the state array --- .../src/lib/codemirror6-editor.component.ts | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/projects/codemirror6-editor/src/lib/codemirror6-editor.component.ts b/projects/codemirror6-editor/src/lib/codemirror6-editor.component.ts index 76e6f69..7d20a0f 100644 --- a/projects/codemirror6-editor/src/lib/codemirror6-editor.component.ts +++ b/projects/codemirror6-editor/src/lib/codemirror6-editor.component.ts @@ -7,7 +7,7 @@ import { NgZone, OnDestroy } from '@angular/core'; -import { EditorState, Extension, StateEffect } from '@codemirror/state'; +import { EditorState, Extension } from '@codemirror/state'; import { EditorView } from '@codemirror/view'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms"; @@ -28,26 +28,33 @@ export class CodeMirrorComponent implements AfterViewInit, OnDestroy, ControlVal @Input() set extensions(extensions: Extension[]) { - this.editor?.dispatch({ - effects: StateEffect.reconfigure.of(extensions), + const state = EditorState.create({ + extensions: [...extensions, this.updateListener] }); + if (this.editor) { + this.editor.setState(state); + } else { + this.editor = new EditorView({ + state, + parent: this.host.nativeElement, + }); + } } editor: EditorView | null = null; private handleChange: (value: string) => void = () => {}; + private readonly updateListener = EditorView.updateListener.of((update) => { + this.ngZone.run(() => { + const value = update.state.doc.toString(); + this.handleChange(value); + }); + }); constructor(private host: ElementRef, private ngZone: NgZone) {} ngAfterViewInit(): void { const state = EditorState.create({ - extensions: [ - EditorView.updateListener.of((update) => { - this.ngZone.run(() => { - const value = update.state.doc.toString(); - this.handleChange(value); - }); - }), - ], + extensions: [this.updateListener], }); this.editor = new EditorView({ state,