Compare commits
183 Commits
a99040f42e
...
v0.0.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
f8a2a95bc1
|
|||
|
c9dd143916
|
|||
|
898dd49aee
|
|||
|
9fb69d760f
|
|||
|
bafbcca2b8
|
|||
|
8ad9e5535c
|
|||
|
|
43a3c54838 | ||
|
11eaeb719b
|
|||
|
74c2978cd1
|
|||
|
4fdc247904
|
|||
|
c3f8b4b5aa
|
|||
|
67591c0572
|
|||
|
de1f9d6ab6
|
|||
|
6acce72fb8
|
|||
|
cf8943b205
|
|||
|
9e03d36482
|
|||
|
fd7268d620
|
|||
|
6358c22a85
|
|||
|
655b6a18b2
|
|||
|
37b2bdc8bd
|
|||
|
94e01d4ea8
|
|||
|
35f5177884
|
|||
|
ac2c61f221
|
|||
|
ef3d46279f
|
|||
|
703da324fa
|
|||
|
1dae472253
|
|||
|
09fdfb88cd
|
|||
|
04b63cc7e2
|
|||
|
cb6a35606d
|
|||
|
9c9f3ba3b7
|
|||
|
08dda2b2cb
|
|||
|
059129a738
|
|||
|
437c9f4a25
|
|||
|
48bf447ce1
|
|||
|
548fa4f0a1
|
|||
|
|
642cca30ad | ||
|
|
419249aca3 | ||
|
c69cb94ac7
|
|||
|
|
4b652d885f | ||
|
381f784775
|
|||
| 91866b4e9a | |||
|
01f1568221
|
|||
|
3e8d2768b3
|
|||
|
16a832779a
|
|||
|
d582915842
|
|||
|
|
caaecd7a02 | ||
|
93ca436412
|
|||
|
ecdb986a96
|
|||
|
304abf2866
|
|||
|
a547d86946
|
|||
|
667d140883
|
|||
|
0ac65fd7a7
|
|||
|
|
5437e062e1
|
||
|
|
1015d17afb
|
||
|
|
fd8e5e92d2
|
||
| a2c2503a8e | |||
|
|
e18f75e1b8
|
||
|
|
6a178dc3a7
|
||
|
|
76cdfee018
|
||
|
|
b19da950a6
|
||
|
|
89e4cf8364
|
||
|
|
a28f15c256
|
||
|
|
57e3a707c5
|
||
|
|
dced7db3ad
|
||
|
|
c2dc538c05
|
||
|
|
9484b3599e
|
||
|
|
3c168aa9b6
|
||
|
|
812099c55d
|
||
|
|
025921aeab
|
||
|
|
abaf5245d3
|
||
|
|
a53cee2d5c
|
||
|
|
7d91e53704
|
||
|
|
18db3cb9f2
|
||
|
|
b6d3269478
|
||
| 7d18c10007 | |||
|
|
6f33cdf066
|
||
|
|
30e897468a
|
||
|
|
137425b31b
|
||
|
|
5570d975f5 | ||
|
|
8c1ba2ee65 | ||
|
|
3e019e4e21 | ||
|
|
a58b19e935 | ||
|
|
6f5c5bb46e
|
||
|
7f2214f15c
|
|||
|
43ef563ae7
|
|||
|
|
714d01da94 | ||
|
|
92308fc43a | ||
|
|
5adf67ed52 | ||
|
|
f54cde734e | ||
| 70d8095869 | |||
|
|
2a90d5de3f | ||
|
d7e9e8b8de
|
|||
|
bdbaab25a4
|
|||
|
|
c7bfb0f05b | ||
|
|
d3a46af4c2 | ||
|
4c76c62a3e
|
|||
|
36cf9211d2
|
|||
|
97a2ffb683
|
|||
|
fffa8c7cdf
|
|||
| de799c2d55 | |||
| 24bef0460c | |||
|
93b64fc7dd
|
|||
|
64ac28f60c
|
|||
|
bd0c2eaacd
|
|||
|
8693c63d16
|
|||
| fbd82bbdfa | |||
| 63997ec262 | |||
|
a3d10d6094
|
|||
|
|
6b6038e546 | ||
|
|
3e3d41ae98 | ||
|
|
a8c76a846e | ||
|
f98b90dcd3
|
|||
|
1ea7d6629f
|
|||
|
617dfb0c9d
|
|||
|
|
c46bf9e64f | ||
|
|
0cfd1e5c96 | ||
|
|
ecfd4d5f2f | ||
|
|
03102fdc75 | ||
|
|
0bd00b0192 | ||
|
|
edbc71ed8f | ||
|
|
4485cef82b | ||
| cdef71265e | |||
|
8e5412c25c
|
|||
|
2904c13c41
|
|||
|
450262b4ae
|
|||
|
11de746c01
|
|||
|
83cb2bd950
|
|||
| e84c715f4c | |||
| f5cea555cd | |||
|
|
ecbcc814ed
|
||
|
|
be97387252
|
||
|
|
987ece2a4b
|
||
|
|
8d2e3f006b
|
||
|
|
80d3e117b4
|
||
|
|
8a540522dd
|
||
|
|
a11214072f
|
||
|
d068828b68
|
|||
|
3565a18364
|
|||
|
73be4fdd73
|
|||
|
702c3ee6cf
|
|||
|
98672eb702
|
|||
|
3eafdc50b1
|
|||
|
|
548e445eb7
|
||
| db77a4fd94 | |||
|
|
7ae1fae3b9
|
||
|
1126cf8f9f
|
|||
|
|
ef479d0557
|
||
|
|
a1c926c3cf
|
||
|
ca8b1e15ac
|
|||
|
4878d02705
|
|||
|
2b4c81f557
|
|||
|
d178f812fb
|
|||
|
669a2c7991
|
|||
|
becd7a1eb3
|
|||
|
d140f42468
|
|||
|
be835e5cff
|
|||
|
|
6229becfd8
|
||
|
|
af944cefaa
|
||
|
|
a1ea56093c
|
||
|
|
1850e21810
|
||
|
|
7e51cc5ea1
|
||
|
|
1ea544e765
|
||
|
e5658b8a7e
|
|||
|
d3a9b3f056
|
|||
|
0894141d3e
|
|||
|
925167d9f2
|
|||
|
|
9c4554a1f0
|
||
|
|
67a104ff84
|
||
|
|
1212c28152
|
||
|
|
cfcb447784
|
||
|
|
d64877666b
|
||
|
|
0fa1b64d49
|
||
|
|
6ca1ff2a34
|
||
|
|
716df245ab
|
||
|
|
2e76202c63
|
||
|
|
7818148b12
|
||
|
|
566b287550
|
||
|
|
62d3f58d86
|
||
|
|
c868818ba2
|
||
|
|
64ea7ac349
|
||
|
|
2dcd797762
|
||
| 05b192e7ab | |||
|
edcaab4bd4
|
56
.dprint.jsonc
Normal file
56
.dprint.jsonc
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://dprint.dev/schemas/v0.json",
|
||||||
|
"indentWidth": 2,
|
||||||
|
"lineWidth": 100,
|
||||||
|
"typescript": {
|
||||||
|
// https://dprint.dev/plugins/typescript/config/
|
||||||
|
"quoteStyle": "preferSingle",
|
||||||
|
"trailingCommas": "never",
|
||||||
|
},
|
||||||
|
"json": {
|
||||||
|
// https://dprint.dev/plugins/json/config/
|
||||||
|
},
|
||||||
|
"markdown": {},
|
||||||
|
"toml": {},
|
||||||
|
"dockerfile": {},
|
||||||
|
"markup": {
|
||||||
|
// https://dprint.dev/plugins/markup_fmt/config/
|
||||||
|
"scriptIndent": true,
|
||||||
|
"styleIndent": true,
|
||||||
|
},
|
||||||
|
"yaml": {},
|
||||||
|
"exec": {
|
||||||
|
"cwd": "${configDir}",
|
||||||
|
"commands": [
|
||||||
|
{
|
||||||
|
"command": "rustfmt",
|
||||||
|
"exts": [
|
||||||
|
"rs",
|
||||||
|
],
|
||||||
|
"cacheKeyFiles": [
|
||||||
|
"rustfmt.toml",
|
||||||
|
"rust-toolchain.toml",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"excludes": [
|
||||||
|
"**/node_modules",
|
||||||
|
"**/build",
|
||||||
|
"**/.svelte-kit",
|
||||||
|
"**/package",
|
||||||
|
"**/*-lock.yaml",
|
||||||
|
"**/yaml.lock",
|
||||||
|
"**/.DS_Store",
|
||||||
|
],
|
||||||
|
"plugins": [
|
||||||
|
"https://plugins.dprint.dev/typescript-0.95.13.wasm",
|
||||||
|
"https://plugins.dprint.dev/json-0.21.1.wasm",
|
||||||
|
"https://plugins.dprint.dev/markdown-0.20.0.wasm",
|
||||||
|
"https://plugins.dprint.dev/toml-0.7.0.wasm",
|
||||||
|
"https://plugins.dprint.dev/dockerfile-0.3.3.wasm",
|
||||||
|
"https://plugins.dprint.dev/g-plane/markup_fmt-v0.25.3.wasm",
|
||||||
|
"https://plugins.dprint.dev/g-plane/pretty_yaml-v0.5.1.wasm",
|
||||||
|
"https://plugins.dprint.dev/exec-0.6.0.json@a054130d458f124f9b5c91484833828950723a5af3f8ff2bd1523bd47b83b364",
|
||||||
|
],
|
||||||
|
}
|
||||||
472
.gitea/graphics/nodes.svg
Normal file
472
.gitea/graphics/nodes.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 39 KiB |
43
.gitea/scripts/build.sh
Executable file
43
.gitea/scripts/build.sh
Executable file
@@ -0,0 +1,43 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
mkdir -p app/static
|
||||||
|
|
||||||
|
cp CHANGELOG.md app/static/CHANGELOG.md
|
||||||
|
|
||||||
|
# Derive branch/tag info
|
||||||
|
REF_TYPE="${GITHUB_REF_TYPE:-branch}"
|
||||||
|
REF_NAME="${GITHUB_REF_NAME:-$(basename "$GITHUB_REF")}"
|
||||||
|
BRANCH="${GITHUB_HEAD_REF:-}"
|
||||||
|
if [[ -z "$BRANCH" && "$REF_TYPE" == "branch" ]]; then
|
||||||
|
BRANCH="$REF_NAME"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Determine last tag and commits since
|
||||||
|
LAST_TAG="$(git describe --tags --abbrev=0 2>/dev/null || true)"
|
||||||
|
if [[ -n "$LAST_TAG" ]]; then
|
||||||
|
COMMITS_SINCE_LAST_RELEASE="$(git rev-list --count "${LAST_TAG}..HEAD")"
|
||||||
|
else
|
||||||
|
COMMITS_SINCE_LAST_RELEASE="0"
|
||||||
|
fi
|
||||||
|
|
||||||
|
cat >app/static/git.json <<EOF
|
||||||
|
{
|
||||||
|
"ref": "${GITHUB_REF:-}",
|
||||||
|
"ref_name": "${REF_NAME}",
|
||||||
|
"ref_type": "${REF_TYPE}",
|
||||||
|
"sha": "${GITHUB_SHA:-}",
|
||||||
|
"run_number": "${GITHUB_RUN_NUMBER:-}",
|
||||||
|
"event_name": "${GITHUB_EVENT_NAME:-}",
|
||||||
|
"workflow": "${GITHUB_WORKFLOW:-}",
|
||||||
|
"job": "${GITHUB_JOB:-}",
|
||||||
|
"commit_message": "$(git log -1 --pretty=%B)",
|
||||||
|
"commit_timestamp": "$(git log -1 --pretty=%cI)",
|
||||||
|
"branch": "${BRANCH}",
|
||||||
|
"commits_since_last_release": "${COMMITS_SINCE_LAST_RELEASE}"
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
|
||||||
|
pnpm build
|
||||||
|
|
||||||
|
cp -R packages/ui/build app/build/ui
|
||||||
18
.gitea/scripts/ci-checks.sh
Executable file
18
.gitea/scripts/ci-checks.sh
Executable file
@@ -0,0 +1,18 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
pnpm build
|
||||||
|
|
||||||
|
pnpm lint &
|
||||||
|
LINT_PID=$!
|
||||||
|
pnpm format:check &
|
||||||
|
FORMAT_PID=$!
|
||||||
|
pnpm check &
|
||||||
|
TYPE_PID=$!
|
||||||
|
xvfb-run --auto-servernum --server-args="-screen 0 1280x1024x24" pnpm test &
|
||||||
|
TEST_PID=$!
|
||||||
|
|
||||||
|
wait $LINT_PID
|
||||||
|
wait $FORMAT_PID
|
||||||
|
wait $TYPE_PID
|
||||||
|
wait $TEST_PID
|
||||||
91
.gitea/scripts/create-release.sh
Executable file
91
.gitea/scripts/create-release.sh
Executable file
@@ -0,0 +1,91 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
TAG="$GITHUB_REF_NAME"
|
||||||
|
VERSION=$(echo "$TAG" | sed 's/^v//')
|
||||||
|
DATE=$(date +%Y-%m-%d)
|
||||||
|
|
||||||
|
echo "🚀 Creating release for $TAG"
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# 1. Extract release notes from annotated tag
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Ensure the local git knows this is an annotated tag with metadata
|
||||||
|
git fetch origin "refs/tags/$TAG:refs/tags/$TAG" --force
|
||||||
|
|
||||||
|
# %(contents) gets the whole message.
|
||||||
|
# If you want ONLY what you typed after the first line, use %(contents:body)
|
||||||
|
NOTES=$(git tag -l "$TAG" --format='%(contents)')
|
||||||
|
|
||||||
|
if [ -z "$(echo "$NOTES" | tr -d '[:space:]')" ]; then
|
||||||
|
echo "❌ Tag message is empty or tag is not annotated"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
git checkout main
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# 2. Update all package.json versions
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
echo "🔧 Updating package.json versions to $VERSION"
|
||||||
|
find . -name package.json ! -path "*/node_modules/*" | while read -r file; do
|
||||||
|
tmp_file="$file.tmp"
|
||||||
|
jq --arg v "$VERSION" '.version = $v' "$file" >"$tmp_file"
|
||||||
|
mv "$tmp_file" "$file"
|
||||||
|
done
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# 3. Generate commit list since last release
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
LAST_TAG=$(git tag --sort=-creatordate | grep -v "^$TAG$" | head -n 1 || echo "")
|
||||||
|
|
||||||
|
if [ -n "$LAST_TAG" ]; then
|
||||||
|
# Filter out previous 'chore(release)' commits so the list stays clean
|
||||||
|
COMMITS=$(git log "$LAST_TAG"..HEAD --pretty=format:'* [%h](https://git.max-richter.dev/max/nodarium/commit/%H) %s' | grep -v "chore(release)")
|
||||||
|
else
|
||||||
|
COMMITS=$(git log HEAD --pretty=format:'* [%h](https://git.max-richter.dev/max/nodarium/commit/%H) %s' | grep -v "chore(release)")
|
||||||
|
fi
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# 4. Update CHANGELOG.md (prepend)
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
tmp_changelog="CHANGELOG.tmp"
|
||||||
|
{
|
||||||
|
echo "## $TAG ($DATE)"
|
||||||
|
echo ""
|
||||||
|
echo "$NOTES"
|
||||||
|
echo ""
|
||||||
|
if [ -n "$COMMITS" ]; then
|
||||||
|
echo "### All Commits in this version:"
|
||||||
|
echo "$COMMITS"
|
||||||
|
echo ""
|
||||||
|
fi
|
||||||
|
echo "---"
|
||||||
|
echo ""
|
||||||
|
if [ -f CHANGELOG.md ]; then
|
||||||
|
cat CHANGELOG.md
|
||||||
|
fi
|
||||||
|
} >"$tmp_changelog"
|
||||||
|
|
||||||
|
mv "$tmp_changelog" CHANGELOG.md
|
||||||
|
|
||||||
|
pnpm exec dprint fmt CHANGELOG.md
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# 5. Create release commit
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
git config user.name "release-bot"
|
||||||
|
git config user.email "release-bot@ci"
|
||||||
|
|
||||||
|
git add CHANGELOG.md $(find . -name package.json ! -path "*/node_modules/*")
|
||||||
|
|
||||||
|
if git diff --cached --quiet; then
|
||||||
|
echo "No changes to commit for release $TAG"
|
||||||
|
else
|
||||||
|
git commit -m "chore(release): $TAG"
|
||||||
|
git push origin main
|
||||||
|
fi
|
||||||
|
|
||||||
|
cp CHANGELOG.md app/static/CHANGELOG.md
|
||||||
|
echo "✅ Release process for $TAG complete"
|
||||||
43
.gitea/scripts/deploy-files.sh
Executable file
43
.gitea/scripts/deploy-files.sh
Executable file
@@ -0,0 +1,43 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
echo "Configuring rclone"
|
||||||
|
|
||||||
|
KEY_FILE="$(mktemp)"
|
||||||
|
echo "${SSH_PRIVATE_KEY}" >"${KEY_FILE}"
|
||||||
|
chmod 600 "${KEY_FILE}"
|
||||||
|
|
||||||
|
mkdir -p ~/.config/rclone
|
||||||
|
cat >~/.config/rclone/rclone.conf <<EOF
|
||||||
|
[sftp-remote]
|
||||||
|
type = sftp
|
||||||
|
host = ${SSH_HOST}
|
||||||
|
user = ${SSH_USER}
|
||||||
|
port = ${SSH_PORT}
|
||||||
|
key_file = ${KEY_FILE}
|
||||||
|
EOF
|
||||||
|
|
||||||
|
if [[ "${GITHUB_REF_TYPE:-}" == "tag" ]]; then
|
||||||
|
TARGET_DIR="${REMOTE_DIR}"
|
||||||
|
elif [[ "${GITHUB_EVENT_NAME:-}" == "pull_request" ]]; then
|
||||||
|
SAFE_PR_NAME="${GITHUB_HEAD_REF//\//-}"
|
||||||
|
TARGET_DIR="${REMOTE_DIR}_${SAFE_PR_NAME}"
|
||||||
|
elif [[ "${GITHUB_REF_NAME:-}" == "main" ]]; then
|
||||||
|
TARGET_DIR="${REMOTE_DIR}_main"
|
||||||
|
else
|
||||||
|
SAFE_REF="${GITHUB_REF_NAME//\//-}"
|
||||||
|
TARGET_DIR="${REMOTE_DIR}_${SAFE_REF}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Deploying to ${TARGET_DIR}"
|
||||||
|
|
||||||
|
rclone sync \
|
||||||
|
--update \
|
||||||
|
--verbose \
|
||||||
|
--progress \
|
||||||
|
--exclude _astro/** \
|
||||||
|
--stats 2s \
|
||||||
|
--stats-one-line \
|
||||||
|
--transfers 4 \
|
||||||
|
./app/build/ \
|
||||||
|
"sftp-remote:${TARGET_DIR}"
|
||||||
39
.gitea/workflows/build-ci-image.yaml
Normal file
39
.gitea/workflows/build-ci-image.yaml
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
name: Build & Push CI Image
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- "Dockerfile.ci"
|
||||||
|
- ".gitea/workflows/build-ci-image.yaml"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-push:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Docker BuildX
|
||||||
|
uses: docker/setup-buildx-action@v2
|
||||||
|
with:
|
||||||
|
config-inline: |
|
||||||
|
[registry."git.max-richter.dev"]
|
||||||
|
https = true
|
||||||
|
insecure = false
|
||||||
|
|
||||||
|
- name: Login to Gitea Registry
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: git.max-richter.dev
|
||||||
|
username: ${{ gitea.actor }}
|
||||||
|
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
|
||||||
|
- name: Build and Push
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: ./Dockerfile.ci
|
||||||
|
push: true
|
||||||
|
tags: |
|
||||||
|
git.max-richter.dev/${{ gitea.repository }}-ci:latest
|
||||||
|
git.max-richter.dev/${{ gitea.repository }}-ci:${{ github.sha }}
|
||||||
76
.gitea/workflows/release.yaml
Normal file
76
.gitea/workflows/release.yaml
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
name: 🚀 Lint & Test & Deploy
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: ["*"]
|
||||||
|
tags: ["*"]
|
||||||
|
pull_request:
|
||||||
|
branches: ["*"]
|
||||||
|
|
||||||
|
env:
|
||||||
|
PNPM_CACHE_FOLDER: /.pnpm-store
|
||||||
|
CARGO_HOME: /.cargo
|
||||||
|
CARGO_TARGET_DIR: target
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container: git.max-richter.dev/max/nodarium-ci:fd7268d6208aede435e1685817ae6b271c68bd83
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: 📑 Checkout Code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
token: ${{ secrets.GITEA_TOKEN }}
|
||||||
|
|
||||||
|
- name: 💾 Setup pnpm Cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ${{ env.PNPM_CACHE_FOLDER }}
|
||||||
|
key: ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-pnpm-
|
||||||
|
|
||||||
|
- name: 🦀 Cache Cargo
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/registry
|
||||||
|
~/.cargo/git
|
||||||
|
target
|
||||||
|
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-cargo-
|
||||||
|
|
||||||
|
- name: 📦 Install Dependencies
|
||||||
|
run: pnpm install --frozen-lockfile --store-dir ${{ env.PNPM_CACHE_FOLDER }}
|
||||||
|
|
||||||
|
- name: 🧹 Quality Control
|
||||||
|
run: ./.gitea/scripts/ci-checks.sh
|
||||||
|
|
||||||
|
- name: 🛠️ Build
|
||||||
|
run: ./.gitea/scripts/build.sh
|
||||||
|
|
||||||
|
- name: 🚀 Create Release Commit
|
||||||
|
if: gitea.ref_type == 'tag'
|
||||||
|
run: ./.gitea/scripts/create-release.sh
|
||||||
|
|
||||||
|
- name: 🏷️ Create Gitea Release
|
||||||
|
if: gitea.ref_type == 'tag'
|
||||||
|
uses: akkuman/gitea-release-action@v1
|
||||||
|
with:
|
||||||
|
tag_name: ${{ gitea.ref_name }}
|
||||||
|
release_name: Release ${{ gitea.ref_name }}
|
||||||
|
body_path: CHANGELOG.md
|
||||||
|
draft: false
|
||||||
|
prerelease: false
|
||||||
|
|
||||||
|
- name: 🚀 Deploy Changed Files via rclone
|
||||||
|
run: ./.gitea/scripts/deploy-files.sh
|
||||||
|
env:
|
||||||
|
REMOTE_DIR: ${{ vars.REMOTE_DIR }}
|
||||||
|
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||||
|
SSH_HOST: ${{ vars.SSH_HOST }}
|
||||||
|
SSH_PORT: ${{ vars.SSH_PORT }}
|
||||||
|
SSH_USER: ${{ vars.SSH_USER }}
|
||||||
1
.github/graphics/nodes.svg
vendored
1
.github/graphics/nodes.svg
vendored
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 36 KiB |
38
.github/workflows/deploy.yaml
vendored
38
.github/workflows/deploy.yaml
vendored
@@ -1,38 +0,0 @@
|
|||||||
name: Deploy to GitHub Pages
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: 'main'
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build_site:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
container: jimfx/nodes:latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: pnpm install
|
|
||||||
|
|
||||||
- name: build
|
|
||||||
run: pnpm run build:deploy
|
|
||||||
|
|
||||||
- name: 🔑 Configure rclone
|
|
||||||
run: |
|
|
||||||
echo "$SSH_PRIVATE_KEY" > /tmp/id_rsa
|
|
||||||
chmod 600 /tmp/id_rsa
|
|
||||||
mkdir -p ~/.config/rclone
|
|
||||||
echo "[sftp-remote]\ntype = sftp\nhost = ${SSH_HOST}\nuser = ${SSH_USER}\nport = ${SSH_PORT}\nkey_file = /tmp/id_rsa" > ~/.config/rclone/rclone.conf
|
|
||||||
env:
|
|
||||||
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
|
|
||||||
SSH_HOST: ${{ vars.SSH_HOST }}
|
|
||||||
SSH_PORT: ${{ vars.SSH_PORT }}
|
|
||||||
SSH_USER: ${{ vars.SSH_USER }}
|
|
||||||
|
|
||||||
- name: 🚀 Deploy Changed Files via rclone
|
|
||||||
run: |
|
|
||||||
echo "Uploading the rest"
|
|
||||||
rclone sync --update -v --progress --exclude _astro/** --stats 2s --stats-one-line ./app/build/ sftp-remote:${REMOTE_DIR} --transfers 4
|
|
||||||
env:
|
|
||||||
REMOTE_DIR: ${{ vars.REMOTE_DIR }}
|
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -4,3 +4,4 @@ node_modules/
|
|||||||
# Added by cargo
|
# Added by cargo
|
||||||
|
|
||||||
/target
|
/target
|
||||||
|
.direnv/
|
||||||
|
|||||||
13
CHANGELOG.md
Normal file
13
CHANGELOG.md
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
## v0.0.2 (2026-02-04)
|
||||||
|
|
||||||
|
fix(ci): actually deploy on tags
|
||||||
|
fix(app): correctly handle false value in settings
|
||||||
|
-> This caused a bug where random seed could not be false.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## v0.0.1 (2026-02-03)
|
||||||
|
|
||||||
|
chore: format
|
||||||
|
|
||||||
|
---
|
||||||
367
Cargo.lock
generated
367
Cargo.lock
generated
@@ -1,176 +1,80 @@
|
|||||||
# This file is automatically @generated by Cargo.
|
# This file is automatically @generated by Cargo.
|
||||||
# It is not intended for manual editing.
|
# It is not intended for manual editing.
|
||||||
version = 3
|
version = 4
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "autocfg"
|
name = "autocfg"
|
||||||
version = "1.2.0"
|
version = "1.5.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80"
|
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "box"
|
name = "box"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"console_error_panic_hook",
|
|
||||||
"nodarium_macros",
|
"nodarium_macros",
|
||||||
"nodarium_utils",
|
"nodarium_utils",
|
||||||
"serde",
|
|
||||||
"serde-wasm-bindgen",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-test",
|
|
||||||
"web-sys",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "branch"
|
name = "branch"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"console_error_panic_hook",
|
|
||||||
"glam",
|
|
||||||
"nodarium_macros",
|
"nodarium_macros",
|
||||||
"nodarium_utils",
|
"nodarium_utils",
|
||||||
"serde",
|
|
||||||
"serde-wasm-bindgen",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-test",
|
|
||||||
"web-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "bumpalo"
|
|
||||||
version = "3.16.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "cfg-if"
|
|
||||||
version = "1.0.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "console_error_panic_hook"
|
|
||||||
version = "0.1.7"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"wasm-bindgen",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "float"
|
name = "float"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"console_error_panic_hook",
|
|
||||||
"nodarium_macros",
|
"nodarium_macros",
|
||||||
"nodarium_utils",
|
"nodarium_utils",
|
||||||
"serde",
|
|
||||||
"serde-wasm-bindgen",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-test",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "glam"
|
name = "glam"
|
||||||
version = "0.27.0"
|
version = "0.30.10"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9e05e7e6723e3455f4818c7b26e855439f7546cf617ef669d1adedb8669e5cb9"
|
checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "gravity"
|
name = "gravity"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"console_error_panic_hook",
|
|
||||||
"glam",
|
"glam",
|
||||||
"nodarium_macros",
|
"nodarium_macros",
|
||||||
"nodarium_utils",
|
"nodarium_utils",
|
||||||
"noise",
|
]
|
||||||
"serde",
|
|
||||||
"serde-wasm-bindgen",
|
[[package]]
|
||||||
"wasm-bindgen",
|
name = "instance"
|
||||||
"wasm-bindgen-test",
|
version = "0.1.0"
|
||||||
"web-sys",
|
dependencies = [
|
||||||
|
"glam",
|
||||||
|
"nodarium_macros",
|
||||||
|
"nodarium_utils",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "itoa"
|
name = "itoa"
|
||||||
version = "1.0.11"
|
version = "1.0.17"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"
|
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "js-sys"
|
|
||||||
version = "0.3.69"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d"
|
|
||||||
dependencies = [
|
|
||||||
"wasm-bindgen",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "log"
|
|
||||||
version = "0.4.21"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "math"
|
name = "math"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"console_error_panic_hook",
|
|
||||||
"nodarium_macros",
|
"nodarium_macros",
|
||||||
"nodarium_utils",
|
"nodarium_utils",
|
||||||
"serde",
|
|
||||||
"serde-wasm-bindgen",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-test",
|
|
||||||
"web-sys",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "max-plantarium-triangle"
|
name = "memchr"
|
||||||
version = "0.1.0"
|
version = "2.7.6"
|
||||||
dependencies = [
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
"console_error_panic_hook",
|
checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
|
||||||
"nodarium_macros",
|
|
||||||
"nodarium_utils",
|
|
||||||
"serde",
|
|
||||||
"serde-wasm-bindgen",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-test",
|
|
||||||
"web-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "max-plantarium-vec3"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"console_error_panic_hook",
|
|
||||||
"nodarium_macros",
|
|
||||||
"nodarium_utils",
|
|
||||||
"serde",
|
|
||||||
"serde-wasm-bindgen",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-test",
|
|
||||||
"web-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "nodarium_instance"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"console_error_panic_hook",
|
|
||||||
"glam",
|
|
||||||
"nodarium_macros",
|
|
||||||
"nodarium_utils",
|
|
||||||
"serde",
|
|
||||||
"serde-wasm-bindgen",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-test",
|
|
||||||
"web-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nodarium_macros"
|
name = "nodarium_macros"
|
||||||
@@ -180,7 +84,7 @@ dependencies = [
|
|||||||
"quote",
|
"quote",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"syn 1.0.109",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -195,29 +99,19 @@ dependencies = [
|
|||||||
name = "nodarium_utils"
|
name = "nodarium_utils"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"console_error_panic_hook",
|
|
||||||
"glam",
|
"glam",
|
||||||
"noise",
|
"noise 0.9.0",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"wasm-bindgen",
|
|
||||||
"web-sys",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nodes-noise"
|
name = "noise"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"console_error_panic_hook",
|
|
||||||
"glam",
|
|
||||||
"nodarium_macros",
|
"nodarium_macros",
|
||||||
"nodarium_utils",
|
"nodarium_utils",
|
||||||
"noise",
|
"noise 0.9.0",
|
||||||
"serde",
|
|
||||||
"serde-wasm-bindgen",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-test",
|
|
||||||
"web-sys",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -233,48 +127,35 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "num-traits"
|
name = "num-traits"
|
||||||
version = "0.2.18"
|
version = "0.2.19"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a"
|
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"autocfg",
|
"autocfg",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "once_cell"
|
|
||||||
version = "1.19.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "output"
|
name = "output"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"console_error_panic_hook",
|
|
||||||
"glam",
|
|
||||||
"nodarium_macros",
|
"nodarium_macros",
|
||||||
"nodarium_utils",
|
"nodarium_utils",
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-test",
|
|
||||||
"web-sys",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "proc-macro2"
|
name = "proc-macro2"
|
||||||
version = "1.0.81"
|
version = "1.0.105"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba"
|
checksum = "535d180e0ecab6268a3e718bb9fd44db66bbbc256257165fc699dadf70d16fe7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quote"
|
name = "quote"
|
||||||
version = "1.0.36"
|
version = "1.0.43"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7"
|
checksum = "dc74d9a594b72ae6656596548f56f667211f8a97b3d4c3d467150794690dc40a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
]
|
]
|
||||||
@@ -307,103 +188,76 @@ dependencies = [
|
|||||||
name = "random"
|
name = "random"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"console_error_panic_hook",
|
|
||||||
"nodarium_macros",
|
"nodarium_macros",
|
||||||
"nodarium_utils",
|
"nodarium_utils",
|
||||||
"serde",
|
|
||||||
"serde-wasm-bindgen",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-test",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rotate"
|
name = "rotate"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"console_error_panic_hook",
|
|
||||||
"glam",
|
"glam",
|
||||||
"nodarium_macros",
|
"nodarium_macros",
|
||||||
"nodarium_utils",
|
"nodarium_utils",
|
||||||
"serde",
|
"serde",
|
||||||
"serde-wasm-bindgen",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-test",
|
|
||||||
"web-sys",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "ryu"
|
|
||||||
version = "1.0.17"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "scoped-tls"
|
|
||||||
version = "1.0.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde"
|
name = "serde"
|
||||||
version = "1.0.198"
|
version = "1.0.228"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9846a40c979031340571da2545a4e5b7c4163bdae79b301d5f86d03979451fcc"
|
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
|
||||||
|
dependencies = [
|
||||||
|
"serde_core",
|
||||||
|
"serde_derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_core"
|
||||||
|
version = "1.0.228"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_derive",
|
"serde_derive",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde-wasm-bindgen"
|
|
||||||
version = "0.4.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e3b4c031cd0d9014307d82b8abf653c0290fbdaeb4c02d00c63cf52f728628bf"
|
|
||||||
dependencies = [
|
|
||||||
"js-sys",
|
|
||||||
"serde",
|
|
||||||
"wasm-bindgen",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_derive"
|
name = "serde_derive"
|
||||||
version = "1.0.198"
|
version = "1.0.228"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e88edab869b01783ba905e7d0153f9fc1a6505a96e4ad3018011eedb838566d9"
|
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn 2.0.60",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_json"
|
name = "serde_json"
|
||||||
version = "1.0.116"
|
version = "1.0.149"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3e17db7126d17feb94eb3fad46bf1a96b034e8aacbc2e775fe81505f8b0b2813"
|
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"itoa",
|
"itoa",
|
||||||
"ryu",
|
"memchr",
|
||||||
"serde",
|
"serde",
|
||||||
|
"serde_core",
|
||||||
|
"zmij",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "stem"
|
name = "stem"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"console_error_panic_hook",
|
|
||||||
"nodarium_macros",
|
"nodarium_macros",
|
||||||
"nodarium_utils",
|
"nodarium_utils",
|
||||||
"serde",
|
|
||||||
"serde-wasm-bindgen",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-test",
|
|
||||||
"web-sys",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "syn"
|
name = "syn"
|
||||||
version = "1.0.109"
|
version = "2.0.114"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
|
checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
@@ -411,119 +265,30 @@ dependencies = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "syn"
|
name = "triangle"
|
||||||
version = "2.0.60"
|
version = "0.1.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3"
|
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"nodarium_macros",
|
||||||
"quote",
|
"nodarium_utils",
|
||||||
"unicode-ident",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.12"
|
version = "1.0.22"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
|
checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasm-bindgen"
|
name = "vec3"
|
||||||
version = "0.2.92"
|
version = "0.1.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8"
|
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"nodarium_macros",
|
||||||
"wasm-bindgen-macro",
|
"nodarium_utils",
|
||||||
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasm-bindgen-backend"
|
name = "zmij"
|
||||||
version = "0.2.92"
|
version = "1.0.15"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da"
|
checksum = "94f63c051f4fe3c1509da62131a678643c5b6fbdc9273b2b79d4378ebda003d2"
|
||||||
dependencies = [
|
|
||||||
"bumpalo",
|
|
||||||
"log",
|
|
||||||
"once_cell",
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.60",
|
|
||||||
"wasm-bindgen-shared",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasm-bindgen-futures"
|
|
||||||
version = "0.4.42"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"js-sys",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"web-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasm-bindgen-macro"
|
|
||||||
version = "0.2.92"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726"
|
|
||||||
dependencies = [
|
|
||||||
"quote",
|
|
||||||
"wasm-bindgen-macro-support",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasm-bindgen-macro-support"
|
|
||||||
version = "0.2.92"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.60",
|
|
||||||
"wasm-bindgen-backend",
|
|
||||||
"wasm-bindgen-shared",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasm-bindgen-shared"
|
|
||||||
version = "0.2.92"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasm-bindgen-test"
|
|
||||||
version = "0.3.42"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d9bf62a58e0780af3e852044583deee40983e5886da43a271dd772379987667b"
|
|
||||||
dependencies = [
|
|
||||||
"console_error_panic_hook",
|
|
||||||
"js-sys",
|
|
||||||
"scoped-tls",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-futures",
|
|
||||||
"wasm-bindgen-test-macro",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasm-bindgen-test-macro"
|
|
||||||
version = "0.3.42"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b7f89739351a2e03cb94beb799d47fb2cac01759b40ec441f7de39b00cbf7ef0"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.60",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "web-sys"
|
|
||||||
version = "0.3.69"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef"
|
|
||||||
dependencies = [
|
|
||||||
"js-sys",
|
|
||||||
"wasm-bindgen",
|
|
||||||
]
|
|
||||||
|
|||||||
18
Dockerfile
18
Dockerfile
@@ -1,18 +0,0 @@
|
|||||||
FROM node:22
|
|
||||||
|
|
||||||
# IMAGE CUSTOMISATIONS
|
|
||||||
|
|
||||||
# Install rust
|
|
||||||
# https://github.com/rust-lang/rustup/issues/1085
|
|
||||||
RUN RUSTUP_URL="https://sh.rustup.rs" \
|
|
||||||
&& curl --silent --show-error --location --fail --retry 3 --proto '=https' --tlsv1.2 --output /tmp/rustup-linux-install.sh $RUSTUP_URL \
|
|
||||||
&& bash /tmp/rustup-linux-install.sh -y \
|
|
||||||
&& curl https://rclone.org/install.sh --output /tmp/rclone-install.sh \
|
|
||||||
&& bash /tmp/rclone-install.sh
|
|
||||||
|
|
||||||
ENV PATH=/root/.cargo/bin:$PATH
|
|
||||||
|
|
||||||
RUN rustup target add wasm32-unknown-unknown \
|
|
||||||
&& cargo install wasm-pack \
|
|
||||||
&& npm i -g pnpm
|
|
||||||
|
|
||||||
30
Dockerfile.ci
Normal file
30
Dockerfile.ci
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
FROM node:25-bookworm-slim
|
||||||
|
|
||||||
|
ENV RUSTUP_HOME=/usr/local/rustup \
|
||||||
|
CARGO_HOME=/usr/local/cargo \
|
||||||
|
PATH=/usr/local/cargo/bin:$PATH
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y \
|
||||||
|
ca-certificates=20230311+deb12u1 \
|
||||||
|
curl=7.88.1-10+deb12u14 \
|
||||||
|
git=1:2.39.5-0+deb12u3 \
|
||||||
|
jq=1.6-2.1+deb12u1 \
|
||||||
|
g++=4:12.2.0-3 \
|
||||||
|
rclone=1.60.1+dfsg-2+b5 \
|
||||||
|
xvfb=2:21.1.7-3+deb12u11 \
|
||||||
|
xauth=1:1.1.2-1 \
|
||||||
|
--no-install-recommends \
|
||||||
|
# Install Rust
|
||||||
|
&& curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y \
|
||||||
|
--default-toolchain stable \
|
||||||
|
--profile minimal \
|
||||||
|
&& rustup target add wasm32-unknown-unknown \
|
||||||
|
# Setup Playwright
|
||||||
|
&& npm i -g pnpm \
|
||||||
|
&& pnpm dlx playwright install --with-deps firefox \
|
||||||
|
# Final Cleanup
|
||||||
|
&& rm -rf /usr/local/rustup/downloads /usr/local/rustup/tmp \
|
||||||
|
&& rm -rf /usr/local/cargo/registry/index /usr/local/cargo/registry/cache \
|
||||||
|
&& rm -rf /usr/local/rustup/toolchains/*/share/doc \
|
||||||
|
&& apt-get purge -y --auto-remove \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
35
README.md
35
README.md
@@ -2,17 +2,17 @@ Nodarium
|
|||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
<a href="https://nodes.max-richter.dev/"><h2 align="center">Nodarium</h2></a>
|
<a href="https://nodes.max-richter.dev/"><h2 align="center">Nodarium</h2></a>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
Nodarium is a WebAssembly based visual programming language.
|
Nodarium is a WebAssembly based visual programming language.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<img src=".github/graphics/nodes.svg" width="80%"/>
|
<img src=".gitea/graphics/nodes.svg" width="80%"/>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
Currently this visual programming language is used to develop https://nodes.max-richter.dev, a procedural modelling tool for 3d-plants.
|
Currently this visual programming language is used to develop <https://nodes.max-richter.dev>, a procedural modelling tool for 3d-plants.
|
||||||
|
|
||||||
# Table of contents
|
# Table of contents
|
||||||
|
|
||||||
@@ -22,7 +22,7 @@ Currently this visual programming language is used to develop https://nodes.max-
|
|||||||
|
|
||||||
# Developing
|
# Developing
|
||||||
|
|
||||||
### Install prerequisites:
|
### Install prerequisites
|
||||||
|
|
||||||
- [Node.js](https://nodejs.org/en/download)
|
- [Node.js](https://nodejs.org/en/download)
|
||||||
- [pnpm](https://pnpm.io/installation)
|
- [pnpm](https://pnpm.io/installation)
|
||||||
@@ -50,4 +50,29 @@ pnpm dev
|
|||||||
|
|
||||||
### [Now you can create your first node 🤓](./docs/DEVELOPING_NODES.md)
|
### [Now you can create your first node 🤓](./docs/DEVELOPING_NODES.md)
|
||||||
|
|
||||||
|
# Releasing
|
||||||
|
|
||||||
|
## Creating a Release
|
||||||
|
|
||||||
|
1. **Create an annotated tag** with your release notes:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git tag -a v1.0.0 -m "Release notes for this version"
|
||||||
|
git push origin v1.0.0
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **The CI workflow will:**
|
||||||
|
- Run lint, format check, and type check
|
||||||
|
- Build the project
|
||||||
|
- Update all `package.json` versions to match the tag
|
||||||
|
- Generate/update `CHANGELOG.md`
|
||||||
|
- Create a release commit on `main`
|
||||||
|
- Publish a Gitea release
|
||||||
|
|
||||||
|
## Version Requirements
|
||||||
|
|
||||||
|
- Tag must match pattern `v*` (e.g., `v1.0.0`, `v2.3.1`)
|
||||||
|
- Tag message must not be empty (annotated tag required)
|
||||||
|
- Tag must be pushed from `main` branch
|
||||||
|
|
||||||
# Roadmap
|
# Roadmap
|
||||||
|
|||||||
2
app/.gitignore
vendored
2
app/.gitignore
vendored
@@ -27,3 +27,5 @@ dist-ssr
|
|||||||
*.sln
|
*.sln
|
||||||
*.sw?
|
*.sw?
|
||||||
build/
|
build/
|
||||||
|
|
||||||
|
test-results/
|
||||||
|
|||||||
32
app/Dockerfile
Normal file
32
app/Dockerfile
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
FROM jimfx/nodes:latest AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json Cargo.lock Cargo.toml ./
|
||||||
|
|
||||||
|
COPY packages/ ./packages/
|
||||||
|
COPY nodes/ ./nodes/
|
||||||
|
COPY app/package.json ./app/
|
||||||
|
|
||||||
|
RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
|
||||||
|
--mount=type=cache,target=/usr/local/cargo/registry \
|
||||||
|
--mount=type=cache,target=/app/target \
|
||||||
|
pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
|
||||||
|
--mount=type=cache,target=/usr/local/cargo/registry \
|
||||||
|
--mount=type=cache,target=/app/target \
|
||||||
|
pnpm build:nodes && \
|
||||||
|
pnpm --filter @nodarium/app... build
|
||||||
|
|
||||||
|
FROM nginx:alpine AS runner
|
||||||
|
|
||||||
|
RUN rm /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
COPY app/docker/app.conf /etc/nginx/conf.d/app.conf
|
||||||
|
|
||||||
|
COPY --from=builder /app/app/build /app
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
@@ -1,7 +1 @@
|
|||||||
# Tauri + Svelte + Typescript
|
# Nodarium App
|
||||||
|
|
||||||
This template should help get you started developing with Tauri, Svelte and TypeScript in Vite.
|
|
||||||
|
|
||||||
## Recommended IDE Setup
|
|
||||||
|
|
||||||
[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer).
|
|
||||||
|
|||||||
10
app/docker/app.conf
Normal file
10
app/docker/app.conf
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
root /app;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files \$uri \$uri/ /index.html;
|
||||||
|
}
|
||||||
|
}
|
||||||
62
app/e2e/main.test.ts
Normal file
62
app/e2e/main.test.ts
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import { expect, test } from '@playwright/test';
|
||||||
|
|
||||||
|
test('test', async ({ page }) => {
|
||||||
|
// Listen for console messages
|
||||||
|
page.on('console', msg => {
|
||||||
|
console.log(`[Browser Console] ${msg.type()}: ${msg.text()}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.goto('http://localhost:4173', { waitUntil: 'load' });
|
||||||
|
|
||||||
|
// await expect(page).toHaveScreenshot();
|
||||||
|
await expect(page.locator('.graph-wrapper')).toHaveScreenshot();
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: 'projects' }).click();
|
||||||
|
await page.getByRole('button', { name: 'New', exact: true }).click();
|
||||||
|
await page.getByRole('combobox').selectOption('2');
|
||||||
|
await page.getByRole('textbox', { name: 'Project name' }).click();
|
||||||
|
await page.getByRole('textbox', { name: 'Project name' }).fill('Test Project');
|
||||||
|
await page.getByRole('button', { name: 'Create' }).click();
|
||||||
|
|
||||||
|
const expectedNodes = [
|
||||||
|
{
|
||||||
|
id: '10',
|
||||||
|
type: 'max/plantarium/stem',
|
||||||
|
props: {
|
||||||
|
amount: 50,
|
||||||
|
length: 4,
|
||||||
|
thickness: 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '11',
|
||||||
|
type: 'max/plantarium/noise',
|
||||||
|
props: {
|
||||||
|
scale: 0.5,
|
||||||
|
strength: 5
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '9',
|
||||||
|
type: 'max/plantarium/output'
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const node of expectedNodes) {
|
||||||
|
const wrapper = page.locator(
|
||||||
|
`div.wrapper[data-node-id="${node.id}"][data-node-type="${node.type}"]`
|
||||||
|
);
|
||||||
|
await expect(wrapper).toBeVisible();
|
||||||
|
if ('props' in node) {
|
||||||
|
const props = node.props as unknown as Record<string, number>;
|
||||||
|
for (const propId in node.props) {
|
||||||
|
const expectedValue = props[propId];
|
||||||
|
const inputElement = page.locator(
|
||||||
|
`div.wrapper[data-node-type="${node.type}"][data-node-input="${propId}"] input[type="number"]`
|
||||||
|
);
|
||||||
|
const value = parseFloat(await inputElement.inputValue());
|
||||||
|
expect(value).toBe(expectedValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
BIN
app/e2e/main.test.ts-snapshots/test-1-linux.png
Normal file
BIN
app/e2e/main.test.ts-snapshots/test-1-linux.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 42 KiB |
37
app/eslint.config.mjs
Normal file
37
app/eslint.config.mjs
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { includeIgnoreFile } from '@eslint/compat';
|
||||||
|
import js from '@eslint/js';
|
||||||
|
import svelte from 'eslint-plugin-svelte';
|
||||||
|
import { defineConfig } from 'eslint/config';
|
||||||
|
import globals from 'globals';
|
||||||
|
import path from 'node:path';
|
||||||
|
import ts from 'typescript-eslint';
|
||||||
|
import svelteConfig from './svelte.config.js';
|
||||||
|
|
||||||
|
const gitignorePath = path.resolve(import.meta.dirname, '.gitignore');
|
||||||
|
|
||||||
|
export default defineConfig(
|
||||||
|
includeIgnoreFile(gitignorePath),
|
||||||
|
js.configs.recommended,
|
||||||
|
...ts.configs.recommended,
|
||||||
|
...svelte.configs.recommended,
|
||||||
|
{
|
||||||
|
languageOptions: { globals: { ...globals.browser, ...globals.node } },
|
||||||
|
rules: {
|
||||||
|
// typescript-eslint strongly recommend that you do not use the no-undef lint rule on TypeScript projects.
|
||||||
|
// see: https://typescript-eslint.io/troubleshooting/faqs/eslint/#i-get-errors-from-the-no-undef-rule-about-global-variables-not-being-defined-even-though-there-are-no-typescript-errors
|
||||||
|
'no-undef': 'off'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
projectService: true,
|
||||||
|
extraFileExtensions: ['.svelte'],
|
||||||
|
parser: ts.parser,
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
svelteConfig
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
@@ -1,46 +1,61 @@
|
|||||||
{
|
{
|
||||||
"name": "@nodes/app",
|
"name": "@nodarium/app",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.0",
|
"version": "0.0.3",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite dev",
|
"dev": "vite dev",
|
||||||
"build": "svelte-kit sync && vite build",
|
"build": "svelte-kit sync && vite build",
|
||||||
"test": "vitest",
|
"test:unit": "vitest",
|
||||||
"preview": "vite preview"
|
"test": "npm run test:unit -- --run && npm run test:e2e",
|
||||||
|
"test:e2e": "playwright test",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"format": "dprint fmt -c '../.dprint.jsonc' .",
|
||||||
|
"format:check": "dprint check -c '../.dprint.jsonc' .",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nodes/registry": "link:../packages/registry",
|
"@nodarium/ui": "workspace:*",
|
||||||
"@nodes/ui": "link:../packages/ui",
|
"@nodarium/utils": "workspace:*",
|
||||||
"@nodes/utils": "link:../packages/utils",
|
"@sveltejs/kit": "^2.50.2",
|
||||||
"@sveltejs/kit": "^2.12.2",
|
"@tailwindcss/vite": "^4.1.18",
|
||||||
"@threlte/core": "8.0.0-next.23",
|
"@threlte/core": "8.3.1",
|
||||||
"@threlte/extras": "9.0.0-next.33",
|
"@threlte/extras": "9.7.1",
|
||||||
"@types/three": "^0.171.0",
|
|
||||||
"@unocss/reset": "^0.65.2",
|
|
||||||
"comlink": "^4.4.2",
|
"comlink": "^4.4.2",
|
||||||
"file-saver": "^2.0.5",
|
"file-saver": "^2.0.5",
|
||||||
"idb": "^8.0.1",
|
"idb": "^8.0.3",
|
||||||
"jsondiffpatch": "^0.6.0",
|
"jsondiffpatch": "^0.7.3",
|
||||||
"three": "^0.171.0"
|
"tailwindcss": "^4.1.18",
|
||||||
|
"three": "^0.182.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@iconify-json/tabler": "^1.2.13",
|
"@eslint/compat": "^2.0.2",
|
||||||
"@nodes/types": "link:../packages/types",
|
"@eslint/js": "^9.39.2",
|
||||||
"@sveltejs/adapter-static": "^3.0.6",
|
"@iconify-json/tabler": "^1.2.26",
|
||||||
"@sveltejs/vite-plugin-svelte": "^5.0.3",
|
"@iconify/tailwind4": "^1.2.1",
|
||||||
"@tsconfig/svelte": "^5.0.4",
|
"@nodarium/types": "workspace:^",
|
||||||
|
"@playwright/test": "^1.58.1",
|
||||||
|
"@sveltejs/adapter-static": "^3.0.10",
|
||||||
|
"@sveltejs/vite-plugin-svelte": "^6.2.4",
|
||||||
|
"@tsconfig/svelte": "^5.0.7",
|
||||||
"@types/file-saver": "^2.0.7",
|
"@types/file-saver": "^2.0.7",
|
||||||
"@unocss/preset-icons": "^0.65.2",
|
"@types/three": "^0.182.0",
|
||||||
"svelte": "^5.14.4",
|
"@vitest/browser-playwright": "^4.0.18",
|
||||||
"svelte-check": "^4.1.1",
|
"dprint": "^0.51.1",
|
||||||
|
"eslint": "^9.39.2",
|
||||||
|
"eslint-plugin-svelte": "^3.14.0",
|
||||||
|
"globals": "^17.3.0",
|
||||||
|
"svelte": "^5.49.2",
|
||||||
|
"svelte-check": "^4.3.6",
|
||||||
"tslib": "^2.8.1",
|
"tslib": "^2.8.1",
|
||||||
"typescript": "^5.7.2",
|
"typescript": "^5.9.3",
|
||||||
"unocss": "^0.65.2",
|
"typescript-eslint": "^8.54.0",
|
||||||
"vite": "^6.0.4",
|
"vite": "^7.3.1",
|
||||||
"vite-plugin-comlink": "^5.1.0",
|
"vite-plugin-comlink": "^5.3.0",
|
||||||
"vite-plugin-glsl": "^1.3.1",
|
"vite-plugin-glsl": "^1.5.5",
|
||||||
"vite-plugin-wasm": "^3.3.0",
|
"vite-plugin-wasm": "^3.5.0",
|
||||||
"vitest": "^2.1.8"
|
"vitest": "^4.0.18",
|
||||||
|
"vitest-browser-svelte": "^2.0.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
20
app/playwright.config.ts
Normal file
20
app/playwright.config.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { defineConfig } from '@playwright/test';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
webServer: { command: 'pnpm build && pnpm preview', port: 4173 },
|
||||||
|
testDir: 'e2e',
|
||||||
|
use: {
|
||||||
|
browserName: 'firefox',
|
||||||
|
launchOptions: {
|
||||||
|
firefoxUserPrefs: {
|
||||||
|
// Force WebGL even without a GPU
|
||||||
|
'webgl.force-enabled': true,
|
||||||
|
'webgl.disabled': false,
|
||||||
|
// Use software rendering (Mesa) instead of hardware
|
||||||
|
'layers.acceleration.disabled': true,
|
||||||
|
'gfx.webrender.software': true,
|
||||||
|
'webgl.enable-webgl2': true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
1576
app/pnpm-lock.yaml
generated
1576
app/pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
10
app/src/app.css
Normal file
10
app/src/app.css
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
@source "../../packages/ui/**/*.svelte";
|
||||||
|
@plugin "@iconify/tailwind4" {
|
||||||
|
prefix: "i";
|
||||||
|
icon-sets: from-folder("custom", "./src/lib/icons");
|
||||||
|
}
|
||||||
|
|
||||||
|
body * {
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
14
app/src/app.d.ts
vendored
14
app/src/app.d.ts
vendored
@@ -1,13 +1,13 @@
|
|||||||
// See https://kit.svelte.dev/docs/types#app
|
// See https://kit.svelte.dev/docs/types#app
|
||||||
// for information about these interfaces
|
// for information about these interfaces
|
||||||
declare global {
|
declare global {
|
||||||
namespace App {
|
namespace App {
|
||||||
// interface Error {}
|
// interface Error {}
|
||||||
// interface Locals {}
|
// interface Locals {}
|
||||||
// interface PageData {}
|
// interface PageData {}
|
||||||
// interface PageState {}
|
// interface PageState {}
|
||||||
// interface Platform {}
|
// interface Platform {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export {};
|
export {};
|
||||||
|
|||||||
@@ -1,29 +1,26 @@
|
|||||||
<!doctype html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<link rel="icon" href="%sveltekit.assets%/svelte.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
%sveltekit.head%
|
||||||
|
<title>Nodes</title>
|
||||||
|
<script>
|
||||||
|
var store = localStorage.getItem('node-settings');
|
||||||
|
if (store) {
|
||||||
|
try {
|
||||||
|
var value = JSON.parse(store);
|
||||||
|
var themes = ['dark', 'light', 'catppuccin'];
|
||||||
|
if (themes[value.theme]) {
|
||||||
|
document.documentElement.classList.add('theme-' + themes[value.theme]);
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
|
||||||
<head>
|
<body data-sveltekit-preload-data="hover">
|
||||||
<meta charset="utf-8" />
|
<div style="display: contents">%sveltekit.body%</div>
|
||||||
<link rel="icon" href="%sveltekit.assets%/svelte.svg" />
|
</body>
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
||||||
<script defer src="https://umami.max-richter.dev/script.js" data-website-id="585c442b-0524-4874-8955-f9853b44b17e"></script>
|
|
||||||
%sveltekit.head%
|
|
||||||
<title>Nodes</title>
|
|
||||||
<script>
|
|
||||||
var store = localStorage.getItem("node-settings");
|
|
||||||
if (store) {
|
|
||||||
try {
|
|
||||||
var value = JSON.parse(store);
|
|
||||||
var themes = ["dark", "light", "catppuccin"];
|
|
||||||
if (themes[value.theme]) {
|
|
||||||
document.documentElement.classList.add("theme-" + themes[value.theme]);
|
|
||||||
}
|
|
||||||
} catch (e) { }
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body data-sveltekit-preload-data="hover">
|
|
||||||
<div style="display: contents">%sveltekit.body%</div>
|
|
||||||
</body>
|
|
||||||
|
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
2
app/src/lib/config.ts
Normal file
2
app/src/lib/config.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
import { PUBLIC_ANALYTIC_SCRIPT } from '$env/static/public';
|
||||||
|
export const ANALYTIC_SCRIPT = PUBLIC_ANALYTIC_SCRIPT;
|
||||||
@@ -1,168 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import type { GraphManager } from "./graph-manager.js";
|
|
||||||
import { HTML } from "@threlte/extras";
|
|
||||||
import { onMount } from "svelte";
|
|
||||||
|
|
||||||
export let position: [x: number, y: number] | null;
|
|
||||||
|
|
||||||
export let graph: GraphManager;
|
|
||||||
|
|
||||||
let input: HTMLInputElement;
|
|
||||||
let value: string = "";
|
|
||||||
let activeNodeId: string = "";
|
|
||||||
|
|
||||||
const allNodes = graph.getNodeDefinitions();
|
|
||||||
|
|
||||||
function filterNodes() {
|
|
||||||
return allNodes.filter((node) => node.id.includes(value));
|
|
||||||
}
|
|
||||||
|
|
||||||
$: nodes = value === "" ? allNodes : filterNodes();
|
|
||||||
$: if (nodes) {
|
|
||||||
if (activeNodeId === "") {
|
|
||||||
activeNodeId = nodes[0].id;
|
|
||||||
} else if (nodes.length) {
|
|
||||||
const node = nodes.find((node) => node.id === activeNodeId);
|
|
||||||
if (!node) {
|
|
||||||
activeNodeId = nodes[0].id;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleKeyDown(event: KeyboardEvent) {
|
|
||||||
event.stopImmediatePropagation();
|
|
||||||
|
|
||||||
if (event.key === "Escape") {
|
|
||||||
position = null;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.key === "ArrowDown") {
|
|
||||||
const index = nodes.findIndex((node) => node.id === activeNodeId);
|
|
||||||
activeNodeId = nodes[(index + 1) % nodes.length].id;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.key === "ArrowUp") {
|
|
||||||
const index = nodes.findIndex((node) => node.id === activeNodeId);
|
|
||||||
activeNodeId = nodes[(index - 1 + nodes.length) % nodes.length].id;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.key === "Enter") {
|
|
||||||
if (activeNodeId && position) {
|
|
||||||
graph.createNode({ type: activeNodeId, position });
|
|
||||||
position = null;
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onMount(() => {
|
|
||||||
input.disabled = false;
|
|
||||||
setTimeout(() => input.focus(), 50);
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<HTML position.x={position?.[0]} position.z={position?.[1]} transform={false}>
|
|
||||||
<div class="add-menu-wrapper">
|
|
||||||
<div class="header">
|
|
||||||
<input
|
|
||||||
id="add-menu"
|
|
||||||
type="text"
|
|
||||||
aria-label="Search for a node type"
|
|
||||||
role="searchbox"
|
|
||||||
placeholder="Search..."
|
|
||||||
disabled={false}
|
|
||||||
on:keydown={handleKeyDown}
|
|
||||||
bind:value
|
|
||||||
bind:this={input}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="content">
|
|
||||||
{#each nodes as node}
|
|
||||||
<div
|
|
||||||
class="result"
|
|
||||||
role="treeitem"
|
|
||||||
tabindex="0"
|
|
||||||
aria-selected={node.id === activeNodeId}
|
|
||||||
on:keydown={(event) => {
|
|
||||||
if (event.key === "Enter") {
|
|
||||||
if (position) {
|
|
||||||
graph.createNode({ type: node.id, position, props: {} });
|
|
||||||
position = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
on:mousedown={() => {
|
|
||||||
if (position) {
|
|
||||||
graph.createNode({ type: node.id, position, props: {} });
|
|
||||||
position = null;
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
on:focus={() => {
|
|
||||||
activeNodeId = node.id;
|
|
||||||
}}
|
|
||||||
class:selected={node.id === activeNodeId}
|
|
||||||
on:mouseover={() => {
|
|
||||||
activeNodeId = node.id;
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{node.id.split("/").at(-1)}
|
|
||||||
</div>
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</HTML>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.header {
|
|
||||||
padding: 5px;
|
|
||||||
}
|
|
||||||
|
|
||||||
input {
|
|
||||||
background: var(--layer-0);
|
|
||||||
font-family: var(--font-family);
|
|
||||||
border: none;
|
|
||||||
border-radius: 5px;
|
|
||||||
color: var(--text-color);
|
|
||||||
padding: 0.6em;
|
|
||||||
width: calc(100% - 2px);
|
|
||||||
box-sizing: border-box;
|
|
||||||
font-size: 0.8em;
|
|
||||||
margin-left: 1px;
|
|
||||||
margin-top: 1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
input:focus {
|
|
||||||
outline: solid 2px rgba(255, 255, 255, 0.2);
|
|
||||||
}
|
|
||||||
|
|
||||||
.add-menu-wrapper {
|
|
||||||
position: absolute;
|
|
||||||
background: var(--layer-1);
|
|
||||||
border-radius: 7px;
|
|
||||||
overflow: hidden;
|
|
||||||
border: solid 2px var(--layer-2);
|
|
||||||
width: 150px;
|
|
||||||
}
|
|
||||||
.content {
|
|
||||||
min-height: none;
|
|
||||||
width: 100%;
|
|
||||||
color: var(--text-color);
|
|
||||||
}
|
|
||||||
|
|
||||||
.result {
|
|
||||||
padding: 1em 0.9em;
|
|
||||||
border-bottom: solid 1px var(--layer-2);
|
|
||||||
opacity: 0.7;
|
|
||||||
font-size: 0.9em;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.result[aria-selected="true"] {
|
|
||||||
background: var(--layer-2);
|
|
||||||
opacity: 1;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
precision highp float;
|
precision highp float;
|
||||||
|
// For WebGL1 make sure this extension is enabled in your material:
|
||||||
|
// #extension GL_OES_standard_derivatives : enable
|
||||||
|
|
||||||
varying vec2 vUv;
|
varying vec2 vUv;
|
||||||
|
|
||||||
@@ -10,33 +12,45 @@ uniform vec2 zoomLimits;
|
|||||||
uniform vec3 backgroundColor;
|
uniform vec3 backgroundColor;
|
||||||
uniform vec3 lineColor;
|
uniform vec3 lineColor;
|
||||||
|
|
||||||
|
// Anti-aliased step: threshold in the same units as `value`
|
||||||
|
float aaStep(float threshold, float value, float deriv) {
|
||||||
|
float w = deriv * 0.5; // ~one pixel
|
||||||
|
return smoothstep(threshold - w, threshold + w, value);
|
||||||
|
}
|
||||||
|
|
||||||
float grid(float x, float y, float divisions, float thickness) {
|
float grid(float x, float y, float divisions, float thickness) {
|
||||||
x = fract(x * divisions);
|
// Continuous grid coordinates
|
||||||
x = min(x, 1.0 - x);
|
float gx = x * divisions;
|
||||||
|
float gy = y * divisions;
|
||||||
|
|
||||||
float xdelta = fwidth(x);
|
// Distance to nearest grid line (0 at the line)
|
||||||
x = smoothstep(x - xdelta, x + xdelta, thickness);
|
float fx = fract(gx);
|
||||||
|
fx = min(fx, 1.0 - fx);
|
||||||
|
float fy = fract(gy);
|
||||||
|
fy = min(fy, 1.0 - fy);
|
||||||
|
|
||||||
y = fract(y * divisions);
|
// Derivatives in screen space – use the continuous coords here
|
||||||
y = min(y, 1.0 - y);
|
float dx = fwidth(gx);
|
||||||
|
float dy = fwidth(gy);
|
||||||
|
|
||||||
float ydelta = fwidth(y);
|
// Keep the original semantics: thickness is the threshold in the [0, 0.5] distance domain
|
||||||
y = smoothstep(y - ydelta, y + ydelta, thickness);
|
float lineX = 1.0 - aaStep(thickness, fx, dx);
|
||||||
|
float lineY = 1.0 - aaStep(thickness, fy, dy);
|
||||||
|
|
||||||
return clamp(x + y, 0.0, 1.0);
|
return clamp(lineX + lineY, 0.0, 1.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
float circle_grid(float x, float y, float divisions, float circleRadius) {
|
float circle_grid(float x, float y, float divisions, float circleRadius) {
|
||||||
|
float gridX = mod(x + divisions * 0.5, divisions) - divisions * 0.5;
|
||||||
|
float gridY = mod(y + divisions * 0.5, divisions) - divisions * 0.5;
|
||||||
|
|
||||||
float gridX = mod(x + divisions/2.0, divisions) - divisions / 2.0;
|
vec2 g = vec2(gridX, gridY);
|
||||||
float gridY = mod(y + divisions/2.0, divisions) - divisions / 2.0;
|
float d = length(g);
|
||||||
|
|
||||||
// Calculate the distance from the center of the grid
|
// Screen-space derivative for AA on the circle edge
|
||||||
float gridDistance = length(vec2(gridX, gridY));
|
float w = fwidth(d);
|
||||||
|
|
||||||
// Use smoothstep to create a smooth transition at the edges of the circle
|
|
||||||
float circle = 1.0 - smoothstep(circleRadius - 0.5, circleRadius + 0.5, gridDistance);
|
|
||||||
|
|
||||||
|
float circle = 1.0 - smoothstep(circleRadius - w, circleRadius + w, d);
|
||||||
return circle;
|
return circle;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,44 +70,43 @@ void main(void) {
|
|||||||
float minZ = zoomLimits.x;
|
float minZ = zoomLimits.x;
|
||||||
float maxZ = zoomLimits.y;
|
float maxZ = zoomLimits.y;
|
||||||
|
|
||||||
float divisions = 0.1/cz;
|
float divisions = 0.1 / cz;
|
||||||
float thickness = 0.05/cz;
|
float thickness = 0.05 / cz;
|
||||||
float delta = 0.1 / 2.0;
|
|
||||||
|
|
||||||
float nz = (cz - minZ) / (maxZ - minZ);
|
float nz = (cz - minZ) / (maxZ - minZ);
|
||||||
|
|
||||||
float ux = (vUv.x-0.5) * width + cx*cz;
|
float ux = (vUv.x - 0.5) * width + cx * cz;
|
||||||
float uy = (vUv.y-0.5) * height - cy*cz;
|
float uy = (vUv.y - 0.5) * height - cy * cz;
|
||||||
|
|
||||||
|
// extra small grid
|
||||||
//extra small grid
|
float m1 = grid(ux, uy, divisions * 4.0, thickness * 4.0) * 0.9;
|
||||||
float m1 = grid(ux, uy, divisions*4.0, thickness*4.0) * 0.9;
|
float m2 = grid(ux, uy, divisions * 16.0, thickness * 16.0) * 0.5;
|
||||||
float m2 = grid(ux, uy, divisions*16.0, thickness*16.0) * 0.5;
|
|
||||||
float xsmall = max(m1, m2);
|
float xsmall = max(m1, m2);
|
||||||
|
|
||||||
float s3 = circle_grid(ux, uy, cz/1.6, 1.0) * 0.5;
|
float s3 = circle_grid(ux, uy, cz / 1.6, 1.0) * 0.5;
|
||||||
xsmall = max(xsmall, s3);
|
xsmall = max(xsmall, s3);
|
||||||
|
|
||||||
// small grid
|
// small grid
|
||||||
float c1 = grid(ux, uy, divisions, thickness) * 0.6;
|
float c1 = grid(ux, uy, divisions, thickness) * 0.6;
|
||||||
float c2 = grid(ux, uy, divisions*2.0, thickness) * 0.5;
|
float c2 = grid(ux, uy, divisions * 2.0, thickness * 2.0) * 0.5;
|
||||||
float small = max(c1, c2);
|
float small = max(c1, c2);
|
||||||
|
|
||||||
float s1 = circle_grid(ux, uy, cz*10.0, 2.0) * 0.5;
|
float s1 = circle_grid(ux, uy, cz * 10.0, 2.0) * 0.5;
|
||||||
small = max(small, s1);
|
small = max(small, s1);
|
||||||
|
|
||||||
// large grid
|
// large grid
|
||||||
float c3 = grid(ux, uy, divisions/8.0, thickness/8.0) * 0.5;
|
float c3 = grid(ux, uy, divisions / 8.0, thickness / 8.0) * 0.5;
|
||||||
float c4 = grid(ux, uy, divisions/2.0, thickness/4.0) * 0.4;
|
float c4 = grid(ux, uy, divisions / 2.0, thickness / 4.0) * 0.4;
|
||||||
float large = max(c3, c4);
|
float large = max(c3, c4);
|
||||||
|
|
||||||
float s2 = circle_grid(ux, uy, cz*20.0, 1.0) * 0.4;
|
float s2 = circle_grid(ux, uy, cz * 20.0, 1.0) * 0.4;
|
||||||
large = max(large, s2);
|
large = max(large, s2);
|
||||||
|
|
||||||
float c = mix(large, small, min(nz*2.0+0.05, 1.0));
|
float c = mix(large, small, min(nz * 2.0 + 0.05, 1.0));
|
||||||
c = mix(c, xsmall, max(min((nz-0.3)/0.7, 1.0), 0.0));
|
c = mix(c, xsmall, clamp((nz - 0.3) / 0.7, 0.0, 1.0));
|
||||||
|
|
||||||
vec3 color = mix(backgroundColor, lineColor, c);
|
vec3 color = mix(backgroundColor, lineColor, c);
|
||||||
|
|
||||||
gl_FragColor = vec4(color, 1.0);
|
gl_FragColor = vec4(color, 1.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import type { Hst } from "@histoire/plugin-svelte";
|
|
||||||
export let Hst: Hst;
|
|
||||||
import Background from "./Background.svelte";
|
|
||||||
import { Canvas } from "@threlte/core";
|
|
||||||
import Camera from "../Camera.svelte";
|
|
||||||
let width = globalThis.innerWidth || 100;
|
|
||||||
let height = globalThis.innerHeight || 100;
|
|
||||||
|
|
||||||
let cameraPosition: [number, number, number] = [0, 1, 0];
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<svelte:window bind:innerWidth={width} bind:innerHeight={height} />
|
|
||||||
|
|
||||||
<Hst.Story>
|
|
||||||
<Canvas shadows={false}>
|
|
||||||
<Camera bind:position={cameraPosition} />
|
|
||||||
|
|
||||||
<Background {cameraPosition} {width} {height} />
|
|
||||||
</Canvas>
|
|
||||||
</Hst.Story>
|
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { T } from "@threlte/core";
|
import { appSettings } from '$lib/settings/app-settings.svelte';
|
||||||
import BackgroundVert from "./Background.vert";
|
import { T } from '@threlte/core';
|
||||||
import BackgroundFrag from "./Background.frag";
|
import { colors } from '../graph/colors.svelte';
|
||||||
import { colors } from "../graph/colors.svelte";
|
import BackgroundFrag from './Background.frag';
|
||||||
import { Color } from "three";
|
import BackgroundVert from './Background.vert';
|
||||||
import { appSettings } from "$lib/settings/app-settings.svelte";
|
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
minZoom: number;
|
minZoom: number;
|
||||||
@@ -19,7 +18,7 @@
|
|||||||
maxZoom = 150,
|
maxZoom = 150,
|
||||||
cameraPosition = [0, 1, 0],
|
cameraPosition = [0, 1, 0],
|
||||||
width = globalThis?.innerWidth || 100,
|
width = globalThis?.innerWidth || 100,
|
||||||
height = globalThis?.innerHeight || 100,
|
height = globalThis?.innerHeight || 100
|
||||||
}: Props = $props();
|
}: Props = $props();
|
||||||
|
|
||||||
let bw = $derived(width / cameraPosition[2]);
|
let bw = $derived(width / cameraPosition[2]);
|
||||||
@@ -39,25 +38,25 @@
|
|||||||
fragmentShader={BackgroundFrag}
|
fragmentShader={BackgroundFrag}
|
||||||
uniforms={{
|
uniforms={{
|
||||||
camPos: {
|
camPos: {
|
||||||
value: [0, 1, 0],
|
value: [0, 1, 0]
|
||||||
},
|
},
|
||||||
backgroundColor: {
|
backgroundColor: {
|
||||||
value: colors["layer-0"].clone(),
|
value: colors['layer-0']
|
||||||
},
|
},
|
||||||
lineColor: {
|
lineColor: {
|
||||||
value: colors["outline"].clone(),
|
value: colors['outline']
|
||||||
},
|
},
|
||||||
zoomLimits: {
|
zoomLimits: {
|
||||||
value: [2, 50],
|
value: [2, 50]
|
||||||
},
|
},
|
||||||
dimensions: {
|
dimensions: {
|
||||||
value: [100, 100],
|
value: [100, 100]
|
||||||
},
|
}
|
||||||
}}
|
}}
|
||||||
uniforms.camPos.value={cameraPosition}
|
uniforms.camPos.value={cameraPosition}
|
||||||
uniforms.backgroundColor.value={appSettings.theme &&
|
uniforms.backgroundColor.value={appSettings.value.theme
|
||||||
colors["layer-0"].clone()}
|
&& colors['layer-0']}
|
||||||
uniforms.lineColor.value={appSettings.theme && colors["outline"].clone()}
|
uniforms.lineColor.value={appSettings.value.theme && colors['outline']}
|
||||||
uniforms.zoomLimits.value={[minZoom, maxZoom]}
|
uniforms.zoomLimits.value={[minZoom, maxZoom]}
|
||||||
uniforms.dimensions.value={[width, height]}
|
uniforms.dimensions.value={[width, height]}
|
||||||
/>
|
/>
|
||||||
|
|||||||
197
app/src/lib/graph-interface/components/AddMenu.svelte
Normal file
197
app/src/lib/graph-interface/components/AddMenu.svelte
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { NodeId, NodeInstance } from '@nodarium/types';
|
||||||
|
import { HTML } from '@threlte/extras';
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { getGraphManager, getGraphState } from '../graph-state.svelte';
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
onnode: (n: NodeInstance) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const { onnode }: Props = $props();
|
||||||
|
|
||||||
|
const graph = getGraphManager();
|
||||||
|
const graphState = getGraphState();
|
||||||
|
|
||||||
|
let input: HTMLInputElement;
|
||||||
|
let wrapper: HTMLDivElement;
|
||||||
|
let value = $state<string>();
|
||||||
|
let activeNodeId = $state<NodeId>();
|
||||||
|
|
||||||
|
const allNodes = graphState.activeSocket
|
||||||
|
? graph.getPossibleNodes(graphState.activeSocket)
|
||||||
|
: graph.getNodeDefinitions();
|
||||||
|
|
||||||
|
function filterNodes() {
|
||||||
|
return allNodes.filter((node) => node.id.includes(value ?? ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
const nodes = $derived(value === '' ? allNodes : filterNodes());
|
||||||
|
$effect(() => {
|
||||||
|
if (nodes) {
|
||||||
|
if (activeNodeId === undefined) {
|
||||||
|
activeNodeId = nodes?.[0]?.id;
|
||||||
|
} else if (nodes.length) {
|
||||||
|
const node = nodes.find((node) => node.id === activeNodeId);
|
||||||
|
if (!node) {
|
||||||
|
activeNodeId = nodes[0].id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function handleNodeCreation(nodeType: NodeInstance['type']) {
|
||||||
|
if (!graphState.addMenuPosition) return;
|
||||||
|
onnode?.({
|
||||||
|
id: -1,
|
||||||
|
type: nodeType,
|
||||||
|
position: [...graphState.addMenuPosition],
|
||||||
|
props: {},
|
||||||
|
state: {}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleKeyDown(event: KeyboardEvent) {
|
||||||
|
event.stopImmediatePropagation();
|
||||||
|
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
graphState.addMenuPosition = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event.key === 'ArrowDown') {
|
||||||
|
const index = nodes.findIndex((node) => node.id === activeNodeId);
|
||||||
|
activeNodeId = nodes[(index + 1) % nodes.length].id;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event.key === 'ArrowUp') {
|
||||||
|
const index = nodes.findIndex((node) => node.id === activeNodeId);
|
||||||
|
activeNodeId = nodes[(index - 1 + nodes.length) % nodes.length].id;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event.key === 'Enter') {
|
||||||
|
if (activeNodeId && graphState.addMenuPosition) {
|
||||||
|
handleNodeCreation(activeNodeId);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
input.disabled = false;
|
||||||
|
setTimeout(() => input.focus(), 50);
|
||||||
|
|
||||||
|
const rect = wrapper.getBoundingClientRect();
|
||||||
|
const deltaY = rect.bottom - window.innerHeight;
|
||||||
|
const deltaX = rect.right - window.innerWidth;
|
||||||
|
if (deltaY > 0) {
|
||||||
|
wrapper.style.marginTop = `-${deltaY + 30}px`;
|
||||||
|
}
|
||||||
|
if (deltaX > 0) {
|
||||||
|
wrapper.style.marginLeft = `-${deltaX + 30}px`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<HTML
|
||||||
|
position.x={graphState.addMenuPosition?.[0]}
|
||||||
|
position.z={graphState.addMenuPosition?.[1]}
|
||||||
|
transform={false}
|
||||||
|
>
|
||||||
|
<div class="add-menu-wrapper" bind:this={wrapper}>
|
||||||
|
<div class="header">
|
||||||
|
<input
|
||||||
|
id="add-menu"
|
||||||
|
type="text"
|
||||||
|
aria-label="Search for a node type"
|
||||||
|
role="searchbox"
|
||||||
|
placeholder="Search..."
|
||||||
|
disabled={false}
|
||||||
|
onkeydown={handleKeyDown}
|
||||||
|
bind:value
|
||||||
|
bind:this={input}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="content">
|
||||||
|
{#each nodes as node (node.id)}
|
||||||
|
<div
|
||||||
|
class="result"
|
||||||
|
role="treeitem"
|
||||||
|
tabindex="0"
|
||||||
|
aria-selected={node.id === activeNodeId}
|
||||||
|
onkeydown={(event) => {
|
||||||
|
if (event.key === 'Enter') {
|
||||||
|
handleNodeCreation(node.id);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onmousedown={() => handleNodeCreation(node.id)}
|
||||||
|
onfocus={() => {
|
||||||
|
activeNodeId = node.id;
|
||||||
|
}}
|
||||||
|
class:selected={node.id === activeNodeId}
|
||||||
|
onmouseover={() => {
|
||||||
|
activeNodeId = node.id;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{node.id.split('/').at(-1)}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</HTML>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.header {
|
||||||
|
padding: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input {
|
||||||
|
background: var(--color-layer-0);
|
||||||
|
font-family: var(--font-family);
|
||||||
|
border: none;
|
||||||
|
border-radius: 5px;
|
||||||
|
color: var(--text-color);
|
||||||
|
padding: 0.6em;
|
||||||
|
width: calc(100% - 2px);
|
||||||
|
box-sizing: border-box;
|
||||||
|
font-size: 0.8em;
|
||||||
|
margin-left: 1px;
|
||||||
|
margin-top: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus {
|
||||||
|
outline: solid 2px rgba(255, 255, 255, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-menu-wrapper {
|
||||||
|
position: absolute;
|
||||||
|
background: var(--color-layer-1);
|
||||||
|
border-radius: 7px;
|
||||||
|
overflow: hidden;
|
||||||
|
border: solid 2px var(--color-layer-2);
|
||||||
|
width: 150px;
|
||||||
|
}
|
||||||
|
.content {
|
||||||
|
min-height: none;
|
||||||
|
width: 100%;
|
||||||
|
color: var(--text-color);
|
||||||
|
max-height: 300px;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result {
|
||||||
|
padding: 1em 0.9em;
|
||||||
|
border-bottom: solid 1px var(--color-layer-2);
|
||||||
|
opacity: 0.7;
|
||||||
|
font-size: 0.9em;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result[aria-selected="true"] {
|
||||||
|
background: var(--color-layer-2);
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { HTML } from "@threlte/extras";
|
import { HTML } from '@threlte/extras';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
p1: { x: number; y: number };
|
p1: { x: number; y: number };
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
const {
|
const {
|
||||||
p1 = { x: 0, y: 0 },
|
p1 = { x: 0, y: 0 },
|
||||||
p2 = { x: 0, y: 0 },
|
p2 = { x: 0, y: 0 },
|
||||||
cameraPosition = [0, 1, 0],
|
cameraPosition = [0, 1, 0]
|
||||||
}: Props = $props();
|
}: Props = $props();
|
||||||
|
|
||||||
const width = $derived(Math.abs(p1.x - p2.x) * cameraPosition[2]);
|
const width = $derived(Math.abs(p1.x - p2.x) * cameraPosition[2]);
|
||||||
@@ -24,14 +24,15 @@
|
|||||||
<div
|
<div
|
||||||
class="box-selection"
|
class="box-selection"
|
||||||
style={`width: ${width}px; height: ${height}px;`}
|
style={`width: ${width}px; height: ${height}px;`}
|
||||||
></div>
|
>
|
||||||
|
</div>
|
||||||
</HTML>
|
</HTML>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.box-selection {
|
.box-selection {
|
||||||
width: 40px;
|
width: 40px;
|
||||||
height: 20px;
|
height: 20px;
|
||||||
border: solid 2px var(--outline);
|
border: solid 2px var(--color-outline);
|
||||||
border-style: dashed;
|
border-style: dashed;
|
||||||
border-radius: 2px;
|
border-radius: 2px;
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { T } from "@threlte/core";
|
import { T } from '@threlte/core';
|
||||||
import { type OrthographicCamera } from "three";
|
import { type OrthographicCamera } from 'three';
|
||||||
type Props = {
|
type Props = {
|
||||||
camera: OrthographicCamera;
|
camera: OrthographicCamera;
|
||||||
position: [number, number, number];
|
position: [number, number, number];
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type { NodeDefinition, NodeRegistry } from "@nodes/types";
|
import type { NodeDefinition, NodeRegistry } from '@nodarium/types';
|
||||||
import { onDestroy, onMount } from "svelte";
|
import { onMount } from 'svelte';
|
||||||
|
|
||||||
let mx = $state(0);
|
let mx = $state(0);
|
||||||
let my = $state(0);
|
let my = $state(0);
|
||||||
@@ -20,15 +20,15 @@
|
|||||||
my = ev.clientY;
|
my = ev.clientY;
|
||||||
if (!target) return;
|
if (!target) return;
|
||||||
|
|
||||||
const closest = target?.closest?.("[data-node-type]");
|
const closest = target?.closest?.('[data-node-type]');
|
||||||
|
|
||||||
if (!closest) {
|
if (!closest) {
|
||||||
node = undefined;
|
node = undefined;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let nodeType = closest.getAttribute("data-node-type");
|
let nodeType = closest.getAttribute('data-node-type');
|
||||||
let nodeInput = closest.getAttribute("data-node-input");
|
let nodeInput = closest.getAttribute('data-node-input');
|
||||||
|
|
||||||
if (!nodeType) {
|
if (!nodeType) {
|
||||||
node = undefined;
|
node = undefined;
|
||||||
@@ -40,9 +40,9 @@
|
|||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
const style = wrapper.parentElement?.style;
|
const style = wrapper.parentElement?.style;
|
||||||
style?.setProperty("cursor", "help");
|
style?.setProperty('cursor', 'help');
|
||||||
return () => {
|
return () => {
|
||||||
style?.removeProperty("cursor");
|
style?.removeProperty('cursor');
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
@@ -53,12 +53,12 @@
|
|||||||
class="help-wrapper p-4"
|
class="help-wrapper p-4"
|
||||||
class:visible={node}
|
class:visible={node}
|
||||||
bind:clientWidth={width}
|
bind:clientWidth={width}
|
||||||
style="--my:{my}px; --mx:{Math.min(mx, window.innerWidth - width - 20)}px;"
|
style="--my: {my}px; --mx: {Math.min(mx, window.innerWidth - width - 20)}px"
|
||||||
bind:this={wrapper}
|
bind:this={wrapper}
|
||||||
>
|
>
|
||||||
<p class="m-0 text-light opacity-40 flex items-center gap-3 mb-4">
|
<p class="m-0 text-light opacity-40 flex items-center gap-3 mb-4">
|
||||||
<span class="i-tabler-help block w-4 h-4"></span>
|
<span class="i-tabler-help block w-4 h-4"></span>
|
||||||
{node?.id.split("/").at(-1) || "Help"}
|
{node?.id.split('/').at(-1) || 'Help'}
|
||||||
{#if input}
|
{#if input}
|
||||||
<span>> {input}</span>
|
<span>> {input}</span>
|
||||||
{/if}
|
{/if}
|
||||||
@@ -77,7 +77,7 @@
|
|||||||
{#if !input}
|
{#if !input}
|
||||||
<div>
|
<div>
|
||||||
<span class="i-tabler-arrow-right opacity-30">-></span>
|
<span class="i-tabler-arrow-right opacity-30">-></span>
|
||||||
{node?.outputs?.map((o) => o).join(", ") ?? "nothing"}
|
{node?.outputs?.map((o) => o).join(', ') ?? 'nothing'}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
{/if}
|
{/if}
|
||||||
@@ -88,12 +88,12 @@
|
|||||||
position: fixed;
|
position: fixed;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
transform: translate(var(--mx), var(--my));
|
transform: translate(var(--mx), var(--my));
|
||||||
background: var(--layer-1);
|
background: var(--color-layer-1);
|
||||||
border-radius: 5px;
|
border-radius: 5px;
|
||||||
top: 10px;
|
top: 10px;
|
||||||
left: 10px;
|
left: 10px;
|
||||||
max-width: 250px;
|
max-width: 250px;
|
||||||
border: 1px solid var(--outline);
|
border: 1px solid var(--color-outline);
|
||||||
z-index: 10000;
|
z-index: 10000;
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
@@ -1,19 +1,65 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { MeshLineGeometry, MeshLineMaterial } from '@threlte/extras';
|
import type { Box } from '@nodarium/types';
|
||||||
import { points, lines } from './store.js';
|
import { T } from '@threlte/core';
|
||||||
import { T } from '@threlte/core';
|
import { MeshLineGeometry, MeshLineMaterial } from '@threlte/extras';
|
||||||
|
import { Color, Vector3 } from 'three';
|
||||||
|
import { lines, points, rects } from './store.js';
|
||||||
|
|
||||||
|
type Line = {
|
||||||
|
points: Vector3[];
|
||||||
|
color?: Color;
|
||||||
|
};
|
||||||
|
|
||||||
|
function getEachKey(value: Vector3 | Box | Line): string {
|
||||||
|
if ('x' in value) {
|
||||||
|
return [value.x, value.y, value.z].join('-');
|
||||||
|
}
|
||||||
|
if ('minX' in value) {
|
||||||
|
return [value.maxX, value.minX, value.maxY, value.minY].join('-');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ('points' in value) {
|
||||||
|
return getEachKey(value.points[Math.floor(value.points.length / 2)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return '';
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#each $points as point}
|
{#each $points as point (getEachKey(point))}
|
||||||
<T.Mesh position.x={point.x} position.y={point.y} position.z={point.z} rotation.x={-Math.PI / 2}>
|
<T.Mesh
|
||||||
<T.CircleGeometry args={[0.2, 32]} />
|
position.x={point.x}
|
||||||
<T.MeshBasicMaterial color="red" />
|
position.y={point.y}
|
||||||
</T.Mesh>
|
position.z={point.z}
|
||||||
|
rotation.x={-Math.PI / 2}
|
||||||
|
>
|
||||||
|
<T.CircleGeometry args={[0.2, 32]} />
|
||||||
|
<T.MeshBasicMaterial color="red" />
|
||||||
|
</T.Mesh>
|
||||||
{/each}
|
{/each}
|
||||||
|
|
||||||
{#each $lines as line}
|
{#each $rects as rect, i (getEachKey(rect))}
|
||||||
<T.Mesh>
|
<T.Mesh
|
||||||
<MeshLineGeometry points={line} />
|
position.x={(rect.minX + rect.maxX) / 2}
|
||||||
<MeshLineMaterial color="red" linewidth={1} attenuate={false} />
|
position.y={0}
|
||||||
</T.Mesh>
|
position.z={(rect.minY + rect.maxY) / 2}
|
||||||
|
rotation.x={-Math.PI / 2}
|
||||||
|
>
|
||||||
|
<T.PlaneGeometry args={[rect.maxX - rect.minX, rect.maxY - rect.minY]} />
|
||||||
|
<T.MeshBasicMaterial
|
||||||
|
color={new Color().setHSL((i * 1.77) % 1, 1, 0.5)}
|
||||||
|
opacity={0.9}
|
||||||
|
/>
|
||||||
|
</T.Mesh>
|
||||||
|
{/each}
|
||||||
|
|
||||||
|
{#each $lines as line (getEachKey(line))}
|
||||||
|
<T.Mesh position.y={1}>
|
||||||
|
<MeshLineGeometry points={line.points} />
|
||||||
|
<MeshLineMaterial
|
||||||
|
color={line.color || 'red'}
|
||||||
|
linewidth={1}
|
||||||
|
attenuate={false}
|
||||||
|
/>
|
||||||
|
</T.Mesh>
|
||||||
{/each}
|
{/each}
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import { Vector3 } from "three/src/math/Vector3.js";
|
import type { Box } from '@nodarium/types';
|
||||||
import { lines, points } from "./store";
|
import type { Color } from 'three';
|
||||||
|
import { Vector3 } from 'three/src/math/Vector3.js';
|
||||||
|
import Component from './Debug.svelte';
|
||||||
|
import { lines, points, rects } from './store';
|
||||||
|
|
||||||
export function debugPosition(x: number, y: number) {
|
export function debugPosition(x: number, y: number) {
|
||||||
points.update((p) => {
|
points.update((p) => {
|
||||||
@@ -8,18 +11,27 @@ export function debugPosition(x: number, y: number) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function debugRect(rect: Box) {
|
||||||
|
rects.update((r) => {
|
||||||
|
r.push(rect);
|
||||||
|
return r;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function clear() {
|
export function clear() {
|
||||||
points.set([]);
|
points.set([]);
|
||||||
lines.set([]);
|
lines.set([]);
|
||||||
|
rects.set([]);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function debugLine(line: Vector3[]) {
|
export function debugLine(points: Vector3[], color?: Color) {
|
||||||
lines.update((l) => {
|
lines.update((l) => {
|
||||||
l.push(line);
|
l.push({ points, color });
|
||||||
return l;
|
return l;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
import Component from "./Debug.svelte";
|
export default Component;
|
||||||
|
export function clearLines() {
|
||||||
export default Component
|
lines.set([]);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { writable } from "svelte/store";
|
import type { Box } from '@nodarium/types';
|
||||||
import { Vector3 } from "three/src/math/Vector3.js";
|
import { writable } from 'svelte/store';
|
||||||
|
import type { Color } from 'three';
|
||||||
|
import { Vector3 } from 'three/src/math/Vector3.js';
|
||||||
|
|
||||||
export const points = writable<Vector3[]>([]);
|
export const points = writable<Vector3[]>([]);
|
||||||
|
export const rects = writable<Box[]>([]);
|
||||||
export const lines = writable<Vector3[][]>([]);
|
export const lines = writable<{ points: Vector3[]; color?: Color }[]>([]);
|
||||||
|
|||||||
@@ -1,100 +1,109 @@
|
|||||||
<script module lang="ts">
|
<script module lang="ts">
|
||||||
import { colors } from "../graph/colors.svelte";
|
import { colors } from '../graph/colors.svelte';
|
||||||
|
|
||||||
const circleMaterial = new MeshBasicMaterial({
|
const circleMaterial = new MeshBasicMaterial({
|
||||||
color: colors.edge.clone(),
|
color: colors.edge.clone(),
|
||||||
toneMapped: false,
|
toneMapped: false
|
||||||
});
|
|
||||||
$effect.root(() => {
|
|
||||||
$effect(() => {
|
|
||||||
appSettings.theme;
|
|
||||||
circleMaterial.color = colors.edge.clone().convertSRGBToLinear();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const lineCache = new Map<number, BufferGeometry>();
|
let lineColor = $state(colors.edge.clone().convertSRGBToLinear());
|
||||||
|
|
||||||
|
$effect.root(() => {
|
||||||
|
$effect(() => {
|
||||||
|
if (appSettings.value.theme === undefined) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
circleMaterial.color = colors.edge.clone().convertSRGBToLinear();
|
||||||
|
lineColor = colors.edge.clone().convertSRGBToLinear();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
const curve = new CubicBezierCurve(
|
const curve = new CubicBezierCurve(
|
||||||
new Vector2(0, 0),
|
new Vector2(0, 0),
|
||||||
new Vector2(0, 0),
|
new Vector2(0, 0),
|
||||||
new Vector2(0, 0),
|
new Vector2(0, 0),
|
||||||
new Vector2(0, 0),
|
new Vector2(0, 0)
|
||||||
);
|
);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { T } from "@threlte/core";
|
import { appSettings } from '$lib/settings/app-settings.svelte';
|
||||||
import { MeshLineMaterial } from "@threlte/extras";
|
import { T } from '@threlte/core';
|
||||||
import { BufferGeometry, MeshBasicMaterial, Vector3 } from "three";
|
import { MeshLineGeometry, MeshLineMaterial } from '@threlte/extras';
|
||||||
import { CubicBezierCurve } from "three/src/extras/curves/CubicBezierCurve.js";
|
import { onDestroy } from 'svelte';
|
||||||
import { Vector2 } from "three/src/math/Vector2.js";
|
import { MeshBasicMaterial, Vector3 } from 'three';
|
||||||
import { createEdgeGeometry } from "./createEdgeGeometry.js";
|
import { CubicBezierCurve } from 'three/src/extras/curves/CubicBezierCurve.js';
|
||||||
import { appSettings } from "$lib/settings/app-settings.svelte";
|
import { Vector2 } from 'three/src/math/Vector2.js';
|
||||||
|
import { getGraphState } from '../graph-state.svelte';
|
||||||
|
|
||||||
|
const graphState = getGraphState();
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
from: { x: number; y: number };
|
x1: number;
|
||||||
to: { x: number; y: number };
|
y1: number;
|
||||||
|
x2: number;
|
||||||
|
y2: number;
|
||||||
z: number;
|
z: number;
|
||||||
|
id?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const { from, to, z }: Props = $props();
|
const { x1, y1, x2, y2, z, id }: Props = $props();
|
||||||
|
|
||||||
let geometry: BufferGeometry | null = $state(null);
|
const thickness = $derived(Math.max(0.001, 0.00082 * Math.exp(0.055 * z)));
|
||||||
|
|
||||||
const lineColor = $derived(
|
let points = $state<Vector3[]>([]);
|
||||||
appSettings.theme && colors.edge.clone().convertSRGBToLinear(),
|
|
||||||
);
|
|
||||||
|
|
||||||
let lastId: number | null = null;
|
let lastId: string | null = null;
|
||||||
|
const curveId = $derived(`${x1}-${y1}-${x2}-${y2}`);
|
||||||
const primeA = 31;
|
|
||||||
const primeB = 37;
|
|
||||||
|
|
||||||
function update() {
|
function update() {
|
||||||
const new_x = to.x - from.x;
|
const new_x = x2 - x1;
|
||||||
const new_y = to.y - from.y;
|
const new_y = y2 - y1;
|
||||||
const curveId = new_x * primeA + new_y * primeB;
|
|
||||||
if (lastId === curveId) {
|
if (lastId === curveId) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
lastId = curveId;
|
||||||
const mid = new Vector2(new_x / 2, new_y / 2);
|
|
||||||
|
|
||||||
if (lineCache.has(curveId)) {
|
|
||||||
geometry = lineCache.get(curveId)!;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const length = Math.floor(
|
const length = Math.floor(
|
||||||
Math.sqrt(Math.pow(new_x, 2) + Math.pow(new_y, 2)) / 4,
|
Math.sqrt(Math.pow(new_x, 2) + Math.pow(new_y, 2)) / 4
|
||||||
);
|
);
|
||||||
|
|
||||||
const samples = Math.max(length * 16, 10);
|
const samples = Math.max(length * 16, 10);
|
||||||
|
|
||||||
curve.v0.set(0, 0);
|
curve.v0.set(0, 0);
|
||||||
curve.v1.set(mid.x, 0);
|
curve.v1.set(new_x / 2, 0);
|
||||||
curve.v2.set(mid.x, new_y);
|
curve.v2.set(new_x / 2, new_y);
|
||||||
curve.v3.set(new_x, new_y);
|
curve.v3.set(new_x, new_y);
|
||||||
|
|
||||||
const points = curve
|
points = curve
|
||||||
.getPoints(samples)
|
.getPoints(samples)
|
||||||
.map((p) => new Vector3(p.x, 0, p.y))
|
.map((p) => new Vector3(p.x, 0, p.y))
|
||||||
.flat();
|
.flat();
|
||||||
|
|
||||||
geometry = createEdgeGeometry(points);
|
if (id) {
|
||||||
lineCache.set(curveId, geometry);
|
graphState.setEdgeGeometry(
|
||||||
|
id,
|
||||||
|
x1,
|
||||||
|
y1,
|
||||||
|
$state.snapshot(points) as unknown as Vector3[]
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (from || to) {
|
if (x1 || x2 || y1 || y2) {
|
||||||
update();
|
update();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
onDestroy(() => {
|
||||||
|
if (id) graphState.removeEdgeGeometry(id);
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<T.Mesh
|
<T.Mesh
|
||||||
position.x={from.x}
|
position.x={x1}
|
||||||
position.z={from.y}
|
position.z={y1}
|
||||||
position.y={0.8}
|
position.y={0.8}
|
||||||
rotation.x={-Math.PI / 2}
|
rotation.x={-Math.PI / 2}
|
||||||
material={circleMaterial}
|
material={circleMaterial}
|
||||||
@@ -103,8 +112,8 @@
|
|||||||
</T.Mesh>
|
</T.Mesh>
|
||||||
|
|
||||||
<T.Mesh
|
<T.Mesh
|
||||||
position.x={to.x}
|
position.x={x2}
|
||||||
position.z={to.y}
|
position.z={y2}
|
||||||
position.y={0.8}
|
position.y={0.8}
|
||||||
rotation.x={-Math.PI / 2}
|
rotation.x={-Math.PI / 2}
|
||||||
material={circleMaterial}
|
material={circleMaterial}
|
||||||
@@ -112,8 +121,19 @@
|
|||||||
<T.CircleGeometry args={[0.5, 16]} />
|
<T.CircleGeometry args={[0.5, 16]} />
|
||||||
</T.Mesh>
|
</T.Mesh>
|
||||||
|
|
||||||
{#if geometry}
|
{#if graphState.hoveredEdgeId === id}
|
||||||
<T.Mesh position.x={from.x} position.z={from.y} position.y={0.1} {geometry}>
|
<T.Mesh position.x={x1} position.z={y1} position.y={0.1}>
|
||||||
<MeshLineMaterial width={Math.max(z * 0.0001, 0.00001)} color={lineColor} />
|
<MeshLineGeometry {points} />
|
||||||
|
<MeshLineMaterial
|
||||||
|
width={thickness * 5}
|
||||||
|
color={lineColor}
|
||||||
|
opacity={0.5}
|
||||||
|
transparent
|
||||||
|
/>
|
||||||
</T.Mesh>
|
</T.Mesh>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
<T.Mesh position.x={x1} position.z={y1} position.y={0.1}>
|
||||||
|
<MeshLineGeometry {points} />
|
||||||
|
<MeshLineMaterial width={thickness} color={lineColor} />
|
||||||
|
</T.Mesh>
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import Edge from "./Edge.svelte";
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
from: { x: number; y: number };
|
|
||||||
to: { x: number; y: number };
|
|
||||||
z: number;
|
|
||||||
};
|
|
||||||
const { from, to, z }: Props = $props();
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<Edge {from} {to} {z} />
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
import { BufferAttribute, BufferGeometry, Vector3 } from 'three';
|
|
||||||
import { setXY, setXYZ, setXYZW, setXYZXYZ } from './utils.js';
|
|
||||||
|
|
||||||
|
|
||||||
export function createEdgeGeometry(points: Vector3[]) {
|
|
||||||
|
|
||||||
const length = points[0].distanceTo(points[points.length - 1]);
|
|
||||||
|
|
||||||
const startRadius = 8;
|
|
||||||
const constantWidth = 2;
|
|
||||||
const taperFraction = 0.8 / length;
|
|
||||||
|
|
||||||
function ease(t: number) {
|
|
||||||
return t * t * (3 - 2 * t);
|
|
||||||
}
|
|
||||||
let shapeFunction = (alpha: number) => {
|
|
||||||
if (alpha < taperFraction) {
|
|
||||||
const easedAlpha = ease(alpha / taperFraction);
|
|
||||||
return startRadius + (constantWidth - startRadius) * easedAlpha;
|
|
||||||
} else if (alpha > 1 - taperFraction) {
|
|
||||||
const easedAlpha = ease((alpha - (1 - taperFraction)) / taperFraction);
|
|
||||||
return constantWidth + (startRadius - constantWidth) * easedAlpha;
|
|
||||||
} else {
|
|
||||||
return constantWidth;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// When the component first runs we create the buffer geometry and allocate the buffer attributes
|
|
||||||
let pointCount = points.length
|
|
||||||
let counters: number[] = []
|
|
||||||
let counterIndex = 0
|
|
||||||
let side: number[] = []
|
|
||||||
let widthArray: number[] = []
|
|
||||||
let doubleIndex = 0
|
|
||||||
let uvArray: number[] = []
|
|
||||||
let uvIndex = 0
|
|
||||||
let indices: number[] = []
|
|
||||||
let indicesIndex = 0
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
for (let j = 0; j < pointCount; j++) {
|
|
||||||
const c = j / points.length
|
|
||||||
counters[counterIndex + 0] = c
|
|
||||||
counters[counterIndex + 1] = c
|
|
||||||
counterIndex += 2
|
|
||||||
|
|
||||||
setXY(side, doubleIndex, 1, -1)
|
|
||||||
let width = shapeFunction((j / (pointCount - 1)))
|
|
||||||
setXY(widthArray, doubleIndex, width, width)
|
|
||||||
doubleIndex += 2
|
|
||||||
|
|
||||||
setXYZW(uvArray, uvIndex, j / (pointCount - 1), 0, j / (pointCount - 1), 1)
|
|
||||||
uvIndex += 4
|
|
||||||
|
|
||||||
if (j < pointCount - 1) {
|
|
||||||
const n = j * 2
|
|
||||||
setXYZ(indices, indicesIndex, n + 0, n + 1, n + 2)
|
|
||||||
setXYZ(indices, indicesIndex + 3, n + 2, n + 1, n + 3)
|
|
||||||
indicesIndex += 6
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const geometry = new BufferGeometry()
|
|
||||||
// create these buffer attributes at the correct length but leave them empty for now
|
|
||||||
geometry.setAttribute('position', new BufferAttribute(new Float32Array(pointCount * 6), 3))
|
|
||||||
geometry.setAttribute('previous', new BufferAttribute(new Float32Array(pointCount * 6), 3))
|
|
||||||
geometry.setAttribute('next', new BufferAttribute(new Float32Array(pointCount * 6), 3))
|
|
||||||
// create and populate these buffer attributes
|
|
||||||
geometry.setAttribute('counters', new BufferAttribute(new Float32Array(counters), 1))
|
|
||||||
geometry.setAttribute('side', new BufferAttribute(new Float32Array(side), 1))
|
|
||||||
geometry.setAttribute('width', new BufferAttribute(new Float32Array(widthArray), 1))
|
|
||||||
geometry.setAttribute('uv', new BufferAttribute(new Float32Array(uvArray), 2))
|
|
||||||
geometry.setIndex(new BufferAttribute(new Uint16Array(indices), 1))
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
let positions: number[] = []
|
|
||||||
let previous: number[] = []
|
|
||||||
let next: number[] = []
|
|
||||||
let positionIndex = 0
|
|
||||||
let previousIndex = 0
|
|
||||||
let nextIndex = 0
|
|
||||||
setXYZXYZ(previous, previousIndex, points[0].x, points[0].y, points[0].z)
|
|
||||||
previousIndex += 6
|
|
||||||
for (let j = 0; j < pointCount; j++) {
|
|
||||||
const p = points[j]
|
|
||||||
setXYZXYZ(positions, positionIndex, p.x, p.y, p.z)
|
|
||||||
positionIndex += 6
|
|
||||||
if (j < pointCount - 1) {
|
|
||||||
setXYZXYZ(previous, previousIndex, p.x, p.y, p.z)
|
|
||||||
previousIndex += 6
|
|
||||||
}
|
|
||||||
if (j > 0 && j + 1 <= pointCount) {
|
|
||||||
setXYZXYZ(next, nextIndex, p.x, p.y, p.z)
|
|
||||||
nextIndex += 6
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setXYZXYZ(
|
|
||||||
next,
|
|
||||||
nextIndex,
|
|
||||||
points[pointCount - 1].x,
|
|
||||||
points[pointCount - 1].y,
|
|
||||||
points[pointCount - 1].z
|
|
||||||
)
|
|
||||||
const positionAttribute = (geometry.getAttribute('position') as BufferAttribute).set(positions)
|
|
||||||
const previousAttribute = (geometry.getAttribute('previous') as BufferAttribute).set(previous)
|
|
||||||
const nextAttribute = (geometry.getAttribute('next') as BufferAttribute).set(next)
|
|
||||||
positionAttribute.needsUpdate = true
|
|
||||||
previousAttribute.needsUpdate = true
|
|
||||||
nextAttribute.needsUpdate = true
|
|
||||||
geometry.computeBoundingSphere()
|
|
||||||
|
|
||||||
return geometry;
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,23 +1,23 @@
|
|||||||
export const setXYZXYZ = (array: number[], location: number, x: number, y: number, z: number) => {
|
export const setXYZXYZ = (array: number[], location: number, x: number, y: number, z: number) => {
|
||||||
array[location + 0] = x
|
array[location + 0] = x;
|
||||||
array[location + 1] = y
|
array[location + 1] = y;
|
||||||
array[location + 2] = z
|
array[location + 2] = z;
|
||||||
|
|
||||||
array[location + 3] = x
|
array[location + 3] = x;
|
||||||
array[location + 4] = y
|
array[location + 4] = y;
|
||||||
array[location + 5] = z
|
array[location + 5] = z;
|
||||||
}
|
};
|
||||||
|
|
||||||
export const setXY = (array: number[], location: number, x: number, y: number) => {
|
export const setXY = (array: number[], location: number, x: number, y: number) => {
|
||||||
array[location + 0] = x
|
array[location + 0] = x;
|
||||||
array[location + 1] = y
|
array[location + 1] = y;
|
||||||
}
|
};
|
||||||
|
|
||||||
export const setXYZ = (array: number[], location: number, x: number, y: number, z: number) => {
|
export const setXYZ = (array: number[], location: number, x: number, y: number, z: number) => {
|
||||||
array[location + 0] = x
|
array[location + 0] = x;
|
||||||
array[location + 1] = y
|
array[location + 1] = y;
|
||||||
array[location + 2] = z
|
array[location + 2] = z;
|
||||||
}
|
};
|
||||||
|
|
||||||
export const setXYZW = (
|
export const setXYZW = (
|
||||||
array: number[],
|
array: number[],
|
||||||
@@ -27,8 +27,8 @@ export const setXYZW = (
|
|||||||
z: number,
|
z: number,
|
||||||
w: number
|
w: number
|
||||||
) => {
|
) => {
|
||||||
array[location + 0] = x
|
array[location + 0] = x;
|
||||||
array[location + 1] = y
|
array[location + 1] = y;
|
||||||
array[location + 2] = z
|
array[location + 2] = z;
|
||||||
array[location + 3] = w
|
array[location + 3] = w;
|
||||||
}
|
};
|
||||||
|
|||||||
265
app/src/lib/graph-interface/graph-manager.svelte.test.ts
Normal file
265
app/src/lib/graph-interface/graph-manager.svelte.test.ts
Normal file
@@ -0,0 +1,265 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { GraphManager } from './graph-manager.svelte';
|
||||||
|
import {
|
||||||
|
createMockNodeRegistry,
|
||||||
|
mockFloatInputNode,
|
||||||
|
mockFloatOutputNode,
|
||||||
|
mockGeometryOutputNode,
|
||||||
|
mockPathInputNode,
|
||||||
|
mockVec3OutputNode
|
||||||
|
} from './test-utils';
|
||||||
|
|
||||||
|
describe('GraphManager', () => {
|
||||||
|
describe('getPossibleSockets', () => {
|
||||||
|
describe('when dragging an output socket', () => {
|
||||||
|
it('should return compatible input sockets based on type', () => {
|
||||||
|
const registry = createMockNodeRegistry([
|
||||||
|
mockFloatOutputNode,
|
||||||
|
mockFloatInputNode,
|
||||||
|
mockGeometryOutputNode,
|
||||||
|
mockPathInputNode
|
||||||
|
]);
|
||||||
|
|
||||||
|
const manager = new GraphManager(registry);
|
||||||
|
|
||||||
|
const floatInputNode = manager.createNode({
|
||||||
|
type: 'test/node/input',
|
||||||
|
position: [100, 100],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const floatOutputNode = manager.createNode({
|
||||||
|
type: 'test/node/output',
|
||||||
|
position: [0, 0],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(floatInputNode).toBeDefined();
|
||||||
|
expect(floatOutputNode).toBeDefined();
|
||||||
|
|
||||||
|
const possibleSockets = manager.getPossibleSockets({
|
||||||
|
node: floatOutputNode!,
|
||||||
|
index: 0,
|
||||||
|
position: [0, 0]
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(possibleSockets.length).toBe(1);
|
||||||
|
const socketNodeIds = possibleSockets.map(([node]) => node.id);
|
||||||
|
expect(socketNodeIds).toContain(floatInputNode!.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should exclude self node from possible sockets', () => {
|
||||||
|
const registry = createMockNodeRegistry([
|
||||||
|
mockFloatOutputNode,
|
||||||
|
mockFloatInputNode
|
||||||
|
]);
|
||||||
|
|
||||||
|
const manager = new GraphManager(registry);
|
||||||
|
|
||||||
|
const floatInputNode = manager.createNode({
|
||||||
|
type: 'test/node/input',
|
||||||
|
position: [100, 100],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(floatInputNode).toBeDefined();
|
||||||
|
|
||||||
|
const possibleSockets = manager.getPossibleSockets({
|
||||||
|
node: floatInputNode!,
|
||||||
|
index: 'value',
|
||||||
|
position: [0, 0]
|
||||||
|
});
|
||||||
|
|
||||||
|
const socketNodeIds = possibleSockets.map(([node]) => node.id);
|
||||||
|
expect(socketNodeIds).not.toContain(floatInputNode!.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should exclude parent nodes from possible sockets when dragging output', () => {
|
||||||
|
const registry = createMockNodeRegistry([
|
||||||
|
mockFloatOutputNode,
|
||||||
|
mockFloatInputNode
|
||||||
|
]);
|
||||||
|
|
||||||
|
const manager = new GraphManager(registry);
|
||||||
|
|
||||||
|
const parentNode = manager.createNode({
|
||||||
|
type: 'test/node/output',
|
||||||
|
position: [0, 0],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const childNode = manager.createNode({
|
||||||
|
type: 'test/node/input',
|
||||||
|
position: [100, 100],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(parentNode).toBeDefined();
|
||||||
|
expect(childNode).toBeDefined();
|
||||||
|
|
||||||
|
if (parentNode && childNode) {
|
||||||
|
manager.createEdge(parentNode, 0, childNode, 'value');
|
||||||
|
}
|
||||||
|
|
||||||
|
const possibleSockets = manager.getPossibleSockets({
|
||||||
|
node: parentNode!,
|
||||||
|
index: 0,
|
||||||
|
position: [0, 0]
|
||||||
|
});
|
||||||
|
|
||||||
|
const socketNodeIds = possibleSockets.map(([node]) => node.id);
|
||||||
|
expect(socketNodeIds).not.toContain(childNode!.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return sockets compatible with accepts property', () => {
|
||||||
|
const registry = createMockNodeRegistry([
|
||||||
|
mockGeometryOutputNode,
|
||||||
|
mockPathInputNode
|
||||||
|
]);
|
||||||
|
|
||||||
|
const manager = new GraphManager(registry);
|
||||||
|
|
||||||
|
const geometryOutputNode = manager.createNode({
|
||||||
|
type: 'test/node/geometry',
|
||||||
|
position: [0, 0],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const pathInputNode = manager.createNode({
|
||||||
|
type: 'test/node/path',
|
||||||
|
position: [100, 100],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(geometryOutputNode).toBeDefined();
|
||||||
|
expect(pathInputNode).toBeDefined();
|
||||||
|
|
||||||
|
const possibleSockets = manager.getPossibleSockets({
|
||||||
|
node: geometryOutputNode!,
|
||||||
|
index: 0,
|
||||||
|
position: [0, 0]
|
||||||
|
});
|
||||||
|
|
||||||
|
const socketNodeIds = possibleSockets.map(([node]) => node.id);
|
||||||
|
expect(socketNodeIds).toContain(pathInputNode!.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return empty array when no compatible sockets exist', () => {
|
||||||
|
const registry = createMockNodeRegistry([
|
||||||
|
mockVec3OutputNode,
|
||||||
|
mockFloatInputNode
|
||||||
|
]);
|
||||||
|
|
||||||
|
const manager = new GraphManager(registry);
|
||||||
|
|
||||||
|
const vec3OutputNode = manager.createNode({
|
||||||
|
type: 'test/node/vec3',
|
||||||
|
position: [0, 0],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const floatInputNode = manager.createNode({
|
||||||
|
type: 'test/node/input',
|
||||||
|
position: [100, 100],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(vec3OutputNode).toBeDefined();
|
||||||
|
expect(floatInputNode).toBeDefined();
|
||||||
|
|
||||||
|
const possibleSockets = manager.getPossibleSockets({
|
||||||
|
node: vec3OutputNode!,
|
||||||
|
index: 0,
|
||||||
|
position: [0, 0]
|
||||||
|
});
|
||||||
|
|
||||||
|
const socketNodeIds = possibleSockets.map(([node]) => node.id);
|
||||||
|
expect(socketNodeIds).not.toContain(floatInputNode!.id);
|
||||||
|
expect(possibleSockets.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return socket info with correct socket key for inputs', () => {
|
||||||
|
const registry = createMockNodeRegistry([
|
||||||
|
mockFloatOutputNode,
|
||||||
|
mockFloatInputNode
|
||||||
|
]);
|
||||||
|
|
||||||
|
const manager = new GraphManager(registry);
|
||||||
|
|
||||||
|
const floatOutputNode = manager.createNode({
|
||||||
|
type: 'test/node/output',
|
||||||
|
position: [0, 0],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const floatInputNode = manager.createNode({
|
||||||
|
type: 'test/node/input',
|
||||||
|
position: [100, 100],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(floatOutputNode).toBeDefined();
|
||||||
|
expect(floatInputNode).toBeDefined();
|
||||||
|
|
||||||
|
const possibleSockets = manager.getPossibleSockets({
|
||||||
|
node: floatOutputNode!,
|
||||||
|
index: 0,
|
||||||
|
position: [0, 0]
|
||||||
|
});
|
||||||
|
|
||||||
|
const matchingSocket = possibleSockets.find(([node]) => node.id === floatInputNode!.id);
|
||||||
|
expect(matchingSocket).toBeDefined();
|
||||||
|
expect(matchingSocket![1]).toBe('value');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return multiple compatible sockets', () => {
|
||||||
|
const registry = createMockNodeRegistry([
|
||||||
|
mockFloatOutputNode,
|
||||||
|
mockFloatInputNode,
|
||||||
|
mockGeometryOutputNode,
|
||||||
|
mockPathInputNode
|
||||||
|
]);
|
||||||
|
|
||||||
|
const manager = new GraphManager(registry);
|
||||||
|
|
||||||
|
const floatOutputNode = manager.createNode({
|
||||||
|
type: 'test/node/output',
|
||||||
|
position: [0, 0],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const geometryOutputNode = manager.createNode({
|
||||||
|
type: 'test/node/geometry',
|
||||||
|
position: [200, 0],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const floatInputNode = manager.createNode({
|
||||||
|
type: 'test/node/input',
|
||||||
|
position: [100, 100],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const pathInputNode = manager.createNode({
|
||||||
|
type: 'test/node/path',
|
||||||
|
position: [300, 100],
|
||||||
|
props: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(floatOutputNode).toBeDefined();
|
||||||
|
expect(geometryOutputNode).toBeDefined();
|
||||||
|
expect(floatInputNode).toBeDefined();
|
||||||
|
expect(pathInputNode).toBeDefined();
|
||||||
|
|
||||||
|
const possibleSocketsForFloat = manager.getPossibleSockets({
|
||||||
|
node: floatOutputNode!,
|
||||||
|
index: 0,
|
||||||
|
position: [0, 0]
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(possibleSocketsForFloat.length).toBe(1);
|
||||||
|
expect(possibleSocketsForFloat.map(([n]) => n.id)).toContain(floatInputNode!.id);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
850
app/src/lib/graph-interface/graph-manager.svelte.ts
Normal file
850
app/src/lib/graph-interface/graph-manager.svelte.ts
Normal file
@@ -0,0 +1,850 @@
|
|||||||
|
import throttle from '$lib/helpers/throttle';
|
||||||
|
import { RemoteNodeRegistry } from '$lib/node-registry/index';
|
||||||
|
import type {
|
||||||
|
Edge,
|
||||||
|
Graph,
|
||||||
|
NodeDefinition,
|
||||||
|
NodeId,
|
||||||
|
NodeInput,
|
||||||
|
NodeInstance,
|
||||||
|
NodeRegistry,
|
||||||
|
Socket
|
||||||
|
} from '@nodarium/types';
|
||||||
|
import { fastHashString } from '@nodarium/utils';
|
||||||
|
import { createLogger } from '@nodarium/utils';
|
||||||
|
import { SvelteMap, SvelteSet } from 'svelte/reactivity';
|
||||||
|
import EventEmitter from './helpers/EventEmitter';
|
||||||
|
import { HistoryManager } from './history-manager';
|
||||||
|
|
||||||
|
const logger = createLogger('graph-manager');
|
||||||
|
logger.mute();
|
||||||
|
|
||||||
|
const remoteRegistry = new RemoteNodeRegistry('');
|
||||||
|
|
||||||
|
const clone = 'structuredClone' in self
|
||||||
|
? self.structuredClone
|
||||||
|
: (args: unknown) => JSON.parse(JSON.stringify(args));
|
||||||
|
|
||||||
|
function areSocketsCompatible(
|
||||||
|
output: string | undefined,
|
||||||
|
inputs: string | (string | undefined)[] | undefined
|
||||||
|
) {
|
||||||
|
if (Array.isArray(inputs) && output) {
|
||||||
|
return inputs.includes(output);
|
||||||
|
}
|
||||||
|
return inputs === output;
|
||||||
|
}
|
||||||
|
|
||||||
|
function areEdgesEqual(firstEdge: Edge, secondEdge: Edge) {
|
||||||
|
if (firstEdge[0].id !== secondEdge[0].id) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (firstEdge[1] !== secondEdge[1]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (firstEdge[2].id !== secondEdge[2].id) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (firstEdge[3] !== secondEdge[3]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GraphManager extends EventEmitter<{
|
||||||
|
save: Graph;
|
||||||
|
result: unknown;
|
||||||
|
settings: {
|
||||||
|
types: Record<string, NodeInput>;
|
||||||
|
values: Record<string, unknown>;
|
||||||
|
};
|
||||||
|
}> {
|
||||||
|
status = $state<'loading' | 'idle' | 'error'>();
|
||||||
|
loaded = false;
|
||||||
|
|
||||||
|
graph: Graph = { id: 0, nodes: [], edges: [] };
|
||||||
|
id = $state(0);
|
||||||
|
|
||||||
|
nodes = new SvelteMap<number, NodeInstance>();
|
||||||
|
|
||||||
|
edges = $state<Edge[]>([]);
|
||||||
|
|
||||||
|
settingTypes: Record<string, NodeInput> = {};
|
||||||
|
settings = $state<Record<string, unknown>>();
|
||||||
|
|
||||||
|
currentUndoGroup: number | null = null;
|
||||||
|
|
||||||
|
inputSockets = $derived.by(() => {
|
||||||
|
const s = new SvelteSet<string>();
|
||||||
|
for (const edge of this.edges) {
|
||||||
|
s.add(`${edge[2].id}-${edge[3]}`);
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
|
||||||
|
history: HistoryManager = new HistoryManager();
|
||||||
|
execute = throttle(() => {
|
||||||
|
if (this.loaded === false) return;
|
||||||
|
this.emit('result', this.serialize());
|
||||||
|
}, 10);
|
||||||
|
|
||||||
|
constructor(public registry: NodeRegistry) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
serialize(): Graph {
|
||||||
|
const nodes = Array.from(this.nodes.values()).map((node) => ({
|
||||||
|
id: node.id,
|
||||||
|
position: [...node.position],
|
||||||
|
type: node.type,
|
||||||
|
props: node.props
|
||||||
|
})) as NodeInstance[];
|
||||||
|
const edges = this.edges.map((edge) => [
|
||||||
|
edge[0].id,
|
||||||
|
edge[1],
|
||||||
|
edge[2].id,
|
||||||
|
edge[3]
|
||||||
|
]) as Graph['edges'];
|
||||||
|
const serialized = {
|
||||||
|
id: this.graph.id,
|
||||||
|
settings: $state.snapshot(this.settings),
|
||||||
|
meta: $state.snapshot(this.graph.meta),
|
||||||
|
nodes,
|
||||||
|
edges
|
||||||
|
};
|
||||||
|
logger.log('serializing graph', serialized);
|
||||||
|
return clone($state.snapshot(serialized));
|
||||||
|
}
|
||||||
|
|
||||||
|
private lastSettingsHash = 0;
|
||||||
|
setSettings(settings: Record<string, unknown>) {
|
||||||
|
const hash = fastHashString(JSON.stringify(settings));
|
||||||
|
if (hash === this.lastSettingsHash) return;
|
||||||
|
this.lastSettingsHash = hash;
|
||||||
|
|
||||||
|
this.settings = settings;
|
||||||
|
this.save();
|
||||||
|
this.execute();
|
||||||
|
}
|
||||||
|
|
||||||
|
getNodeDefinitions() {
|
||||||
|
return this.registry.getAllNodes();
|
||||||
|
}
|
||||||
|
|
||||||
|
getLinkedNodes(node: NodeInstance) {
|
||||||
|
const nodes = new SvelteSet<NodeInstance>();
|
||||||
|
const stack = [node];
|
||||||
|
while (stack.length) {
|
||||||
|
const n = stack.pop();
|
||||||
|
if (!n) continue;
|
||||||
|
nodes.add(n);
|
||||||
|
const children = this.getChildren(n);
|
||||||
|
const parents = this.getParentsOfNode(n);
|
||||||
|
const newNodes = [...children, ...parents].filter((n) => !nodes.has(n));
|
||||||
|
stack.push(...newNodes);
|
||||||
|
}
|
||||||
|
return [...nodes.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
getEdgeId(e: Edge) {
|
||||||
|
return `${e[0].id}-${e[1]}-${e[2].id}-${e[3]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
getEdgeById(id: string): Edge | undefined {
|
||||||
|
return this.edges.find((e) => this.getEdgeId(e) === id);
|
||||||
|
}
|
||||||
|
|
||||||
|
dropNodeOnEdge(nodeId: number, edge: Edge) {
|
||||||
|
const draggedNode = this.getNode(nodeId);
|
||||||
|
if (!draggedNode || !draggedNode.state?.type) return;
|
||||||
|
|
||||||
|
const [fromNode, fromSocketIdx, toNode, toSocketKey] = edge;
|
||||||
|
|
||||||
|
const draggedInputs = Object.entries(draggedNode.state.type.inputs ?? {});
|
||||||
|
const draggedOutputs = draggedNode.state.type.outputs ?? [];
|
||||||
|
|
||||||
|
const edgeOutputSocketType = fromNode.state?.type?.outputs?.[fromSocketIdx];
|
||||||
|
const targetInput = toNode.state?.type?.inputs?.[toSocketKey];
|
||||||
|
const targetAcceptedTypes = [targetInput?.type, ...(targetInput?.accepts || [])];
|
||||||
|
|
||||||
|
const bestInputEntry = draggedInputs.find(([, input]) => {
|
||||||
|
const accepted = [input.type, ...(input.accepts || [])];
|
||||||
|
return areSocketsCompatible(edgeOutputSocketType, accepted);
|
||||||
|
});
|
||||||
|
|
||||||
|
const bestOutputIdx = draggedOutputs.findIndex(outputType =>
|
||||||
|
areSocketsCompatible(outputType, targetAcceptedTypes)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!bestInputEntry || bestOutputIdx === -1) {
|
||||||
|
logger.error('Could not find compatible sockets for drop');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.startUndoGroup();
|
||||||
|
|
||||||
|
this.removeEdge(edge, { applyDeletion: false });
|
||||||
|
|
||||||
|
this.createEdge(fromNode, fromSocketIdx, draggedNode, bestInputEntry[0], {
|
||||||
|
applyUpdate: false
|
||||||
|
});
|
||||||
|
|
||||||
|
this.createEdge(draggedNode, bestOutputIdx, toNode, toSocketKey, {
|
||||||
|
applyUpdate: false
|
||||||
|
});
|
||||||
|
|
||||||
|
this.saveUndoGroup();
|
||||||
|
this.execute();
|
||||||
|
}
|
||||||
|
|
||||||
|
getPossibleDropOnEdges(nodeId: number): Edge[] {
|
||||||
|
const draggedNode = this.getNode(nodeId);
|
||||||
|
if (!draggedNode || !draggedNode.state?.type) return [];
|
||||||
|
|
||||||
|
const draggedInputs = Object.values(draggedNode.state.type.inputs ?? {});
|
||||||
|
const draggedOutputs = draggedNode.state.type.outputs ?? [];
|
||||||
|
|
||||||
|
// Optimization: Pre-calculate parents to avoid cycles
|
||||||
|
const parentIds = new SvelteSet(this.getParentsOfNode(draggedNode).map(n => n.id));
|
||||||
|
|
||||||
|
return this.edges.filter((edge) => {
|
||||||
|
const [fromNode, fromSocketIdx, toNode, toSocketKey] = edge;
|
||||||
|
|
||||||
|
// 1. Prevent cycles: If the target node is already a parent, we can't drop here
|
||||||
|
if (parentIds.has(toNode.id)) return false;
|
||||||
|
|
||||||
|
// 2. Prevent self-dropping: Don't drop on edges already connected to this node
|
||||||
|
if (fromNode.id === nodeId || toNode.id === nodeId) return false;
|
||||||
|
|
||||||
|
// 3. Check if edge.source can plug into ANY draggedNode.input
|
||||||
|
const edgeOutputSocketType = fromNode.state?.type?.outputs?.[fromSocketIdx];
|
||||||
|
const canPlugIntoDragged = draggedInputs.some(input => {
|
||||||
|
const acceptedTypes = [input.type, ...(input.accepts || [])];
|
||||||
|
return areSocketsCompatible(edgeOutputSocketType, acceptedTypes);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!canPlugIntoDragged) return false;
|
||||||
|
|
||||||
|
// 4. Check if ANY draggedNode.output can plug into edge.target
|
||||||
|
const targetInput = toNode.state?.type?.inputs?.[toSocketKey];
|
||||||
|
const targetAcceptedTypes = [targetInput?.type, ...(targetInput?.accepts || [])];
|
||||||
|
|
||||||
|
const draggedCanPlugIntoTarget = draggedOutputs.some(outputType =>
|
||||||
|
areSocketsCompatible(outputType, targetAcceptedTypes)
|
||||||
|
);
|
||||||
|
|
||||||
|
return draggedCanPlugIntoTarget;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
getEdgesBetweenNodes(nodes: NodeInstance[]): [number, number, number, string][] {
|
||||||
|
const edges = [];
|
||||||
|
for (const node of nodes) {
|
||||||
|
const children = node.state?.children || [];
|
||||||
|
for (const child of children) {
|
||||||
|
if (nodes.includes(child)) {
|
||||||
|
const edge = this.edges.find(
|
||||||
|
(e) => e[0].id === node.id && e[2].id === child.id
|
||||||
|
);
|
||||||
|
if (edge) {
|
||||||
|
edges.push([edge[0].id, edge[1], edge[2].id, edge[3]] as [
|
||||||
|
number,
|
||||||
|
number,
|
||||||
|
number,
|
||||||
|
string
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return edges;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _init(graph: Graph) {
|
||||||
|
const nodes = new SvelteMap(
|
||||||
|
graph.nodes.map((node) => {
|
||||||
|
const nodeType = this.registry.getNode(node.type);
|
||||||
|
const n = node as NodeInstance;
|
||||||
|
if (nodeType) {
|
||||||
|
n.state = {
|
||||||
|
type: nodeType
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return [node.id, n];
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
this.edges = graph.edges.map((edge) => {
|
||||||
|
const from = nodes.get(edge[0]);
|
||||||
|
const to = nodes.get(edge[2]);
|
||||||
|
if (!from || !to) {
|
||||||
|
throw new Error('Edge references non-existing node');
|
||||||
|
}
|
||||||
|
from.state.children = from.state.children || [];
|
||||||
|
from.state.children.push(to);
|
||||||
|
to.state.parents = to.state.parents || [];
|
||||||
|
to.state.parents.push(from);
|
||||||
|
return [from, edge[1], to, edge[3]] as Edge;
|
||||||
|
});
|
||||||
|
|
||||||
|
this.nodes.clear();
|
||||||
|
for (const [id, node] of nodes) {
|
||||||
|
this.nodes.set(id, node);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.execute();
|
||||||
|
}
|
||||||
|
|
||||||
|
async load(graph: Graph) {
|
||||||
|
const a = performance.now();
|
||||||
|
|
||||||
|
this.loaded = false;
|
||||||
|
this.graph = graph;
|
||||||
|
this.status = 'loading';
|
||||||
|
this.id = graph.id;
|
||||||
|
|
||||||
|
logger.info('loading graph', { nodes: graph.nodes, edges: graph.edges, id: graph.id });
|
||||||
|
|
||||||
|
const nodeIds = Array.from(new SvelteSet([...graph.nodes.map((n) => n.type)]));
|
||||||
|
await this.registry.load(nodeIds);
|
||||||
|
|
||||||
|
// Fetch all nodes from all collections of the loaded nodes
|
||||||
|
const allCollections = new SvelteSet<`${string}/${string}`>();
|
||||||
|
for (const id of nodeIds) {
|
||||||
|
const [user, collection] = id.split('/');
|
||||||
|
allCollections.add(`${user}/${collection}`);
|
||||||
|
}
|
||||||
|
for (const collection of allCollections) {
|
||||||
|
remoteRegistry
|
||||||
|
.fetchCollection(collection)
|
||||||
|
.then((collection: { nodes: { id: NodeId }[] }) => {
|
||||||
|
const ids = collection.nodes.map((n) => n.id);
|
||||||
|
return this.registry.load(ids);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('loaded node types', this.registry.getAllNodes());
|
||||||
|
|
||||||
|
for (const node of this.graph.nodes) {
|
||||||
|
const nodeType = this.registry.getNode(node.type);
|
||||||
|
if (!nodeType) {
|
||||||
|
logger.error(`Node type not found: ${node.type}`);
|
||||||
|
this.status = 'error';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Turn into runtime node
|
||||||
|
const n = node as NodeInstance;
|
||||||
|
n.state = {};
|
||||||
|
n.state.type = nodeType;
|
||||||
|
}
|
||||||
|
|
||||||
|
// load settings
|
||||||
|
const settingTypes: Record<
|
||||||
|
string,
|
||||||
|
// Optional metadata to map settings to specific nodes
|
||||||
|
NodeInput & { __node_type: string; __node_input: string }
|
||||||
|
> = {};
|
||||||
|
const settingValues = graph.settings || {};
|
||||||
|
const types = this.getNodeDefinitions();
|
||||||
|
for (const type of types) {
|
||||||
|
if (type.inputs) {
|
||||||
|
for (const key in type.inputs) {
|
||||||
|
const settingId = type.inputs[key].setting;
|
||||||
|
if (settingId) {
|
||||||
|
settingTypes[settingId] = {
|
||||||
|
__node_type: type.id,
|
||||||
|
__node_input: key,
|
||||||
|
...type.inputs[key]
|
||||||
|
};
|
||||||
|
if (
|
||||||
|
settingValues[settingId] === undefined
|
||||||
|
&& 'value' in type.inputs[key]
|
||||||
|
) {
|
||||||
|
settingValues[settingId] = type.inputs[key].value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.settings = settingValues;
|
||||||
|
this.emit('settings', { types: settingTypes, values: settingValues });
|
||||||
|
|
||||||
|
this.history.reset();
|
||||||
|
this._init(this.graph);
|
||||||
|
|
||||||
|
this.save();
|
||||||
|
|
||||||
|
this.status = 'idle';
|
||||||
|
|
||||||
|
this.loaded = true;
|
||||||
|
logger.log(`Graph loaded in ${performance.now() - a}ms`);
|
||||||
|
setTimeout(() => this.execute(), 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
getAllNodes() {
|
||||||
|
return Array.from(this.nodes.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
getNode(id: number) {
|
||||||
|
return this.nodes.get(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
getNodeType(id: string) {
|
||||||
|
return this.registry.getNode(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async loadNodeType(id: NodeId) {
|
||||||
|
await this.registry.load([id]);
|
||||||
|
const nodeType = this.registry.getNode(id);
|
||||||
|
|
||||||
|
if (!nodeType) return;
|
||||||
|
|
||||||
|
const settingTypes = this.settingTypes;
|
||||||
|
const settingValues = this.settings;
|
||||||
|
if (nodeType.inputs) {
|
||||||
|
for (const key in nodeType.inputs) {
|
||||||
|
const settingId = nodeType.inputs[key].setting;
|
||||||
|
if (settingId) {
|
||||||
|
settingTypes[settingId] = nodeType.inputs[key];
|
||||||
|
if (
|
||||||
|
settingValues
|
||||||
|
&& settingValues?.[settingId] === undefined
|
||||||
|
&& 'value' in nodeType.inputs[key]
|
||||||
|
) {
|
||||||
|
settingValues[settingId] = nodeType.inputs[key].value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.settings = settingValues;
|
||||||
|
this.settingTypes = settingTypes;
|
||||||
|
this.emit('settings', { types: settingTypes, values: settingValues });
|
||||||
|
}
|
||||||
|
|
||||||
|
getChildren(node: NodeInstance) {
|
||||||
|
const children = [];
|
||||||
|
const stack = node.state?.children?.slice(0);
|
||||||
|
while (stack?.length) {
|
||||||
|
const child = stack.pop();
|
||||||
|
if (!child) continue;
|
||||||
|
children.push(child);
|
||||||
|
stack.push(...(child.state?.children || []));
|
||||||
|
}
|
||||||
|
return children;
|
||||||
|
}
|
||||||
|
|
||||||
|
getNodesBetween(from: NodeInstance, to: NodeInstance): NodeInstance[] | undefined {
|
||||||
|
// < - - - - from
|
||||||
|
const toParents = this.getParentsOfNode(to);
|
||||||
|
// < - - - - from - - - - to
|
||||||
|
const fromParents = this.getParentsOfNode(from);
|
||||||
|
if (toParents.includes(from)) {
|
||||||
|
const fromChildren = this.getChildren(from);
|
||||||
|
return toParents.filter((n) => fromChildren.includes(n));
|
||||||
|
} else if (fromParents.includes(to)) {
|
||||||
|
const toChildren = this.getChildren(to);
|
||||||
|
return fromParents.filter((n) => toChildren.includes(n));
|
||||||
|
} else {
|
||||||
|
// these two nodes are not connected
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
removeNode(node: NodeInstance, { restoreEdges = false } = {}) {
|
||||||
|
const edgesToNode = this.edges.filter((edge) => edge[2].id === node.id);
|
||||||
|
const edgesFromNode = this.edges.filter((edge) => edge[0].id === node.id);
|
||||||
|
for (const edge of [...edgesToNode, ...edgesFromNode]) {
|
||||||
|
this.removeEdge(edge, { applyDeletion: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (restoreEdges) {
|
||||||
|
const outputSockets = edgesToNode.map((e) => [e[0], e[1]] as const);
|
||||||
|
const inputSockets = edgesFromNode.map((e) => [e[2], e[3]] as const);
|
||||||
|
|
||||||
|
for (const [to, toSocket] of inputSockets) {
|
||||||
|
for (const [from, fromSocket] of outputSockets) {
|
||||||
|
const outputType = from.state?.type?.outputs?.[fromSocket];
|
||||||
|
const inputType = to?.state?.type?.inputs?.[toSocket]?.type;
|
||||||
|
if (outputType === inputType) {
|
||||||
|
this.createEdge(from, fromSocket, to, toSocket, {
|
||||||
|
applyUpdate: false
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.nodes.delete(node.id);
|
||||||
|
this.execute();
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
smartConnect(from: NodeInstance, to: NodeInstance): Edge | undefined {
|
||||||
|
const inputs = Object.entries(to.state?.type?.inputs ?? {});
|
||||||
|
const outputs = from.state?.type?.outputs ?? [];
|
||||||
|
for (let i = 0; i < inputs.length; i++) {
|
||||||
|
const [inputName, input] = inputs[0];
|
||||||
|
for (let o = 0; o < outputs.length; o++) {
|
||||||
|
const output = outputs[0];
|
||||||
|
if (input.type === output) {
|
||||||
|
return this.createEdge(from, o, to, inputName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
createNodeId() {
|
||||||
|
return Math.max(0, ...this.nodes.keys()) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
createGraph(nodes: NodeInstance[], edges: [number, number, number, string][]) {
|
||||||
|
// map old ids to new ids
|
||||||
|
const idMap = new SvelteMap<number, number>();
|
||||||
|
|
||||||
|
let startId = this.createNodeId();
|
||||||
|
|
||||||
|
nodes = nodes.map((node) => {
|
||||||
|
const id = startId++;
|
||||||
|
idMap.set(node.id, id);
|
||||||
|
const type = this.registry.getNode(node.type);
|
||||||
|
if (!type) {
|
||||||
|
throw new Error(`Node type not found: ${node.type}`);
|
||||||
|
}
|
||||||
|
return { ...node, id, tmp: { type } };
|
||||||
|
});
|
||||||
|
|
||||||
|
const _edges = edges.map((edge) => {
|
||||||
|
const from = nodes.find((n) => n.id === idMap.get(edge[0]));
|
||||||
|
const to = nodes.find((n) => n.id === idMap.get(edge[2]));
|
||||||
|
|
||||||
|
if (!from || !to) {
|
||||||
|
throw new Error('Edge references non-existing node');
|
||||||
|
}
|
||||||
|
|
||||||
|
to.state.parents = to.state.parents || [];
|
||||||
|
to.state.parents.push(from);
|
||||||
|
|
||||||
|
from.state.children = from.state.children || [];
|
||||||
|
from.state.children.push(to);
|
||||||
|
|
||||||
|
return [from, edge[1], to, edge[3]] as Edge;
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
this.nodes.set(node.id, node);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.edges.push(..._edges);
|
||||||
|
|
||||||
|
this.save();
|
||||||
|
return nodes;
|
||||||
|
}
|
||||||
|
|
||||||
|
createNode({
|
||||||
|
type,
|
||||||
|
position,
|
||||||
|
props = {}
|
||||||
|
}: {
|
||||||
|
type: NodeInstance['type'];
|
||||||
|
position: NodeInstance['position'];
|
||||||
|
props: NodeInstance['props'];
|
||||||
|
}) {
|
||||||
|
const nodeType = this.registry.getNode(type);
|
||||||
|
if (!nodeType) {
|
||||||
|
logger.error(`Node type not found: ${type}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const node: NodeInstance = $state({
|
||||||
|
id: this.createNodeId(),
|
||||||
|
type,
|
||||||
|
position,
|
||||||
|
state: { type: nodeType },
|
||||||
|
props
|
||||||
|
});
|
||||||
|
|
||||||
|
this.nodes.set(node.id, node);
|
||||||
|
|
||||||
|
this.save();
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
createEdge(
|
||||||
|
from: NodeInstance,
|
||||||
|
fromSocket: number,
|
||||||
|
to: NodeInstance,
|
||||||
|
toSocket: string,
|
||||||
|
{ applyUpdate = true } = {}
|
||||||
|
): Edge | undefined {
|
||||||
|
const existingEdges = this.getEdgesToNode(to);
|
||||||
|
|
||||||
|
// check if this exact edge already exists
|
||||||
|
const existingEdge = existingEdges.find(
|
||||||
|
(e) => e[0].id === from.id && e[1] === fromSocket && e[3] === toSocket
|
||||||
|
);
|
||||||
|
if (existingEdge) {
|
||||||
|
logger.error('Edge already exists', existingEdge);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// check if socket types match
|
||||||
|
const fromSocketType = from.state?.type?.outputs?.[fromSocket];
|
||||||
|
const toSocketType = [to.state?.type?.inputs?.[toSocket]?.type];
|
||||||
|
if (to.state?.type?.inputs?.[toSocket]?.accepts) {
|
||||||
|
toSocketType.push(...(to?.state?.type?.inputs?.[toSocket]?.accepts || []));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!areSocketsCompatible(fromSocketType, toSocketType)) {
|
||||||
|
logger.error(
|
||||||
|
`Socket types do not match: ${fromSocketType} !== ${toSocketType}`
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const edgeToBeReplaced = this.edges.find(
|
||||||
|
(e) => e[2].id === to.id && e[3] === toSocket
|
||||||
|
);
|
||||||
|
if (edgeToBeReplaced) {
|
||||||
|
this.removeEdge(edgeToBeReplaced, { applyDeletion: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
const edge = [from, fromSocket, to, toSocket] as Edge;
|
||||||
|
|
||||||
|
this.edges.push(edge);
|
||||||
|
|
||||||
|
from.state.children = from.state.children || [];
|
||||||
|
from.state.children.push(to);
|
||||||
|
to.state.parents = to.state.parents || [];
|
||||||
|
to.state.parents.push(from);
|
||||||
|
|
||||||
|
if (applyUpdate) {
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
this.execute();
|
||||||
|
|
||||||
|
return edge;
|
||||||
|
}
|
||||||
|
|
||||||
|
undo() {
|
||||||
|
const nextState = this.history.undo();
|
||||||
|
if (nextState) {
|
||||||
|
this._init(nextState);
|
||||||
|
this.emit('save', this.serialize());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
redo() {
|
||||||
|
const nextState = this.history.redo();
|
||||||
|
if (nextState) {
|
||||||
|
this._init(nextState);
|
||||||
|
this.emit('save', this.serialize());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
startUndoGroup() {
|
||||||
|
this.currentUndoGroup = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
saveUndoGroup() {
|
||||||
|
this.currentUndoGroup = null;
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
save() {
|
||||||
|
if (this.currentUndoGroup) return;
|
||||||
|
const state = this.serialize();
|
||||||
|
this.history.save(state);
|
||||||
|
|
||||||
|
// This is some stupid race condition where the graph-manager emits a save event
|
||||||
|
// when the graph is not fully loaded
|
||||||
|
if (this.nodes.size === 0 && this.edges.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.emit('save', state);
|
||||||
|
logger.log('saving graphs', state);
|
||||||
|
}
|
||||||
|
|
||||||
|
getParentsOfNode(node: NodeInstance) {
|
||||||
|
const parents = [];
|
||||||
|
const stack = node.state?.parents?.slice(0);
|
||||||
|
while (stack?.length) {
|
||||||
|
if (parents.length > 1000000) {
|
||||||
|
logger.warn('Infinite loop detected');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const parent = stack.pop();
|
||||||
|
if (!parent) continue;
|
||||||
|
parents.push(parent);
|
||||||
|
stack.push(...(parent.state?.parents || []));
|
||||||
|
}
|
||||||
|
return parents.reverse();
|
||||||
|
}
|
||||||
|
|
||||||
|
getPossibleNodes(socket: Socket): NodeDefinition[] {
|
||||||
|
const allDefinitions = this.getNodeDefinitions();
|
||||||
|
|
||||||
|
const nodeType = socket.node.state?.type;
|
||||||
|
if (!nodeType) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const definitions = typeof socket.index === 'string'
|
||||||
|
? allDefinitions.filter(s => {
|
||||||
|
return s.outputs?.find(_s =>
|
||||||
|
Object
|
||||||
|
.values(nodeType?.inputs || {})
|
||||||
|
.map(s => s.type)
|
||||||
|
.includes(_s as NodeInput['type'])
|
||||||
|
);
|
||||||
|
})
|
||||||
|
: allDefinitions.filter(s =>
|
||||||
|
Object
|
||||||
|
.values(s.inputs ?? {})
|
||||||
|
.find(s => {
|
||||||
|
if (s.hidden) return false;
|
||||||
|
if (nodeType.outputs?.includes(s.type)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return s.accepts?.find(a => nodeType.outputs?.includes(a));
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
return definitions;
|
||||||
|
}
|
||||||
|
|
||||||
|
getPossibleSockets({ node, index }: Socket): [NodeInstance, string | number][] {
|
||||||
|
const nodeType = node?.state?.type;
|
||||||
|
if (!nodeType) return [];
|
||||||
|
|
||||||
|
const sockets: [NodeInstance, string | number][] = [];
|
||||||
|
|
||||||
|
// if index is a string, we are an input looking for outputs
|
||||||
|
if (typeof index === 'string') {
|
||||||
|
// filter out self and child nodes
|
||||||
|
const children = new SvelteSet(this.getChildren(node).map((n) => n.id));
|
||||||
|
const nodes = this.getAllNodes().filter(
|
||||||
|
(n) => n.id !== node.id && !children.has(n.id)
|
||||||
|
);
|
||||||
|
|
||||||
|
const ownType = nodeType?.inputs?.[index].type;
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
const nodeType = node?.state?.type;
|
||||||
|
const inputs = nodeType?.outputs;
|
||||||
|
if (!inputs) continue;
|
||||||
|
for (let index = 0; index < inputs.length; index++) {
|
||||||
|
if (inputs[index] === ownType) {
|
||||||
|
sockets.push([node, index]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (typeof index === 'number') {
|
||||||
|
// if index is a number, we are an output looking for inputs
|
||||||
|
|
||||||
|
// filter out self and parent nodes
|
||||||
|
const parents = new SvelteSet(this.getParentsOfNode(node).map((n) => n.id));
|
||||||
|
const nodes = this.getAllNodes().filter(
|
||||||
|
(n) => n.id !== node.id && !parents.has(n.id)
|
||||||
|
);
|
||||||
|
|
||||||
|
const edges = new SvelteMap<number, string[]>();
|
||||||
|
this.getEdgesFromNode(node)
|
||||||
|
.filter((e) => e[1] === index)
|
||||||
|
.forEach((e) => {
|
||||||
|
if (edges.has(e[2].id)) {
|
||||||
|
edges.get(e[2].id)?.push(e[3]);
|
||||||
|
} else {
|
||||||
|
edges.set(e[2].id, [e[3]]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const ownType = nodeType.outputs?.[index];
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
const inputs = node?.state?.type?.inputs;
|
||||||
|
if (!inputs) continue;
|
||||||
|
for (const key in inputs) {
|
||||||
|
const otherType = [inputs[key].type];
|
||||||
|
otherType.push(...(inputs[key].accepts || []));
|
||||||
|
|
||||||
|
if (
|
||||||
|
areSocketsCompatible(ownType, otherType)
|
||||||
|
&& !edges.get(node.id)?.includes(key)
|
||||||
|
) {
|
||||||
|
sockets.push([node, key]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return sockets;
|
||||||
|
}
|
||||||
|
|
||||||
|
removeEdge(
|
||||||
|
edge: Edge,
|
||||||
|
{ applyDeletion = true }: { applyDeletion?: boolean } = {}
|
||||||
|
) {
|
||||||
|
const id0 = edge[0].id;
|
||||||
|
const sid0 = edge[1];
|
||||||
|
const id2 = edge[2].id;
|
||||||
|
const sid2 = edge[3];
|
||||||
|
|
||||||
|
const _edge = this.edges.find(
|
||||||
|
(e) => e[0].id === id0 && e[1] === sid0 && e[2].id === id2 && e[3] === sid2
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!_edge) return;
|
||||||
|
|
||||||
|
if (edge[0].state.children) {
|
||||||
|
edge[0].state.children = edge[0].state.children.filter(
|
||||||
|
(n: NodeInstance) => n.id !== id2
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (edge[2].state.parents) {
|
||||||
|
edge[2].state.parents = edge[2].state.parents.filter(
|
||||||
|
(n: NodeInstance) => n.id !== id0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.edges = this.edges.filter((e) => !areEdgesEqual(e, edge));
|
||||||
|
if (applyDeletion) {
|
||||||
|
this.execute();
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getEdgesToNode(node: NodeInstance) {
|
||||||
|
return this.edges
|
||||||
|
.filter((edge) => edge[2].id === node.id)
|
||||||
|
.map((edge) => {
|
||||||
|
const from = this.getNode(edge[0].id);
|
||||||
|
const to = this.getNode(edge[2].id);
|
||||||
|
if (!from || !to) return;
|
||||||
|
return [from, edge[1], to, edge[3]] as const;
|
||||||
|
})
|
||||||
|
.filter(Boolean) as unknown as [NodeInstance, number, NodeInstance, string][];
|
||||||
|
}
|
||||||
|
|
||||||
|
getEdgesFromNode(node: NodeInstance) {
|
||||||
|
return this.edges
|
||||||
|
.filter((edge) => edge[0].id === node.id)
|
||||||
|
.map((edge) => {
|
||||||
|
const from = this.getNode(edge[0].id);
|
||||||
|
const to = this.getNode(edge[2].id);
|
||||||
|
if (!from || !to) return;
|
||||||
|
return [from, edge[1], to, edge[3]] as const;
|
||||||
|
})
|
||||||
|
.filter(Boolean) as unknown as [NodeInstance, number, NodeInstance, string][];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,611 +0,0 @@
|
|||||||
import type { Edge, Graph, Node, NodeInput, NodeRegistry, Socket, } from "@nodes/types";
|
|
||||||
import { fastHashString } from "@nodes/utils";
|
|
||||||
import { writable, type Writable } from "svelte/store";
|
|
||||||
import EventEmitter from "./helpers/EventEmitter.js";
|
|
||||||
import { createLogger } from "./helpers/index.js";
|
|
||||||
import throttle from "./helpers/throttle.js";
|
|
||||||
import { HistoryManager } from "./history-manager.js";
|
|
||||||
|
|
||||||
const logger = createLogger("graph-manager");
|
|
||||||
|
|
||||||
logger.mute();
|
|
||||||
|
|
||||||
const clone = "structuredClone" in self ? self.structuredClone : (args: any) => JSON.parse(JSON.stringify(args));
|
|
||||||
|
|
||||||
function areSocketsCompatible(output: string | undefined, inputs: string | string[] | undefined) {
|
|
||||||
if (Array.isArray(inputs) && output) {
|
|
||||||
return inputs.includes(output);
|
|
||||||
}
|
|
||||||
return inputs === output;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class GraphManager extends EventEmitter<{ "save": Graph, "result": any, "settings": { types: Record<string, NodeInput>, values: Record<string, unknown> } }> {
|
|
||||||
|
|
||||||
status: Writable<"loading" | "idle" | "error"> = writable("loading");
|
|
||||||
loaded = false;
|
|
||||||
|
|
||||||
graph: Graph = { id: 0, nodes: [], edges: [] };
|
|
||||||
id = writable(0);
|
|
||||||
|
|
||||||
private _nodes: Map<number, Node> = new Map();
|
|
||||||
nodes: Writable<Map<number, Node>> = writable(new Map());
|
|
||||||
|
|
||||||
private _edges: Edge[] = [];
|
|
||||||
edges: Writable<Edge[]> = writable([]);
|
|
||||||
|
|
||||||
settingTypes: Record<string, NodeInput> = {};
|
|
||||||
settings: Record<string, unknown> = {};
|
|
||||||
|
|
||||||
currentUndoGroup: number | null = null;
|
|
||||||
|
|
||||||
inputSockets: Writable<Set<string>> = writable(new Set());
|
|
||||||
|
|
||||||
history: HistoryManager = new HistoryManager();
|
|
||||||
execute = throttle(() => {
|
|
||||||
if (this.loaded === false) return;
|
|
||||||
this.emit("result", this.serialize());
|
|
||||||
}, 10);
|
|
||||||
|
|
||||||
constructor(public registry: NodeRegistry) {
|
|
||||||
super();
|
|
||||||
this.nodes.subscribe((nodes) => {
|
|
||||||
this._nodes = nodes;
|
|
||||||
});
|
|
||||||
this.edges.subscribe((edges) => {
|
|
||||||
this._edges = edges;
|
|
||||||
const s = new Set<string>();
|
|
||||||
for (const edge of edges) {
|
|
||||||
s.add(`${edge[2].id}-${edge[3]}`);
|
|
||||||
}
|
|
||||||
this.inputSockets.set(s);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
serialize(): Graph {
|
|
||||||
logger.group("serializing graph")
|
|
||||||
const nodes = Array.from(this._nodes.values()).map(node => ({
|
|
||||||
id: node.id,
|
|
||||||
position: [...node.position],
|
|
||||||
type: node.type,
|
|
||||||
props: node.props,
|
|
||||||
})) as Node[];
|
|
||||||
const edges = this._edges.map(edge => [edge[0].id, edge[1], edge[2].id, edge[3]]) as Graph["edges"];
|
|
||||||
const serialized = { id: this.graph.id, settings: this.settings, nodes, edges };
|
|
||||||
logger.groupEnd();
|
|
||||||
|
|
||||||
return clone(serialized);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private lastSettingsHash = 0;
|
|
||||||
setSettings(settings: Record<string, unknown>) {
|
|
||||||
|
|
||||||
let hash = fastHashString(JSON.stringify(settings));
|
|
||||||
if (hash === this.lastSettingsHash) return;
|
|
||||||
this.lastSettingsHash = hash;
|
|
||||||
|
|
||||||
this.settings = settings;
|
|
||||||
this.save();
|
|
||||||
this.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
getNodeDefinitions() {
|
|
||||||
return this.registry.getAllNodes();
|
|
||||||
}
|
|
||||||
|
|
||||||
getLinkedNodes(node: Node) {
|
|
||||||
const nodes = new Set<Node>();
|
|
||||||
const stack = [node];
|
|
||||||
while (stack.length) {
|
|
||||||
const n = stack.pop();
|
|
||||||
if (!n) continue;
|
|
||||||
nodes.add(n);
|
|
||||||
const children = this.getChildrenOfNode(n);
|
|
||||||
const parents = this.getParentsOfNode(n);
|
|
||||||
const newNodes = [...children, ...parents].filter(n => !nodes.has(n));
|
|
||||||
stack.push(...newNodes);
|
|
||||||
}
|
|
||||||
return [...nodes.values()];
|
|
||||||
}
|
|
||||||
|
|
||||||
getEdgesBetweenNodes(nodes: Node[]): [number, number, number, string][] {
|
|
||||||
const edges = [];
|
|
||||||
for (const node of nodes) {
|
|
||||||
const children = node.tmp?.children || [];
|
|
||||||
for (const child of children) {
|
|
||||||
if (nodes.includes(child)) {
|
|
||||||
const edge = this._edges.find(e => e[0].id === node.id && e[2].id === child.id);
|
|
||||||
if (edge) {
|
|
||||||
edges.push([edge[0].id, edge[1], edge[2].id, edge[3]] as [number, number, number, string]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return edges;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private _init(graph: Graph) {
|
|
||||||
const nodes = new Map(graph.nodes.map(node => {
|
|
||||||
const nodeType = this.registry.getNode(node.type);
|
|
||||||
if (nodeType) {
|
|
||||||
node.tmp = {
|
|
||||||
random: (Math.random() - 0.5) * 2,
|
|
||||||
type: nodeType
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return [node.id, node]
|
|
||||||
}));
|
|
||||||
|
|
||||||
const edges = graph.edges.map((edge) => {
|
|
||||||
const from = nodes.get(edge[0]);
|
|
||||||
const to = nodes.get(edge[2]);
|
|
||||||
if (!from || !to) {
|
|
||||||
throw new Error("Edge references non-existing node");
|
|
||||||
};
|
|
||||||
from.tmp = from.tmp || {};
|
|
||||||
from.tmp.children = from.tmp.children || [];
|
|
||||||
from.tmp.children.push(to);
|
|
||||||
to.tmp = to.tmp || {};
|
|
||||||
to.tmp.parents = to.tmp.parents || [];
|
|
||||||
to.tmp.parents.push(from);
|
|
||||||
return [from, edge[1], to, edge[3]] as Edge;
|
|
||||||
})
|
|
||||||
|
|
||||||
this.edges.set(edges);
|
|
||||||
this.nodes.set(nodes);
|
|
||||||
|
|
||||||
this.execute();
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
async load(graph: Graph) {
|
|
||||||
|
|
||||||
const a = performance.now();
|
|
||||||
|
|
||||||
this.loaded = false;
|
|
||||||
this.graph = graph;
|
|
||||||
this.status.set("loading");
|
|
||||||
this.id.set(graph.id);
|
|
||||||
|
|
||||||
const nodeIds = Array.from(new Set([...graph.nodes.map(n => n.type)]));
|
|
||||||
await this.registry.load(nodeIds);
|
|
||||||
|
|
||||||
for (const node of this.graph.nodes) {
|
|
||||||
const nodeType = this.registry.getNode(node.type);
|
|
||||||
if (!nodeType) {
|
|
||||||
logger.error(`Node type not found: ${node.type}`);
|
|
||||||
this.status.set("error");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
node.tmp = node.tmp || {};
|
|
||||||
node.tmp.random = (Math.random() - 0.5) * 2;
|
|
||||||
node.tmp.type = nodeType;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// load settings
|
|
||||||
const settingTypes: Record<string, NodeInput> = {};
|
|
||||||
const settingValues = graph.settings || {};
|
|
||||||
const types = this.getNodeDefinitions();
|
|
||||||
for (const type of types) {
|
|
||||||
if (type.inputs) {
|
|
||||||
for (const key in type.inputs) {
|
|
||||||
let settingId = type.inputs[key].setting;
|
|
||||||
if (settingId) {
|
|
||||||
settingTypes[settingId] = { __node_type: type.id, __node_input: key, ...type.inputs[key] };
|
|
||||||
if (settingValues[settingId] === undefined && "value" in type.inputs[key]) {
|
|
||||||
settingValues[settingId] = type.inputs[key].value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.settings = settingValues;
|
|
||||||
this.emit("settings", { types: settingTypes, values: settingValues });
|
|
||||||
|
|
||||||
this.history.reset();
|
|
||||||
this._init(this.graph);
|
|
||||||
|
|
||||||
this.save();
|
|
||||||
|
|
||||||
this.status.set("idle");
|
|
||||||
|
|
||||||
this.loaded = true;
|
|
||||||
logger.log(`Graph loaded in ${performance.now() - a}ms`);
|
|
||||||
setTimeout(() => this.execute(), 100);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
getAllNodes() {
|
|
||||||
return Array.from(this._nodes.values());
|
|
||||||
}
|
|
||||||
|
|
||||||
getNode(id: number) {
|
|
||||||
return this._nodes.get(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
getNodeType(id: string) {
|
|
||||||
return this.registry.getNode(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
async loadNode(id: string) {
|
|
||||||
|
|
||||||
await this.registry.load([id]);
|
|
||||||
const nodeType = this.registry.getNode(id);
|
|
||||||
|
|
||||||
if (!nodeType) return;
|
|
||||||
|
|
||||||
const settingTypes = this.settingTypes;
|
|
||||||
const settingValues = this.settings;
|
|
||||||
if (nodeType.inputs) {
|
|
||||||
for (const key in nodeType.inputs) {
|
|
||||||
let settingId = nodeType.inputs[key].setting;
|
|
||||||
if (settingId) {
|
|
||||||
settingTypes[settingId] = nodeType.inputs[key];
|
|
||||||
if (settingValues[settingId] === undefined && "value" in nodeType.inputs[key]) {
|
|
||||||
settingValues[settingId] = nodeType.inputs[key].value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.settings = settingValues;
|
|
||||||
this.settingTypes = settingTypes;
|
|
||||||
this.emit("settings", { types: settingTypes, values: settingValues });
|
|
||||||
}
|
|
||||||
|
|
||||||
getChildrenOfNode(node: Node) {
|
|
||||||
const children = [];
|
|
||||||
const stack = node.tmp?.children?.slice(0);
|
|
||||||
while (stack?.length) {
|
|
||||||
const child = stack.pop();
|
|
||||||
if (!child) continue;
|
|
||||||
children.push(child);
|
|
||||||
stack.push(...child.tmp?.children || []);
|
|
||||||
}
|
|
||||||
return children;
|
|
||||||
}
|
|
||||||
|
|
||||||
getNodesBetween(from: Node, to: Node): Node[] | undefined {
|
|
||||||
// < - - - - from
|
|
||||||
const toParents = this.getParentsOfNode(to);
|
|
||||||
// < - - - - from - - - - to
|
|
||||||
const fromParents = this.getParentsOfNode(from);
|
|
||||||
if (toParents.includes(from)) {
|
|
||||||
const fromChildren = this.getChildrenOfNode(from);
|
|
||||||
return toParents.filter(n => fromChildren.includes(n));
|
|
||||||
} else if (fromParents.includes(to)) {
|
|
||||||
const toChildren = this.getChildrenOfNode(to);
|
|
||||||
return fromParents.filter(n => toChildren.includes(n));
|
|
||||||
} else {
|
|
||||||
// these two nodes are not connected
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
removeNode(node: Node, { restoreEdges = false } = {}) {
|
|
||||||
|
|
||||||
const edgesToNode = this._edges.filter((edge) => edge[2].id === node.id);
|
|
||||||
const edgesFromNode = this._edges.filter((edge) => edge[0].id === node.id);
|
|
||||||
for (const edge of [...edgesToNode, ...edgesFromNode]) {
|
|
||||||
this.removeEdge(edge, { applyDeletion: false });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (restoreEdges) {
|
|
||||||
const outputSockets = edgesToNode.map(e => [e[0], e[1]] as const);
|
|
||||||
const inputSockets = edgesFromNode.map(e => [e[2], e[3]] as const);
|
|
||||||
|
|
||||||
for (const [to, toSocket] of inputSockets) {
|
|
||||||
for (const [from, fromSocket] of outputSockets) {
|
|
||||||
const outputType = from.tmp?.type?.outputs?.[fromSocket];
|
|
||||||
const inputType = to?.tmp?.type?.inputs?.[toSocket]?.type;
|
|
||||||
if (outputType === inputType) {
|
|
||||||
this.createEdge(from, fromSocket, to, toSocket, { applyUpdate: false });
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.edges.set(this._edges);
|
|
||||||
|
|
||||||
this.nodes.update((nodes) => {
|
|
||||||
nodes.delete(node.id);
|
|
||||||
return nodes;
|
|
||||||
});
|
|
||||||
this.execute()
|
|
||||||
this.save();
|
|
||||||
}
|
|
||||||
|
|
||||||
createNodeId() {
|
|
||||||
const max = Math.max(...this._nodes.keys());
|
|
||||||
return max + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
createGraph(nodes: Node[], edges: [number, number, number, string][]) {
|
|
||||||
|
|
||||||
// map old ids to new ids
|
|
||||||
const idMap = new Map<number, number>();
|
|
||||||
|
|
||||||
const startId = this.createNodeId();
|
|
||||||
|
|
||||||
nodes = nodes.map((node, i) => {
|
|
||||||
const id = startId + i;
|
|
||||||
idMap.set(node.id, id);
|
|
||||||
const type = this.registry.getNode(node.type);
|
|
||||||
if (!type) {
|
|
||||||
throw new Error(`Node type not found: ${node.type}`);
|
|
||||||
}
|
|
||||||
return { ...node, id, tmp: { type } };
|
|
||||||
});
|
|
||||||
|
|
||||||
const _edges = edges.map(edge => {
|
|
||||||
const from = nodes.find(n => n.id === idMap.get(edge[0]));
|
|
||||||
const to = nodes.find(n => n.id === idMap.get(edge[2]));
|
|
||||||
|
|
||||||
if (!from || !to) {
|
|
||||||
throw new Error("Edge references non-existing node");
|
|
||||||
}
|
|
||||||
|
|
||||||
to.tmp = to.tmp || {};
|
|
||||||
to.tmp.parents = to.tmp.parents || [];
|
|
||||||
to.tmp.parents.push(from);
|
|
||||||
|
|
||||||
from.tmp = from.tmp || {};
|
|
||||||
from.tmp.children = from.tmp.children || [];
|
|
||||||
from.tmp.children.push(to);
|
|
||||||
|
|
||||||
return [from, edge[1], to, edge[3]] as Edge;
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const node of nodes) {
|
|
||||||
this._nodes.set(node.id, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this._edges.push(..._edges);
|
|
||||||
|
|
||||||
this.nodes.set(this._nodes);
|
|
||||||
this.edges.set(this._edges);
|
|
||||||
this.save();
|
|
||||||
return nodes;
|
|
||||||
}
|
|
||||||
|
|
||||||
createNode({ type, position, props = {} }: { type: Node["type"], position: Node["position"], props: Node["props"] }) {
|
|
||||||
|
|
||||||
const nodeType = this.registry.getNode(type);
|
|
||||||
if (!nodeType) {
|
|
||||||
logger.error(`Node type not found: ${type}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const node: Node = { id: this.createNodeId(), type, position, tmp: { type: nodeType }, props };
|
|
||||||
|
|
||||||
this.nodes.update((nodes) => {
|
|
||||||
nodes.set(node.id, node);
|
|
||||||
return nodes;
|
|
||||||
});
|
|
||||||
|
|
||||||
this.save();
|
|
||||||
}
|
|
||||||
|
|
||||||
createEdge(from: Node, fromSocket: number, to: Node, toSocket: string, { applyUpdate = true } = {}) {
|
|
||||||
|
|
||||||
const existingEdges = this.getEdgesToNode(to);
|
|
||||||
|
|
||||||
// check if this exact edge already exists
|
|
||||||
const existingEdge = existingEdges.find(e => e[0].id === from.id && e[1] === fromSocket && e[3] === toSocket);
|
|
||||||
if (existingEdge) {
|
|
||||||
logger.error("Edge already exists", existingEdge);
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
// check if socket types match
|
|
||||||
const fromSocketType = from.tmp?.type?.outputs?.[fromSocket];
|
|
||||||
const toSocketType = [to.tmp?.type?.inputs?.[toSocket]?.type];
|
|
||||||
if (to.tmp?.type?.inputs?.[toSocket]?.accepts) {
|
|
||||||
toSocketType.push(...(to?.tmp?.type?.inputs?.[toSocket]?.accepts || []));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!areSocketsCompatible(fromSocketType, toSocketType)) {
|
|
||||||
logger.error(`Socket types do not match: ${fromSocketType} !== ${toSocketType}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const edgeToBeReplaced = this._edges.find(e => e[2].id === to.id && e[3] === toSocket);
|
|
||||||
if (edgeToBeReplaced) {
|
|
||||||
this.removeEdge(edgeToBeReplaced, { applyDeletion: false });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (applyUpdate) {
|
|
||||||
this._edges.push([from, fromSocket, to, toSocket]);
|
|
||||||
} else {
|
|
||||||
this._edges.push([from, fromSocket, to, toSocket]);
|
|
||||||
}
|
|
||||||
|
|
||||||
from.tmp = from.tmp || {};
|
|
||||||
from.tmp.children = from.tmp.children || [];
|
|
||||||
from.tmp.children.push(to);
|
|
||||||
|
|
||||||
to.tmp = to.tmp || {};
|
|
||||||
to.tmp.parents = to.tmp.parents || [];
|
|
||||||
to.tmp.parents.push(from);
|
|
||||||
|
|
||||||
if (applyUpdate) {
|
|
||||||
this.edges.set(this._edges);
|
|
||||||
this.save();
|
|
||||||
}
|
|
||||||
this.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
undo() {
|
|
||||||
const nextState = this.history.undo();
|
|
||||||
if (nextState) {
|
|
||||||
this._init(nextState);
|
|
||||||
this.emit("save", this.serialize());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
redo() {
|
|
||||||
const nextState = this.history.redo();
|
|
||||||
if (nextState) {
|
|
||||||
this._init(nextState);
|
|
||||||
this.emit("save", this.serialize());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
startUndoGroup() {
|
|
||||||
this.currentUndoGroup = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
saveUndoGroup() {
|
|
||||||
this.currentUndoGroup = null;
|
|
||||||
this.save();
|
|
||||||
}
|
|
||||||
|
|
||||||
save() {
|
|
||||||
if (this.currentUndoGroup) return;
|
|
||||||
const state = this.serialize();
|
|
||||||
this.history.save(state);
|
|
||||||
this.emit("save", state);
|
|
||||||
logger.log("saving graphs", state);
|
|
||||||
}
|
|
||||||
|
|
||||||
getParentsOfNode(node: Node) {
|
|
||||||
const parents = [];
|
|
||||||
const stack = node.tmp?.parents?.slice(0);
|
|
||||||
while (stack?.length) {
|
|
||||||
if (parents.length > 1000000) {
|
|
||||||
logger.warn("Infinite loop detected")
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
const parent = stack.pop();
|
|
||||||
if (!parent) continue;
|
|
||||||
parents.push(parent);
|
|
||||||
stack.push(...parent.tmp?.parents || []);
|
|
||||||
}
|
|
||||||
return parents.reverse();
|
|
||||||
}
|
|
||||||
|
|
||||||
getPossibleSockets({ node, index }: Socket): [Node, string | number][] {
|
|
||||||
|
|
||||||
const nodeType = node?.tmp?.type;
|
|
||||||
if (!nodeType) return [];
|
|
||||||
|
|
||||||
const sockets: [Node, string | number][] = []
|
|
||||||
|
|
||||||
// if index is a string, we are an input looking for outputs
|
|
||||||
if (typeof index === "string") {
|
|
||||||
|
|
||||||
// filter out self and child nodes
|
|
||||||
const children = new Set(this.getChildrenOfNode(node).map(n => n.id));
|
|
||||||
const nodes = this.getAllNodes().filter(n => n.id !== node.id && !children.has(n.id));
|
|
||||||
|
|
||||||
const ownType = nodeType?.inputs?.[index].type;
|
|
||||||
|
|
||||||
for (const node of nodes) {
|
|
||||||
const nodeType = node?.tmp?.type;
|
|
||||||
const inputs = nodeType?.outputs;
|
|
||||||
if (!inputs) continue;
|
|
||||||
for (let index = 0; index < inputs.length; index++) {
|
|
||||||
if (inputs[index] === ownType) {
|
|
||||||
sockets.push([node, index]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} else if (typeof index === "number") {
|
|
||||||
// if index is a number, we are an output looking for inputs
|
|
||||||
|
|
||||||
// filter out self and parent nodes
|
|
||||||
const parents = new Set(this.getParentsOfNode(node).map(n => n.id));
|
|
||||||
const nodes = this.getAllNodes().filter(n => n.id !== node.id && !parents.has(n.id));
|
|
||||||
|
|
||||||
// get edges from this socket
|
|
||||||
const edges = new Map(this.getEdgesFromNode(node).filter(e => e[1] === index).map(e => [e[2].id, e[3]]));
|
|
||||||
|
|
||||||
const ownType = nodeType.outputs?.[index];
|
|
||||||
|
|
||||||
for (const node of nodes) {
|
|
||||||
const inputs = node?.tmp?.type?.inputs;
|
|
||||||
if (!inputs) continue;
|
|
||||||
for (const key in inputs) {
|
|
||||||
|
|
||||||
const otherType = [inputs[key].type];
|
|
||||||
otherType.push(...(inputs[key].accepts || []));
|
|
||||||
|
|
||||||
if (areSocketsCompatible(ownType, otherType) && edges.get(node.id) !== key) {
|
|
||||||
sockets.push([node, key]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return sockets;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
removeEdge(edge: Edge, { applyDeletion = true }: { applyDeletion?: boolean } = {}) {
|
|
||||||
const id0 = edge[0].id;
|
|
||||||
const sid0 = edge[1];
|
|
||||||
const id2 = edge[2].id;
|
|
||||||
const sid2 = edge[3];
|
|
||||||
|
|
||||||
const _edge = this._edges.find((e) => e[0].id === id0 && e[1] === sid0 && e[2].id === id2 && e[3] === sid2);
|
|
||||||
if (!_edge) return;
|
|
||||||
|
|
||||||
edge[0].tmp = edge[0].tmp || {};
|
|
||||||
if (edge[0].tmp.children) {
|
|
||||||
edge[0].tmp.children = edge[0].tmp.children.filter(n => n.id !== id2);
|
|
||||||
}
|
|
||||||
|
|
||||||
edge[2].tmp = edge[2].tmp || {};
|
|
||||||
if (edge[2].tmp.parents) {
|
|
||||||
edge[2].tmp.parents = edge[2].tmp.parents.filter(n => n.id !== id0);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (applyDeletion) {
|
|
||||||
this.edges.update((edges) => {
|
|
||||||
return edges.filter(e => e !== _edge);
|
|
||||||
});
|
|
||||||
this.execute();
|
|
||||||
this.save();
|
|
||||||
} else {
|
|
||||||
this._edges = this._edges.filter(e => e !== _edge);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
getEdgesToNode(node: Node) {
|
|
||||||
return this._edges
|
|
||||||
.filter((edge) => edge[2].id === node.id)
|
|
||||||
.map((edge) => {
|
|
||||||
const from = this.getNode(edge[0].id);
|
|
||||||
const to = this.getNode(edge[2].id);
|
|
||||||
if (!from || !to) return;
|
|
||||||
return [from, edge[1], to, edge[3]] as const;
|
|
||||||
})
|
|
||||||
.filter(Boolean) as unknown as [Node, number, Node, string][];
|
|
||||||
}
|
|
||||||
|
|
||||||
getEdgesFromNode(node: Node) {
|
|
||||||
return this._edges
|
|
||||||
.filter((edge) => edge[0].id === node.id)
|
|
||||||
.map((edge) => {
|
|
||||||
const from = this.getNode(edge[0].id);
|
|
||||||
const to = this.getNode(edge[2].id);
|
|
||||||
if (!from || !to) return;
|
|
||||||
return [from, edge[1], to, edge[3]] as const;
|
|
||||||
})
|
|
||||||
.filter(Boolean) as unknown as [Node, number, Node, string][];
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
341
app/src/lib/graph-interface/graph-state.svelte.ts
Normal file
341
app/src/lib/graph-interface/graph-state.svelte.ts
Normal file
@@ -0,0 +1,341 @@
|
|||||||
|
import type { NodeInstance, Socket } from '@nodarium/types';
|
||||||
|
import { getContext, setContext } from 'svelte';
|
||||||
|
import { SvelteMap, SvelteSet } from 'svelte/reactivity';
|
||||||
|
import type { OrthographicCamera, Vector3 } from 'three';
|
||||||
|
import type { GraphManager } from './graph-manager.svelte';
|
||||||
|
|
||||||
|
const graphStateKey = Symbol('graph-state');
|
||||||
|
export function getGraphState() {
|
||||||
|
return getContext<GraphState>(graphStateKey);
|
||||||
|
}
|
||||||
|
export function setGraphState(graphState: GraphState) {
|
||||||
|
return setContext(graphStateKey, graphState);
|
||||||
|
}
|
||||||
|
|
||||||
|
const graphManagerKey = Symbol('graph-manager');
|
||||||
|
export function getGraphManager() {
|
||||||
|
return getContext<GraphManager>(graphManagerKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setGraphManager(manager: GraphManager) {
|
||||||
|
return setContext(graphManagerKey, manager);
|
||||||
|
}
|
||||||
|
|
||||||
|
type EdgeData = {
|
||||||
|
x1: number;
|
||||||
|
y1: number;
|
||||||
|
points: Vector3[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export class GraphState {
|
||||||
|
constructor(private graph: GraphManager) {
|
||||||
|
$effect.root(() => {
|
||||||
|
$effect(() => {
|
||||||
|
localStorage.setItem(
|
||||||
|
'cameraPosition',
|
||||||
|
`[${this.cameraPosition[0]},${this.cameraPosition[1]},${this.cameraPosition[2]}]`
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
const storedPosition = localStorage.getItem('cameraPosition');
|
||||||
|
if (storedPosition) {
|
||||||
|
try {
|
||||||
|
const d = JSON.parse(storedPosition);
|
||||||
|
this.cameraPosition[0] = d[0];
|
||||||
|
this.cameraPosition[1] = d[1];
|
||||||
|
this.cameraPosition[2] = d[2];
|
||||||
|
} catch (e) {
|
||||||
|
console.log('Failed to parsed stored camera position', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
width = $state(100);
|
||||||
|
height = $state(100);
|
||||||
|
|
||||||
|
hoveredEdgeId = $state<string | null>(null);
|
||||||
|
edges = new SvelteMap<string, EdgeData>();
|
||||||
|
|
||||||
|
wrapper = $state<HTMLDivElement>(null!);
|
||||||
|
rect: DOMRect = $derived(
|
||||||
|
(this.wrapper && this.width && this.height)
|
||||||
|
? this.wrapper.getBoundingClientRect()
|
||||||
|
: new DOMRect(0, 0, 0, 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
camera = $state<OrthographicCamera>(null!);
|
||||||
|
cameraPosition: [number, number, number] = $state([140, 100, 3.5]);
|
||||||
|
|
||||||
|
clipboard: null | {
|
||||||
|
nodes: NodeInstance[];
|
||||||
|
edges: [number, number, number, string][];
|
||||||
|
} = null;
|
||||||
|
|
||||||
|
cameraBounds = $derived([
|
||||||
|
this.cameraPosition[0] - this.width / this.cameraPosition[2] / 2,
|
||||||
|
this.cameraPosition[0] + this.width / this.cameraPosition[2] / 2,
|
||||||
|
this.cameraPosition[1] - this.height / this.cameraPosition[2] / 2,
|
||||||
|
this.cameraPosition[1] + this.height / this.cameraPosition[2] / 2
|
||||||
|
]);
|
||||||
|
|
||||||
|
boxSelection = $state(false);
|
||||||
|
edgeEndPosition = $state<[number, number] | null>();
|
||||||
|
addMenuPosition = $state<[number, number] | null>(null);
|
||||||
|
|
||||||
|
snapToGrid = $state(false);
|
||||||
|
showGrid = $state(true);
|
||||||
|
showHelp = $state(false);
|
||||||
|
|
||||||
|
cameraDown = [0, 0];
|
||||||
|
mouseDownNodeId = -1;
|
||||||
|
|
||||||
|
isPanning = $state(false);
|
||||||
|
isDragging = $state(false);
|
||||||
|
hoveredNodeId = $state(-1);
|
||||||
|
mousePosition = $state([0, 0]);
|
||||||
|
mouseDown = $state<[number, number] | null>(null);
|
||||||
|
activeNodeId = $state(-1);
|
||||||
|
selectedNodes = new SvelteSet<number>();
|
||||||
|
activeSocket = $state<Socket | null>(null);
|
||||||
|
hoveredSocket = $state<Socket | null>(null);
|
||||||
|
possibleSockets = $state<Socket[]>([]);
|
||||||
|
possibleSocketIds = $derived(
|
||||||
|
new SvelteSet(this.possibleSockets.map((s) => `${s.node.id}-${s.index}`))
|
||||||
|
);
|
||||||
|
|
||||||
|
getEdges() {
|
||||||
|
return $state.snapshot(this.edges);
|
||||||
|
}
|
||||||
|
|
||||||
|
clearSelection() {
|
||||||
|
this.selectedNodes.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
isBodyFocused = () => document?.activeElement?.nodeName !== 'INPUT';
|
||||||
|
|
||||||
|
setEdgeGeometry(edgeId: string, x1: number, y1: number, points: Vector3[]) {
|
||||||
|
this.edges.set(edgeId, { x1, y1, points });
|
||||||
|
}
|
||||||
|
|
||||||
|
removeEdgeGeometry(edgeId: string) {
|
||||||
|
this.edges.delete(edgeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
getEdgeData() {
|
||||||
|
return this.edges;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateNodePosition(node: NodeInstance) {
|
||||||
|
if (
|
||||||
|
node.state.x === node.position[0]
|
||||||
|
&& node.state.y === node.position[1]
|
||||||
|
) {
|
||||||
|
delete node.state.x;
|
||||||
|
delete node.state.y;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.state['x'] !== undefined && node.state['y'] !== undefined) {
|
||||||
|
if (node.state.ref) {
|
||||||
|
node.state.ref.style.setProperty('--nx', `${node.state.x * 10}px`);
|
||||||
|
node.state.ref.style.setProperty('--ny', `${node.state.y * 10}px`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (node.state.ref) {
|
||||||
|
node.state.ref.style.setProperty('--nx', `${node.position[0] * 10}px`);
|
||||||
|
node.state.ref.style.setProperty('--ny', `${node.position[1] * 10}px`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getSnapLevel() {
|
||||||
|
const z = this.cameraPosition[2];
|
||||||
|
if (z > 66) {
|
||||||
|
return 8;
|
||||||
|
} else if (z > 55) {
|
||||||
|
return 4;
|
||||||
|
} else if (z > 11) {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
getSocketPosition(
|
||||||
|
node: NodeInstance,
|
||||||
|
index: string | number
|
||||||
|
): [number, number] {
|
||||||
|
if (typeof index === 'number') {
|
||||||
|
return [
|
||||||
|
(node?.state?.x ?? node.position[0]) + 20,
|
||||||
|
(node?.state?.y ?? node.position[1]) + 2.5 + 10 * index
|
||||||
|
];
|
||||||
|
} else {
|
||||||
|
const _index = Object.keys(node.state?.type?.inputs || {}).indexOf(index);
|
||||||
|
return [
|
||||||
|
node?.state?.x ?? node.position[0],
|
||||||
|
(node?.state?.y ?? node.position[1]) + 10 + 10 * _index
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private nodeHeightCache: Record<string, number> = {};
|
||||||
|
getNodeHeight(nodeTypeId: string) {
|
||||||
|
if (nodeTypeId in this.nodeHeightCache) {
|
||||||
|
return this.nodeHeightCache[nodeTypeId];
|
||||||
|
}
|
||||||
|
const node = this.graph.getNodeType(nodeTypeId);
|
||||||
|
if (!node?.inputs) {
|
||||||
|
return 5;
|
||||||
|
}
|
||||||
|
const height = 5
|
||||||
|
+ 10
|
||||||
|
* Object.keys(node.inputs).filter(
|
||||||
|
(p) =>
|
||||||
|
p !== 'seed'
|
||||||
|
&& node?.inputs
|
||||||
|
&& !(node?.inputs?.[p] !== undefined && 'setting' in node.inputs[p])
|
||||||
|
&& node.inputs[p].hidden !== true
|
||||||
|
).length;
|
||||||
|
this.nodeHeightCache[nodeTypeId] = height;
|
||||||
|
return height;
|
||||||
|
}
|
||||||
|
|
||||||
|
copyNodes() {
|
||||||
|
if (this.activeNodeId === -1 && !this.selectedNodes?.size) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let nodes = [
|
||||||
|
this.activeNodeId,
|
||||||
|
...(this.selectedNodes?.values() || [])
|
||||||
|
]
|
||||||
|
.map((id) => this.graph.getNode(id))
|
||||||
|
.filter(b => !!b);
|
||||||
|
|
||||||
|
const edges = this.graph.getEdgesBetweenNodes(nodes);
|
||||||
|
nodes = nodes.map((node) => ({
|
||||||
|
...node,
|
||||||
|
position: [
|
||||||
|
this.mousePosition[0] - node.position[0],
|
||||||
|
this.mousePosition[1] - node.position[1]
|
||||||
|
],
|
||||||
|
tmp: undefined
|
||||||
|
}));
|
||||||
|
|
||||||
|
this.clipboard = {
|
||||||
|
nodes: nodes,
|
||||||
|
edges: edges
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pasteNodes() {
|
||||||
|
if (!this.clipboard) return;
|
||||||
|
|
||||||
|
const nodes = this.clipboard.nodes
|
||||||
|
.map((node) => {
|
||||||
|
node.position[0] = this.mousePosition[0] - node.position[0];
|
||||||
|
node.position[1] = this.mousePosition[1] - node.position[1];
|
||||||
|
return node;
|
||||||
|
})
|
||||||
|
.filter(Boolean) as NodeInstance[];
|
||||||
|
|
||||||
|
const newNodes = this.graph.createGraph(nodes, this.clipboard.edges);
|
||||||
|
this.selectedNodes.clear();
|
||||||
|
for (const node of newNodes) {
|
||||||
|
this.selectedNodes.add(node.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setDownSocket(socket: Socket) {
|
||||||
|
this.activeSocket = socket;
|
||||||
|
|
||||||
|
let { node, index, position } = socket;
|
||||||
|
|
||||||
|
// remove existing edge
|
||||||
|
if (typeof index === 'string') {
|
||||||
|
const edges = this.graph.getEdgesToNode(node);
|
||||||
|
for (const edge of edges) {
|
||||||
|
if (edge[3] === index) {
|
||||||
|
node = edge[0];
|
||||||
|
index = edge[1];
|
||||||
|
position = this.getSocketPosition(node, index);
|
||||||
|
this.graph.removeEdge(edge);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.mouseDown = position;
|
||||||
|
this.activeSocket = {
|
||||||
|
node,
|
||||||
|
index,
|
||||||
|
position
|
||||||
|
};
|
||||||
|
|
||||||
|
this.possibleSockets = this.graph
|
||||||
|
.getPossibleSockets(this.activeSocket)
|
||||||
|
.map(([node, index]) => {
|
||||||
|
return {
|
||||||
|
node,
|
||||||
|
index,
|
||||||
|
position: this.getSocketPosition(node, index)
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
projectScreenToWorld(x: number, y: number): [number, number] {
|
||||||
|
return [
|
||||||
|
this.cameraPosition[0]
|
||||||
|
+ (x - this.width / 2) / this.cameraPosition[2],
|
||||||
|
this.cameraPosition[1]
|
||||||
|
+ (y - this.height / 2) / this.cameraPosition[2]
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
getNodeIdFromEvent(event: MouseEvent) {
|
||||||
|
let clickedNodeId = -1;
|
||||||
|
|
||||||
|
const mx = event.clientX - this.rect.x;
|
||||||
|
const my = event.clientY - this.rect.y;
|
||||||
|
|
||||||
|
if (event.button === 0) {
|
||||||
|
// check if the clicked element is a node
|
||||||
|
if (event.target instanceof HTMLElement) {
|
||||||
|
const nodeElement = event.target.closest('.node');
|
||||||
|
const nodeId = nodeElement?.getAttribute?.('data-node-id');
|
||||||
|
if (nodeId) {
|
||||||
|
clickedNodeId = parseInt(nodeId, 10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// if we do not have an active node,
|
||||||
|
// we are going to check if we clicked on a node by coordinates
|
||||||
|
if (clickedNodeId === -1) {
|
||||||
|
const [downX, downY] = this.projectScreenToWorld(mx, my);
|
||||||
|
for (const node of this.graph.nodes.values()) {
|
||||||
|
const x = node.position[0];
|
||||||
|
const y = node.position[1];
|
||||||
|
const height = this.getNodeHeight(node.type);
|
||||||
|
if (downX > x && downX < x + 20 && downY > y && downY < y + height) {
|
||||||
|
clickedNodeId = node.id;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return clickedNodeId;
|
||||||
|
}
|
||||||
|
|
||||||
|
isNodeInView(node: NodeInstance) {
|
||||||
|
const height = this.getNodeHeight(node.type);
|
||||||
|
const width = 20;
|
||||||
|
return (
|
||||||
|
node.position[0] > this.cameraBounds[0] - width
|
||||||
|
&& node.position[0] < this.cameraBounds[1]
|
||||||
|
&& node.position[1] > this.cameraBounds[2] - height
|
||||||
|
&& node.position[1] < this.cameraBounds[3]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
openNodePalette() {
|
||||||
|
this.addMenuPosition = [this.mousePosition[0], this.mousePosition[1]];
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,94 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import type { Edge as EdgeType, Node as NodeType } from "@nodes/types";
|
|
||||||
import { HTML } from "@threlte/extras";
|
|
||||||
import Edge from "../edges/Edge.svelte";
|
|
||||||
import Node from "../node/Node.svelte";
|
|
||||||
import { getContext, onMount } from "svelte";
|
|
||||||
import type { Writable } from "svelte/store";
|
|
||||||
import { getGraphState } from "./state.svelte";
|
|
||||||
import { useThrelte } from "@threlte/core";
|
|
||||||
import { appSettings } from "$lib/settings/app-settings.svelte";
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
nodes: Writable<Map<number, NodeType>>;
|
|
||||||
edges: Writable<EdgeType[]>;
|
|
||||||
cameraPosition: [number, number, number];
|
|
||||||
};
|
|
||||||
|
|
||||||
const { nodes, edges, cameraPosition = [0, 0, 4] }: Props = $props();
|
|
||||||
|
|
||||||
const { invalidate } = useThrelte();
|
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
appSettings.theme;
|
|
||||||
invalidate();
|
|
||||||
});
|
|
||||||
|
|
||||||
const graphState = getGraphState();
|
|
||||||
|
|
||||||
const isNodeInView = getContext<(n: NodeType) => boolean>("isNodeInView");
|
|
||||||
|
|
||||||
const getSocketPosition =
|
|
||||||
getContext<(node: NodeType, index: string | number) => [number, number]>(
|
|
||||||
"getSocketPosition",
|
|
||||||
);
|
|
||||||
|
|
||||||
function getEdgePosition(edge: EdgeType) {
|
|
||||||
const pos1 = getSocketPosition(edge[0], edge[1]);
|
|
||||||
const pos2 = getSocketPosition(edge[2], edge[3]);
|
|
||||||
return [pos1[0], pos1[1], pos2[0], pos2[1]];
|
|
||||||
}
|
|
||||||
|
|
||||||
onMount(() => {
|
|
||||||
for (const node of $nodes.values()) {
|
|
||||||
if (node?.tmp?.ref) {
|
|
||||||
node.tmp.ref.style.setProperty("--nx", `${node.position[0] * 10}px`);
|
|
||||||
node.tmp.ref.style.setProperty("--ny", `${node.position[1] * 10}px`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
{#each $edges as edge (`${edge[0].id}-${edge[1]}-${edge[2].id}-${edge[3]}`)}
|
|
||||||
{@const pos = getEdgePosition(edge)}
|
|
||||||
{@const [x1, y1, x2, y2] = pos}
|
|
||||||
<Edge
|
|
||||||
z={cameraPosition[2]}
|
|
||||||
from={{
|
|
||||||
x: x1,
|
|
||||||
y: y1,
|
|
||||||
}}
|
|
||||||
to={{
|
|
||||||
x: x2,
|
|
||||||
y: y2,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
{/each}
|
|
||||||
|
|
||||||
<HTML transform={false}>
|
|
||||||
<div
|
|
||||||
role="tree"
|
|
||||||
id="graph"
|
|
||||||
tabindex="0"
|
|
||||||
class="wrapper"
|
|
||||||
style:transform={`scale(${cameraPosition[2] * 0.1})`}
|
|
||||||
class:hovering-sockets={graphState.activeSocket}
|
|
||||||
>
|
|
||||||
{#each $nodes.values() as node (node.id)}
|
|
||||||
<Node
|
|
||||||
{node}
|
|
||||||
inView={cameraPosition && isNodeInView(node)}
|
|
||||||
z={cameraPosition[2]}
|
|
||||||
/>
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
</HTML>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.wrapper {
|
|
||||||
position: absolute;
|
|
||||||
z-index: 100;
|
|
||||||
width: 0px;
|
|
||||||
height: 0px;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,29 +1,25 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type { Graph, Node, NodeRegistry } from "@nodes/types";
|
import { createKeyMap } from '$lib/helpers/createKeyMap';
|
||||||
import GraphEl from "./Graph.svelte";
|
import type { Graph, NodeInstance, NodeRegistry } from '@nodarium/types';
|
||||||
import { GraphManager } from "../graph-manager.js";
|
import { GraphManager } from '../graph-manager.svelte';
|
||||||
import { setContext } from "svelte";
|
import { GraphState, setGraphManager, setGraphState } from '../graph-state.svelte';
|
||||||
import { debounce } from "$lib/helpers";
|
import { setupKeymaps } from '../keymaps';
|
||||||
import { createKeyMap } from "$lib/helpers/createKeyMap";
|
import GraphEl from './Graph.svelte';
|
||||||
import { GraphState } from "./state.svelte";
|
|
||||||
|
|
||||||
const graphState = new GraphState();
|
|
||||||
setContext("graphState", graphState);
|
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
graph: Graph;
|
graph?: Graph;
|
||||||
registry: NodeRegistry;
|
registry: NodeRegistry;
|
||||||
|
|
||||||
settings?: Record<string, any>;
|
settings?: Record<string, unknown>;
|
||||||
|
|
||||||
activeNode?: Node;
|
activeNode?: NodeInstance;
|
||||||
showGrid?: boolean;
|
showGrid?: boolean;
|
||||||
snapToGrid?: boolean;
|
snapToGrid?: boolean;
|
||||||
showHelp?: boolean;
|
showHelp?: boolean;
|
||||||
settingTypes?: Record<string, any>;
|
settingTypes?: Record<string, unknown>;
|
||||||
|
|
||||||
onsave?: (save: Graph) => void;
|
onsave?: (save: Graph) => void;
|
||||||
onresult?: (result: any) => void;
|
onresult?: (result: unknown) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
let {
|
let {
|
||||||
@@ -31,19 +27,30 @@
|
|||||||
registry,
|
registry,
|
||||||
settings = $bindable(),
|
settings = $bindable(),
|
||||||
activeNode = $bindable(),
|
activeNode = $bindable(),
|
||||||
showGrid,
|
showGrid = $bindable(true),
|
||||||
snapToGrid,
|
snapToGrid = $bindable(true),
|
||||||
showHelp = $bindable(false),
|
showHelp = $bindable(false),
|
||||||
settingTypes = $bindable(),
|
settingTypes = $bindable(),
|
||||||
onsave,
|
onsave,
|
||||||
onresult,
|
onresult
|
||||||
}: Props = $props();
|
}: Props = $props();
|
||||||
|
|
||||||
export const keymap = createKeyMap([]);
|
export const keymap = createKeyMap([]);
|
||||||
setContext("keymap", keymap);
|
|
||||||
|
|
||||||
|
// svelte-ignore state_referenced_locally
|
||||||
export const manager = new GraphManager(registry);
|
export const manager = new GraphManager(registry);
|
||||||
setContext("graphManager", manager);
|
setGraphManager(manager);
|
||||||
|
|
||||||
|
const graphState = new GraphState(manager);
|
||||||
|
$effect(() => {
|
||||||
|
graphState.showGrid = showGrid;
|
||||||
|
graphState.snapToGrid = snapToGrid;
|
||||||
|
graphState.showHelp = showHelp;
|
||||||
|
});
|
||||||
|
|
||||||
|
setGraphState(graphState);
|
||||||
|
|
||||||
|
setupKeymaps(keymap, manager, graphState);
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (graphState.activeNodeId !== -1) {
|
if (graphState.activeNodeId !== -1) {
|
||||||
@@ -53,26 +60,27 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const updateSettings = debounce((s) => {
|
|
||||||
manager.setSettings(s);
|
|
||||||
}, 200);
|
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (settingTypes && settings) {
|
if (!graphState.addMenuPosition) {
|
||||||
updateSettings($state.snapshot(settings));
|
graphState.edgeEndPosition = null;
|
||||||
|
graphState.activeSocket = null;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
manager.on("settings", (_settings) => {
|
manager.on('settings', (_settings) => {
|
||||||
settingTypes = { ...settingTypes, ..._settings.types };
|
settingTypes = { ...settingTypes, ..._settings.types };
|
||||||
settings = _settings.values;
|
settings = _settings.values;
|
||||||
});
|
});
|
||||||
|
|
||||||
manager.on("result", (result) => onresult?.(result));
|
manager.on('result', (result) => onresult?.(result));
|
||||||
|
|
||||||
manager.on("save", (save) => onsave?.(save));
|
manager.on('save', (save) => onsave?.(save));
|
||||||
|
|
||||||
manager.load(graph);
|
$effect(() => {
|
||||||
|
if (graph) {
|
||||||
|
manager.load(graph);
|
||||||
|
}
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<GraphEl bind:showGrid bind:snapToGrid bind:showHelp />
|
<GraphEl {keymap} />
|
||||||
|
|||||||
@@ -1,32 +1,34 @@
|
|||||||
import { appSettings } from "$lib/settings/app-settings.svelte";
|
import { appSettings } from '$lib/settings/app-settings.svelte';
|
||||||
import { Color, LinearSRGBColorSpace } from "three";
|
import { Color, LinearSRGBColorSpace } from 'three';
|
||||||
|
|
||||||
const variables = [
|
const variables = [
|
||||||
"layer-0",
|
'layer-0',
|
||||||
"layer-1",
|
'layer-1',
|
||||||
"layer-2",
|
'layer-2',
|
||||||
"layer-3",
|
'layer-3',
|
||||||
"outline",
|
'outline',
|
||||||
"active",
|
'active',
|
||||||
"selected",
|
'selected',
|
||||||
"edge",
|
'edge'
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
function getColor(variable: typeof variables[number]) {
|
function getColor(variable: (typeof variables)[number]) {
|
||||||
const style = getComputedStyle(document.body.parentElement!);
|
const style = getComputedStyle(document.body.parentElement!);
|
||||||
let color = style.getPropertyValue(`--${variable}`);
|
const color = style.getPropertyValue(`--color-${variable}`);
|
||||||
return new Color().setStyle(color, LinearSRGBColorSpace);
|
return new Color().setStyle(color, LinearSRGBColorSpace);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const colors = Object.fromEntries(variables.map(v => [v, getColor(v)])) as Record<typeof variables[number], Color>;
|
export const colors = Object.fromEntries(
|
||||||
|
variables.map((v) => [v, getColor(v)])
|
||||||
|
) as Record<(typeof variables)[number], Color>;
|
||||||
|
|
||||||
$effect.root(() => {
|
$effect.root(() => {
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (!appSettings.theme || !("getComputedStyle" in globalThis)) return;
|
if (!appSettings.value.theme || !('getComputedStyle' in globalThis)) return;
|
||||||
const style = getComputedStyle(document.body.parentElement!);
|
const style = getComputedStyle(document.body.parentElement!);
|
||||||
for (const v of variables) {
|
for (const v of variables) {
|
||||||
const hex = style.getPropertyValue(`--${v}`);
|
const hex = style.getPropertyValue(`--color-${v}`);
|
||||||
colors[v].setStyle(hex, LinearSRGBColorSpace);
|
colors[v].setStyle(hex, LinearSRGBColorSpace);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
})
|
});
|
||||||
|
|||||||
3
app/src/lib/graph-interface/graph/constants.ts
Normal file
3
app/src/lib/graph-interface/graph/constants.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export const minZoom = 1;
|
||||||
|
export const maxZoom = 40;
|
||||||
|
export const zoomSpeed = 2;
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
import type { GraphManager } from "../graph-manager.js";
|
|
||||||
import { getContext } from "svelte";
|
|
||||||
|
|
||||||
export function getGraphManager(): GraphManager {
|
|
||||||
return getContext("graphManager");
|
|
||||||
}
|
|
||||||
109
app/src/lib/graph-interface/graph/drop.events.ts
Normal file
109
app/src/lib/graph-interface/graph/drop.events.ts
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
import { GraphSchema, type NodeId } from '@nodarium/types';
|
||||||
|
import type { GraphManager } from '../graph-manager.svelte';
|
||||||
|
import type { GraphState } from '../graph-state.svelte';
|
||||||
|
|
||||||
|
export class FileDropEventManager {
|
||||||
|
constructor(
|
||||||
|
private graph: GraphManager,
|
||||||
|
private state: GraphState
|
||||||
|
) {}
|
||||||
|
|
||||||
|
handleFileDrop(event: DragEvent) {
|
||||||
|
event.preventDefault();
|
||||||
|
this.state.isDragging = false;
|
||||||
|
if (!event.dataTransfer) return;
|
||||||
|
const nodeId = event.dataTransfer.getData('data/node-id') as NodeId;
|
||||||
|
let mx = event.clientX - this.state.rect.x;
|
||||||
|
let my = event.clientY - this.state.rect.y;
|
||||||
|
|
||||||
|
if (nodeId) {
|
||||||
|
const nodeOffsetX = event.dataTransfer.getData('data/node-offset-x');
|
||||||
|
const nodeOffsetY = event.dataTransfer.getData('data/node-offset-y');
|
||||||
|
if (nodeOffsetX && nodeOffsetY) {
|
||||||
|
mx += parseInt(nodeOffsetX);
|
||||||
|
my += parseInt(nodeOffsetY);
|
||||||
|
}
|
||||||
|
|
||||||
|
let props = {};
|
||||||
|
const rawNodeProps = event.dataTransfer.getData('data/node-props');
|
||||||
|
if (rawNodeProps) {
|
||||||
|
try {
|
||||||
|
props = JSON.parse(rawNodeProps);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to parse node dropped', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const pos = this.state.projectScreenToWorld(mx, my);
|
||||||
|
this.graph.registry.load([nodeId]).then(() => {
|
||||||
|
this.graph.createNode({
|
||||||
|
type: nodeId,
|
||||||
|
props,
|
||||||
|
position: pos
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} else if (event.dataTransfer.files.length) {
|
||||||
|
const file = event.dataTransfer.files[0];
|
||||||
|
|
||||||
|
if (file.type === 'application/wasm') {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = async (e) => {
|
||||||
|
const buffer = e.target?.result;
|
||||||
|
if (buffer?.constructor === ArrayBuffer) {
|
||||||
|
const nodeType = await this.graph.registry.register(nodeId, buffer);
|
||||||
|
|
||||||
|
this.graph.createNode({
|
||||||
|
type: nodeType.id,
|
||||||
|
props: {},
|
||||||
|
position: this.state.projectScreenToWorld(mx, my)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.readAsArrayBuffer(file);
|
||||||
|
} else if (file.type === 'application/json') {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = (e) => {
|
||||||
|
const buffer = e.target?.result as ArrayBuffer;
|
||||||
|
if (buffer) {
|
||||||
|
const state = GraphSchema.parse(JSON.parse(buffer.toString()));
|
||||||
|
this.graph.load(state);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.readAsText(file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handleMouseLeave() {
|
||||||
|
this.state.isDragging = false;
|
||||||
|
this.state.isPanning = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
handleDragEnter(e: DragEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
this.state.isDragging = true;
|
||||||
|
this.state.isPanning = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
handleDragOver(e: DragEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
this.state.isDragging = true;
|
||||||
|
this.state.isPanning = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
handleDragEnd(e: DragEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
this.state.isDragging = true;
|
||||||
|
this.state.isPanning = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
getEventListenerProps() {
|
||||||
|
return {
|
||||||
|
ondragenter: (ev: DragEvent) => this.handleDragEnter(ev),
|
||||||
|
ondragover: (ev: DragEvent) => this.handleDragOver(ev),
|
||||||
|
ondragexit: (ev: DragEvent) => this.handleDragEnd(ev),
|
||||||
|
ondrop: (ev: DragEvent) => this.handleFileDrop(ev),
|
||||||
|
onmouseleave: () => this.handleMouseLeave()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
117
app/src/lib/graph-interface/graph/edge.events.ts
Normal file
117
app/src/lib/graph-interface/graph/edge.events.ts
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
import type { Box } from '@nodarium/types';
|
||||||
|
import type { GraphManager } from '../graph-manager.svelte';
|
||||||
|
import type { GraphState } from '../graph-state.svelte';
|
||||||
|
import { distanceFromPointToSegment } from '../helpers';
|
||||||
|
|
||||||
|
export class EdgeInteractionManager {
|
||||||
|
constructor(
|
||||||
|
private graph: GraphManager,
|
||||||
|
private state: GraphState
|
||||||
|
) {}
|
||||||
|
|
||||||
|
private MIN_DISTANCE = 3;
|
||||||
|
|
||||||
|
private _boundingBoxes = new Map<string, Box>();
|
||||||
|
|
||||||
|
handleMouseDown() {
|
||||||
|
this._boundingBoxes.clear();
|
||||||
|
|
||||||
|
const possibleEdges = this.graph
|
||||||
|
.getPossibleDropOnEdges(this.state.activeNodeId)
|
||||||
|
.map(e => this.graph.getEdgeId(e));
|
||||||
|
|
||||||
|
const edges = this.state.getEdges();
|
||||||
|
for (const edge of edges) {
|
||||||
|
const edgeId = edge[0];
|
||||||
|
if (!possibleEdges.includes(edgeId)) {
|
||||||
|
edges.delete(edgeId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [edgeId, data] of edges) {
|
||||||
|
const points = data.points;
|
||||||
|
let minX = points[0].x + data.x1;
|
||||||
|
let maxX = points[0].x + data.x1;
|
||||||
|
let minY = points[0].z + data.y1;
|
||||||
|
let maxY = points[0].z + data.y1;
|
||||||
|
|
||||||
|
// Iterate through all points to find the true bounds
|
||||||
|
for (let i = 0; i < points.length; i++) {
|
||||||
|
const x = data.x1 + points[i].x;
|
||||||
|
const y = data.y1 + points[i].z;
|
||||||
|
if (x < minX) minX = x;
|
||||||
|
if (x > maxX) maxX = x;
|
||||||
|
if (y < minY) minY = y;
|
||||||
|
if (y > maxY) maxY = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
const boundingBox = {
|
||||||
|
minX: minX - this.MIN_DISTANCE,
|
||||||
|
maxX: maxX + this.MIN_DISTANCE,
|
||||||
|
minY: minY - this.MIN_DISTANCE,
|
||||||
|
maxY: maxY + this.MIN_DISTANCE
|
||||||
|
};
|
||||||
|
|
||||||
|
this._boundingBoxes.set(edgeId, boundingBox);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handleMouseMove() {
|
||||||
|
const [mouseX, mouseY] = this.state.mousePosition;
|
||||||
|
const hoveredEdgeIds: string[] = [];
|
||||||
|
|
||||||
|
const edges = this.state.getEdges();
|
||||||
|
|
||||||
|
// Check if mouse is inside any bounding box
|
||||||
|
for (const [edgeId, box] of this._boundingBoxes) {
|
||||||
|
const isInside = mouseX >= box.minX
|
||||||
|
&& mouseX <= box.maxX
|
||||||
|
&& mouseY >= box.minY
|
||||||
|
&& mouseY <= box.maxY;
|
||||||
|
|
||||||
|
if (isInside) {
|
||||||
|
hoveredEdgeIds.push(edgeId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let hoveredEdgeId: string | null = null;
|
||||||
|
let hoveredEdgeDistance = Infinity;
|
||||||
|
|
||||||
|
const DENSITY = 10; // higher DENSITY = less points checked (yes density might not be the best name :-)
|
||||||
|
for (const edgeId of hoveredEdgeIds) {
|
||||||
|
const edge = edges.get(edgeId)!;
|
||||||
|
for (let i = 0; i < edge.points.length - DENSITY; i += DENSITY) {
|
||||||
|
const pointAx = edge.points[i].x + edge.x1;
|
||||||
|
const pointAy = edge.points[i].z + edge.y1;
|
||||||
|
const pointBx = edge.points[i + DENSITY].x + edge.x1;
|
||||||
|
const pointBy = edge.points[i + DENSITY].z + edge.y1;
|
||||||
|
const distance = distanceFromPointToSegment(
|
||||||
|
pointAx,
|
||||||
|
pointAy,
|
||||||
|
pointBx,
|
||||||
|
pointBy,
|
||||||
|
mouseX,
|
||||||
|
mouseY
|
||||||
|
);
|
||||||
|
if (distance < this.MIN_DISTANCE) {
|
||||||
|
if (distance < hoveredEdgeDistance) {
|
||||||
|
hoveredEdgeDistance = distance;
|
||||||
|
hoveredEdgeId = edgeId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.state.hoveredEdgeId = hoveredEdgeId;
|
||||||
|
}
|
||||||
|
|
||||||
|
handleMouseUp() {
|
||||||
|
if (this.state.hoveredEdgeId) {
|
||||||
|
const edge = this.graph.getEdgeById(this.state.hoveredEdgeId);
|
||||||
|
if (edge) {
|
||||||
|
this.graph.dropNodeOnEdge(this.state.activeNodeId, edge);
|
||||||
|
}
|
||||||
|
this.state.hoveredEdgeId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
398
app/src/lib/graph-interface/graph/mouse.events.ts
Normal file
398
app/src/lib/graph-interface/graph/mouse.events.ts
Normal file
@@ -0,0 +1,398 @@
|
|||||||
|
import { animate, lerp } from '$lib/helpers';
|
||||||
|
import { type NodeInstance } from '@nodarium/types';
|
||||||
|
import type { GraphManager } from '../graph-manager.svelte';
|
||||||
|
import { type GraphState } from '../graph-state.svelte';
|
||||||
|
import { snapToGrid as snapPointToGrid } from '../helpers';
|
||||||
|
import { maxZoom, minZoom, zoomSpeed } from './constants';
|
||||||
|
import { EdgeInteractionManager } from './edge.events';
|
||||||
|
|
||||||
|
export class MouseEventManager {
|
||||||
|
edgeInteractionManager: EdgeInteractionManager;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private graph: GraphManager,
|
||||||
|
private state: GraphState
|
||||||
|
) {
|
||||||
|
this.edgeInteractionManager = new EdgeInteractionManager(graph, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleWindowMouseUp(event: MouseEvent) {
|
||||||
|
this.edgeInteractionManager.handleMouseUp();
|
||||||
|
this.state.isPanning = false;
|
||||||
|
if (!this.state.mouseDown) return;
|
||||||
|
|
||||||
|
const activeNode = this.graph.getNode(this.state.activeNodeId);
|
||||||
|
|
||||||
|
const clickedNodeId = this.state.getNodeIdFromEvent(event);
|
||||||
|
|
||||||
|
if (clickedNodeId !== -1) {
|
||||||
|
if (activeNode) {
|
||||||
|
if (!activeNode?.state?.isMoving && !event.ctrlKey && !event.shiftKey) {
|
||||||
|
this.state.activeNodeId = clickedNodeId;
|
||||||
|
this.state.clearSelection();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (activeNode?.state?.isMoving) {
|
||||||
|
activeNode.state = activeNode.state || {};
|
||||||
|
activeNode.state.isMoving = false;
|
||||||
|
if (this.state.snapToGrid) {
|
||||||
|
const snapLevel = this.state.getSnapLevel();
|
||||||
|
activeNode.position[0] = snapPointToGrid(
|
||||||
|
activeNode?.state?.x ?? activeNode.position[0],
|
||||||
|
5 / snapLevel
|
||||||
|
);
|
||||||
|
activeNode.position[1] = snapPointToGrid(
|
||||||
|
activeNode?.state?.y ?? activeNode.position[1],
|
||||||
|
5 / snapLevel
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
activeNode.position[0] = activeNode?.state?.x ?? activeNode.position[0];
|
||||||
|
activeNode.position[1] = activeNode?.state?.y ?? activeNode.position[1];
|
||||||
|
}
|
||||||
|
const nodes = [
|
||||||
|
...[...(this.state.selectedNodes?.values() || [])].map((id) => this.graph.getNode(id))
|
||||||
|
] as NodeInstance[];
|
||||||
|
|
||||||
|
const vec = [
|
||||||
|
activeNode.position[0] - (activeNode?.state.x || 0),
|
||||||
|
activeNode.position[1] - (activeNode?.state.y || 0)
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (!node) continue;
|
||||||
|
node.state = node.state || {};
|
||||||
|
const { x, y } = node.state;
|
||||||
|
if (x !== undefined && y !== undefined) {
|
||||||
|
node.position[0] = x + vec[0];
|
||||||
|
node.position[1] = y + vec[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nodes.push(activeNode);
|
||||||
|
animate(500, (a: number) => {
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (
|
||||||
|
node?.state
|
||||||
|
&& node.state['x'] !== undefined
|
||||||
|
&& node.state['y'] !== undefined
|
||||||
|
) {
|
||||||
|
node.state.x = lerp(node.state.x, node.position[0], a);
|
||||||
|
node.state.y = lerp(node.state.y, node.position[1], a);
|
||||||
|
this.state.updateNodePosition(node);
|
||||||
|
if (node?.state?.isMoving) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
this.graph.save();
|
||||||
|
} else if (this.state.hoveredSocket && this.state.activeSocket) {
|
||||||
|
if (
|
||||||
|
typeof this.state.hoveredSocket.index === 'number'
|
||||||
|
&& typeof this.state.activeSocket.index === 'string'
|
||||||
|
) {
|
||||||
|
this.graph.createEdge(
|
||||||
|
this.state.hoveredSocket.node,
|
||||||
|
this.state.hoveredSocket.index || 0,
|
||||||
|
this.state.activeSocket.node,
|
||||||
|
this.state.activeSocket.index
|
||||||
|
);
|
||||||
|
} else if (
|
||||||
|
typeof this.state.activeSocket.index == 'number'
|
||||||
|
&& typeof this.state.hoveredSocket.index === 'string'
|
||||||
|
) {
|
||||||
|
this.graph.createEdge(
|
||||||
|
this.state.activeSocket.node,
|
||||||
|
this.state.activeSocket.index || 0,
|
||||||
|
this.state.hoveredSocket.node,
|
||||||
|
this.state.hoveredSocket.index
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.graph.save();
|
||||||
|
} else if (this.state.activeSocket && event.ctrlKey) {
|
||||||
|
// Handle automatic adding of nodes on ctrl+mouseUp
|
||||||
|
this.state.edgeEndPosition = [
|
||||||
|
this.state.mousePosition[0],
|
||||||
|
this.state.mousePosition[1]
|
||||||
|
];
|
||||||
|
|
||||||
|
if (typeof this.state.activeSocket.index === 'number') {
|
||||||
|
this.state.addMenuPosition = [
|
||||||
|
this.state.mousePosition[0],
|
||||||
|
this.state.mousePosition[1] - 25 / this.state.cameraPosition[2]
|
||||||
|
];
|
||||||
|
} else {
|
||||||
|
this.state.addMenuPosition = [
|
||||||
|
this.state.mousePosition[0] - 155 / this.state.cameraPosition[2],
|
||||||
|
this.state.mousePosition[1] - 25 / this.state.cameraPosition[2]
|
||||||
|
];
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// check if camera moved
|
||||||
|
if (
|
||||||
|
clickedNodeId === -1
|
||||||
|
&& !this.state.boxSelection
|
||||||
|
&& this.state.cameraDown[0] === this.state.cameraPosition[0]
|
||||||
|
&& this.state.cameraDown[1] === this.state.cameraPosition[1]
|
||||||
|
&& this.state.isBodyFocused()
|
||||||
|
) {
|
||||||
|
this.state.activeNodeId = -1;
|
||||||
|
this.state.clearSelection();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.state.mouseDown = null;
|
||||||
|
this.state.boxSelection = false;
|
||||||
|
this.state.activeSocket = null;
|
||||||
|
this.state.possibleSockets = [];
|
||||||
|
this.state.hoveredSocket = null;
|
||||||
|
this.state.addMenuPosition = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
handleContextMenu(event: MouseEvent) {
|
||||||
|
if (!this.state.addMenuPosition) {
|
||||||
|
event.preventDefault();
|
||||||
|
this.state.openNodePalette();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handleMouseDown(event: MouseEvent) {
|
||||||
|
// Right click
|
||||||
|
if (event.button === 2) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.state.mouseDown) return;
|
||||||
|
this.state.edgeEndPosition = null;
|
||||||
|
|
||||||
|
if (event.target instanceof HTMLElement) {
|
||||||
|
if (
|
||||||
|
event.target.nodeName !== 'CANVAS'
|
||||||
|
&& !event.target.classList.contains('node')
|
||||||
|
&& !event.target.classList.contains('content')
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const mx = event.clientX - this.state.rect.x;
|
||||||
|
const my = event.clientY - this.state.rect.y;
|
||||||
|
|
||||||
|
this.state.mouseDown = [mx, my];
|
||||||
|
this.state.cameraDown[0] = this.state.cameraPosition[0];
|
||||||
|
this.state.cameraDown[1] = this.state.cameraPosition[1];
|
||||||
|
|
||||||
|
const clickedNodeId = this.state.getNodeIdFromEvent(event);
|
||||||
|
this.state.mouseDownNodeId = clickedNodeId;
|
||||||
|
|
||||||
|
// if we clicked on a node
|
||||||
|
if (clickedNodeId !== -1) {
|
||||||
|
if (this.state.activeNodeId === -1) {
|
||||||
|
this.state.activeNodeId = clickedNodeId;
|
||||||
|
// if the selected node is the same as the clicked node
|
||||||
|
} else if (this.state.activeNodeId === clickedNodeId) {
|
||||||
|
// $activeNodeId = -1;
|
||||||
|
// if the clicked node is different from the selected node and secondary
|
||||||
|
} else if (event.ctrlKey) {
|
||||||
|
this.state.selectedNodes.add(this.state.activeNodeId);
|
||||||
|
this.state.selectedNodes.delete(clickedNodeId);
|
||||||
|
this.state.activeNodeId = clickedNodeId;
|
||||||
|
// select the node
|
||||||
|
} else if (event.shiftKey) {
|
||||||
|
const activeNode = this.graph.getNode(this.state.activeNodeId);
|
||||||
|
const newNode = this.graph.getNode(clickedNodeId);
|
||||||
|
if (activeNode && newNode) {
|
||||||
|
const edge = this.graph.getNodesBetween(activeNode, newNode);
|
||||||
|
if (edge) {
|
||||||
|
this.state.selectedNodes.clear();
|
||||||
|
for (const node of edge) {
|
||||||
|
this.state.selectedNodes.add(node.id);
|
||||||
|
}
|
||||||
|
this.state.selectedNodes.add(clickedNodeId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (!this.state.selectedNodes.has(clickedNodeId)) {
|
||||||
|
this.state.activeNodeId = clickedNodeId;
|
||||||
|
this.state.clearSelection();
|
||||||
|
}
|
||||||
|
this.edgeInteractionManager.handleMouseDown();
|
||||||
|
} else if (event.ctrlKey) {
|
||||||
|
this.state.boxSelection = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const node = this.graph.getNode(this.state.activeNodeId);
|
||||||
|
if (!node) return;
|
||||||
|
node.state = node.state || {};
|
||||||
|
node.state.downX = node.position[0];
|
||||||
|
node.state.downY = node.position[1];
|
||||||
|
|
||||||
|
if (this.state.selectedNodes) {
|
||||||
|
for (const nodeId of this.state.selectedNodes) {
|
||||||
|
const n = this.graph.getNode(nodeId);
|
||||||
|
if (!n) continue;
|
||||||
|
n.state = n.state || {};
|
||||||
|
n.state.downX = n.position[0];
|
||||||
|
n.state.downY = n.position[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.state.edgeEndPosition = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
handleWindowMouseMove(event: MouseEvent) {
|
||||||
|
const mx = event.clientX - this.state.rect.x;
|
||||||
|
const my = event.clientY - this.state.rect.y;
|
||||||
|
|
||||||
|
this.state.mousePosition = this.state.projectScreenToWorld(mx, my);
|
||||||
|
this.state.hoveredNodeId = this.state.getNodeIdFromEvent(event);
|
||||||
|
|
||||||
|
if (!this.state.mouseDown) return;
|
||||||
|
|
||||||
|
// we are creating a new edge here
|
||||||
|
if (this.state.activeSocket || this.state.possibleSockets?.length) {
|
||||||
|
let smallestDist = 1000;
|
||||||
|
let _socket;
|
||||||
|
for (const socket of this.state.possibleSockets) {
|
||||||
|
const dist = Math.sqrt(
|
||||||
|
(socket.position[0] - this.state.mousePosition[0]) ** 2
|
||||||
|
+ (socket.position[1] - this.state.mousePosition[1]) ** 2
|
||||||
|
);
|
||||||
|
if (dist < smallestDist) {
|
||||||
|
smallestDist = dist;
|
||||||
|
_socket = socket;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_socket && smallestDist < 1.5) {
|
||||||
|
this.state.mousePosition = _socket.position;
|
||||||
|
this.state.hoveredSocket = _socket;
|
||||||
|
} else {
|
||||||
|
this.state.hoveredSocket = null;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// handle box selection
|
||||||
|
if (this.state.boxSelection) {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
const mouseD = this.state.projectScreenToWorld(
|
||||||
|
this.state.mouseDown[0],
|
||||||
|
this.state.mouseDown[1]
|
||||||
|
);
|
||||||
|
const x1 = Math.min(mouseD[0], this.state.mousePosition[0]);
|
||||||
|
const x2 = Math.max(mouseD[0], this.state.mousePosition[0]);
|
||||||
|
const y1 = Math.min(mouseD[1], this.state.mousePosition[1]);
|
||||||
|
const y2 = Math.max(mouseD[1], this.state.mousePosition[1]);
|
||||||
|
for (const node of this.graph.nodes.values()) {
|
||||||
|
if (!node?.state) continue;
|
||||||
|
const x = node.position[0];
|
||||||
|
const y = node.position[1];
|
||||||
|
const height = this.state.getNodeHeight(node.type);
|
||||||
|
if (x > x1 - 20 && x < x2 && y > y1 - height && y < y2) {
|
||||||
|
this.state.selectedNodes?.add(node.id);
|
||||||
|
} else {
|
||||||
|
this.state.selectedNodes?.delete(node.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// here we are handling dragging of nodes
|
||||||
|
if (this.state.activeNodeId !== -1 && this.state.mouseDownNodeId !== -1) {
|
||||||
|
this.edgeInteractionManager.handleMouseMove();
|
||||||
|
const node = this.graph.getNode(this.state.activeNodeId);
|
||||||
|
if (!node || event.buttons !== 1) return;
|
||||||
|
|
||||||
|
node.state = node.state || {};
|
||||||
|
|
||||||
|
const oldX = node.state.downX || 0;
|
||||||
|
const oldY = node.state.downY || 0;
|
||||||
|
|
||||||
|
let newX = oldX + (mx - this.state.mouseDown[0]) / this.state.cameraPosition[2];
|
||||||
|
let newY = oldY + (my - this.state.mouseDown[1]) / this.state.cameraPosition[2];
|
||||||
|
|
||||||
|
if (event.ctrlKey) {
|
||||||
|
const snapLevel = this.state.getSnapLevel();
|
||||||
|
if (this.state.snapToGrid) {
|
||||||
|
newX = snapPointToGrid(newX, 5 / snapLevel);
|
||||||
|
newY = snapPointToGrid(newY, 5 / snapLevel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!node.state.isMoving) {
|
||||||
|
const dist = Math.sqrt((oldX - newX) ** 2 + (oldY - newY) ** 2);
|
||||||
|
if (dist > 0.2) {
|
||||||
|
node.state.isMoving = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const vecX = oldX - newX;
|
||||||
|
const vecY = oldY - newY;
|
||||||
|
|
||||||
|
if (this.state.selectedNodes?.size) {
|
||||||
|
for (const nodeId of this.state.selectedNodes) {
|
||||||
|
const n = this.graph.getNode(nodeId);
|
||||||
|
if (!n?.state) continue;
|
||||||
|
n.state.x = (n?.state?.downX || 0) - vecX;
|
||||||
|
n.state.y = (n?.state?.downY || 0) - vecY;
|
||||||
|
this.state.updateNodePosition(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
node.state.x = newX;
|
||||||
|
node.state.y = newY;
|
||||||
|
|
||||||
|
this.state.updateNodePosition(node);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// here we are handling panning of camera
|
||||||
|
this.state.isPanning = true;
|
||||||
|
const newX = this.state.cameraDown[0]
|
||||||
|
- (mx - this.state.mouseDown[0]) / this.state.cameraPosition[2];
|
||||||
|
const newY = this.state.cameraDown[1]
|
||||||
|
- (my - this.state.mouseDown[1]) / this.state.cameraPosition[2];
|
||||||
|
|
||||||
|
this.state.cameraPosition[0] = newX;
|
||||||
|
this.state.cameraPosition[1] = newY;
|
||||||
|
}
|
||||||
|
|
||||||
|
handleMouseScroll(event: WheelEvent) {
|
||||||
|
const bodyIsFocused = document.activeElement === document.body
|
||||||
|
|| document.activeElement === this.state.wrapper
|
||||||
|
|| document?.activeElement?.id === 'graph';
|
||||||
|
if (!bodyIsFocused) return;
|
||||||
|
|
||||||
|
// Define zoom speed and clamp it between -1 and 1
|
||||||
|
const isNegative = event.deltaY < 0;
|
||||||
|
const normalizedDelta = Math.abs(event.deltaY * 0.01);
|
||||||
|
const delta = Math.pow(0.95, zoomSpeed * normalizedDelta);
|
||||||
|
|
||||||
|
// Calculate new zoom level and clamp it between minZoom and maxZoom
|
||||||
|
const newZoom = Math.max(
|
||||||
|
minZoom,
|
||||||
|
Math.min(
|
||||||
|
maxZoom,
|
||||||
|
isNegative
|
||||||
|
? this.state.cameraPosition[2] / delta
|
||||||
|
: this.state.cameraPosition[2] * delta
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Calculate the ratio of the new zoom to the original zoom
|
||||||
|
const zoomRatio = newZoom / this.state.cameraPosition[2];
|
||||||
|
|
||||||
|
// Update camera position and zoom level
|
||||||
|
this.state.cameraPosition[0] = this.state.mousePosition[0]
|
||||||
|
- (this.state.mousePosition[0] - this.state.cameraPosition[0])
|
||||||
|
/ zoomRatio;
|
||||||
|
this.state.cameraPosition[1] = this.state.mousePosition[1]
|
||||||
|
- (this.state.mousePosition[1] - this.state.cameraPosition[1])
|
||||||
|
/ zoomRatio;
|
||||||
|
this.state.cameraPosition[2] = newZoom;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
import type { Socket } from "@nodes/types";
|
|
||||||
import { getContext } from "svelte";
|
|
||||||
import { SvelteSet } from 'svelte/reactivity';
|
|
||||||
|
|
||||||
export function getGraphState() {
|
|
||||||
return getContext<GraphState>("graphState");
|
|
||||||
}
|
|
||||||
|
|
||||||
export class GraphState {
|
|
||||||
activeNodeId = $state(-1);
|
|
||||||
selectedNodes = new SvelteSet<number>();
|
|
||||||
activeSocket = $state<Socket | null>(null);
|
|
||||||
hoveredSocket = $state<Socket | null>(null);
|
|
||||||
possibleSockets = $state<Socket[]>([]);
|
|
||||||
possibleSocketIds = $derived(new Set(
|
|
||||||
this.possibleSockets.map((s) => `${s.node.id}-${s.index}`),
|
|
||||||
));
|
|
||||||
clearSelection() {
|
|
||||||
this.selectedNodes.clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,15 +1,15 @@
|
|||||||
import throttle from './throttle.js';
|
import throttle from '$lib/helpers/throttle';
|
||||||
|
|
||||||
type EventMap = Record<string, unknown>;
|
type EventMap = Record<string, unknown>;
|
||||||
type EventKey<T extends EventMap> = string & keyof T;
|
type EventKey<T extends EventMap> = string & keyof T;
|
||||||
type EventReceiver<T> = (params: T, stuff?: Record<string, unknown>) => unknown;
|
type EventReceiver<T> = (params: T, stuff?: Record<string, unknown>) => unknown;
|
||||||
|
|
||||||
|
export default class EventEmitter<
|
||||||
export default class EventEmitter<T extends EventMap = { [key: string]: unknown }> {
|
T extends EventMap = { [key: string]: unknown }
|
||||||
|
> {
|
||||||
index = 0;
|
index = 0;
|
||||||
public eventMap: T = {} as T;
|
public eventMap: T = {} as T;
|
||||||
constructor() {
|
constructor() {}
|
||||||
}
|
|
||||||
|
|
||||||
private cbs: { [key: string]: ((data?: unknown) => unknown)[] } = {};
|
private cbs: { [key: string]: ((data?: unknown) => unknown)[] } = {};
|
||||||
private cbsOnce: { [key: string]: ((data?: unknown) => unknown)[] } = {};
|
private cbsOnce: { [key: string]: ((data?: unknown) => unknown)[] } = {};
|
||||||
@@ -29,16 +29,20 @@ export default class EventEmitter<T extends EventMap = { [key: string]: unknown
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public on<K extends EventKey<T>>(event: K, cb: EventReceiver<T[K]>, throttleTimer = 0) {
|
public on<K extends EventKey<T>>(
|
||||||
|
event: K,
|
||||||
|
cb: EventReceiver<T[K]>,
|
||||||
|
throttleTimer = 0
|
||||||
|
) {
|
||||||
if (throttleTimer > 0) cb = throttle(cb, throttleTimer);
|
if (throttleTimer > 0) cb = throttle(cb, throttleTimer);
|
||||||
const cbs = Object.assign(this.cbs, {
|
const cbs = Object.assign(this.cbs, {
|
||||||
[event]: [...(this.cbs[event] || []), cb],
|
[event]: [...(this.cbs[event] || []), cb]
|
||||||
});
|
});
|
||||||
this.cbs = cbs;
|
this.cbs = cbs;
|
||||||
|
|
||||||
// console.log('New EventEmitter ', this.constructor.name);
|
// console.log('New EventEmitter ', this.constructor.name);
|
||||||
return () => {
|
return () => {
|
||||||
cbs[event]?.splice(cbs[event].indexOf(cb), 1);
|
this.cbs[event]?.splice(cbs[event].indexOf(cb), 1);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,10 +52,17 @@ export default class EventEmitter<T extends EventMap = { [key: string]: unknown
|
|||||||
* @param {function} cb Listener, gets called everytime the event is emitted
|
* @param {function} cb Listener, gets called everytime the event is emitted
|
||||||
* @returns {function} Returns a function which removes the listener when called
|
* @returns {function} Returns a function which removes the listener when called
|
||||||
*/
|
*/
|
||||||
public once<K extends EventKey<T>>(event: K, cb: EventReceiver<T[K]>): () => void {
|
public once<K extends EventKey<T>>(
|
||||||
this.cbsOnce[event] = [...(this.cbsOnce[event] || []), cb];
|
event: K,
|
||||||
|
cb: EventReceiver<T[K]>
|
||||||
|
): () => void {
|
||||||
|
const cbsOnce = Object.assign(this.cbsOnce, {
|
||||||
|
[event]: [...(this.cbsOnce[event] || []), cb]
|
||||||
|
});
|
||||||
|
this.cbsOnce = cbsOnce;
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
this.cbsOnce[event].splice(this.cbsOnce[event].indexOf(cb), 1);
|
cbsOnce[event]?.splice(cbsOnce[event].indexOf(cb), 1);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,10 @@ export function lerp(a: number, b: number, t: number) {
|
|||||||
return a + (b - a) * t;
|
return a + (b - a) * t;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function animate(duration: number, callback: (progress: number) => void | false) {
|
export function animate(
|
||||||
|
duration: number,
|
||||||
|
callback: (progress: number) => void | false
|
||||||
|
) {
|
||||||
const start = performance.now();
|
const start = performance.now();
|
||||||
const loop = (time: number) => {
|
const loop = (time: number) => {
|
||||||
const progress = (time - start) / duration;
|
const progress = (time - start) / duration;
|
||||||
@@ -18,7 +21,7 @@ export function animate(duration: number, callback: (progress: number) => void |
|
|||||||
} else {
|
} else {
|
||||||
callback(1);
|
callback(1);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
requestAnimationFrame(loop);
|
requestAnimationFrame(loop);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,10 +33,11 @@ export function createNodePath({
|
|||||||
cornerBottom = 0,
|
cornerBottom = 0,
|
||||||
leftBump = false,
|
leftBump = false,
|
||||||
rightBump = false,
|
rightBump = false,
|
||||||
aspectRatio = 1,
|
aspectRatio = 1
|
||||||
} = {}) {
|
} = {}) {
|
||||||
return `M0,${cornerTop}
|
return `M0,${cornerTop}
|
||||||
${cornerTop
|
${
|
||||||
|
cornerTop
|
||||||
? ` V${cornerTop}
|
? ` V${cornerTop}
|
||||||
Q0,0 ${cornerTop * aspectRatio},0
|
Q0,0 ${cornerTop * aspectRatio},0
|
||||||
H${100 - cornerTop * aspectRatio}
|
H${100 - cornerTop * aspectRatio}
|
||||||
@@ -42,62 +46,37 @@ export function createNodePath({
|
|||||||
: ` V0
|
: ` V0
|
||||||
H100
|
H100
|
||||||
`
|
`
|
||||||
}
|
}
|
||||||
V${y - height / 2}
|
V${y - height / 2}
|
||||||
${rightBump
|
${
|
||||||
|
rightBump
|
||||||
? ` C${100 - depth},${y - height / 2} ${100 - depth},${y + height / 2} 100,${y + height / 2}`
|
? ` C${100 - depth},${y - height / 2} ${100 - depth},${y + height / 2} 100,${y + height / 2}`
|
||||||
: ` H100`
|
: ` H100`
|
||||||
}
|
}
|
||||||
${cornerBottom
|
${
|
||||||
|
cornerBottom
|
||||||
? ` V${100 - cornerBottom}
|
? ` V${100 - cornerBottom}
|
||||||
Q100,100 ${100 - cornerBottom * aspectRatio},100
|
Q100,100 ${100 - cornerBottom * aspectRatio},100
|
||||||
H${cornerBottom * aspectRatio}
|
H${cornerBottom * aspectRatio}
|
||||||
Q0,100 0,${100 - cornerBottom}
|
Q0,100 0,${100 - cornerBottom}
|
||||||
`
|
`
|
||||||
: `${leftBump ? `V100 H0` : `V100`}`
|
: `${leftBump ? `V100 H0` : `V100`}`
|
||||||
}
|
}
|
||||||
${leftBump
|
${
|
||||||
? ` V${y + height / 2} C${depth},${y + height / 2} ${depth},${y - height / 2} 0,${y - height / 2}`
|
leftBump
|
||||||
|
? ` V${y + height / 2} C${depth},${y + height / 2} ${depth},${y - height / 2} 0,${
|
||||||
|
y - height / 2
|
||||||
|
}`
|
||||||
: ` H0`
|
: ` H0`
|
||||||
}
|
}
|
||||||
Z`.replace(/\s+/g, " ");
|
Z`.replace(/\s+/g, ' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
export const debounce = (fn: Function, ms = 300) => {
|
export const clone: <T>(v: T) => T = 'structedClone' in globalThis
|
||||||
let timeoutId: ReturnType<typeof setTimeout>;
|
? globalThis.structuredClone
|
||||||
return function (this: any, ...args: any[]) {
|
: (obj) => JSON.parse(JSON.stringify(obj));
|
||||||
clearTimeout(timeoutId);
|
|
||||||
timeoutId = setTimeout(() => fn.apply(this, args), ms);
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export const clone: <T>(v: T) => T = "structedClone" in globalThis ? globalThis.structuredClone : (obj) => JSON.parse(JSON.stringify(obj));
|
export function withSubComponents<A, B extends Record<string, unknown>>(
|
||||||
|
|
||||||
export const createLogger = (() => {
|
|
||||||
let maxLength = 5;
|
|
||||||
return (scope: string) => {
|
|
||||||
maxLength = Math.max(maxLength, scope.length);
|
|
||||||
let muted = false;
|
|
||||||
return {
|
|
||||||
log: (...args: any[]) => !muted && console.log(`[%c${scope.padEnd(maxLength, " ")}]:`, "color: #888", ...args),
|
|
||||||
group: (...args: any[]) => !muted && console.groupCollapsed(`[%c${scope.padEnd(maxLength, " ")}]:`, "color: #888", ...args),
|
|
||||||
groupEnd: () => !muted && console.groupEnd(),
|
|
||||||
info: (...args: any[]) => !muted && console.info(`[%c${scope.padEnd(maxLength, " ")}]:`, "color: #888", ...args),
|
|
||||||
warn: (...args: any[]) => !muted && console.warn(`[%c${scope.padEnd(maxLength, " ")}]:`, "color: #888", ...args),
|
|
||||||
error: (...args: any[]) => console.error(`[%c${scope.padEnd(maxLength, " ")}]:`, "color: #f88", ...args),
|
|
||||||
mute() {
|
|
||||||
muted = true;
|
|
||||||
},
|
|
||||||
unmute() {
|
|
||||||
muted = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
|
|
||||||
export function withSubComponents<A, B extends Record<string, any>>(
|
|
||||||
component: A,
|
component: A,
|
||||||
subcomponents: B
|
subcomponents: B
|
||||||
): A & B {
|
): A & B {
|
||||||
@@ -107,3 +86,27 @@ export function withSubComponents<A, B extends Record<string, any>>(
|
|||||||
});
|
});
|
||||||
return component as A & B;
|
return component as A & B;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function distanceFromPointToSegment(
|
||||||
|
x1: number,
|
||||||
|
y1: number,
|
||||||
|
x2: number,
|
||||||
|
y2: number,
|
||||||
|
x0: number,
|
||||||
|
y0: number
|
||||||
|
): number {
|
||||||
|
const dx = x2 - x1;
|
||||||
|
const dy = y2 - y1;
|
||||||
|
|
||||||
|
if (dx === 0 && dy === 0) {
|
||||||
|
return Math.hypot(x0 - x1, y0 - y1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const t = ((x0 - x1) * dx + (y0 - y1) * dy) / (dx * dx + dy * dy);
|
||||||
|
const clampedT = Math.max(0, Math.min(1, t));
|
||||||
|
|
||||||
|
const px = x1 + clampedT * dx;
|
||||||
|
const py = y1 + clampedT * dy;
|
||||||
|
|
||||||
|
return Math.hypot(x0 - px, y0 - py);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
import { writable, type Writable } from "svelte/store";
|
import { type Writable, writable } from 'svelte/store';
|
||||||
|
|
||||||
function isStore(v: unknown): v is Writable<unknown> {
|
function isStore(v: unknown): v is Writable<unknown> {
|
||||||
return v !== null && typeof v === "object" && "subscribe" in v && "set" in v;
|
return v !== null && typeof v === 'object' && 'subscribe' in v && 'set' in v;
|
||||||
}
|
}
|
||||||
|
|
||||||
const storeIds: Map<string, ReturnType<typeof createLocalStore>> = new Map();
|
const storeIds: Map<string, ReturnType<typeof createLocalStore>> = new Map();
|
||||||
|
|
||||||
const HAS_LOCALSTORAGE = "localStorage" in globalThis;
|
const HAS_LOCALSTORAGE = 'localStorage' in globalThis;
|
||||||
|
|
||||||
function createLocalStore<T>(key: string, initialValue: T | Writable<T>) {
|
function createLocalStore<T>(key: string, initialValue: T | Writable<T>) {
|
||||||
|
|
||||||
let store: Writable<T>;
|
let store: Writable<T>;
|
||||||
|
|
||||||
if (HAS_LOCALSTORAGE) {
|
if (HAS_LOCALSTORAGE) {
|
||||||
@@ -36,18 +35,15 @@ function createLocalStore<T>(key: string, initialValue: T | Writable<T>) {
|
|||||||
subscribe: store.subscribe,
|
subscribe: store.subscribe,
|
||||||
set: store.set,
|
set: store.set,
|
||||||
update: store.update
|
update: store.update
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export default function localStore<T>(key: string, initialValue: T | Writable<T>): Writable<T> {
|
export default function localStore<T>(key: string, initialValue: T | Writable<T>): Writable<T> {
|
||||||
|
|
||||||
if (storeIds.has(key)) return storeIds.get(key) as Writable<T>;
|
if (storeIds.has(key)) return storeIds.get(key) as Writable<T>;
|
||||||
|
|
||||||
const store = createLocalStore(key, initialValue)
|
const store = createLocalStore(key, initialValue);
|
||||||
|
|
||||||
storeIds.set(key, store);
|
storeIds.set(key, store);
|
||||||
|
|
||||||
return store
|
return store;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
export default <R, A extends any[]>(
|
|
||||||
fn: (...args: A) => R,
|
|
||||||
delay: number
|
|
||||||
): ((...args: A) => R) => {
|
|
||||||
let wait = false;
|
|
||||||
|
|
||||||
return (...args: A) => {
|
|
||||||
if (wait) return undefined;
|
|
||||||
|
|
||||||
const val = fn(...args);
|
|
||||||
|
|
||||||
wait = true;
|
|
||||||
|
|
||||||
setTimeout(() => {
|
|
||||||
wait = false;
|
|
||||||
}, delay);
|
|
||||||
|
|
||||||
return val;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,24 +1,24 @@
|
|||||||
import { create, type Delta } from "jsondiffpatch";
|
import type { Graph } from '@nodarium/types';
|
||||||
import type { Graph } from "@nodes/types";
|
import { createLogger } from '@nodarium/utils';
|
||||||
import { createLogger, clone } from "./helpers/index.js";
|
import { create, type Delta } from 'jsondiffpatch';
|
||||||
|
import { clone } from './helpers/index.js';
|
||||||
|
|
||||||
const diff = create({
|
const diff = create({
|
||||||
objectHash: function (obj, index) {
|
objectHash: function(obj, index) {
|
||||||
if (obj === null) return obj;
|
if (obj === null) return obj;
|
||||||
if ("id" in obj) return obj.id;
|
if ('id' in obj) return obj.id as string;
|
||||||
|
if ('_id' in obj) return obj._id as string;
|
||||||
if (Array.isArray(obj)) {
|
if (Array.isArray(obj)) {
|
||||||
return obj.join("-")
|
return obj.join('-');
|
||||||
}
|
}
|
||||||
return obj?.id || obj._id || '$$index:' + index;
|
return '$$index:' + index;
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
|
||||||
const log = createLogger("history")
|
const log = createLogger('history');
|
||||||
log.mute();
|
log.mute();
|
||||||
|
|
||||||
export class HistoryManager {
|
export class HistoryManager {
|
||||||
|
|
||||||
index: number = -1;
|
index: number = -1;
|
||||||
history: Delta[] = [];
|
history: Delta[] = [];
|
||||||
private initialState: Graph | undefined;
|
private initialState: Graph | undefined;
|
||||||
@@ -26,27 +26,26 @@ export class HistoryManager {
|
|||||||
|
|
||||||
private opts = {
|
private opts = {
|
||||||
debounce: 400,
|
debounce: 400,
|
||||||
maxHistory: 100,
|
maxHistory: 100
|
||||||
}
|
};
|
||||||
|
|
||||||
constructor({ maxHistory = 100, debounce = 100 } = {}) {
|
constructor({ maxHistory = 100, debounce = 100 } = {}) {
|
||||||
this.history = [];
|
this.history = [];
|
||||||
this.index = -1;
|
this.index = -1;
|
||||||
this.opts.debounce = debounce;
|
this.opts.debounce = debounce;
|
||||||
this.opts.maxHistory = maxHistory;
|
this.opts.maxHistory = maxHistory;
|
||||||
globalThis["_history"] = this;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
save(state: Graph) {
|
save(state: Graph) {
|
||||||
if (!this.state) {
|
if (!this.state) {
|
||||||
this.state = clone(state);
|
this.state = clone(state);
|
||||||
this.initialState = this.state;
|
this.initialState = this.state;
|
||||||
log.log("initial state saved")
|
log.log('initial state saved');
|
||||||
} else {
|
} else {
|
||||||
const newState = state;
|
const newState = state;
|
||||||
const delta = diff.diff(this.state, newState);
|
const delta = diff.diff(this.state, newState);
|
||||||
if (delta) {
|
if (delta) {
|
||||||
log.log("saving state")
|
log.log('saving state');
|
||||||
// Add the delta to history
|
// Add the delta to history
|
||||||
if (this.index < this.history.length - 1) {
|
if (this.index < this.history.length - 1) {
|
||||||
// Clear the history after the current index if new changes are made
|
// Clear the history after the current index if new changes are made
|
||||||
@@ -62,7 +61,7 @@ export class HistoryManager {
|
|||||||
}
|
}
|
||||||
this.state = newState;
|
this.state = newState;
|
||||||
} else {
|
} else {
|
||||||
log.log("no changes")
|
log.log('no changes');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -76,7 +75,7 @@ export class HistoryManager {
|
|||||||
|
|
||||||
undo() {
|
undo() {
|
||||||
if (this.index === -1 && this.initialState) {
|
if (this.index === -1 && this.initialState) {
|
||||||
log.log("reached start, loading initial state")
|
log.log('reached start, loading initial state');
|
||||||
return clone(this.initialState);
|
return clone(this.initialState);
|
||||||
} else {
|
} else {
|
||||||
const delta = this.history[this.index];
|
const delta = this.history[this.index];
|
||||||
@@ -96,7 +95,7 @@ export class HistoryManager {
|
|||||||
this.state = nextState;
|
this.state = nextState;
|
||||||
return clone(nextState);
|
return clone(nextState);
|
||||||
} else {
|
} else {
|
||||||
log.log("reached end")
|
log.log('reached end');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
183
app/src/lib/graph-interface/keymaps.ts
Normal file
183
app/src/lib/graph-interface/keymaps.ts
Normal file
@@ -0,0 +1,183 @@
|
|||||||
|
import { animate, lerp } from '$lib/helpers';
|
||||||
|
import type { createKeyMap } from '$lib/helpers/createKeyMap';
|
||||||
|
import { panelState } from '$lib/sidebar/PanelState.svelte';
|
||||||
|
import FileSaver from 'file-saver';
|
||||||
|
import type { GraphManager } from './graph-manager.svelte';
|
||||||
|
import type { GraphState } from './graph-state.svelte';
|
||||||
|
|
||||||
|
type Keymap = ReturnType<typeof createKeyMap>;
|
||||||
|
export function setupKeymaps(keymap: Keymap, graph: GraphManager, graphState: GraphState) {
|
||||||
|
keymap.addShortcut({
|
||||||
|
key: 'l',
|
||||||
|
description: 'Select linked nodes',
|
||||||
|
callback: () => {
|
||||||
|
const activeNode = graph.getNode(graphState.activeNodeId);
|
||||||
|
if (activeNode) {
|
||||||
|
const nodes = graph.getLinkedNodes(activeNode);
|
||||||
|
graphState.selectedNodes.clear();
|
||||||
|
for (const node of nodes) {
|
||||||
|
graphState.selectedNodes.add(node.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
keymap.addShortcut({
|
||||||
|
key: '?',
|
||||||
|
description: 'Toggle Help',
|
||||||
|
callback: () => {
|
||||||
|
panelState.setActivePanel('shortcuts');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
keymap.addShortcut({
|
||||||
|
key: 'c',
|
||||||
|
ctrl: true,
|
||||||
|
description: 'Copy active nodes',
|
||||||
|
callback: () => graphState.copyNodes()
|
||||||
|
});
|
||||||
|
|
||||||
|
keymap.addShortcut({
|
||||||
|
key: 'v',
|
||||||
|
ctrl: true,
|
||||||
|
description: 'Paste nodes',
|
||||||
|
callback: () => graphState.pasteNodes()
|
||||||
|
});
|
||||||
|
|
||||||
|
keymap.addShortcut({
|
||||||
|
key: 'Escape',
|
||||||
|
description: 'Deselect nodes',
|
||||||
|
callback: () => {
|
||||||
|
graphState.activeNodeId = -1;
|
||||||
|
graphState.clearSelection();
|
||||||
|
graphState.edgeEndPosition = null;
|
||||||
|
(document.activeElement as HTMLElement)?.blur();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
keymap.addShortcut({
|
||||||
|
key: 'A',
|
||||||
|
shift: true,
|
||||||
|
description: 'Add new Node',
|
||||||
|
callback: () => graphState.openNodePalette()
|
||||||
|
});
|
||||||
|
|
||||||
|
keymap.addShortcut({
|
||||||
|
key: '.',
|
||||||
|
description: 'Center camera',
|
||||||
|
callback: () => {
|
||||||
|
if (!graphState.isBodyFocused()) return;
|
||||||
|
|
||||||
|
const average = [0, 0];
|
||||||
|
for (const node of graph.nodes.values()) {
|
||||||
|
average[0] += node.position[0];
|
||||||
|
average[1] += node.position[1];
|
||||||
|
}
|
||||||
|
average[0] = average[0] ? average[0] / graph.nodes.size : 0;
|
||||||
|
average[1] = average[1] ? average[1] / graph.nodes.size : 0;
|
||||||
|
|
||||||
|
const camX = graphState.cameraPosition[0];
|
||||||
|
const camY = graphState.cameraPosition[1];
|
||||||
|
const camZ = graphState.cameraPosition[2];
|
||||||
|
|
||||||
|
const ease = (t: number) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t);
|
||||||
|
|
||||||
|
animate(500, (a: number) => {
|
||||||
|
graphState.cameraPosition[0] = lerp(camX, average[0], ease(a));
|
||||||
|
graphState.cameraPosition[1] = lerp(camY, average[1], ease(a));
|
||||||
|
graphState.cameraPosition[2] = lerp(camZ, 2, ease(a));
|
||||||
|
if (graphState.mouseDown) return false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
keymap.addShortcut({
|
||||||
|
key: 'a',
|
||||||
|
ctrl: true,
|
||||||
|
preventDefault: true,
|
||||||
|
description: 'Select all nodes',
|
||||||
|
callback: () => {
|
||||||
|
if (!graphState.isBodyFocused()) return;
|
||||||
|
for (const node of graph.nodes.keys()) {
|
||||||
|
graphState.selectedNodes.add(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
keymap.addShortcut({
|
||||||
|
key: 'z',
|
||||||
|
ctrl: true,
|
||||||
|
description: 'Undo',
|
||||||
|
callback: () => {
|
||||||
|
if (!graphState.isBodyFocused()) return;
|
||||||
|
graph.undo();
|
||||||
|
for (const node of graph.nodes.values()) {
|
||||||
|
graphState.updateNodePosition(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
keymap.addShortcut({
|
||||||
|
key: 'y',
|
||||||
|
ctrl: true,
|
||||||
|
description: 'Redo',
|
||||||
|
callback: () => {
|
||||||
|
graph.redo();
|
||||||
|
for (const node of graph.nodes.values()) {
|
||||||
|
graphState.updateNodePosition(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
keymap.addShortcut({
|
||||||
|
key: 's',
|
||||||
|
ctrl: true,
|
||||||
|
description: 'Save',
|
||||||
|
preventDefault: true,
|
||||||
|
callback: () => {
|
||||||
|
const state = graph.serialize();
|
||||||
|
const blob = new Blob([JSON.stringify(state)], {
|
||||||
|
type: 'application/json;charset=utf-8'
|
||||||
|
});
|
||||||
|
FileSaver.saveAs(blob, 'nodarium-graph.json');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
keymap.addShortcut({
|
||||||
|
key: ['Delete', 'Backspace', 'x'],
|
||||||
|
description: 'Delete selected nodes',
|
||||||
|
callback: (event) => {
|
||||||
|
if (!graphState.isBodyFocused()) return;
|
||||||
|
graph.startUndoGroup();
|
||||||
|
if (graphState.activeNodeId !== -1) {
|
||||||
|
const node = graph.getNode(graphState.activeNodeId);
|
||||||
|
if (node) {
|
||||||
|
graph.removeNode(node, { restoreEdges: event.ctrlKey });
|
||||||
|
graphState.activeNodeId = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (graphState.selectedNodes) {
|
||||||
|
for (const nodeId of graphState.selectedNodes) {
|
||||||
|
const node = graph.getNode(nodeId);
|
||||||
|
if (node) {
|
||||||
|
graph.removeNode(node, { restoreEdges: event.ctrlKey });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
graphState.clearSelection();
|
||||||
|
}
|
||||||
|
graph.saveUndoGroup();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
keymap.addShortcut({
|
||||||
|
key: 'f',
|
||||||
|
description: 'Smart Connect Nodes',
|
||||||
|
callback: () => {
|
||||||
|
const nodes = [...graphState.selectedNodes.values()]
|
||||||
|
.map((g) => graph.getNode(g))
|
||||||
|
.filter((n) => !!n);
|
||||||
|
const edge = graph.smartConnect(nodes[0], nodes[1]);
|
||||||
|
if (!edge) graph.smartConnect(nodes[1], nodes[0]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,61 +1,49 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type { Node } from "@nodes/types";
|
import { appSettings } from '$lib/settings/app-settings.svelte';
|
||||||
import { getContext, onMount } from "svelte";
|
import type { NodeInstance } from '@nodarium/types';
|
||||||
import { getGraphState } from "../graph/state.svelte";
|
import { T } from '@threlte/core';
|
||||||
import { T } from "@threlte/core";
|
import { type Mesh } from 'three';
|
||||||
import { type Mesh } from "three";
|
import { getGraphState } from '../graph-state.svelte';
|
||||||
import NodeFrag from "./Node.frag";
|
import { colors } from '../graph/colors.svelte';
|
||||||
import NodeVert from "./Node.vert";
|
import NodeFrag from './Node.frag';
|
||||||
import NodeHtml from "./NodeHTML.svelte";
|
import NodeVert from './Node.vert';
|
||||||
import { colors } from "../graph/colors.svelte";
|
import NodeHtml from './NodeHTML.svelte';
|
||||||
import { appSettings } from "$lib/settings/app-settings.svelte";
|
|
||||||
|
|
||||||
const graphState = getGraphState();
|
const graphState = getGraphState();
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
node: Node;
|
node: NodeInstance;
|
||||||
inView: boolean;
|
inView: boolean;
|
||||||
z: number;
|
z: number;
|
||||||
};
|
};
|
||||||
const { node, inView, z }: Props = $props();
|
let { node = $bindable(), inView, z }: Props = $props();
|
||||||
|
|
||||||
const isActive = $derived(graphState.activeNodeId === node.id);
|
const isActive = $derived(graphState.activeNodeId === node.id);
|
||||||
const isSelected = $derived(graphState.selectedNodes.has(node.id));
|
const isSelected = $derived(graphState.selectedNodes.has(node.id));
|
||||||
let strokeColor = $state(colors.selected);
|
const strokeColor = $derived(
|
||||||
$effect(() => {
|
appSettings.value.theme
|
||||||
appSettings.theme;
|
&& (isSelected
|
||||||
strokeColor = isSelected
|
? colors.selected
|
||||||
? colors.selected
|
: isActive
|
||||||
: isActive
|
|
||||||
? colors.active
|
? colors.active
|
||||||
: colors.outline;
|
: colors.outline)
|
||||||
});
|
);
|
||||||
|
|
||||||
const updateNodePosition =
|
|
||||||
getContext<(n: Node) => void>("updateNodePosition");
|
|
||||||
|
|
||||||
const getNodeHeight = getContext<(n: string) => number>("getNodeHeight");
|
|
||||||
|
|
||||||
let meshRef: Mesh | undefined = $state();
|
let meshRef: Mesh | undefined = $state();
|
||||||
|
|
||||||
const height = getNodeHeight?.(node.type);
|
const height = graphState.getNodeHeight(node.type);
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
node.tmp = node.tmp || {};
|
if (meshRef && !node.state?.mesh) {
|
||||||
node.tmp.mesh = meshRef;
|
node.state.mesh = meshRef;
|
||||||
updateNodePosition?.(node);
|
graphState.updateNodePosition(node);
|
||||||
});
|
}
|
||||||
|
|
||||||
onMount(() => {
|
|
||||||
node.tmp = node.tmp || {};
|
|
||||||
node.tmp.mesh = meshRef;
|
|
||||||
updateNodePosition?.(node);
|
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<T.Mesh
|
<T.Mesh
|
||||||
position.x={node.position[0] + 10}
|
position.x={(node.state.x ?? node.position[0]) + 10}
|
||||||
position.z={node.position[1] + height / 2}
|
position.z={(node.state.y ?? node.position[1]) + height / 2}
|
||||||
position.y={0.8}
|
position.y={0.8}
|
||||||
rotation.x={-Math.PI / 2}
|
rotation.x={-Math.PI / 2}
|
||||||
bind:ref={meshRef}
|
bind:ref={meshRef}
|
||||||
@@ -67,16 +55,16 @@
|
|||||||
fragmentShader={NodeFrag}
|
fragmentShader={NodeFrag}
|
||||||
transparent
|
transparent
|
||||||
uniforms={{
|
uniforms={{
|
||||||
uColorBright: { value: colors["layer-2"] },
|
uColorBright: { value: colors['layer-2'] },
|
||||||
uColorDark: { value: colors["layer-1"] },
|
uColorDark: { value: colors['layer-1'] },
|
||||||
uStrokeColor: { value: colors.outline.clone() },
|
uStrokeColor: { value: colors.outline.clone() },
|
||||||
uStrokeWidth: { value: 1.0 },
|
uStrokeWidth: { value: 1.0 },
|
||||||
uWidth: { value: 20 },
|
uWidth: { value: 20 },
|
||||||
uHeight: { value: height },
|
uHeight: { value: height }
|
||||||
}}
|
}}
|
||||||
uniforms.uStrokeColor.value={strokeColor.clone()}
|
uniforms.uStrokeColor.value={strokeColor.clone()}
|
||||||
uniforms.uStrokeWidth.value={(7 - z) / 3}
|
uniforms.uStrokeWidth.value={(7 - z) / 3}
|
||||||
/>
|
/>
|
||||||
</T.Mesh>
|
</T.Mesh>
|
||||||
|
|
||||||
<NodeHtml {node} {inView} {isActive} {isSelected} {z} />
|
<NodeHtml bind:node {inView} {isActive} {isSelected} {z} />
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type { Node } from "@nodes/types";
|
import type { NodeInstance } from '@nodarium/types';
|
||||||
import NodeHeader from "./NodeHeader.svelte";
|
import { getGraphState } from '../graph-state.svelte';
|
||||||
import NodeParameter from "./NodeParameter.svelte";
|
import NodeHeader from './NodeHeader.svelte';
|
||||||
import { getContext, onMount } from "svelte";
|
import NodeParameter from './NodeParameter.svelte';
|
||||||
|
|
||||||
let ref: HTMLDivElement;
|
let ref: HTMLDivElement;
|
||||||
|
|
||||||
|
const graphState = getGraphState();
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
node: Node;
|
node: NodeInstance;
|
||||||
position?: "absolute" | "fixed" | "relative";
|
position?: 'absolute' | 'fixed' | 'relative';
|
||||||
isActive?: boolean;
|
isActive?: boolean;
|
||||||
isSelected?: boolean;
|
isSelected?: boolean;
|
||||||
inView?: boolean;
|
inView?: boolean;
|
||||||
@@ -17,30 +19,26 @@
|
|||||||
|
|
||||||
let {
|
let {
|
||||||
node = $bindable(),
|
node = $bindable(),
|
||||||
position = "absolute",
|
position = 'absolute',
|
||||||
isActive = false,
|
isActive = false,
|
||||||
isSelected = false,
|
isSelected = false,
|
||||||
inView = true,
|
inView = true,
|
||||||
z = 2,
|
z = 2
|
||||||
}: Props = $props();
|
}: Props = $props();
|
||||||
|
|
||||||
const zOffset = (node.tmp?.random || 0) * 0.5;
|
// If we dont have a random offset, all nodes becom visible at the same zoom level -> stuttering
|
||||||
|
const zOffset = Math.random() - 0.5;
|
||||||
const zLimit = 2 - zOffset;
|
const zLimit = 2 - zOffset;
|
||||||
|
|
||||||
const type = node?.tmp?.type;
|
const parameters = Object.entries(node.state?.type?.inputs || {}).filter(
|
||||||
|
(p) => p[1].type !== 'seed' && !('setting' in p[1]) && p[1]?.hidden !== true
|
||||||
const parameters = Object.entries(type?.inputs || {}).filter(
|
|
||||||
(p) =>
|
|
||||||
p[1].type !== "seed" && !("setting" in p[1]) && p[1]?.hidden !== true,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const updateNodePosition =
|
$effect(() => {
|
||||||
getContext<(n: Node) => void>("updateNodePosition");
|
if ('state' in node && !node.state.ref) {
|
||||||
|
node.state.ref = ref;
|
||||||
onMount(() => {
|
graphState?.updateNodePosition(node);
|
||||||
node.tmp = node.tmp || {};
|
}
|
||||||
node.tmp.ref = ref;
|
|
||||||
updateNodePosition?.(node);
|
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -48,7 +46,7 @@
|
|||||||
class="node {position}"
|
class="node {position}"
|
||||||
class:active={isActive}
|
class:active={isActive}
|
||||||
style:--cz={z + zOffset}
|
style:--cz={z + zOffset}
|
||||||
style:display={inView && z > zLimit ? "block" : "none"}
|
style:display={inView && z > zLimit ? 'block' : 'none'}
|
||||||
class:selected={isSelected}
|
class:selected={isSelected}
|
||||||
class:out-of-view={!inView}
|
class:out-of-view={!inView}
|
||||||
data-node-id={node.id}
|
data-node-id={node.id}
|
||||||
@@ -57,7 +55,7 @@
|
|||||||
>
|
>
|
||||||
<NodeHeader {node} />
|
<NodeHeader {node} />
|
||||||
|
|
||||||
{#each parameters as [key, value], i}
|
{#each parameters as [key, value], i (key)}
|
||||||
<NodeParameter
|
<NodeParameter
|
||||||
bind:node
|
bind:node
|
||||||
id={key}
|
id={key}
|
||||||
@@ -73,22 +71,22 @@
|
|||||||
user-select: none !important;
|
user-select: none !important;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
width: 200px;
|
width: 200px;
|
||||||
color: var(--text-color);
|
color: var(--color-text);
|
||||||
transform: translate3d(var(--nx), var(--ny), 0);
|
transform: translate3d(var(--nx), var(--ny), 0);
|
||||||
z-index: 1;
|
z-index: 1;
|
||||||
opacity: calc((var(--cz) - 2.5) / 3.5);
|
opacity: calc((var(--cz) - 2.5) / 3.5);
|
||||||
font-weight: 300;
|
font-weight: 300;
|
||||||
--stroke: var(--outline);
|
--stroke: var(--color-outline);
|
||||||
--stroke-width: 2px;
|
--stroke-width: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.node.active {
|
.node.active {
|
||||||
--stroke: var(--active);
|
--stroke: var(--color-active);
|
||||||
--stroke-width: 2px;
|
--stroke-width: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.node.selected {
|
.node.selected {
|
||||||
--stroke: var(--selected);
|
--stroke: var(--color-selected);
|
||||||
--stroke-width: 2px;
|
--stroke-width: 2px;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,66 +1,61 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { createNodePath } from "../helpers/index.js";
|
import type { NodeInstance } from '@nodarium/types';
|
||||||
import type { Node, Socket } from "@nodes/types";
|
import { getGraphState } from '../graph-state.svelte';
|
||||||
import { getContext } from "svelte";
|
import { createNodePath } from '../helpers/index.js';
|
||||||
|
|
||||||
export let node: Node;
|
const graphState = getGraphState();
|
||||||
|
|
||||||
const setDownSocket = getContext<(socket: Socket) => void>("setDownSocket");
|
const { node }: { node: NodeInstance } = $props();
|
||||||
const getSocketPosition =
|
|
||||||
getContext<(node: Node, index: number) => [number, number]>(
|
|
||||||
"getSocketPosition",
|
|
||||||
);
|
|
||||||
|
|
||||||
function handleMouseDown(event: MouseEvent) {
|
function handleMouseDown(event: MouseEvent) {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
setDownSocket?.({
|
if ('state' in node) {
|
||||||
node,
|
graphState.setDownSocket?.({
|
||||||
index: 0,
|
node,
|
||||||
position: getSocketPosition?.(node, 0),
|
index: 0,
|
||||||
});
|
position: graphState.getSocketPosition?.(node, 0)
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const cornerTop = 10;
|
const cornerTop = 10;
|
||||||
const rightBump = !!node?.tmp?.type?.outputs?.length;
|
const rightBump = $derived(!!node?.state?.type?.outputs?.length);
|
||||||
const aspectRatio = 0.25;
|
const aspectRatio = 0.25;
|
||||||
|
|
||||||
const path = createNodePath({
|
const path = $derived(
|
||||||
depth: 5.5,
|
createNodePath({
|
||||||
height: 34,
|
depth: 5.5,
|
||||||
y: 49,
|
height: 34,
|
||||||
cornerTop,
|
y: 49,
|
||||||
rightBump,
|
cornerTop,
|
||||||
aspectRatio,
|
rightBump,
|
||||||
});
|
aspectRatio
|
||||||
const pathDisabled = createNodePath({
|
})
|
||||||
depth: 0,
|
);
|
||||||
height: 15,
|
const pathHover = $derived(
|
||||||
y: 50,
|
createNodePath({
|
||||||
cornerTop,
|
depth: 7,
|
||||||
rightBump,
|
height: 40,
|
||||||
aspectRatio,
|
y: 49,
|
||||||
});
|
cornerTop,
|
||||||
const pathHover = createNodePath({
|
rightBump,
|
||||||
depth: 8.5,
|
aspectRatio
|
||||||
height: 50,
|
})
|
||||||
y: 49,
|
);
|
||||||
cornerTop,
|
|
||||||
rightBump,
|
|
||||||
aspectRatio,
|
|
||||||
});
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="wrapper" data-node-id={node.id} data-node-type={node.type}>
|
<div class="wrapper" data-node-id={node.id} data-node-type={node.type}>
|
||||||
<div class="content">
|
<div class="content">
|
||||||
{node.type.split("/").pop()}
|
{node.type.split('/').pop()}
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
class="click-target"
|
class="click-target"
|
||||||
role="button"
|
role="button"
|
||||||
tabindex="0"
|
tabindex="0"
|
||||||
on:mousedown={handleMouseDown}
|
onmousedown={handleMouseDown}
|
||||||
></div>
|
>
|
||||||
|
</div>
|
||||||
<svg
|
<svg
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
viewBox="0 0 100 100"
|
viewBox="0 0 100 100"
|
||||||
@@ -72,8 +67,7 @@
|
|||||||
--hover-path: path("${pathHover}");
|
--hover-path: path("${pathHover}");
|
||||||
`}
|
`}
|
||||||
>
|
>
|
||||||
<path vector-effect="non-scaling-stroke" stroke="white" stroke-width="0.1"
|
<path vector-effect="non-scaling-stroke" stroke="white" stroke-width="0.1"></path>
|
||||||
></path>
|
|
||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -114,13 +108,14 @@
|
|||||||
|
|
||||||
svg path {
|
svg path {
|
||||||
stroke-width: 0.2px;
|
stroke-width: 0.2px;
|
||||||
transition:
|
transition: d 0.3s ease, fill 0.3s ease;
|
||||||
d 0.3s ease,
|
fill: var(--color-layer-2);
|
||||||
fill 0.3s ease;
|
|
||||||
fill: var(--layer-2);
|
|
||||||
stroke: var(--stroke);
|
stroke: var(--stroke);
|
||||||
stroke-width: var(--stroke-width);
|
stroke-width: var(--stroke-width);
|
||||||
d: var(--path);
|
d: var(--path);
|
||||||
|
|
||||||
|
stroke-linejoin: round;
|
||||||
|
shape-rendering: geometricPrecision;
|
||||||
}
|
}
|
||||||
|
|
||||||
.content {
|
.content {
|
||||||
|
|||||||
@@ -1,32 +1,33 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type { Node, NodeInput } from "@nodes/types";
|
import type { NodeInput, NodeInstance } from '@nodarium/types';
|
||||||
import { getGraphManager } from "../graph/context.js";
|
import { Input } from '@nodarium/ui';
|
||||||
import { Input } from "@nodes/ui";
|
import type { GraphManager } from '../graph-manager.svelte';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
node: Node;
|
node: NodeInstance;
|
||||||
input: NodeInput;
|
input: NodeInput;
|
||||||
id: string;
|
id: string;
|
||||||
elementId?: string;
|
elementId?: string;
|
||||||
|
graph?: GraphManager;
|
||||||
};
|
};
|
||||||
|
|
||||||
const {
|
const {
|
||||||
node,
|
node = $bindable(),
|
||||||
input,
|
input,
|
||||||
id,
|
id,
|
||||||
elementId = `input-${Math.random().toString(36).substring(7)}`,
|
elementId = `input-${Math.random().toString(36).substring(7)}`,
|
||||||
|
graph
|
||||||
}: Props = $props();
|
}: Props = $props();
|
||||||
|
|
||||||
const graph = getGraphManager();
|
|
||||||
|
|
||||||
function getDefaultValue() {
|
function getDefaultValue() {
|
||||||
if (node?.props?.[id] !== undefined) return node?.props?.[id] as number;
|
if (node?.props?.[id] !== undefined) return node?.props?.[id] as number;
|
||||||
if ("value" in input && input?.value !== undefined)
|
if ('value' in input && input?.value !== undefined) {
|
||||||
return input?.value as number;
|
return input?.value as number;
|
||||||
if (input.type === "boolean") return 0;
|
}
|
||||||
if (input.type === "float") return 0.5;
|
if (input.type === 'boolean') return 0;
|
||||||
if (input.type === "integer") return 0;
|
if (input.type === 'float') return 0.5;
|
||||||
if (input.type === "select") return 0;
|
if (input.type === 'integer') return 0;
|
||||||
|
if (input.type === 'select') return 0;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,112 +1,94 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type {
|
import type { NodeInput, NodeInstance } from '@nodarium/types';
|
||||||
NodeInput as NodeInputType,
|
import { getGraphManager, getGraphState } from '../graph-state.svelte';
|
||||||
Socket,
|
import { createNodePath } from '../helpers';
|
||||||
Node as NodeType,
|
import NodeInputEl from './NodeInput.svelte';
|
||||||
} from "@nodes/types";
|
|
||||||
import { getContext } from "svelte";
|
|
||||||
import { createNodePath } from "../helpers/index.js";
|
|
||||||
import { getGraphManager } from "../graph/context.js";
|
|
||||||
import NodeInput from "./NodeInput.svelte";
|
|
||||||
import { getGraphState } from "../graph/state.svelte.js";
|
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
node: NodeType;
|
node: NodeInstance;
|
||||||
input: NodeInputType;
|
input: NodeInput;
|
||||||
id: string;
|
id: string;
|
||||||
isLast?: boolean;
|
isLast?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
const { node = $bindable(), input, id, isLast }: Props = $props();
|
|
||||||
|
|
||||||
const inputType = node?.tmp?.type?.inputs?.[id]!;
|
|
||||||
|
|
||||||
const socketId = `${node.id}-${id}`;
|
|
||||||
|
|
||||||
const graph = getGraphManager();
|
const graph = getGraphManager();
|
||||||
|
|
||||||
|
let { node = $bindable(), input, id, isLast }: Props = $props();
|
||||||
|
|
||||||
|
const inputType = $derived(node?.state?.type?.inputs?.[id]);
|
||||||
|
|
||||||
|
const socketId = $derived(`${node.id}-${id}`);
|
||||||
|
|
||||||
const graphState = getGraphState();
|
const graphState = getGraphState();
|
||||||
const graphId = graph?.id;
|
const graphId = graph?.id;
|
||||||
const inputSockets = graph?.inputSockets;
|
|
||||||
|
|
||||||
const elementId = `input-${Math.random().toString(36).substring(7)}`;
|
const elementId = `input-${Math.random().toString(36).substring(7)}`;
|
||||||
|
|
||||||
const setDownSocket = getContext<(socket: Socket) => void>("setDownSocket");
|
|
||||||
const getSocketPosition =
|
|
||||||
getContext<(node: NodeType, index: string) => [number, number]>(
|
|
||||||
"getSocketPosition",
|
|
||||||
);
|
|
||||||
|
|
||||||
function handleMouseDown(ev: MouseEvent) {
|
function handleMouseDown(ev: MouseEvent) {
|
||||||
ev.preventDefault();
|
ev.preventDefault();
|
||||||
ev.stopPropagation();
|
ev.stopPropagation();
|
||||||
setDownSocket?.({
|
graphState.setDownSocket({
|
||||||
node,
|
node,
|
||||||
index: id,
|
index: id,
|
||||||
position: getSocketPosition?.(node, id),
|
position: graphState.getSocketPosition?.(node, id)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const leftBump = node.tmp?.type?.inputs?.[id].internal !== true;
|
const leftBump = $derived(node.state?.type?.inputs?.[id].internal !== true);
|
||||||
const cornerBottom = isLast ? 5 : 0;
|
const cornerBottom = $derived(isLast ? 5 : 0);
|
||||||
const aspectRatio = 0.5;
|
const aspectRatio = 0.5;
|
||||||
|
|
||||||
const path = createNodePath({
|
const path = $derived(
|
||||||
depth: 7,
|
createNodePath({
|
||||||
height: 20,
|
depth: 6,
|
||||||
y: 50.5,
|
height: 18,
|
||||||
cornerBottom,
|
y: 50.5,
|
||||||
leftBump,
|
cornerBottom,
|
||||||
aspectRatio,
|
leftBump,
|
||||||
});
|
aspectRatio
|
||||||
const pathDisabled = createNodePath({
|
})
|
||||||
depth: 6,
|
);
|
||||||
height: 18,
|
const pathHover = $derived(
|
||||||
y: 50.5,
|
createNodePath({
|
||||||
cornerBottom,
|
depth: 7,
|
||||||
leftBump,
|
height: 20,
|
||||||
aspectRatio,
|
y: 50.5,
|
||||||
});
|
cornerBottom,
|
||||||
const pathHover = createNodePath({
|
leftBump,
|
||||||
depth: 8,
|
aspectRatio
|
||||||
height: 25,
|
})
|
||||||
y: 50.5,
|
);
|
||||||
cornerBottom,
|
|
||||||
leftBump,
|
|
||||||
aspectRatio,
|
|
||||||
});
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
class="wrapper"
|
class="wrapper"
|
||||||
data-node-type={node.type}
|
data-node-type={node.type}
|
||||||
data-node-input={id}
|
data-node-input={id}
|
||||||
class:disabled={!graphState?.possibleSocketIds.has(socketId)}
|
class:possible-socket={graphState?.possibleSocketIds.has(socketId)}
|
||||||
>
|
>
|
||||||
{#key id && graphId}
|
{#key id && graphId}
|
||||||
<div class="content" class:disabled={$inputSockets?.has(socketId)}>
|
<div class="content" class:disabled={graph?.inputSockets?.has(socketId)}>
|
||||||
{#if inputType.label !== ""}
|
{#if inputType?.label !== ''}
|
||||||
<label for={elementId}>{input.label || id}</label>
|
<label for={elementId} title={input.description}>{input.label || id}</label>
|
||||||
{/if}
|
{/if}
|
||||||
{#if inputType.external !== true}
|
<span
|
||||||
<NodeInput {elementId} {node} {input} {id} />
|
class="absolute i-[tabler--help-circle] size-4 block top-2 right-2 opacity-30"
|
||||||
|
title={JSON.stringify(input, null, 2)}
|
||||||
|
></span>
|
||||||
|
{#if inputType?.external !== true}
|
||||||
|
<NodeInputEl {graph} {elementId} bind:node {input} {id} />
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{#if node?.tmp?.type?.inputs?.[id]?.internal !== true}
|
{#if node?.state?.type?.inputs?.[id]?.internal !== true}
|
||||||
<div
|
<div
|
||||||
data-node-socket
|
data-node-socket
|
||||||
class="large target"
|
class="target"
|
||||||
onmousedown={handleMouseDown}
|
onmousedown={handleMouseDown}
|
||||||
role="button"
|
role="button"
|
||||||
tabindex="0"
|
tabindex="0"
|
||||||
></div>
|
>
|
||||||
<div
|
</div>
|
||||||
data-node-socket
|
|
||||||
class="small target"
|
|
||||||
onmousedown={handleMouseDown}
|
|
||||||
role="button"
|
|
||||||
tabindex="0"
|
|
||||||
></div>
|
|
||||||
{/if}
|
{/if}
|
||||||
{/key}
|
{/key}
|
||||||
|
|
||||||
@@ -119,7 +101,6 @@
|
|||||||
style={`
|
style={`
|
||||||
--path: path("${path}");
|
--path: path("${path}");
|
||||||
--hover-path: path("${pathHover}");
|
--hover-path: path("${pathHover}");
|
||||||
--hover-path-disabled: path("${pathDisabled}");
|
|
||||||
`}
|
`}
|
||||||
>
|
>
|
||||||
<path vector-effect="non-scaling-stroke"></path>
|
<path vector-effect="non-scaling-stroke"></path>
|
||||||
@@ -135,28 +116,22 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.target {
|
.target {
|
||||||
|
width: 30px;
|
||||||
|
height: 30px;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
top: 50%;
|
top: 50%;
|
||||||
transform: translateY(-50%) translateX(-50%);
|
transform: translateY(-50%) translateX(-50%);
|
||||||
/* background: red; */
|
|
||||||
/* opacity: 0.1; */
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.small.target {
|
.possible-socket .target {
|
||||||
width: 30px;
|
box-shadow: 0px 0px 10px rgba(255, 255, 255, 0.5);
|
||||||
height: 30px;
|
background-color: rgba(255, 255, 255, 0.2);
|
||||||
|
z-index: -10;
|
||||||
}
|
}
|
||||||
|
|
||||||
.large.target {
|
.target:hover ~ svg path{
|
||||||
width: 60px;
|
d: var(--hover-path);
|
||||||
height: 60px;
|
|
||||||
cursor: unset;
|
|
||||||
pointer-events: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
:global(.hovering-sockets) .large.target {
|
|
||||||
pointer-events: all;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.content {
|
.content {
|
||||||
@@ -181,29 +156,21 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
svg path {
|
svg path {
|
||||||
transition:
|
transition: d 0.3s ease, fill 0.3s ease;
|
||||||
d 0.3s ease,
|
fill: var(--color-layer-1);
|
||||||
fill 0.3s ease;
|
|
||||||
fill: var(--layer-1);
|
|
||||||
stroke: var(--stroke);
|
stroke: var(--stroke);
|
||||||
stroke-width: var(--stroke-width);
|
stroke-width: var(--stroke-width);
|
||||||
d: var(--path);
|
d: var(--path);
|
||||||
}
|
|
||||||
|
|
||||||
:global {
|
stroke-linejoin: round;
|
||||||
.hovering-sockets .large:hover ~ svg path {
|
shape-rendering: geometricPrecision;
|
||||||
d: var(--hover-path);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.content.disabled {
|
.content.disabled {
|
||||||
opacity: 0.2;
|
opacity: 0.2;
|
||||||
}
|
}
|
||||||
.content.disabled > * {
|
|
||||||
pointer-events: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.disabled svg path {
|
.possible-socket svg path {
|
||||||
d: var(--hover-path-disabled) !important;
|
d: var(--hover-path);
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
86
app/src/lib/graph-interface/test-utils.ts
Normal file
86
app/src/lib/graph-interface/test-utils.ts
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
import type { NodeDefinition, NodeId, NodeRegistry } from '@nodarium/types';
|
||||||
|
|
||||||
|
export function createMockNodeRegistry(nodes: NodeDefinition[]): NodeRegistry {
|
||||||
|
const nodesMap = new Map(nodes.map(n => [n.id, n]));
|
||||||
|
return {
|
||||||
|
status: 'ready' as const,
|
||||||
|
load: async (nodeIds: NodeId[]) => {
|
||||||
|
const loaded: NodeDefinition[] = [];
|
||||||
|
for (const id of nodeIds) {
|
||||||
|
if (nodesMap.has(id)) {
|
||||||
|
loaded.push(nodesMap.get(id)!);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return loaded;
|
||||||
|
},
|
||||||
|
getNode: (id: string) => nodesMap.get(id as NodeId),
|
||||||
|
getAllNodes: () => Array.from(nodesMap.values()),
|
||||||
|
register: async () => {
|
||||||
|
throw new Error('Not implemented in mock');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const mockFloatOutputNode: NodeDefinition = {
|
||||||
|
id: 'test/node/output',
|
||||||
|
inputs: {},
|
||||||
|
outputs: ['float'],
|
||||||
|
meta: { title: 'Float Output' },
|
||||||
|
execute: () => new Int32Array()
|
||||||
|
};
|
||||||
|
|
||||||
|
export const mockFloatInputNode: NodeDefinition = {
|
||||||
|
id: 'test/node/input',
|
||||||
|
inputs: { value: { type: 'float' } },
|
||||||
|
outputs: [],
|
||||||
|
meta: { title: 'Float Input' },
|
||||||
|
execute: () => new Int32Array()
|
||||||
|
};
|
||||||
|
|
||||||
|
export const mockGeometryOutputNode: NodeDefinition = {
|
||||||
|
id: 'test/node/geometry',
|
||||||
|
inputs: {},
|
||||||
|
outputs: ['geometry'],
|
||||||
|
meta: { title: 'Geometry Output' },
|
||||||
|
execute: () => new Int32Array()
|
||||||
|
};
|
||||||
|
|
||||||
|
export const mockPathInputNode: NodeDefinition = {
|
||||||
|
id: 'test/node/path',
|
||||||
|
inputs: { input: { type: 'path', accepts: ['geometry'] } },
|
||||||
|
outputs: [],
|
||||||
|
meta: { title: 'Path Input' },
|
||||||
|
execute: () => new Int32Array()
|
||||||
|
};
|
||||||
|
|
||||||
|
export const mockVec3OutputNode: NodeDefinition = {
|
||||||
|
id: 'test/node/vec3',
|
||||||
|
inputs: {},
|
||||||
|
outputs: ['vec3'],
|
||||||
|
meta: { title: 'Vec3 Output' },
|
||||||
|
execute: () => new Int32Array()
|
||||||
|
};
|
||||||
|
|
||||||
|
export const mockIntegerInputNode: NodeDefinition = {
|
||||||
|
id: 'test/node/integer',
|
||||||
|
inputs: { value: { type: 'integer' } },
|
||||||
|
outputs: [],
|
||||||
|
meta: { title: 'Integer Input' },
|
||||||
|
execute: () => new Int32Array()
|
||||||
|
};
|
||||||
|
|
||||||
|
export const mockBooleanOutputNode: NodeDefinition = {
|
||||||
|
id: 'test/node/boolean',
|
||||||
|
inputs: {},
|
||||||
|
outputs: ['boolean'],
|
||||||
|
meta: { title: 'Boolean Output' },
|
||||||
|
execute: () => new Int32Array()
|
||||||
|
};
|
||||||
|
|
||||||
|
export const mockBooleanInputNode: NodeDefinition = {
|
||||||
|
id: 'test/node/boolean-input',
|
||||||
|
inputs: { value: { type: 'boolean' } },
|
||||||
|
outputs: [],
|
||||||
|
meta: { title: 'Boolean Input' },
|
||||||
|
execute: () => new Int32Array()
|
||||||
|
};
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
import type { Node, NodeDefinition } from "@nodes/types";
|
|
||||||
|
|
||||||
export type GraphNode = Node & {
|
|
||||||
tmp?: {
|
|
||||||
depth?: number;
|
|
||||||
mesh?: any;
|
|
||||||
random?: number;
|
|
||||||
parents?: Node[];
|
|
||||||
children?: Node[];
|
|
||||||
inputNodes?: Record<string, Node>;
|
|
||||||
type?: NodeDefinition;
|
|
||||||
downX?: number;
|
|
||||||
downY?: number;
|
|
||||||
x?: number;
|
|
||||||
y?: number;
|
|
||||||
ref?: HTMLElement;
|
|
||||||
visible?: boolean;
|
|
||||||
isMoving?: boolean;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
110
app/src/lib/graph-templates.test.ts
Normal file
110
app/src/lib/graph-templates.test.ts
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
import { grid } from '$lib/graph-templates/grid';
|
||||||
|
import { tree } from '$lib/graph-templates/tree';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
describe('graph-templates', () => {
|
||||||
|
describe('grid', () => {
|
||||||
|
it('should create a grid graph with nodes and edges', () => {
|
||||||
|
const result = grid(2, 3);
|
||||||
|
expect(result.nodes.length).toBeGreaterThan(0);
|
||||||
|
expect(result.edges.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should have output node at the end', () => {
|
||||||
|
const result = grid(1, 1);
|
||||||
|
const outputNode = result.nodes.find(n => n.type === 'max/plantarium/output');
|
||||||
|
expect(outputNode).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create nodes based on grid dimensions', () => {
|
||||||
|
const result = grid(2, 2);
|
||||||
|
const mathNodes = result.nodes.filter(n => n.type === 'max/plantarium/math');
|
||||||
|
expect(mathNodes.length).toBeGreaterThan(0);
|
||||||
|
const outputNode = result.nodes.find(n => n.type === 'max/plantarium/output');
|
||||||
|
expect(outputNode).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should have output node at the end', () => {
|
||||||
|
const result = grid(1, 1);
|
||||||
|
const outputNode = result.nodes.find(n => n.type === 'max/plantarium/output');
|
||||||
|
expect(outputNode).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create nodes based on grid dimensions', () => {
|
||||||
|
const result = grid(2, 2);
|
||||||
|
const mathNodes = result.nodes.filter(n => n.type === 'max/plantarium/math');
|
||||||
|
expect(mathNodes.length).toBeGreaterThan(0);
|
||||||
|
const outputNode = result.nodes.find(n => n.type === 'max/plantarium/output');
|
||||||
|
expect(outputNode).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should have valid node positions', () => {
|
||||||
|
const result = grid(3, 2);
|
||||||
|
|
||||||
|
result.nodes.forEach(node => {
|
||||||
|
expect(node.position).toHaveLength(2);
|
||||||
|
expect(typeof node.position[0]).toBe('number');
|
||||||
|
expect(typeof node.position[1]).toBe('number');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should generate valid graph structure', () => {
|
||||||
|
const result = grid(2, 2);
|
||||||
|
|
||||||
|
result.nodes.forEach(node => {
|
||||||
|
expect(typeof node.id).toBe('number');
|
||||||
|
expect(node.type).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
result.edges.forEach(edge => {
|
||||||
|
expect(edge).toHaveLength(4);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('tree', () => {
|
||||||
|
it('should create a tree graph with specified depth', () => {
|
||||||
|
const result = tree(0);
|
||||||
|
|
||||||
|
expect(result.nodes.length).toBeGreaterThan(0);
|
||||||
|
expect(result.edges.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should have root output node', () => {
|
||||||
|
const result = tree(2);
|
||||||
|
|
||||||
|
const outputNode = result.nodes.find(n => n.type === 'max/plantarium/output');
|
||||||
|
expect(outputNode).toBeDefined();
|
||||||
|
expect(outputNode?.id).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should increase node count with depth', () => {
|
||||||
|
const tree0 = tree(0);
|
||||||
|
const tree1 = tree(1);
|
||||||
|
const tree2 = tree(2);
|
||||||
|
|
||||||
|
expect(tree0.nodes.length).toBeLessThan(tree1.nodes.length);
|
||||||
|
expect(tree1.nodes.length).toBeLessThan(tree2.nodes.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create binary tree structure', () => {
|
||||||
|
const result = tree(2);
|
||||||
|
|
||||||
|
const mathNodes = result.nodes.filter(n => n.type === 'max/plantarium/math');
|
||||||
|
expect(mathNodes.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const edgeCount = result.edges.length;
|
||||||
|
expect(edgeCount).toBe(result.nodes.length - 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should have valid node positions', () => {
|
||||||
|
const result = tree(3);
|
||||||
|
|
||||||
|
result.nodes.forEach(node => {
|
||||||
|
expect(node.position).toHaveLength(2);
|
||||||
|
expect(typeof node.position[0]).toBe('number');
|
||||||
|
expect(typeof node.position[1]).toBe('number');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1 +1,95 @@
|
|||||||
{"settings":{"resolution.circle":26,"resolution.curve":39},"nodes":[{"id":9,"position":[220,80],"type":"max/plantarium/output","props":{}},{"id":10,"position":[95,80],"type":"max/plantarium/stem","props":{"amount":5,"length":11,"thickness":0.1}},{"id":14,"position":[195,80],"type":"max/plantarium/gravity","props":{"strength":0.38,"scale":39,"fixBottom":0,"directionalStrength":[1,1,1],"depth":1,"curviness":1}},{"id":15,"position":[120,80],"type":"max/plantarium/noise","props":{"strength":4.9,"scale":2.2,"fixBottom":1,"directionalStrength":[1,1,1],"depth":1,"octaves":1}},{"id":16,"position":[70,80],"type":"max/plantarium/vec3","props":{"0":0,"1":0,"2":0}},{"id":17,"position":[45,80],"type":"max/plantarium/random","props":{"min":-2,"max":2}},{"id":18,"position":[170,80],"type":"max/plantarium/branch","props":{"length":1.6,"thickness":0.69,"amount":36,"offsetSingle":0.5,"lowestBranch":0.46,"highestBranch":1,"depth":1,"rotation":180}},{"id":19,"position":[145,80],"type":"max/plantarium/gravity","props":{"strength":0.38,"scale":39,"fixBottom":0,"directionalStrength":[1,1,1],"depth":1,"curviness":1}},{"id":20,"position":[70,120],"type":"max/plantarium/random","props":{"min":0.073,"max":0.15}}],"edges":[[14,0,9,"input"],[10,0,15,"plant"],[16,0,10,"origin"],[17,0,16,"0"],[17,0,16,"2"],[18,0,14,"plant"],[15,0,19,"plant"],[19,0,18,"plant"],[20,0,10,"thickness"]]}
|
{
|
||||||
|
"settings": { "resolution.circle": 26, "resolution.curve": 39 },
|
||||||
|
"nodes": [
|
||||||
|
{ "id": 9, "position": [220, 80], "type": "max/plantarium/output", "props": {} },
|
||||||
|
{
|
||||||
|
"id": 10,
|
||||||
|
"position": [95, 80],
|
||||||
|
"type": "max/plantarium/stem",
|
||||||
|
"props": { "amount": 5, "length": 11, "thickness": 0.1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 14,
|
||||||
|
"position": [195, 80],
|
||||||
|
"type": "max/plantarium/gravity",
|
||||||
|
"props": {
|
||||||
|
"strength": 0.38,
|
||||||
|
"scale": 39,
|
||||||
|
"fixBottom": 0,
|
||||||
|
"directionalStrength": [1, 1, 1],
|
||||||
|
"depth": 1,
|
||||||
|
"curviness": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 15,
|
||||||
|
"position": [120, 80],
|
||||||
|
"type": "max/plantarium/noise",
|
||||||
|
"props": {
|
||||||
|
"strength": 4.9,
|
||||||
|
"scale": 2.2,
|
||||||
|
"fixBottom": 1,
|
||||||
|
"directionalStrength": [1, 1, 1],
|
||||||
|
"depth": 1,
|
||||||
|
"octaves": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 16,
|
||||||
|
"position": [70, 80],
|
||||||
|
"type": "max/plantarium/vec3",
|
||||||
|
"props": { "0": 0, "1": 0, "2": 0 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 17,
|
||||||
|
"position": [45, 80],
|
||||||
|
"type": "max/plantarium/random",
|
||||||
|
"props": { "min": -2, "max": 2 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 18,
|
||||||
|
"position": [170, 80],
|
||||||
|
"type": "max/plantarium/branch",
|
||||||
|
"props": {
|
||||||
|
"length": 1.6,
|
||||||
|
"thickness": 0.69,
|
||||||
|
"amount": 36,
|
||||||
|
"offsetSingle": 0.5,
|
||||||
|
"lowestBranch": 0.46,
|
||||||
|
"highestBranch": 1,
|
||||||
|
"depth": 1,
|
||||||
|
"rotation": 180
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 19,
|
||||||
|
"position": [145, 80],
|
||||||
|
"type": "max/plantarium/gravity",
|
||||||
|
"props": {
|
||||||
|
"strength": 0.38,
|
||||||
|
"scale": 39,
|
||||||
|
"fixBottom": 0,
|
||||||
|
"directionalStrength": [1, 1, 1],
|
||||||
|
"depth": 1,
|
||||||
|
"curviness": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 20,
|
||||||
|
"position": [70, 120],
|
||||||
|
"type": "max/plantarium/random",
|
||||||
|
"props": { "min": 0.073, "max": 0.15 }
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"edges": [
|
||||||
|
[14, 0, 9, "input"],
|
||||||
|
[10, 0, 15, "plant"],
|
||||||
|
[16, 0, 10, "origin"],
|
||||||
|
[17, 0, 16, "0"],
|
||||||
|
[17, 0, 16, "2"],
|
||||||
|
[18, 0, 14, "plant"],
|
||||||
|
[15, 0, 19, "plant"],
|
||||||
|
[19, 0, 18, "plant"],
|
||||||
|
[20, 0, 10, "thickness"]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import type { Graph } from "@nodes/types";
|
import type { Graph } from '@nodarium/types';
|
||||||
|
|
||||||
export function grid(width: number, height: number) {
|
export function grid(width: number, height: number) {
|
||||||
|
|
||||||
const graph: Graph = {
|
const graph: Graph = {
|
||||||
id: Math.floor(Math.random() * 100000),
|
id: Math.floor(Math.random() * 100000),
|
||||||
edges: [],
|
edges: [],
|
||||||
nodes: [],
|
nodes: []
|
||||||
};
|
};
|
||||||
|
|
||||||
const amount = width * height;
|
const amount = width * height;
|
||||||
@@ -16,27 +15,20 @@ export function grid(width: number, height: number) {
|
|||||||
|
|
||||||
graph.nodes.push({
|
graph.nodes.push({
|
||||||
id: i,
|
id: i,
|
||||||
tmp: {
|
|
||||||
visible: false,
|
|
||||||
},
|
|
||||||
position: [x * 30, y * 40],
|
position: [x * 30, y * 40],
|
||||||
props: i == 0 ? { value: 0 } : { op_type: 0, a: 1, b: 0.05 },
|
props: i == 0 ? { value: 0 } : { op_type: 0, a: 1, b: 0.05 },
|
||||||
type: i == 0 ? "max/plantarium/float" : "max/plantarium/math",
|
type: i == 0 ? 'max/plantarium/float' : 'max/plantarium/math'
|
||||||
});
|
});
|
||||||
|
|
||||||
graph.edges.push([i, 0, i + 1, i === amount - 1 ? "input" : "a",]);
|
graph.edges.push([i, 0, i + 1, i === amount - 1 ? 'input' : 'a']);
|
||||||
}
|
}
|
||||||
|
|
||||||
graph.nodes.push({
|
graph.nodes.push({
|
||||||
id: amount,
|
id: amount,
|
||||||
tmp: {
|
|
||||||
visible: false,
|
|
||||||
},
|
|
||||||
position: [width * 30, (height - 1) * 40],
|
position: [width * 30, (height - 1) * 40],
|
||||||
type: "max/plantarium/output",
|
type: 'max/plantarium/output',
|
||||||
props: {},
|
props: {}
|
||||||
});
|
});
|
||||||
|
|
||||||
return graph;
|
return graph;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
export { grid } from "./grid";
|
export { default as defaultPlant } from './default.json';
|
||||||
export { tree } from "./tree";
|
export { grid } from './grid';
|
||||||
export { plant } from "./plant";
|
export { default as lottaFaces } from './lotta-faces.json';
|
||||||
export { default as lottaFaces } from "./lotta-faces.json";
|
export { default as lottaNodesAndFaces } from './lotta-nodes-and-faces.json';
|
||||||
export { default as lottaNodes } from "./lotta-nodes.json";
|
export { default as lottaNodes } from './lotta-nodes.json';
|
||||||
export { default as defaultPlant } from "./default.json"
|
export { plant } from './plant';
|
||||||
export { default as lottaNodesAndFaces } from "./lotta-nodes-and-faces.json";
|
export { default as simple } from './simple.json';
|
||||||
|
export { tree } from './tree';
|
||||||
|
|||||||
@@ -1 +1,44 @@
|
|||||||
{"settings":{"resolution.circle":64,"resolution.curve":64,"randomSeed":false},"nodes":[{"id":9,"position":[260,0],"type":"max/plantarium/output","props":{}},{"id":18,"position":[185,0],"type":"max/plantarium/stem","props":{"amount":64,"length":12,"thickness":0.15}},{"id":19,"position":[210,0],"type":"max/plantarium/noise","props":{"scale":1.3,"strength":5.4}},{"id":20,"position":[235,0],"type":"max/plantarium/branch","props":{"length":0.8,"thickness":0.8,"amount":3}},{"id":21,"position":[160,0],"type":"max/plantarium/vec3","props":{"0":0.39,"1":0,"2":0.41}},{"id":22,"position":[130,0],"type":"max/plantarium/random","props":{"min":-2,"max":2}}],"edges":[[18,0,19,"plant"],[19,0,20,"plant"],[20,0,9,"input"],[21,0,18,"origin"],[22,0,21,"0"],[22,0,21,"2"]]}
|
{
|
||||||
|
"settings": { "resolution.circle": 64, "resolution.curve": 64, "randomSeed": false },
|
||||||
|
"nodes": [
|
||||||
|
{ "id": 9, "position": [260, 0], "type": "max/plantarium/output", "props": {} },
|
||||||
|
{
|
||||||
|
"id": 18,
|
||||||
|
"position": [185, 0],
|
||||||
|
"type": "max/plantarium/stem",
|
||||||
|
"props": { "amount": 64, "length": 12, "thickness": 0.15 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 19,
|
||||||
|
"position": [210, 0],
|
||||||
|
"type": "max/plantarium/noise",
|
||||||
|
"props": { "scale": 1.3, "strength": 5.4 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 20,
|
||||||
|
"position": [235, 0],
|
||||||
|
"type": "max/plantarium/branch",
|
||||||
|
"props": { "length": 0.8, "thickness": 0.8, "amount": 3 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 21,
|
||||||
|
"position": [160, 0],
|
||||||
|
"type": "max/plantarium/vec3",
|
||||||
|
"props": { "0": 0.39, "1": 0, "2": 0.41 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 22,
|
||||||
|
"position": [130, 0],
|
||||||
|
"type": "max/plantarium/random",
|
||||||
|
"props": { "min": -2, "max": 2 }
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"edges": [
|
||||||
|
[18, 0, 19, "plant"],
|
||||||
|
[19, 0, 20, "plant"],
|
||||||
|
[20, 0, 9, "input"],
|
||||||
|
[21, 0, 18, "origin"],
|
||||||
|
[22, 0, 21, "0"],
|
||||||
|
[22, 0, 21, "2"]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,12 +1,71 @@
|
|||||||
export const plant = {
|
export const plant = {
|
||||||
"settings": { "resolution.circle": 26, "resolution.curve": 39 },
|
'settings': { 'resolution.circle': 26, 'resolution.curve': 39 },
|
||||||
"nodes": [
|
'nodes': [
|
||||||
{ "id": 9, "position": [180, 80], "type": "max/plantarium/output", "props": {} },
|
{ 'id': 9, 'position': [180, 80], 'type': 'max/plantarium/output', 'props': {} },
|
||||||
{ "id": 10, "position": [55, 80], "type": "max/plantarium/stem", "props": { "amount": 1, "length": 11, "thickness": 0.71 } },
|
{
|
||||||
{ "id": 11, "position": [80, 80], "type": "max/plantarium/noise", "props": { "strength": 35, "scale": 4.6, "fixBottom": 1, "directionalStrength": [1, 0.74, 0.083], "depth": 1 } },
|
'id': 10,
|
||||||
{ "id": 12, "position": [105, 80], "type": "max/plantarium/branch", "props": { "length": 3, "thickness": 0.6, "amount": 10, "rotation": 180, "offsetSingle": 0.34, "lowestBranch": 0.53, "highestBranch": 1, "depth": 1 } },
|
'position': [55, 80],
|
||||||
{ "id": 13, "position": [130, 80], "type": "max/plantarium/noise", "props": { "strength": 8, "scale": 7.7, "fixBottom": 1, "directionalStrength": [1, 0, 1], "depth": 1 } },
|
'type': 'max/plantarium/stem',
|
||||||
{ "id": 14, "position": [155, 80], "type": "max/plantarium/gravity", "props": { "strength": 0.11, "scale": 39, "fixBottom": 0, "directionalStrength": [1, 1, 1], "depth": 1, "curviness": 1 } }
|
'props': { 'amount': 1, 'length': 11, 'thickness': 0.71 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 11,
|
||||||
|
'position': [80, 80],
|
||||||
|
'type': 'max/plantarium/noise',
|
||||||
|
'props': {
|
||||||
|
'strength': 35,
|
||||||
|
'scale': 4.6,
|
||||||
|
'fixBottom': 1,
|
||||||
|
'directionalStrength': [1, 0.74, 0.083],
|
||||||
|
'depth': 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 12,
|
||||||
|
'position': [105, 80],
|
||||||
|
'type': 'max/plantarium/branch',
|
||||||
|
'props': {
|
||||||
|
'length': 3,
|
||||||
|
'thickness': 0.6,
|
||||||
|
'amount': 10,
|
||||||
|
'rotation': 180,
|
||||||
|
'offsetSingle': 0.34,
|
||||||
|
'lowestBranch': 0.53,
|
||||||
|
'highestBranch': 1,
|
||||||
|
'depth': 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 13,
|
||||||
|
'position': [130, 80],
|
||||||
|
'type': 'max/plantarium/noise',
|
||||||
|
'props': {
|
||||||
|
'strength': 8,
|
||||||
|
'scale': 7.7,
|
||||||
|
'fixBottom': 1,
|
||||||
|
'directionalStrength': [1, 0, 1],
|
||||||
|
'depth': 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 14,
|
||||||
|
'position': [155, 80],
|
||||||
|
'type': 'max/plantarium/gravity',
|
||||||
|
'props': {
|
||||||
|
'strength': 0.11,
|
||||||
|
'scale': 39,
|
||||||
|
'fixBottom': 0,
|
||||||
|
'directionalStrength': [1, 1, 1],
|
||||||
|
'depth': 1,
|
||||||
|
'curviness': 1
|
||||||
|
}
|
||||||
|
}
|
||||||
],
|
],
|
||||||
"edges": [[10, 0, 11, "plant"], [11, 0, 12, "plant"], [12, 0, 13, "plant"], [13, 0, 14, "plant"], [14, 0, 9, "input"]]
|
'edges': [
|
||||||
}
|
[10, 0, 11, 'plant'],
|
||||||
|
[11, 0, 12, 'plant'],
|
||||||
|
[12, 0, 13, 'plant'],
|
||||||
|
[13, 0, 14, 'plant'],
|
||||||
|
[14, 0, 9, 'input']
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|||||||
63
app/src/lib/graph-templates/simple.json
Normal file
63
app/src/lib/graph-templates/simple.json
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
{
|
||||||
|
"id": 0,
|
||||||
|
"settings": {
|
||||||
|
"resolution.circle": 54,
|
||||||
|
"resolution.curve": 20,
|
||||||
|
"randomSeed": true
|
||||||
|
},
|
||||||
|
"meta": {
|
||||||
|
"title": "New Project",
|
||||||
|
"lastModified": "2026-02-03T16:56:40.375Z"
|
||||||
|
},
|
||||||
|
"nodes": [
|
||||||
|
{
|
||||||
|
"id": 9,
|
||||||
|
"position": [
|
||||||
|
215,
|
||||||
|
85
|
||||||
|
],
|
||||||
|
"type": "max/plantarium/output",
|
||||||
|
"props": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 10,
|
||||||
|
"position": [
|
||||||
|
165,
|
||||||
|
72.5
|
||||||
|
],
|
||||||
|
"type": "max/plantarium/stem",
|
||||||
|
"props": {
|
||||||
|
"amount": 50,
|
||||||
|
"length": 4,
|
||||||
|
"thickness": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 11,
|
||||||
|
"position": [
|
||||||
|
190,
|
||||||
|
77.5
|
||||||
|
],
|
||||||
|
"type": "max/plantarium/noise",
|
||||||
|
"props": {
|
||||||
|
"plant": 0,
|
||||||
|
"scale": 0.5,
|
||||||
|
"strength": 5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"edges": [
|
||||||
|
[
|
||||||
|
10,
|
||||||
|
0,
|
||||||
|
11,
|
||||||
|
"plant"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
11,
|
||||||
|
0,
|
||||||
|
9,
|
||||||
|
"input"
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,28 +1,26 @@
|
|||||||
import type { Graph, Node } from "@nodes/types";
|
import type { Graph, SerializedNode } from '@nodarium/types';
|
||||||
|
|
||||||
export function tree(depth: number): Graph {
|
export function tree(depth: number): Graph {
|
||||||
|
const nodes: SerializedNode[] = [
|
||||||
const nodes: Node[] = [
|
|
||||||
{
|
{
|
||||||
id: 0,
|
id: 0,
|
||||||
type: "max/plantarium/output",
|
type: 'max/plantarium/output',
|
||||||
position: [0, 0]
|
position: [0, 0]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
type: "max/plantarium/math",
|
type: 'max/plantarium/math',
|
||||||
position: [-40, -10]
|
position: [-40, -10]
|
||||||
}
|
}
|
||||||
]
|
];
|
||||||
|
|
||||||
const edges: [number, number, number, string][] = [
|
const edges: [number, number, number, string][] = [
|
||||||
[1, 0, 0, "input"]
|
[1, 0, 0, 'input']
|
||||||
];
|
];
|
||||||
|
|
||||||
for (let d = 0; d < depth; d++) {
|
for (let d = 0; d < depth; d++) {
|
||||||
const amount = Math.pow(2, d);
|
const amount = Math.pow(2, d);
|
||||||
for (let i = 0; i < amount; i++) {
|
for (let i = 0; i < amount; i++) {
|
||||||
|
|
||||||
const id0 = amount * 2 + i * 2;
|
const id0 = amount * 2 + i * 2;
|
||||||
const id1 = amount * 2 + i * 2 + 1;
|
const id1 = amount * 2 + i * 2 + 1;
|
||||||
|
|
||||||
@@ -33,24 +31,22 @@ export function tree(depth: number): Graph {
|
|||||||
|
|
||||||
nodes.push({
|
nodes.push({
|
||||||
id: id0,
|
id: id0,
|
||||||
type: "max/plantarium/math",
|
type: 'max/plantarium/math',
|
||||||
position: [x, y],
|
position: [x, y]
|
||||||
});
|
});
|
||||||
edges.push([id0, 0, parent, "a"]);
|
edges.push([id0, 0, parent, 'a']);
|
||||||
nodes.push({
|
nodes.push({
|
||||||
id: id1,
|
id: id1,
|
||||||
type: "max/plantarium/math",
|
type: 'max/plantarium/math',
|
||||||
position: [x, y + 35],
|
position: [x, y + 35]
|
||||||
});
|
});
|
||||||
edges.push([id1, 0, parent, "b"]);
|
edges.push([id1, 0, parent, 'b']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: Math.floor(Math.random() * 100000),
|
id: Math.floor(Math.random() * 100000),
|
||||||
nodes,
|
nodes,
|
||||||
edges
|
edges
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,24 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { getContext } from "svelte";
|
import { getContext, type Snippet } from 'svelte';
|
||||||
import type { Writable } from "svelte/store";
|
|
||||||
|
|
||||||
let index = -1;
|
let index = $state(-1);
|
||||||
let wrapper: HTMLDivElement;
|
let wrapper: HTMLDivElement;
|
||||||
|
|
||||||
$: if (index === -1) {
|
const { children } = $props<{ children?: Snippet }>();
|
||||||
index = getContext<() => number>("registerCell")();
|
|
||||||
}
|
|
||||||
|
|
||||||
const sizes = getContext<Writable<string[]>>("sizes");
|
$effect(() => {
|
||||||
|
if (index === -1) {
|
||||||
|
index = getContext<() => number>('registerCell')();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const sizes = getContext<{ value: string[] }>('sizes');
|
||||||
|
|
||||||
let downSizes: string[] = [];
|
|
||||||
let downWidth = 0;
|
let downWidth = 0;
|
||||||
let mouseDown = false;
|
let mouseDown = false;
|
||||||
let startX = 0;
|
let startX = 0;
|
||||||
|
|
||||||
function handleMouseDown(event: MouseEvent) {
|
function handleMouseDown(event: MouseEvent) {
|
||||||
downSizes = [...$sizes];
|
|
||||||
mouseDown = true;
|
mouseDown = true;
|
||||||
startX = event.clientX;
|
startX = event.clientX;
|
||||||
downWidth = wrapper.getBoundingClientRect().width;
|
downWidth = wrapper.getBoundingClientRect().width;
|
||||||
@@ -26,15 +27,14 @@
|
|||||||
function handleMouseMove(event: MouseEvent) {
|
function handleMouseMove(event: MouseEvent) {
|
||||||
if (mouseDown) {
|
if (mouseDown) {
|
||||||
const width = downWidth + startX - event.clientX;
|
const width = downWidth + startX - event.clientX;
|
||||||
$sizes[index] = `${width}px`;
|
sizes.value[index] = `${width}px`;
|
||||||
$sizes = $sizes;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:window
|
<svelte:window
|
||||||
on:mouseup={() => (mouseDown = false)}
|
onmouseup={() => (mouseDown = false)}
|
||||||
on:mousemove={handleMouseMove}
|
onmousemove={handleMouseMove}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{#if index > 0}
|
{#if index > 0}
|
||||||
@@ -42,12 +42,13 @@
|
|||||||
class="seperator"
|
class="seperator"
|
||||||
role="button"
|
role="button"
|
||||||
tabindex="0"
|
tabindex="0"
|
||||||
on:mousedown={handleMouseDown}
|
onmousedown={handleMouseDown}
|
||||||
></div>
|
>
|
||||||
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
<div class="cell" bind:this={wrapper}>
|
<div class="cell" bind:this={wrapper}>
|
||||||
<slot />
|
{@render children?.()}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
@@ -61,7 +62,7 @@
|
|||||||
cursor: ew-resize;
|
cursor: ew-resize;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
width: 1px;
|
width: 1px;
|
||||||
background: var(--outline);
|
background: var(--color-outline);
|
||||||
}
|
}
|
||||||
.seperator::before {
|
.seperator::before {
|
||||||
content: "";
|
content: "";
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { setContext } from "svelte";
|
import { onMount, setContext, type Snippet } from 'svelte';
|
||||||
|
|
||||||
export let id = "grid-0";
|
const { children, id } = $props<{ children?: Snippet; id?: string }>();
|
||||||
|
|
||||||
setContext("grid-id", id);
|
onMount(() => {
|
||||||
|
setContext('grid-id', id);
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<slot {id} />
|
{@render children({ id })}
|
||||||
|
|||||||
@@ -1,27 +1,31 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { setContext, getContext } from "svelte";
|
import { localState } from '$lib/helpers/localState.svelte';
|
||||||
import localStore from "$lib/helpers/localStore";
|
import { getContext, setContext } from 'svelte';
|
||||||
|
|
||||||
const gridId = getContext<string>("grid-id") || "grid-0";
|
const gridId = getContext<string>('grid-id') || 'grid-0';
|
||||||
let sizes = localStore<string[]>(gridId, []);
|
let sizes = localState<string[]>(gridId, []);
|
||||||
|
|
||||||
|
const { children } = $props();
|
||||||
|
|
||||||
let registerIndex = 0;
|
let registerIndex = 0;
|
||||||
setContext("registerCell", function () {
|
setContext('registerCell', function() {
|
||||||
let index = registerIndex;
|
let index = registerIndex;
|
||||||
registerIndex++;
|
registerIndex++;
|
||||||
if (registerIndex > $sizes.length) {
|
if (registerIndex > sizes.value.length) {
|
||||||
$sizes = [...$sizes, "1fr"];
|
sizes.value = [...sizes.value, '1fr'];
|
||||||
}
|
}
|
||||||
return index;
|
return index;
|
||||||
});
|
});
|
||||||
|
|
||||||
setContext("sizes", sizes);
|
setContext('sizes', sizes);
|
||||||
|
|
||||||
$: cols = $sizes.map((size, i) => `${i > 0 ? "1px " : ""}` + size).join(" ");
|
const cols = $derived(
|
||||||
|
sizes.value.map((size, i) => `${i > 0 ? '1px ' : ''}` + size).join(' ')
|
||||||
|
);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="wrapper" style={`grid-template-columns: ${cols};`}>
|
<div class="wrapper" style={`grid-template-columns: ${cols};`}>
|
||||||
<slot />
|
{@render children()}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { withSubComponents } from "$lib/helpers";
|
import { withSubComponents } from '$lib/helpers';
|
||||||
import Grid from "./Grid.svelte";
|
import Cell from './Cell.svelte';
|
||||||
import Row from "./Row.svelte";
|
import Grid from './Grid.svelte';
|
||||||
import Cell from "./Cell.svelte";
|
import Row from './Row.svelte';
|
||||||
|
|
||||||
export default withSubComponents(Grid, { Row, Cell });
|
export default withSubComponents(Grid, { Row, Cell });
|
||||||
|
|||||||
145
app/src/lib/helpers.test.ts
Normal file
145
app/src/lib/helpers.test.ts
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
import { clone, debounce, humanizeDuration, humanizeNumber, lerp, snapToGrid } from '$lib/helpers';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
describe('helpers', () => {
|
||||||
|
describe('snapToGrid', () => {
|
||||||
|
it('should snap to nearest grid point', () => {
|
||||||
|
expect(snapToGrid(5, 10)).toBe(10);
|
||||||
|
expect(snapToGrid(15, 10)).toBe(20);
|
||||||
|
expect(snapToGrid(0, 10)).toBe(0);
|
||||||
|
expect(snapToGrid(-10, 10)).toBe(-10);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should snap exact midpoint values', () => {
|
||||||
|
expect(snapToGrid(5, 10)).toBe(10);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should use default grid size of 10', () => {
|
||||||
|
expect(snapToGrid(5)).toBe(10);
|
||||||
|
expect(snapToGrid(15)).toBe(20);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle values exactly on grid', () => {
|
||||||
|
expect(snapToGrid(10, 10)).toBe(10);
|
||||||
|
expect(snapToGrid(20, 10)).toBe(20);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('lerp', () => {
|
||||||
|
it('should linearly interpolate between two values', () => {
|
||||||
|
expect(lerp(0, 100, 0)).toBe(0);
|
||||||
|
expect(lerp(0, 100, 0.5)).toBe(50);
|
||||||
|
expect(lerp(0, 100, 1)).toBe(100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle negative values', () => {
|
||||||
|
expect(lerp(-50, 50, 0.5)).toBe(0);
|
||||||
|
expect(lerp(-100, 0, 0.5)).toBe(-50);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle t values outside 0-1 range', () => {
|
||||||
|
expect(lerp(0, 100, -0.5)).toBe(-50);
|
||||||
|
expect(lerp(0, 100, 1.5)).toBe(150);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('humanizeNumber', () => {
|
||||||
|
it('should return unchanged numbers below 1000', () => {
|
||||||
|
expect(humanizeNumber(0)).toBe('0');
|
||||||
|
expect(humanizeNumber(999)).toBe('999');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should add K suffix for thousands', () => {
|
||||||
|
expect(humanizeNumber(1000)).toBe('1K');
|
||||||
|
expect(humanizeNumber(1500)).toBe('1.5K');
|
||||||
|
expect(humanizeNumber(999999)).toBe('1000K');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should add M suffix for millions', () => {
|
||||||
|
expect(humanizeNumber(1000000)).toBe('1M');
|
||||||
|
expect(humanizeNumber(2500000)).toBe('2.5M');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should add B suffix for billions', () => {
|
||||||
|
expect(humanizeNumber(1000000000)).toBe('1B');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('humanizeDuration', () => {
|
||||||
|
it('should return ms for very short durations', () => {
|
||||||
|
expect(humanizeDuration(100)).toBe('100ms');
|
||||||
|
expect(humanizeDuration(999)).toBe('999ms');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should format seconds', () => {
|
||||||
|
expect(humanizeDuration(1000)).toBe('1s');
|
||||||
|
expect(humanizeDuration(1500)).toBe('1s500ms');
|
||||||
|
expect(humanizeDuration(59000)).toBe('59s');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should format minutes', () => {
|
||||||
|
expect(humanizeDuration(60000)).toBe('1m');
|
||||||
|
expect(humanizeDuration(90000)).toBe('1m 30s');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should format hours', () => {
|
||||||
|
expect(humanizeDuration(3600000)).toBe('1h');
|
||||||
|
expect(humanizeDuration(3661000)).toBe('1h 1m 1s');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should format days', () => {
|
||||||
|
expect(humanizeDuration(86400000)).toBe('1d');
|
||||||
|
expect(humanizeDuration(90061000)).toBe('1d 1h 1m 1s');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle zero', () => {
|
||||||
|
expect(humanizeDuration(0)).toBe('0ms');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('debounce', () => {
|
||||||
|
it('should return a function', () => {
|
||||||
|
const fn = debounce(() => {}, 100);
|
||||||
|
expect(typeof fn).toBe('function');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should only call once when invoked multiple times within delay', () => {
|
||||||
|
let callCount = 0;
|
||||||
|
const fn = debounce(() => {
|
||||||
|
callCount++;
|
||||||
|
}, 100);
|
||||||
|
fn();
|
||||||
|
const firstCall = callCount;
|
||||||
|
fn();
|
||||||
|
fn();
|
||||||
|
expect(callCount).toBe(firstCall);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('clone', () => {
|
||||||
|
it('should deep clone objects', () => {
|
||||||
|
const original = { a: 1, b: { c: 2 } };
|
||||||
|
const cloned = clone(original);
|
||||||
|
|
||||||
|
expect(cloned).toEqual(original);
|
||||||
|
expect(cloned).not.toBe(original);
|
||||||
|
expect(cloned.b).not.toBe(original.b);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle arrays', () => {
|
||||||
|
const original = [1, 2, [3, 4]];
|
||||||
|
const cloned = clone(original);
|
||||||
|
|
||||||
|
expect(cloned).toEqual(original);
|
||||||
|
expect(cloned).not.toBe(original);
|
||||||
|
expect(cloned[2]).not.toBe(original[2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle primitives', () => {
|
||||||
|
expect(clone(42)).toBe(42);
|
||||||
|
expect(clone('hello')).toBe('hello');
|
||||||
|
expect(clone(true)).toBe(true);
|
||||||
|
expect(clone(null)).toBe(null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,38 +1,39 @@
|
|||||||
import { derived, get, writable } from "svelte/store";
|
import { derived, get, writable } from 'svelte/store';
|
||||||
|
|
||||||
type Shortcut = {
|
export type ShortCut = {
|
||||||
key: string | string[],
|
key: string | string[];
|
||||||
shift?: boolean,
|
shift?: boolean;
|
||||||
ctrl?: boolean,
|
ctrl?: boolean;
|
||||||
alt?: boolean,
|
alt?: boolean;
|
||||||
preventDefault?: boolean,
|
preventDefault?: boolean;
|
||||||
description?: string,
|
description?: string;
|
||||||
callback: (event: KeyboardEvent) => void
|
callback: (event: KeyboardEvent) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
function getShortcutId(shortcut: ShortCut) {
|
||||||
|
return `${shortcut.key}${shortcut.shift ? '+shift' : ''}${shortcut.ctrl ? '+ctrl' : ''}${
|
||||||
|
shortcut.alt ? '+alt' : ''
|
||||||
|
}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getShortcutId(shortcut: Shortcut) {
|
export function createKeyMap(keys: ShortCut[]) {
|
||||||
return `${shortcut.key}${shortcut.shift ? "+shift" : ""}${shortcut.ctrl ? "+ctrl" : ""}${shortcut.alt ? "+alt" : ""}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createKeyMap(keys: Shortcut[]) {
|
|
||||||
|
|
||||||
const store = writable(new Map(keys.map(k => [getShortcutId(k), k])));
|
const store = writable(new Map(keys.map(k => [getShortcutId(k), k])));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
handleKeyboardEvent: (event: KeyboardEvent) => {
|
handleKeyboardEvent: (event: KeyboardEvent) => {
|
||||||
const activeElement = document.activeElement as HTMLElement;
|
const activeElement = document.activeElement as HTMLElement;
|
||||||
if (activeElement?.tagName === "INPUT" || activeElement?.tagName === "TEXTAREA") return;
|
if (activeElement?.tagName === 'INPUT' || activeElement?.tagName === 'TEXTAREA') return;
|
||||||
const key = [...get(store).values()].find(k => {
|
const key = [...get(store).values()].find(k => {
|
||||||
if (Array.isArray(k.key) ? !k.key.includes(event.key) : k.key !== event.key) return false;
|
if (Array.isArray(k.key) ? !k.key.includes(event.key) : k.key !== event.key) return false;
|
||||||
if ("shift" in k && k.shift !== event.shiftKey) return false;
|
if ('shift' in k && k.shift !== event.shiftKey) return false;
|
||||||
if ("ctrl" in k && k.ctrl !== event.ctrlKey) return false;
|
if ('ctrl' in k && k.ctrl !== event.ctrlKey) return false;
|
||||||
if ("alt" in k && k.alt !== event.altKey) return false;
|
if ('alt' in k && k.alt !== event.altKey) return false;
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
if (key && key.preventDefault) event.preventDefault();
|
if (key && key.preventDefault) event.preventDefault();
|
||||||
key?.callback(event);
|
key?.callback(event);
|
||||||
},
|
},
|
||||||
addShortcut: (shortcut: Shortcut) => {
|
addShortcut: (shortcut: ShortCut) => {
|
||||||
if (Array.isArray(shortcut.key)) {
|
if (Array.isArray(shortcut.key)) {
|
||||||
for (const k of shortcut.key) {
|
for (const k of shortcut.key) {
|
||||||
store.update(shortcuts => {
|
store.update(shortcuts => {
|
||||||
@@ -52,6 +53,5 @@ export function createKeyMap(keys: Shortcut[]) {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
keys: derived(store, $store => Array.from($store.values()))
|
keys: derived(store, $store => Array.from($store.values()))
|
||||||
}
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
72
app/src/lib/helpers/deepMerge.test.ts
Normal file
72
app/src/lib/helpers/deepMerge.test.ts
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
import { isObject, mergeDeep } from '$lib/helpers/deepMerge';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
describe('deepMerge', () => {
|
||||||
|
describe('isObject', () => {
|
||||||
|
it('should return true for plain objects', () => {
|
||||||
|
expect(isObject({})).toBe(true);
|
||||||
|
expect(isObject({ a: 1 })).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return false for non-objects', () => {
|
||||||
|
expect(isObject([])).toBe(false);
|
||||||
|
expect(isObject('string')).toBe(false);
|
||||||
|
expect(isObject(42)).toBe(false);
|
||||||
|
expect(isObject(undefined)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('mergeDeep', () => {
|
||||||
|
it('should merge two flat objects', () => {
|
||||||
|
const target = { a: 1, b: 2 };
|
||||||
|
const source = { b: 3, c: 4 };
|
||||||
|
const result = mergeDeep(target, source);
|
||||||
|
|
||||||
|
expect(result).toEqual({ a: 1, b: 3, c: 4 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should deeply merge nested objects', () => {
|
||||||
|
const target = { a: { x: 1 }, b: { y: 2 } };
|
||||||
|
const source = { a: { y: 2 }, c: { z: 3 } };
|
||||||
|
const result = mergeDeep(target, source);
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
a: { x: 1, y: 2 },
|
||||||
|
b: { y: 2 },
|
||||||
|
c: { z: 3 }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle multiple sources', () => {
|
||||||
|
const target = { a: 1 };
|
||||||
|
const source1 = { b: 2 };
|
||||||
|
const source2 = { c: 3 };
|
||||||
|
const result = mergeDeep(target, source1, source2);
|
||||||
|
|
||||||
|
expect(result).toEqual({ a: 1, b: 2, c: 3 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return target if no sources provided', () => {
|
||||||
|
const target = { a: 1 };
|
||||||
|
const result = mergeDeep(target);
|
||||||
|
|
||||||
|
expect(result).toBe(target);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should overwrite non-object values', () => {
|
||||||
|
const target = { a: { b: 1 } };
|
||||||
|
const source = { a: 'string' };
|
||||||
|
const result = mergeDeep(target, source);
|
||||||
|
|
||||||
|
expect(result.a).toBe('string');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle arrays by replacing', () => {
|
||||||
|
const target = { a: [1, 2] };
|
||||||
|
const source = { a: [3, 4] };
|
||||||
|
const result = mergeDeep(target, source);
|
||||||
|
|
||||||
|
expect(result.a).toEqual([3, 4]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -18,7 +18,7 @@ export function animate(duration: number, callback: (progress: number) => void |
|
|||||||
} else {
|
} else {
|
||||||
callback(1);
|
callback(1);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
requestAnimationFrame(loop);
|
requestAnimationFrame(loop);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,10 +30,11 @@ export function createNodePath({
|
|||||||
cornerBottom = 0,
|
cornerBottom = 0,
|
||||||
leftBump = false,
|
leftBump = false,
|
||||||
rightBump = false,
|
rightBump = false,
|
||||||
aspectRatio = 1,
|
aspectRatio = 1
|
||||||
} = {}) {
|
} = {}) {
|
||||||
return `M0,${cornerTop}
|
return `M0,${cornerTop}
|
||||||
${cornerTop
|
${
|
||||||
|
cornerTop
|
||||||
? ` V${cornerTop}
|
? ` V${cornerTop}
|
||||||
Q0,0 ${cornerTop * aspectRatio},0
|
Q0,0 ${cornerTop * aspectRatio},0
|
||||||
H${100 - cornerTop * aspectRatio}
|
H${100 - cornerTop * aspectRatio}
|
||||||
@@ -42,40 +43,45 @@ export function createNodePath({
|
|||||||
: ` V0
|
: ` V0
|
||||||
H100
|
H100
|
||||||
`
|
`
|
||||||
}
|
}
|
||||||
V${y - height / 2}
|
V${y - height / 2}
|
||||||
${rightBump
|
${
|
||||||
|
rightBump
|
||||||
? ` C${100 - depth},${y - height / 2} ${100 - depth},${y + height / 2} 100,${y + height / 2}`
|
? ` C${100 - depth},${y - height / 2} ${100 - depth},${y + height / 2} 100,${y + height / 2}`
|
||||||
: ` H100`
|
: ` H100`
|
||||||
}
|
}
|
||||||
${cornerBottom
|
${
|
||||||
|
cornerBottom
|
||||||
? ` V${100 - cornerBottom}
|
? ` V${100 - cornerBottom}
|
||||||
Q100,100 ${100 - cornerBottom * aspectRatio},100
|
Q100,100 ${100 - cornerBottom * aspectRatio},100
|
||||||
H${cornerBottom * aspectRatio}
|
H${cornerBottom * aspectRatio}
|
||||||
Q0,100 0,${100 - cornerBottom}
|
Q0,100 0,${100 - cornerBottom}
|
||||||
`
|
`
|
||||||
: `${leftBump ? `V100 H0` : `V100`}`
|
: `${leftBump ? `V100 H0` : `V100`}`
|
||||||
}
|
}
|
||||||
${leftBump
|
${
|
||||||
? ` V${y + height / 2} C${depth},${y + height / 2} ${depth},${y - height / 2} 0,${y - height / 2}`
|
leftBump
|
||||||
|
? ` V${y + height / 2} C${depth},${y + height / 2} ${depth},${y - height / 2} 0,${
|
||||||
|
y - height / 2
|
||||||
|
}`
|
||||||
: ` H0`
|
: ` H0`
|
||||||
}
|
}
|
||||||
Z`.replace(/\s+/g, " ");
|
Z`.replace(/\s+/g, ' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
export const debounce = (fn: Function, ms = 300) => {
|
export const debounce = (fn: () => void, ms = 300) => {
|
||||||
let timeoutId: ReturnType<typeof setTimeout>;
|
let timeoutId: ReturnType<typeof setTimeout>;
|
||||||
return function (this: any, ...args: any[]) {
|
return function(this: unknown, ...args: unknown[]) {
|
||||||
clearTimeout(timeoutId);
|
clearTimeout(timeoutId);
|
||||||
timeoutId = setTimeout(() => fn.apply(this, args), ms);
|
timeoutId = setTimeout(() => fn.apply(this, args as []), ms);
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export const clone: <T>(v: T) => T = "structedClone" in globalThis ? globalThis.structuredClone : (obj) => JSON.parse(JSON.stringify(obj));
|
export const clone: <T>(v: T) => T = 'structedClone' in globalThis
|
||||||
|
? globalThis.structuredClone
|
||||||
|
: (obj) => JSON.parse(JSON.stringify(obj));
|
||||||
|
|
||||||
|
export function withSubComponents<A, B extends Record<string, unknown>>(
|
||||||
|
|
||||||
export function withSubComponents<A, B extends Record<string, any>>(
|
|
||||||
component: A,
|
component: A,
|
||||||
subcomponents: B
|
subcomponents: B
|
||||||
): A & B {
|
): A & B {
|
||||||
@@ -87,7 +93,7 @@ export function withSubComponents<A, B extends Record<string, any>>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function humanizeNumber(number: number): string {
|
export function humanizeNumber(number: number): string {
|
||||||
const suffixes = ["", "K", "M", "B", "T"];
|
const suffixes = ['', 'K', 'M', 'B', 'T'];
|
||||||
if (number < 1000) {
|
if (number < 1000) {
|
||||||
return number.toString();
|
return number.toString();
|
||||||
}
|
}
|
||||||
@@ -104,11 +110,15 @@ export function humanizeDuration(durationInMilliseconds: number) {
|
|||||||
const millisecondsPerHour = 3600000;
|
const millisecondsPerHour = 3600000;
|
||||||
const millisecondsPerDay = 86400000;
|
const millisecondsPerDay = 86400000;
|
||||||
|
|
||||||
let days = Math.floor(durationInMilliseconds / millisecondsPerDay);
|
const days = Math.floor(durationInMilliseconds / millisecondsPerDay);
|
||||||
let hours = Math.floor((durationInMilliseconds % millisecondsPerDay) / millisecondsPerHour);
|
const hours = Math.floor((durationInMilliseconds % millisecondsPerDay) / millisecondsPerHour);
|
||||||
let minutes = Math.floor((durationInMilliseconds % millisecondsPerHour) / millisecondsPerMinute);
|
const minutes = Math.floor(
|
||||||
let seconds = Math.floor((durationInMilliseconds % millisecondsPerMinute) / millisecondsPerSecond);
|
(durationInMilliseconds % millisecondsPerHour) / millisecondsPerMinute
|
||||||
let millis = durationInMilliseconds % millisecondsPerSecond;
|
);
|
||||||
|
const seconds = Math.floor(
|
||||||
|
(durationInMilliseconds % millisecondsPerMinute) / millisecondsPerSecond
|
||||||
|
);
|
||||||
|
const millis = durationInMilliseconds % millisecondsPerSecond;
|
||||||
|
|
||||||
let durationString = '';
|
let durationString = '';
|
||||||
|
|
||||||
@@ -126,37 +136,15 @@ export function humanizeDuration(durationInMilliseconds: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (millis > 0 || durationString === '') {
|
if (millis > 0 || durationString === '') {
|
||||||
durationString += millis + 'ms';
|
durationString += Math.floor(millis) + 'ms';
|
||||||
}
|
}
|
||||||
|
|
||||||
return durationString.trim();
|
return durationString.trim();
|
||||||
}
|
}
|
||||||
// export function debounceAsyncFunction<T extends any[], R>(
|
|
||||||
// func: (...args: T) => Promise<R>
|
export function debounceAsyncFunction<T extends (...args: never[]) => Promise<unknown>>(
|
||||||
// ): (...args: T) => Promise<R> {
|
asyncFn: T
|
||||||
// let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
): T {
|
||||||
// let lastPromise: Promise<R> | null = null;
|
|
||||||
// let lastReject: ((reason?: any) => void) | null = null;
|
|
||||||
//
|
|
||||||
// return (...args: T): Promise<R> => {
|
|
||||||
// if (timeoutId) {
|
|
||||||
// clearTimeout(timeoutId);
|
|
||||||
// if (lastReject) {
|
|
||||||
// lastReject(new Error("Debounced: Previous call was canceled."));
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// return new Promise<R>((resolve, reject) => {
|
|
||||||
// lastReject = reject;
|
|
||||||
// timeoutId = setTimeout(() => {
|
|
||||||
// timeoutId = null;
|
|
||||||
// lastReject = null;
|
|
||||||
// lastPromise = func(...args).then(resolve, reject);
|
|
||||||
// }, 300); // Default debounce time is 300ms; you can make this configurable.
|
|
||||||
// });
|
|
||||||
// };
|
|
||||||
// }
|
|
||||||
export function debounceAsyncFunction<T extends (...args: any[]) => Promise<any>>(asyncFn: T): T {
|
|
||||||
let isRunning = false;
|
let isRunning = false;
|
||||||
let latestArgs: Parameters<T> | null = null;
|
let latestArgs: Parameters<T> | null = null;
|
||||||
let resolveNext: (() => void) | null = null;
|
let resolveNext: (() => void) | null = null;
|
||||||
@@ -177,7 +165,7 @@ export function debounceAsyncFunction<T extends (...args: any[]) => Promise<any>
|
|||||||
try {
|
try {
|
||||||
// Execute with the latest arguments
|
// Execute with the latest arguments
|
||||||
const result = await asyncFn(...latestArgs!);
|
const result = await asyncFn(...latestArgs!);
|
||||||
return result;
|
return result as ReturnType<T>;
|
||||||
} finally {
|
} finally {
|
||||||
// Allow the next execution
|
// Allow the next execution
|
||||||
isRunning = false;
|
isRunning = false;
|
||||||
@@ -190,48 +178,18 @@ export function debounceAsyncFunction<T extends (...args: any[]) => Promise<any>
|
|||||||
}) as T;
|
}) as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
// export function debounceAsyncFunction<T extends any[], R>(func: (...args: T) => Promise<R>): (...args: T) => Promise<R> {
|
export function withArgsChangeOnly<T extends unknown[], R>(
|
||||||
// let currentPromise: Promise<R> | null = null;
|
func: (...args: T) => R
|
||||||
// let nextArgs: T | null = null;
|
): (...args: T) => R {
|
||||||
// let resolveNext: ((result: R) => void) | null = null;
|
|
||||||
//
|
|
||||||
// const debouncedFunction = async (...args: T): Promise<R> => {
|
|
||||||
// if (currentPromise) {
|
|
||||||
// // Store the latest arguments and create a new promise to resolve them later
|
|
||||||
// nextArgs = args;
|
|
||||||
// return new Promise<R>((resolve) => {
|
|
||||||
// resolveNext = resolve;
|
|
||||||
// });
|
|
||||||
// } else {
|
|
||||||
// // Execute the function immediately
|
|
||||||
// try {
|
|
||||||
// currentPromise = func(...args);
|
|
||||||
// const result = await currentPromise;
|
|
||||||
// return result;
|
|
||||||
// } finally {
|
|
||||||
// currentPromise = null;
|
|
||||||
// // If there are stored arguments, call the function again with the latest arguments
|
|
||||||
// if (nextArgs) {
|
|
||||||
// const argsToUse = nextArgs;
|
|
||||||
// const resolver = resolveNext;
|
|
||||||
// nextArgs = null;
|
|
||||||
// resolveNext = null;
|
|
||||||
// resolver!(await debouncedFunction(...argsToUse));
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// };
|
|
||||||
//
|
|
||||||
// return debouncedFunction;
|
|
||||||
// }
|
|
||||||
|
|
||||||
export function withArgsChangeOnly<T extends any[], R>(func: (...args: T) => R): (...args: T) => R {
|
|
||||||
let lastArgs: T | undefined = undefined;
|
let lastArgs: T | undefined = undefined;
|
||||||
let lastResult: R;
|
let lastResult: R;
|
||||||
|
|
||||||
return (...args: T): R => {
|
return (...args: T): R => {
|
||||||
// Check if arguments are the same as last call
|
// Check if arguments are the same as last call
|
||||||
if (lastArgs && args.length === lastArgs.length && args.every((val, index) => val === lastArgs?.[index])) {
|
if (
|
||||||
|
lastArgs && args.length === lastArgs.length
|
||||||
|
&& args.every((val, index) => val === lastArgs?.[index])
|
||||||
|
) {
|
||||||
return lastResult; // Return cached result if arguments haven't changed
|
return lastResult; // Return cached result if arguments haven't changed
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,4 +199,3 @@ export function withArgsChangeOnly<T extends any[], R>(func: (...args: T) => R):
|
|||||||
return lastResult; // Return new result
|
return lastResult; // Return new result
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,34 @@
|
|||||||
export function localState<T>(key: string, defaultValue: T): T {
|
import { browser } from '$app/environment';
|
||||||
const stored = localStorage.getItem(key)
|
|
||||||
const state = $state(stored ? JSON.parse(stored) : defaultValue)
|
export class LocalStore<T> {
|
||||||
$effect.root(() => {
|
value = $state<T>() as T;
|
||||||
$effect(() => {
|
key = '';
|
||||||
const value = $state.snapshot(state);
|
|
||||||
localStorage.setItem(key, JSON.stringify(value));
|
constructor(key: string, value: T) {
|
||||||
|
this.key = key;
|
||||||
|
this.value = value;
|
||||||
|
|
||||||
|
if (browser) {
|
||||||
|
const item = localStorage.getItem(key);
|
||||||
|
if (item) this.value = this.deserialize(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
$effect.root(() => {
|
||||||
|
$effect(() => {
|
||||||
|
localStorage.setItem(this.key, this.serialize(this.value));
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
}
|
||||||
return state;
|
|
||||||
|
serialize(value: T): string {
|
||||||
|
return JSON.stringify(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
deserialize(item: string): T {
|
||||||
|
return JSON.parse(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function localState<T>(key: string, value: T) {
|
||||||
|
return new LocalStore(key, value);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
import { writable, type Writable } from "svelte/store";
|
import { type Writable, writable } from 'svelte/store';
|
||||||
|
|
||||||
function isStore(v: unknown): v is Writable<unknown> {
|
function isStore(v: unknown): v is Writable<unknown> {
|
||||||
return v !== null && typeof v === "object" && "subscribe" in v && "set" in v;
|
return v !== null && typeof v === 'object' && 'subscribe' in v && 'set' in v;
|
||||||
}
|
}
|
||||||
|
|
||||||
const storeIds: Map<string, ReturnType<typeof createLocalStore>> = new Map();
|
const storeIds: Map<string, ReturnType<typeof createLocalStore>> = new Map();
|
||||||
|
|
||||||
const HAS_LOCALSTORAGE = "localStorage" in globalThis;
|
const HAS_LOCALSTORAGE = 'localStorage' in globalThis;
|
||||||
|
|
||||||
function createLocalStore<T>(key: string, initialValue: T | Writable<T>) {
|
function createLocalStore<T>(key: string, initialValue: T | Writable<T>) {
|
||||||
|
|
||||||
let store: Writable<T>;
|
let store: Writable<T>;
|
||||||
|
|
||||||
if (HAS_LOCALSTORAGE) {
|
if (HAS_LOCALSTORAGE) {
|
||||||
@@ -36,18 +35,15 @@ function createLocalStore<T>(key: string, initialValue: T | Writable<T>) {
|
|||||||
subscribe: store.subscribe,
|
subscribe: store.subscribe,
|
||||||
set: store.set,
|
set: store.set,
|
||||||
update: store.update
|
update: store.update
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export default function localStore<T>(key: string, initialValue: T | Writable<T>): Writable<T> {
|
export default function localStore<T>(key: string, initialValue: T | Writable<T>): Writable<T> {
|
||||||
|
|
||||||
if (storeIds.has(key)) return storeIds.get(key) as Writable<T>;
|
if (storeIds.has(key)) return storeIds.get(key) as Writable<T>;
|
||||||
|
|
||||||
const store = createLocalStore(key, initialValue)
|
const store = createLocalStore(key, initialValue);
|
||||||
|
|
||||||
storeIds.set(key, store);
|
storeIds.set(key, store);
|
||||||
|
|
||||||
return store
|
return store;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,19 @@
|
|||||||
export default <R, A extends any[]>(
|
export default <T extends unknown[]>(
|
||||||
fn: (...args: A) => R,
|
callback: (...args: T) => void,
|
||||||
delay: number
|
delay: number
|
||||||
): ((...args: A) => R) => {
|
) => {
|
||||||
let wait = false;
|
let isWaiting = false;
|
||||||
|
|
||||||
return (...args: A) => {
|
return (...args: T) => {
|
||||||
if (wait) return undefined;
|
if (isWaiting) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const val = fn(...args);
|
callback(...args);
|
||||||
|
isWaiting = true;
|
||||||
wait = true;
|
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
wait = false;
|
isWaiting = false;
|
||||||
}, delay);
|
}, delay);
|
||||||
|
};
|
||||||
return val;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||||
<rect x="17" y="8" width="5" height="7" rx="1" stroke="currentColor" stroke-width="2"/>
|
<rect x="17" y="8" width="5" height="7" rx="1" stroke="currentColor" stroke-width="2" />
|
||||||
<rect x="2" y="3" width="5" height="7" rx="1" stroke="currentColor" stroke-width="2"/>
|
<rect x="2" y="3" width="5" height="7" rx="1" stroke="currentColor" stroke-width="2" />
|
||||||
<rect x="2" y="14" width="5" height="7" rx="1" stroke="currentColor" stroke-width="2"/>
|
<rect x="2" y="14" width="5" height="7" rx="1" stroke="currentColor" stroke-width="2" />
|
||||||
<path d="M16 10.5C9.33333 10.5 14.8889 6 8.22222 6H6M16 12.5C8.77778 12.5 14.8889 17 8.22222 17H6" stroke="currentColor" stroke-width="2"/>
|
<path
|
||||||
|
d="M16 10.5C9.33333 10.5 14.8889 6 8.22222 6H6M16 12.5C8.77778 12.5 14.8889 17 8.22222 17H6"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 519 B After Width: | Height: | Size: 509 B |
@@ -1,35 +1,34 @@
|
|||||||
import { createWasmWrapper } from "@nodes/utils"
|
import { createWasmWrapper } from '@nodarium/utils';
|
||||||
import fs from "fs/promises"
|
import fs from 'fs/promises';
|
||||||
import path from "path"
|
import path from 'path';
|
||||||
|
|
||||||
export async function getWasm(id: `${string}/${string}/${string}`) {
|
export async function getWasm(id: `${string}/${string}/${string}`) {
|
||||||
const filePath = path.resolve(`../nodes/${id}/pkg/index_bg.wasm`);
|
const filePath = path.resolve(`./static/nodes/${id}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await fs.access(filePath);
|
await fs.access(filePath);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return null
|
console.error(`Failed to read node: ${id}`, e);
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const file = await fs.readFile(filePath);
|
const file = await fs.readFile(filePath);
|
||||||
|
|
||||||
return new Uint8Array(file);
|
return new Uint8Array(file);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getNodeWasm(id: `${string}/${string}/${string}`) {
|
export async function getNodeWasm(id: `${string}/${string}/${string}`) {
|
||||||
|
|
||||||
const wasmBytes = await getWasm(id);
|
const wasmBytes = await getWasm(id);
|
||||||
if (!wasmBytes) return null;
|
if (!wasmBytes) return null;
|
||||||
|
|
||||||
const wrapper = createWasmWrapper(wasmBytes);
|
try {
|
||||||
|
return createWasmWrapper(wasmBytes.buffer);
|
||||||
return wrapper;
|
} catch (error) {
|
||||||
|
console.error(`Failed to create node wrapper for node: ${id}`, error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export async function getNode(id: `${string}/${string}/${string}`) {
|
export async function getNode(id: `${string}/${string}/${string}`) {
|
||||||
|
|
||||||
const wrapper = await getNodeWasm(id);
|
const wrapper = await getNodeWasm(id);
|
||||||
|
|
||||||
const definition = wrapper?.get_definition?.();
|
const definition = wrapper?.get_definition?.();
|
||||||
@@ -37,37 +36,38 @@ export async function getNode(id: `${string}/${string}/${string}`) {
|
|||||||
if (!definition) return null;
|
if (!definition) return null;
|
||||||
|
|
||||||
return definition;
|
return definition;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getCollectionNodes(userId: `${string}/${string}`) {
|
export async function getCollectionNodes(userId: `${string}/${string}`) {
|
||||||
const nodes = await fs.readdir(path.resolve(`../nodes/${userId}`));
|
const nodes = await fs.readdir(path.resolve(`./static/nodes/${userId}`));
|
||||||
return nodes
|
return nodes
|
||||||
.filter(n => n !== "pkg" && n !== ".template")
|
.filter((n) => n !== 'pkg' && n !== '.template')
|
||||||
.map(n => {
|
.map((n) => {
|
||||||
return {
|
return {
|
||||||
id: `${userId}/${n}`,
|
id: `${userId}/${n}`
|
||||||
}
|
};
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getCollection(userId: `${string}/${string}`) {
|
export async function getCollection(userId: `${string}/${string}`) {
|
||||||
const nodes = await getCollectionNodes(userId);
|
const nodes = await getCollectionNodes(userId);
|
||||||
return {
|
return {
|
||||||
id: userId,
|
id: userId,
|
||||||
nodes,
|
nodes
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getUserCollections(userId: string) {
|
export async function getUserCollections(userId: string) {
|
||||||
const collections = await fs.readdir(path.resolve(`../nodes/${userId}`));
|
const collections = await fs.readdir(path.resolve(`./static/nodes/${userId}`));
|
||||||
return Promise.all(collections.map(async n => {
|
return Promise.all(
|
||||||
const nodes = await getCollectionNodes(`${userId}/${n}`);
|
collections.map(async (n) => {
|
||||||
return {
|
const nodes = await getCollectionNodes(`${userId}/${n}`);
|
||||||
id: `${userId}/${n}`,
|
return {
|
||||||
nodes,
|
id: `${userId}/${n}`,
|
||||||
}
|
nodes
|
||||||
}));
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getUser(userId: string) {
|
export async function getUser(userId: string) {
|
||||||
@@ -75,17 +75,19 @@ export async function getUser(userId: string) {
|
|||||||
return {
|
return {
|
||||||
id: userId,
|
id: userId,
|
||||||
collections
|
collections
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getUsers() {
|
export async function getUsers() {
|
||||||
const nodes = await fs.readdir(path.resolve("../nodes"));
|
const nodes = await fs.readdir(path.resolve('./static/nodes'));
|
||||||
const users = await Promise.all(nodes.map(async n => {
|
const users = await Promise.all(
|
||||||
const collections = await getUserCollections(n);
|
nodes.map(async (n) => {
|
||||||
return {
|
const collections = await getUserCollections(n);
|
||||||
id: n,
|
return {
|
||||||
collections
|
id: n,
|
||||||
}
|
collections
|
||||||
}))
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
return users;
|
return users;
|
||||||
}
|
}
|
||||||
|
|||||||
2
app/src/lib/node-registry/index.ts
Normal file
2
app/src/lib/node-registry/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export * from './node-registry-cache';
|
||||||
|
export * from './node-registry-client';
|
||||||
56
app/src/lib/node-registry/node-registry-cache.ts
Normal file
56
app/src/lib/node-registry/node-registry-cache.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import type { AsyncCache } from '@nodarium/types';
|
||||||
|
import { type IDBPDatabase, openDB } from 'idb';
|
||||||
|
|
||||||
|
export class IndexDBCache implements AsyncCache<unknown> {
|
||||||
|
size: number = 100;
|
||||||
|
|
||||||
|
db: Promise<IDBPDatabase<unknown>>;
|
||||||
|
private _cache = new Map<string, unknown>();
|
||||||
|
|
||||||
|
constructor(id: string) {
|
||||||
|
this.db = openDB<unknown>('cache/' + id, 1, {
|
||||||
|
upgrade(db) {
|
||||||
|
db.createObjectStore('keyval');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async get<T>(key: string): Promise<T> {
|
||||||
|
let res = this._cache.get(key);
|
||||||
|
if (!res) {
|
||||||
|
res = await (await this.db).get('keyval', key);
|
||||||
|
}
|
||||||
|
if (res) {
|
||||||
|
this._cache.set(key, res);
|
||||||
|
}
|
||||||
|
return res as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getArrayBuffer(key: string) {
|
||||||
|
const res = await this.get(key);
|
||||||
|
if (!res) return;
|
||||||
|
if (res instanceof ArrayBuffer) {
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getString(key: string) {
|
||||||
|
const res = await this.get(key);
|
||||||
|
if (!res) return;
|
||||||
|
if (typeof res === 'string') {
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
async set(key: string, value: unknown) {
|
||||||
|
this._cache.set(key, value);
|
||||||
|
const db = await this.db;
|
||||||
|
await db.put('keyval', value, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
clear() {
|
||||||
|
this.db.then(db => db.clear('keyval'));
|
||||||
|
}
|
||||||
|
}
|
||||||
168
app/src/lib/node-registry/node-registry-client.ts
Normal file
168
app/src/lib/node-registry/node-registry-client.ts
Normal file
@@ -0,0 +1,168 @@
|
|||||||
|
import {
|
||||||
|
type AsyncCache,
|
||||||
|
type NodeDefinition,
|
||||||
|
NodeDefinitionSchema,
|
||||||
|
type NodeRegistry
|
||||||
|
} from '@nodarium/types';
|
||||||
|
import { createLogger, createWasmWrapper } from '@nodarium/utils';
|
||||||
|
|
||||||
|
const log = createLogger('node-registry');
|
||||||
|
log.mute();
|
||||||
|
|
||||||
|
export class RemoteNodeRegistry implements NodeRegistry {
|
||||||
|
status: 'loading' | 'ready' | 'error' = 'loading';
|
||||||
|
private nodes: Map<string, NodeDefinition> = new Map();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private url: string,
|
||||||
|
public cache?: AsyncCache<ArrayBuffer | string>
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async fetchJson(url: string, skipCache = false) {
|
||||||
|
const finalUrl = `${this.url}/${url}`;
|
||||||
|
|
||||||
|
if (!skipCache && this.cache) {
|
||||||
|
const cachedValue = await this.cache?.get<string>(finalUrl);
|
||||||
|
if (cachedValue) {
|
||||||
|
// fetch again in the background, maybe implement that only refetch after a certain time
|
||||||
|
this.fetchJson(url, true);
|
||||||
|
return JSON.parse(cachedValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(finalUrl);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
log.error(`Failed to load ${url}`, { response, url, host: this.url });
|
||||||
|
throw new Error(`Failed to load ${url}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
this.cache?.set(finalUrl, JSON.stringify(result));
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fetchArrayBuffer(url: string, skipCache = false) {
|
||||||
|
const finalUrl = `${this.url}/${url}`;
|
||||||
|
|
||||||
|
if (!skipCache && this.cache) {
|
||||||
|
const cachedNode = await this.cache?.get<ArrayBuffer>(finalUrl);
|
||||||
|
if (cachedNode) {
|
||||||
|
// fetch again in the background, maybe implement that only refetch after a certain time
|
||||||
|
this.fetchArrayBuffer(url, true);
|
||||||
|
return cachedNode;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(finalUrl);
|
||||||
|
if (!response.ok) {
|
||||||
|
log.error(`Failed to load ${url}`, { response, url, host: this.url });
|
||||||
|
throw new Error(`Failed to load ${url}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const buffer = await response.arrayBuffer();
|
||||||
|
this.cache?.set(finalUrl, buffer);
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fetchUsers() {
|
||||||
|
return this.fetchJson(`nodes/users.json`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async fetchUser(userId: `${string}`) {
|
||||||
|
return this.fetchJson(`user/${userId}.json`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async fetchCollection(userCollectionId: `${string}/${string}`) {
|
||||||
|
const col = await this.fetchJson(`nodes/${userCollectionId}.json`);
|
||||||
|
return col;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fetchNodeDefinition(nodeId: `${string}/${string}/${string}`) {
|
||||||
|
return this.fetchJson(`nodes/${nodeId}.json`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchNodeWasm(nodeId: `${string}/${string}/${string}`) {
|
||||||
|
const node = await this.fetchArrayBuffer(`nodes/${nodeId}.wasm`);
|
||||||
|
if (!node) {
|
||||||
|
throw new Error(`Failed to load node wasm ${nodeId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
async load(nodeIds: `${string}/${string}/${string}`[]) {
|
||||||
|
const a = performance.now();
|
||||||
|
|
||||||
|
const nodes = (await Promise.all(
|
||||||
|
[...new Set(nodeIds).values()].map(async (id) => {
|
||||||
|
if (this.nodes.has(id)) {
|
||||||
|
return this.nodes.get(id)!;
|
||||||
|
}
|
||||||
|
|
||||||
|
const wasmBuffer = await this.fetchNodeWasm(id);
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await this.register(id, wasmBuffer);
|
||||||
|
} catch (e) {
|
||||||
|
console.log('Failed to register: ', id);
|
||||||
|
console.error(e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)).filter(Boolean) as NodeDefinition[];
|
||||||
|
|
||||||
|
const duration = performance.now() - a;
|
||||||
|
|
||||||
|
log.group('loaded nodes in', duration, 'ms');
|
||||||
|
log.info(nodeIds);
|
||||||
|
log.info(nodes);
|
||||||
|
log.groupEnd();
|
||||||
|
this.status = 'ready';
|
||||||
|
|
||||||
|
return nodes;
|
||||||
|
}
|
||||||
|
|
||||||
|
async register(id: string, wasmBuffer: ArrayBuffer) {
|
||||||
|
let wrapper: ReturnType<typeof createWasmWrapper> = null!;
|
||||||
|
try {
|
||||||
|
wrapper = createWasmWrapper(wasmBuffer);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Failed to create node wrapper for node: ${id}`, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawDefinition = wrapper.get_definition();
|
||||||
|
const definition = NodeDefinitionSchema.safeParse(rawDefinition);
|
||||||
|
|
||||||
|
if (definition.error) {
|
||||||
|
throw new Error(
|
||||||
|
'Failed to parse node definition from node:+\n' + JSON.stringify(rawDefinition, null, 2)
|
||||||
|
+ '\n'
|
||||||
|
+ definition.error
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.cache) {
|
||||||
|
this.cache.set(definition.data.id, wasmBuffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
const node = {
|
||||||
|
...definition.data,
|
||||||
|
execute: wrapper.execute
|
||||||
|
};
|
||||||
|
|
||||||
|
this.nodes.set(definition.data.id, node);
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
getNode(id: string) {
|
||||||
|
return this.nodes.get(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
getAllNodes() {
|
||||||
|
return [...this.nodes.values()];
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user