|
| 1 | +import { Fragment, useRef, useState } from 'react'; |
| 2 | +import { ViewPlugin, ViewUpdate } from '@codemirror/view'; |
| 3 | +import { StateEffect } from '@codemirror/state'; |
| 4 | +import CodeMirrorMerge, { type CodeMirrorMergeRef } from 'react-codemirror-merge'; |
| 5 | + |
| 6 | +const Original = CodeMirrorMerge.Original; |
| 7 | +const Modified = CodeMirrorMerge.Modified; |
| 8 | +let doc = `one |
| 9 | +two |
| 10 | +three |
| 11 | +four |
| 12 | +five`; |
| 13 | + |
| 14 | +const log1UpdatePlugin = ViewPlugin.fromClass( |
| 15 | + class { |
| 16 | + update(update: ViewUpdate) { |
| 17 | + if (update.docChanged) { |
| 18 | + console.log('Document changed! test 1'); |
| 19 | + } |
| 20 | + } |
| 21 | + }, |
| 22 | +); |
| 23 | + |
| 24 | +const log2UpdatePlugin = ViewPlugin.fromClass( |
| 25 | + class { |
| 26 | + update(update: ViewUpdate) { |
| 27 | + if (update.docChanged) { |
| 28 | + console.log('Document changed! test 2'); |
| 29 | + } |
| 30 | + } |
| 31 | + }, |
| 32 | +); |
| 33 | + |
| 34 | +/** |
| 35 | + * https://github.com/uiwjs/react-codemirror/issues/681#issuecomment-2341521112 |
| 36 | + */ |
| 37 | +export function Component() { |
| 38 | + return ( |
| 39 | + <Fragment> |
| 40 | + <Example /> |
| 41 | + </Fragment> |
| 42 | + ); |
| 43 | +} |
| 44 | + |
| 45 | +function Example() { |
| 46 | + const [value, setValue] = useState(doc); |
| 47 | + const [valueModified, setValueModified] = useState(doc); |
| 48 | + const $ref = useRef<CodeMirrorMergeRef>(null); |
| 49 | + const handle1 = () => { |
| 50 | + $ref.current?.view?.a.dispatch({ |
| 51 | + effects: StateEffect.appendConfig.of([log2UpdatePlugin]), |
| 52 | + }); |
| 53 | + }; |
| 54 | + return ( |
| 55 | + <div style={{ width: '100%' }}> |
| 56 | + <div> |
| 57 | + <button onClick={handle1}>Add extension 2</button> |
| 58 | + </div> |
| 59 | + <CodeMirrorMerge ref={$ref} destroyRerender={false}> |
| 60 | + <Original |
| 61 | + value={value} |
| 62 | + extensions={[log1UpdatePlugin]} |
| 63 | + onChange={(val) => { |
| 64 | + setValue(val); |
| 65 | + }} |
| 66 | + /> |
| 67 | + <Modified |
| 68 | + value={valueModified} |
| 69 | + onChange={(val) => { |
| 70 | + setValueModified(val); |
| 71 | + }} |
| 72 | + /> |
| 73 | + </CodeMirrorMerge> |
| 74 | + <div style={{ display: 'flex', marginTop: 10 }}> |
| 75 | + <pre style={{ flex: 1 }}>{value} </pre> |
| 76 | + <pre style={{ backgroundColor: '#fff', flex: 1 }}>{valueModified} </pre> |
| 77 | + </div> |
| 78 | + </div> |
| 79 | + ); |
| 80 | +} |
0 commit comments