2021-05-25 18:35:08 +01:00
|
|
|
import { Component, JSX, createRef } from "preact";
|
|
|
|
import { CodeJar as _CodeJar } from "codejar";
|
2021-05-26 09:20:04 +01:00
|
|
|
import { highlightElement } from "prismjs";
|
2021-05-24 11:49:49 +01:00
|
|
|
|
2021-05-25 18:35:08 +01:00
|
|
|
interface CodeJarProps {
|
|
|
|
language: string;
|
|
|
|
tabSize: number;
|
2021-05-24 11:49:49 +01:00
|
|
|
code: string;
|
|
|
|
onUpdate: (code: string) => void;
|
|
|
|
}
|
|
|
|
|
2021-05-25 18:35:08 +01:00
|
|
|
export class CodeJarEditor extends Component<CodeJarProps, unknown> {
|
|
|
|
editorRef = createRef<HTMLDivElement>();
|
|
|
|
jar = createRef<_CodeJar | null>();
|
2021-05-24 11:49:49 +01:00
|
|
|
|
2021-05-26 09:20:04 +01:00
|
|
|
highlighter(e: HTMLElement, pos?: unknown): void {
|
|
|
|
highlightElement(e);
|
|
|
|
}
|
|
|
|
|
2021-05-25 18:35:08 +01:00
|
|
|
componentDidMount(): void {
|
2021-05-26 09:20:04 +01:00
|
|
|
this.jar.current = _CodeJar(this.editorRef.current, this.highlighter, {
|
2021-05-25 18:35:08 +01:00
|
|
|
tab: " ".repeat(this.props.tabSize),
|
|
|
|
window: window,
|
2021-05-24 11:49:49 +01:00
|
|
|
});
|
|
|
|
|
2021-05-25 18:35:08 +01:00
|
|
|
this.jar.current.updateCode(this.props.code);
|
2021-05-24 11:49:49 +01:00
|
|
|
|
2021-05-25 18:35:08 +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
|
|
|
}
|