Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

197 changes: 185 additions & 12 deletions src/features/modals/NodeModal/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import React from "react";
import type { ModalProps } from "@mantine/core";
import { Modal, Stack, Text, ScrollArea, Flex, CloseButton } from "@mantine/core";
import { Modal, Stack, Text, ScrollArea, Flex, CloseButton, Button, TextInput, Group } from "@mantine/core";
import { CodeHighlight } from "@mantine/code-highlight";
import type { NodeData } from "../../../types/graph";
import type { NodeData, NodeRow } from "../../../types/graph";
import useGraph from "../../editor/views/GraphView/stores/useGraph";
import useJson from "../../../store/useJson";
import useFile from "../../../store/useFile";

// return object from json removing array and object fields
const normalizeNodeData = (nodeRows: NodeData["text"]) => {
Expand All @@ -26,8 +28,145 @@ const jsonPathToString = (path?: NodeData["path"]) => {
return `$[${segments.join("][")}]`;
};

// Update JSON at specified path with new value
const updateJsonAtPath = (json: string, path: NodeData["path"], value: any): string => {
try {
const obj = JSON.parse(json);
if (!path || path.length === 0) return JSON.stringify(value);

let current = obj;
for (let i = 0; i < path.length - 1; i++) {
current = current[path[i]];
}
current[path[path.length - 1]] = value;
return JSON.stringify(obj, null, 2);
} catch {
return json;
}
};

export const NodeModal = ({ opened, onClose }: ModalProps) => {
const nodeData = useGraph(state => state.selectedNode);
const setJson = useJson(state => state.setJson);
const currentJson = useJson(state => state.json);
const setSelectedNode = useGraph(state => state.setSelectedNode);

const [isEditing, setIsEditing] = React.useState(false);
const [editedRows, setEditedRows] = React.useState<NodeRow[]>([]);

// Initialize edited rows when modal opens or nodeData changes
React.useEffect(() => {
if (nodeData && opened) {
setEditedRows(nodeData.text.filter(row => row.type !== "array" && row.type !== "object"));
setIsEditing(false);
}
}, [nodeData, opened]);

const handleEditClick = () => {
setIsEditing(true);
};

const handleSave = () => {
if (!nodeData) return;
// Build updatedNodeText (for immediate UI feedback)
const updatedNodeText = nodeData.text.map(row => {
const editedRow = editedRows.find(er => er.key === row.key && er.type === row.type && er.key !== null);
// For primitive value nodes (key === null) match by index
if (!editedRow && row.key === null) {
const prim = editedRows.find((r, idx) => r.key === null && nodeData.text[idx] && nodeData.text[idx].key === null);
return prim || row;
}
return editedRow || row;
});

// Helper to coerce string input back to original types
const coerceValue = (input: any, originalType: string | undefined) => {
if (input === null) return null;
if (originalType === "number") {
const n = Number(input);
return Number.isNaN(n) ? input : n;
}
if (originalType === "boolean") {
if (typeof input === "boolean") return input;
if (String(input).toLowerCase() === "true") return true;
if (String(input).toLowerCase() === "false") return false;
return input;
}
if (originalType === "null") return null;
return input;
};

// Parse current JSON and apply edits to the node's path
try {
const fullJson = JSON.parse(currentJson);

if (nodeData.path && nodeData.path.length >= 0) {
// Locate parent and target key/index
let parent: any = fullJson;
for (let i = 0; i < (nodeData.path.length - 1); i++) {
parent = parent[nodeData.path[i]];
if (parent === undefined) break;
}

const lastKey = nodeData.path.length > 0 ? nodeData.path[nodeData.path.length - 1] : undefined;

// If node represents a primitive value (single row with no key), replace the value directly
if (nodeData.text.length === 1 && nodeData.text[0].key === null) {
const editedPrim = editedRows[0];
if (lastKey !== undefined) {
parent[lastKey as any] = coerceValue(editedPrim?.value ?? nodeData.text[0].value, nodeData.text[0].type as string);
}
} else {
// Ensure target object exists
const target = lastKey !== undefined ? parent[lastKey as any] : parent;
if (target && typeof target === "object") {
editedRows.forEach(edited => {
if (edited.key) {
// find original row to get its type
const original = nodeData.text.find(r => r.key === edited.key && r.type === edited.type);
const coerced = coerceValue(edited.value, original?.type as string | undefined);
target[edited.key] = coerced;
}
});
}
}

// Persist updated JSON and also update the text editor on the left
const updatedJsonString = JSON.stringify(fullJson, null, 2);
setJson(updatedJsonString);
useFile.getState().setContents({ contents: updatedJsonString, hasChanges: true });
}
} catch (err) {
// fallback: if something goes wrong, don't crash — keep node update in-memory
console.error("Failed to update JSON in NodeModal.save:", err);
}

// Update the selected node with edited text for immediate feedback
const updatedNodeData: NodeData = {
...nodeData,
text: updatedNodeText,
};
setSelectedNode(updatedNodeData);

setIsEditing(false);
};

const handleCancel = () => {
setIsEditing(false);
if (nodeData) {
setEditedRows(nodeData.text.filter(row => row.type !== "array" && row.type !== "object"));
}
};

const handleFieldChange = (index: number, newValue: string) => {
const updated = [...editedRows];
updated[index] = { ...updated[index], value: newValue };
setEditedRows(updated);
};

if (!nodeData) return null;

const editableFields = editedRows;

return (
<Modal size="auto" opened={opened} onClose={onClose} centered withCloseButton={false}>
Expand All @@ -37,18 +176,52 @@ export const NodeModal = ({ opened, onClose }: ModalProps) => {
<Text fz="xs" fw={500}>
Content
</Text>
<CloseButton onClick={onClose} />
<Flex gap="xs">
{!isEditing && <Button size="xs" variant="default" onClick={handleEditClick}>
Edit
</Button>}
{isEditing && (
<Group gap="xs">
<Button size="xs" variant="default" onClick={handleCancel}>
Cancel
</Button>
<Button size="xs" onClick={handleSave}>
Save
</Button>
</Group>
)}
<CloseButton onClick={onClose} />
</Flex>
</Flex>
<ScrollArea.Autosize mah={250} maw={600}>
<CodeHighlight
code={normalizeNodeData(nodeData?.text ?? [])}
miw={350}
maw={600}
language="json"
withCopyButton
/>
</ScrollArea.Autosize>

{!isEditing ? (
<ScrollArea.Autosize mah={250} maw={600}>
<CodeHighlight
code={normalizeNodeData(nodeData?.text ?? [])}
miw={350}
maw={600}
language="json"
withCopyButton
/>
</ScrollArea.Autosize>
) : (
<Stack gap="sm" style={{ maxHeight: 300, overflowY: "auto" }}>
{editableFields.map((field, index) => (
<div key={`${field.key}-${index}`}>
<Text size="xs" fw={500} mb={4}>
{field.key || "Value"}
</Text>
<TextInput
placeholder={`Enter ${field.key || "value"}`}
value={String(field.value ?? "")}
onChange={e => handleFieldChange(index, e.currentTarget.value)}
/>
</div>
))}
</Stack>
)}
</Stack>

<Text fz="xs" fw={500}>
JSON Path
</Text>
Expand Down