diff --git a/backend/windmill-worker/src/js_eval.rs b/backend/windmill-worker/src/js_eval.rs index ea89e7d03c..a16da6b1d5 100644 --- a/backend/windmill-worker/src/js_eval.rs +++ b/backend/windmill-worker/src/js_eval.rs @@ -40,7 +40,7 @@ pub async fn eval_timeout( let (sender, mut receiver) = oneshot::channel::(); let base_internal_url: String = base_internal_url.to_string(); timeout( - std::time::Duration::from_millis(2000), + std::time::Duration::from_millis(3000), tokio::task::spawn_blocking(move || { let mut ops = vec![]; @@ -104,7 +104,7 @@ pub async fn eval_timeout( isolate.terminate_execution(); }; Error::ExecutionErr(format!( - "The expression of evaluation `{expr2}` took too long to execute (>2000ms)" + "The expression of evaluation `{expr2}` took too long to execute (>3000ms)" )) })?? } diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 24143558a9..0a5069ca48 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -19,6 +19,7 @@ "chart.js": "^3.9.1", "chartjs-adapter-date-fns": "^3.0.0", "chartjs-plugin-zoom": "^2.0.0", + "d3-zoom": "^3.0.0", "date-fns": "^2.29.3", "fast-equals": "^4.0.3", "highlight.js": "^11.7.0", @@ -46,7 +47,6 @@ "@typescript-eslint/eslint-plugin": "^5.49.0", "@typescript-eslint/parser": "^5.48.0", "@windmill-labs/svelte-grid": "^5.1.6", - "@windmill-labs/svelvet": "^4.0.20", "@zerodevx/svelte-toast": "^0.8.1", "autoprefixer": "^10.4.13", "cssnano": "^5.1.14", @@ -1323,15 +1323,6 @@ "integrity": "sha512-wXHIG7XeMxwxnfaHajhjvz9c0u5uGgiQtTk/QxAVyViGdshsclfIfIWZF113QQBKCKp2jY/zP1cj64BrqioRoQ==", "dev": true }, - "node_modules/@windmill-labs/svelvet": { - "version": "4.0.20", - "resolved": "https://registry.npmjs.org/@windmill-labs/svelvet/-/svelvet-4.0.20.tgz", - "integrity": "sha512-pbYoqYgLPNlNaLYiBQE5ealVLEXBrlAmzlSIeQYGnXIAEYpfkBxNyYmZo7Gek7ankn9WIHB0W4HHZKeCIo2v3A==", - "dev": true, - "dependencies": { - "d3-zoom": "^3.0.0" - } - }, "node_modules/@zeit/schemas": { "version": "2.21.0", "resolved": "https://registry.npmjs.org/@zeit/schemas/-/schemas-2.21.0.tgz", @@ -2335,7 +2326,6 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", - "dev": true, "engines": { "node": ">=12" } @@ -2356,7 +2346,6 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz", "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==", - "dev": true, "engines": { "node": ">=12" } @@ -2365,7 +2354,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz", "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==", - "dev": true, "dependencies": { "d3-dispatch": "1 - 3", "d3-selection": "3" @@ -2378,7 +2366,6 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==", - "dev": true, "engines": { "node": ">=12" } @@ -2387,7 +2374,6 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", - "dev": true, "dependencies": { "d3-color": "1 - 3" }, @@ -2399,7 +2385,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz", "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==", - "dev": true, "engines": { "node": ">=12" } @@ -2408,7 +2393,6 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz", "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==", - "dev": true, "engines": { "node": ">=12" } @@ -2417,7 +2401,6 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz", "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==", - "dev": true, "dependencies": { "d3-color": "1 - 3", "d3-dispatch": "1 - 3", @@ -2436,7 +2419,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz", "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==", - "dev": true, "dependencies": { "d3-dispatch": "1 - 3", "d3-drag": "2 - 3", @@ -8230,15 +8212,6 @@ "integrity": "sha512-wXHIG7XeMxwxnfaHajhjvz9c0u5uGgiQtTk/QxAVyViGdshsclfIfIWZF113QQBKCKp2jY/zP1cj64BrqioRoQ==", "dev": true }, - "@windmill-labs/svelvet": { - "version": "4.0.20", - "resolved": "https://registry.npmjs.org/@windmill-labs/svelvet/-/svelvet-4.0.20.tgz", - "integrity": "sha512-pbYoqYgLPNlNaLYiBQE5ealVLEXBrlAmzlSIeQYGnXIAEYpfkBxNyYmZo7Gek7ankn9WIHB0W4HHZKeCIo2v3A==", - "dev": true, - "requires": { - "d3-zoom": "^3.0.0" - } - }, "@zeit/schemas": { "version": "2.21.0", "resolved": "https://registry.npmjs.org/@zeit/schemas/-/schemas-2.21.0.tgz", @@ -8956,8 +8929,7 @@ "d3-color": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", - "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", - "dev": true + "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==" }, "d3-dag": { "version": "0.11.5", @@ -8974,14 +8946,12 @@ "d3-dispatch": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz", - "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==", - "dev": true + "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==" }, "d3-drag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz", "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==", - "dev": true, "requires": { "d3-dispatch": "1 - 3", "d3-selection": "3" @@ -8990,14 +8960,12 @@ "d3-ease": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", - "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==", - "dev": true + "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==" }, "d3-interpolate": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", - "dev": true, "requires": { "d3-color": "1 - 3" } @@ -9005,20 +8973,17 @@ "d3-selection": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz", - "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==", - "dev": true + "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==" }, "d3-timer": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz", - "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==", - "dev": true + "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==" }, "d3-transition": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz", "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==", - "dev": true, "requires": { "d3-color": "1 - 3", "d3-dispatch": "1 - 3", @@ -9031,7 +8996,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz", "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==", - "dev": true, "requires": { "d3-dispatch": "1 - 3", "d3-drag": "2 - 3", diff --git a/frontend/package.json b/frontend/package.json index 7b01a3111c..27ba37da53 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -26,7 +26,6 @@ "@typescript-eslint/eslint-plugin": "^5.49.0", "@typescript-eslint/parser": "^5.48.0", "@windmill-labs/svelte-grid": "^5.1.6", - "@windmill-labs/svelvet": "^4.0.20", "@zerodevx/svelte-toast": "^0.8.1", "autoprefixer": "^10.4.13", "cssnano": "^5.1.14", @@ -72,6 +71,7 @@ "chart.js": "^3.9.1", "chartjs-adapter-date-fns": "^3.0.0", "chartjs-plugin-zoom": "^2.0.0", + "d3-zoom": "^3.0.0", "date-fns": "^2.29.3", "fast-equals": "^4.0.3", "highlight.js": "^11.7.0", diff --git a/frontend/src/lib/assets/app.css b/frontend/src/lib/assets/app.css index 40ca117468..66a91482bc 100644 --- a/frontend/src/lib/assets/app.css +++ b/frontend/src/lib/assets/app.css @@ -56,6 +56,5 @@ /* Flow graph viewer -> Svelvet library internal class overwrite */ .Node { display: flex !important; - cursor: pointer !important; } } diff --git a/frontend/src/lib/components/DisplayResult.svelte b/frontend/src/lib/components/DisplayResult.svelte index cbcf18eedc..5bfaac04de 100644 --- a/frontend/src/lib/components/DisplayResult.svelte +++ b/frontend/src/lib/components/DisplayResult.svelte @@ -110,7 +110,7 @@ {#if result != undefined} {#if resultKind && resultKind != 'json'}
- as JSON 
{/if}{#if typeof result == 'object' && Object.keys(result).length > 0}
The result keys are: {truncate(Object.keys(result).join(', '), 50)} diff --git a/frontend/src/lib/components/FlowBuilder.svelte b/frontend/src/lib/components/FlowBuilder.svelte index e38a685d3f..a7bd51708d 100644 --- a/frontend/src/lib/components/FlowBuilder.svelte +++ b/frontend/src/lib/components/FlowBuilder.svelte @@ -1,6 +1,5 @@ {#if !$userStore?.operator} - - -
- -
-
-
-
-
diff --git a/frontend/src/lib/components/SchemaForm.svelte b/frontend/src/lib/components/SchemaForm.svelte index 61db77d490..12b75efc65 100644 --- a/frontend/src/lib/components/SchemaForm.svelte +++ b/frontend/src/lib/components/SchemaForm.svelte @@ -6,11 +6,9 @@ import { faPlus } from '@fortawesome/free-solid-svg-icons' import ArgInput from './ArgInput.svelte' import { Button } from './common' - import InputTransformForm from './InputTransformForm.svelte' import ItemPicker from './ItemPicker.svelte' import VariableEditor from './VariableEditor.svelte' - export let inputTransform = false export let schema: Schema export let args: Record = {} export let disabledArgs: string[] = [] @@ -18,16 +16,12 @@ export let editableSchema = false export let isValid: boolean = true - export let extraLib: string = 'missing extraLib' export let autofocus = false - export let previousModuleId: string | undefined = undefined export let shouldHideNoInputs: boolean = false export let compact = false export let password: string | undefined = undefined export let noVariablePicker = false - export let filter: string[] | undefined = undefined - export let noDynamicToggle = false export let flexWrap = false export let noDelete = false @@ -42,17 +36,19 @@ } function removeExtraKey() { + const nargs = {} Object.keys(args ?? {}).forEach((key) => { - if (!keys.includes(key)) { - delete args[key] - delete inputCheck[key] + if (keys.includes(key)) { + nargs[key] = args[key] } }) + args = nargs } let pickForField: string | undefined let itemPicker: ItemPicker | undefined = undefined let variableEditor: VariableEditor | undefined = undefined + let keys: string[] = [] $: { let lkeys = Object.keys(schema?.properties ?? {}) @@ -68,48 +64,60 @@
{#if keys.length > 0} {#each keys as argName, i (argName)} - {#if (!filter || filter.includes(argName)) && Object.keys(schema.properties ?? {}).includes(argName)} + {#if Object.keys(schema.properties ?? {}).includes(argName)}
- {#if inputTransform} - - {:else if typeof args == 'object' && schema?.properties[argName]} - - {:else} - Expected argument to be an object, got {JSON.stringify(args)} instead + {#if typeof args == 'object' && schema?.properties[argName]} + {#if editableSchema} + + {:else} + + {/if} {/if}
{/if} @@ -124,11 +132,7 @@ bind:this={itemPicker} pickCallback={(path, _) => { if (pickForField) { - if (inputTransform) { - args[pickForField].value = '$var:' + path - } else { - args[pickForField] = '$var:' + path - } + args[pickForField] = '$var:' + path } }} itemName="Variable" diff --git a/frontend/src/lib/components/apps/components/display/table/AppTable.svelte b/frontend/src/lib/components/apps/components/display/table/AppTable.svelte index 3c71e9f2ce..79e66113be 100644 --- a/frontend/src/lib/components/apps/components/display/table/AppTable.svelte +++ b/frontend/src/lib/components/apps/components/display/table/AppTable.svelte @@ -242,16 +242,28 @@ toggleRow(row, rowIndex)}>
{#each actionButtons as actionButton, actionIndex (actionIndex)} - { - toggleRow(row, rowIndex) - }} - extraQueryParams={{ row: row.original }} - bind:componentInput={actionButton.componentInput} - bind:staticOutputs={$staticOutputsStore[actionButton.id]} - /> + {#if rowIndex == 0} + { + toggleRow(row, rowIndex) + }} + extraQueryParams={{ row: row.original }} + bind:componentInput={actionButton.componentInput} + bind:staticOutputs={$staticOutputsStore[actionButton.id]} + /> + {:else} + { + toggleRow(row, rowIndex) + }} + extraQueryParams={{ row: row.original }} + bind:componentInput={actionButton.componentInput} + /> + {/if} {/each}
diff --git a/frontend/src/lib/components/apps/components/helpers/InputValue.svelte b/frontend/src/lib/components/apps/components/helpers/InputValue.svelte index 86b476867d..d2c83342f9 100644 --- a/frontend/src/lib/components/apps/components/helpers/InputValue.svelte +++ b/frontend/src/lib/components/apps/components/helpers/InputValue.svelte @@ -23,12 +23,26 @@ $: state = $worldStore?.state - $: lastInput && $worldStore && handleConnection() - $: lastInput && lastInput.type == 'template' && $state && (value = getValue(lastInput)) - $: lastInput && lastInput.type == 'eval' && $state && (value = evalExpr(lastInput)) + let timeout: NodeJS.Timeout | undefined = undefined + const debounce_ms = 50 + function debounce(cb: () => void) { + if (timeout) { + clearTimeout(timeout) + } + timeout = setTimeout(cb, debounce_ms) + } + + $: lastInput && $worldStore && debounce(handleConnection) + $: lastInput && + lastInput.type == 'template' && + $state && + debounce(() => (value = getValue(lastInput))) + $: lastInput && + lastInput.type == 'eval' && + $state && + debounce(() => (value = evalExpr(lastInput))) function handleConnection() { - // console.log('handle connection', id, lastInput) if (lastInput.type === 'connected') { $worldStore?.connect(lastInput, onValueChange) } else if (lastInput.type === 'static' || lastInput.type == 'template') { @@ -108,6 +122,7 @@ } function onValueChange(newValue: any): void { + console.log('newValue', newValue, id) if (lastInput.type === 'connected' && newValue !== undefined && newValue !== null) { const { connection } = lastInput diff --git a/frontend/src/lib/components/apps/components/inputs/AppMultiSelect.svelte b/frontend/src/lib/components/apps/components/inputs/AppMultiSelect.svelte index e52075d53b..faf466ef8c 100644 --- a/frontend/src/lib/components/apps/components/inputs/AppMultiSelect.svelte +++ b/frontend/src/lib/components/apps/components/inputs/AppMultiSelect.svelte @@ -61,12 +61,16 @@
{#if !value || Array.isArray(value)} -
+
{#if name !== undefined} diff --git a/frontend/src/lib/components/apps/editor/settingsPanel/ComponentPanel.svelte b/frontend/src/lib/components/apps/editor/settingsPanel/ComponentPanel.svelte index 9f38100b1d..e480092455 100644 --- a/frontend/src/lib/components/apps/editor/settingsPanel/ComponentPanel.svelte +++ b/frontend/src/lib/components/apps/editor/settingsPanel/ComponentPanel.svelte @@ -191,7 +191,7 @@
{#if viewCssOptions} -
+
{#each Object.keys(component.customCss ?? {}) as name} {#if component?.customCss?.[name]}
diff --git a/frontend/src/lib/components/apps/utils.ts b/frontend/src/lib/components/apps/utils.ts index a1fcf1efc9..e01a5abb44 100644 --- a/frontend/src/lib/components/apps/utils.ts +++ b/frontend/src/lib/components/apps/utils.ts @@ -4,13 +4,11 @@ import { inferArgs } from '$lib/infer' import { emptySchema } from '$lib/utils' import type { AppComponent } from './editor/component' import type { App, ComponentCssProperty, ComponentCustomCSS, GridItem } from './types' -import { getRecommendedDimensionsByComponent } from './editor/component' -import { gridColumns } from './gridUtils' -import gridHelp from '@windmill-labs/svelte-grid/src/utils/helper' import { twMerge } from 'tailwind-merge' import type { AppInput, InputType, ResultAppInput, StaticAppInput } from './inputType' import type { Output } from './rx' import { getNextId } from '../flows/flowStateUtils' +import { createNewGridItem } from './editor/appUtils' export function allItems( grid: GridItem[], @@ -283,45 +281,6 @@ export function insertNewGridItem( return root } -// The grid is needed to find a space for the new component -export function createNewGridItem(grid: GridItem[], id: string, data: AppComponent): GridItem { - const appComponent = data - - appComponent.id = id - - const newComponent = { - fixed: false, - resizable: true, - draggable: true, - customDragger: false, - customResizer: false, - x: 0, - y: 0 - } - - let newData: AppComponent = JSON.parse(JSON.stringify(appComponent)) - - const newItem: GridItem = { - data: newData, - id: id - } - - gridColumns.forEach((column) => { - const rec = getRecommendedDimensionsByComponent(appComponent.type, column) - - newItem[column] = { - ...newComponent, - min: { w: 1, h: 1 }, - max: { w: column, h: 100 }, - w: rec.w, - h: rec.h - } - const position = gridHelp.findSpace(newItem, grid, column) as { x: number; y: number } - newItem[column] = { ...newItem[column], ...position } - }) - - return newItem -} function recursiveGetIds(gridItem: GridItem): string[] { const subGrids = gridItem.data.subGrids ?? [] diff --git a/frontend/src/lib/components/common/menu/Menu.svelte b/frontend/src/lib/components/common/menu/Menu.svelte index 57b43396ec..880ac69bac 100644 --- a/frontend/src/lib/components/common/menu/Menu.svelte +++ b/frontend/src/lib/components/common/menu/Menu.svelte @@ -7,10 +7,10 @@ import { onMount } from 'svelte' export let noMinW = false - let show = false + export let show = false let menu: HTMLDivElement - type Alignment = 'start' | 'end' + type Alignment = 'start' | 'end' | 'center' type Side = 'top' | 'bottom' type Placement = `${Side}-${Alignment}` @@ -45,6 +45,7 @@ }) const placementsClasses = { + 'bottom-center': 'origin-top-left left-1/2 transform -translate-x-1/2', 'bottom-start': 'origin-top-left left-0', 'bottom-end': 'origin-top-right right-0', 'top-start': 'origin-bottom-left left-0 bottom-0', @@ -52,7 +53,7 @@ } -
+
{ diff --git a/frontend/src/lib/components/flows/FlowEditor.svelte b/frontend/src/lib/components/flows/FlowEditor.svelte index 82276142a0..213161c4b1 100644 --- a/frontend/src/lib/components/flows/FlowEditor.svelte +++ b/frontend/src/lib/components/flows/FlowEditor.svelte @@ -5,14 +5,18 @@ import { flowStore } from './flowStore' import WindmillIcon from '../icons/WindmillIcon.svelte' import { Skeleton } from '../common' + import { getContext } from 'svelte' + import type { FlowEditorContext } from './types' export let initialPath: string export let loading: boolean + + let size = 50
- +
{#if loading}
@@ -21,11 +25,11 @@ {/each}
{:else if $flowStore.value.modules} - + {/if}
- + {#if loading}
diff --git a/frontend/src/lib/components/flows/common/FlowCardHeader.svelte b/frontend/src/lib/components/flows/common/FlowCardHeader.svelte index 7b99248c16..13994016ce 100644 --- a/frontend/src/lib/components/flows/common/FlowCardHeader.svelte +++ b/frontend/src/lib/components/flows/common/FlowCardHeader.svelte @@ -34,7 +34,7 @@
{#if flowModule} diff --git a/frontend/src/lib/components/flows/content/FlowBranchesAllWrapper.svelte b/frontend/src/lib/components/flows/content/FlowBranchesAllWrapper.svelte index 8ca0a2abcb..10c0f98252 100644 --- a/frontend/src/lib/components/flows/content/FlowBranchesAllWrapper.svelte +++ b/frontend/src/lib/components/flows/content/FlowBranchesAllWrapper.svelte @@ -33,7 +33,7 @@ >
{#each value.branches as branch, i} -
+
diff --git a/frontend/src/lib/components/flows/content/FlowConstants.svelte b/frontend/src/lib/components/flows/content/FlowConstants.svelte index 17eb3e5561..c61fb5856c 100644 --- a/frontend/src/lib/components/flows/content/FlowConstants.svelte +++ b/frontend/src/lib/components/flows/content/FlowConstants.svelte @@ -9,6 +9,7 @@ import type { PropPickerWrapperContext } from '../propPicker/PropPickerWrapper.svelte' import { writable } from 'svelte/store' import Toggle from '../../Toggle.svelte' + import InputTransformSchemaForm from '$lib/components/InputTransformSchemaForm.svelte' let hideOptional = false @@ -75,9 +76,8 @@ {m.id} - -{:else if $selectedId === 'inputs'} +{:else if $selectedId === 'Input'} {:else if $selectedId === 'constants'} diff --git a/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte b/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte index a66c66cc00..5861f8d656 100644 --- a/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte +++ b/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte @@ -28,6 +28,7 @@ import Alert from '$lib/components/common/alert/Alert.svelte' import FlowModuleSleep from './FlowModuleSleep.svelte' import FlowPathViewer from './FlowPathViewer.svelte' + import InputTransformSchemaForm from '$lib/components/InputTransformSchemaForm.svelte' const { selectedId, previewArgs } = getContext('FlowEditorContext') @@ -225,9 +226,8 @@ pickableProperties={stepPropPicker.pickableProperties} error={failureModule} > - - If defined, the error handler will take as input, the result of the step that errored (which - has its error in the 'error field'). -
-
- Steps are retried until they succeed, or until the maximum number of retries defined for that - spec is reached, at which point the error handler is called. + If defined, the error handler will take the error as input. {/if} diff --git a/frontend/src/lib/components/flows/content/FlowSettings.svelte b/frontend/src/lib/components/flows/content/FlowSettings.svelte index 832f18f7fd..ecbbd479dc 100644 --- a/frontend/src/lib/components/flows/content/FlowSettings.svelte +++ b/frontend/src/lib/components/flows/content/FlowSettings.svelte @@ -10,7 +10,6 @@ import FlowSchedules from './FlowSchedules.svelte' import Toggle from '$lib/components/Toggle.svelte' import { Alert } from '$lib/components/common' - import { FlowGraph } from '$lib/components/graph' import { getContext } from 'svelte' import type { FlowEditorContext } from '../types' import autosize from 'svelte-autosize' @@ -25,8 +24,6 @@ export let initialPath: string - let topHeight = 0 - $: url = `${$page.url.hostname}/api/w/${$workspaceStore}/jobs/run/f/${$flowStore?.path}` @@ -37,7 +34,6 @@ Metadata Schedule Shared Directory - Graph @@ -89,18 +85,22 @@
  • -
    - 2. Use a trigger script and schedule this flow to run as frequently as - needed and compare a state persisted in Windmill to the state of the - external system. If a difference is detected, then the rest of the flow is - triggered. Oftentimes, the second step of a flow is a for-loop that will - iterate over every elements. When using a trigger, a default schedule will - be created. - static button +
    +

    + 2. Use a trigger script and schedule this flow to run as frequently as + needed and compare a state persisted in Windmill to the state of the + external system. If a difference is detected, then the rest of the flow is + triggered. Oftentimes, the second step of a flow is a for-loop that will + iterate over every elements. When using a trigger, a default schedule will + be created. +

    +
    + static button +
  • @@ -132,26 +132,6 @@ }} />
    - -
    - {#if $flowStore.value.modules} - { - if (e.detail.id) { - $selectedId = e.detail.id - } - }} - minHeight={topHeight} - modules={$flowStore.value.modules} - failureModule={$flowStore.value.failure_module} - notSelectable - /> - {/if} -
    -
    diff --git a/frontend/src/lib/components/flows/map/FlowBranchAllMap.svelte b/frontend/src/lib/components/flows/map/FlowBranchAllMap.svelte deleted file mode 100644 index 2ab7e00e08..0000000000 --- a/frontend/src/lib/components/flows/map/FlowBranchAllMap.svelte +++ /dev/null @@ -1,110 +0,0 @@ - - -{#if module.value.type === 'branchall'} -
    -
    - {#each module.value.branches ?? [] as branch, branchIndex (branchIndex)} - -
    -
    { - selectedBranch = branchIndex - select(`${module.id}-branch-${branchIndex}`) - }} - class={classNames( - `border-b ${ - branchIndex > 0 ? 'border-t' : '' - } w-full p-2 bg-white border-gray-500 text-sm cursor-pointer flex items-center relative module`, - $selectedId === `${module.id}-branch-${branchIndex}` - ? 'outline outline-2 outline-slate-900' - : '' - )} - > - - - {branch.summary || `Branch ${branchIndex}`} - - -
    - -
    - -
    -
    - {/each} -
    - -
    -
    -
    -{/if} - - diff --git a/frontend/src/lib/components/flows/map/FlowBranchOneMap.svelte b/frontend/src/lib/components/flows/map/FlowBranchOneMap.svelte deleted file mode 100644 index 3cf9b1703c..0000000000 --- a/frontend/src/lib/components/flows/map/FlowBranchOneMap.svelte +++ /dev/null @@ -1,134 +0,0 @@ - - -{#if module.value.type === 'branchone'} -
    -
    - -
    { - selectedBranch = 0 - select(`${module.id}-branch-default`) - }} - class={classNames( - `border-b w-full p-2 bg-white border-gray-500 text-sm cursor-pointer flex items-center relative module`, - $selectedId === `${module.id}-branch-default` - ? 'outline outline-2 outline-slate-900' - : '' - )} - > - - - Default branch - -
    -
    - -
    - - {#each module.value.branches ?? [] as branch, branchIndex (branchIndex)} - -
    -
    { - selectedBranch = branchIndex + 1 - select(`${module.id}-branch-${branchIndex}`) - }} - class={classNames( - `border-b border-t w-full p-2 bg-white border-gray-500 text-sm cursor-pointer flex items-center relative module`, - $selectedId === `${module.id}-branch-${branchIndex}` - ? 'outline outline-2 outline-slate-900' - : '' - )} - > - - - {branch.summary || `Branch ${branchIndex}`} - - -
    - -
    - -
    -
    - {/each} -
    - -
    -
    -
    -{/if} - - diff --git a/frontend/src/lib/components/flows/map/FlowConstantsItem.svelte b/frontend/src/lib/components/flows/map/FlowConstantsItem.svelte index b78f36f138..3f69e8de70 100644 --- a/frontend/src/lib/components/flows/map/FlowConstantsItem.svelte +++ b/frontend/src/lib/components/flows/map/FlowConstantsItem.svelte @@ -4,7 +4,7 @@ import { classNames } from '$lib/utils' import { DollarSign } from 'lucide-svelte' - const { select, selectedId } = getContext('FlowEditorContext') + const { selectedId } = getContext('FlowEditorContext') $: settingsClass = classNames( 'border w-full rounded-sm p-2 bg-white border-gray-400 text-sm cursor-pointer flex items-center', @@ -12,7 +12,7 @@ ) - - {/if} -
    + {#if deletable} + + {/if}
    diff --git a/frontend/src/lib/components/flows/map/FlowModuleSchemaMap.svelte b/frontend/src/lib/components/flows/map/FlowModuleSchemaMap.svelte index a209f014ac..cdb5e35c3c 100644 --- a/frontend/src/lib/components/flows/map/FlowModuleSchemaMap.svelte +++ b/frontend/src/lib/components/flows/map/FlowModuleSchemaMap.svelte @@ -6,167 +6,220 @@ createBranches, createLoop, deleteFlowStateById, - emptyModule, - idMutex + emptyModule } from '$lib/components/flows/flowStateUtils' - import { flowStateStore, type FlowModuleState } from '../flowState' + import { flowStateStore } from '../flowState' import type { FlowModule } from '$lib/gen' - import FlowErrorHandlerItem from './FlowErrorHandlerItem.svelte' import RemoveStepConfirmationModal from '../content/RemoveStepConfirmationModal.svelte' import { emptyFlowModuleState } from '../utils' - import MapItem from './MapItem.svelte' import FlowSettingsItem from './FlowSettingsItem.svelte' - import FlowInputsItem from './FlowInputsItem.svelte' - import InsertModuleButton from './InsertModuleButton.svelte' - import { slide } from 'svelte/transition' import FlowConstantsItem from './FlowConstantsItem.svelte' - export let root: boolean = false - export let modules: FlowModule[] | undefined - export let parentType: 'flow' | 'forloop' | 'branchall' | 'branchone' | undefined = undefined + import { dfs, flowStore } from '../flowStore' + import { FlowGraph } from '$lib/components/graph' + import FlowErrorHandlerItem from './FlowErrorHandlerItem.svelte' - let indexToRemove: number | undefined = undefined - const { select, selectedId } = getContext('FlowEditorContext') + export let modules: FlowModule[] | undefined + export let sidebarSize: number | undefined = undefined + + let idToRemove: string | undefined = undefined + + const { selectedId } = getContext('FlowEditorContext') async function insertNewModuleAtIndex( + modules: FlowModule[], index: number, kind: 'script' | 'forloop' | 'branchone' | 'branchall' | 'flow' | 'trigger' | 'approval' | 'end' - ): Promise { - await idMutex.runExclusive(async () => { - var module = emptyModule(kind == 'flow') - var state = emptyFlowModuleState() - if (kind == 'forloop') { - ;[module, state] = await createLoop(module.id) - } else if (kind == 'branchone') { - ;[module, state] = await createBranches(module.id) - } else if (kind == 'branchall') { - ;[module, state] = await createBranchAll(module.id) + ): Promise { + var module = emptyModule(kind == 'flow') + var state = emptyFlowModuleState() + if (kind == 'forloop') { + ;[module, state] = await createLoop(module.id) + } else if (kind == 'branchone') { + ;[module, state] = await createBranches(module.id) + } else if (kind == 'branchall') { + ;[module, state] = await createBranchAll(module.id) + } + $flowStateStore[module.id] = state + if (kind == 'trigger') { + module.summary = 'Trigger' + } else if (kind == 'approval') { + module.summary = 'Approval' + } else if (kind == 'end') { + module.summary = 'Terminate flow' + module.stop_after_if = { skip_if_stopped: false, expr: 'true' } + } + if (!modules) return [module] + modules.splice(index, 0, module) + return modules + } + + function removeAtId(modules: FlowModule[], id: string): FlowModule[] { + const index = modules.findIndex((mod) => mod.id == id) + if (index != -1) { + const [removed] = modules.splice(index, 1) + const leaves = dfs([removed], (mod) => mod.id) + leaves.forEach((leafId: string) => deleteFlowStateById(leafId)) + return modules + } + return modules.map((mod) => { + if (mod.value.type == 'forloopflow') { + mod.value.modules = removeAtId(mod.value.modules, id) + } else if (mod.value.type == 'branchall') { + mod.value.branches = mod.value.branches.map((branch) => { + branch.modules = removeAtId(branch.modules, id) + return branch + }) + } else if (mod.value.type == 'branchone') { + mod.value.branches = mod.value.branches.map((branch) => { + branch.modules = removeAtId(branch.modules, id) + return branch + }) + mod.value.default = removeAtId(mod.value.default, id) } - const flowModule = module - if (!modules) return - modules.splice(index, 0, flowModule) - modules = modules - $flowStateStore[flowModule.id] = state - if (kind == 'trigger') { - flowModule.summary = 'Trigger' - } else if (kind == 'approval') { - flowModule.summary = 'Approval' - } else if (kind == 'end') { - flowModule.summary = 'Terminate flow' - flowModule.stop_after_if = { skip_if_stopped: false, expr: 'true' } - } - select(flowModule.id) + return mod }) } - function removeAtIndex(index: number): void { - if (!modules) return - const [removedModule] = modules.splice(index, 1) - modules = modules + // async function insertModule( + // modules: FlowModule[], + // id: string, + // kind: string, + // where: 'before' | 'after' + // ): Promise { + // console.log(modules, id, kind, where) + // const index = modules.findIndex((mod) => mod.id == id) + // if (index != -1) { + // console.log('INSERTING', modules, index) + // return await insertNewModuleAtIndex(modules, index + (where == 'after' ? 1 : 0), kind as any) + // } + // return await Promise.all( + // modules.map(async (mod) => { + // if (mod.value.type == 'forloopflow') { + // mod.value.modules = await insertModule(mod.value.modules, id, kind, where) + // } else if (mod.value.type == 'branchall') { + // mod.value.branches = await Promise.all( + // mod.value.branches.map(async (branch) => { + // branch.modules = await insertModule(branch.modules, id, kind, where) + // return branch + // }) + // ) + // } else if (mod.value.type == 'branchone') { + // mod.value.branches = await Promismod.value.branches.map((branch) => { + // branch.modules = await insertModule(branch.modules, id, kind, where) + // return branch + // }) + // mod.value.default = await insertModule(mod.value.default, id, kind, where) + // } + // return mod + // }) + // ) + // } - const leaves = findLeaves(removedModule) + $: confirmationModalOpen = idToRemove !== undefined - leaves.forEach((leafId: string) => deleteFlowStateById(leafId)) - select('settings-graph') + $: sidebarMode == 'graph' ? (sidebarSize = 40) : (sidebarSize = 20) + + let sidebarMode: 'list' | 'graph' = 'graph' + + let minHeight = 0 + + function selectNextId(id: any) { + if (modules) { + let allIds = dfs(modules, (mod) => mod.id) + if (allIds.length > 1) { + const idx = allIds.indexOf(id) + $selectedId = idx == 0 ? allIds[0] : allIds[idx - 1] + } else { + $selectedId = 'settings-metadata' + } + } + } + async function addBranch(module: FlowModule) { + if (module.value.type === 'branchone' || module.value.type === 'branchall') { + module.value.branches.splice(module.value.branches.length, 0, { + summary: '', + expr: 'false', + modules: [] + }) + } } - function findLeaves(flowModule: FlowModule): string[] { - const id = flowModule.id - - if (flowModule.value.type === 'forloopflow') { - return [id, ...flowModule.value.modules.map((fm) => findLeaves(fm)).flat()] + function removeBranch(module: FlowModule, index: number) { + if (module.value.type === 'branchone' || module.value.type === 'branchall') { + const leaves = dfs(module.value.branches[index].modules, (mod) => mod.id) + leaves.forEach((leafId: string) => deleteFlowStateById(leafId)) + module.value.branches.splice(index, 1) } - - if (flowModule.value.type === 'branchall') { - return [ - id, - ...flowModule.value.branches - .map((branch) => branch.modules.map((mod) => findLeaves(mod)).flat()) - .flat() - ] - } - - if (flowModule.value.type === 'branchone') { - return [ - id, - ...flowModule.value.branches - .map((branch) => { - return branch.modules.map((mod) => findLeaves(mod)).flat() - }) - .flat(), - ...flowModule.value.default.map((mod) => findLeaves(mod)).flat() - ] - } - - return [id] } - - $: confirmationModalOpen = indexToRemove !== undefined
    - {#if root} -
    - - -
    - {/if} -
      - {#if root} -
    • - -
    • - {/if} +
      + + +
      - {#if modules} - {#each modules as mod, index (mod.id ?? index)} -
      - { - if (event.detail.detail.shiftKey || mod.value.type === 'identity') { - removeAtIndex(index) - } else { - indexToRemove = index - } - }} - on:insert={(e) => { - insertNewModuleAtIndex(index, e.detail) - }} - /> -
      - {/each} - {/if} - {#if !modules || modules[modules?.length - 1]?.summary != 'Terminate flow'} - insertNewModuleAtIndex(modules?.length ?? 0, e.detail)} - /> - {:else} -
      - {/if} -
    - {#if root} -
    - -
    - {/if} +
    + { + let e = detail.detail + if (e.event.shiftKey || e.type == 'identity') { + selectNextId(e.id) + removeAtId($flowStore.value.modules, e.id) + $flowStore = $flowStore + } else { + idToRemove = e.id + } + }} + on:insert={async ({ detail }) => { + if (detail.modules) { + await insertNewModuleAtIndex(detail.modules, detail.index ?? 0, detail.detail) + $flowStore = $flowStore + $selectedId = detail.modules[detail.index ?? 0].id + } + }} + on:newBranch={async ({ detail }) => { + if (detail.module) { + await addBranch(detail.module) + $flowStore = $flowStore + } + }} + on:deleteBranch={async ({ detail }) => { + if (detail.module) { + await removeBranch(detail.module, detail.index) + $flowStore = $flowStore + $selectedId = detail.module.id + } + }} + /> +
    +
    + +
    { - indexToRemove = undefined + idToRemove = undefined }} on:confirmed={() => { - if (indexToRemove !== undefined) { - removeAtIndex(indexToRemove) - indexToRemove = undefined + if (idToRemove !== undefined) { + selectNextId(idToRemove) + removeAtId($flowStore.value.modules, idToRemove) + $flowStore = $flowStore + idToRemove = undefined } - $selectedId = 'settings-graph' }} /> diff --git a/frontend/src/lib/components/flows/map/FlowSettingsItem.svelte b/frontend/src/lib/components/flows/map/FlowSettingsItem.svelte index 12c6e193a5..2d44fad52f 100644 --- a/frontend/src/lib/components/flows/map/FlowSettingsItem.svelte +++ b/frontend/src/lib/components/flows/map/FlowSettingsItem.svelte @@ -6,7 +6,7 @@ import { flowStore } from '../flowStore' import { SlidersHorizontal } from 'lucide-svelte' - const { select, selectedId } = getContext('FlowEditorContext') + const { selectedId } = getContext('FlowEditorContext') $: settingsClass = classNames( 'border w-full rounded-sm p-2 bg-white border-gray-400 text-sm cursor-pointer flex items-center', @@ -16,9 +16,11 @@ ) - -
    +
    {#if trigger} {/if}
    + + {/if} + {#if insertable && insertableEnd} +
    + { + dispatch('insert', { modules, index: idx + 1, detail: e.detail }) + }} + /> +
    + {/if} + + {#if insertable && branchable} +
    + +
    {/if} {/if} - - diff --git a/frontend/src/lib/components/flows/map/VirtualItem.svelte b/frontend/src/lib/components/flows/map/VirtualItem.svelte new file mode 100644 index 0000000000..dd2375fac3 --- /dev/null +++ b/frontend/src/lib/components/flows/map/VirtualItem.svelte @@ -0,0 +1,98 @@ + + +{#if insertable && deleteBranch} +
    + +
    +{/if} + +
    { + if (selectable) { + if (id) { + dispatch('select', id) + } else { + dispatch('select', label) + } + } + }} +> +
    + {#if $$slots.icon} + + + {/if} +
    +
    {label}
    +
    + {#if id} + {id} + {/if} +
    +
    +
    + +{#if insertable && modules} +
    + { + if (modules) { + dispatch('insert', { modules, index, detail: e.detail }) + } + }} + /> +
    +{/if} diff --git a/frontend/src/lib/components/flows/types.ts b/frontend/src/lib/components/flows/types.ts index 5f6594560b..924bc2375d 100644 --- a/frontend/src/lib/components/flows/types.ts +++ b/frontend/src/lib/components/flows/types.ts @@ -4,7 +4,6 @@ import type { Schedule } from './scheduleUtils' export type FlowEditorContext = { selectedId: Writable - select: (id: string) => void schedule: Writable, previewArgs: Writable>, scriptEditorDrawer: Writable diff --git a/frontend/src/lib/components/graph/FlowGraph.svelte b/frontend/src/lib/components/graph/FlowGraph.svelte index f948525b56..bb5122d20a 100644 --- a/frontend/src/lib/components/graph/FlowGraph.svelte +++ b/frontend/src/lib/components/graph/FlowGraph.svelte @@ -1,8 +1,6 @@
    {#if width && height} - + {#key width} + + {/key} {/if}
    diff --git a/frontend/src/lib/components/graph/model.ts b/frontend/src/lib/components/graph/model.ts index 1d0ea87b97..a77f58fd9e 100644 --- a/frontend/src/lib/components/graph/model.ts +++ b/frontend/src/lib/components/graph/model.ts @@ -1,40 +1,9 @@ import type { FlowStatusModule } from "$lib/gen" +import type { UserNodeType } from "./svelvet/types"; -export interface SvelvetNode { - id: number; - position: { x: number, y: number }; - data: T; - width: number; - height: number; - bgColor?: string; - fontSize?: number; - borderColor?: string; - parentNode?: number; - childNodes?: number[]; - borderRadius?: number; - textColor?: string; - clickCallback?: Function; - image?: boolean; - src?: string; - sourcePosition?: 'left' | 'right' | 'top' | 'bottom'; - targetPosition?: 'left' | 'right' | 'top' | 'bottom'; -} -export interface Edge { - id: string; - source: number; - target: number; - label?: string; - labelBgColor?: string; - labelTextColor?: string; - edgeColor?: string; - type?: string; - animate?: boolean; - noHandle?: boolean; - arrow?: boolean; -} export type ModuleHost = 'workspace' | 'inline' | 'hub' -export type Node = SvelvetNode & { parentIds: string[], edgeLabel?: string, host?: ModuleHost } +export type Node = UserNodeType & { parentIds: string[], edgeLabel?: string, host?: ModuleHost, type: 'node', loopDepth: number } export type Loop = { type: 'loop', @@ -43,6 +12,7 @@ export type Loop = { export type Branch = { node: Node, + nodeEnd: Node, type: 'branch', items: NestedNodes[] } @@ -64,7 +34,7 @@ export type GraphModuleState = { export type NestedNodes = GraphItem[] export function isNode(item: GraphItem | NestedNodes | undefined): item is Node { - return typeof item?.['id'] === 'number' + return item?.['type'] === 'node' } export function isLoop(item: GraphItem | NestedNodes | undefined): item is Loop { diff --git a/frontend/src/lib/components/graph/svelvet/LICENSE b/frontend/src/lib/components/graph/svelvet/LICENSE new file mode 100644 index 0000000000..73a46f09bf --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 OSLabs Beta + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/frontend/src/lib/components/graph/svelvet/collapsible/controllers/util.ts b/frontend/src/lib/components/graph/svelvet/collapsible/controllers/util.ts new file mode 100644 index 0000000000..a6f6c37167 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/collapsible/controllers/util.ts @@ -0,0 +1,186 @@ +import type { + EdgeType, + NodeType, + ResizeNodeType, + StoreType, +} from '../../store/types/types'; +import type { UserEdgeType, UserNodeType } from '../../types/types'; +import { Collapsible } from '../models/Collapsible'; +import type { CollapsibleType } from '../types/types'; +import { get } from 'svelte/store'; +import type { AnchorType } from '../../edges/types/types'; +import { getAnchorById } from '../../edges/controllers/util'; +import { getAnchors } from '../../edges/controllers/util'; + +const pkStringGenerator = () => (Math.random() + 1).toString(36).substring(7); + +/* +Initializes store with array of Collapsible objects. You shoould only use this if you want the collapsible feature enabled. +*/ +export function populateCollapsibleStore( + store: StoreType, + userNodes: UserNodeType[], + userEdges: UserEdgeType[], + canvasId: string +) { + const newCollapsibleStore: CollapsibleType[] = []; + for (let userNode of userNodes) { + const collapsible = new Collapsible( + pkStringGenerator(), + userNode.id, + 0, + 'expanded' + ); + newCollapsibleStore.push(collapsible); + } + store.collapsibleStore.set(newCollapsibleStore); +} + +/* + +*/ +function incrementHideCount(store: StoreType, nodeId: string) { + const collapsibles = get(store.collapsibleStore); + for (let collapsible of collapsibles) + if (collapsible.nodeId === nodeId) collapsible.hideCount++; + store.collapsibleStore.set(collapsibles); +} + +// Given a nodeId, find ids of all connecting target nodes +function findTargets(store: StoreType, nodeId: string): string[] { + // get source anchors on the node + const anchors = getAnchors(store, { + nodeId: nodeId, + sourceOrTarget: 'source', + }); + + // get target anchors on other node, and record the node id + const targetNodeIds: string[] = []; + for (const anchor of anchors) { + const targetAnchorId = anchor.getOtherAnchorId(); + const targetAnchor = getAnchorById(store, targetAnchorId); + targetNodeIds.push(targetAnchor.nodeId); + } + return targetNodeIds; +} + +// traverses tree and increments hideCount +function traverseAndIncrement( + store: StoreType, + nodeId: string, + operation: 'increment' | 'decrement' +) { + const collapsibles = get(store.collapsibleStore); + recursiveTraverse(nodeId); + store.collapsibleStore.set(collapsibles); + + function recursiveTraverse(nId: string) { + for (const collapsible of collapsibles) { + if (collapsible.nodeId === nId) { + if (operation === 'increment') collapsible.hideCount++; + else collapsible.hideCount--; + const targetIds = findTargets(store, nId); + for (const targetId of targetIds) { + recursiveTraverse(targetId); + } + } + } + } +} + +function collapse(store: StoreType, nodeId: string) { + const targetNodeIds = findTargets(store, nodeId); + for (const targetNodeId of targetNodeIds) + traverseAndIncrement(store, targetNodeId, 'increment'); +} +function expand(store: StoreType, nodeId: string) { + const targetNodeIds = findTargets(store, nodeId); + for (const targetNodeId of targetNodeIds) + traverseAndIncrement(store, targetNodeId, 'decrement'); +} + +export function toggleExpandAndCollapse(store: StoreType, nodeId: string) { + const collapsibles = getCollapsibles(store, { nodeId: nodeId }); + if (collapsibles.length === 0) return; // when the collapsible feature is disabled, there will be no collapbsible objects + if (collapsibles.length > 1) + throw 'there should only be one collapsible object per node'; + const collapsible = collapsibles[0]; + if (collapsible.state === 'expanded') collapse(store, nodeId); + else expand(store, nodeId); + store.collapsibleStore.update((arr) => { + for (const c of arr) if (c.id === collapsible.id) c.toggleState(); + return [...arr]; + }); +} + +export function getCollapsibles( + store: StoreType, + filter?: { [key: string]: any } +) { + let collapsibles = Object.values(get(store.collapsibleStore)); + // filter the array of anchors for elements that match filter + // Example: if filter = {sourceOrTarget: 'source', positionX: 35} then we will + //return all anchors with sourceOrTarget = source AND poxitionX = 35 + if (filter !== undefined) { + collapsibles = collapsibles.filter((collapsible) => { + for (let filterKey in filter) { + const filterValue = filter[filterKey]; + if (collapsible[filterKey as keyof CollapsibleType] !== filterValue) + return false; + } + return true; + }); + } + // return list of anchors + return collapsibles; +} + +/* + This function is responsible for filtering nodes should be displayed based on Collapsible. + It also filters node-associated elements such as anchors, edges, etc. so that when you collapse a node, the + edges also hide. + There is a better way to implement this with foreign keys; when collapsing a node, you would also collapse any rows with a foreign key + linking to that node (like a cascading delete in SQL, but with hiding instead of deleting) +*/ +export function filterByCollapsible( + store: StoreType, + nodes: NodeType[], + resizeNodes: ResizeNodeType[], + anchors: AnchorType[], + edges: EdgeType[] +) { + // filter nodes for the collapsible nodes feature + const filteredNodes = nodes.filter((node) => { + const nodeId = node.id; + const collapssibleObj = get(store.collapsibleStore).find( + (e) => e.nodeId === nodeId + ); + if (collapssibleObj === undefined) return true; + return collapssibleObj.isHidden() === false; + }); + const filteredNodeIds = filteredNodes.map((e) => e.id); + // filter resizeNodes + const filteredResizeNodes = resizeNodes.filter((resizeNode) => + filteredNodeIds.includes(resizeNode.nodeId) + ); + const filteredAnchors = anchors.filter((selfAnchor) => { + const otherAnchorId = selfAnchor.getOtherAnchorId(); + const otherAnchor = get(store.anchorsStore)[otherAnchorId]; + + if ( + filteredNodeIds.includes(selfAnchor.nodeId) && + filteredNodeIds.includes(otherAnchor.nodeId) + ) + return true; + return false; + }); + const filteredEdgeIds = new Set(filteredAnchors.map((e) => e.edgeId)); + const filteredEdges = edges.filter((edge) => filteredEdgeIds.has(edge.id)); + + return { + filteredNodes, + filteredResizeNodes, + filteredAnchors, + filteredEdges, + }; +} diff --git a/frontend/src/lib/components/graph/svelvet/collapsible/models/Collapsible.ts b/frontend/src/lib/components/graph/svelvet/collapsible/models/Collapsible.ts new file mode 100644 index 0000000000..6dbd74e159 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/collapsible/models/Collapsible.ts @@ -0,0 +1,26 @@ +/** + * This model implements functionality for nodes to expand and collapse their children + */ + +import type { CollapsibleType } from '../types/types'; + +/** Class that implements collapsible/expandable functionality for Node objects + * @param {string} id Unique string that serves as a primary key + * @param {string} nodeId Foreign key to a Node Object + */ +export class Collapsible implements CollapsibleType { + constructor( + public id: string, + public nodeId: string, + public hideCount: number, + public state: 'expanded' | 'collapsed' + ) {} + + isHidden() { + return this.hideCount > 0; + } + + toggleState() { + this.state = this.state === 'expanded' ? 'collapsed' : 'expanded'; + } +} diff --git a/frontend/src/lib/components/graph/svelvet/collapsible/types/types.ts b/frontend/src/lib/components/graph/svelvet/collapsible/types/types.ts new file mode 100644 index 0000000000..f9b76b0971 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/collapsible/types/types.ts @@ -0,0 +1,8 @@ +export interface CollapsibleType { + id: string; + nodeId: string; + hideCount: number; + state: 'expanded' | 'collapsed'; + isHidden: Function; + toggleState: Function; +} diff --git a/frontend/src/lib/components/graph/svelvet/container/README.md b/frontend/src/lib/components/graph/svelvet/container/README.md new file mode 100644 index 0000000000..27a6c64fe7 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/container/README.md @@ -0,0 +1,7 @@ +# Container + +This folder contains two containers: Svelvet and Canvas. + +## Svelvet.svelte + +Svelvet.svelte is the top level component diff --git a/frontend/src/lib/components/graph/svelvet/container/controllers/middleware.ts b/frontend/src/lib/components/graph/svelvet/container/controllers/middleware.ts new file mode 100644 index 0000000000..70385bffad --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/container/controllers/middleware.ts @@ -0,0 +1,120 @@ +/* +This file contains "middleware" functions that sanitize user input (UserNodeType and UserEdgeType). Put functions that +maintain consistency between previous + +*/ +import { get } from 'svelte/store'; +import { + bottomCb, + leftCb, + rightCb, + topCb, +} from '../../edges/controllers/anchorCbUser'; +import type { StoreType } from '../../store/types/types'; +import type { UserEdgeType, UserNodeType } from '../../types/types'; + +/** + * sanitizeCanvasOptions will sanitize the canvas level options so that incompatible features will not be run simulataneously + * @param store The array of nodes that have a UserNodeType + * @returns void. The store is modified directly + */ +export function sanitizeCanvasOptions(store: StoreType) { + enforceCollapsibleCompatibility(store); +} + +function enforceCollapsibleCompatibility(store: StoreType) { + if (get(store.collapsibleOption)) { + store.nodeCreate.set(false); + } +} + +/** + * sanitizeUserNodesAndEdges will sanitize the data initially passed in to Svelvet component. For example, the node that user specified have an integar as its id but to instantiate a Node and be compatible with uuid we will need to convert the integar id to a string. + * @param userNodes The array of nodes that have a UserNodeType + * @param userEdges The array of edges that have a UserEdgeType + * @returns An object of sanitized userNodes and userEdges + */ +export function sanitizeUserNodesAndEdges( + userNodes: UserNodeType[], + userEdges: UserEdgeType[] +) { + convertIdToString(userNodes); + convertEdgeIdsToString(userEdges); + convertAnchorPositionsToCallbacks(userNodes, userEdges); + setDefaultEdgeType(userEdges); + return { userNodes, userEdges }; +} + +/** + * setDefaultEdgeType ensures a default edge type of 'bezier' if the user does not set one, or sets a nonsense type. + * @param userEdges The array of edges that have a UserEdgeType + * @returns No return, the function edits the objects in place + */ +function setDefaultEdgeType(userEdges) { + for (let userEdge of userEdges) { + if (!['smoothstep', 'step', 'bezier', 'straight'].includes(userEdge.type)) + userEdge.type = 'bezier'; + } +} + +/** + * convertAnchorPositionsToCallbacks + * @description + * WHY: This function is in order to maintain compliance with earlier versions of Svelvet. + * HISTORY: In Svelvet<=5, anchor points were hard-coded onto each node. Each node had a "sourcePosition" + * "targetPosition" where the edges would be attached. In Svelvet6, the store was re-designed + * from the ground up into an object-relational data model where anchor points could be attached + * at any point on the node using callbacks. This enabled features such as custom edge position, + * adaptive edge positioning, and dynamic edges. + * The purpose of this function is to parse the old way of specifying edge positions (as two source/target + * anchors on the node) into the Svelvet6 (where anchors are separate objects) in order to maintain a + * consistent user experience. However, we suggest that this functionality (parsing Svelvet5 syntax into + * Svelvet6 syntax) be removed completely in favor of only using Svelvet6 syntax in order to reduce edge cases. + */ +function convertAnchorPositionsToCallbacks( + userNodes: UserNodeType[], + userEdges: UserEdgeType[] +) { + // convert userNodes array into object for constant time lookup by id + const userNodesObj: { [key: string]: UserNodeType } = {}; + for (let userNode of userNodes) userNodesObj[userNode.id] = userNode; + + // iterate through userEdges, and check the source/target nodes. + for (let userEdge of userEdges) { + const userNodeSource = userNodesObj[userEdge.source]; + const userNodeTarget = userNodesObj[userEdge.target]; + const sourcePosition = userNodeSource.sourcePosition; + const targetPosition = userNodeTarget.targetPosition; + + const cbs = { left: leftCb, right: rightCb, top: topCb, bottom: bottomCb }; + if (sourcePosition) userEdge.sourceAnchorCb = cbs[sourcePosition]; + if (targetPosition) userEdge.targetAnchorCb = cbs[targetPosition]; + } +} + +/** + * Converts node id's to strings. For Svelvet<6, node id's were numbers. These were switched to strings for compatibility with uuid. This function does not return a new array, instead it mutates and sanitizes the original array. + * @param userNodes The array of userNodes (not yet sanitized) + */ +function convertIdToString(userNodes: UserNodeType[]) { + userNodes = userNodes.map((node) => { + node.id = node.id.toString(); + node.childNodes = + node.childNodes === undefined + ? [] + : node.childNodes.map((childId) => childId.toString()); + return node; + }); +} + +/** + * Converts source/target node id's to string. For Svelvet<6, id's were numbers. These were switched to strings for compatibility with uuid. This function does not return a new array, instead it mutates and sanitizes the original array. + * @param userEdges The array of userEdges (not yet sanitized) + */ +function convertEdgeIdsToString(userEdges: UserEdgeType[]) { + userEdges = userEdges.map((edge) => { + edge.source = edge.source.toString(); + edge.target = edge.target.toString(); + return edge; + }); +} diff --git a/frontend/src/lib/components/graph/svelvet/container/views/GraphView.svelte b/frontend/src/lib/components/graph/svelvet/container/views/GraphView.svelte new file mode 100644 index 0000000000..a2be922a3c --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/container/views/GraphView.svelte @@ -0,0 +1,370 @@ + + +{#if $edgeEditModal} + +{/if} + +
    +
    + +
    + {#each filteredNodes as node} + {#if node.data.html} + {@html node.data.html} + {:else if node.data.custom} + + node?.data?.custom?.cb?.('new', e.detail)} + on:delete={(e) => node?.data?.custom?.cb?.('delete', e.detail)} + on:select={(e) => node?.data?.custom?.cb?.('select', e.detail)} + on:insert={(e) => node?.data?.custom?.cb?.('insert', e.detail)} + on:newBranch={(e) => node?.data?.custom?.cb?.('newBranch', e.detail)} + on:deleteBranch={(e) => node?.data?.custom?.cb?.('deleteBranch', e.detail)} + {...node.data.custom.props} + /> + + {:else} + {node.data.label} + {/if} + {/each} + + + + {#each potentialAnchors as potentialAnchor} + + {/each} +
    +
    +
    + + + + + + + + + {#if $backgroundStore} + + {/if} + + + + {#each filteredEdges as edge} + {#if edge.type === 'smoothstep'} + + {:else if edge.type === 'step'} + + {:else} + + {/if} + {/each} + + {#each tempEdges as temporaryEdge} + + {/each} + + + + + + + + +
    + + +
    + + diff --git a/frontend/src/lib/components/graph/svelvet/container/views/Svelvet.svelte b/frontend/src/lib/components/graph/svelvet/container/views/Svelvet.svelte new file mode 100644 index 0000000000..ce9081b64c --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/container/views/Svelvet.svelte @@ -0,0 +1,116 @@ + + + +
    + +
    + + diff --git a/frontend/src/lib/components/graph/svelvet/customCss/controllers/getCss.ts b/frontend/src/lib/components/graph/svelvet/customCss/controllers/getCss.ts new file mode 100644 index 0000000000..784a3d1d9b --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/customCss/controllers/getCss.ts @@ -0,0 +1,62 @@ +// Required for "custom css" feature + +import type { NodeType, StoreType } from '../../store/types/types'; + +// WHAT: For a given node with a user-defined classname, see if there are any css properties for height and width +// Get that height and width and set properties in node store. This is necessary for +export const forceCssHeightAndWidth = (store: StoreType, node: NodeType) => { + let width, height, innerText; + // Look through each CSS rule to find the one the user defined + for (let i = 0; i < document.styleSheets.length; i++) { + const styleSheet = document.styleSheets[i]; + const styleRules = styleSheet.cssRules; + for (let j = 0; j < styleRules.length; j++) { + const rule = styleRules[j]; + + // this is necessary to get rid of typescript warning for rule.selectorText + if (!(rule instanceof CSSStyleRule)) continue; + + if (rule.selectorText === `.${node.className}`) { + const initialText = rule.cssText; // getting the full text of the CSS rule + const i = initialText.indexOf('{'); // finding index of first bracket + innerText = initialText.substring(i + 1, initialText.length - 1); // extracting the CSS to insert into inline style + // Adjusting the width and height if they are set via the custom class + const arr = innerText.split(' '); + arr.forEach((str, i) => { + if (str === 'width:') { + width = str.concat(arr[i + 1]); // go through the array and join width and the number + const w = parseInt(arr[i + 1]); // getting the number for the width + width = w; + } + if (str === 'height:') { + height = str.concat(arr[i + 1]); // same as with the width + const h = parseInt(arr[i + 1]); + height = h; + } + }); + } + } + } + + // update the width/height of the node + store.nodesStore.update((nodes) => { + if (width !== undefined) nodes[node.id].width = width; + if (height !== undefined) nodes[node.id].height = height; + return { ...nodes }; + }); + + // move the node a bit to force update to anchors, potential anchors + node.setPositionFromMovement(0, 0); + + // update the position of the resize node. TODO: this should be refactored so that it cascades from movement + store.resizeNodesStore.update((resizeNodes) => { + for (let resizeNode of Object.values(resizeNodes)) { + if (resizeNode.nodeId === node.id) { + // set resizeNode position to bottom left corner of Node + resizeNode.positionX = node.positionX + node.width; + resizeNode.positionY = node.positionY + node.height; + } + } + return { ...resizeNodes }; + }); +}; diff --git a/frontend/src/lib/components/graph/svelvet/d3/controllers/README.md b/frontend/src/lib/components/graph/svelvet/d3/controllers/README.md new file mode 100644 index 0000000000..fe976031d2 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/d3/controllers/README.md @@ -0,0 +1,3 @@ +d3 is responsible for zooming and panning. + +The code works but is obviously in a bad state. However, at least it is modularized so it doesn't clutter graphview anymore. diff --git a/frontend/src/lib/components/graph/svelvet/d3/controllers/d3.ts b/frontend/src/lib/components/graph/svelvet/d3/controllers/d3.ts new file mode 100644 index 0000000000..cce8f4e890 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/d3/controllers/d3.ts @@ -0,0 +1,90 @@ +// import { zoom, zoomTransform } from 'd3-zoom'; +// import { select, selectAll } from 'd3-selection'; +import { get } from 'svelte/store'; + +export function zoomInit( + d3, + canvasId, + d3Zoom, + d3Translate, + initialLocation, + initialZoom, + d3Scale +) { + //set default zoom logic + d3.select(`.Edges-${canvasId}`) + //makes sure translation is default at center coordinates + .transition() + .duration(0) + .call(d3Zoom.translateTo, 0, 0) + //moves camera to coordinates + .transition() + .duration(0) + .call( + d3Zoom.translateTo, + initialLocation.x / initialZoom, + initialLocation.y / initialZoom + ) + // zooms in on selected point + .transition() + .duration(0) + .call(d3Zoom.scaleTo, initialZoom.toFixed(2)); + // updates d3Translate with d3 object with x, y, and k values to be sent down to the minimap to be further calculated further + d3Translate = d3.zoomIdentity + .translate(initialLocation.x, initialLocation.y) + .scale(initialZoom.toFixed(2)); + d3.select(`.Nodes-${canvasId}`) + .transition() + .duration(0) + .call(d3Zoom.translateTo, 0, 0) + .transition() + .duration(0) + .call( + d3Zoom.translateTo, + initialLocation.x / initialZoom, + initialLocation.y / initialZoom + ) + .transition() + .duration(0) + .call(d3Zoom.scaleTo, initialZoom.toFixed(2)); + // sets D3 scale to current k of object + d3Scale.set(d3.zoomTransform(d3.select(`.Nodes-${canvasId}`)).k); + return d3Translate; +} +// create d3 instance conditionally based on boundary prop +export function determineD3Instance( + boundary, + d3, + nodeSelected, + width, + height, + movementStore, + backgroundStore, + gridSize, + dotSize, + canvasId, + d3Scale, + handleZoom +) { + if (boundary) { + return d3 + .zoom() + .filter(() => !get(nodeSelected)) + .scaleExtent([0.4, 4]) // limits for zooming in/out + .translateExtent([ + [0, 0], + [boundary.x, boundary.y], + ]) // world extent + .extent([ + [0, 0], + [width, height], + ]) + .on('zoom', handleZoom); + } else { + return d3 + .zoom() + .filter(() => !get(nodeSelected)) + .scaleExtent([0.4, 2]) + .on('zoom', handleZoom); + } +} diff --git a/frontend/src/lib/components/graph/svelvet/d3/controllers/d3Old.ts b/frontend/src/lib/components/graph/svelvet/d3/controllers/d3Old.ts new file mode 100644 index 0000000000..567a2ac77a --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/d3/controllers/d3Old.ts @@ -0,0 +1,58 @@ +import { writable, derived, get, readable } from 'svelte/store'; + +export function d3ZoomCreator( + nodeSelected, + movementStore, + backgroundStore, + canvasId, + gridSize, + dotSize, + d3Scale, + d3 +) { + // TODO: Update d3Zoom type (refer to d3Zoom docs) + let d3Zoom: any = d3 + .zoom() + .filter(() => !get(nodeSelected)) + .scaleExtent([0.4, 2]) + .on('zoom', handleZoom); + + return d3Zoom; + + // function to handle zoom events - arguments: d3ZoomEvent + function handleZoom(this: any, e: any): void { + if (!get(movementStore)) return; + + //add a store that contains the current value of the d3-zoom's scale to be used in onMouseMove function + d3Scale.set(e.transform.k); + // should not run d3.select below if backgroundStore is false + if (get(backgroundStore)) { + d3.select(`#background-${canvasId}`) + .attr('x', e.transform.x) + .attr('y', e.transform.y) + .attr('width', gridSize * e.transform.k) + .attr('height', gridSize * e.transform.k) + .selectAll('#dot') + .attr('x', (gridSize * e.transform.k) / 2 - dotSize / 2) + .attr('y', (gridSize * e.transform.k) / 2 - dotSize / 2) + .attr('opacity', Math.min(e.transform.k, 1)); + } + // transform 'g' SVG elements (edge, edge text, edge anchor) + d3.select(`.Edges-${canvasId} g`).attr('transform', e.transform); + // transform div elements (nodes) + let transform = d3.zoomTransform(this); + // selects and transforms all node divs from class 'Node' and performs transformation + d3.select(`.Node-${canvasId}`) + .style( + 'transform', + 'translate(' + + transform.x + + 'px,' + + transform.y + + 'px) scale(' + + transform.k + + ')' + ) + .style('transform-origin', '0 0'); + } +} diff --git a/frontend/src/lib/components/graph/svelvet/docs/CHANGELOG.md b/frontend/src/lib/components/graph/svelvet/docs/CHANGELOG.md new file mode 100644 index 0000000000..43d5b6b5f8 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/docs/CHANGELOG.md @@ -0,0 +1,145 @@ +# CHANGELOG + +This article documents the changes from Svelvet5 to Svelvet6. It is for internal use. + +## custom-nodes + +https://www.svelvet.io/docs/custom-nodes/ + +Anchor points no longer display on nodes in isolation. This is because anchor points are no longer tied to the node object. + + + + +## custom-edges + +https://www.svelvet.io/docs/custom-edges/ + +Edges now use adaptive anchors by default. Previously, source/target anchors were placed on the top/bottom of the node by default. It looks nice in the specific causes when target nodes are located below source nodes, but in the general case there will be intersecting edges. + + + + +## panning and zooming + +https://www.svelvet.io/docs/pan-and-zoom/ + +Panning and zooming is functional. Removed option to stop panning, lock nodes due to store pollution. This is simple to add back if it is a community requested feature. + +TODO: need to update this text in docs: + +``` +play around with the flow diagram below! If you wish to stop panning, set the movement prop to false. If you wish to stop node dragging, pass in the locked prop. +``` + +## usage with typescript + +https://www.svelvet.io/docs/typescript/ + +Type names changed from Node, Edge ,to UserNodeType, UserEdgeType. The main reason for this is: + +- The internal state of Svelvet is stored in objects Node, Edge which are different from the specifications passed in by users (hereafter referred to as UserNode, UserEdge). For example, UserNodes have "sourcePosition" and "targetPosition" parameters. However, the internal node project does not have "sourcePosition" and "targetPosition"; instead that functionality has been abstracted to a separate Anchor class. This promotes greater code modularity. + +## CSS-Background + +https://www.svelvet.io/docs/CSS-Background/ + + + + +No visual changes. Moved background color out of store in order to minimize store pollution. This means that background color will not be serialized using the import-export-store feature. We talk more about this later in import-export-store section. + +## node-grouping + +https://www.svelvet.io/docs/node-grouping/ + +No change in functionality. + +## snap-to-grid + +https://www.svelvet.io/docs/snap-to-grid/ +http://localhost:3000/compatability-8-snap-to-grid/ + +No change in functionality + +## html-docs + +https://www.svelvet.io/docs/snap-to-grid/ +http://localhost:3000/compatability-8-snap-to-grid/ + + + + +no change in functionality + +## node-create + +https://www.svelvet.io/docs/Interactive-Nodes/ +http://localhost:3000/compatibility-10-node-create/ + + + + +- Previously, the new node inherits from the old node. Now, the new node is created with default parameters. Note that we have functionality to edit nodes. +- edge creation works the same as before (not shown) +- there are now 4 potential anchor points, rather than one source / on target anchor point. + +## custom-svelte-components + +https://www.svelvet.io/docs/Custom-Svelte/ +http://localhost:3000/compatibility-11-custom-svelte-components/ + + + + +Same functionality as before. The reason why it looks different is because I created my own dummy Svelte component to test. + +## Minimap + +http://localhost:3000/compatibility-12-minimap/ +https://www.svelvet.io/docs/Minimap/ + +Same functionality as before. It looks like there is a big with HTML feature (unrelated to minimap) + + + + +## Initial zoom and location + +Same functionality as Svelvet5. It appears the center of the canvas is 0,0 + +## node classes + + + + +You need to put !important in the CSS + +## ImportDiagrams + +https://www.svelvet.io/docs/importDiagrams/ +http://localhost:3000/featureImportExport/ + +Feature works as expected. Note that previous version of Svelvet did not serialize callbacks (there is no general way to do this since callbacks can involve closures). We do not do serialize callbacks in Svelvet6; this includes anchors which are reset to adaptive upon serialization. + +As before, any canvas-wide parameters (such as nodeCreate, backgroundColor, etc.) will not be serialized. + +This feature is fragile since there is no guarantee that it will work with new features involving nodes and edges. In order to future-proof this feature, it would be best to specify that import/export of diagrams only serializes certain parameters. + +## Diagram Boundary + +http://localhost:3000/compatibility-15-diagramBoundary/ +https://www.svelvet.io/docs/boundary/ + +Feature works as expected + +## Iteractive Editable nodes + +http://localhost:3000/compatibility-16-nodeEdit/ +https://www.svelvet.io/docs/editNodes/ + +Feature works as expected. NodeEdit is now active by default. This is to reduce store pollution. In addition, node edit chaning width/height of nodes has been removed because this functionality is duplicated by resizableNodes + +## Deletable nodes + +This feature has been removed to reduce feature bloat. Its functionality is duplicated by Interactive Editable nodes feature. diff --git a/frontend/src/lib/components/graph/svelvet/docs/DESIGN_PATTERNS.md b/frontend/src/lib/components/graph/svelvet/docs/DESIGN_PATTERNS.md new file mode 100644 index 0000000000..c7d266125f --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/docs/DESIGN_PATTERNS.md @@ -0,0 +1,44 @@ +# Design Patterns + +Svelvet was originally written as a monolith. This increased development speed but made the code fragile. Teams struggled to implement simple features such as deleting nodes and resizing nodes. One major goal of Svelvet6 was to re-design Svelvet with more robust design patterns. This document serves as an opinionated guide towards how Svelvet should be structured. + +## Each Svelvet feature should have its own folder + +Svelvet has a lot of features that interact with each other. In order to encourage modularity, each feature should be given its own folder. For example, code related to the "resizableNodes" feature can be found in the folder `$lib/resizableNodes`. + +## Svelvet should follow an MVC Architecture + +While Svelvet is a frontend libray, it has components that interact in a complex way. As such, code should adhere to an MVC architecture to increase modularity. One useful way to think about MVC is drawing an analogy to frontend/backend/database. The frontend is the "view" of MVC, the backend is the "controller" of MVC, and the database is the "model" of MVC. To that end, within each feature folder there should be four folders: models, views, controllers, types. + +- models: holds code related to the internal state of Svelvet +- controllers: holds code used to interact with the Svelvet models. Ideally, all interaction with Svelvet models/stores should take place through controllers. +- views: holds code used to visualize the Svelvet state. Ideally, views should not modify models directly. +- types: holds types/interfaces for Typescript. This is unrelated to MVC. + +More comments: Explicitly labeling folders as model/view/controller increases verbosity and most projects do not do this. We feel that this increased verbosity is worth the tradeoff of reminding developers they should be following establshed design patterns when coding. If you are considering removing explicit model/view/controller folders, consider that Svelvet is an OSP where developers may have little to no prior coding experience; increased verbosity may be helpful in guiding developers towards established design principles. + +## Svelvet's internal state should be an object-relational data structure + +Too Long Didn't Read: The main takeaway can be summed up as: make the Svelvet store look more like PostgreSQL and less like mongoDB. + +### A longer explanation + +The store holds Svelvet's internal state. We urge future developers to structure the store as a relational object rather than an unstructured object. To give an analogy, if Svelvet was a full-stack app with a backend and database, you should use a postgreSQL instead of mongoDB to store the internal state of Svelvet because nodes/edges are inherently relational. We give an example of a bad design pattern and a good design pattern below. + +Suppose you want to implement a "resizableNodes" feature, where users can resize nodes by dragging a node corner. One (bad) way to do this is by could do this by hacking in an extra div on the Node component representing a draggable control point, then hacking in a "resizeNode" method on the Node object so that when the control point is dragged the node is resized. While it may be easier to throw everything on an unstructured Node object, this is bad for modularity. As more and more features get added in, the Node object becomes bloated, difficult to read, and difficult to debug. + +The better way to do this is to create a brand new resizableNodes model. This model should hold `nodeId` (a foreign key to a node object), `positionX` (its x-position), and `positionY` (its y-position). This model should also have a method `setPosition` that sets its x,y position, but also sets the width/height of the associated node defined by `nodeId`. Note the similarity of the process described above to adding extra data to a SQL database; a big advantage of SQL is that it is easy to add new relational data by creating a brand new table and linking with a foreign key. + +By creating new objects/tables whenever adding new features, you make the code more readable, more modular, and more testable. + +### Foreign keys + +One question you may come up with when adding new tables is how to structure foreign keys. In our resizableNodes example, we placed a foreign key `nodeId` on our ResizableNode object/table. Alternatively, we could have placed a foreign key `ResizableNodeId` on our Node object/table. How do we choose between these two alternatives (or maybe we could even do two foreign keys)? + +You can make the decision on foreign keys based on your component heirarchy. A Node can exist without functionality to resize itself, but a ResizableNode should not exist if its parent Node does not exist. Therefore, you should place a `nodeId` foreign key on ResizableNode. + +This decision has the following advantages: + +- Increased readability: When developers are reading the Node class definition, they are not overwhelmed by all the different Svelvet features. On the other hand, when developers are reading the ResizableNode class definition, they should realize that ResizableNodes are children of Nodes. +- Increased modularity: You can remove a ResizableNode without disturbing core Node functionality. +- Easy deletes: Previous teams struggled with implementing delete functionality. When you think about a SQL database, deleting rows is very simple. You simply delete the row, then specify cascade to delete other rows that reference the primary key of the row you deleted. Keeping a disciplined approach when structuring foreign keys makes the entity hierarchies clear, and makes operations such as delete easy to implement. diff --git a/frontend/src/lib/components/graph/svelvet/docs/DOCUMENTATION.md b/frontend/src/lib/components/graph/svelvet/docs/DOCUMENTATION.md new file mode 100644 index 0000000000..0a30d726e3 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/docs/DOCUMENTATION.md @@ -0,0 +1,5 @@ +# Documentation + +- Documentation should be written assuming the developer working on Svelvet has coding experience equivalent to six weeks of bootcamp. +- If you write documents in tsDoc format, you can use TypeDoc to generate documentation automatically. For instructions on how to use TypeDoc, see Tutorials.md +- Write READMEs for every feature so that future teams can understand how they work. Put your email down if you want to be a resource for future teams. diff --git a/frontend/src/lib/components/graph/svelvet/docs/README.md b/frontend/src/lib/components/graph/svelvet/docs/README.md new file mode 100644 index 0000000000..71f6258cab --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/docs/README.md @@ -0,0 +1,34 @@ +# README + +This README provides suggestions to developers working on Svelvet. + +## What is Svelvet? + +Svelvet is a frontend library that allows users to programmatically create graph diagrams. Graphs are composed of nodes and edges; each edge connects two nodes. There are two main challenges when working with Svelvet: (1) nodes and edges interact in complex ways, making new features difficult to implement without interfering with old features, and (2) Svelvet has an active userbase, making breaking changes undesirable. + +## Things to think about as a Svelvet developer + +- Svelvet teams have 3.5 weeks to iterate on the project, less if you consider time spent on marketing/deployment. It is important for code to be readable, otherwise future teams will be unable to understand the codebase within a reasonable timeframe. +- It is important to write documentation that is easy understand. Write comments/documentation assuming that developers have ~6 weeks of prior bootcamp experience. +- Writing non-modular code with zero tests and zero documentation increases technical debt and puts future teams in a bad place. Accumulated technical debt can kill projects. +- Svelvet has an active userbase. When possible, breaking changes should be avoided. However, if a breaking change must occur, it is better that it happen sooner rather than later. + +## Suggestions + +- Write modular code, separated by feature. For suggestions, see `./DESIGN_PATTERNS.md` + +- Write tests. Svelvet components interact with each other in complex ways, making it difficult to predict whether changes will break Svelvet without tests. + +- Writing tests and documentation is good for your resume. A long list of features by itself makes for poor resume; mentioning testing, documentation, and specific technologies used to implement specific features make for a stronger resume. + +- Don't leave typescript warnings unaddressed. This makes it so much easier to debug. + +## Where to start + +Here is one way to start understanding the Svelvet codebase + +(1) Read the Node class (`$lib/nodes/models/Node.ts`) +(2) Create a new branch, delete all features except for nodes, containers, and store, then try to get Svelvet to running only rendering nodes to the screen. You can test Svelvet using routes such as `testingplayground` at `http://localhost:3000/testingplayground`. +(3) Try to refactor Node.ts. You may notice that Node.ts has 16 fields, when really only six of them are important (id, canvasId, positionX, positionY, widthX, widthY). Create a new table `NodeAttributes` that links to Node via foreign key, move all attributes (bgColor, textColor, etc) to this new table and get Node rendering again. +(4) After understanding how Node works, add back the "edges" folder. Try to get Svelvet working rendering only nodes and edges to the screen. +(5) Node / Edge / Anchor form the core tables of Svelvet. All other feature build on top of these core tables. diff --git a/frontend/src/lib/components/graph/svelvet/docs/TODO.md b/frontend/src/lib/components/graph/svelvet/docs/TODO.md new file mode 100644 index 0000000000..328a4b6ff9 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/docs/TODO.md @@ -0,0 +1,14 @@ +## custom node functionality should be refactored into its own table.'' + +## tay10alan60@gmail.com - minimap, d3, node deletion, interactiveNodes + +## dillan - customSvelete components, deletable nodes, node classes + +## Minimap 75 boundless, 200 bounded + +## New team: + +- split up the website and the svelvet npm package +- continue store refactoring +- refactor store dispatch into flux architecture +- testing - 1 full iteration diff --git a/frontend/src/lib/components/graph/svelvet/docs/Tutorials.md b/frontend/src/lib/components/graph/svelvet/docs/Tutorials.md new file mode 100644 index 0000000000..1f7c029d27 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/docs/Tutorials.md @@ -0,0 +1,25 @@ +# Tutorials + +This file contains instructions on how to do useful things such as generating developer documentation, publishing to npm, etc. + +## TypeDoc + +You may notice TSDoc comments throughout our code. These TSDoc comments can be converted into documentation using TypeDoc: + +``` +npx typedoc --entryPointStrategy expand src/lib +``` + +This command will create documentation in root folder `./docs`. + +## Publishing to npm + +- create an account on npm.js. You can skip this step if you already have an account +- log in with `$ npm login` +- Within the `src/lib` directory, type `npm version patch` to increment version number. Or if you want a new name, you can modify `src/lib/package.json` directly +- In the base directory, type `npm run package`. This will use svelte-kit's package feature to create an npm package in `./package`. +- Within the `./package` directory, type `npm publish` to publish to npm. Note that you cannot "overwrite" previous publishes, you must increment the version number + +## Testing npm package + +- install locally with `npm install svelvet-lime@latest -f`, where svelvet-lime is replaced with whatever you named your package. Note that if you have a previously installed version of svelvet, you must force a re-install otherwise you will be using an outdated npm package. diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/css-background-after.png b/frontend/src/lib/components/graph/svelvet/docs/images/css-background-after.png new file mode 100644 index 0000000000..68c40c5881 Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/css-background-after.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/css-background-before.png b/frontend/src/lib/components/graph/svelvet/docs/images/css-background-before.png new file mode 100644 index 0000000000..c7f37de68f Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/css-background-before.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/custom-edges-after.png b/frontend/src/lib/components/graph/svelvet/docs/images/custom-edges-after.png new file mode 100644 index 0000000000..b8267dce7a Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/custom-edges-after.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/custom-edges-before.png b/frontend/src/lib/components/graph/svelvet/docs/images/custom-edges-before.png new file mode 100644 index 0000000000..a7466daa35 Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/custom-edges-before.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/custom-nodes-after.png b/frontend/src/lib/components/graph/svelvet/docs/images/custom-nodes-after.png new file mode 100644 index 0000000000..cc7a80074d Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/custom-nodes-after.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/custom-nodes-before.png b/frontend/src/lib/components/graph/svelvet/docs/images/custom-nodes-before.png new file mode 100644 index 0000000000..c6e37ae783 Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/custom-nodes-before.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/custom-svelte-components-after.png b/frontend/src/lib/components/graph/svelvet/docs/images/custom-svelte-components-after.png new file mode 100644 index 0000000000..c81f5014f0 Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/custom-svelte-components-after.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/custom-svelte-components-before.png b/frontend/src/lib/components/graph/svelvet/docs/images/custom-svelte-components-before.png new file mode 100644 index 0000000000..f0026b36a8 Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/custom-svelte-components-before.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/html-docs-after.png b/frontend/src/lib/components/graph/svelvet/docs/images/html-docs-after.png new file mode 100644 index 0000000000..37380b30ee Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/html-docs-after.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/html-docs-before.png b/frontend/src/lib/components/graph/svelvet/docs/images/html-docs-before.png new file mode 100644 index 0000000000..bafc046b64 Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/html-docs-before.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/minimap-after.png b/frontend/src/lib/components/graph/svelvet/docs/images/minimap-after.png new file mode 100644 index 0000000000..e0dda0b5d5 Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/minimap-after.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/minimap-before.png b/frontend/src/lib/components/graph/svelvet/docs/images/minimap-before.png new file mode 100644 index 0000000000..00e5322bdd Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/minimap-before.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/node-classes-after.png b/frontend/src/lib/components/graph/svelvet/docs/images/node-classes-after.png new file mode 100644 index 0000000000..b303012849 Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/node-classes-after.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/node-classes-before.png b/frontend/src/lib/components/graph/svelvet/docs/images/node-classes-before.png new file mode 100644 index 0000000000..606695e2d6 Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/node-classes-before.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/node-create-after.png b/frontend/src/lib/components/graph/svelvet/docs/images/node-create-after.png new file mode 100644 index 0000000000..052f1d6461 Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/node-create-after.png differ diff --git a/frontend/src/lib/components/graph/svelvet/docs/images/node-create-before.png b/frontend/src/lib/components/graph/svelvet/docs/images/node-create-before.png new file mode 100644 index 0000000000..dcff6fe63b Binary files /dev/null and b/frontend/src/lib/components/graph/svelvet/docs/images/node-create-before.png differ diff --git a/frontend/src/lib/components/graph/svelvet/edges/controllers/anchorCbDev.ts b/frontend/src/lib/components/graph/svelvet/edges/controllers/anchorCbDev.ts new file mode 100644 index 0000000000..82c531e8f2 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/controllers/anchorCbDev.ts @@ -0,0 +1,170 @@ +import { rightCb, leftCb, topCb, bottomCb } from './anchorCbUser'; // these are callbacks used to calculate anchor position relative to node +import type { AnchorCbType } from '../../edges/types/types'; +import type { StoreType } from '../../store/types/types'; + +import { getPotentialAnchorById } from '../../interactiveNodes/controllers/util'; + +import { getAnchors } from './util'; +import { getNodeById } from '../../nodes/controllers/util'; +export function fixedCbCreator( + store: StoreType, + edgeId: string, + anchorId: string, + userNodeId: string, + positionCb: Function // positionCb should be a function that takes 4 arguments (x,y,width,height) and returns a 3-array [x,y,angle] that represents the x,y position of the anchor as well as it's angle with respect to it's node. +) { + const rn = fixedCb; + rn.type = 'fixed'; + return rn; + + function fixedCb() { + // get the two anchors + const anchors = getAnchors(store, { edgeId: edgeId }); + if (anchors.length !== 2) + throw `there should be two anchors per edge, have: ${anchors.length}`; + let [anchorSelf, anchorOther] = anchors; + if (anchorSelf.id !== anchorId) + [anchorSelf, anchorOther] = [anchorOther, anchorSelf]; + + const node = getNodeById(store, userNodeId); + const { positionX, positionY, width, height } = node; + const [x, y, angle] = positionCb(positionX, positionY, width, height); + anchorSelf.positionX = x; + anchorSelf.positionY = y; + anchorSelf.angle = angle; + // update the other anchor if it is a dynamic anchor + // Note dyanamic anchor callbacks have a check that prevents an infinite loop + if (anchorOther.callback.type === 'dynamic') anchorOther.callback(); + } +} + +export function dynamicCbCreator( + store: StoreType, + edgeId: string, + anchorId: string +) { + const rn = dynamicCb; + rn.type = 'dynamic'; + return rn; + + function dynamicCb() { + // get the two anchors + const anchors = getAnchors(store, { edgeId: edgeId }); + if (anchors.length !== 2) + throw `there should be two anchors per edge, have: ${anchors.length}`; + + let [anchorSelf, anchorOther] = anchors; + if (anchorSelf.id !== anchorId) + [anchorSelf, anchorOther] = [anchorOther, anchorSelf]; + // get the two nodes + const nodeSelf = getNodeById(store, anchorSelf.nodeId); + const nodeOther = getNodeById(store, anchorOther.nodeId); + // get the midpoints + const [xSelf, ySelf, xOther, yOther] = [ + nodeSelf.positionX + nodeSelf.width / 2, + nodeSelf.positionY + nodeSelf.height / 2, + nodeOther.positionX + nodeOther.width / 2, + nodeOther.positionY + nodeOther.height / 2, + ]; + + // record angle for later. We use this so we don't have an infinite loop + let prevAngle = anchorSelf.angle; + + // calculate the slope + const slope = (ySelf - yOther) / (xSelf - xOther); + // slope<1 means -45 to 45 degrees so left/right anchors + if (Math.abs(slope) < 1) { + // self node is on the left, other node is on the right + if (nodeSelf.positionX < nodeOther.positionX) { + const [selfX, selfY] = rightCb( + nodeSelf.positionX, + nodeSelf.positionY, + nodeSelf.width, + nodeSelf.height + ); + const [otherX, otherY] = leftCb( + nodeOther.positionX, + nodeOther.positionY, + nodeOther.width, + nodeOther.height + ); + anchorSelf.setPosition(selfX, selfY); + anchorSelf.angle = 0; // if the self node is on the left, the anchor should have orientation of 0 degrees on the unit circle + } else { + // in this case, the self node is on the right and the other node is on the left + const [selfX, selfY] = leftCb( + nodeSelf.positionX, + nodeSelf.positionY, + nodeSelf.width, + nodeSelf.height + ); + const [otherX, otherY] = rightCb( + nodeOther.positionX, + nodeOther.positionY, + nodeOther.width, + nodeOther.height + ); + anchorSelf.setPosition(selfX, selfY); + anchorSelf.angle = 180; + } + } else { + if (nodeSelf.positionY < nodeOther.positionY) { + // here the self node is above the other node + const [selfX, selfY] = bottomCb( + nodeSelf.positionX, + nodeSelf.positionY, + nodeSelf.width, + nodeSelf.height + ); + const [otherX, otherY] = topCb( + nodeOther.positionX, + nodeOther.positionY, + nodeOther.width, + nodeOther.height + ); + anchorSelf.setPosition(selfX, selfY); + anchorSelf.angle = 270; + } else { + const [selfX, selfY] = topCb( + nodeSelf.positionX, + nodeSelf.positionY, + nodeSelf.width, + nodeSelf.height + ); + const [otherX, otherY] = bottomCb( + nodeOther.positionX, + nodeOther.positionY, + nodeOther.width, + nodeOther.height + ); + anchorSelf.setPosition(selfX, selfY); + anchorSelf.angle = 90; + } + } + + // if the anchor changed position, then do operation for other anchor + // otherwise, don't do anything. This check is so we don't have an infinite loop + if (prevAngle !== anchorSelf.angle) anchorOther.callback(); + } +} + +export function potentialAnchorCbCreator( + store: StoreType, + potentialAnchorId: string, + userNodeId: string, + positionCb: Function // positionCb should be a function that takes 4 arguments (x,y,width,height) and returns a 3-array [x,y,angle] that represents the x,y position of the anchor as well as it's angle with respect to it's node. +) { + return fixedCb; + + function fixedCb() { + // get the two anchors + const potentialAnchor = getPotentialAnchorById(store, potentialAnchorId); + const node = getNodeById(store, userNodeId); + const { positionX, positionY, width, height } = node; + const [x, y, angle] = positionCb(positionX, positionY, width, height); + potentialAnchor.positionX = x; + potentialAnchor.positionY = y; + potentialAnchor.angle = angle; + // potential anchors don't have partners so we can end here + } +} diff --git a/frontend/src/lib/components/graph/svelvet/edges/controllers/anchorCbUser.ts b/frontend/src/lib/components/graph/svelvet/edges/controllers/anchorCbUser.ts new file mode 100644 index 0000000000..69e4d86bcd --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/controllers/anchorCbUser.ts @@ -0,0 +1,98 @@ +/** + * These are callbacks used to define anchor positions relative to the node they are attached to. + * These may be provided to developers as examples of how to write their own custom callbacks for adjustable anchors + * It calculates the position of an anchor (x,y) coordinates given a node parameterized by (x,y,width, height) + */ + +/** + * @function rightCb - This is a callback function to define the anchor position on the node to be on the right side of the node. + * @param xNode - positionX of the attached node + * @param yNode - positionY of the attached node + * @param widthNode - width of the attached node + * @param heightNode - height of the attached node + * @returns [xAnchor, yAnchor, 0] + * xAnchor - positionX for the anchor + * yAnchor - positionY for the anchor + * 0 - this is angle of the anchor with respect to the node. The right anchor should fall at 0 degrees on the unit circle. + * @export rightCb + */ +export const rightCb = ( + xNode: number, + yNode: number, + widthNode: number, + heightNode: number +) => { + const xAnchor = xNode + widthNode; + const yAnchor = yNode + heightNode / 2; + return [xAnchor, yAnchor, 0]; +}; + +/** + * @function leftCb - This is a callback function to define the anchor position on the node to be on the left side of the node. + * @param xNode - positionX of the attached node + * @param yNode - positionY of the attached node + * @param widthNode - width of the attached node + * @param heightNode - height of the attached node + * @returns [xAnchor, yAnchor, 180] + * xAnchor - positionX for the anchor + * yAnchor - positionY for the anchor + * 180 - this is angle of the anchor with respect to the node. The left anchor should fall at 180 degrees on the unit circle. + * @export leftCb + */ +export const leftCb = ( + xNode: number, + yNode: number, + widthNode: number, + heightNode: number +) => { + const xAnchor = xNode; + const yAnchor = yNode + heightNode / 2; + return [xAnchor, yAnchor, 180]; +}; + +/** + * @function topCb - This is a callback function to define the anchor position on the node to be on the top of the node. + * @param xNode - positionX of the attached node + * @param yNode - positionY of the attached node + * @param widthNode - width of the attached node + * @param heightNode - height of the attached node + * @returns [xAnchor, yAnchor, 90] + * xAnchor - positionX for the anchor + * yAnchor - positionY for the anchor + * 90 - this is angle of the anchor with respect to the node. The top anchor should fall at 90 degrees on the unit circle. + * @export topCb + */ + +export const topCb = ( + xNode: number, + yNode: number, + widthNode: number, + heightNode: number +) => { + const xAnchor = xNode + widthNode / 2; + const yAnchor = yNode; + return [xAnchor, yAnchor, 90]; +}; + +/** + * @function bottomCb - This is a callback function to define the anchor position on the node to be on the bottom of the node. + * @param xNode - positionX of the attached node + * @param yNode - positionY of the attached node + * @param widthNode - width of the attached node + * @param heightNode - height of the attached node + * @returns - [xAnchor, yAnchor, 90] + * xAnchor - positionX for the anchor + * yAnchor - positionY for the anchor + * 270 - this is angle of the anchor with respect to the node. The bottom anchor should fall at 270 degrees on the unit circle. + * @export bottomCb + */ +export const bottomCb = ( + xNode: number, + yNode: number, + widthNode: number, + heightNode: number +) => { + const xAnchor = xNode + widthNode / 2; + const yAnchor = yNode + heightNode; + return [xAnchor, yAnchor, 270]; +}; diff --git a/frontend/src/lib/components/graph/svelvet/edges/controllers/util.ts b/frontend/src/lib/components/graph/svelvet/edges/controllers/util.ts new file mode 100644 index 0000000000..4802e155a1 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/controllers/util.ts @@ -0,0 +1,82 @@ +import type { StoreType } from '../../store/types/types'; +import { writable, derived, get, readable } from 'svelte/store'; +import type { AnchorType } from '../types/types'; +import { getNodeById } from '../../nodes/controllers/util'; + +/** + * Finds all Anchors that matches the conditions specified in the filter parameter from a Svelvet store and returns these Anchors in an array. + * + * @param store The Svelvet store containing the state of a Svelvet component + * @param filter An object to specify conditions. Example: if filter = \{ sourceOrTarget: 'source', positionX: 35 \} then we will return all anchors with sourceOrTarget = source AND poxitionX = 35 + * @returns An array of Anchors that matches the conditions specified in the filter parameter + */ +export function getAnchors(store: StoreType, filter?: { [key: string]: any }) { + let anchors = Object.values(get(store.anchorsStore)); + // filter the array of anchors for elements that match filter + // Example: if filter = {sourceOrTarget: 'source', positionX: 35} then we will + //return all anchors with sourceOrTarget = source AND poxitionX = 35 + if (filter !== undefined) { + anchors = anchors.filter((anchor) => { + for (let filterKey in filter) { + const filterValue = filter[filterKey]; + if (anchor[filterKey as keyof AnchorType] !== filterValue) return false; + } + return true; + }); + } + // return list of anchors + return anchors; +} + +/** + * Gets one anchor (source anchor or target anchor) from a given edge + * + * @param store The Svelvet store containing the state of the Svelvet component + * @param edgeId The id of a given edge + * @param sourceOrTarget A string of 'source' or 'target' to specify which anchor the function should return + * @returns The source or target Anchor object of a given edge + */ +export function getAnchorFromEdge( + store: StoreType, + edgeId: string, + sourceOrTarget: 'source' | 'target' +): AnchorType { + const edge = getEdgeById(store, edgeId); + const anchors = getAnchors(store, { edgeId: edgeId }); + if (anchors.length !== 2) + throw `there should be two anchors for a given edge, there are ${anchors.length}`; + // there should be one source anchor and one target anchor. Return the source anchor + const anchor = anchors.filter( + (anchor) => anchor.sourceOrTarget === sourceOrTarget + ); + if (anchor.length !== 1) + throw `there should only be one source/target anchor`; + return anchor[0]; +} + +/** + * getEdgeById will look for the targeted Edge that has the same id provided in the Svelvet component store. + * + * @param store The Svelvet store containing the state of a Svelvet component + * @param id The id of the targeted Node + * @returns The targeted Edge object in store.edgesStore + */ +export function getEdgeById(store: StoreType, id: string) { + const edgesStore = get(store.edgesStore); + const edge = edgesStore[id]; + if (edge === undefined) throw 'edge not found'; + return edge; +} + +/** + * getAnchorById will look for the targeted Anchor that has the same id in the Svelvet component store. + * + * @param store The Svelvet store containing the state of a Svelvet component + * @param id The id of the targeted Anchor + * @returns The target Anchor object in store.anchorsStore + */ +export function getAnchorById(store: StoreType, id: string) { + const anchorsStore = get(store.anchorsStore); + const anchor = anchorsStore[id]; + return anchor; +} diff --git a/frontend/src/lib/components/graph/svelvet/edges/models/Anchor.ts b/frontend/src/lib/components/graph/svelvet/edges/models/Anchor.ts new file mode 100644 index 0000000000..daa9b25b51 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/models/Anchor.ts @@ -0,0 +1,119 @@ +/** + * This is where we create, update the Anchor store. + */ + +import type { AnchorCbType, AnchorType } from '../../edges/types/types'; +import { stores } from '../../store/models/store'; +import { getAnchors } from '../controllers/util'; + +/** Class representing an Anchor that implements Anchortype. + * @param {string} id The id of the Anchor + * @param {string} nodeId The id of the Node which the instantiated Anchor will be attached to + * @param {string} edgeId The id of the Edge which connects to the instantiated Anchor + * @param {'source' | 'target'} sourceOrTarget Specify the Anchor is a source or target + * @param {number} positionX The 'X' coordinate of the Anchor + * @param {number} positionY The 'Y' coordinate of the Anchor + * @param {function} callback The callback function that will determine the position of this Anchor + * @param {string} canvasId The canvasId of the Svelvet component that will hold this Anchor + * @param { number } angle This is the orientation of the anchor and is used to make sure bezier/step curves are rendered perpendicular to the node. Angles are defined along the unit circle. EX: 0 = right side of node, 180 = left side of node. + */ +export class Anchor implements AnchorType { + constructor( + public id: string, + public nodeId: string, + public edgeId: string, + public sourceOrTarget: 'source' | 'target', + public positionX: number, + public positionY: number, + public callback: AnchorCbType, + public canvasId: string, + public angle: 0 | 90 | 180 | 270 + ) {} + + getOtherAnchorId() { + const store = stores[this.canvasId]; + const anchors = getAnchors(store, { edgeId: this.edgeId }); + if (anchors.length !== 2) + throw 'something is wrong, every anchor should have exactly one other associated anchor'; + const anchor = anchors.filter((anchor) => anchor.id !== this.id)[0]; + return anchor.id; + } + + /** + * setPositionFromNode will invoke the user-defined callback to calculate the position of the Anchor, set the position of the Anchor in the anchorsStore, and also update the Edge position accordingly. + */ + setPositionFromNode() { + // calculate the new position of the anchor using user-defined callback + this.callback(); + const { edgesStore } = stores[this.canvasId]; + // update edges + edgesStore.update((edges) => { + const edge = edges[this.edgeId]; + if (this.sourceOrTarget === 'source') { + edge.sourceX = this.positionX; + edge.sourceY = this.positionY; + } else { + edge.targetX = this.positionX; + edge.targetY = this.positionY; + } + return { ...edges }; + }); + } + /** + * updateEdges will update the edgesStore based on Anchor's change. + */ + updateEdges() { + const { edgesStore } = stores[this.canvasId]; + /** update edges by deconstructing edges store and setting its new vlue to stores[this.canvasID] */ + + edgesStore.update((edges) => { + const edge = edges[this.edgeId]; + // this means that no edge was found, just return without doing anything + + if (edge === undefined) { + return { ...edges }; + } + if (this.sourceOrTarget === 'source') { + edge.sourceX = this.positionX; + edge.sourceY = this.positionY; + } else { + edge.targetX = this.positionX; + edge.targetY = this.positionY; + } + return { ...edges }; + }); + } + + /** + * setPosition will update the positionX and positionY of the Anchor and also cascade changes to related Edge. + * @param x The X coordinate of the new position for the Anchor + * @param y The Y coordinate of the new position for the Anchor + */ + setPosition(x: number, y: number) { + this.positionX = x; + this.positionY = y; + this.updateEdges(); + } + + /** + * Anchor.setPositionFromMovement works similarly to Anchor.setPosition. But setPosition is more powerful and we recommend using setPosition whenever possible and in the future, setPositionFromMovement can be removed. + * @param movementX The mouse movement value on the X-axis + * @param movementY The mouse movement value on the Y-axis + */ + setPositionFromMovement(movementX: number, movementY: number) { + this.positionX += movementX; + this.positionY += movementY; + const { edgesStore } = stores[this.canvasId]; + edgesStore.update((edges) => { + const edge = edges[this.edgeId]; + if (this.sourceOrTarget === 'source') { + edge.sourceX += movementX; + edge.sourceY += movementY; + } else { + edge.targetX += movementX; + edge.targetY += movementY; + } + return { ...edges }; + }); + } +} diff --git a/frontend/src/lib/components/graph/svelvet/edges/models/Edge.ts b/frontend/src/lib/components/graph/svelvet/edges/models/Edge.ts new file mode 100644 index 0000000000..de1fdef8b7 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/models/Edge.ts @@ -0,0 +1,97 @@ +import { findStore } from '../../store/controllers/storeApi'; +import type { UserEdgeType } from '../../types/types'; +import type { EdgeType } from '../../store/types/types'; + +import { stores } from '../../store/models/store'; +import { getAnchors, getAnchorFromEdge } from '../../edges/controllers/util'; +/** + * Class Edge that implements EdgeType. + * @param id The id of the Edge + * @param sourceX The X coordinate of the source Anchor + * @param sourceY The Y coordinate of the source Anchor + * @param targetX The X coordinate of the target Anchor + * @param targetY The Y coordinate of the target Anchor + * @param canvasId The canvasId of the Svelvet component that holds the instantiated Edge + * @param label The label of the Edge + * @param type The type of the Edge (options: 'straight', 'smoothstep', 'step', or 'bezier'). If user doesn't specify, the type will default to 'bezier'. + * @param labelBgColor The background color of the Edge label + * @param labelTextColor The text color of the Edge label + * @param edgeColor The color of the Edge + * @param animate Boolean value to specify whether the Edge should be animated + * @param noHandle Boolean value but looks like it is already depracated and can be removed without damage + * @param arraw Boolean value to specify whether the Edge displays an arrow near its target Anchor + */ +export class Edge implements EdgeType { + constructor( + public id: string, + public sourceX: number, + public sourceY: number, + public targetX: number, + public targetY: number, + public canvasId: string, + public label: string, + public type: 'straight' | 'smoothstep' | 'step' | 'bezier', + public labelBgColor: string, + public labelTextColor: string, + public edgeColor: string, + public animate: boolean, + public noHandle: boolean, + public arrow: boolean, + public clickCallback: Function, + public className: string + ) {} + + /** + * delete is going to delete the Edge and also delete associated Anchors + */ + delete() { + const store = stores[this.canvasId]; + const { nodesStore, anchorsStore, edgesStore } = store; + const sourceAnchor = getAnchorFromEdge(store, this.id, 'source'); // this is a bit wasteful + const targetAnchor = getAnchorFromEdge(store, this.id, 'target'); + anchorsStore.update((anchors) => { + for (const anchorId in anchors) { + if (anchorId === sourceAnchor.id || anchorId == targetAnchor.id) + delete anchors[anchorId]; + } + return { ...anchors }; + }); + edgesStore.update((edges) => { + delete edges[this.id]; + return { ...edges }; + }); + } + + /** + * setExportableData will construct an object that holds all the edge data that can be exported. This is needed for the Exporting Diagram feature. + * @returns The object of exportable edge data. The format of the object should be as close as what user initially passes in to Svelvet. + */ + setExportableData() { + const exportableData: UserEdgeType = { + id: this.id, + label: this.label, + type: this.type, + labelBgColor: this.labelBgColor, + labelTextColor: this.labelTextColor, + edgeColor: this.edgeColor, + animate: this.animate, + noHandle: this.noHandle, + arrow: this.arrow, + source: 'dummy', // these will be set later + target: 'dummy', // these will be set later + }; + + // set source, target on exportableData + const store = findStore(this.canvasId); + const anchors = getAnchors(store, { edgeId: this.id }); + if (anchors.length !== 2) throw 'there should be two anchors per edge'; + for (const anchor of anchors) { + if (anchor.sourceOrTarget === 'target') + exportableData.target = anchor.nodeId; + if (anchor.sourceOrTarget === 'source') + exportableData.source = anchor.nodeId; + } + + return exportableData; + } +} diff --git a/frontend/src/lib/components/graph/svelvet/edges/types/types.ts b/frontend/src/lib/components/graph/svelvet/edges/types/types.ts new file mode 100644 index 0000000000..57917fc098 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/types/types.ts @@ -0,0 +1,19 @@ +export type AnchorCbType = { + (): void; + type: 'dynamic' | 'fixed'; +}; + +export interface AnchorType { + id: string; // note that the user never specifies an anchor and they are generated dynamically. id will be a random string. + nodeId: string; + edgeId: string; + sourceOrTarget: 'source' | 'target'; + positionX: number; + positionY: number; + callback: AnchorCbType; // callback is used to calculate positionX, positionY based on parent node's data, and set the anchor position // TODO: rename to something better + angle: number; + setPositionFromNode: Function; + setPosition: Function; + updateEdges: Function; + getOtherAnchorId: Function; +} diff --git a/frontend/src/lib/components/graph/svelvet/edges/views/Edges/BaseEdge.svelte b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/BaseEdge.svelte new file mode 100644 index 0000000000..372a63d275 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/BaseEdge.svelte @@ -0,0 +1,109 @@ + + + + + + + + + +{#if highlightEdgesOption} + {}} + /> +{/if} + +{#if arrow} + +{:else} + +{/if} + +{#if edgeTextProps.label} + +{/if} + + diff --git a/frontend/src/lib/components/graph/svelvet/edges/views/Edges/EdgeAnchor.svelte b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/EdgeAnchor.svelte new file mode 100644 index 0000000000..4e64c945fc --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/EdgeAnchor.svelte @@ -0,0 +1,14 @@ + + + + + + + diff --git a/frontend/src/lib/components/graph/svelvet/edges/views/Edges/EdgeText.svelte b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/EdgeText.svelte new file mode 100644 index 0000000000..1630bf4df8 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/EdgeText.svelte @@ -0,0 +1,49 @@ + + +{#if typeof label === 'undefined' || !label} + {null} +{:else} + + + + {label} + + +{/if} diff --git a/frontend/src/lib/components/graph/svelvet/edges/views/Edges/SimpleBezierEdge.svelte b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/SimpleBezierEdge.svelte new file mode 100644 index 0000000000..6293bf31f9 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/SimpleBezierEdge.svelte @@ -0,0 +1,159 @@ + + + diff --git a/frontend/src/lib/components/graph/svelvet/edges/views/Edges/SmoothStepEdge.svelte b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/SmoothStepEdge.svelte new file mode 100644 index 0000000000..f9bd3f6fb6 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/SmoothStepEdge.svelte @@ -0,0 +1,176 @@ + + + diff --git a/frontend/src/lib/components/graph/svelvet/edges/views/Edges/StepEdge.svelte b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/StepEdge.svelte new file mode 100644 index 0000000000..0e192fcd5f --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/StepEdge.svelte @@ -0,0 +1,8 @@ + + + + diff --git a/frontend/src/lib/components/graph/svelvet/edges/views/Edges/types.ts b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/types.ts new file mode 100644 index 0000000000..48a97a8582 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/types.ts @@ -0,0 +1,58 @@ +import type { XYPosition, Position } from './utils'; + +export interface Node { + id: number; + position: XYPosition; + data: T; + width: number; + height: number; + bgColor?: string; + fontSize?: number; + borderColor?: string; + borderRadius?: number; + textColor?: string; + clickCallback?: Function; + image?: boolean; + src?: string; + sourcePosition?: 'left' | 'right' | 'top' | 'bottom'; + targetPosition?: 'left' | 'right' | 'top' | 'bottom'; +} + +export interface Edge { + id: string; + source: number; + target: number; + label?: string; + labelBgColor?: string; + labelTextColor?: string; + edgeColor?: string; + type?: string; + animate?: boolean; + noHandle?: boolean; + arrow?: boolean; +} + +export interface DerivedEdge extends Edge { + sourceX: number; + sourceY: number; + sourcePosition: Position; + targetX: number; + targetY: number; + targetPosition: Position; +} + +export interface EdgeProps extends DerivedEdge { + path: string; + centerX: number; + centerY: number; +} + +export interface EdgeTextProps { + label?: any; + labelBgColor?: string; + labelTextColor?: string; + centerX: number; + centerY: number; +} + +export type HandleType = 'source' | 'target'; diff --git a/frontend/src/lib/components/graph/svelvet/edges/views/Edges/utils.ts b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/utils.ts new file mode 100644 index 0000000000..8685e6e3e8 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/edges/views/Edges/utils.ts @@ -0,0 +1,84 @@ +// enumerable values (static) set for Position +export enum Position { + Left = 'left', + Right = 'right', + Top = 'top', + Bottom = 'bottom', +} + +// interface for XYPosition to use in nodes and edges +export interface XYPosition { + x: number; + y: number; +} + +// type for z axis positioning with D3 +export type XYZPosition = XYPosition & { z: number }; + +// interface for changing dimensions of Viewport +export interface Dimensions { + width: number; + height: number; +} + +// interface of Rect divs in zoompane +export interface Rect extends Dimensions, XYPosition {} + +// interface of Box using XYPosition of nodes +export interface Box extends XYPosition { + x2: number; + y2: number; +} + +// D3 type array for Transform +export type Transform = [number, number, number]; + +// +// export type CoordinateExtent = [[number, number], [number, number]]; + +export interface GetCenterParams { + sourceX: number; + sourceY: number; + targetX: number; + targetY: number; + sourcePosition?: Position; + targetPosition?: Position; +} +//needed for getCenter funciotn +const LeftOrRight = [Position.Left, Position.Right]; +//used to determine the position for edge text on a Smooth or Step Edge +export const getCenter = ({ + sourceX, + sourceY, + targetX, + targetY, + sourcePosition = Position.Bottom, + targetPosition = Position.Top, +}: GetCenterParams): [number, number, number, number] => { + const sourceIsLeftOrRight = LeftOrRight.includes(sourcePosition); + const targetIsLeftOrRight = LeftOrRight.includes(targetPosition); + + // we expect flows to be horizontal or vertical (all handles left or right respectively top or bottom) + // a mixed edge is when one the source is on the left and the target is on the top for example. + const mixedEdge = + (sourceIsLeftOrRight && !targetIsLeftOrRight) || + (targetIsLeftOrRight && !sourceIsLeftOrRight); + + if (mixedEdge) { + const xOffset = sourceIsLeftOrRight ? Math.abs(targetX - sourceX) : 0; + const centerX = sourceX > targetX ? sourceX - xOffset : sourceX + xOffset; + + const yOffset = sourceIsLeftOrRight ? 0 : Math.abs(targetY - sourceY); + const centerY = sourceY < targetY ? sourceY + yOffset : sourceY - yOffset; + + return [centerX, centerY, xOffset, yOffset]; + } + + const xOffset = Math.abs(targetX - sourceX) / 2; + const centerX = targetX < sourceX ? targetX + xOffset : targetX - xOffset; + + const yOffset = Math.abs(targetY - sourceY) / 2; + const centerY = targetY < sourceY ? targetY + yOffset : targetY - yOffset; + + return [centerX, centerY, xOffset, yOffset]; +}; diff --git a/frontend/src/lib/components/graph/svelvet/editEdges/views/EditEdge.svelte b/frontend/src/lib/components/graph/svelvet/editEdges/views/EditEdge.svelte new file mode 100644 index 0000000000..9118426fbe --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/editEdges/views/EditEdge.svelte @@ -0,0 +1,153 @@ + + +
    ($nodeSelected = true)} + on:focus + on:wheel|preventDefault +> +
    + + + + + + + + + +
    +
    + + + +
    +
    + + diff --git a/frontend/src/lib/components/graph/svelvet/interactiveNodes/README.md b/frontend/src/lib/components/graph/svelvet/interactiveNodes/README.md new file mode 100644 index 0000000000..9e113c4589 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/interactiveNodes/README.md @@ -0,0 +1,5 @@ +# README + +## Description + +Thie folder implements functionality to create new nodes and new edges dynamically. diff --git a/frontend/src/lib/components/graph/svelvet/interactiveNodes/controllers/createEdgeAndAnchors.ts b/frontend/src/lib/components/graph/svelvet/interactiveNodes/controllers/createEdgeAndAnchors.ts new file mode 100644 index 0000000000..e7a08c482d --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/interactiveNodes/controllers/createEdgeAndAnchors.ts @@ -0,0 +1,100 @@ +const pkStringGenerator = () => (Math.random() + 1).toString(36).substring(7); +import type { StoreType, PotentialAnchorType } from '../../store/types/types'; +import { get } from 'svelte/store'; +import { Node } from '../../nodes/models/Node'; +import { Edge } from '../../edges/models/Edge'; +import { Anchor } from '../../edges/models/Anchor'; + +import { + rightCb, + leftCb, + topCb, + bottomCb, +} from '../../edges/controllers/anchorCbUser'; +import { createPotentialAnchor } from '../../store/controllers/util'; +import { dynamicCbCreator } from '../../edges/controllers/anchorCbDev'; +import { getAnchors } from '../../edges/controllers/util'; +import { getPotentialAnchors } from './util'; + +/** + * Creates a new edge and two adaptive anchor points and updates the edgesStore and anchorsStore. + * + * @param store The Svelvet store containing the state of a Svelvet component + * @param sourceNodeId The id of the source Node + * @param targetNodeId The id of the target Node + * @param canvasId The canvasId of a Svelvet component + */ +export function createEdgeAndAnchors( + store: StoreType, + sourceNodeId: string, + targetNodeId: string, + canvasId: string +) { + // create an edge + const edgeId = pkStringGenerator(); + const newEdge = new Edge( + edgeId, + -1, + -1, + -1, + -1, + canvasId, + '', + 'bezier', + 'black', + 'black', + 'black', + false, + true, + false, + () => {}, + '' + ); + + // create source anchor + const sourceAnchorId = pkStringGenerator(); + const sourceDynamicCb = dynamicCbCreator(store, edgeId, sourceAnchorId); + const sourceAnchor = new Anchor( + sourceAnchorId, + sourceNodeId, + edgeId, + 'source', + -1, // dummy variables for x,y,angle for now + -1, // dummy variables for x,y,angle for now + sourceDynamicCb, + canvasId, + 0 // dummy variables for x,y,angle for now + ); + + // create target anchor + const targetAnchorId = pkStringGenerator(); + const targetDynamicCb = dynamicCbCreator(store, edgeId, targetAnchorId); + const targetAnchor = new Anchor( + targetAnchorId, + targetNodeId, + edgeId, + 'target', + -1, // dummy variables for x,y,angle for now + -1, // dummy variables for x,y,angle for now + targetDynamicCb, + canvasId, + 0 // dummy variables for x,y,angle for now + ); + + // put everything into the store + const { edgesStore, anchorsStore } = store; + + anchorsStore.update((anchors) => { + anchors[sourceAnchorId] = sourceAnchor; + anchors[targetAnchorId] = targetAnchor; + return { ...anchors }; + }); + edgesStore.update((edges) => { + edges[edgeId] = newEdge; + return { ...edges }; + }); + + // make sure to update positions. TODO: don't need to do this for the entire store + const anchors = getAnchors(store); + for (const anchor of anchors) anchor.callback(); +} diff --git a/frontend/src/lib/components/graph/svelvet/interactiveNodes/controllers/createNode.ts b/frontend/src/lib/components/graph/svelvet/interactiveNodes/controllers/createNode.ts new file mode 100644 index 0000000000..2463554d26 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/interactiveNodes/controllers/createNode.ts @@ -0,0 +1,166 @@ +const pkStringGenerator = () => (Math.random() + 1).toString(36).substring(7); +import type { StoreType, PotentialAnchorType } from '../../store/types/types'; +import { get } from 'svelte/store'; +import { Node } from '../../nodes/models/Node'; +import { Edge } from '../../edges/models/Edge'; +import { Anchor } from '../../edges/models/Anchor'; + +import { + rightCb, + leftCb, + topCb, + bottomCb, +} from '../../edges/controllers/anchorCbUser'; +import { createPotentialAnchor } from '../../store/controllers/util'; +import { dynamicCbCreator } from '../../edges/controllers/anchorCbDev'; +import { getAnchors } from '../../edges/controllers/util'; +import { getPotentialAnchors } from './util'; + +/** + * Creates a new Node when user drags the Edge and releases mouse at a new spot. This functionality is needed for the "create new node by dragging" feature. See TemporaryEdge.createNode() + * This function has no output, but alters the store. New Node/Edge/Anchor objects are added to the store. + * + * @param store The Svelvet store containing the state of a Svelvet component + * @param sourceNodeId The id of the source Node + * @param targetNodeX The postion X where user releases the mouse, which should be the x-axis position for the new Node + * @param targetNodeY The postion Y where user releases the mouse, which should be the y-axis position for the new Node + * @param canvasId The canvasId of a Svelvet component + */ +export function createNode( + store: StoreType, + sourceNodeId: string, + targetNodeX: number, + targetNodeY: number, + canvasId: string +) { + // create a new node + const targetNodeId = pkStringGenerator(); + + const node = new Node( + targetNodeId, + targetNodeX, + targetNodeY, + 100, // width + 100, // height + 'white', // background color + { + label: 'new node', + }, + canvasId, + 'black', // borderColor + false, // Node has an image + '', // src, not sure what this does + 'black', // text color + 0, // borderRadius + [], + '', + () => {} + ); + + // create new potential anchor, we do this because if we create + const potentialAnchorRight = createPotentialAnchor( + rightCb, + store, + targetNodeId, + canvasId + ); + const potentialAnchorLeft = createPotentialAnchor( + leftCb, + store, + targetNodeId, + canvasId + ); + const potentialAnchorTop = createPotentialAnchor( + topCb, + store, + targetNodeId, + canvasId + ); + const potentialAnchorBottom = createPotentialAnchor( + bottomCb, + store, + targetNodeId, + canvasId + ); + + // create an edge + const edgeId = pkStringGenerator(); + const newEdge = new Edge( + edgeId, + -1, + -1, + -1, + -1, + canvasId, + '', + 'bezier', + 'black', + 'black', + 'black', + false, + true, + false, + () => {}, + '' + ); + + // create source anchor + const sourceAnchorId = pkStringGenerator(); + const sourceDynamicCb = dynamicCbCreator(store, edgeId, sourceAnchorId); + const sourceAnchor = new Anchor( + sourceAnchorId, + sourceNodeId, + edgeId, + 'source', + -1, // dummy variables for x,y,angle for now + -1, // dummy variables for x,y,angle for now + sourceDynamicCb, + canvasId, + 0 // dummy variables for x,y,angle for now + ); + + // create target anchor + const targetAnchorId = pkStringGenerator(); + const targetDynamicCb = dynamicCbCreator(store, edgeId, targetAnchorId); + const targetAnchor = new Anchor( + targetAnchorId, + targetNodeId, + edgeId, + 'target', + -1, // dummy variables for x,y,angle for now + -1, // dummy variables for x,y,angle for now + targetDynamicCb, + canvasId, + 0 // dummy variables for x,y,angle for now + ); + + // put everything into the store + const { nodesStore, edgesStore, anchorsStore, potentialAnchorsStore } = store; + + nodesStore.update((nodes) => { + nodes[targetNodeId] = node; + return { ...nodes }; + }); + + anchorsStore.update((anchors) => { + anchors[sourceAnchorId] = sourceAnchor; + anchors[targetAnchorId] = targetAnchor; + return { ...anchors }; + }); + potentialAnchorsStore.update((anchors) => { + anchors[potentialAnchorRight.id] = potentialAnchorRight; + anchors[potentialAnchorTop.id] = potentialAnchorTop; + anchors[potentialAnchorBottom.id] = potentialAnchorBottom; + anchors[potentialAnchorLeft.id] = potentialAnchorLeft; + return { ...anchors }; + }); + edgesStore.update((edges) => { + edges[edgeId] = newEdge; + return { ...edges }; + }); + // make sure to update positions of anchors and potential anchors. TODO: don't need to do this for the entire store + const anchors = getAnchors(store); + for (const anchor of anchors) anchor.callback(); + const potAnchors = getPotentialAnchors(store); + for (const anchor of potAnchors) anchor.callback(); +} diff --git a/frontend/src/lib/components/graph/svelvet/interactiveNodes/controllers/util.ts b/frontend/src/lib/components/graph/svelvet/interactiveNodes/controllers/util.ts new file mode 100644 index 0000000000..2f3256b9ab --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/interactiveNodes/controllers/util.ts @@ -0,0 +1,75 @@ +import type { StoreType, PotentialAnchorType } from '../../store/types/types'; +import { get } from 'svelte/store'; +import type { NodeType } from '../../store/types/types'; + +/** + * getPotentialAnchorById will look for the targeted potential Anchor that has the same id provided in the Svelvet component store. + * + * @param store The Svelvet store containing the state of a Svelvet component + * @param id The id of the targeted potential Anchor + * @returns The targeted potential Anchor object in store.potentialAnchorsStore + */ +export function getPotentialAnchorById(store: StoreType, id: string) { + const potentialAnchorsStore = get(store.potentialAnchorsStore); + const potentialAnchor = potentialAnchorsStore[id]; + if (potentialAnchor === undefined) throw 'potential anchor not found'; + return potentialAnchor; +} + +/** + * Finds all potentialAnchors that matches the conditions specified in the filter parameter from a Svelvet store and returns these potential anchors in an array + * + * @param store The Svelvet store containing the state of a Svelvet component + * @param filter An object to specify conditions. + * @returns An array of potential anchors that matches the conditions specified in filter parameter + */ +export function getPotentialAnchors( + store: StoreType, + filter?: { [key: string]: any } +) { + let potentialAnchorsArr = Object.values(get(store.potentialAnchorsStore)); + // filter the array for elements that match filter + if (filter !== undefined) { + potentialAnchorsArr = potentialAnchorsArr.filter((potentialAnchor) => { + for (let filterKey in filter) { + const filterValue = filter[filterKey]; + if ( + potentialAnchor[filterKey as keyof PotentialAnchorType] !== + filterValue + ) + return false; + } + return true; + }); + } + // return list of anchors + return potentialAnchorsArr; +} + +/** + * Finds all Nodes that matches the conditions specified in the filter parameter from a Svelvet store and returns these Nodes in an array + * + * @param store The Svelvet store containing the state of a Svelvet component + * @param filter An object to specify conditions. + * @returns An array of Node objects that matches the conditions specified in filter parameter. This array is non-reactive (ie, you cannot use information from this array to force a re-render of a Svelte component) + */ +export function getNodes( + store: StoreType, + filter?: { [key: string]: any } +): NodeType[] { + let nodes = Object.values(get(store.nodesStore)); + // filter the array of anchors for elements that match filter + // Example: if filter = {sourceOrTarget: 'source', positionX: 35} then we will + // return all anchors with sourceOrTarget = source AND poxitionX = 35 + if (filter !== undefined) { + nodes = nodes.filter((node) => { + for (let filterKey in filter) { + const filterValue = filter[filterKey]; + if (node[filterKey as keyof NodeType] !== filterValue) return false; + } + return true; + }); + } + // return list of nodes + return nodes; +} diff --git a/frontend/src/lib/components/graph/svelvet/interactiveNodes/models/PotentialAnchor.ts b/frontend/src/lib/components/graph/svelvet/interactiveNodes/models/PotentialAnchor.ts new file mode 100644 index 0000000000..883f191304 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/interactiveNodes/models/PotentialAnchor.ts @@ -0,0 +1,34 @@ +// this class is for the 4 potential anchors that appear on each node + +import type { PotentialAnchorType } from '../../store/types/types'; +import { stores } from '../../store/models/store'; + +/** Class representing an anchor with a Anchortype alias */ +export class PotentialAnchor implements PotentialAnchorType { + /** + * creates a potential anchor. + * Users can create edges by linking two potential anchors + */ + constructor( + public id: string, + public nodeId: string, + public callback: Function, // callback is used to calculate positionX, positionY based on parent node's data, and set the anchor position // TODO: rename to something better + public positionX: number, + public positionY: number, + public angle: number, + public canvasId: string + ) {} + + delete() { + const { potentialAnchorsStore } = stores[this.canvasId]; + + potentialAnchorsStore.update((potentialAnchors) => { + for (const potentialAnchorId in potentialAnchors) { + if (potentialAnchors[potentialAnchorId].id === this.id) { + delete potentialAnchors[potentialAnchorId]; + } + } + return { ...potentialAnchors }; + }); + } +} diff --git a/frontend/src/lib/components/graph/svelvet/interactiveNodes/models/TemporaryEdge.ts b/frontend/src/lib/components/graph/svelvet/interactiveNodes/models/TemporaryEdge.ts new file mode 100644 index 0000000000..45e9cc8676 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/interactiveNodes/models/TemporaryEdge.ts @@ -0,0 +1,58 @@ +// table for the "connecting edge" feature +import type { TemporaryEdgeType } from '../../store/types/types'; +import { getPotentialAnchorById } from '../controllers/util'; +import { findStore } from '../../store/controllers/storeApi'; +import { createEdgeAndAnchors } from '../controllers/createEdgeAndAnchors'; + +import { createNode } from '../controllers/createNode'; + +import { getNodeById } from '../..//nodes/controllers/util'; + +export class TemporaryEdge implements TemporaryEdgeType { + constructor( + public id: string, + public sourcePotentialAnchorId: string, // this will always be set + public sourceX: number, + public sourceY: number, + public targetPotentialAnchorId: string | null, // this will be null until the temporary edge reaches another temporary anchor + public targetX: number, + public targetY: number, + public canvasId: string, + public type: string, + public edgeColor: string + ) {} + + // HOW: (1) Get the source/target potentialAnchor object + // (3) Get node id's of corresponding source/target nodes + // (4) + createEdge() { + if (this.targetPotentialAnchorId === null) + throw 'cannot create edge with null target'; + const store = findStore(this.canvasId); + // get the source/target potentialAnchor objects + const potentialAnchorSource = getPotentialAnchorById( + store, + this.sourcePotentialAnchorId + ); + const potentialAnchorTarget = getPotentialAnchorById( + store, + this.targetPotentialAnchorId + ); + // get node id's of source/target nodes + const sourceNode = getNodeById(store, potentialAnchorSource.nodeId); + const targetNode = getNodeById(store, potentialAnchorTarget.nodeId); + createEdgeAndAnchors(store, sourceNode.id, targetNode.id, this.canvasId); + } + createNode() { + if (this.targetPotentialAnchorId !== null) + throw 'you should only create a node when you are hovering over blank space'; + const store = findStore(this.canvasId); + // get the source/target potentialAnchor objects + const potentialAnchorSource = getPotentialAnchorById( + store, + this.sourcePotentialAnchorId + ); + const sourceNodeId = potentialAnchorSource.nodeId; + createNode(store, sourceNodeId, this.targetX, this.targetY, this.canvasId); + } +} diff --git a/frontend/src/lib/components/graph/svelvet/interactiveNodes/views/PotentialAnchor.svelte b/frontend/src/lib/components/graph/svelvet/interactiveNodes/views/PotentialAnchor.svelte new file mode 100644 index 0000000000..bb47b5285b --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/interactiveNodes/views/PotentialAnchor.svelte @@ -0,0 +1,169 @@ + + + { + // imelements drawing an (temporary) edge from a potential anchor to the mouse cursor + e.preventDefault(); + if (isDragging) { + temporaryEdgeStore.update((edges) => { + if (edges.length !== 1) + throw `if you are dragging, there should be one edge. We have not implemented multiple edges`; + const edge = edges[0]; + const d3Scale = get(store.d3Scale); + edge.targetX += e.movementX / d3Scale; + edge.targetY += e.movementY / d3Scale; + return [edge]; + }); + } + }} + on:mouseup={(e) => { + isDragging = false; // prevent the new edge from moving + + // only do update if temporaryEdgeStore has one element, and if that tempEdge.targetId = potentialAnchorId + // otherwise don't do anything (don't even update at all!!!) + if ( + get(temporaryEdgeStore).length === 1 && + get(temporaryEdgeStore)[0].targetPotentialAnchorId === potentialAnchorId + ) { + temporaryEdgeStore.update((edges) => { + for (let edge of edges) { + if (potentialAnchorId === edge.targetPotentialAnchorId) { + edge.createEdge(); + } + } + return []; + }); + } else if ( + get(temporaryEdgeStore).length === 1 && + get(temporaryEdgeStore)[0].targetPotentialAnchorId === null + ) { + temporaryEdgeStore.update((edges) => { + for (let edge of edges) { + // note length 1, refactor store to single tempEdge instead of arr of tempEdge + edge.createNode(); + } + return []; + }); + } + }} +/> + +
    { + // mouseHover is used to decide whether to create a new edge/node + mouseHover = true; + // our mouse is over anchor, so set the target anchor + temporaryEdgeStore.update((edges) => { + for (let edge of edges) { + edge.targetPotentialAnchorId = potentialAnchorId; + } + return [...edges]; + }); + }} + on:mouseleave={(e) => { + // mouseHover is used to decide whether to create a new edge/node + mouseHover = false; + + // If you are dragging an edge, and your mouse leaves an anchor area, then make sure to + // set targetAnchor back to null. We do a check because there are multiple anchorpoints + if (isDragging) { + temporaryEdgeStore.update((edges) => { + for (let edge of edges) { + if (edge.targetPotentialAnchorId === potentialAnchorId) + edge.targetPotentialAnchorId = null; + } + return [...edges]; + }); + } + }} + on:mousedown={(e) => { + e.preventDefault(); + e.stopPropagation(); // Important! Prevents the event from firing on the parent element (the .Nodes div) + isDragging = true; + temporaryEdgeStore.update((edges) => { + if (edges.length === 0) { + // say there are no temporary edges. This means the user just clicked on the potential anchor + // so the current mouse position = temporary anchor position = mouseX, mouseY + const newTempEdge = new TemporaryEdge( + pkStringGenerator(), + potentialAnchor.id, + mouseX, + mouseY, + null, + mouseX, + mouseY, + canvasId, + 'straight', + 'black' + ); + return [newTempEdge]; + } else { + throw `there should only be zero or one temporary edge at any given time`; + } + }); + }} + class="Anchor" + style={` + height:${anchorHeight}px; + width:${anchorWidth}px; + top: ${y - anchorHeight / 2}px; + left:${x - anchorWidth / 2}px; + `} +/> + + diff --git a/frontend/src/lib/components/graph/svelvet/interactiveNodes/views/TemporaryEdge.svelte b/frontend/src/lib/components/graph/svelvet/interactiveNodes/views/TemporaryEdge.svelte new file mode 100644 index 0000000000..6c777a4551 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/interactiveNodes/views/TemporaryEdge.svelte @@ -0,0 +1,28 @@ + + + + + diff --git a/frontend/src/lib/components/graph/svelvet/nodes/controllers/util.ts b/frontend/src/lib/components/graph/svelvet/nodes/controllers/util.ts new file mode 100644 index 0000000000..8f78a85a5e --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/nodes/controllers/util.ts @@ -0,0 +1,16 @@ +import type { StoreType } from '../../store/types/types'; +import { writable, derived, get, readable } from 'svelte/store'; + +/** + * getNodeById will look for the targeted Node that has the same id provided in the Svelvet component store. + * + * @param store The Svelvet store containing the state of a Svelvet component + * @param id The id of the targeted Node + * @returns The targeted Node object in store.nodesStore + */ + +export function getNodeById(store: StoreType, id: string) { + const nodesStore = get(store.nodesStore); + const node = nodesStore[id]; + return node; +} diff --git a/frontend/src/lib/components/graph/svelvet/nodes/models/Node.ts b/frontend/src/lib/components/graph/svelvet/nodes/models/Node.ts new file mode 100644 index 0000000000..48ae5749b2 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/nodes/models/Node.ts @@ -0,0 +1,213 @@ +/** this is where we create our node store */ +import type { NodeType } from '../../store/types/types'; +import { writable, derived, get, readable } from 'svelte/store'; +import { getPotentialAnchors } from '../../interactiveNodes/controllers/util'; +import { stores } from '../../store/models/store'; +import { getAnchors, getEdgeById } from '../../edges/controllers/util'; +import { getResizeNodes } from '../../resizableNodes/controllers/util'; +/** A Node class that implements NodeType interface + * @param {string} id The id of the Node + * @param {number} positionX The X-axis position of the Node (left top corner of the Node) + * @param {number} positionY The Y-axis position of the Node (left top corner of the Node) + * @param {number} width The width of the Node + * @param {number} height The height of the Node + * @param {string} bgColor The background color of the node + * @param {object} data A data object that user can specify; possible keys are 'label' and 'custom'; + * @param {string} canvasId The canvasId of the Svelvet component that the instantiated Node will be on. + * @param {string} borderColor The border color of the Node + * @param {boolean} image A boolean set to true if the Node needs to display an image + * @param {string} src The src link for the image; image and src are closely tied and a src link is only needed when image sets to true + * @param {string} textColor The color of the text in the Node + * @param {string} borderRadius The border radius of the Node + * @param {string} childNodes An array of node ids that will be grouped as child nodes of this Node. This is for the GroupNodes feature. The current implementation of this feature works one way but not the other (when you drag the parent node, the child nodes will move as a group but when you drag the child node, the parent node would not move along) + * @param {string} className The custom class name if user specifies. This is for the custom className feature for Node. + */ +export class Node implements NodeType { + constructor( + public id: string, + public positionX: number, + public positionY: number, + public width: number, + public height: number, + public bgColor: string, + public data: object, + public canvasId: string, + public borderColor: string, + public image: boolean, + public src: string, + public textColor: string, + public borderRadius: number, + public childNodes: string[], + public className: string, + public clickCallback: Function + ) {} + + /** + * setPositionFromMovement will update the positionX and positionY of the Node when user drags a Node around on the canvas, reflect the changes in real time in the nodesStore, and also cascade the changes to all relative elements like Anchors and Edges. + * @param {number} movementX The mouse movement value on the X-axis + * @param {number} movementY The mouse movement value on the Y-axis + */ + setPositionFromMovement(movementX: number, movementY: number) { + const { + nodesStore, + anchorsStore, + resizeNodesStore, + potentialAnchorsStore, + boundary, + lockedOption, + } = stores[this.canvasId]; + + if (get(lockedOption)) return; // don't do anything if locked is enabled + + // boundary sets the boundary of the canvas, or else it is false if their is no boundary + // check if out of bounds, and if so return without doing anything + const boundaryObj = get(boundary); + if ( + typeof boundaryObj === 'object' && + (this.positionX + this.width + movementX >= boundaryObj.x || + this.positionY + this.height + movementY >= boundaryObj.y || + this.positionY + movementY <= 0 || + this.positionX + movementX <= 0) + ) + return; + //update all necessary data + this.positionX += movementX; + this.positionY += movementY; + + // update children + nodesStore.update((nodes) => { + if (this.childNodes) + for (const childNodeId of this.childNodes) + nodes[childNodeId].setPositionFromMovement(movementX, movementY); + return { ...nodes }; + }); + + //update all the anchors on the node in the anchorsStore + anchorsStore.update((anchors) => { + for (const anchorId in anchors) { + if (anchors[anchorId].nodeId === this.id) { + anchors[anchorId].setPositionFromNode(); + } + } + return { ...anchors }; + }); + + //update all the anchors on the node in the anchorsStore + potentialAnchorsStore.update((anchors) => { + for (const anchorId in anchors) { + if (anchors[anchorId].nodeId === this.id) { + anchors[anchorId].callback(); // we don't have to worry about setting partner anchors/etc; + } + } + return { ...anchors }; + }); + + resizeNodesStore.update((resAnchors) => { + for (const anchorId in resAnchors) { + if (resAnchors[anchorId].nodeId === this.id) { + resAnchors[anchorId].setPosition(movementX, movementY); + //resAnchors[anchorId].setPosition(movementX, movementY); + } + } + return { ...resAnchors }; + }); + } + + /** + * setSizeFromMovement will update the width and height of the Node when user resizes the Node by dragging at the right bottom corner (where the ResizedNode attached), reflect the changes in real time in the nodesStore, and also cascade the changes to all relative elements like Anchors and potential Anchors. + * + * @param movementX The mouse movement value on the X-axis + * @param movementY The mouse movement value on the Y-axis + */ + setSizeFromMovement(movementX: number, movementY: number) { + this.width += movementX; + this.height += movementY; + + const { anchorsStore, potentialAnchorsStore } = stores[this.canvasId]; + + //Updates the anchor so it follows the node's position as the dimensions change + anchorsStore.update((anchors) => { + for (const anchorId in anchors) { + if (anchors[anchorId].nodeId === this.id) { + anchors[anchorId].setPositionFromNode(); + //anchors[anchorId].setPosition(movementX, movementY); + } + } + return { ...anchors }; + }); + + //update all the anchors on the node in the anchorsStore + potentialAnchorsStore.update((anchors) => { + for (const anchorId in anchors) { + if (anchors[anchorId].nodeId === this.id) { + anchors[anchorId].callback(); // we don't have to worry about setting partner anchors/etc; + } + } + return { ...anchors }; + }); + } + + /** + * delete will handle the deletion of a Node (also waterfall down to delete anchors and edges) + */ + delete() { + const store = stores[this.canvasId]; + const { nodesStore, anchorsStore, edgesStore } = stores[this.canvasId]; + + nodesStore.update((nodes) => { + for (const nodeId in nodes) { + if (nodes[nodeId].id === this.id) { + delete nodes[nodeId]; + } + } + return { ...nodes }; + }); + + // variable `anchors` is an array of Anchor objects on the node + const anchors = getAnchors(store, { nodeId: this.id }); + for (let anchorSelf of anchors) { + const edgeId = anchorSelf.edgeId; + const edge = getEdgeById(store, edgeId); + edge.delete(); // this also deletes anchors. TODO: maybe this should be renamed to explicitly say + } + + // delete the resize nodes + const resizeNodesArr = getResizeNodes(store, { nodeId: this.id }); + // there should be only 1 resize node if option is enabled, 0 if not enabled + for (const resizeNode of resizeNodesArr) { + resizeNode.delete(); + } + + // delete the potential anchors + const potentialAnchorsArr = getPotentialAnchors(store, { nodeId: this.id }); + for (const potentialAnchor of potentialAnchorsArr) { + potentialAnchor.delete(); + } + } + + /** + * setExportableData is going to construct an object that holds all the node data that can be exported. This method is used for Exporting Diagrams feature. + * + * @returns An object with all the exportable data of the Node. The format of this object should align with the original format of node data user provided. + */ + setExportableData() { + const exportableData = { + id: this.id, + // canvasId: this.canvasId, + width: this.width, + height: this.height, + position: { x: this.positionX, y: this.positionY }, + data: this.data, + bgColor: this.bgColor, + borderColor: this.borderColor, + textColor: this.textColor, + borderRadius: this.borderRadius, + image: this.image, + src: this.src, + childNodes: this.childNodes, + customClassName: this.className, + }; + + return exportableData; + } +} diff --git a/frontend/src/lib/components/graph/svelvet/nodes/views/EditNode.svelte b/frontend/src/lib/components/graph/svelvet/nodes/views/EditNode.svelte new file mode 100644 index 0000000000..84f3f20a8f --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/nodes/views/EditNode.svelte @@ -0,0 +1,146 @@ + + +{#if isEditing} +
    ($nodeSelected = true)} + on:focus + on:wheel|preventDefault + class="EditNode" + style="left:{currentNode.positionX + + currentNode.width}px; top:{currentNode.positionY}px" + > +
    + + + + + + +
    +
    + + +
    +
    +{/if} + + diff --git a/frontend/src/lib/components/graph/svelvet/nodes/views/Node.svelte b/frontend/src/lib/components/graph/svelvet/nodes/views/Node.svelte new file mode 100644 index 0000000000..93b707fc0d --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/nodes/views/Node.svelte @@ -0,0 +1,92 @@ + + + +
    + + {#if node.image} + + {/if} + +
    + + diff --git a/frontend/src/lib/components/graph/svelvet/resizableNodes/controllers/util.ts b/frontend/src/lib/components/graph/svelvet/resizableNodes/controllers/util.ts new file mode 100644 index 0000000000..f8bc6dab57 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/resizableNodes/controllers/util.ts @@ -0,0 +1,28 @@ +import type { StoreType, ResizeNodeType } from '../../store/types/types'; +import { get } from 'svelte/store'; +/** + * Finds all resizeNodes that matches the conditions specified in the filter parameter from a Svelvet store and returns these resizeNodes in an array + * + * @param store The Svelvet store containing the state of a Svelvet component + * @param filter An object to specify conditions. + * @returns An array of resizeNode objects that matches the conditions specified in filter parameter + */ +export function getResizeNodes( + store: StoreType, + filter?: { [key: string]: any } +) { + let resizeNodes = Object.values(get(store.resizeNodesStore)); + // filter the array for elements that match filter + if (filter !== undefined) { + resizeNodes = resizeNodes.filter((resizeNode) => { + for (let filterKey in filter) { + const filterValue = filter[filterKey]; + if (resizeNode[filterKey as keyof ResizeNodeType] !== filterValue) + return false; + } + return true; + }); + } + // return list of anchors + return resizeNodes; +} diff --git a/frontend/src/lib/components/graph/svelvet/resizableNodes/models/ResizeNode.ts b/frontend/src/lib/components/graph/svelvet/resizableNodes/models/ResizeNode.ts new file mode 100644 index 0000000000..a23fec9317 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/resizableNodes/models/ResizeNode.ts @@ -0,0 +1,73 @@ +import type { ResizeNodeType } from '../../store/types/types'; +// import { writable, derived, get, readable } from 'svelte/store'; +import { stores } from '../../store/models/store'; + +/** A ResizeNode class that implements ResizeNodeType interface +* @param {string} id The id of the ResizeNode +* @param {string} canvasId The canvasId of the Svelvet component that the instantiated ResizeNode will be on. +* @param {string} nodeId The id of the Node that the instantiated ResizedNode will be attached to. +* @param {number} positionX The X-axis position of the ResizeNode (left top corner of the ResizeNode) +* @param {number} positionY The Y-axis position of the ResizeNode (left top corner of the ResizeNode) +*/ +export class ResizeNode implements ResizeNodeType { + constructor( + public id: string, + public canvasId: string, + public nodeId: string, + public positionX: number, + public positionY: number + ) {} + + /** + * setPosition will update the positionX and positionY of the ResizeNode. This will be invoked when the Node that this ResizeNode attached to is moving so that the ResizeNode will follow the Node. + * + * @param movementX The mouse movement value on the X-axis + * @param movementY The mouse movement value on the Y-axis + */ + setPosition(movementX: number, movementY: number) { + this.positionX += movementX; + this.positionY += movementY; + } + + /** + * setPositionAndCascade will update the positionX and positionY of the ResizeNode and also cascade changes to related Node. This will be invoked when the user drags the ResizeNode so the position of the ResizeNode and the width and height of the Node would change accordingly. + * @param movementX The mouse movement value on the X-axis + * @param movementY The mouse movement value on the Y-axis + */ + setPositionAndCascade(movementX: number, movementY: number) { + //declare variables needed to interact with the corresponding node to this resize anchor + const nodeId = this.nodeId; + const { nodesStore } = stores[this.canvasId]; + + //Updates the width/height of the corresponding Node + nodesStore.update((nodes) => { + const node = nodes[nodeId]; + + //sets condition so node cannot be less than 20 px in width or height. + if (node.width + movementX > 20 && node.height + movementY > 20) { + //Updates position to this resizeNode anchor. Must be done within the update method so ensure the position doesn't change if the width goes below 20px + this.positionX += movementX; + this.positionY += movementY; + //setSizeFromMovement will then update the anchors position as the width & height changes + node.setSizeFromMovement(movementX, movementY); + } + return { ...nodes }; + }); + } + + /** + * delete is going to delete the ResizeNode from the resizeNodesStore. + */ + delete() { + const store = stores[this.canvasId]; + const { resizeNodesStore } = stores[this.canvasId]; + resizeNodesStore.update((resizeNodes) => { + for (const resizeNodeId in resizeNodes) { + if (resizeNodes[resizeNodeId].id === this.id) { + delete resizeNodes[resizeNodeId]; + } + } + return { ...resizeNodes }; + }); + } +} diff --git a/frontend/src/lib/components/graph/svelvet/resizableNodes/views/ResizeNode.svelte b/frontend/src/lib/components/graph/svelvet/resizableNodes/views/ResizeNode.svelte new file mode 100644 index 0000000000..53c593bdd7 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/resizableNodes/views/ResizeNode.svelte @@ -0,0 +1,85 @@ + + + { + e.preventDefault(); + if (isSelected) { + resizeNodesStore.update((resNode) => { + const newResNode = resNode[resizeId]; + const d3Scale = get(store.d3Scale); + newResNode.setPositionAndCascade( + e.movementX / d3Scale, + e.movementY / d3Scale, + resizeId + ); + return { ...resNode }; + }); + } + }} + on:mouseup={(e) => { + e.preventDefault(); + // don't need to set $nodeSelected = false because Node component will do it for you + isSelected = false; + }} +/> + +
    { + e.preventDefault(); + $nodeSelected = true; + isSelected = true; + }} + on:mouseover={(e) => ($nodeSelected = true)} + on:focus + on:mouseleave={(e) => ($nodeSelected = false)} + on:mouseenter={(e) => ($nodeSelected = true)} + on:wheel|preventDefault + class="ResizeNode" + style=" + left: {reactResizeNode.positionX - 10}px; + top: {reactResizeNode.positionY - 10}px; + width: {20}px; + height: {20}px; + background-color: purple; + border-color: purple; + border-radius: 50%;" + id="svelvet-{resizeId}" +/> + + diff --git a/frontend/src/lib/components/graph/svelvet/store/controllers/storeApi.ts b/frontend/src/lib/components/graph/svelvet/store/controllers/storeApi.ts new file mode 100644 index 0000000000..12500f9099 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/store/controllers/storeApi.ts @@ -0,0 +1,131 @@ +/* + + +Important functions (in order of how likely I think you are to use them): + +findStore(canvasId: string) +- Input: canvasId. There can be multiple Svelvet canvases on the same page, and each has their own store +- Returns: store +- Notes: You will need to call this function on every component you make + +getNodes(store, filter) +- Description: this function returns of list of Node objects +- Input: store: the store where you get the list of Node objects from +- filter: an object where you can filter the array. For example, if you want to find nodes with an id of 'sdf-2d3fs' and positionX=35, then you + would set filter = {id: 'sdf-2d3fs, positionX: 35}. + Right now, you can only test for equality. +- Notes: This is a very mongoose way of retrieving information. Given the relational nature of our stores, maybe it would be better to use an SQL-like syntax + This array is non-reactive (ie, you cannot use information from this array to force a re-render of a Svelte component) + +createStoreEmpty(canvasId: string) +- Input: canvasId. +- Returns: store +- Notes. This should be called once every time you initialize a new Svelvet canvas, (ie, only in the Svelvet.svelte file) + +populateSvelvetStoreFromUserInput(canvasId, nodes, edges) +- canvasId: this the the canvasId of the Svelvet component you are creating a store for +- nodes: this is an array of objects containing node info that is defined by the user. NOTE THAT THE STRUCTURE DIFFERS FROM THE NODES CLASS + The whole point of populateSvelvetStoreFromUserInput is to convert nodes into proper Svelvet Node objects. An example of nodes is in + $routes/testingplayground/index.svelte +- edges: same as nodes, this is an array of objects containing edge info THAT IS DIFFERENT FROM THE EDGE CLASS. +- Returns: store +*/ +import { stores } from '../models/store'; +import { writable, get } from 'svelte/store'; + +import type { StoreType } from '../types/types'; +import type { UserNodeType, UserEdgeType } from '../../types/types'; +import { + populateAnchorsStore, + populateNodesStore, + populateEdgesStore, + populateResizeNodeStore, + populatePotentialAnchorStore, +} from './util'; +import { populateCollapsibleStore } from '../../collapsible/controllers/util'; + +/** + * findStore is going to return the target Svelvet store with the canvasId provided as argument. + * There can be multiple Svelvet canvases on the same page, and each has their own store with a unique canvasId. + * @param canvasId The canvasId of a Svelvet component + * @returns The store of a Svelvet component that matches the canvasId + */ +export function findStore(canvasId: string): StoreType { + return stores[canvasId]; +} + +/** + * createStoreEmpty will initialize a new Svelvet store with a unique canvasId. + * If you have multiple Svelvet components on the page, the stores object will look like the following example: + * const stores = \{ + * canvasId-1: store of Svelvet component 1, + * canvasId-2: store of Svelvet component 2, + * canvasId-3: store of Svelvet component 3, + * \} + * Notes: This should be called once every time you initialize a new Svelvet canvas, (ie, only in the Svelvet.svelte file). + * This function will initialize an empty store for the Svelvet component and should be followed by invoking populateSvelvetStoreFromUserInput to populate all the initial state from the user input. + * + * @param canvasId The canvasId of the newly created Svelvet component + * @returns An empty store for the newly created Svelvet component. + */ +export function createStoreEmpty(canvasId: string): StoreType { + stores[canvasId] = { + nodesStore: writable({}), + edgesStore: writable({}), + anchorsStore: writable({}), + resizeNodesStore: writable({}), + potentialAnchorsStore: writable({}), + widthStore: writable(600), + heightStore: writable(600), + backgroundStore: writable(false), + movementStore: writable(true), + nodeSelected: writable(false), + nodeIdSelected: writable(-1), + d3Scale: writable(1), + options: writable({}), + temporaryEdgeStore: writable([]), + nodeCreate: writable(false), // this option sets whether the "nodeEdit" feature is enabled + boundary: writable(false), + edgeEditModal: writable(null), // this is used for edgeEditModal feature. When an edge is right clicked, store.edgeEditModal is set to the edgeId string. This causes a modal to be rendered + collapsibleStore: writable([]), // this is used for the collaspsible node feature. If the feature is enabled, store.collapsible will be populated with Collapsible objects which will track whether the node should be displayed or not + collapsibleOption: writable(false), + lockedOption: writable(false), + editableOption: writable(false), // true if you want nodes/edges to be editable. See feature editEdges + d3ZoomParameters: writable({}), // this stores d3 parameters x, y, and zoom. This isn't used for anything other than giving users a way to access d3 zoom parameters if they want to build on top of Svelvet + resizableOption: writable(true), // option to turn on/off resizable nodes. + highlightEdgesOption: writable(true), // option to turn on/off highlightable edges + }; + return stores[canvasId]; +} + +/** + * populateSvelvetStoreFromUserInput will populate all the states and set these states into the Svelvet store initialized by invoking createStoreEmpty + * + * @param canvasId The canvasId of the Svelvet component you are creating a store for + * @param nodes This is an array of objects containing node info that is defined by the user. NOTE THAT THE STRUCTURE DIFFERS FROM THE NODES CLASS. The whole point of populateSvelvetStoreFromUserInput is to convert nodes into proper Svelvet Node objects. An example of nodes is in $routes/testingplayground/index.svelte + * @param edges Same as nodes, this is an array of objects containing edge info THAT IS DIFFERENT FROM THE EDGE CLASS. + */ +export function populateSvelvetStoreFromUserInput( + canvasId: string, + nodes: UserNodeType[], + edges: UserEdgeType[] +): void { + // find the store + const store = findStore(canvasId); + + // populate store.nodesStore with user nodes + populateNodesStore(store, nodes, canvasId); + // populate store.anchorsStore with anchors. Note the userdoes not explictly define anchors; anchors are calculated from the edges + populateAnchorsStore(store, nodes, edges, canvasId); + // populate edges + populateEdgesStore(store, edges, canvasId); + //populate resize Store + if (get(store.resizableOption)) + populateResizeNodeStore(store, nodes, canvasId); + //populate potential anchors if "node create" feature is turned on + if (get(store.nodeCreate)) + populatePotentialAnchorStore(store, nodes, canvasId); + // populatate collapsible objects if "collapsible" feature is turned on + if (get(store.collapsibleOption)) + populateCollapsibleStore(store, nodes, edges, canvasId); +} diff --git a/frontend/src/lib/components/graph/svelvet/store/controllers/userApi.ts b/frontend/src/lib/components/graph/svelvet/store/controllers/userApi.ts new file mode 100644 index 0000000000..88922d33be --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/store/controllers/userApi.ts @@ -0,0 +1,18 @@ +import { findStore } from './storeApi'; +import { get } from 'svelte/store'; +export function getD3PositionX(canvasId) { + const store = findStore(canvasId); + const width = get(store.widthStore); + const x = width / 2 - get(store.d3ZoomParameters).x; // user input is shifted so that x=0, y=0 occurs in the center + return x; +} +export function getD3PositionY(canvasId) { + const store = findStore(canvasId); + const height = get(store.heightStore); + const y = height / 2 - get(store.d3ZoomParameters).y; // user input is shifted so that x=0, y=0 occurs in the center + return y; +} +export function getD3Zoom(canvasId) { + const store = findStore(canvasId); + return get(store.d3ZoomParameters).k; +} diff --git a/frontend/src/lib/components/graph/svelvet/store/controllers/util.ts b/frontend/src/lib/components/graph/svelvet/store/controllers/util.ts new file mode 100644 index 0000000000..4eceff659e --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/store/controllers/util.ts @@ -0,0 +1,382 @@ +const pkStringGenerator = () => (Math.random() + 1).toString(36).substring(7); +import { + rightCb, + leftCb, + topCb, + bottomCb, +} from '../../edges/controllers/anchorCbUser'; // these are callbacks used to calculate anchor position relative to node +import { + dynamicCbCreator, + fixedCbCreator, + potentialAnchorCbCreator, +} from '../../edges/controllers/anchorCbDev'; + +import type { AnchorType, AnchorCbType } from '../../edges/types/types'; + +import type { + NodeType, + EdgeType, + StoreType, + ResizeNodeType, + PotentialAnchorType, +} from '../types/types'; +import type { UserNodeType, UserEdgeType } from '../../types/types'; + +import { ResizeNode } from '../../resizableNodes/models/ResizeNode'; +import { Anchor } from '../../edges/models/Anchor'; +import { Node } from '../../nodes/models/Node'; +import { Edge } from '../../edges/models/Edge'; +import { writable, derived, get, readable } from 'svelte/store'; +import { PotentialAnchor } from '../../interactiveNodes/models/PotentialAnchor'; +import { getEdgeById, getAnchors } from '../../edges/controllers/util'; + +/** + * Creates resize node on the bottom right corner of the targeted Node + * @param canvasId The canvasId of the Svelvet component that holds the targeted Node + * @param nodeId The id of the Node that the resize node attached to + * @param posX The number of pixels on the x-axis relative to the left top corner of the targeted Node + * @param posY The number of pixels on the y-axis relative to the left top corner of the targeted Node + * @returns A ReziseNode object with randomized id, canvasId, nodeId, posX, and posY + */ +function createResizeNode( + canvasId: string, + nodeId: string, + posX: number, + posY: number +) { + const id = pkStringGenerator(); + const resizeNode = new ResizeNode(id, canvasId, nodeId, posX, posY); + return resizeNode; +} + +/** + * Creates an Anchor on the targeted Node with infomation the userNode holds + * @param store An object containing the state of the Svelvet component. You can access the following through `store`: nodesStore, edgesStore, anchorsStore, etc. + * @param userNode A node that the user specifies. This is NOT the same as a Node object. + * @param sourceOrTarget User specified information of source or target + * @param canvasId The id of the canvas that holds the Anchor and its attached Node + * @param edge An edge that the user specifies. It should target the userNode as source or target. This is NOT the same as an Edge object + * @returns An Anchor object + */ + +function createAnchor( + store: StoreType, + userNode: UserNodeType | null, + sourceOrTarget: 'source' | 'target', + canvasId: string, + edge: UserEdgeType +) { + // edge case + if (userNode === null) + throw `you cannot create an anchor without a user node (for now)`; + + const edgeId = edge.id; + const anchorId = pkStringGenerator(); + + // userCb is the appropriate source or taret callback from userEdge object. It is + // possible the user to NOT set userCb in which case userCb will be undefined + let userCb: Function | undefined; + if (sourceOrTarget === 'target') userCb = edge.targetAnchorCb; + else userCb = edge.sourceAnchorCb; + + // create anchor callbacks + + let cb: AnchorCbType; + if (userCb === undefined) cb = dynamicCbCreator(store, edgeId, anchorId); + else cb = fixedCbCreator(store, edgeId, anchorId, userNode.id, userCb); + + // Create a new anchor. + const anchor = new Anchor( + anchorId, + userNode.id, + edgeId, + sourceOrTarget, + -1, // dummy variables for x,y,angle for now + -1, // dummy variables for x,y,angle for now + cb, + canvasId, + 0 // dummy variables for x,y,angle for now + ); + // return + return anchor; +} + +/** + * Populates edgesStore of Edges. This function does not return the edgesStore. Instead it sets the nodesStore of Svelvet store. + * @param store An object containing the state of the Svelvet component. You can access the following through `store`: nodesStore, edgesStore, anchorsStore, etc. + * @param edges An edge that the user specifies. This is NOT the same as a Edge object. + * @param canvasId The canvasId of the Svelvet component that holds the Edges + */ +export function populateEdgesStore( + store: StoreType, + edges: UserEdgeType[], + canvasId: string +) { + const edgesStore: { [key: string]: EdgeType } = {}; + for (let i = 0; i < edges.length; i++) { + const userEdge = edges[i]; + // { id: 'e1-2', source: 1, type: 'straight', target: 2, label: 'e1-2' }, + // source is node.id for the source node + // target is node.id for the target node + // We need to get the anchors + const { + source: sourceNodeId, + target: targetNodeId, + id: edgeId, + type, + label, + labelBgColor, + labelTextColor, + edgeColor, + animate, + noHandle, + arrow, + clickCallback, + className, + } = userEdge; + + const anchors = getAnchors(store, { edgeId: edgeId }); + // check that we have two anchors for every edge + if (anchors.length !== 2) throw 'We should have two anchors for every node'; + // check that we have 1 source anchor and 1 target anchor. Since sourceOrTarget is typed to be either 'source' + // or 'target', it suffices to check whether there are two unique elements + if (new Set(anchors.map((e) => e.sourceOrTarget)).size !== 2) + throw 'we should have one source and one target anchor'; + // get source and target anchor + let sourceAnchor, targetAnchor; + if (anchors[0].sourceOrTarget === 'source') { + sourceAnchor = anchors[0]; + targetAnchor = anchors[1]; + } else { + sourceAnchor = anchors[1]; + targetAnchor = anchors[0]; + } + + edgesStore[edgeId] = new Edge( + edgeId, + sourceAnchor.positionX, + sourceAnchor.positionY, + targetAnchor.positionX, + targetAnchor.positionY, + canvasId, + userEdge.label === undefined ? '' : userEdge.label, + userEdge.type === undefined ? 'bezier' : userEdge.type, + userEdge.labelBgColor === undefined ? 'white' : userEdge.labelBgColor, + userEdge.labelTextColor === undefined ? 'black' : userEdge.labelTextColor, + userEdge.edgeColor === undefined ? 'black' : userEdge.edgeColor, + userEdge.animate === undefined ? false : userEdge.animate, + userEdge.noHandle === undefined ? false : userEdge.noHandle, + userEdge.arrow === undefined ? false : userEdge.arrow, + userEdge.clickCallback === undefined ? () => { } : userEdge.clickCallback, + userEdge.className === undefined ? '' : userEdge.className + ); + } + store.edgesStore.set(edgesStore); +} + +/** + * Finds userNode (with UserNodeType; Not the same as the Node) by the node id from nodesStore + * @param id The id of the Node in its nodesStore + * @param userNodes The array of userNodes (NOT the same as Node object) + * @returns The node that user specified or null if not found + */ +function findUserNodeById( + id: string, + userNodes: UserNodeType[] +): UserNodeType | null { + for (let i = 0; i < userNodes.length; i++) { + const userNode = userNodes[i]; + if (userNode.id === id) return userNode; + } + return null; +} + +/** + * Creates potential anchor based on the user input data in userNode + * @param positionCb positionCb should be a function that takes 4 arguments (x,y,width,height) and returns a 3-array [x,y,angle] that represents the x,y position of the anchor as well as it's angle with respect to it's node. + * @param store An object containing the state of the Svelvet component. You can access the following through `store`: nodesStore, edgesStore, anchorsStore, etc. + * @param userNode The array of userNodes (NOT the same as Node object) + * @param canvasId The canvasId of the Svelvet component that holds the Anchors + * @returns A PotentialAnchor object with default placeholder values for its positionX, positionY, and angle + */ +export function createPotentialAnchor( + positionCb: Function, + store: StoreType, + nodeId: string, + canvasId: string +) { + const anchorId = pkStringGenerator(); + const fixedCb = potentialAnchorCbCreator(store, anchorId, nodeId, positionCb); + // Create a new anchor. The + const anchor = new PotentialAnchor( + anchorId, + nodeId, + fixedCb, + -1, // dummy variables for x,y,angle for now + -1, // dummy variables for x,y,angle for now + 0, // dummy variables for x,y,angle for now + canvasId + ); + // return + return anchor; +} + +/** + * Populates potentialAnchorsStore + * @param store An object containing the state of the Svelvet component. You can access the following through `store`: nodesStore, edgesStore, anchorsStore, etc. + * @param nodes An array of nodes with UserNodeType + * @param canvasId The canvasId of the Svelvet component that holds the potential anchors + */ +export function populatePotentialAnchorStore( + store: StoreType, + nodes: UserNodeType[], + canvasId: string +) { + // anchorsStore will populated and eventaully synchronized to store.anchorsStore + const potentialAnchorsStore: { [key: string]: PotentialAnchorType } = {}; + // iterate through user nodes and create four anchors per node + for (let i = 0; i < nodes.length; i++) { + const userNode = nodes[i]; + + // create 4 potentialAnchors + for (let cb of [topCb, bottomCb, rightCb, leftCb]) { + const anchor = createPotentialAnchor(cb, store, userNode.id, canvasId); + // store potential anchors + potentialAnchorsStore[anchor.id] = anchor; + } + } + + //populates the anchorsStore + store.potentialAnchorsStore.set(potentialAnchorsStore); + + // set potentialAnchor positions. We can only set potentialAnchor positions after anchorsStore and nodesStore + // has been populated. TODO: maybe add a check to see that anchorsStore and NodesStore populated? + const potentialAnchors = Object.values(get(store.potentialAnchorsStore)); + for (const potentialAnchor of potentialAnchors) potentialAnchor.callback(); +} + +/** + * Populates the anchorsStore. This will overwrite any data in the AnchorsStore. + * @param store The Svelvet store containing the state of the Svelvet component + * @param nodes An array of user specified nodes + * @param edges An array of user specified edges + * @param canvasId The canvasId of the Svelvet component that holds the nodes and edges + */ +export function populateAnchorsStore( + store: StoreType, + nodes: UserNodeType[], + edges: UserEdgeType[], + canvasId: string +) { + // anchorsStore will populated and eventaully synchronized to store.anchorsStore + const anchorsStore: { [key: string]: AnchorType } = {}; + // iterate through user edges. Note the user never explicitly defines anchors; we calculate anchors + // from the user edge/node information + for (let i = 0; i < edges.length; i++) { + const userEdge = edges[i]; + // find the source and target userNodes. These will be used to create the nodeId foreign key and + // determine placement of the anchor based on userNode.targetPosition, useNode.sourcePosition + const { source: sourceNodeId, target: targetNodeId } = userEdge; + const sourceUserNode = findUserNodeById(sourceNodeId, nodes); + const targetUserNode = findUserNodeById(targetNodeId, nodes); + // create source anchor + const sourceAnchor = createAnchor( + store, + sourceUserNode, + 'source', + canvasId, + userEdge + ); + // create target anchor + const targetAnchor = createAnchor( + store, + targetUserNode, + 'target', + canvasId, + userEdge + ); + // store source and target anchors + anchorsStore[sourceAnchor.id] = sourceAnchor; + anchorsStore[targetAnchor.id] = targetAnchor; + } + + //populates the anchorsStore + store.anchorsStore.set(anchorsStore); + + // set anchor positions. We can only set anchor positions after anchorsStore and nodesStore + // has been populated. TODO: maybe add a check to see that anchorsStore and NodesStore populated? + const anchors = getAnchors(store); + for (const anchor of anchors) anchor.callback(); +} + +/** + * Populates the nodesStore. This will overwrite any data in the nodesStore. + * @param store The Svelvet store containing the state of the Svelvet component + * @param nodes An array of user specifed nodes + * @param canvasId The canvasId of the Svelvet component that holds the nodes + */ +export function populateNodesStore( + store: StoreType, + nodes: UserNodeType[], + canvasId: string +) { + // this is the nodesStore object. THIS IS NOT THE SAME AS A NODESTORE + const nodesStore: { [key: string]: NodeType } = {}; + // iterate through user nodes and create node objects + for (let i = 0; i < nodes.length; i++) { + const userNode: UserNodeType = nodes[i]; + const nodeId = userNode.id; + + // TODO: move sanitizing default values to middleware + const node = new Node( + nodeId.toString(), + userNode.position.x, + userNode.position.y, + userNode.width, + userNode.height, + userNode.bgColor ?? 'white', + userNode.data, + canvasId, + userNode.borderColor === undefined ? 'black' : userNode.borderColor, + userNode.image === undefined ? false : userNode.image, + userNode.src === undefined ? '' : userNode.src, + userNode.textColor === undefined ? '' : userNode.textColor, + userNode.borderRadius === undefined ? 0 : userNode.borderRadius, + userNode.childNodes === undefined ? [] : userNode.childNodes, + userNode.className === undefined ? '' : userNode.className, + userNode.clickCallback === undefined ? () => { } : userNode.clickCallback + ); + + nodesStore[nodeId] = node; + } + // This is actually what sets the store + store.nodesStore.set(nodesStore); +} + +/** + * Populates the resizeNodeStore. If a Node is resizable, a small ResizeNode object is going to be attached to the Node's right bottom corner to react to the mouse drag. + * @param store The Svelvet store containing the state of the Svelvet component + * @param nodes An array of user specifed nodes (NOT the same as Node) + * @param canvasId The canvasId of the Svelvet component that holds the resizeNodes + */ +export function populateResizeNodeStore( + store: StoreType, + nodes: UserNodeType[], + canvasId: string +) { + const resizeNodeStore: { [key: string]: ResizeNodeType } = {}; + + for (let i = 0; i < nodes.length; i++) { + const userNode = nodes[i]; + const { id, width, height, position } = userNode; + const resizeNode = createResizeNode( + canvasId, + id, + position.x + width, + position.y + height + ); + resizeNodeStore[resizeNode.id] = resizeNode; + } + + store.resizeNodesStore.set(resizeNodeStore); +} diff --git a/frontend/src/lib/components/graph/svelvet/store/models/store.ts b/frontend/src/lib/components/graph/svelvet/store/models/store.ts new file mode 100644 index 0000000000..8d6ebae177 --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/store/models/store.ts @@ -0,0 +1,11 @@ +import type { StoreType } from '../types/types'; + +/** + `store` is a dictionary of Svelvet stores. + * The reason why we have multiple Svelvet stores is to handle multiple canvases on the same page. + * A Svelvet store is the single source of truth for a canvas state. + * We discourage developers from interacting with stores directly; instead use the api methods in + `src/lib/controllers/storeApi.ts`. However, if need to direct access you can do so by importing: + `import { store } from 'src/lib/models/store';` +*/ +export const stores: { [key: string]: StoreType } = {}; diff --git a/frontend/src/lib/components/graph/svelvet/store/types/types.ts b/frontend/src/lib/components/graph/svelvet/store/types/types.ts new file mode 100644 index 0000000000..e4f22dcd6d --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/store/types/types.ts @@ -0,0 +1,124 @@ +import type { CollapsibleType } from '../../collapsible/types/types'; +import type { Writable } from 'svelte/store'; +import type { AnchorType } from '../../edges/types/types'; +import type { SvelteComponentTyped } from "svelte"; + +export interface ResizeNodeType { + id: string; + nodeId: string; + edgeId?: string; + canvasId: string; + anchorId?: string; + positionX: number; + positionY: number; + setPositionAndCascade: Function; + setPosition: Function; + delete: Function; +} + +/* +Type for a single svelvet store +*/ +export interface StoreType { + nodesStore: Writable<{ [key: string]: NodeType }>; + edgesStore: Writable<{ [key: string]: EdgeType }>; + anchorsStore: Writable<{ [key: string]: AnchorType }>; + resizeNodesStore: Writable<{ [key: string]: ResizeNodeType }>; + potentialAnchorsStore: Writable<{ [key: string]: PotentialAnchorType }>; + widthStore: Writable; + heightStore: Writable; + backgroundStore: Writable; + movementStore: Writable; + nodeIdSelected: Writable; + nodeSelected: Writable; // this is used to stop d3 panning when node is being dragged + d3Scale: Writable; // for zoom and pan + options: Writable<{ [key: string]: any }>; + temporaryEdgeStore: Writable; + nodeCreate: Writable; // this option sets whether the "nodeEdit" feature is enabled + boundary: Writable; + edgeEditModal: Writable; // this options is used to place the edgeEdit modal when an edge is right-clicked. null is no modal, positionType if modal should be placed at position defined by postionType.x, positionType.y + collapsibleStore: Writable; + collapsibleOption: Writable; + lockedOption: Writable; + editableOption: Writable; + d3ZoomParameters: Writable<{ + [key: string]: number; + }>; + resizableOption: Writable; + highlightEdgesOption: Writable; +} + +export interface PositionType { + x: number; + y: number; +} + +export interface NodeType { + id: string; + width: number; + height: number; + positionX: number; + positionY: number; + bgColor: string; + data: { html?: any, custom?: { component: any, props?: any, cb?: (e: string, detail: any) => void }, img?: any, label?: string } + canvasId: string; + setPositionFromMovement: Function; + delete: Function; //This is the method to delete the node from the store + setSizeFromMovement: Function; + setExportableData: Function; + borderColor: string; + image: boolean; + src: string; + textColor: string; + borderRadius: number; + childNodes: string[]; + className: string; //This is for custom className for node + clickCallback: Function; // user-supplied callback that executes when the node is clicked +} + +export interface EdgeType { + id: string; + sourceX: number; + sourceY: number; + targetX: number; + targetY: number; + canvasId: string; + label: string; + type: 'straight' | 'smoothstep' | 'step' | 'bezier'; + labelBgColor: string; + labelTextColor: string; + edgeColor: string; + animate: boolean; + noHandle: boolean; + arrow: boolean; + clickCallback: Function; + className: string; + delete: Function; + setExportableData: Function; +} + +export interface PotentialAnchorType { + id: string; + nodeId: string; + callback: Function; // callback is used to calculate positionX, positionY based on parent node's data, and set the anchor position // TODO: rename to something better + positionX: number; + positionY: number; + angle: number; + canvasId: string; + delete: Function; +} + +export interface TemporaryEdgeType { + id: string; + sourcePotentialAnchorId: string; // this will always be set + sourceX: number; + sourceY: number; + targetPotentialAnchorId: string | null; // this will be null until the temporary edge reaches another temporary anchor + targetX: number; + targetY: number; + canvasId: string; + type: string; + edgeColor: string; + createEdge: Function; + createNode: Function; +} diff --git a/frontend/src/lib/components/graph/svelvet/types/README.md b/frontend/src/lib/components/graph/svelvet/types/README.md new file mode 100644 index 0000000000..85773d6efc --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/types/README.md @@ -0,0 +1,3 @@ +# Types + +This folder contains types exported to the user, as decribed in feature: `https://www.svelvet.io/docs/typescript/` diff --git a/frontend/src/lib/components/graph/svelvet/types/index.ts b/frontend/src/lib/components/graph/svelvet/types/index.ts new file mode 100644 index 0000000000..a8e729568e --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/types/index.ts @@ -0,0 +1,3 @@ +// this file exports user types +import type { UserEdgeType, UserNodeType } from './types' +export { UserEdgeType, UserNodeType } diff --git a/frontend/src/lib/components/graph/svelvet/types/types.ts b/frontend/src/lib/components/graph/svelvet/types/types.ts new file mode 100644 index 0000000000..f1d56f980e --- /dev/null +++ b/frontend/src/lib/components/graph/svelvet/types/types.ts @@ -0,0 +1,55 @@ +export interface UserNodeType { + id: string; + width: number; + height: number; + bgColor?: string; + data: { html?: any, custom?: { component: any, props?: any, cb?: (e: string, detail: any) => void }, img?: any } + position: { x: number; y: number }; + borderColor?: string | undefined; + image?: boolean; + src?: string; + textColor?: string; + targetPosition?: 'left' | 'right' | 'top' | 'bottom'; + sourcePosition?: 'left' | 'right' | 'top' | 'bottom'; + borderRadius?: number; + childNodes?: string[]; + className?: string; + clickCallback?: Function; +} + +export interface UserEdgeType { + id: string; + source: string; + target: string; + sourceAnchorCb?: Function; + targetAnchorCb?: Function; + label?: string; + labelBgColor?: string; + labelTextColor?: string; + edgeColor?: string; + type?: 'straight' | 'smoothstep' | 'step' | 'bezier' | undefined; + animate?: boolean; + noHandle?: boolean; + arrow?: boolean; + clickCallback?: Function; + className?: string; +} + +import { findStore } from '../store/controllers/storeApi'; +import { get } from 'svelte/store'; +export function getD3PositionX(canvasId: string) { + const store = findStore(canvasId); + const width = get(store.widthStore); + const x = width / 2 - get(store.d3ZoomParameters).x; // user input is shifted so that x=0, y=0 occurs in the center + return x; +} +export function getD3PositionY(canvasId: string) { + const store = findStore(canvasId); + const height = get(store.heightStore); + const y = height / 2 - get(store.d3ZoomParameters).y; // user input is shifted so that x=0, y=0 occurs in the center + return y; +} +export function getD3Zoom(canvasId: string) { + const store = findStore(canvasId); + return get(store.d3ZoomParameters).k; +} diff --git a/frontend/src/lib/components/graph/util.ts b/frontend/src/lib/components/graph/util.ts index c174b49316..141a301cdd 100644 --- a/frontend/src/lib/components/graph/util.ts +++ b/frontend/src/lib/components/graph/util.ts @@ -1,6 +1,6 @@ export const NODE = { - width: 300, - height: 35, + width: 275, + height: 34, gap: { horizontal: 40, vertical: 50 diff --git a/frontend/src/routes/(root)/(logged)/+layout.svelte b/frontend/src/routes/(root)/(logged)/+layout.svelte index 5a1e7b4b5b..d292b07d0b 100644 --- a/frontend/src/routes/(root)/(logged)/+layout.svelte +++ b/frontend/src/routes/(root)/(logged)/+layout.svelte @@ -29,9 +29,9 @@ goto('/user/login') } - $: if(userSettings && $page.url.hash === USER_SETTINGS_HASH) { + $: if (userSettings && $page.url.hash === USER_SETTINGS_HASH) { userSettings.openDrawer() - } else if(superadminSettings && $page.url.hash === SUPERADMIN_SETTINGS_HASH) { + } else if (superadminSettings && $page.url.hash === SUPERADMIN_SETTINGS_HASH) { superadminSettings.openDrawer() } @@ -87,8 +87,16 @@ ] } + function pathInAppMode(pathname: string | undefined): boolean { + if (!pathname) return false + return ( + pathname.startsWith('/apps') || + pathname.startsWith('/flows/add') || + pathname.startsWith('/flows/edit') + ) + } afterNavigate((n) => { - if (n.to?.url.pathname.startsWith('/apps') && innerWidth >= 768) { + if (pathInAppMode(n.to?.url.pathname) && innerWidth >= 768) { isCollapsed = true } }) @@ -98,10 +106,7 @@ function changeCollapsed() { if (innerWidth < 1248 && innerWidth >= 768) { isCollapsed = true - } else if ( - (innerWidth >= 1248 || innerWidth < 768) && - !$page.url.pathname.startsWith('/apps') - ) { + } else if ((innerWidth >= 1248 || innerWidth < 768) && !pathInAppMode($page.url.pathname)) { isCollapsed = false } } diff --git a/frontend/src/routes/(root)/(logged)/flows/add/+page.svelte b/frontend/src/routes/(root)/(logged)/flows/add/+page.svelte index 3bccefcfcd..7fb738d19a 100644 --- a/frontend/src/routes/(root)/(logged)/flows/add/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/flows/add/+page.svelte @@ -55,7 +55,7 @@ flow.path = `u/${$userStore?.username}/${oldPath[oldPath.length - 1]}` flow = flow goto('?', { replaceState: true }) - selectedId = 'settings-graph' + selectedId = 'settings-metadata' } else if (hubId) { const hub = await FlowService.getHubFlowById({ id: Number(hubId) }) delete hub['comments'] @@ -63,7 +63,7 @@ Object.assign(flow, hub.flow) flow = flow goto('?', { replaceState: true }) - selectedId = 'settings-graph' + selectedId = 'settings-metadata' } } await initFlow(flow) diff --git a/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte index 5f7f242032..d67070d87f 100644 --- a/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte @@ -20,7 +20,7 @@ let loading = false - let selectedId: string = 'settings-graph' + let selectedId: string = 'settings-metadata' let initialPath: string = '' diff --git a/frontend/src/types.d.ts b/frontend/src/types.d.ts index 4177bf3748..1401dbbccc 100644 --- a/frontend/src/types.d.ts +++ b/frontend/src/types.d.ts @@ -46,7 +46,7 @@ declare module '@windmill-labs/svelte-grid' { default: { item: ItemLayout; dataItem: Item & { data: AppComponent } } } - export default class Grid extends SvelteComponentTyped, {}, Slots> {} + export default class Grid extends SvelteComponentTyped, {}, Slots> { } } declare module '@windmill-labs/svelte-grid/build/helper/index.mjs' { diff --git a/frontend/tailwind.config.cjs b/frontend/tailwind.config.cjs index 3a73000dc6..bbaa454116 100644 --- a/frontend/tailwind.config.cjs +++ b/frontend/tailwind.config.cjs @@ -50,6 +50,7 @@ const config = { orange: { 100: '#ffedd5', 200: '#ffedd5', + 300: '#FDC089', 400: '#fb923c', 500: '#f97316', 600: '#ea580c', @@ -249,7 +250,7 @@ const config = { a: { color: theme('colors.blue.500') }, - 'input,input[type="text"],input[type="email"],input[type="url"],input[type="password"],input[type="number"],input[type="date"],input[type="datetime-local"],input[type="month"],input[type="search"],input[type="tel"],input[type="time"],input[type="week"],textarea:not(.monaco-mouse-cursor-text),select': + 'input:not(.windmillapp),input[type="text"]:not(.windmillapp),input[type="email"]:not(.windmillapp),input[type="url"]:not(.windmillapp),input[type="password"]:not(.windmillapp),input[type="number"]:not(.windmillapp),input[type="date"]:not(.windmillapp),input[type="datetime-local"]:not(.windmillapp),input[type="month"]:not(.windmillapp),input[type="search"]:not(.windmillapp),input[type="tel"]:not(.windmillapp),input[type="time"]:not(.windmillapp),input[type="week"]:not(.windmillapp),textarea:not(.windmillapp):not(.monaco-mouse-cursor-text),select:not(.windmillapp)': { display: 'block', fontSize: theme('fontSize.sm'),