2024-08-30 00:47:35 +00:00
|
|
|
'use client';
|
|
|
|
|
|
|
|
|
|
import { Compartment, Extension } from "@codemirror/state";
|
|
|
|
|
import { EditorView } from "@codemirror/view";
|
|
|
|
|
import { useEffect, useMemo } from "react";
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @see https://thetrevorharmon.com/blog/codemirror-and-react/
|
|
|
|
|
*/
|
|
|
|
|
export function useExtensionWithDependency(
|
|
|
|
|
view: EditorView | null,
|
|
|
|
|
extensionFactory: () => Extension,
|
2024-08-30 04:38:48 +00:00
|
|
|
deps: unknown[],
|
2024-08-30 00:47:35 +00:00
|
|
|
) {
|
|
|
|
|
const compartment = useMemo(() => new Compartment(), []);
|
2024-08-30 04:38:48 +00:00
|
|
|
const extension = useMemo(() => compartment.of(extensionFactory()), [compartment, extensionFactory]);
|
2024-08-30 00:47:35 +00:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
if (view) {
|
|
|
|
|
view.dispatch({
|
|
|
|
|
effects: compartment.reconfigure(extensionFactory()),
|
|
|
|
|
});
|
|
|
|
|
}
|
2024-08-30 04:38:48 +00:00
|
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
2024-08-30 00:47:35 +00:00
|
|
|
}, deps);
|
|
|
|
|
|
|
|
|
|
return extension;
|
|
|
|
|
}
|