1
0
Fork 0
VaultUI/src/elements/CodeJar/CodeJarEditor.tsx

55 lines
1.3 KiB
TypeScript
Raw Normal View History

import { Component, JSX, createRef } from "preact";
import { CodeJar as _CodeJar } from "codejar";
import { highlightElement } from "prismjs";
2021-05-24 11:49:49 +01:00
interface CodeJarProps {
language: string;
tabSize: number;
2021-05-24 11:49:49 +01:00
code: string;
onUpdate: (code: string) => void;
}
export class CodeJarEditor extends Component<CodeJarProps, unknown> {
editorRef = createRef<HTMLDivElement>();
jar = createRef<_CodeJar | null>();
2021-05-24 11:49:49 +01:00
highlighter(e: HTMLElement, pos?: unknown): void {
highlightElement(e);
}
componentDidMount(): void {
this.jar.current = _CodeJar(this.editorRef.current, this.highlighter, {
tab: " ".repeat(this.props.tabSize),
window: window,
2021-05-24 11:49:49 +01:00
});
this.jar.current.updateCode(this.props.code);
2021-05-24 11:49:49 +01:00
this.jar.current.onUpdate((txt) => {
this.props.onUpdate(txt);
});
}
componentWillUnmount(): void {
if (this.jar.current) {
this.jar.current.destroy();
}
}
componentDidUpdate(prevProps: CodeJarProps): void {
if (!this.jar.current) return;
if (
prevProps.code !== this.props.code ||
prevProps.tabSize !== this.props.tabSize ||
prevProps.language !== this.props.language
) {
this.componentDidMount();
}
}
render(): JSX.Element {
return <div class={"editor language-" + this.props.language} ref={this.editorRef} />;
}
2021-05-24 11:49:49 +01:00
}