This commit is contained in:
Orion Reed 2025-07-28 19:26:05 -04:00
parent 5a58ed4ebc
commit 3ccb69c94c
5 changed files with 4528 additions and 5058 deletions

View File

@ -1 +0,0 @@
nodeLinker: node-modules

4003
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,270 +1,538 @@
import {
BaseBoxShapeUtil,
Editor,
Geometry2d,
HTMLContainer,
Rectangle2d,
TLBaseShape,
TLOnResizeHandler,
TLShape,
TLShapeId,
resizeBox,
} from 'tldraw'
import { getUserId } from './storeUtils'
import { getEdge } from './propagators/tlgraph'
BaseBoxShapeUtil,
Editor,
Geometry2d,
HTMLContainer,
Rectangle2d,
TLBaseShape,
TLOnResizeHandler,
TLShape,
TLShapeId,
resizeBox,
} from "tldraw";
import { getUserId } from "./storeUtils";
import { getEdge } from "./propagators/tlgraph";
export type ValueType = "SCALAR" | "BOOLEAN" | "STRING" | "RANK" | "NONE"
export type ValueType = "SCALAR" | "BOOLEAN" | "STRING" | "RANK" | "NONE";
export type ISocialShape = TLBaseShape<
"social",
{
w: number
h: number
text: string
selector: string
valueType: ValueType
values: Record<string, any>
value: any
syntaxError: boolean
}
>
"social",
{
w: number;
h: number;
text: string;
selector: string;
valueType: ValueType;
values: Record<string, any>;
value: any;
syntaxError: boolean;
}
>;
export class SocialShapeUtil extends BaseBoxShapeUtil<ISocialShape> {
static override type = 'social' as const
override canBind = () => true
override canEdit = () => false
override getDefaultProps(): ISocialShape['props'] {
return { w: 160 * 2, h: 90 * 2, text: '', selector: '', valueType: "NONE", values: {}, value: null, syntaxError: false }
}
override onResize: TLOnResizeHandler<ISocialShape> = (shape, info) => {
return resizeBox(shape, info)
}
override getGeometry(shape: ISocialShape): Geometry2d {
return new Rectangle2d({
width: shape.props.w,
height: shape.props.h,
isFilled: true,
})
}
static override type = "social" as const;
private valueTypeRegex = (valueType: ValueType) =>
new RegExp(`${valueType}\\s*\\((.*?)\\)|${valueType}`);
override canBind = () => true;
override canEdit = () => false;
override getDefaultProps(): ISocialShape["props"] {
return {
w: 160 * 2,
h: 90 * 2,
text: "",
selector: "",
valueType: "NONE",
values: {},
value: null,
syntaxError: false,
};
}
override onResize: TLOnResizeHandler<ISocialShape> = (shape, info) => {
return resizeBox(shape, info);
};
override getGeometry(shape: ISocialShape): Geometry2d {
return new Rectangle2d({
width: shape.props.w,
height: shape.props.h,
isFilled: true,
});
}
indicator(shape: ISocialShape) {
return (
<rect
width={shape.props.w}
height={shape.props.h}
rx={4}
/>
)
}
indicator(shape: ISocialShape) {
return <rect width={shape.props.w} height={shape.props.h} rx={4} />;
}
override component(shape: ISocialShape) {
const currentUser = getUserId(this.editor)
override component(shape: ISocialShape) {
const currentUser = getUserId(this.editor);
const defaultValues = {
BOOLEAN: false,
SCALAR: 0,
DEFAULT: null
}
const defaultValues = {
BOOLEAN: false,
SCALAR: 0,
DEFAULT: null,
};
const handleOnChange = (newValue: boolean | number) => {
this.updateProps(shape, { values: { ...shape.props.values, [currentUser]: newValue } })
this.updateValue(shape.id)
}
const handleOnChange = (newValue: boolean | number) => {
console.log("NEW VALUE", newValue);
this.updateProps(shape, {
values: { ...shape.props.values, [currentUser]: newValue },
});
this.updateValue(shape.id);
};
const handleTextChange = (text: string) => {
let valueType: ValueType = "NONE"
const selector = text.match(/@([a-zA-Z]+)/)?.[1] || ''
const handleTextChange = (text: string) => {
let valueType: ValueType = "NONE";
const selector = text.match(/@([a-zA-Z]+)/)?.[1] || "";
if (text.includes('SCALAR')) {
valueType = 'SCALAR'
} else if (text.includes('BOOLEAN')) {
valueType = 'BOOLEAN'
} else if (text.includes('STRING')) {
valueType = 'STRING'
} else if (text.includes('RANK')) {
valueType = 'RANK'
}
if (text.includes("SCALAR")) {
valueType = "SCALAR";
} else if (text.includes("BOOLEAN")) {
valueType = "BOOLEAN";
} else if (text.includes("STRING")) {
valueType = "STRING";
} else if (text.includes("RANK")) {
valueType = "RANK";
}
if (valueType !== shape.props.valueType) {
this.updateProps(shape, { text, valueType, selector, values: {} })
} else {
this.updateProps(shape, { text, selector })
}
this.updateValue(shape.id)
}
if (valueType !== shape.props.valueType) {
this.updateProps(shape, { text, valueType, selector, values: {} });
} else {
this.updateProps(shape, { text, selector });
}
this.updateValue(shape.id);
};
return (
<HTMLContainer style={{ padding: 4, borderRadius: 4, border: '1px solid #ccc', outline: shape.props.syntaxError ? '2px solid orange' : 'none' }} onPointerDown={(e) => e.stopPropagation()}>
<textarea style={{ width: '100%', height: '60%', border: '1px solid lightgrey', resize: 'none', pointerEvents: 'all' }} value={shape.props.text} onChange={(e) => handleTextChange(e.target.value)} />
<ValueInterface
type={shape.props.valueType ?? null}
value={shape.props.values[currentUser] ?? defaultValues[shape.props.valueType as keyof typeof defaultValues]}
values={shape.props.values}
onChange={handleOnChange} />
</HTMLContainer>
)
}
const args = this.getArgs(shape, shape.props.valueType);
const inputMap = getInputMap(this.editor, shape);
const usedInputs: any[] = [];
for (const arg of args) {
if (arg !== false && arg !== true && inputMap[arg]) {
if (Array.isArray(inputMap[arg].value)) {
usedInputs.push(...inputMap[arg].value);
} else {
usedInputs.push(inputMap[arg].value);
}
}
}
// console.log("USED INPUTS", usedInputs)
private updateValue(shapeId: TLShapeId) {
const shape = this.editor.getShape(shapeId) as ISocialShape
const valueType = shape.props.valueType
const vals = Array.from(Object.values(shape.props.values))
return (
<HTMLContainer
style={{
padding: 4,
borderRadius: 4,
border: "1px solid #ccc",
outline: shape.props.syntaxError ? "2px solid orange" : "none",
}}
onPointerDown={(e) => e.stopPropagation()}
>
<textarea
style={{
width: "100%",
minHeight: "4em",
height: "auto",
border: "1px solid lightgrey",
resize: "none",
pointerEvents: "all",
}}
value={shape.props.text}
onChange={(e) => handleTextChange(e.target.value)}
rows={2}
/>
<ValueInterface
type={shape.props.valueType ?? null}
value={
shape.props.values[currentUser] ??
defaultValues[shape.props.valueType as keyof typeof defaultValues]
}
values={shape.props.values}
inputs={usedInputs}
onChange={handleOnChange}
editor={this.editor}
/>
</HTMLContainer>
);
}
const functionBody = `return ${shape.props.text.replace(valueType, 'VALUES')};`
private getArgs(shape: ISocialShape, valueType: ValueType) {
const match = shape.props.text.match(this.valueTypeRegex(valueType));
let args: (string | number | boolean)[] = [];
if (match?.[1]) {
args = match[1].split(",").map((arg) => {
const trimmed = arg.trim();
if (trimmed === "true") return true;
if (trimmed === "false") return false;
if (!Number.isNaN(Number(trimmed))) return Number(trimmed);
return trimmed;
});
}
return args;
}
const sum = (vals: number[] | boolean[]) => {
if (valueType === 'SCALAR') {
return (vals as number[]).reduce((acc, val) => acc + val, 0)
}
if (valueType === 'BOOLEAN') {
//@ts-ignore
return vals.filter(Boolean).length;
}
}
const average = (vals: number[] | boolean[]) => {
if (valueType === 'SCALAR') {
return (vals as number[]).reduce((acc, val) => acc + val, 0) / vals.length
}
if (valueType === 'BOOLEAN') {
//@ts-ignore
return vals.filter(Boolean).length;
}
}
private updateValue(shapeId: TLShapeId) {
const shape = this.editor.getShape(shapeId) as ISocialShape;
const valueType = shape.props.valueType;
const vals = Array.from(Object.values(shape.props.values));
const inputMap = getInputMap(this.editor, shape)
const functionBody = `return ${shape.props.text.replace(
this.valueTypeRegex(valueType),
"VALUES"
)};`;
try {
const paramNames = ['sum', 'average', 'VALUES', ...Object.keys(inputMap)]
const paramValues = [sum, average, vals, ...Object.values(inputMap).map(s => s.value)]
const func = new Function(...paramNames, functionBody)
const result = func(...paramValues)
const sum = (vals: number[] | boolean[]) => {
if (valueType === "SCALAR") {
return (vals as number[]).reduce((acc, val) => acc + val, 0);
}
if (valueType === "BOOLEAN") {
//@ts-ignore
return vals.filter(Boolean).length;
}
};
const average = (vals: number[] | boolean[]) => {
if (valueType === "SCALAR") {
return (
(vals as number[]).reduce((acc, val) => acc + val, 0) / vals.length
);
}
if (valueType === "BOOLEAN") {
//@ts-ignore
return vals.filter(Boolean).length;
}
};
if (typeof result === 'function') {
this.updateProps({ ...shape, props: { ...shape.props, value: null } }, { syntaxError: true })
return
}
console.log("VALUE", result)
this.updateProps(shape, { value: result, syntaxError: false })
} catch (e) {
console.log("ERROR", e)
this.updateProps(shape, { syntaxError: true })
}
}
const countVotes = (votes: Array<{ up: string[]; down: string[] }>) => {
const voteCount = votes.reduce((acc, vote) => {
for (const item of vote.up) {
acc[item] = (acc[item] || 0) + 1;
}
for (const item of vote.down) {
acc[item] = (acc[item] || 0) - 1;
}
return acc;
}, {} as Record<string, number>);
return Object.entries(voteCount).sort((a, b) => b[1] - a[1]);
};
private updateProps(shape: ISocialShape, props: Partial<ISocialShape['props']>) {
this.editor.updateShape<ISocialShape>({
id: shape.id,
type: 'social',
props: {
...shape.props,
...props
},
})
}
const inputMap = getInputMap(this.editor, shape);
try {
const paramNames = [
"sum",
"average",
"countVotes",
"VALUES",
...Object.keys(inputMap),
];
const paramValues = [
sum,
average,
countVotes,
vals,
...Object.values(inputMap).map((s) => s.value),
];
const func = new Function(...paramNames, functionBody);
const result = func(...paramValues);
if (typeof result === "function") {
this.updateProps(
{ ...shape, props: { ...shape.props, value: null } },
{ syntaxError: true }
);
return;
}
this.updateProps(shape, { value: result, syntaxError: false });
} catch (e) {
console.log("ERROR", e);
this.updateProps(shape, { syntaxError: true });
}
}
private updateProps(
shape: ISocialShape,
props: Partial<ISocialShape["props"]>
) {
this.editor.updateShape<ISocialShape>({
id: shape.id,
type: "social",
props: {
...shape.props,
...props,
},
});
}
}
function ValueInterface({ type, value, values, onChange }: { type: ValueType; value: boolean | number | string; values: Record<string, any>; onChange: (value: any) => void }) {
switch (type) {
case 'BOOLEAN':
return <>
<div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: '4px' }}>
<input style={{ pointerEvents: 'all', width: '20px', height: '20px', margin: 0 }} type="checkbox" checked={value as boolean} onChange={(e) => onChange(e.target.checked)} />
<div style={{ width: '1px', height: '20px', backgroundColor: 'grey' }} />
{Object.values(values).map((bool, i) => (
<div key={`boolean-${i}`} style={{ backgroundColor: bool ? 'blue' : 'white', width: '20px', height: '20px', border: '1px solid lightgrey', borderRadius: 2 }} />
))}
</div>
</>
case 'STRING':
return (
<div style={{ display: 'flex', flexDirection: 'column', width: '100%', gap: '4px' }}>
<textarea
style={{
pointerEvents: 'all',
width: '100%',
minHeight: '60px',
resize: 'vertical',
padding: '4px',
boxSizing: 'border-box',
}}
value={value as string}
onChange={(e) => onChange(e.target.value)}
/>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div style={{ display: 'flex', gap: '2px' }}>
{Object.values(values).filter(value => value !== '').map((_, i) => (
<div
key={`string-${i}`}
style={{
width: '8px',
height: '8px',
backgroundColor: 'blue',
borderRadius: '50%',
}}
/>
))}
</div>
</div>
</div>
);
case 'SCALAR':
return (
<div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: '4px' }}>
<input
type="range"
min="0"
max="1"
step="0.01"
value={value as number ?? 0}
onChange={(e) => onChange(parseFloat(e.target.value))}
style={{ width: '100px', pointerEvents: 'all' }}
/>
<span style={{ fontFamily: 'monospace' }}>{(value as number ?? 0).toFixed(2)}</span>
<div style={{ width: '1px', height: '20px', backgroundColor: 'grey' }} />
{Object.values(values).map((val, i) => (
<div
key={`scalar-${i}`}
style={{
backgroundColor: `rgba(0, 0, 255, ${val ?? 0})`,
width: '20px',
height: '20px',
border: '1px solid lightgrey',
borderRadius: 2
}}
/>
))}
</div>
);
default:
return <div style={{ marginTop: 10, textAlign: 'center' }}>No Interface...</div>
}
function ValueInterface({
type,
value,
values,
onChange,
inputs,
editor,
}: {
type: ValueType;
value: boolean | number | string;
values: Record<string, any>;
onChange: (value: any) => void;
inputs: any[];
editor: Editor;
}) {
switch (type) {
case "BOOLEAN":
return (
<>
<div
style={{
display: "flex",
flexDirection: "row",
alignItems: "center",
gap: "4px",
}}
>
<input
style={{
pointerEvents: "all",
width: "20px",
height: "20px",
margin: 0,
}}
type="checkbox"
checked={value as boolean}
onChange={(e) => onChange(e.target.checked)}
/>
<div
style={{ width: "1px", height: "20px", backgroundColor: "grey" }}
/>
{Object.values(values).map((bool, i) => (
<div
key={`boolean-${i}`}
style={{
backgroundColor: bool ? "blue" : "white",
width: "20px",
height: "20px",
border: "1px solid lightgrey",
borderRadius: 2,
}}
/>
))}
</div>
</>
);
case "STRING":
return (
<div
style={{
display: "flex",
flexDirection: "column",
width: "100%",
gap: "4px",
}}
>
<textarea
style={{
pointerEvents: "all",
width: "100%",
minHeight: "60px",
resize: "vertical",
padding: "4px",
boxSizing: "border-box",
}}
value={value as string}
onChange={(e) => onChange(e.target.value)}
/>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<div style={{ display: "flex", gap: "2px" }}>
{Object.values(values)
.filter((value) => value !== "")
.map((_, i) => (
<div
key={`string-${i}`}
style={{
width: "8px",
height: "8px",
backgroundColor: "blue",
borderRadius: "50%",
}}
/>
))}
</div>
</div>
</div>
);
case "RANK": {
const currentUser = getUserId(editor);
return (
<div
style={{
display: "flex",
flexDirection: "column",
width: "100%",
gap: "8px",
}}
>
{inputs.map((input, index) => (
<div
key={`rank-${index}`}
style={{
display: "flex",
alignItems: "center",
gap: "8px",
border: "1px solid lightgrey",
borderRadius: 4,
padding: "4px 8px",
}}
>
<span
style={{
flex: 1,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
}}
>
{input}
</span>
<button
type="button"
onClick={() => {
const newUp = [
...new Set([...(values[currentUser]?.up || []), input]),
];
//@ts-ignore
const newDown = (values[currentUser]?.down || []).filter(
(v: string) => v !== input
);
onChange({ up: newUp, down: newDown });
}}
style={{
cursor: "pointer",
padding: "4px 8px",
pointerEvents: "all",
backgroundColor: values[currentUser]?.up?.includes(input)
? "#4CAF50"
: "inherit",
}}
>
</button>
<button
type="button"
onClick={() => {
//@ts-ignore
const newUp = (values[currentUser]?.up || []).filter(
(v: string) => v !== input
);
//@ts-ignore
const newDown = [
...new Set([...(values[currentUser]?.down || []), input]),
];
onChange({ up: newUp, down: newDown });
}}
style={{
cursor: "pointer",
padding: "4px 8px",
pointerEvents: "all",
backgroundColor: values[currentUser]?.down?.includes(input)
? "#FF3B30"
: "inherit",
}}
>
</button>
</div>
))}
<div style={{ display: "flex", gap: "2px" }}>
{Object.values(values)
.filter((value) => value !== "")
.map((_, i) => (
<div
key={`rank-dot-${i}`}
style={{
width: "8px",
height: "8px",
backgroundColor: "blue",
borderRadius: "50%",
}}
/>
))}
</div>
</div>
);
}
case "SCALAR":
return (
<div
style={{
display: "flex",
flexDirection: "row",
alignItems: "center",
gap: "4px",
}}
>
<input
type="range"
min="0"
max="1"
step="0.01"
value={(value as number) ?? 0}
onChange={(e) => onChange(parseFloat(e.target.value))}
style={{ width: "100px", pointerEvents: "all" }}
/>
<span style={{ fontFamily: "monospace" }}>
{((value as number) ?? 0).toFixed(2)}
</span>
<div
style={{ width: "1px", height: "20px", backgroundColor: "grey" }}
/>
{Object.values(values).map((val, i) => (
<div
key={`scalar-${i}`}
style={{
backgroundColor: `rgba(0, 0, 255, ${val ?? 0})`,
width: "20px",
height: "20px",
border: "1px solid lightgrey",
borderRadius: 2,
}}
/>
))}
</div>
);
default:
return (
<div style={{ marginTop: 10, textAlign: "center" }}>
No Interface...
</div>
);
}
}
function getInputMap(editor: Editor, shape: TLShape) {
const arrowBindings = editor.getBindingsInvolvingShape(
shape.id,
"arrow",
)
const arrows = arrowBindings
.map((binding) => editor.getShape(binding.fromId))
const arrowBindings = editor.getBindingsInvolvingShape(shape.id, "arrow");
const arrows = arrowBindings.map((binding) =>
editor.getShape(binding.fromId)
);
return arrows.reduce((acc, arrow) => {
const edge = getEdge(arrow, editor);
if (edge && edge.to === shape.id) {
const sourceShape = editor.getShape(edge.from);
if (sourceShape && edge.text) {
acc[edge.text] = { value: sourceShape.props.value || sourceShape.props.text || null, shapeId: sourceShape.id }
}
}
return acc;
}, {} as Record<string, { value: any, shapeId: TLShapeId }>);
return arrows.reduce((acc, arrow) => {
const edge = getEdge(arrow, editor);
if (edge && edge.to === shape.id) {
const sourceShape = editor.getShape(edge.from);
if (sourceShape && edge.text) {
//@ts-ignore
acc[edge.text] = {
//@ts-ignore
value: sourceShape.props.value || sourceShape.props.text || null,
shapeId: sourceShape.id,
};
}
}
return acc;
}, {} as Record<string, { value: any; shapeId: TLShapeId }>);
}
function listenToShape(editor: Editor, shapeId: TLShapeId, callback: (prev: TLShape, next: TLShape) => void) {
return editor.sideEffects.registerAfterChangeHandler<'shape'>('shape', (prev, next) => {
if (next.id === shapeId) {
callback(prev, next)
}
})
}

View File

@ -0,0 +1,16 @@
// vite.config.ts
import { defineConfig } from "file:///Users/orion/Repositories/Orion/ggraph/node_modules/vite/dist/node/index.js";
import react from "file:///Users/orion/Repositories/Orion/ggraph/node_modules/@vitejs/plugin-react/dist/index.mjs";
import wasm from "file:///Users/orion/Repositories/Orion/ggraph/node_modules/vite-plugin-wasm/exports/import.mjs";
import topLevelAwait from "file:///Users/orion/Repositories/Orion/ggraph/node_modules/vite-plugin-top-level-await/exports/import.mjs";
var vite_config_default = defineConfig({
plugins: [
react(),
wasm(),
topLevelAwait()
]
});
export {
vite_config_default as default
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvVXNlcnMvb3Jpb24vUmVwb3NpdG9yaWVzL09yaW9uL2dncmFwaFwiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9maWxlbmFtZSA9IFwiL1VzZXJzL29yaW9uL1JlcG9zaXRvcmllcy9Pcmlvbi9nZ3JhcGgvdml0ZS5jb25maWcudHNcIjtjb25zdCBfX3ZpdGVfaW5qZWN0ZWRfb3JpZ2luYWxfaW1wb3J0X21ldGFfdXJsID0gXCJmaWxlOi8vL1VzZXJzL29yaW9uL1JlcG9zaXRvcmllcy9Pcmlvbi9nZ3JhcGgvdml0ZS5jb25maWcudHNcIjtpbXBvcnQgeyBkZWZpbmVDb25maWcgfSBmcm9tICd2aXRlJ1xuaW1wb3J0IHJlYWN0IGZyb20gJ0B2aXRlanMvcGx1Z2luLXJlYWN0J1xuaW1wb3J0IHdhc20gZnJvbSBcInZpdGUtcGx1Z2luLXdhc21cIjtcbmltcG9ydCB0b3BMZXZlbEF3YWl0IGZyb20gXCJ2aXRlLXBsdWdpbi10b3AtbGV2ZWwtYXdhaXRcIjtcblxuZXhwb3J0IGRlZmF1bHQgZGVmaW5lQ29uZmlnKHtcbiAgcGx1Z2luczogW1xuICAgIHJlYWN0KCksXG4gICAgd2FzbSgpLFxuICAgIHRvcExldmVsQXdhaXQoKVxuICBdLFxufSlcbiJdLAogICJtYXBwaW5ncyI6ICI7QUFBb1MsU0FBUyxvQkFBb0I7QUFDalUsT0FBTyxXQUFXO0FBQ2xCLE9BQU8sVUFBVTtBQUNqQixPQUFPLG1CQUFtQjtBQUUxQixJQUFPLHNCQUFRLGFBQWE7QUFBQSxFQUMxQixTQUFTO0FBQUEsSUFDUCxNQUFNO0FBQUEsSUFDTixLQUFLO0FBQUEsSUFDTCxjQUFjO0FBQUEsRUFDaEI7QUFDRixDQUFDOyIsCiAgIm5hbWVzIjogW10KfQo=

4816
yarn.lock

File diff suppressed because it is too large Load Diff