Add support for variable links

This commit is contained in:
Ayaz Hafiz 2023-08-02 12:10:53 -05:00
parent cf71176bc5
commit a5eaba9ab3
No known key found for this signature in database
GPG key ID: 0E2A37416A25EF58
6 changed files with 271 additions and 127 deletions

View file

@ -4,6 +4,7 @@ import { QuerySubs, TypeDescriptor } from "../../engine/subs";
import { Variable } from "../../schema";
import DrawHeadConstructor from "../Content/HeadConstructor";
import { contentStyles } from "./../Content";
import { VariableName } from "./VariableName";
interface VariableElProps {
variable: Variable;
@ -51,23 +52,6 @@ function Helper({
desc: TypeDescriptor | undefined;
}): JSX.Element {
const { bg } = contentStyles(desc);
const varHeader =
!nested || raw ? (
<span
className={clsx(
"ring-1 ring-inset ring-black-100 px-1 bg-white rounded-md cursor",
nested ? "text-md" : "p-0.5"
)}
onClick={(e) => {
e.stopPropagation();
onClick?.(variable);
}}
>
{variable}
</span>
) : (
<></>
);
return (
<span
className={clsx(
@ -76,7 +60,13 @@ function Helper({
nested ? "text-sm" : "p-0.5 pl-0 text-base"
)}
>
{varHeader}
{(!nested || raw) && (
<VariableName
variable={variable}
onClick={onClick}
className={nested ? "text-md" : "p-0.5"}
/>
)}
{children ? <span className="px-1">{children}</span> : <></>}
</span>
);

View file

@ -0,0 +1,34 @@
import clsx from "clsx";
import { QuerySubs } from "../../engine/subs";
import { Variable } from "../../schema";
import { VariableName } from "./VariableName";
export interface VariableLinkProps {
variable: Variable;
subs: QuerySubs;
onClick?: (variable: Variable) => void;
}
export function VariableLink({
variable,
subs,
onClick,
}: VariableLinkProps): JSX.Element {
const root = subs.get_root_key(variable);
if (variable === root) {
throw new Error("VariableLink: variable is root");
}
return (
<div className={clsx("rounded-md whitespace-nowrap space-x-1")}>
<VariableName className="inline-block" variable={variable} />
<span></span>
<VariableName
className="inline-block"
variable={root}
onClick={onClick}
/>
</div>
);
}

View file

@ -0,0 +1,30 @@
import clsx from "clsx";
import { Variable } from "../../schema";
export interface VariableNameProps {
variable: Variable;
onClick?: (variable: Variable) => void;
className?: string;
}
export function VariableName({
variable,
onClick,
className,
}: VariableNameProps): JSX.Element {
return (
<span
className={clsx(
"ring-1 ring-inset ring-black-100 px-1 bg-white rounded-md",
onClick && "cursor-pointer",
className
)}
onClick={(e) => {
e.stopPropagation();
onClick?.(variable);
}}
>
{variable}
</span>
);
}

View file

@ -64,3 +64,5 @@ export function contentStyles(desc: TypeDescriptor | undefined): ContentStyles {
return { name: "Error", bg: "bg-red-400" };
}
}
export const LinkStyles: ContentStyles = { name: "Link", bg: "bg-slate-500" };

View file

@ -2,13 +2,20 @@ import clsx from "clsx";
import { Handle, Position } from "reactflow";
import { Variable } from "../../schema";
import { assertExhaustive } from "../../utils/exhaustive";
import { contentStyles } from "../Content";
import { contentStyles, LinkStyles } from "../Content";
import { VariableElPretty } from "../Common/Variable";
import { SubsSnapshot, TypeDescriptor } from "../../engine/subs";
import { useEffect, useState } from "react";
import { TypedEmitter } from "tiny-typed-emitter";
import { VariableLink } from "../Common/VariableLink";
type AddSubVariableLink = (from: Variable, subVariable: Variable) => void;
type AddSubVariableLink = ({
from,
variable,
}: {
from: Variable;
variable: Variable;
}) => void;
export interface VariableMessageEvents {
focus: (variable: Variable) => void;
@ -17,7 +24,7 @@ export interface VariableMessageEvents {
export interface VariableNodeProps {
data: {
subs: SubsSnapshot;
variable: Variable;
rawVariable: Variable;
addSubVariableLink: AddSubVariableLink;
isOutlined: boolean;
ee: TypedEmitter<VariableMessageEvents>;
@ -32,8 +39,8 @@ export default function VariableNode({
sourcePosition,
}: VariableNodeProps): JSX.Element {
const {
variable,
subs,
rawVariable,
addSubVariableLink,
isOutlined: isOutlinedProp,
ee: eeProp,
@ -43,10 +50,10 @@ export default function VariableNode({
useEffect(() => {
eeProp.on("focus", (focusVar: Variable) => {
if (focusVar !== variable) return;
if (focusVar !== rawVariable) return;
setIsOutlined(true);
});
}, [eeProp, variable]);
}, [eeProp, rawVariable]);
useEffect(() => {
if (!isOutlined) return;
@ -59,36 +66,82 @@ export default function VariableNode({
};
}, [isOutlined]);
const desc = subs.get_root(variable);
const styles = contentStyles(desc);
const basis: BasisProps = {
subs,
origin: variable,
addSubVariableLink,
};
const varType = subs.get(rawVariable);
if (!varType) throw new Error("VariableNode: no entry for variable");
const content = Object.entries(
VariableNodeContent(variable, desc, basis)
).filter((el): el is [string, JSX.Element] => !!el[1]);
let renderContent: JSX.Element;
let bgStyles: string;
const isContent = varType.type === "descriptor";
switch (varType.type) {
case "link": {
bgStyles = LinkStyles.bg;
let expandedContent = <></>;
if (content.length > 0) {
expandedContent = (
<ul className="text-sm text-left mt-2 space-y-1">
{content.map(([key, value], i) => (
<li key={i} className="space-x-2">
{key}: {value}
</li>
))}
</ul>
);
renderContent = (
<VariableLink
subs={subs}
variable={rawVariable}
onClick={() =>
addSubVariableLink({
from: rawVariable,
variable: subs.get_root_key(rawVariable),
})
}
/>
);
break;
}
case "descriptor": {
const variable = rawVariable;
const desc: TypeDescriptor = varType;
const styles = contentStyles(desc);
bgStyles = styles.bg;
const basis: BasisProps = {
subs,
origin: variable,
addSubVariableLink,
};
const content = Object.entries(
VariableNodeContent(variable, desc, basis)
).filter((el): el is [string, JSX.Element] => !!el[1]);
let expandedContent = <></>;
if (content.length > 0) {
expandedContent = (
<ul className="text-sm text-left mt-2 space-y-1">
{content.map(([key, value], i) => (
<li key={i} className="space-x-2">
{key}: {value}
</li>
))}
</ul>
);
}
renderContent = (
<>
<div>
<VariableElPretty variable={variable} subs={subs} />
</div>
{expandedContent}
</>
);
break;
}
default: {
assertExhaustive(varType);
}
}
return (
<div
className={clsx(
styles.bg,
"bg-opacity-50 py-2 px-4 rounded-lg border transition ease-in-out duration-700",
bgStyles,
"bg-opacity-50 rounded-lg transition ease-in-out duration-700",
isContent ? "py-2 px-4 border" : "p-0",
isOutlined && "ring-2 ring-blue-500",
"text-center font-mono"
)}
@ -97,15 +150,14 @@ export default function VariableNode({
type="target"
position={targetPosition ?? Position.Top}
isConnectable={false}
style={{ background: "transparent", border: "none" }}
/>
<div>
<VariableElPretty variable={variable} subs={subs} />
</div>
{expandedContent}
{renderContent}
<Handle
type="source"
position={sourcePosition ?? Position.Bottom}
isConnectable={false}
style={{ background: "transparent", border: "none" }}
/>
</div>
);
@ -238,7 +290,7 @@ function SubVariable({
<VariableElPretty
variable={variable}
subs={subs}
onClick={() => addSubVariableLink(origin, variable)}
onClick={() => addSubVariableLink({ from: origin, variable })}
/>
);
}

View file

@ -18,6 +18,8 @@ import ReactFlow, {
useStore,
ReactFlowState,
Position,
MarkerType,
EdgeMarkerType,
} from "reactflow";
import { useCallback, useEffect, useRef, useState } from "react";
import { Variable } from "../../schema";
@ -154,7 +156,9 @@ async function computeLayoutedElements({
//height: 50,
})),
//@ts-ignore
edges: edges,
edges: edges.map((edge) => ({
...edge,
})),
};
const layoutedGraph = await elk.layout(graph);
@ -197,20 +201,22 @@ function newVariable(
};
}
function addNodeChange(node: Node, existingNodes: Node[]): NodeChange | null {
if (existingNodes.some((n) => n.id === node.id)) {
return null;
}
function canAddVariable(variableName: string, existingNodes: Node[]): boolean {
return !existingNodes.some((n) => n.id === variableName);
}
function canAddEdge(edgeName: string, existingEdges: Edge[]): boolean {
return !existingEdges.some((e) => e.id === edgeName);
}
function addNode(node: Node): NodeChange {
return {
type: "add",
item: node,
};
}
function addEdgeChange(edge: Edge, existingEdges: Edge[]): EdgeChange | null {
if (existingEdges.some((e) => e.id === edge.id)) {
return null;
}
function addEdge(edge: Edge): EdgeChange {
return {
type: "add",
item: edge,
@ -322,13 +328,26 @@ function Graph({
const initialEdges: Edge[] = [];
const ee = useRef(new TypedEmitter<VariableMessageEvents>());
// Allow an unbounded number of listeners since we attach a listener for each
// variable.
ee.current.setMaxListeners(Infinity);
const [variablesNeedingFocus, setVariablesNeedingFocus] = useState<
Set<Variable>
>(new Set());
useEffect(() => {
if (variablesNeedingFocus.size === 0) {
return;
}
for (const variable of variablesNeedingFocus) {
ee.current.emit("focus", variable);
}
setVariablesNeedingFocus(new Set());
}, [variablesNeedingFocus]);
const [layoutConfig, setLayoutConfig] =
useState<LayoutConfiguration>(LAYOUT_CONFIG_DOWN);
const [elements, setElements] = useState<LayoutedElements>({
nodes: initialNodes,
edges: initialEdges,
});
useAutoLayout(layoutConfig);
useKeydown({
@ -337,6 +356,11 @@ function Graph({
onKeydown,
});
const [elements, setElements] = useState<LayoutedElements>({
nodes: initialNodes,
edges: initialEdges,
});
const onNodesChange = useCallback((changes: NodeChange[]) => {
setElements(({ nodes, edges }) => {
return {
@ -355,81 +379,93 @@ function Graph({
});
}, []);
const addSubVariableLink = useCallback(
(fromN: Variable, subLinkN: Variable) => {
fromN = subs.get_root_key(fromN);
subLinkN = subs.get_root_key(subLinkN);
const from = fromN.toString();
const to = subLinkN.toString();
interface AddNewVariableParams {
from?: Variable;
variable: Variable;
}
const addNewVariable = useCallback(
({ from, variable }: AddNewVariableParams) => {
const variablesToFocus = new Set<Variable>();
setElements(({ nodes, edges }) => {
const optNewNode = addNodeChange(
newVariable(
to,
{
subs,
variable: subLinkN,
addSubVariableLink,
isOutlined: true,
ee: ee.current,
},
layoutConfig.isHorizontal
),
nodes
);
const newNodes = optNewNode
? applyNodeChanges([optNewNode], nodes)
: nodes;
let fromVariable: Variable | undefined = from;
let toVariable: Variable | undefined = variable;
const optNewEdge = addEdgeChange(
{ id: `${from}->${to}`, source: from, target: to },
edges
);
const newEdges = optNewEdge
? applyEdgeChanges([optNewEdge], edges)
: edges;
const nodeChanges: NodeChange[] = [];
const edgeChanges: EdgeChange[] = [];
while (toVariable !== undefined) {
const toVariableName = toVariable.toString();
if (canAddVariable(toVariableName, nodes)) {
const newVariableNode = newVariable(
toVariable.toString(),
{
subs,
rawVariable: toVariable,
addSubVariableLink: addNewVariable,
isOutlined: true,
ee: ee.current,
},
layoutConfig.isHorizontal
);
nodeChanges.push(addNode(newVariableNode));
}
if (fromVariable !== undefined) {
const edgeName = `${fromVariable}->${toVariable}`;
if (canAddEdge(edgeName, edges)) {
let markerEnd: EdgeMarkerType | undefined;
if (subs.get_root_key(fromVariable) === toVariable) {
markerEnd = {
type: MarkerType.ArrowClosed,
width: 20,
height: 20,
};
}
const newEdge = addEdge({
id: `${fromVariable}->${toVariable}`,
source: fromVariable.toString(),
target: toVariableName,
markerEnd,
});
edgeChanges.push(newEdge);
}
}
variablesToFocus.add(toVariable);
fromVariable = toVariable;
const rootToVariable = subs.get_root_key(toVariable);
if (toVariable !== rootToVariable) {
toVariable = rootToVariable;
} else {
toVariable = undefined;
}
}
const newNodes = applyNodeChanges(nodeChanges, nodes);
const newEdges = applyEdgeChanges(edgeChanges, edges);
return { nodes: newNodes, edges: newEdges };
});
ee.current.emit("focus", subLinkN);
setVariablesNeedingFocus(variablesToFocus);
},
[layoutConfig, subs]
[layoutConfig.isHorizontal, subs]
);
const addNode = useCallback(
(variableN: Variable) => {
variableN = subs.get_root_key(variableN);
const variable = variableN.toString();
setElements(({ nodes, edges }) => {
const optNewNode = addNodeChange(
newVariable(
variable,
{
subs,
variable: variableN,
addSubVariableLink,
isOutlined: true,
ee: ee.current,
},
layoutConfig.isHorizontal
),
nodes
);
const newNodes = optNewNode
? applyNodeChanges([optNewNode], nodes)
: nodes;
return { nodes: newNodes, edges: edges };
});
ee.current.emit("focus", variableN);
const addNewVariableNode = useCallback(
(variable: Variable) => {
addNewVariable({ variable });
},
[subs, addSubVariableLink, layoutConfig]
[addNewVariable]
);
onVariable(addNode);
onVariable(addNewVariableNode);
return (
<ReactFlow