organic_ast_explorer/src/Explorer.tsx

83 lines
2.3 KiB
TypeScript

import React, { useMemo, useState } from "react";
import styles from "./Explorer.module.css";
import { Highlight } from "./highlight";
import OrgAst, { OrgNodeReference } from "./OrgAst";
import { parse_org } from "../../organic/target/wasm32-unknown-unknown/js/wasm";
import Editor from "./Editor";
const default_org_source: string = `* Welcome to the Organic Ast Explorer!
Type your Org [fn:1] source in this text box, and it will be parsed by Organic [fn:2] that has been compiled into wasm and embedded in this page. The resulting AST will be rendered to the right.
In the AST on the right, you can:
1. Click on an AST node to highlight the corresponding portion of the Org source on the left.
2. Expand/Collapse the children, properties, and standard properties.
* Footnotes
[fn:1] https://orgmode.org/
[fn:2] https://code.fizz.buzz/talexander/organic
`;
interface ExplorerProps {
defaultValue?: string;
}
function Explorer({ defaultValue = default_org_source }: ExplorerProps) {
const [value, setValue] = useState(defaultValue);
const [highlights, setHighlights] = useState<Array<Highlight>>([]);
const astTree = useMemo(() => {
const astTree = parse_org(value);
console.log(JSON.stringify(astTree));
return astTree;
}, [value]);
function setHighlight(nodes: OrgNodeReference[]) {
let new_highlights = nodes.map((node: OrgNodeReference) => {
return new Highlight(node.start - 1, node.end - 1);
});
new_highlights.sort(function (a, b) {
if (a.start < b.start) return -1;
if (a.start > b.start) return 1;
return 0;
});
setHighlights(new_highlights);
}
function addHighlight(start: number, end: number) {
let new_highlights = [...highlights, new Highlight(start, end)];
new_highlights.sort(function (a, b) {
if (a.start < b.start) return -1;
if (a.start > b.start) return 1;
return 0;
});
setHighlights(new_highlights);
}
function clearHighlights() {
setHighlights([]);
}
return (
<div className={styles.Explorer}>
<Editor
value={value}
setValue={setValue}
highlights={highlights}
clearHighlights={clearHighlights}
/>
<OrgAst
setHighlight={setHighlight}
clearHighlights={clearHighlights}
value={value}
astTree={astTree}
/>
</div>
);
}
export default Explorer;