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.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
Add context menu functionality to workspace
Muhammad Hamza Khan667f41222828
diff --git a/packages/app/src/builder-ui/pages/builder/index.ts b/packages/app/src/builder-ui/pages/builder/index.tsindex 64d6ad36..53175dd3 100644--- a/packages/app/src/builder-ui/pages/builder/index.ts+++ b/packages/app/src/builder-ui/pages/builder/index.ts@@ -11,6 +11,7 @@ import {import { llmModelsStore } from '@src/shared/state_stores/llm-models';import { popupValuesDialog } from '../../ui/tw-dialogs';import { delay } from '../../utils';+import { registerCanvasContextMenu } from '../../workspace/CanvasContextMenu';import { setupAgentAuthScripts } from './agent-auth';import { setupAgentScripts } from './agent-settings';import { setupAgentTemplateScripts } from './agent-template';@@ -238,6 +239,9 @@ export default async function scripts() {//handle componentssetupComponentsScripts(workspace);+ // Register canvas context menu+ registerCanvasContextMenu(workspace);+// preload datapreloadDataScripts(workspace);diff --git a/packages/app/src/builder-ui/workspace/CanvasContextMenu.ts b/packages/app/src/builder-ui/workspace/CanvasContextMenu.tsnew file mode 100644index 00000000..74462e32--- /dev/null+++ b/packages/app/src/builder-ui/workspace/CanvasContextMenu.ts@@ -0,0 +1,171 @@+import { CanvasSearchHelper } from '../helpers/canvasSearch.helper';+import { canCopy, canPaste, copySelection, deleteSelectionWithConfirm } from './SelectionActions';+import { Workspace } from './Workspace.class';++type MenuState = {+ container: HTMLElement;+ menuEl: HTMLElement | null;+ closeHandler: ((e: MouseEvent) => void) | null;+};++const state: MenuState = {+ container: null,+ menuEl: null,+ closeHandler: null,+};++function destroyMenu() {+ if (state.menuEl && state.menuEl.parentElement) {+ state.menuEl.parentElement.removeChild(state.menuEl);+ }+ state.menuEl = null;+ if (state.closeHandler) {+ document.removeEventListener('mousedown', state.closeHandler);+ state.closeHandler = null;+ }+}++function buildMenuItem(label: string, onClick: () => void, disabled = false): HTMLElement {+ const item = document.createElement('button');+ item.type = 'button';+ item.className = `w-full text-left px-3 py-2 text-sm hover:bg-gray-50 ${+ disabled ? 'opacity-50 cursor-not-allowed pointer-events-none' : ''+ }`;+ item.textContent = label;+ if (!disabled) {+ item.addEventListener('click', (e) => {+ e.preventDefault();+ e.stopPropagation();+ try {+ onClick();+ } finally {+ destroyMenu();+ }+ });+ }+ return item;+}++async function createAndShowMenu(event: MouseEvent, workspace: Workspace) {+ destroyMenu();++ const containerRect = workspace.container.getBoundingClientRect();+ const workspaceRect = workspace.domElement.getBoundingClientRect();++ // Position menu relative to container+ let x = event.clientX - containerRect.left;+ let y = event.clientY - containerRect.top;++ // Compute paste position in workspace coordinates+ const pasteX = Math.round((event.clientX - workspaceRect.left) / workspace.scale);+ const pasteY = Math.round((event.clientY - workspaceRect.top) / workspace.scale);++ // Determine disabled states using shared helpers+ const copyEnabled = canCopy(workspace);+ const pasteEnabled = await canPaste(workspace);++ const menu = document.createElement('div');+ menu.setAttribute('data-context-menu', 'true');+ menu.className =+ 'absolute z-50 bg-white border border-gray-200 rounded-md shadow-md w-44 select-none';++ // Build items+ const copyItem = buildMenuItem(+ 'Copy',+ () => {+ const canCopyComponents = canCopy(workspace);+ if (!canCopyComponents) return;+ copySelection(workspace);+ },+ !copyEnabled,+ );++ const pasteItem = buildMenuItem(+ 'Paste',+ async () => {+ try {+ if (!(await canPaste(workspace))) return;+ // Unselect current selection and paste at position+ document+ .querySelectorAll('.component.selected')+ .forEach((c) => c.classList.remove('selected'));+ const text = await workspace.clipboard.read();+ await workspace.clipboard.pasteSelection(text, pasteX, pasteY);+ workspace.redraw();+ } catch (e) {+ // noop+ }+ },+ !pasteEnabled,+ );++ const deleteItem = buildMenuItem(+ 'Delete',+ async () => {+ await deleteSelectionWithConfirm(workspace);+ },+ !document.querySelector('#workspace-container .component.selected'),+ );++ const exportItem = buildMenuItem('Export agent', async () => {+ await workspace.exportTemplate();+ });++ const searchItem = buildMenuItem('Search', () => {+ const searchHelper = CanvasSearchHelper.getInstance();+ searchHelper.openSearch(workspace);+ });++ // Append items with small separators+ const group = document.createElement('div');+ group.className = 'py-1';+ group.appendChild(copyItem);+ group.appendChild(pasteItem);+ group.appendChild(deleteItem);++ const group2 = document.createElement('div');+ group2.className = 'py-1 border-t border-gray-100';+ group2.appendChild(exportItem);+ group2.appendChild(searchItem);++ menu.appendChild(group);+ menu.appendChild(group2);++ workspace.container.appendChild(menu);++ // Keep within bounds after mount+ const maxX = containerRect.width - menu.offsetWidth - 4;+ const maxY = containerRect.height - menu.offsetHeight - 4;+ x = Math.max(4, Math.min(x, maxX));+ y = Math.max(4, Math.min(y, maxY));+ menu.style.left = `${x}px`;+ menu.style.top = `${y}px`;++ state.menuEl = menu;+ state.container = workspace.container;++ // Close on outside click+ state.closeHandler = (e: MouseEvent) => {+ const target = e.target as Node;+ if (state.menuEl && !state.menuEl.contains(target)) {+ destroyMenu();+ }+ };+ document.addEventListener('mousedown', state.closeHandler);+}++export function registerCanvasContextMenu(workspace: Workspace) {+ const handler = async (e: MouseEvent) => {+ // Only handle right-clicks+ if (e.button !== 2) return;+ // Restrict to inside the workspace container+ if (!workspace.container.contains(e.target as Node)) return;++ e.preventDefault();+ e.stopPropagation();+ await createAndShowMenu(e, workspace);+ };++ // Attach to container so it works over components/inputs/agent card+ workspace.container.addEventListener('contextmenu', handler);+}diff --git a/packages/app/src/builder-ui/workspace/SelectionActions.ts b/packages/app/src/builder-ui/workspace/SelectionActions.tsnew file mode 100644index 00000000..209eb8bb--- /dev/null+++ b/packages/app/src/builder-ui/workspace/SelectionActions.ts@@ -0,0 +1,132 @@+import { confirm } from '../ui/dialogs';+import { delay } from '../utils';+import { Workspace } from './Workspace.class';++let deleteConfirmationActive = false;++export function isEditableHover(workspace: Workspace): boolean {+ const el = workspace.hoveredElement;+ if (!el) return false;+ if (el.tagName === 'TEXTAREA' || el.tagName === 'INPUT') return true;+ if (el.classList.contains('dbg') || el.closest('.dbg')) return true;+ return false;+}++export function isInteractionContextOK(): boolean {+ const active = document.activeElement as HTMLElement | null;+ if (!active) return true; // safety+ if (active === document.body) return true; // same as before+ // if focus is inside our context-menu consider it OK+ return !!active.closest('[data-context-menu="true"]');+}++export function hasSelectedText(): boolean {+ const text = window.getSelection()?.toString();+ return !!text;+}++export function isSelectionInEditable(): boolean {+ const selection = window.getSelection();+ const selectedText = selection?.toString();+ const isEditableElement = (node: Node): boolean => {+ const element = node instanceof Element ? node : node?.parentElement;+ return (+ element instanceof HTMLElement &&+ (element.isContentEditable || element.tagName === 'INPUT' || element.tagName === 'TEXTAREA')+ );+ };+ if (+ selectedText &&+ (isEditableElement(selection.anchorNode) || isEditableElement(selection.focusNode))+ ) {+ return true;+ }+ return false;+}++export function hasComponentSelection(): boolean {+ return document.querySelectorAll('#workspace-container .component.selected').length > 0;+}++export function canCopy(workspace: Workspace): boolean {+ if (workspace.locked) return false;++ if (!isInteractionContextOK()) return false;+ if (isEditableHover(workspace)) return false;+ if (hasSelectedText()) return false;+ if (!hasComponentSelection()) return false;+ return true;+}++export function copySelection(workspace: Workspace): void {+ const data = workspace.clipboard.copySelection();+ if (data) workspace.clipboard.write(data);+}++export async function canPaste(workspace: Workspace): Promise<boolean> {+ if (workspace.locked) return false;+ if (!isInteractionContextOK()) return false;+ if (isEditableHover(workspace)) return false;+ try {+ const text = await workspace.clipboard.read();+ return !!(text && text.trim().length > 0);+ } catch (e) {+ return false;+ }+}++export async function pasteFromClipboard(+ workspace: Workspace,+ pasteX?: number,+ pasteY?: number,+): Promise<void> {+ // Unselect current selection+ document.querySelectorAll('.component.selected').forEach((c) => c.classList.remove('selected'));++ const text = await workspace.clipboard.read();+ if (pasteX !== undefined && pasteY !== undefined) {+ await workspace.clipboard.pasteSelection(text, pasteX, pasteY);+ } else {+ await workspace.clipboard.pasteSelection(text);+ }+ workspace.redraw();+}++export function canDelete(workspace: Workspace): boolean {+ if (workspace.locked) return false;+ if (deleteConfirmationActive) return false;+ // If user selected text in an editable element, don't delete components+ if (isSelectionInEditable()) return false;+ if (!hasComponentSelection()) return false;+ return true;+}++export async function deleteSelectionWithConfirm(workspace: Workspace): Promise<boolean> {+ if (!canDelete(workspace)) return false;+ const list = [...document.querySelectorAll('.component.selected')];+ if (list.length <= 0) return false;+ const components = list.map((c: any) => c._control);+ deleteConfirmationActive = true;+ try {+ const confirmText = list.length === 1 ? 'component' : 'components';+ const shouldDelete = await confirm(+ `Are you sure you want to delete selected ${confirmText}?`,+ `This action cannot be undone. Deleting will remove the ${confirmText} permanently.`,+ {+ btnYesLabel: 'Delete',+ btnNoLabel: 'Cancel',+ btnYesClass: 'bg-smyth-red-500 border-smyth-red-500 h-[48px] rounded-lg px-8',+ btnNoClass: 'hidden',+ },+ );+ if (!shouldDelete) return false;+ const promises: Promise<void>[] = [];+ components.forEach((c) => promises.push(c.delete(true, false)));+ await Promise.all(promises);+ await delay(200);+ workspace.saveAgent();+ return true;+ } finally {+ deleteConfirmationActive = false;+ }+}diff --git a/packages/app/src/builder-ui/workspace/Workspace.class.ts b/packages/app/src/builder-ui/workspace/Workspace.class.tsindex a36aae02..d0baed82 100644--- a/packages/app/src/builder-ui/workspace/Workspace.class.ts+++ b/packages/app/src/builder-ui/workspace/Workspace.class.ts@@ -1012,6 +1012,8 @@ export class Workspace extends EventEmitter {let selectionRectangle = null;document.getElementById('workspace-container').addEventListener('mousedown', (event) => {+ const isContextMenu = !!(event.target as HTMLElement).closest('[data-context-menu="true"]');+ if (isContextMenu) return;document.querySelectorAll('#workspace-container .component').forEach((e) => e.classList.remove('selected', 'unselected'));diff --git a/packages/app/src/builder-ui/workspace/hotkeys.ts b/packages/app/src/builder-ui/workspace/hotkeys.tsindex 4b1f7824..93613b3d 100644--- a/packages/app/src/builder-ui/workspace/hotkeys.ts+++ b/packages/app/src/builder-ui/workspace/hotkeys.ts@@ -1,9 +1,13 @@import hotkeys from 'hotkeys-js';-import { Component } from '../components/Component.class';import { CanvasSearchHelper } from '../helpers/canvasSearch.helper';-import { confirm, runUIEnterKey } from '../ui/dialogs';-import { delay } from '../utils';+import { runUIEnterKey } from '../ui/dialogs';import { sortAgent } from './ComponentSort';+import {+ canCopy,+ canPaste,+ copySelection,+ deleteSelectionWithConfirm,+} from './SelectionActions';import { Workspace } from './Workspace.class';export function registerHotkeys(workspace: Workspace) {@@ -59,97 +63,22 @@ export function registerHotkeys(workspace: Workspace) {});hotkey(deleteHotkeys, async (event, handler) => {- if (workspace.locked) return false;- if (deleteConfirmationActive) return false; // Prevent additional modals-- const selection = window.getSelection();- const selectedText = selection.toString();-- // Check if the selection is within an editable element- const isEditableElement = (node: Node): boolean => {- const element = node instanceof Element ? node : node.parentElement;- return (- element instanceof HTMLElement &&- (element.isContentEditable || element.tagName === 'INPUT' || element.tagName === 'TEXTAREA')- );- };-- if (- selectedText &&- (isEditableElement(selection.anchorNode) || isEditableElement(selection.focusNode))- ) {- return false; // Don't proceed with component deletion if text is selected in an editable element- }-- const list = [...document.querySelectorAll('.component.selected')];- if (list.length <= 0) return false;- const components = list.map((c: any) => c._control);- deleteConfirmationActive = true; // Set flag when modal is about to show- const confirmText = list.length === 1 ? 'component' : 'components';- const shouldDelete = await confirm(- '',- `Are you sure you want to delete selected ${confirmText}?`,- {- icon: '',- btnNoLabel: 'Cancel',- btnYesLabel: `Delete ${confirmText}`,- btnYesClass: 'bg-smyth-red-500 border-smyth-red-500',- },- );- deleteConfirmationActive = false; // Reset flag after modal interaction- if (!shouldDelete) return;- const promises = [];- components.forEach((c: Component) => {- promises.push(c.delete(true, false));- });-- await Promise.all(promises);- await delay(200);- workspace.saveAgent();+ const ok = await deleteSelectionWithConfirm(workspace);+ return ok ? true : false;});hotkey(keys.save, (event, handler) => {if (workspace.locked) return false;//workspace.saveAgent();});hotkey(keys.copy, (event, handler) => {- const selectedText = window.getSelection().toString();- if (selectedText) {- return;- //copy selected text- // workspace.writeToClipboard(selectedText);- // return true;- }- if (workspace.locked) return false;- if (- workspace.hoveredElement.tagName == 'TEXTAREA' ||- workspace.hoveredElement.tagName == 'INPUT' ||- workspace.hoveredElement.classList.contains('dbg') ||- workspace.hoveredElement.closest('.dbg')- )- return;- if (document.activeElement != document.body) return;- //console.log('copy pressed');- const selectionData = workspace.clipboard.copySelection();- workspace.clipboard.write(selectionData);+ if (!canCopy(workspace)) return false;+ copySelection(workspace);});hotkey(keys.paste, async (event, handler) => {- if (workspace.locked) return false;- if (- workspace.hoveredElement.tagName == 'TEXTAREA' ||- workspace.hoveredElement.tagName == 'INPUT' ||- workspace.hoveredElement.classList.contains('dbg') ||- workspace.hoveredElement.closest('.dbg')- )- return;- if (document.activeElement != document.body) return;- //console.log('paste pressed');- //unselect all components+ if (!(await canPaste(workspace))) return false;document.querySelectorAll('.component.selected').forEach((c) => c.classList.remove('selected'));-const text = await workspace.clipboard.read();-workspace.clipboard.pasteSelection(text);-workspace.redraw();});hotkey(keys.undo, (event, handler) => {