Skip to content

Commit

Permalink
update source when model changes
Browse files Browse the repository at this point in the history
  • Loading branch information
TaiSakuma committed Sep 7, 2023
1 parent 9a4091c commit 6ba84c7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
12 changes: 12 additions & 0 deletions src/components/main/trace-frame/code-col/__tests__/model.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,16 @@ describe("useModel()", () => {
await nextTick();
expect(model.getValue()).toBe("# New source");
});

it('edit model', async () => {
const source = ref("# Hello, world!");
const { model } = useModel(source);
expect(model.getValue()).toBe("# Hello, world!");
model.setValue("# New source");
await new Promise((resolve) => setTimeout(resolve, 110));
expect(source.value).toBe("# New source");
model.setValue("# New source 2");
await new Promise((resolve) => setTimeout(resolve, 110));
expect(source.value).toBe("# New source 2");
});
});
24 changes: 21 additions & 3 deletions src/components/main/trace-frame/code-col/monaco-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ import {
watchEffect,
onMounted,
} from "vue";
import type { Ref, MaybeRefOrGetter, MaybeRef } from "vue";
import type { MaybeRefOrGetter, MaybeRef } from "vue";
import { useDebounceFn } from "@vueuse/core";
import * as monaco from "monaco-editor";

export function useMonacoEditor(
element: MaybeRef<HTMLElement | undefined>,
source?: MaybeRef<string>,
language = "python"
) {

const { model, source: source_ } = useModel(source, language);
source = source_;

Expand Down Expand Up @@ -51,12 +51,30 @@ export function useMonacoEditor(
return { editor, model, source };
}

export function useModel(source?: MaybeRef<string>, language = "python") {
export function useModel(
source?: MaybeRef<string>,
language = "python",
sourceUpdateDelayMilliseconds = 50,
sourceUpdateMaxWaitMilliseconds = 100
) {
const _source = source === undefined ? ref("") : ref(source);
const model = monaco.editor.createModel(_source.value, language);

// Update model when source changes.
watchEffect(() => {
model.setValue(_source.value);
});

// Update source when model changes (debounced).
const updateSource = useDebounceFn(
() => {
_source.value = model.getValue();
},
sourceUpdateDelayMilliseconds,
{ maxWait: sourceUpdateMaxWaitMilliseconds }
);
model.onDidChangeContent(updateSource);

return { model, source: _source };
}

Expand Down

0 comments on commit 6ba84c7

Please sign in to comment.