1
0
Fork 0
VaultUI/src/elements/CodeEditor.tsx

57 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
2021-05-26 10:13:38 +01:00
interface CodeEditorProps {
language: string;
tabSize: number;
2021-05-24 11:49:49 +01:00
code: string;
onUpdate: (code: string) => void;
}
2021-05-26 10:13:38 +01:00
export class CodeEditor extends Component<CodeEditorProps, unknown> {
editorRef = createRef<HTMLDivElement>();
jar = createRef<_CodeJar | null>();
2021-05-24 11:49:49 +01:00
2021-05-26 10:13:38 +01:00
highlighter(e: HTMLElement): void {
highlightElement(e);
}
componentDidMount(): void {
2021-05-26 10:13:38 +01:00
this.jar.current = _CodeJar(this.editorRef.current, (e) => this.highlighter(e), {
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();
}
}
2021-05-26 10:13:38 +01:00
componentDidUpdate(prevProps: CodeEditorProps): 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 {
2021-05-26 10:13:38 +01:00
return (
<div class={"editor line-numbers language-" + this.props.language} ref={this.editorRef} />
);
}
2021-05-24 11:49:49 +01:00
}