Skip to content

SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.

Implement Note-aware Sorting Features

Muhammad Hamza Khan0870fc160a7d
diff --git a/packages/app/src/builder-ui/workspace/ComponentSort.ts b/packages/app/src/builder-ui/workspace/ComponentSort.ts
index 20dc8366..528c01a8 100644
--- a/packages/app/src/builder-ui/workspace/ComponentSort.ts
+++ b/packages/app/src/builder-ui/workspace/ComponentSort.ts
@@ -3,6 +3,234 @@ import { delay } from '../utils';
declare var workspace: any;
let isSorting = false;
+/** Bounding box type for elements */
+interface Bounds {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+}
+
+/** Relative position offset */
+interface RelativePosition {
+ dx: number;
+ dy: number;
+}
+
+/** Note component with its contained components */
+interface NoteGroup {
+ noteId: string;
+ noteElement: HTMLElement;
+ containedComponentIds: string[];
+ associatedWorkflowIndex: number | null;
+}
+
+/** Context object for Note-aware sorting operations */
+interface NoteSortContext {
+ noteGroups: NoteGroup[];
+ relativePositions: Map<string, Map<string, RelativePosition>>;
+ containedComponentIds: Set<string>;
+}
+
+/**
+ * Gets the style-based bounding box of an element
+ */
+function getElementBounds(element: HTMLElement): Bounds {
+ return {
+ left: parseFloat(element.style.left) || 0,
+ top: parseFloat(element.style.top) || 0,
+ width: element.offsetWidth || 0,
+ height: element.offsetHeight || 0,
+ };
+}
+
+/**
+ * Checks if two rectangles overlap
+ */
+function rectanglesOverlap(rect1: Bounds, rect2: Bounds): boolean {
+ return !(
+ rect1.left + rect1.width <= rect2.left ||
+ rect2.left + rect2.width <= rect1.left ||
+ rect1.top + rect1.height <= rect2.top ||
+ rect2.top + rect2.height <= rect1.top
+ );
+}
+
+/**
+ * Detects all Note components and collects context needed for Note-aware sorting.
+ * @returns NoteSortContext with note groups, relative positions, and contained component IDs
+ */
+function initializeNoteSortContext(): NoteSortContext {
+ const noteGroups: NoteGroup[] = [];
+ const relativePositions = new Map<string, Map<string, RelativePosition>>();
+ const containedComponentIds = new Set<string>();
+
+ const noteElements = Array.from(
+ document.querySelectorAll('.component.Note'),
+ ) as HTMLElement[];
+ const allComponents = Array.from(
+ document.querySelectorAll('.component:not(.Note)'),
+ ) as HTMLElement[];
+
+ for (const noteElement of noteElements) {
+ const noteRect = noteElement.getBoundingClientRect();
+ const noteLeft = parseFloat(noteElement.style.left) || 0;
+ const noteTop = parseFloat(noteElement.style.top) || 0;
+ const contained: string[] = [];
+ const positions = new Map<string, RelativePosition>();
+
+ for (const compEl of allComponents) {
+ if (!compEl.id) continue;
+
+ const compRect = compEl.getBoundingClientRect();
+ const isInside =
+ compRect.left >= noteRect.left &&
+ compRect.right <= noteRect.right &&
+ compRect.top >= noteRect.top &&
+ compRect.bottom <= noteRect.bottom;
+
+ if (isInside) {
+ contained.push(compEl.id);
+ containedComponentIds.add(compEl.id);
+ positions.set(compEl.id, {
+ dx: (parseFloat(compEl.style.left) || 0) - noteLeft,
+ dy: (parseFloat(compEl.style.top) || 0) - noteTop,
+ });
+ }
+ }
+
+ noteGroups.push({
+ noteId: noteElement.id,
+ noteElement,
+ containedComponentIds: contained,
+ associatedWorkflowIndex: null,
+ });
+ relativePositions.set(noteElement.id, positions);
+ }
+
+ return { noteGroups, relativePositions, containedComponentIds };
+}
+
+/**
+ * Associates each Note with a workflow based on its contained components
+ */
+function associateNotesWithWorkflows(
+ noteGroups: NoteGroup[],
+ workflows: Array<{ components: Array<{ id: string }> }>,
+): void {
+ for (const noteGroup of noteGroups) {
+ for (let i = 0; i < workflows.length; i++) {
+ const workflowIds = workflows[i].components.map((c) => c.id);
+ if (noteGroup.containedComponentIds.some((id) => workflowIds.includes(id))) {
+ noteGroup.associatedWorkflowIndex = i;
+ break;
+ }
+ }
+ }
+}
+
+/**
+ * Repositions Notes to follow their contained components after sorting
+ */
+async function repositionNotesAfterSort(
+ noteGroups: NoteGroup[],
+ relativePositions: Map<string, Map<string, RelativePosition>>,
+): Promise<void> {
+ for (const noteGroup of noteGroups) {
+ if (noteGroup.associatedWorkflowIndex === null || noteGroup.containedComponentIds.length === 0) {
+ continue;
+ }
+
+ const containedElements = noteGroup.containedComponentIds
+ .map((id) => document.getElementById(id))
+ .filter((el): el is HTMLElement => el !== null);
+
+ if (containedElements.length === 0) continue;
+
+ const containedBox = calculateBoundingBox(containedElements);
+ const positions = relativePositions.get(noteGroup.noteId);
+ if (!positions) continue;
+
+ // Find minimum relative offset to position Note correctly
+ let minDx = Infinity;
+ let minDy = Infinity;
+ for (const relPos of positions.values()) {
+ minDx = Math.min(minDx, relPos.dx);
+ minDy = Math.min(minDy, relPos.dy);
+ }
+
+ noteGroup.noteElement.style.transition = '0.2s ease-in-out';
+ noteGroup.noteElement.style.left = `${~~(containedBox.x - minDx)}px`;
+ noteGroup.noteElement.style.top = `${~~(containedBox.y - minDy)}px`;
+ }
+
+ await delay(300);
+
+ for (const noteGroup of noteGroups) {
+ noteGroup.noteElement.style.transition = '';
+ }
+}
+
+/**
+ * Resolves collisions by shifting components that overlap with Notes but weren't originally inside
+ */
+async function resolveNoteCollisions(
+ noteGroups: NoteGroup[],
+ padding: number = 100,
+): Promise<void> {
+ const allComponents = Array.from(
+ document.querySelectorAll('.component:not(.Note)'),
+ ) as HTMLElement[];
+
+ const originallyContainedIds = new Set<string>();
+ for (const noteGroup of noteGroups) {
+ for (const compId of noteGroup.containedComponentIds) {
+ originallyContainedIds.add(compId);
+ }
+ }
+
+ for (const noteGroup of noteGroups) {
+ const noteBounds = getElementBounds(noteGroup.noteElement);
+ const noteRightEdge = noteBounds.left + noteBounds.width;
+ let minOverlapX = Infinity;
+ let hasOverlap = false;
+
+ // Find minimum X of overlapping components
+ for (const compEl of allComponents) {
+ if (originallyContainedIds.has(compEl.id)) continue;
+
+ const compBounds = getElementBounds(compEl);
+ if (rectanglesOverlap(noteBounds, compBounds)) {
+ hasOverlap = true;
+ minOverlapX = Math.min(minOverlapX, compBounds.left);
+ }
+ }
+
+ if (!hasOverlap) continue;
+
+ const shiftAmount = noteRightEdge + padding - minOverlapX;
+ if (shiftAmount <= 0) continue;
+
+ // Shift all components at or beyond the overlap point
+ for (const compEl of allComponents) {
+ if (originallyContainedIds.has(compEl.id)) continue;
+
+ const compLeft = parseFloat(compEl.style.left) || 0;
+ if (compLeft >= minOverlapX) {
+ compEl.style.transition = '0.2s ease-in-out';
+ compEl.style.left = `${~~(compLeft + shiftAmount)}px`;
+ }
+ }
+ }
+
+ await delay(300);
+
+ for (const compEl of allComponents) {
+ compEl.style.transition = '';
+ workspace.jsPlumbInstance.repaint(compEl);
+ }
+}
+
function calculateBoundingBox(components) {
if (!Array.isArray(components) || components.length === 0) {
throw new Error('Input must be a non-empty array of DOM components.');
@@ -232,6 +460,8 @@ async function organizeComponents(components, initialX, initialY) {
levels[level].push(component);
});
+ console.log('levels', levels);
+
// Calculate positions
const levelPositions = {};
let xPos = initialX;
@@ -288,45 +518,61 @@ export async function sortAgent() {
}
async function sortAll() {
- if (isSorting) {
- return;
- }
+ if (isSorting) return;
try {
isSorting = true;
const agentData = (await workspace.export(false)) || workspace.agent.data;
+
+ // Initialize Note context before sorting
+ const noteContext = initializeNoteSortContext();
+ const { noteGroups, relativePositions, containedComponentIds } = noteContext;
+
+ // Extract workflows and associate Notes with them
const workflows = await extractWorkflows(agentData);
- await delay(50);
+ associateNotesWithWorkflows(noteGroups, workflows);
await workspace.export();
await delay(200);
workspace.lock();
- // Process workflows in smaller batches if there are many components
+ // Filter out Note-contained components from workflow sorting
+ const workflowsForSorting = workflows.map((wf) => ({
+ ...wf,
+ components: wf.components.filter((c) => !containedComponentIds.has(c.id)),
+ }));
+
+ // Process workflows in batches
const BATCH_SIZE = 10;
- for (let i = 0; i < workflows.length; i += BATCH_SIZE) {
- const batch = workflows.slice(i, i + BATCH_SIZE);
- for (let wf of batch) {
- await organizeComponents(wf.components, wf.box.x, wf.box.y);
+ for (let i = 0; i < workflowsForSorting.length; i += BATCH_SIZE) {
+ const batch = workflowsForSorting.slice(i, i + BATCH_SIZE);
+ for (const wf of batch) {
+ if (wf.components.length > 0) {
+ await organizeComponents(wf.components, wf.box.x, wf.box.y);
+ }
}
- await delay(100); // Allow time for DOM updates
+ await delay(100);
}
await delay(100);
updateWFBoundingBox(workflows);
await delay(100);
await alignBoxes(workflows);
- await delay(200); // Increased delay to ensure DOM updates are complete
- //workspace.jsPlumbInstance.repaintEverything();
+ await delay(200);
+
+ // Reposition Notes to follow their contained components
+ await repositionNotesAfterSort(noteGroups, relativePositions);
+
+ // Resolve collisions with components that weren't originally inside Notes
+ await resolveNoteCollisions(noteGroups);
} catch (error) {
console.error('Error during sort:', error);
} finally {
workspace.unlock();
- // Ensure all component positions are properly saved
try {
- await delay(1000); // Give more time for final DOM updates
- await workspace.export(); // Update the agent data with current positions
+ await delay(1000);
+ await workspace.export();
await workspace.saveAgent();
await delay(100);
isSorting = false;
@@ -338,40 +584,49 @@ async function sortAll() {
}
async function sortSelection() {
- if (isSorting) {
- return;
- }
+ if (isSorting) return;
try {
isSorting = true;
const agentData = (await workspace.export(false)) || workspace.agent.data;
+
+ // Initialize Note context before sorting
+ const noteContext = initializeNoteSortContext();
+ const { noteGroups, relativePositions, containedComponentIds } = noteContext;
+
const workflows = await extractWorkflows(agentData);
const selectedComponents = [...document.querySelectorAll('.component.selected')];
- // Only proceed if there are selected components
- if (!selectedComponents.length) {
- return;
- }
+ if (!selectedComponents.length) return;
+
+ // Associate Notes with workflows
+ associateNotesWithWorkflows(noteGroups, workflows);
- //find workflows containing selected components
+ // Find workflows containing selected components
const selectedWorkflows = workflows.filter((wf) =>
selectedComponents.some((c) => wf.components.some((wc) => wc.id === c.id)),
);
workspace.lock();
- //sort selected workflows
- for (let wf of selectedWorkflows) {
- await organizeComponents(wf.components, wf.box.x, wf.box.y);
- }
- const unsortedComponents = [];
- for (let wf of workflows) {
- if (!selectedWorkflows.includes(wf)) {
- unsortedComponents.push(...wf.components);
+ // Filter out Note-contained components from workflow sorting
+ const selectedWorkflowsForSorting = selectedWorkflows.map((wf) => ({
+ ...wf,
+ components: wf.components.filter((c) => !containedComponentIds.has(c.id)),
+ }));
+
+ // Sort selected workflows
+ for (const wf of selectedWorkflowsForSorting) {
+ if (wf.components.length > 0) {
+ await organizeComponents(wf.components, wf.box.x, wf.box.y);
}
}
- // Only calculate unsorted box if there are unsorted components
+ // Collect unsorted components
+ const unsortedComponents = workflows
+ .filter((wf) => !selectedWorkflows.includes(wf))
+ .flatMap((wf) => wf.components);
+
if (unsortedComponents.length > 0) {
await delay(100);
updateWFBoundingBox(selectedWorkflows);
@@ -386,15 +641,20 @@ async function sortSelection() {
}
await delay(100);
- alignBoxes(selectedWorkflows);
+ await alignBoxes(selectedWorkflows);
await delay(100);
- //workspace.jsPlumbInstance.repaintEverything();
+
+ // Reposition Notes to follow their contained components
+ await repositionNotesAfterSort(noteGroups, relativePositions);
+
+ // Resolve collisions with components that weren't originally inside Notes
+ await resolveNoteCollisions(noteGroups);
} catch (error) {
console.error('Error during sort:', error);
} finally {
workspace.unlock();
await delay(500);
- // Ensure all component positions are properly saved
+
try {
await workspace.saveAgent();
await delay(100);