Compare commits

...
Author SHA1 Message Date
Keavon Chambers e445e4b965 Replace O(N^2) is_acyclic() with O(V+E) using in-degree queue 2026-03-22 21:17:44 -07:00
Keavon Chambers 45e3626579 Skip HashMap construction in topological sort when node IDs are already sequential 2026-03-22 21:17:44 -07:00
Keavon Chambers b8b92cb822 Eliminate redundant graph edge computation in the compilation pipeline 2026-03-22 21:17:44 -07:00
Keavon Chambers f8d5dc1a21 Optimize remove_redundant_id_nodes from O(N×M) to O(N+M) 2026-03-22 21:17:44 -07:00
Timon 9727e14fe9 Add the re-labeled node display name to its Properties panel section header (#3930)
* Show nodes display name in properties panel if set

* Review
2026-03-22 20:20:32 -07:00
Timon 9a23b9908e Add missing 'Copy to Points' migration (#3922)
Add Copy to Points migration
2026-03-23 01:48:39 +00:00
Timon 4a37ce4576 Desktop: Open file dialogs in the folder containing the document (#3934)
Desktop: Open save file dialogs in document parent folder
2026-03-23 01:36:25 +00:00
Timon 5b1e1cb2fb Fix artboards not exporting with transparency using Vello (#3921)
* Fix hide artboard for raster render mode

* Desktop: Fix transparent viewport blending

* Fix vello render using wrong color space conversion for background

* Review
2026-03-23 01:20:54 +00:00
Jatin BhartiandKeavon Chambers bf486b4cb5 Fix bug where nodes (like Text) with a non-visible primary input would gain a primary input when shaken (#3899)
* fix: Shaking a Text layer breaks its type signature

* Add a second fix for the same issue

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-03-22 00:11:19 -07:00
Keavon Chambers b7a1b3e665 Fix CI failing on PRs reaching master via the merge queue 2026-03-22 00:10:55 -07:00
Keavon Chambers 342160b803 Remove unused frontend npm dependencies (#3935)
* Remove unused frontend npm dependencies

* Add a guard on database open
2026-03-21 21:19:24 -07:00
Keavon Chambers 06f27f1d3a Simplify TS configuration 2026-03-21 19:45:57 -07:00
Dennis KobertandKeavon Chambers b0cc8a9243 Update Vite to version 8 (#3900)
* Update vite to version 8

* Fix breakage from the upgrade

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-03-22 02:12:28 +00:00
Keavon Chambers 96418e8f5d Update dependencies to resolve advisories (#3933)
* Update Rust dependencies to resolve cargo-deny advisories

* Update minor/patch npm dependencies, too
2026-03-21 18:25:05 -07:00
Keavon Chambers 17da9ec099 New nodes: 'Decimate' and 'Simplify' (#3851)
* New node: Decimate

* Use preallocated stack to reduce number of allocations and fix double endpoints on closed paths

* Use Kurbo implementation of path-to-polyline sampling

* Add the 'Simplify' node
2026-03-21 17:08:18 -07:00
Keavon Chambers d5d10fe548 Rename /frontend/wasm -> /frontend/wrapper (#3927) 2026-03-21 03:46:47 -07:00
Keavon Chambers 4a0c2016e6 Rename editor_api.rs -> editor_wrapper.rs (#3926) 2026-03-21 03:34:08 -07:00
Keavon Chambers 087b4cd71f Rename EditorHandle -> EditorWrapper and organize editor_api.rs (#3925)
* Rename EditorHandle -> EditorWrapper and organize editor_api.rs

* pub -> pub(crate)
2026-03-21 03:27:57 -07:00
Keavon Chambers 9bcac1af2d Remove JS module import prefixes and use absolute paths to the frontend directory (#3924)
* Remove JS module import prefixes

* Fix code review mistakes
2026-03-21 00:08:32 -07:00
Keavon Chambers ed7987c881 Split apart the frontend Editor type into SubscriptionsRouter and EditorHandle (#3923)
* Remove the unused Editor.raw/wasmMemory/wasmImport

* Split out Editor.subscriptions

* Replace editor.handle.* with editor.* (1 of 2)

* Replace editor.handle.* with editor.* (2 of 2)

* Replace Editor typedef with EditorHandle import

* Pluralize subscription-router and rename subscriptionsRef->subscriptionsRouter and editorRef->editorHandle

* Remove editor.ts

* Update the readme

* Fix demo art loading bug
2026-03-20 23:34:13 -07:00
Keavon Chambers 64fd12a1a0 Break out helper functions from the frontend's managers and stores (#3920)
* Move destructor call to each manager/store constructor for safety

* Break out utility functions
2026-03-20 14:22:46 -07:00
TimonandJames Lindsay 0c7b5cd534 Desktop: Fix broken resizing affecting some Linux systems (#3917)
Desktop: Fix resizeing being broken on some Linux systems

Co-authored-by: James Lindsay <[email protected]>
2026-03-20 01:28:22 +00:00
Keavon Chambers 2e2c4fe180 Restructure frontend TS files so managers/stores export destructors instead of returning them from their constructors (#3919)
* Replace parameter passing with getContext and extract destroy functions to module-level exports

* Resend layouts from Rust when editor is re-mounted on HMR

* Code review
2026-03-19 18:25:34 -07:00
Keavon Chambers 124b17f609 Fix frontend HMR so the page doesn't break upon saving TS files and restructure frontend architecture (#3871)
* Clean up component setup/tear-down side effects

* Clean up more component setup/tear-down side effects

* Remove nonfunctional debouncer

* Clean up even more component setup/tear-down side effects

* Reuse backend state

* Fix HMR for IO Managers and for State Providers

* Rename IO Managers -> Managers and State Providers -> Stores

* Restructure and partially flatten managers/stores

* Code review fixes

* Review fixes
2026-03-19 13:38:41 -07:00
Keavon Chambers eb562146ce Consolidate CI web builds into the build workflow and restore deployments to GitHub environments (#3916)
* Restore the CI "View deployment" button in PRs after building

* Consolidate release.yml functionality into build.yml

* Move build from ci.yml to a delegated run in build.yml

* Rename CI to Check

* Code review fixes

* Review 2
2026-03-19 04:53:05 -07:00
TimonandKeavon Chambers 2e842cb425 Desktop: fix Mac restart dialog to show all changes to preferences requiring restart (#3903)
* Desktop: Fix restart dialog on Mac

* Fix

* Fix

* Fix

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-03-19 02:51:26 +00:00
Keavon Chambers 7f6571ee52 Fix regression from #3834 causing sub-menu lists to close if outside their hover stray distance 2026-03-18 15:53:48 -07:00
Keavon Chambers 187b4c38b4 Port website dev docs generated content scripts from JS to Rust to avoid intermediate parsing (#3909)
* Remove the crate dependency graph website generation intermediate generation step

* Remove the message system tree website generation intermediate generation step

* Code cleanup

* Remove cache system

* Fix Windows comment URL error

* Fix incorrect artifact download URLs

* Add Flatpak to comment

* Make Flatpak use debug/release mode choice instead of always release mode
2026-03-17 15:02:15 -07:00
Keavon Chambers d9214c7292 Add the crate dependency graph visualization to the contributor guide (#3907)
* Add the crate dependency graph visualization to the contributor guide

* Code review fixes

* And more
2026-03-17 01:35:56 -07:00
Keavon Chambers df8001fca8 Consolidate separate platform CI build workflows and improve !build comment commands 2026-03-16 17:10:00 -07:00
Keavon Chambers efd142f030 Update, tidy up, and standardize GitHub Actions workflows 2026-03-16 02:49:42 -07:00
Keavon Chambers f7815d0cd0 Add the build link bisect tool to the website (#3902)
* Add the bisect tool

* Add `cargo run explore` to open bisect tool

* Website cleanup

* Bug fixes

* Fix again
2026-03-16 02:46:21 -07:00
Timon 4c45c88034 Desktop: Remove CEF CREDITS.html from Windows bundle (#3889) 2026-03-14 16:44:38 +00:00
Dennis Kobert eb30ee78bc Fix Grapene CLI compilation (#3892)
* Fix grapene-cli compilation

* Improve cargo features to reduce recompiles
2026-03-13 11:28:34 +01:00
194 changed files with 8819 additions and 6810 deletions

No files matched your search

-75
View File
@@ -1,75 +0,0 @@
name: Build Linux Bundle
on:
push:
branches:
- master
workflow_dispatch:
inputs:
push_to_cache:
description: "Push to Nix Cache"
required: false
type: boolean
default: false
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: DeterminateSystems/nix-installer-action@main
- name: Free disk space
run: sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache
- name: Build Nix Package
run: nix build --no-link --print-out-paths
- name: Push to Nix Cache
if: github.ref == 'refs/heads/master' || inputs.push_to_cache == true
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN }}
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build --no-link --print-out-paths | nix run nixpkgs#cachix -- push graphite
- name: Build Linux Bundle
run: nix build .#graphite-bundle.tar.xz && cp ./result ./graphite-linux-bundle.tar.xz
- name: Upload Linux Bundle
uses: actions/upload-artifact@v4
with:
name: graphite-linux-bundle
path: graphite-linux-bundle.tar.xz
compression-level: 0
- name: Setup Flatpak Tooling
run: |
sudo apt-get update
sudo apt-get install -y flatpak flatpak-builder
flatpak --user remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
- name: Build Flatpak
run: |
nix build .#graphite-flatpak-manifest
rm -rf .flatpak
mkdir -p .flatpak
cp ./result .flatpak/manifest.json
cd .flatpak
mkdir -p repo
flatpak-builder --user --force-clean --install-deps-from=flathub --repo=repo build ./manifest.json
flatpak build-bundle repo Graphite.flatpak art.graphite.Graphite --runtime-repo=https://flathub.org/repo/flathub.flatpakrepo
- name: Upload Flatpak
uses: actions/upload-artifact@v4
with:
name: graphite-flatpak
path: .flatpak/Graphite.flatpak
compression-level: 0
-157
View File
@@ -1,157 +0,0 @@
name: Build Mac Bundle
on:
workflow_dispatch: {}
push:
branches:
- master
jobs:
build:
runs-on: macos-latest
env:
WASM_BINDGEN_CLI_VERSION: "0.2.100"
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: stable
override: true
rustflags: ""
target: wasm32-unknown-unknown
- name: Cache Cargo
uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: cargo-${{ runner.os }}-${{ hashFiles('**/Cargo.lock') }}
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: |
package-lock.json
frontend/package-lock.json
- name: Install Native Dependencies
env:
GITHUB_TOKEN: ${{ github.token }}
BINSTALL_DISABLE_TELEMETRY: "true"
run: |
brew update
brew install \
pkg-config \
openssl@3 \
binaryen \
llvm \
cargo-binstall
echo "OPENSSL_DIR=$(brew --prefix openssl@3)" >> $GITHUB_ENV
echo "PKG_CONFIG_PATH=$(brew --prefix openssl@3)/lib/pkgconfig" >> $GITHUB_ENV
echo "$(brew --prefix llvm)/bin" >> $GITHUB_PATH
cargo binstall --no-confirm --force wasm-pack
cargo binstall --no-confirm --force cargo-about
cargo binstall --no-confirm --force "wasm-bindgen-cli@${WASM_BINDGEN_CLI_VERSION}"
- name: Build Mac Bundle
env:
CARGO_TERM_COLOR: always
run: cargo run build desktop
- name: Stage Artifacts
shell: bash
run: |
rm -rf target/artifacts
mkdir -p target/artifacts
cp -R target/release/Graphite.app target/artifacts/Graphite.app
- name: Upload Mac Bundle
uses: actions/upload-artifact@v4
with:
name: graphite-mac-bundle
path: target/artifacts
- name: Sign and Notarize Mac Bundle Preparation
if: github.ref == 'refs/heads/master'
env:
APPLE_CERT_BASE64: ${{ secrets.APPLE_CERT_BASE64 }}
APPLE_CERT_PASSWORD: ${{ secrets.APPLE_CERT_PASSWORD }}
run: |
mkdir -p .sign
echo "$APPLE_CERT_BASE64" | base64 --decode > .sign/certificate.p12
security create-keychain -p "" .sign/main.keychain
security default-keychain -s .sign/main.keychain
security unlock-keychain -p "" .sign/main.keychain
security set-keychain-settings -t 3600 -u .sign/main.keychain
security import .sign/certificate.p12 -k .sign/main.keychain -P "$APPLE_CERT_PASSWORD" -T /usr/bin/codesign -T /usr/bin/productsign
security set-key-partition-list -S apple-tool:,apple: -s -k "" .sign/main.keychain
cat > .sign/entitlements.plist <<'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.disable-executable-page-protection</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
EOF
- name: Sign and Notarize Mac Bundle
if: github.ref == 'refs/heads/master'
env:
APPLE_EMAIL: ${{ secrets.APPLE_EMAIL }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_CERT_NAME: ${{ secrets.APPLE_CERT_NAME }}
run: |
CERTIFICATE="$APPLE_CERT_NAME"
ENTITLEMENTS=".sign/entitlements.plist"
APP_PATH="target/artifacts/Graphite.app"
ZIP_PATH=".sign/Graphite.zip"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper.app"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (GPU).app"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (Renderer).app"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libcef_sandbox.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libEGL.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libGLESv2.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libvk_swiftshader.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH" --deep
codesign --verify --deep --strict --verbose=4 "$APP_PATH"
ditto -c -k --keepParent "$APP_PATH" "$ZIP_PATH"
xcrun notarytool submit "$ZIP_PATH" --wait --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD"
rm "$ZIP_PATH"
xcrun stapler staple -v "$APP_PATH"
spctl -a -vv "$APP_PATH"
- name: Upload Mac Bundle Signed
if: github.ref == 'refs/heads/master'
uses: actions/upload-artifact@v4
with:
name: graphite-mac-bundle-signed
path: target/artifacts
-17
View File
@@ -1,17 +0,0 @@
name: Build Nix Package
on:
workflow_dispatch: {}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: DeterminateSystems/nix-installer-action@main
- uses: DeterminateSystems/magic-nix-cache-action@main
- name: Build Nix Package Dev
run: nix build .#graphite-dev --print-build-logs
-77
View File
@@ -1,77 +0,0 @@
name: "Editor: Production (Latest Stable)"
on:
push:
tags:
- "latest-stable"
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: self-hosted
permissions:
contents: write
deployments: write
env:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
SCCACHE_DIR: /var/lib/github-actions/.cache
INDEX_HTML_HEAD_REPLACEMENT: <script defer data-domain="editor.graphite.art" data-api="https://graphite.art/visit/event" src="https://graphite.art/visit/script.hash.js"></script>
steps:
- name: 📥 Clone and checkout repository
uses: actions/checkout@v3
- name: 🗑 Clear wasm-bindgen cache
run: rm -r ~/.cache/.wasm-pack
- name: 🟢 Install the latest Node.js
uses: actions/setup-node@v4
with:
node-version: "latest"
- name: 🚧 Install build dependencies
run: |
cd frontend
npm run setup
- name: 🦀 Install the latest Rust
run: |
echo "Initial system version:"
rustc --version
rustup update stable
echo "Latest updated version:"
rustc --version
- name: ✂ Replace template in <head> of index.html
run: |
sed -i "s|<!-- INDEX_HTML_HEAD_REPLACEMENT -->|$INDEX_HTML_HEAD_REPLACEMENT|" frontend/index.html
- name: 🌐 Build Graphite web code
env:
NODE_ENV: production
run: mold -run cargo run build web
- name: 📤 Publish to Cloudflare Pages
id: cloudflare
uses: cloudflare/pages-action@1
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
gitHubToken: ${{ secrets.GITHUB_TOKEN }}
projectName: graphite-editor
directory: frontend/dist
branch: master
- name: 📦 Upload assets to GitHub release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
DATE=$(git log -1 --format=%cd --date=format:%Y-%m-%d)
cd frontend
sed -i "s|$INDEX_HTML_HEAD_REPLACEMENT||" dist/index.html
mv dist "graphite-$DATE"
zip -r "graphite-self-hosted-build.zip" "graphite-$DATE"
gh release upload latest-stable "graphite-self-hosted-build.zip" --clobber
-173
View File
@@ -1,173 +0,0 @@
name: Build Windows Bundle
on:
workflow_dispatch: {}
push:
branches:
- master
permissions:
contents: read
id-token: write
jobs:
build:
runs-on: windows-latest
env:
WASM_BINDGEN_CLI_VERSION: "0.2.100"
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: stable
override: true
rustflags: ""
target: wasm32-unknown-unknown
- name: Cache Cargo
uses: actions/cache@v4
with:
path: |
${{ env.USERPROFILE }}\.cargo\registry
${{ env.USERPROFILE }}\.cargo\git
target
key: cargo-${{ runner.os }}-${{ hashFiles('**/Cargo.lock') }}
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: |
package-lock.json
frontend/package-lock.json
- name: Setup Cargo Binstall
uses: cargo-bins/cargo-binstall@main
- name: Install Native Dependencies
shell: pwsh
env:
GITHUB_TOKEN: ${{ github.token }}
BINSTALL_DISABLE_TELEMETRY: "true"
run: |
winget install --id LLVM.LLVM -e --accept-package-agreements --accept-source-agreements
winget install --id Kitware.CMake -e --accept-package-agreements --accept-source-agreements
winget install --id OpenSSL.OpenSSL -e --accept-package-agreements --accept-source-agreements
winget install --id WebAssembly.Binaryen -e --accept-package-agreements --accept-source-agreements
winget install --id GnuWin32.PkgConfig -e --accept-package-agreements --accept-source-agreements
"OPENSSL_DIR=C:\Program Files\OpenSSL-Win64" | Out-File -FilePath $env:GITHUB_ENV -Append
"PKG_CONFIG_PATH=C:\Program Files\OpenSSL-Win64\lib\pkgconfig" | Out-File -FilePath $env:GITHUB_ENV -Append
cargo binstall --no-confirm --force wasm-pack
cargo binstall --no-confirm --force cargo-about
cargo binstall --no-confirm --force "wasm-bindgen-cli@$env:WASM_BINDGEN_CLI_VERSION"
- name: Build Windows Bundle
shell: bash # `cargo-about` refuses to run in powershell
env:
CARGO_TERM_COLOR: always
run: cargo run build desktop
- name: Stage Artifacts
shell: bash
run: |
rm -rf target/artifacts
mkdir -p target/artifacts
cp -R target/release/Graphite target/artifacts/Graphite
- name: Upload Windows Bundle
uses: actions/upload-artifact@v4
with:
name: graphite-windows-bundle
path: target/artifacts
- name: Azure login
if: github.ref == 'refs/heads/master'
uses: azure/login@v1
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
enable-AzPSSession: true
- name: Sign
if: github.ref == 'refs/heads/master'
uses: azure/artifact-signing-action@v1
with:
endpoint: https://eus.codesigning.azure.net/
signing-account-name: Graphite
certificate-profile-name: Graphite
files: |
${{ github.workspace }}\target\artifacts\Graphite\Graphite.exe
${{ github.workspace }}\target\artifacts\Graphite\libcef.dll
${{ github.workspace }}\target\artifacts\Graphite\chrome_elf.dll
${{ github.workspace }}\target\artifacts\Graphite\vulkan-1.dll
${{ github.workspace }}\target\artifacts\Graphite\dxcompiler.dll
${{ github.workspace }}\target\artifacts\Graphite\libEGL.dll
${{ github.workspace }}\target\artifacts\Graphite\libGLESv2.dll
${{ github.workspace }}\target\artifacts\Graphite\vk_swiftshader.dll
file-digest: SHA256
timestamp-rfc3161: http://timestamp.acs.microsoft.com
timestamp-digest: SHA256
correlation-id: ${{ github.sha }}
- name: Verify Signatures
if: github.ref == 'refs/heads/master'
shell: pwsh
run: |
$ErrorActionPreference = "Stop"
$TargetDir = "target\artifacts\Graphite"
if (-not (Test-Path $TargetDir)) {
throw "TargetDir not found: $TargetDir"
}
$UnsignedOrBad = @()
Get-ChildItem -Path $TargetDir -Recurse -File -Include *.exe,*.dll | ForEach-Object {
$sig = Get-AuthenticodeSignature -FilePath $_.FullName
if ($sig.Status -ne 'Valid') {
$UnsignedOrBad += "$($_.FullName) (Status=$($sig.Status))"
}
}
if ($UnsignedOrBad.Count -gt 0) {
Write-Host "Unsigned or invalid binaries detected:"
$UnsignedOrBad | ForEach-Object {
Write-Host "::error::$_"
}
if ($env:GITHUB_STEP_SUMMARY) {
"### ❌ Unsigned or invalid binaries detected" |
Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
"" | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
$UnsignedOrBad | ForEach-Object {
"* `$_" | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
}
}
exit 1
}
Write-Host "All binaries are signed and valid."
if ($env:GITHUB_STEP_SUMMARY) {
"### ✅ All binaries are signed and valid" |
Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
}
- name: Upload Windows Bundle Signed
if: github.ref == 'refs/heads/master'
uses: actions/upload-artifact@v4
with:
name: graphite-windows-bundle-signed
path: target/artifacts
+730
View File
@@ -0,0 +1,730 @@
name: "Build"
on:
push:
branches:
- master
tags:
- latest-stable
workflow_dispatch:
inputs:
web:
description: "Web"
type: boolean
windows:
description: "Windows"
type: boolean
mac:
description: "Mac"
type: boolean
linux:
description: "Linux"
type: boolean
push_to_nix_cache:
description: "Linux: push to Nix cache"
type: boolean
debug:
description: "Debug build"
type: boolean
workflow_call:
inputs:
web:
type: boolean
windows:
type: boolean
mac:
type: boolean
linux:
type: boolean
push_to_nix_cache:
type: boolean
debug:
type: boolean
checkout_repo:
type: string
checkout_ref:
type: string
pr_number:
type: string
merge_queue:
type: boolean
jobs:
web:
if: github.event_name == 'push' || inputs.web
runs-on: [self-hosted, target/wasm]
permissions:
contents: write
deployments: write
pull-requests: write
actions: write
env:
CARGO_TERM_COLOR: always
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
SCCACHE_DIR: /var/lib/github-actions/.cache
steps:
- name: 📥 Clone repository
uses: actions/checkout@v6
with:
repository: ${{ inputs.checkout_repo || github.repository }}
ref: ${{ inputs.checkout_ref || '' }}
- name: 🗑 Clear wasm-bindgen cache
run: rm -r ~/.cache/.wasm-pack || true
- name: 🟢 Install Node.js
uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
- name: 🚧 Install build dependencies
run: |
cd frontend
npm run setup
- name: 🦀 Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: stable
override: true
cache: false
rustflags: ""
target: wasm32-unknown-unknown
- name: 🔀 Choose production deployment environment and insert template
id: production-env
if: github.event_name == 'push'
run: |
if [[ "${{ github.ref }}" == "refs/tags/latest-stable" ]]; then
echo "cf_project=graphite-editor" >> $GITHUB_OUTPUT
DOMAIN="editor.graphite.art"
else
echo "cf_project=graphite-dev" >> $GITHUB_OUTPUT
DOMAIN="dev.graphite.art"
fi
TEMPLATE="<script defer data-domain=\"$DOMAIN\" data-api=\"https://graphite.art/visit/event\" src=\"https://graphite.art/visit/script.hash.js\"></script>"
echo "template=$TEMPLATE" >> $GITHUB_OUTPUT
sed -i "s|<!-- INDEX_HTML_HEAD_REPLACEMENT -->|$TEMPLATE|" frontend/index.html
- name: 🌐 Build Graphite web code
env:
NODE_ENV: production
run: mold -run cargo run build web${{ inputs.debug && ' debug' || '' }}
- name: 📤 Publish to Cloudflare Pages
if: inputs.merge_queue == false
id: cloudflare
continue-on-error: ${{ github.event_name != 'push' }}
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
run: |
if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
echo "No Cloudflare API token available (fork PR), skipping deploy."
exit 0
fi
MAX_ATTEMPTS=8
DELAY=15
for ATTEMPT in $(seq 1 $MAX_ATTEMPTS); do
echo "Attempt $ATTEMPT of $MAX_ATTEMPTS..."
npx wrangler@3 pages deploy "frontend/dist" --project-name="${{ steps.production-env.outputs.cf_project || 'graphite-dev' }}" --commit-dirty=true 2>&1 | tee /tmp/wrangler_output
if [ ${PIPESTATUS[0]} -eq 0 ]; then
URL=$(grep -oP 'https://[^\s]+\.pages\.dev' /tmp/wrangler_output | head -1)
echo "url=$URL" >> "$GITHUB_OUTPUT"
echo "Published successfully: $URL"
exit 0
fi
echo "Attempt $ATTEMPT failed."
if [ "$ATTEMPT" -lt "$MAX_ATTEMPTS" ]; then
echo "Retrying in ${DELAY}s..."
sleep $DELAY
DELAY=$((DELAY * 2))
fi
done
echo "All $MAX_ATTEMPTS Cloudflare Pages publish attempts failed."
exit 1
- name: 🚀 Create a GitHub environment deployment
if: (inputs.checkout_repo == '' || inputs.checkout_repo == github.repository) && inputs.merge_queue == false
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CF_URL: ${{ steps.cloudflare.outputs.url }}
run: |
if [ -z "$CF_URL" ]; then
echo "No Cloudflare URL available, skipping deployment."
exit 0
fi
if [ "${{ github.ref }}" = "refs/tags/latest-stable" ]; then
REF="latest-stable"
ENVIRONMENT="graphite-editor (Production)"
elif [ "${{ github.event_name }}" = "push" ]; then
REF="master"
ENVIRONMENT="graphite-dev (Production)"
else
REF="${{ inputs.checkout_ref || github.head_ref || github.ref_name }}"
ENVIRONMENT="graphite-dev (Preview)"
fi
DEPLOY_ID=$(gh api \
-X POST \
-H "Accept: application/vnd.github+json" \
repos/${{ github.repository }}/deployments \
--input - \
--jq '.id' <<EOF
{"ref":"$REF","environment":"$ENVIRONMENT","auto_merge":false,"required_contexts":[]}
EOF
)
gh api \
-X POST \
-H "Accept: application/vnd.github+json" \
repos/${{ github.repository }}/deployments/$DEPLOY_ID/statuses \
-f state=success \
-f environment_url="$CF_URL" \
-f log_url="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
- name: 💬 Comment with the build link
if: github.event_name != 'pull_request' && inputs.merge_queue == false
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CF_URL: ${{ steps.cloudflare.outputs.url }}
run: |
if [ -z "$CF_URL" ]; then
echo "No Cloudflare URL available, skipping comment."
exit 0
fi
COMMENT_BODY="| 📦 **Web Build Complete for** $(git rev-parse HEAD) |
|-|
| $CF_URL |"
if [ "${{ github.ref }}" = "refs/tags/latest-stable" ]; then
# Push tag: skip commenting (commit was already commented on master merge)
echo "Tag push, skipping comment."
elif [ "${{ github.event_name }}" = "push" ]; then
# Push master: comment on the commit hash page
gh api \
-X POST \
-H "Accept: application/vnd.github+json" \
repos/${{ github.repository }}/commits/$(git rev-parse HEAD)/comments \
-f body="$COMMENT_BODY"
elif [ "${{ github.event_name }}" != "pull_request" ]; then
# Manual trigger (workflow_dispatch, !build): comment on the PR
PR_NUMBER="${{ inputs.pr_number }}"
if [ -z "$PR_NUMBER" ]; then
BRANCH=$(git rev-parse --abbrev-ref HEAD)
PR_NUMBER=$(gh pr list --repo ${{ github.repository }} --head "$BRANCH" --json number --jq '.[0].number' 2>/dev/null || true)
fi
if [ -n "$PR_NUMBER" ]; then
gh pr comment "$PR_NUMBER" --repo ${{ github.repository }} --body "$COMMENT_BODY"
else
echo "No open PR found, skipping comment."
fi
fi
- name: ✂ Strip template from completed build for a clean artifact
if: github.event_name == 'push'
env:
TEMPLATE: ${{ steps.production-env.outputs.template }}
run: sed -i "s|$TEMPLATE||" frontend/dist/index.html
- name: 📦 Upload web bundle artifact
if: github.event_name != 'pull_request' && inputs.merge_queue == false
uses: actions/upload-artifact@v6
with:
name: graphite-web-bundle
path: frontend/dist
- name: 👕 Lint Graphite web formatting
env:
NODE_ENV: production
run: |
cd frontend
npm run check
- name: 📃 Trigger website rebuild if auto-generated code docs are stale
if: github.event_name == 'push' && github.ref != 'refs/tags/latest-stable'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
cargo run -p editor-message-tree -- website/generated
TREE=volunteer/guide/codebase-overview/hierarchical-message-system-tree
curl -sf "https://graphite.art/$TREE.txt" -o "website/static/$TREE.live.txt" \
&& diff -q "website/static/$TREE.txt" "website/static/$TREE.live.txt" > /dev/null \
|| gh workflow run website.yml --ref master
windows:
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.windows
runs-on: windows-latest
permissions:
contents: read
id-token: write
pull-requests: write
env:
WASM_BINDGEN_CLI_VERSION: "0.2.100"
steps:
- name: 📥 Clone repository
uses: actions/checkout@v6
with:
repository: ${{ inputs.checkout_repo || github.repository }}
ref: ${{ inputs.checkout_ref || '' }}
- name: 🦀 Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: stable
override: true
cache: false
rustflags: ""
target: wasm32-unknown-unknown
- name: 💾 Set up Cargo cache
uses: actions/cache@v5
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: cargo-${{ runner.os }}-${{ hashFiles('**/Cargo.lock') }}
- name: 🟢 Install Node.js
uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: |
package-lock.json
frontend/package-lock.json
- name: 📦 Install Cargo-binstall
uses: cargo-bins/cargo-binstall@main
- name: 🚧 Install native dependencies
shell: pwsh
env:
GITHUB_TOKEN: ${{ github.token }}
BINSTALL_DISABLE_TELEMETRY: "true"
run: |
winget install --id LLVM.LLVM -e --accept-package-agreements --accept-source-agreements
winget install --id Kitware.CMake -e --accept-package-agreements --accept-source-agreements
winget install --id OpenSSL.OpenSSL -e --accept-package-agreements --accept-source-agreements
winget install --id WebAssembly.Binaryen -e --accept-package-agreements --accept-source-agreements
winget install --id GnuWin32.PkgConfig -e --accept-package-agreements --accept-source-agreements
"OPENSSL_DIR=C:\Program Files\OpenSSL-Win64" | Out-File -FilePath $env:GITHUB_ENV -Append
"PKG_CONFIG_PATH=C:\Program Files\OpenSSL-Win64\lib\pkgconfig" | Out-File -FilePath $env:GITHUB_ENV -Append
cargo binstall --no-confirm --force wasm-pack
cargo binstall --no-confirm --force cargo-about
cargo binstall --no-confirm --force "wasm-bindgen-cli@$env:WASM_BINDGEN_CLI_VERSION"
- name: 🏗 Build Windows bundle
shell: bash # `cargo-about` refuses to run in powershell
env:
CARGO_TERM_COLOR: always
run: cargo run build desktop${{ inputs.debug && ' debug' || '' }}
- name: 📁 Stage artifacts
shell: bash
run: |
PROFILE=${{ inputs.debug && 'debug' || 'release' }}
rm -rf target/artifacts
mkdir -p target/artifacts
cp -R target/$PROFILE/Graphite target/artifacts/Graphite
- name: 📦 Upload Windows bundle
if: github.event_name != 'push'
uses: actions/upload-artifact@v6
with:
name: graphite-windows-bundle
path: target/artifacts
- name: 💬 Comment artifact link on PR
if: github.event_name != 'push'
shell: bash
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
ARTIFACT_ID=$(gh api repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts --jq '.artifacts[] | select(.name == "graphite-windows-bundle") | .id')
ARTIFACT_URL="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts/$ARTIFACT_ID"
PR_NUMBER="${{ inputs.pr_number }}"
if [ -z "$PR_NUMBER" ]; then
BRANCH=$(git rev-parse --abbrev-ref HEAD)
PR_NUMBER=$(gh pr list --repo ${{ github.repository }} --head "$BRANCH" --json number --jq '.[0].number' 2>/dev/null || true)
fi
if [ -n "$PR_NUMBER" ] && [ -n "$ARTIFACT_ID" ]; then
BODY="| 📦 **Windows Build Complete for** $(git rev-parse HEAD) |"$'\n'
BODY+="|-|"$'\n'
BODY+="| [Download binary]($ARTIFACT_URL) |"
gh pr comment "$PR_NUMBER" --repo ${{ github.repository }} --body "$BODY"
fi
- name: 🔑 Azure login
if: github.event_name == 'push'
uses: azure/login@v1
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
enable-AzPSSession: true
- name: 🔏 Sign
if: github.event_name == 'push'
uses: azure/artifact-signing-action@v1
with:
endpoint: https://eus.codesigning.azure.net/
signing-account-name: Graphite
certificate-profile-name: Graphite
files: |
${{ github.workspace }}\target\artifacts\Graphite\Graphite.exe
${{ github.workspace }}\target\artifacts\Graphite\libcef.dll
${{ github.workspace }}\target\artifacts\Graphite\chrome_elf.dll
${{ github.workspace }}\target\artifacts\Graphite\vulkan-1.dll
${{ github.workspace }}\target\artifacts\Graphite\dxcompiler.dll
${{ github.workspace }}\target\artifacts\Graphite\libEGL.dll
${{ github.workspace }}\target\artifacts\Graphite\libGLESv2.dll
${{ github.workspace }}\target\artifacts\Graphite\vk_swiftshader.dll
file-digest: SHA256
timestamp-rfc3161: http://timestamp.acs.microsoft.com
timestamp-digest: SHA256
correlation-id: ${{ github.sha }}
- name: ✅ Verify signatures
if: github.event_name == 'push'
shell: pwsh
run: |
$ErrorActionPreference = "Stop"
$TargetDir = "target\artifacts\Graphite"
if (-not (Test-Path $TargetDir)) {
throw "TargetDir not found: $TargetDir"
}
$UnsignedOrBad = @()
Get-ChildItem -Path $TargetDir -Recurse -File -Include *.exe,*.dll | ForEach-Object {
$sig = Get-AuthenticodeSignature -FilePath $_.FullName
if ($sig.Status -ne 'Valid') {
$UnsignedOrBad += "$($_.FullName) (Status=$($sig.Status))"
}
}
if ($UnsignedOrBad.Count -gt 0) {
Write-Host "Unsigned or invalid binaries detected:"
$UnsignedOrBad | ForEach-Object {
Write-Host "::error::$_"
}
if ($env:GITHUB_STEP_SUMMARY) {
"### ❌ Unsigned or invalid binaries detected" |
Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
"" | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
$UnsignedOrBad | ForEach-Object {
"* `$_" | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
}
}
exit 1
}
Write-Host "All binaries are signed and valid."
if ($env:GITHUB_STEP_SUMMARY) {
"### ✅ All binaries are signed and valid" |
Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
}
- name: 📦 Upload signed Windows bundle
if: github.event_name == 'push'
uses: actions/upload-artifact@v6
with:
name: graphite-windows-bundle-signed
path: target/artifacts
mac:
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.mac
runs-on: macos-latest
permissions:
contents: read
pull-requests: write
env:
WASM_BINDGEN_CLI_VERSION: "0.2.100"
steps:
- name: 📥 Clone repository
uses: actions/checkout@v6
with:
repository: ${{ inputs.checkout_repo || github.repository }}
ref: ${{ inputs.checkout_ref || '' }}
- name: 🦀 Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: stable
override: true
cache: false
rustflags: ""
target: wasm32-unknown-unknown
- name: 💾 Set up Cargo cache
uses: actions/cache@v5
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: cargo-${{ runner.os }}-${{ hashFiles('**/Cargo.lock') }}
- name: 🟢 Install Node.js
uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: |
package-lock.json
frontend/package-lock.json
- name: 🚧 Install native dependencies
env:
GITHUB_TOKEN: ${{ github.token }}
BINSTALL_DISABLE_TELEMETRY: "true"
run: |
brew update
brew install \
pkg-config \
openssl@3 \
binaryen \
llvm \
cargo-binstall
echo "OPENSSL_DIR=$(brew --prefix openssl@3)" >> $GITHUB_ENV
echo "PKG_CONFIG_PATH=$(brew --prefix openssl@3)/lib/pkgconfig" >> $GITHUB_ENV
echo "$(brew --prefix llvm)/bin" >> $GITHUB_PATH
cargo binstall --no-confirm --force wasm-pack
cargo binstall --no-confirm --force cargo-about
cargo binstall --no-confirm --force "wasm-bindgen-cli@${WASM_BINDGEN_CLI_VERSION}"
- name: 🏗 Build Mac bundle
env:
CARGO_TERM_COLOR: always
run: cargo run build desktop${{ inputs.debug && ' debug' || '' }}
- name: 📁 Stage artifacts
shell: bash
run: |
PROFILE=${{ inputs.debug && 'debug' || 'release' }}
rm -rf target/artifacts
mkdir -p target/artifacts
cp -R target/$PROFILE/Graphite.app target/artifacts/Graphite.app
- name: 📦 Upload Mac bundle
if: github.event_name != 'push'
uses: actions/upload-artifact@v6
with:
name: graphite-mac-bundle
path: target/artifacts
- name: 💬 Comment artifact link on PR
if: github.event_name != 'push'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
ARTIFACT_ID=$(gh api repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts --jq '.artifacts[] | select(.name == "graphite-mac-bundle") | .id')
ARTIFACT_URL="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts/$ARTIFACT_ID"
PR_NUMBER="${{ inputs.pr_number }}"
if [ -z "$PR_NUMBER" ]; then
BRANCH=$(git rev-parse --abbrev-ref HEAD)
PR_NUMBER=$(gh pr list --repo ${{ github.repository }} --head "$BRANCH" --json number --jq '.[0].number' 2>/dev/null || true)
fi
if [ -n "$PR_NUMBER" ] && [ -n "$ARTIFACT_ID" ]; then
BODY="| 📦 **Mac Build Complete for** $(git rev-parse HEAD) |"$'\n'
BODY+="|-|"$'\n'
BODY+="| [Download binary]($ARTIFACT_URL) |"
gh pr comment "$PR_NUMBER" --repo ${{ github.repository }} --body "$BODY"
fi
- name: 🔏 Sign and notarize (preparation)
if: github.event_name == 'push'
env:
APPLE_CERT_BASE64: ${{ secrets.APPLE_CERT_BASE64 }}
APPLE_CERT_PASSWORD: ${{ secrets.APPLE_CERT_PASSWORD }}
run: |
mkdir -p .sign
echo "$APPLE_CERT_BASE64" | base64 --decode > .sign/certificate.p12
security create-keychain -p "" .sign/main.keychain
security default-keychain -s .sign/main.keychain
security unlock-keychain -p "" .sign/main.keychain
security set-keychain-settings -t 3600 -u .sign/main.keychain
security import .sign/certificate.p12 -k .sign/main.keychain -P "$APPLE_CERT_PASSWORD" -T /usr/bin/codesign -T /usr/bin/productsign
security set-key-partition-list -S apple-tool:,apple: -s -k "" .sign/main.keychain
cat > .sign/entitlements.plist <<'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.disable-executable-page-protection</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
EOF
- name: 🔏 Sign and notarize
if: github.event_name == 'push'
env:
APPLE_EMAIL: ${{ secrets.APPLE_EMAIL }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_CERT_NAME: ${{ secrets.APPLE_CERT_NAME }}
run: |
CERTIFICATE="$APPLE_CERT_NAME"
ENTITLEMENTS=".sign/entitlements.plist"
APP_PATH="target/artifacts/Graphite.app"
ZIP_PATH=".sign/Graphite.zip"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper.app"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (GPU).app"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (Renderer).app"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libcef_sandbox.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libEGL.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libGLESv2.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libvk_swiftshader.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH" --deep
codesign --verify --deep --strict --verbose=4 "$APP_PATH"
ditto -c -k --keepParent "$APP_PATH" "$ZIP_PATH"
xcrun notarytool submit "$ZIP_PATH" --wait --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD"
rm "$ZIP_PATH"
xcrun stapler staple -v "$APP_PATH"
spctl -a -vv "$APP_PATH"
- name: 📦 Upload signed Mac bundle
if: github.event_name == 'push'
uses: actions/upload-artifact@v6
with:
name: graphite-mac-bundle-signed
path: target/artifacts
linux:
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.linux
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- name: 📥 Clone repository
uses: actions/checkout@v6
with:
repository: ${{ inputs.checkout_repo || github.repository }}
ref: ${{ inputs.checkout_ref || '' }}
- name: ❄ Install Nix
uses: DeterminateSystems/nix-installer-action@main
- name: 🗑 Free disk space
run: sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache
- name: 📦 Build Nix package
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }} --no-link --print-out-paths
- name: 📤 Push to Nix cache
if: (github.event_name == 'push' || inputs.push_to_nix_cache) && !inputs.debug
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN }}
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build --no-link --print-out-paths | nix run nixpkgs#cachix -- push graphite
- name: 🏗 Build Linux bundle
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }}-bundle.tar.xz && cp ./result ./graphite-linux-bundle.tar.xz
- name: 📦 Upload Linux bundle
uses: actions/upload-artifact@v6
with:
name: graphite-linux-bundle
path: graphite-linux-bundle.tar.xz
compression-level: 0
- name: 💬 Comment artifact link on PR
id: linux-comment
if: github.event_name != 'push'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
ARTIFACT_ID=$(gh api repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts --jq '.artifacts[] | select(.name == "graphite-linux-bundle") | .id')
ARTIFACT_URL="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts/$ARTIFACT_ID"
PR_NUMBER="${{ inputs.pr_number }}"
if [ -z "$PR_NUMBER" ]; then
BRANCH=$(git rev-parse --abbrev-ref HEAD)
PR_NUMBER=$(gh pr list --repo ${{ github.repository }} --head "$BRANCH" --json number --jq '.[0].number' 2>/dev/null || true)
fi
if [ -n "$PR_NUMBER" ] && [ -n "$ARTIFACT_ID" ]; then
BODY="| 📦 **Linux Build Complete for** $(git rev-parse HEAD) |"$'\n'
BODY+="|-|"$'\n'
BODY+="| [Download binary]($ARTIFACT_URL) |"
COMMENT_ID=$(gh api repos/${{ github.repository }}/issues/$PR_NUMBER/comments -f body="$BODY" --jq '.id')
echo "comment_id=$COMMENT_ID" >> "$GITHUB_OUTPUT"
fi
- name: 🔧 Install Flatpak tooling
run: |
sudo apt-get update
sudo apt-get install -y flatpak flatpak-builder
flatpak --user remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
- name: 🏗 Build Flatpak
run: |
nix build .#graphite${{ inputs.debug && '-dev' || '' }}-flatpak-manifest
rm -rf .flatpak
mkdir -p .flatpak
cp ./result .flatpak/manifest.json
cd .flatpak
mkdir -p repo
flatpak-builder --user --force-clean --install-deps-from=flathub --repo=repo build ./manifest.json
flatpak build-bundle repo Graphite.flatpak art.graphite.Graphite --runtime-repo=https://flathub.org/repo/flathub.flatpakrepo
- name: 📦 Upload Flatpak package
uses: actions/upload-artifact@v6
with:
name: graphite-flatpak
path: .flatpak/Graphite.flatpak
compression-level: 0
- name: 💬 Update PR comment with Flatpak artifact link
if: github.event_name != 'push' && steps.linux-comment.outputs.comment_id
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
ARTIFACT_ID=$(gh api repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts --jq '.artifacts[] | select(.name == "graphite-flatpak") | .id')
ARTIFACT_URL="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts/$ARTIFACT_ID"
COMMENT_ID="${{ steps.linux-comment.outputs.comment_id }}"
if [ -n "$ARTIFACT_ID" ]; then
EXISTING_BODY=$(gh api repos/${{ github.repository }}/issues/comments/$COMMENT_ID --jq '.body')
BODY="$EXISTING_BODY"$'\n'
BODY+="| [Download Flatpak]($ARTIFACT_URL) |"
gh api repos/${{ github.repository }}/issues/comments/$COMMENT_ID -X PATCH -f body="$BODY"
fi
+4 -4
View File
@@ -1,9 +1,9 @@
name: "Audit Security Advisories"
on:
# Run once each day
# Run once each week
schedule:
- cron: "0 0 * * *"
- cron: "0 0 * * 0"
jobs:
cargo-deny:
@@ -11,8 +11,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: 📥 Clone and checkout repository
uses: actions/checkout@v3
- name: 📥 Clone repository
uses: actions/checkout@v6
- name: 🔒 Check crate security advisories for root workspace
uses: EmbarkStudios/cargo-deny-action@v2
+102
View File
@@ -0,0 +1,102 @@
name: "Check"
on:
pull_request: {}
merge_group: {}
env:
CARGO_TERM_COLOR: always
jobs:
# Check if CI can be skipped (for merge queue deduplication)
skip-check:
runs-on: ubuntu-latest
outputs:
skip: ${{ steps.check.outputs.skip-check }}
steps:
- name: 📥 Clone repository
uses: actions/checkout@v6
- name: 🚦 Check if CI can be skipped
id: check
uses: cariad-tech/merge-queue-ci-skipper@cf80db21fc70244e36487acc531b3f1118889b0a
# Build the web app via the shared build workflow
build:
needs: skip-check
if: needs.skip-check.outputs.skip != 'true'
uses: ./.github/workflows/build.yml
secrets: inherit
with:
web: true
merge_queue: ${{ github.event_name == 'merge_group' }}
# Run the Rust tests on the self-hosted native runner
test:
needs: skip-check
if: needs.skip-check.outputs.skip != 'true'
runs-on: [self-hosted, target/native]
env:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
SCCACHE_DIR: /var/lib/github-actions/.cache
steps:
- name: 📥 Clone repository
uses: actions/checkout@v6
- name: 🦀 Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: stable
override: true
cache: false
rustflags: ""
- name: 🦀 Fetch Rust dependencies
run: cargo fetch --locked
- name: 🧪 Run Rust tests
env:
RUSTFLAGS: -Dwarnings
run: mold -run cargo test --all-features
# Rust format check on GitHub runner
rust-fmt:
needs: skip-check
if: needs.skip-check.outputs.skip != 'true'
runs-on: ubuntu-latest
steps:
- name: 📥 Clone repository
uses: actions/checkout@v6
- name: 🦀 Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: stable
override: true
cache: false
rustflags: ""
components: rustfmt
- name: 🔬 Check Rust formatting
run: cargo fmt --all -- --check
# License compatibility check on GitHub runner
check-licenses:
needs: skip-check
if: needs.skip-check.outputs.skip != 'true'
runs-on: ubuntu-latest
steps:
- name: 📥 Clone repository
uses: actions/checkout@v6
- name: 📜 Check crate license compatibility for root workspace
uses: EmbarkStudios/cargo-deny-action@v2
with:
command: check bans licenses sources
- name: 📜 Check crate license compatibility for /libraries/rawkit
uses: EmbarkStudios/cargo-deny-action@v2
with:
command: check bans licenses sources
manifest-path: libraries/rawkit/Cargo.toml
-153
View File
@@ -1,153 +0,0 @@
name: "CI"
on:
pull_request: {}
merge_group: {}
env:
CARGO_TERM_COLOR: always
jobs:
# Rust format check on GitHub runner
rust-fmt:
runs-on: ubuntu-latest
steps:
- name: 📥 Clone and checkout repository
uses: actions/checkout@v3
- name: 🚦 Check if CI can be skipped
id: skip-check
uses: cariad-tech/merge-queue-ci-skipper@main
- name: 🦀 Install the latest Rust
if: steps.skip-check.outputs.skip-check != 'true'
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- name: 🔬 Check Rust formatting
if: steps.skip-check.outputs.skip-check != 'true'
run: cargo fmt --all -- --check
# License compatibility check on GitHub runner
cargo-deny:
runs-on: ubuntu-latest
steps:
- name: 📥 Clone and checkout repository
uses: actions/checkout@v3
- name: 📜 Check crate license compatibility for root workspace
uses: EmbarkStudios/cargo-deny-action@v2
with:
command: check bans licenses sources
- name: 📜 Check crate license compatibility for /libraries/rawkit
uses: EmbarkStudios/cargo-deny-action@v2
with:
command: check bans licenses sources
manifest-path: libraries/rawkit/Cargo.toml
# Build the web app on the self-hosted wasm runner
build:
runs-on: [self-hosted, target/wasm]
permissions:
contents: write
deployments: write
pull-requests: write
actions: write
env:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
SCCACHE_DIR: /var/lib/github-actions/.cache
steps:
- name: 📥 Clone and checkout repository
uses: actions/checkout@v3
- name: 🚦 Check if CI can be skipped
id: skip-check
uses: cariad-tech/merge-queue-ci-skipper@main
- name: 🗑 Clear wasm-bindgen cache
if: steps.skip-check.outputs.skip-check != 'true'
run: rm -r ~/.cache/.wasm-pack || true
- name: 🟢 Install the latest Node.js
if: steps.skip-check.outputs.skip-check != 'true'
uses: actions/setup-node@v4
with:
node-version: "latest"
- name: 🚧 Install build dependencies
if: steps.skip-check.outputs.skip-check != 'true'
run: |
cd frontend
npm run setup
- name: 🦀 Install the latest Rust
if: steps.skip-check.outputs.skip-check != 'true'
run: |
rustup update stable
- name: 🦀 Fetch Rust dependencies
if: steps.skip-check.outputs.skip-check != 'true'
run: |
cargo fetch --locked
- name: 🌐 Build Graphite web code
if: steps.skip-check.outputs.skip-check != 'true'
env:
NODE_ENV: production
run: mold -run cargo run build web
- name: 📤 Publish to Cloudflare Pages
if: steps.skip-check.outputs.skip-check != 'true'
uses: cloudflare/pages-action@1
continue-on-error: true
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
gitHubToken: ${{ secrets.GITHUB_TOKEN }}
projectName: graphite-dev
directory: frontend/dist
- name: 👕 Lint Graphite web formatting
if: steps.skip-check.outputs.skip-check != 'true'
env:
NODE_ENV: production
run: |
cd frontend
npm run check
# Run the Rust tests on the self-hosted native runner
test:
runs-on: [self-hosted, target/native]
env:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
SCCACHE_DIR: /var/lib/github-actions/.cache
steps:
- name: 📥 Clone and checkout repository
uses: actions/checkout@v3
- name: 🚦 Check if CI can be skipped
id: skip-check
uses: cariad-tech/merge-queue-ci-skipper@main
- name: 🦀 Install the latest Rust
if: steps.skip-check.outputs.skip-check != 'true'
run: |
rustup update stable
- name: 🦀 Fetch Rust dependencies
if: steps.skip-check.outputs.skip-check != 'true'
run: |
cargo fetch --locked
- name: 🧪 Run Rust tests
if: steps.skip-check.outputs.skip-check != 'true'
env:
RUSTFLAGS: -Dwarnings
run: |
mold -run cargo test --all-features
+105 -122
View File
@@ -1,154 +1,137 @@
# USAGE:
# After reviewing the code, core team members may comment on a PR with the exact text:
# - `!build-debug` to build with debug symbols and optimizations disabled
# - `!build` to build without debug symbols and optimizations enabled
# The comment may not contain any other text, not even whitespace or newlines.
# After reviewing the code, core team members may comment on a PR with `!build` followed by optional `<target>` and `<profile>` arguments.
# This matches the syntax of the `cargo run build` CLI command, but allows platforms to be specified.
#
# `<target>`: `web` (default), `desktop` (all platforms), or `desktop:<platforms>` (subset of `windows+mac+linux`)
# `<profile>`: `release` (default) or `debug`
#
# Examples:
# - !build
# - !build debug
# - !build desktop
# - !build desktop:windows+mac
# - !build desktop:linux debug
name: "!build PR Command"
on:
issue_comment:
types:
- created
env:
CARGO_TERM_COLOR: always
jobs:
build:
setup:
# Command should be limited to core team members (those in the organization) for security.
# From the GitHub Actions docs:
# author_association = 'MEMBER': Author is a member of the organization that owns the repository.
if: >
github.event.issue.pull_request &&
github.event.comment.author_association == 'MEMBER' &&
(github.event.comment.body == '!build-debug' || github.event.comment.body == '!build')
runs-on: self-hosted
startsWith(github.event.comment.body, '!build')
runs-on: ubuntu-latest
permissions:
contents: read
deployments: write
pull-requests: write
env:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
SCCACHE_DIR: /var/lib/github-actions/.cache
outputs:
repo: ${{ steps.pr_info.outputs.repo }}
ref: ${{ steps.pr_info.outputs.ref }}
web: ${{ steps.pr_info.outputs.web }}
windows: ${{ steps.pr_info.outputs.windows }}
mac: ${{ steps.pr_info.outputs.mac }}
linux: ${{ steps.pr_info.outputs.linux }}
debug: ${{ steps.pr_info.outputs.debug }}
steps:
- name: 🔎 Find branch for this PR
id: commit_info
- name: 🔎 Parse command, find branch, and set build flags
id: pr_info
run: |
RESPONSE=$(curl -L -H 'Accept: application/vnd.github+json' -H 'X-GitHub-Api-Version: 2022-11-28' https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.issue.number }})
REPO=$(echo $RESPONSE | jq -r '.head.repo.full_name')
REF=$(echo $RESPONSE | jq -r '.head.ref')
SHA=$(echo $RESPONSE | jq -r '.head.sha')
echo "repo=$REPO" >> $GITHUB_OUTPUT
echo "ref=$REF" >> $GITHUB_OUTPUT
echo "sha=$SHA" >> $GITHUB_OUTPUT
COMMENT="${{ github.event.comment.body }}"
- name: 📥 Clone and checkout repository
uses: actions/checkout@v3
with:
repository: ${{ steps.commit_info.outputs.repo }}
ref: ${{ steps.commit_info.outputs.ref }}
# Split into space-separated words
read -ra WORDS <<< "$COMMENT"
- name: 🗑 Clear wasm-bindgen cache
continue-on-error: true
run: rm -r ~/.cache/.wasm-pack
- name: 🟢 Install the latest Node.js
uses: actions/setup-node@v4
with:
node-version: "latest"
- name: 🚧 Install build dependencies
run: |
cd frontend
npm run setup
- name: 🦀 Install the latest Rust
run: |
echo "Initial system version:"
rustc --version
rustup update stable
echo "Latest updated version:"
rustc --version
- name: ✂ Replace template in <head> of index.html
env:
INDEX_HTML_HEAD_REPLACEMENT: ""
run: |
# Remove the INDEX_HTML_HEAD_REPLACEMENT environment variable for build links (not master deploys)
sed -i "s|<!-- INDEX_HTML_HEAD_REPLACEMENT -->|$INDEX_HTML_HEAD_REPLACEMENT|" frontend/index.html
- name: ⌨ Set build command based on comment
id: build_command
run: |
if [[ "${{ github.event.comment.body }}" == "!build-debug" ]]; then
echo "command=build web debug" >> $GITHUB_OUTPUT
elif [[ "${{ github.event.comment.body }}" == "!build" ]]; then
echo "command=build web" >> $GITHUB_OUTPUT
else
echo "Failed to detect if the build command written in the comment should have been '!build-debug', or '!build'" >> $GITHUB_OUTPUT
# First word must be "!build"
if [[ "${WORDS[0]}" != "!build" ]]; then
echo "::error::Expected comment to start with !build"
exit 1
fi
- name: 💬 Comment Actions run link
id: comment_actions_run_link
uses: actions/github-script@v6
# Initialize build flags (web defaults to true, matching the CLI default target)
WEB="true"
WINDOWS="false"
MAC="false"
LINUX="false"
DEBUG="false"
# Parse target (optional, defaults to `web` if omitted)
IDX=1
case "${WORDS[$IDX]:-}" in
# Target: `web` enables just the web build (already the default, but accepted explicitly)
"web")
((IDX++)) ;;
# Target: `desktop` enables all three desktop platforms
"desktop")
WEB="false"; WINDOWS="true"; MAC="true"; LINUX="true"; ((IDX++)) ;;
# Target: `desktop:<platforms>` enables a subset of desktop platforms, split by `+`
desktop:*)
WEB="false"
PLATFORMS="${WORDS[$IDX]#desktop:}"
IFS='+' read -ra PARTS <<< "$PLATFORMS"
for PART in "${PARTS[@]}"; do
case "$PART" in
"windows") WINDOWS="true" ;;
"mac") MAC="true" ;;
"linux") LINUX="true" ;;
*) echo "::error::Unrecognized platform: $PART"; exit 1 ;;
esac
done
((IDX++))
;;
esac
# Parse profile (optional, defaults to `release` if omitted)
case "${WORDS[$IDX]:-}" in
"debug") DEBUG="true"; ((IDX++)) ;;
"release") ((IDX++)) ;;
esac
# Reject any unexpected trailing words
if [[ $IDX -lt ${#WORDS[@]} ]]; then
echo "::error::Unexpected argument: ${WORDS[$IDX]}"
exit 1
fi
# Write parsed build flags to job outputs
echo "web=$WEB" >> $GITHUB_OUTPUT
echo "windows=$WINDOWS" >> $GITHUB_OUTPUT
echo "mac=$MAC" >> $GITHUB_OUTPUT
echo "linux=$LINUX" >> $GITHUB_OUTPUT
echo "debug=$DEBUG" >> $GITHUB_OUTPUT
# Fetch the PR's head branch and repo (needed for forked PRs where the code lives in another repo)
RESPONSE=$(curl -L -H 'Accept: application/vnd.github+json' -H 'X-GitHub-Api-Version: 2022-11-28' https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.issue.number }})
echo "repo=$(echo $RESPONSE | jq -r '.head.repo.full_name')" >> $GITHUB_OUTPUT
echo "ref=$(echo $RESPONSE | jq -r '.head.ref')" >> $GITHUB_OUTPUT
- name: 💬 Edit comment with workflow run link
uses: actions/github-script@v8
with:
script: |
github.rest.issues.updateComment({
comment_id: ${{ github.event.comment.id }},
owner: context.repo.owner,
repo: context.repo.repo,
body: '!build ([Run ID ' + context.runId + '](https://github.com/GraphiteEditor/Graphite/actions/runs/' + context.runId + '))'
body: '${{ github.event.comment.body }} ([Run ID ' + context.runId + '](https://github.com/GraphiteEditor/Graphite/actions/runs/' + context.runId + '))'
});
- name: 🌐 Build Graphite web code
env:
NODE_ENV: production
if: ${{ success() || failure()}}
run: mold -run cargo run ${{ steps.build_command.outputs.command }}
- name: ❗ Warn on build failure
if: ${{ failure() }}
uses: actions/github-script@v6
with:
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: 'The build process has failed. Please check the [build logs](https://github.com/GraphiteEditor/Graphite/actions/runs/' + context.runId + ') for details.'
});
- name: 📤 Publish to Cloudflare Pages
id: cloudflare
uses: cloudflare/pages-action@1
continue-on-error: true
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
gitHubToken: ${{ secrets.GITHUB_TOKEN }}
projectName: graphite-dev
directory: frontend/dist
- name: ❗ Warn on publish failure
if: ${{ failure() }}
uses: actions/github-script@v6
with:
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: 'The deployment to Cloudflare Pages has failed. Please check the [build logs](https://github.com/GraphiteEditor/Graphite/actions/runs/' + context.runId + ') for details.
});
- name: 💬 Comment build link
uses: actions/github-script@v6
with:
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: '| 📦 **Build Complete for** ${{ steps.commit_info.outputs.sha }} |\n|-|\n| ${{ steps.cloudflare.outputs.url }} |'
})
invoke-build:
needs: setup
uses: ./.github/workflows/build.yml
secrets: inherit
with:
web: ${{ needs.setup.outputs.web == 'true' }}
windows: ${{ needs.setup.outputs.windows == 'true' }}
mac: ${{ needs.setup.outputs.mac == 'true' }}
linux: ${{ needs.setup.outputs.linux == 'true' }}
debug: ${{ needs.setup.outputs.debug == 'true' }}
checkout_repo: ${{ needs.setup.outputs.repo }}
checkout_ref: ${{ needs.setup.outputs.ref }}
pr_number: ${{ github.event.issue.number }}
@@ -1,4 +1,4 @@
name: Clippy Check
name: "Clippy Check"
on:
pull_request:
@@ -15,7 +15,7 @@ jobs:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v6
- name: Install Rust
uses: actions-rs/toolchain@v1
@@ -52,7 +52,7 @@ jobs:
fi
- name: Delete previous comments
uses: actions/github-script@v6
uses: actions/github-script@v8
with:
github-token: ${{secrets.GITHUB_TOKEN}}
script: |
@@ -76,7 +76,7 @@ jobs:
- name: Comment PR
if: steps.clippy.outputs.CLIPPY_ISSUES_FOUND == 'true'
uses: actions/github-script@v6
uses: actions/github-script@v8
with:
github-token: ${{secrets.GITHUB_TOKEN}}
script: |
@@ -1,4 +1,4 @@
name: Profiling Changes
name: "Profiling Changes"
on:
pull_request:
@@ -15,7 +15,7 @@ jobs:
runs-on: ubuntu-latest
continue-on-error: true
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
with:
fetch-depth: 0
@@ -35,15 +35,14 @@ jobs:
- name: Cache iai-callgrind binary
id: cache-iai
uses: actions/cache@v4
uses: actions/cache@v5
with:
path: ~/.cargo/bin/iai-callgrind-runner
key: ${{ runner.os }}-iai-callgrind-runner-0.16.1
- name: Install iai-callgrind
if: steps.cache-iai.outputs.cache-hit != 'true'
run: |
cargo install [email protected]
run: cargo install [email protected]
- name: Checkout master branch
run: |
@@ -65,7 +64,7 @@ jobs:
- name: Cache benchmark baselines
id: cache-benchmark-baselines
uses: actions/cache@v4
uses: actions/cache@v5
with:
path: target/iai
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
@@ -84,8 +83,7 @@ jobs:
cargo bench --bench run_cached_iai -- --save-baseline=master
- name: Checkout PR branch
run: |
git checkout ${{ github.event.pull_request.head.sha }}
run: git checkout ${{ github.event.pull_request.head.sha }}
- name: Run PR benchmarks
run: |
@@ -100,7 +98,7 @@ jobs:
- name: Make old comments collapsed by default
# Only run if we have write permissions (not a fork)
if: github.event.pull_request.head.repo.full_name == github.repository
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
github-token: ${{secrets.GITHUB_TOKEN}}
script: |
@@ -126,7 +124,7 @@ jobs:
- name: Analyze profiling changes
id: analyze
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const fs = require('fs');
@@ -185,7 +183,7 @@ jobs:
- name: Comment PR
if: github.event.pull_request.head.repo.full_name == github.repository
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
github-token: ${{secrets.GITHUB_TOKEN}}
script: |
@@ -335,7 +333,7 @@ jobs:
- name: Fail on significant regressions
if: steps.analyze.outputs.has-significant-changes == 'true'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const regressionDetails = JSON.parse('${{ steps.analyze.outputs.regression-details }}');
-119
View File
@@ -1,119 +0,0 @@
name: "Deploy Master"
on:
push:
branches:
- master
env:
CARGO_TERM_COLOR: always
INDEX_HTML_HEAD_REPLACEMENT: <script defer data-domain="dev.graphite.art" data-api="https://graphite.art/visit/event" src="https://graphite.art/visit/script.hash.js"></script>
jobs:
deploy:
runs-on: [self-hosted, target/wasm]
permissions:
contents: write
deployments: write
actions: write
env:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
SCCACHE_DIR: /var/lib/github-actions/.cache
steps:
- name: 📥 Clone and checkout repository
uses: actions/checkout@v3
- name: 🗑 Clear wasm-bindgen cache
run: rm -r ~/.cache/.wasm-pack || true
- name: 🟢 Install the latest Node.js
uses: actions/setup-node@v4
with:
node-version: "latest"
- name: 🚧 Install build dependencies
run: |
cd frontend
npm run setup
- name: 🦀 Install the latest Rust
run: |
rustup update stable
- name: ✂ Replace template in <head> of index.html
run: |
sed -i "s|<!-- INDEX_HTML_HEAD_REPLACEMENT -->|$INDEX_HTML_HEAD_REPLACEMENT|" frontend/index.html
- name: 🌐 Build Graphite web code
env:
NODE_ENV: production
run: mold -run cargo run build web
- name: 📤 Publish to Cloudflare Pages
id: cloudflare
uses: cloudflare/pages-action@1
continue-on-error: true
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
gitHubToken: ${{ secrets.GITHUB_TOKEN }}
projectName: graphite-dev
directory: frontend/dist
- name: 💬 Comment build link URL to commit hash page on GitHub
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh api \
-X POST \
-H "Accept: application/vnd.github+json" \
/repos/${{ github.repository }}/commits/$(git rev-parse HEAD)/comments \
-f body="| 📦 **Build Complete for** $(git rev-parse HEAD) |
|-|
| ${{ steps.cloudflare.outputs.url }} |"
- name: 📃 Generate code documentation info for website
run: |
cd tools/editor-message-tree
cargo run
cd ../..
mkdir -p artifacts-generated
mv website/generated/hierarchical_message_system_tree.txt artifacts-generated/hierarchical_message_system_tree.txt
- name: 💿 Obtain cache of auto-generated code docs artifacts, to check if they've changed
id: cache-website-code-docs
uses: actions/cache/restore@v3
with:
path: artifacts
key: website-code-docs
- name: 🔍 Check if auto-generated code docs artifacts changed
id: website-code-docs-changed
run: |
if ! diff --brief --recursive artifacts-generated artifacts; then
echo "Auto-generated code docs artifacts have changed."
rm -rf artifacts
mv artifacts-generated artifacts
echo "changed=true" >> $GITHUB_OUTPUT
else
echo "Auto-generated code docs artifacts have not changed."
rm -rf artifacts
rm -rf artifacts-generated
fi
- name: 💾 Save cache of auto-generated code docs artifacts
if: steps.website-code-docs-changed.outputs.changed == 'true'
uses: actions/cache/save@v3
with:
path: artifacts
key: ${{ steps.cache-website-code-docs.outputs.cache-primary-key }}
- name: ♻️ Trigger website rebuild if the auto-generated code docs artifacts have changed
if: steps.website-code-docs-changed.outputs.changed == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
rm -rf artifacts
gh workflow run website.yml --ref master
+9 -9
View File
@@ -25,16 +25,16 @@ jobs:
SCCACHE_DIR: /var/lib/github-actions/.cache
steps:
- name: 📥 Clone and checkout repository
uses: actions/checkout@v3
- name: 📥 Clone repository
uses: actions/checkout@v6
- name: 🦀 Install the latest Rust
run: |
echo "Initial system version:"
rustc --version
rustup update stable
echo "Latest updated version:"
rustc --version
- name: 🦀 Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: stable
override: true
cache: false
rustflags: ""
- name: 📦 Run sccache-cache
uses: mozilla-actions/[email protected]
+11 -6
View File
@@ -1,4 +1,4 @@
name: Provide Shaders
name: "Provide Shaders"
on:
push:
@@ -12,14 +12,19 @@ jobs:
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: DeterminateSystems/nix-installer-action@main
- uses: DeterminateSystems/magic-nix-cache-action@main
- name: 📥 Clone repository
uses: actions/checkout@v6
- name: Build graphene raster nodes shaders
- name: ❄ Install Nix
uses: DeterminateSystems/nix-installer-action@main
- name: 💾 Set up Nix cache
uses: DeterminateSystems/magic-nix-cache-action@main
- name: 🏗 Build graphene raster nodes shaders
run: nix build .#graphite-raster-nodes-shaders && cp result raster_nodes_shaders_entrypoint.wgsl
- name: Upload graphene raster nodes shaders to artifacts repository
- name: 📤 Upload graphene raster nodes shaders to artifacts repository
run: |
bash .github/workflows/scripts/artifact-upload.bash \
${{ vars.ARTIFACTS_REPO_OWNER }} \
+16 -46
View File
@@ -1,6 +1,7 @@
name: "Website"
on:
workflow_dispatch: {}
push:
branches:
- master
@@ -9,7 +10,6 @@ on:
pull_request:
paths:
- website/**
workflow_dispatch: {}
env:
CARGO_TERM_COLOR: always
INDEX_HTML_HEAD_INCLUSION: <script defer data-domain="graphite.art" data-api="/visit/event" src="/visit/script.hash.js"></script>
@@ -23,16 +23,13 @@ jobs:
pull-requests: write
steps:
- name: 📥 Clone and checkout repository
uses: actions/checkout@v3
- name: 📥 Clone repository
uses: actions/checkout@v6
# We can remove this step once `ubuntu-latest` has Node.js 22 or newer for its native TypeScript support. See:
# https://github.com/actions/runner-images?tab=readme-ov-file#available-images
# https://nodejs.org/en/learn/typescript/run-natively
- name: 📦 Install the latest Node.js
uses: actions/setup-node@v4
- name: 🟢 Install Node.js
uses: actions/setup-node@v6
with:
node-version: "latest"
node-version-file: .nvmrc
- name: 🕸 Install Zola
uses: taiki-e/install-action@v2
@@ -52,58 +49,31 @@ jobs:
# Remove the INDEX_HTML_HEAD_INCLUSION environment variable for build links (not master deploys)
git rev-parse --abbrev-ref HEAD | grep master > /dev/null || export INDEX_HTML_HEAD_INCLUSION=""
- name: 💿 Obtain cache of auto-generated code docs artifacts
id: cache-website-code-docs
uses: actions/cache/restore@v3
with:
path: artifacts
key: website-code-docs
- name: 📁 Fallback in case auto-generated code docs artifacts weren't cached
if: steps.cache-website-code-docs.outputs.cache-hit != 'true'
- name: 🦀 Produce auto-generated code docs data
run: |
echo "🦀 Initial system version of Rust:"
rustc --version
rustup update stable
echo "🦀 Latest updated version of Rust:"
rustc --version
cd tools/editor-message-tree
cargo run
cd ../..
mkdir artifacts
mv website/generated/hierarchical_message_system_tree.txt artifacts/hierarchical_message_system_tree.txt
cargo run -p crate-hierarchy-viz -- website/generated
cargo run -p editor-message-tree -- website/generated
- name: 🚚 Move `artifacts` contents to website/generated
run: |
mkdir -p website/generated
mv artifacts/* website/generated/
- name: 🔧 Build auto-generated code docs artifacts into HTML
- name: 🔧 Install website npm dependencies
run: |
cd website
npm run generate-editor-structure
npm ci
- name: 📃 Generate node catalog documentation
run: |
cd tools/node-docs
cargo run
run: cargo run -p node-docs -- website/content/learn/node-catalog
- name: 🌐 Build Graphite website with Zola
env:
MODE: prod
run: |
cd website
npm ci
npm run check
zola --config config.toml build --minify
- name: 📤 Publish to Cloudflare Pages
id: cloudflare
uses: cloudflare/pages-action@1
continue-on-error: true
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
gitHubToken: ${{ secrets.GITHUB_TOKEN }}
projectName: graphite-website
directory: website/public
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
run: npx wrangler@3 pages deploy "website/public" --project-name="graphite-website" --commit-dirty=true
+4 -2
View File
@@ -59,8 +59,10 @@ in
graphite-dev = (lib.call ./pkgs/graphite.nix) { dev = true; };
graphite-raster-nodes-shaders = lib.call ./pkgs/graphite-raster-nodes-shaders.nix;
graphite-branding = lib.call ./pkgs/graphite-branding.nix;
graphite-bundle = lib.call ./pkgs/graphite-bundle.nix;
graphite-flatpak-manifest = lib.call ./pkgs/graphite-flatpak-manifest.nix;
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
graphite-dev-bundle = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
graphite-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { };
graphite-dev-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { graphite-bundle = graphite-dev-bundle; };
# TODO: graphene-cli = lib.call ./pkgs/graphene-cli.nix;
+3 -1
View File
@@ -4,6 +4,9 @@
system,
...
}:
{
graphite ? self.packages.${system}.graphite,
}:
let
bundle =
{
@@ -13,7 +16,6 @@ let
}:
(
let
graphite = self.packages.${system}.graphite;
tar = if compression == null then archive else true;
nameArchiveSuffix = if tar then ".tar" else "";
nameCompressionSuffix = if compression == null then "" else "." + compression;
+4 -1
View File
@@ -4,6 +4,9 @@
system,
...
}:
{
graphite-bundle ? self.packages.${system}.graphite-bundle,
}:
(pkgs.formats.json { }).generate "art.graphite.Graphite.json" {
app-id = "art.graphite.Graphite";
@@ -30,7 +33,7 @@
sources = [
{
type = "archive";
path = self.packages.${system}.graphite-bundle.tar;
path = graphite-bundle.tar;
strip-components = 0;
}
];
+1 -1
View File
@@ -32,7 +32,7 @@ let
];
buildInputs = [ pkgs.openssl ];
env.CARGO_PROFILE = if dev then "dev" else "release";
cargoExtraArgs = "--target wasm32-unknown-unknown -p graphite-wasm --no-default-features --features native";
cargoExtraArgs = "--target wasm32-unknown-unknown -p graphite-wasm-wrapper --no-default-features --features native";
doCheck = false;
};
resources = deps.crane.lib.buildPackage (
+1 -1
View File
@@ -1 +1 @@
20
24
Generated
+29 -23
View File
@@ -384,9 +384,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "aws-lc-rs"
version = "1.16.0"
version = "1.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9a7b350e3bb1767102698302bc37256cbd48422809984b98d292c40e2579aa9"
checksum = "a054912289d18629dc78375ba2c3726a3afe3ff71b4edba9dedfca0e3446d1fc"
dependencies = [
"aws-lc-sys",
"zeroize",
@@ -394,9 +394,9 @@ dependencies = [
[[package]]
name = "aws-lc-sys"
version = "0.37.1"
version = "0.39.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b092fe214090261288111db7a2b2c2118e5a7f30dc2569f1732c4069a6840549"
checksum = "1fa7e52a4c5c547c741610a2c6f123f3881e409b714cd27e6798ef020c514f0a"
dependencies = [
"cc",
"cmake",
@@ -585,9 +585,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "bytes"
version = "1.10.1"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "bzip2"
@@ -1106,7 +1106,7 @@ name = "crate-hierarchy-viz"
version = "0.0.0"
dependencies = [
"anyhow",
"clap",
"glob",
"serde",
"toml 0.8.23",
]
@@ -1291,9 +1291,9 @@ checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
[[package]]
name = "deranged"
version = "0.4.0"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c9e6a11ca8224451684bc0d7d5a7adbf8f2fd6887261a1cfc3c0432f9d4068e"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
dependencies = [
"powerfmt",
]
@@ -2064,6 +2064,12 @@ dependencies = [
"serde",
]
[[package]]
name = "glob"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]]
name = "glow"
version = "0.16.0"
@@ -2433,7 +2439,7 @@ dependencies = [
]
[[package]]
name = "graphite-wasm"
name = "graphite-wasm-wrapper"
version = "0.0.0"
dependencies = [
"graph-craft",
@@ -3610,9 +3616,9 @@ dependencies = [
[[package]]
name = "num-conv"
version = "0.1.0"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050"
[[package]]
name = "num-derive"
@@ -4960,9 +4966,9 @@ dependencies = [
[[package]]
name = "rustls"
version = "0.23.31"
version = "0.23.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0ebcbd2f03de0fc1122ad9bb24b127a5a6cd51d72604a3f3c50ac459762b6cc"
checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"
dependencies = [
"aws-lc-rs",
"log",
@@ -5034,9 +5040,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
[[package]]
name = "rustls-webpki"
version = "0.103.4"
version = "0.103.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a17884ae0c1b773f1ccd2bd4a8c72f16da897310a98b0e84bf349ad5ead92fc"
checksum = "df33b2b81ac578cabaf06b89b0631153a3f416b0a886e8a7a1707fb51abbd1ef"
dependencies = [
"aws-lc-rs",
"ring",
@@ -5863,30 +5869,30 @@ dependencies = [
[[package]]
name = "time"
version = "0.3.41"
version = "0.3.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7619e19bc266e0f9c5e6686659d394bc57973859340060a69221e57dbc0c40"
checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"
dependencies = [
"deranged",
"itoa",
"num-conv",
"powerfmt",
"serde",
"serde_core",
"time-core",
"time-macros",
]
[[package]]
name = "time-core"
version = "0.1.4"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9e9a38711f559d9e3ce1cdb06dd7c5b8ea546bc90052da6d06bb76da74bb07c"
checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"
[[package]]
name = "time-macros"
version = "0.2.22"
version = "0.2.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3526739392ec93fd8b359c8e98514cb3e8e021beb4e5f597b00a0221f8ed8a49"
checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215"
dependencies = [
"num-conv",
"time-core",
+2 -2
View File
@@ -8,7 +8,7 @@ members = [
"desktop/platform/mac",
"desktop/platform/win",
"editor",
"frontend/wasm",
"frontend/wrapper",
"libraries/dyn-any",
"libraries/math-parser",
"node-graph/libraries/*",
@@ -30,7 +30,7 @@ members = [
]
default-members = [
"editor",
"frontend/wasm",
"frontend/wrapper",
"libraries/dyn-any",
"libraries/math-parser",
"node-graph/graph-craft",
+4 -1
View File
@@ -39,7 +39,10 @@ db-urls = ["https://github.com/rustsec/advisory-db"]
# A list of advisory IDs to ignore. Note that ignored advisories will still
# output a note when they are encountered.
ignore = [
"RUSTSEC-2024-0436", # Unmaintained but still fully functional crate `paste`
"RUSTSEC-2024-0388", # Unmaintained `derivative`, used directly by graphite-editor and graphite-desktop
"RUSTSEC-2024-0436", # Unmaintained `paste`, pulled in by dependencies `metal` and `wgpu-hal`
"RUSTSEC-2025-0134", # Unmaintained `rustls-pemfile`, pulled in by build dependency `download-cef`
"RUSTSEC-2025-0141", # Unmaintained `bincode`, pulled in by dev dependency `iai-callgrind`
]
# Threshold for security vulnerabilities, any vulnerability with a CVSS score
# lower than the range specified will be ignored. Note that ignored advisories
+1
View File
@@ -55,6 +55,7 @@ fn remove_unnecessary_cef_files(app_dir: &Path) -> Result<(), Box<dyn Error>> {
fs::remove_file(app_dir.join("bootstrapc.exe"))?;
fs::remove_file(app_dir.join("bootstrap.exe"))?;
fs::remove_file(app_dir.join("libcef.lib"))?;
fs::remove_file(app_dir.join("CREDITS.html"))?;
Ok(())
}
+1 -2
View File
@@ -29,9 +29,8 @@ impl CefContext for SingleThreadedCefContext {
host.set_zoom_level(view_info.zoom());
host.was_resized();
// Fix for CEF not updating the view after resize on windows and mac
// Fix for CEF not updating the view after resize
// TODO: remove once https://github.com/chromiumembedded/cef/issues/3822 is fixed
#[cfg(any(target_os = "windows", target_os = "macos"))]
host.invalidate(cef::PaintElementType::default());
}
+1 -1
View File
@@ -114,7 +114,7 @@ pub fn start() {
match exit_reason {
app::ExitReason::Restart | app::ExitReason::UiAccelerationFailure => {
tracing::error!("Restarting application");
tracing::info!("Restarting application");
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
#[cfg(target_family = "unix")]
let _ = std::os::unix::process::CommandExt::exec(&mut command);
+2
View File
@@ -71,6 +71,8 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
if (viewport_srgb.a < 0.001) {
viewport_srgb = constants.background_color;
} else if (viewport_srgb.a < 0.999) {
viewport_srgb = blend(viewport_srgb, constants.background_color);
}
if (overlay_srgb.a < 0.001) {
@@ -1,7 +1,6 @@
#[cfg(target_os = "macos")]
use graphite_editor::messages::layout::utility_types::layout_widget::LayoutTarget;
use graphite_editor::messages::prelude::FrontendMessage;
use std::path::PathBuf;
use super::DesktopWrapperMessageDispatcher;
use super::messages::{DesktopFrontendMessage, Document, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
@@ -25,7 +24,13 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
context: OpenFileDialogContext::Import,
});
}
FrontendMessage::TriggerSaveDocument { document_id, name, path, content } => {
FrontendMessage::TriggerSaveDocument {
document_id,
name,
path,
folder,
content,
} => {
let content = content.into_vec();
if let Some(path) = path {
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
@@ -33,7 +38,7 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
title: "Save Document".to_string(),
default_filename: name,
default_folder: path.and_then(|p| p.parent().map(PathBuf::from)),
default_folder: folder,
filters: vec![FileFilter {
name: "Graphite".to_string(),
extensions: vec!["graphite".to_string()],
@@ -42,12 +47,12 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
});
}
}
FrontendMessage::TriggerSaveFile { name, content } => {
FrontendMessage::TriggerSaveFile { name, folder, content } => {
let content = content.into_vec();
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
title: "Save File".to_string(),
default_filename: name,
default_folder: None,
default_folder: folder,
filters: Vec::new(),
context: SaveFileDialogContext::File { content },
});
+2 -2
View File
@@ -5,10 +5,10 @@ pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
pub use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
pub use graphite_editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState as MouseState, EditorPosition as Position, MouseKeys};
pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMessage;
pub use graphite_editor::messages::prelude::DocumentId;
pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMessage;
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
pub enum DesktopFrontendMessage {
ToWeb(Vec<FrontendMessage>),
OpenLaunchDocuments,
+3 -1
View File
@@ -37,5 +37,7 @@ pub enum DialogMessage {
},
RequestNewDocumentDialog,
RequestPreferencesDialog,
RequestConfirmRestartDialog,
RequestConfirmRestartDialog {
preferences_requiring_restart: Vec<String>,
},
}
@@ -136,11 +136,9 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
self.on_dismiss = Some(PreferencesDialogMessage::Confirm.into());
self.preferences_dialog.send_dialog_to_frontend(responses, preferences);
}
DialogMessage::RequestConfirmRestartDialog => {
DialogMessage::RequestConfirmRestartDialog { preferences_requiring_restart } => {
self.on_dismiss = Some(DialogMessage::Close.into());
let dialog = ConfirmRestartDialog {
changed_settings: vec!["Disable UI Acceleration".into()],
};
let dialog = ConfirmRestartDialog { preferences_requiring_restart };
dialog.send_dialog_to_frontend(responses);
}
}
@@ -28,9 +28,10 @@ impl MessageHandler<PreferencesDialogMessage, PreferencesDialogMessageContext<'_
}
PreferencesDialogMessage::Confirm => {
if let Some(unmodified_preferences) = &self.unmodified_preferences
&& unmodified_preferences.needs_restart(preferences)
&& let preferences_requiring_restart = unmodified_preferences.preferences_requiring_restart(preferences)
&& !preferences_requiring_restart.is_empty()
{
responses.add(DialogMessage::RequestConfirmRestartDialog);
responses.add(DialogMessage::RequestConfirmRestartDialog { preferences_requiring_restart });
} else {
responses.add(DialogMessage::Close);
}
@@ -3,7 +3,7 @@ use crate::messages::prelude::*;
/// A dialog for confirming the restart of the application when changing a preference that requires a restart to take effect.
pub struct ConfirmRestartDialog {
pub changed_settings: Vec<String>,
pub preferences_requiring_restart: Vec<String>,
}
impl DialogLayoutHolder for ConfirmRestartDialog {
@@ -30,7 +30,7 @@ impl DialogLayoutHolder for ConfirmRestartDialog {
impl LayoutHolder for ConfirmRestartDialog {
fn layout(&self) -> Layout {
let changed_settings = "• ".to_string() + &self.changed_settings.join("\n• ");
let changed_settings = "• ".to_string() + &self.preferences_requiring_restart.join("\n• ");
Layout(vec![
LayoutGroup::row(vec![TextLabel::new("Restart to apply changes?").bold(true).multiline(true).widget_instance()]),
@@ -89,10 +89,12 @@ pub enum FrontendMessage {
document_id: DocumentId,
name: String,
path: Option<PathBuf>,
folder: Option<PathBuf>,
content: serde_bytes::ByteBuf,
},
TriggerSaveFile {
name: String,
folder: Option<PathBuf>,
content: serde_bytes::ByteBuf,
},
TriggerExportImage {
@@ -8,6 +8,7 @@ pub enum LayoutMessage {
layout_target: LayoutTarget,
widget_id: WidgetId,
},
ResendAllLayouts,
SendLayout {
layout: Layout,
layout_target: LayoutTarget,
@@ -33,6 +33,20 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
// Resend that diff
self.send_diff(vec![diff], layout_target, responses, action_input_mapping);
}
LayoutMessage::ResendAllLayouts => {
// Collect non-empty layouts and their indices, then clear the stored copies so diffs compute as full re-sends
let layouts_to_resend: Vec<_> = self
.layouts
.iter_mut()
.enumerate()
.filter(|(_, layout)| !layout.0.is_empty())
.map(|(i, layout)| (LayoutTarget::from(i as u8), std::mem::take(layout)))
.collect();
for (layout_target, layout) in layouts_to_resend {
self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping);
}
}
LayoutMessage::SendLayout { layout, layout_target } => {
self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping);
}
@@ -20,10 +20,30 @@ impl core::fmt::Display for WidgetId {
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum LayoutTarget {
macro_rules! define_layout_target {
($($(#[$attr:meta])* $variant:ident),* $(,)?) => {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum LayoutTarget {
$($(#[$attr])* $variant,)*
// KEEP THIS ENUM LAST
// This is a marker that is used to define an array that is used to hold widgets
#[serde(skip)]
_LayoutTargetLength,
}
impl From<u8> for LayoutTarget {
fn from(value: u8) -> Self {
match value {
$(x if x == Self::$variant as u8 => Self::$variant,)*
_ => panic!("Invalid LayoutTarget discriminant: {value}"),
}
}
}
};
}
define_layout_target!(
/// The spreadsheet panel allows for the visualisation of data in the graph.
DataPanel,
/// Contains the action buttons at the bottom of the dialog. Must be shown with the `FrontendMessage::DisplayDialog` message.
@@ -58,12 +78,7 @@ pub enum LayoutTarget {
WelcomeScreenButtons,
/// The color swatch for the working colors and a flip and reset button found at the bottom of the tool shelf.
WorkingColors,
// KEEP THIS ENUM LAST
// This is a marker that is used to define an array that is used to hold widgets
#[serde(skip)]
_LayoutTargetLength,
}
);
/// For use by structs that define a UI widget layout by implementing the layout() function belonging to this trait.
/// The send_layout() function can then be called by other code which is a part of the same struct so as to send the layout to the frontend.
@@ -835,26 +835,28 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
});
}
DocumentMessage::SaveDocument | DocumentMessage::SaveDocumentAs => {
if let DocumentMessage::SaveDocumentAs = message {
self.path = None;
responses.add(PortfolioMessage::AutoSaveActiveDocument);
let path = if let DocumentMessage::SaveDocumentAs = message { None } else { self.path.clone() };
if path.is_some() {
responses.add(DocumentMessage::MarkAsSaved);
}
self.set_save_state(true);
responses.add(PortfolioMessage::AutoSaveActiveDocument);
// Update the save status of the just saved document
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
let folder = self.path.as_ref().and_then(|path| path.parent()).map(|parent| parent.to_path_buf());
responses.add(FrontendMessage::TriggerSaveDocument {
document_id,
name: format!("{}.{}", self.name.clone(), FILE_EXTENSION),
path: self.path.clone(),
path,
folder,
content: self.serialize_document().into_bytes().into(),
})
});
}
DocumentMessage::SavedDocument { path } => {
self.path = path;
responses.add(PortfolioMessage::AutoSaveActiveDocument);
responses.add(DocumentMessage::MarkAsSaved);
// Update the name to match the file stem
let document_name_from_path = self.path.as_ref().and_then(|path| {
@@ -174,7 +174,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
properties: Some("monitor_properties"),
},
DocumentNodeDefinition {
identifier: "Default Network",
identifier: "Custom Node",
category: "General",
node_template: NodeTemplate {
document_node: DocumentNode {
@@ -645,7 +645,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports
let encapsulating_node_id = NodeId::new();
let mut default_node_template = resolve_network_node_type("Default Network").expect("Default Network node should exist").default_node_template();
let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template();
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
log::error!("Could not get center of selected_nodes");
return;
@@ -1521,10 +1521,9 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
for input_index in 0..network_interface.number_of_inputs(selected_node, selection_network_path) {
let input_connector = InputConnector::node(*selected_node, input_index);
// Only disconnect inputs to non selected nodes
if !network_interface
if network_interface
.upstream_output_connector(&input_connector, selection_network_path)
.and_then(|connector| connector.node_id())
.is_some_and(|node_id| all_selected_nodes.contains(&node_id))
.is_some_and(|connector| connector.node_id().map_or(true, |node_id| !all_selected_nodes.contains(&node_id)))
{
responses.add(NodeGraphMessage::DisconnectInput { input_connector });
}
@@ -1949,15 +1948,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
NodeGraphMessage::UpdateBoxSelection => {
if let Some((box_selection_start, _)) = self.box_selection_start {
// The mouse button was released but we missed the pointer up event
// if ((e.buttons & 1) === 0) {
// completeBoxSelection();
// boxSelection = undefined;
// } else if ((e.buttons & 2) !== 0) {
// editor.handle.selectNodes(new BigUint64Array(previousSelection));
// boxSelection = undefined;
// }
let Some(network_metadata) = network_interface.network_metadata(selection_network_path) else {
log::error!("Could not get network metadata in UpdateBoxSelection");
return;
@@ -1796,7 +1796,21 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
if layout.is_empty() {
layout = node_no_properties(node_id, context);
}
let name = context.network_interface.implementation_name(&node_id, context.selection_network_path);
let display_name = context
.network_interface
.node_metadata(&node_id, context.selection_network_path)
.map(|metadata| metadata.persistent_metadata.display_name.as_str());
let implementation_name = context.network_interface.implementation_name(&node_id, context.selection_network_path);
let name = if let Some(display_name) = display_name
&& implementation_name != display_name
&& implementation_name != "Custom Node"
&& !display_name.is_empty()
{
format!("{display_name} ({implementation_name})")
} else {
implementation_name
};
let description = context
.network_interface
@@ -2,7 +2,7 @@ pub mod grid_overlays;
mod overlays_message;
mod overlays_message_handler;
pub mod utility_functions;
// Native (non‑wasm)
// Native (non‑Wasm)
#[cfg(not(target_family = "wasm"))]
pub mod utility_types_native;
#[cfg(not(target_family = "wasm"))]
@@ -4068,8 +4068,8 @@ impl NodeNetworkInterface {
log::error!("Could not get current input in disconnect_input");
return;
};
// Do not disconnect an already disconnected input
if matches!(current_input, NodeInput::Value { .. }) {
// Only disconnect inputs that are actual wire connections (Node or Import)
if !matches!(current_input, NodeInput::Node { .. } | NodeInput::Import { .. }) {
return;
}
@@ -860,6 +860,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::repeat::repeat_on_points::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceOnPointsNode", "core_types::vector::InstanceOnPointsNode"],
},
NodeReplacement {
node: graphene_std::vector::copy_to_points::IDENTIFIER,
aliases: &["graphene_core::vector::CopyToPointsNode", "core_types::vector::CopyToPointsNode"],
},
NodeReplacement {
node: graphene_std::vector::jitter_points::IDENTIFIER,
aliases: &["graphene_core::vector::JitterPointsNode"],
@@ -485,9 +485,10 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
let name = path.file_stem().map(|n| n.to_string_lossy().to_string());
match Self::read_file(&path, content) {
FileContent::Document(content) => {
let document_path = if path.is_absolute() { Some(path) } else { None };
responses.add(PortfolioMessage::OpenDocumentFile {
document_name: name,
document_path: Some(path),
document_path,
document_serialized_content: content,
});
}
@@ -28,14 +28,16 @@ pub struct PreferencesMessageHandler {
}
impl PreferencesMessageHandler {
#[cfg(not(target_os = "macos"))]
pub fn needs_restart(&self, other: &Self) -> bool {
self.disable_ui_acceleration != other.disable_ui_acceleration
}
#[cfg(target_os = "macos")]
pub fn needs_restart(&self, other: &Self) -> bool {
self.disable_ui_acceleration != other.disable_ui_acceleration || self.vsync != other.vsync
pub fn preferences_requiring_restart(&self, other: &Self) -> Vec<String> {
let mut requiring_restart = Vec::new();
if self.disable_ui_acceleration != other.disable_ui_acceleration {
requiring_restart.push("Disable UI Acceleration");
}
#[cfg(target_os = "macos")]
if self.vsync != other.vsync {
requiring_restart.push("Enable V-Sync");
}
requiring_restart.into_iter().map(String::from).collect()
}
pub fn get_selection_mode(&self) -> SelectionMode {
+10 -11
View File
@@ -332,7 +332,7 @@ impl NodeGraphExecutor {
if let Some(export_config) = execution_context.export_config {
// Special handling for exporting the artwork
self.process_export(node_graph_output, export_config, responses)?;
self.process_export(node_graph_output, export_config, document, responses)?;
} else {
self.process_node_graph_output(node_graph_output, responses)?;
}
@@ -435,13 +435,11 @@ impl NodeGraphExecutor {
Ok(())
}
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, responses: &mut VecDeque<Message>) -> Result<(), String> {
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) -> Result<(), String> {
let ExportConfig {
file_type,
name,
size,
#[cfg(feature = "gpu")]
transparent_background,
artboard_name,
artboard_count,
..
@@ -457,6 +455,7 @@ impl NodeGraphExecutor {
_ => name,
};
let name = format!("{base_name}.{file_extension}");
let folder = document.path.as_ref().and_then(|path| path.parent()).map(|parent| parent.to_path_buf());
match node_graph_output {
TaggedValue::RenderOutput(RenderOutput {
@@ -466,6 +465,7 @@ impl NodeGraphExecutor {
if file_type == FileType::Svg {
responses.add(FrontendMessage::TriggerSaveFile {
name,
folder,
content: svg.into_bytes().into(),
});
} else {
@@ -491,12 +491,7 @@ impl NodeGraphExecutor {
match file_type {
FileType::Png => {
let result = if transparent_background {
image.write_to(&mut cursor, ImageFormat::Png)
} else {
let image: RgbImage = image.convert();
image.write_to(&mut cursor, ImageFormat::Png)
};
let result = image.write_to(&mut cursor, ImageFormat::Png);
if let Err(err) = result {
return Err(format!("Failed to encode PNG: {err}"));
}
@@ -513,7 +508,11 @@ impl NodeGraphExecutor {
}
}
responses.add(FrontendMessage::TriggerSaveFile { name, content: encoded.into() });
responses.add(FrontendMessage::TriggerSaveFile {
name,
folder,
content: encoded.into(),
});
}
_ => {
return Err(format!("Incorrect render type for exporting to an SVG ({file_type:?}, {node_graph_output})"));
+1 -1
View File
@@ -10,7 +10,7 @@ Images that are used in components and embedded into the application bundle by t
Source code for the web app in the form of Svelte components and [TypeScript](https://www.typescriptlang.org/) files.
## WebAssembly wrapper: `wasm/`
## Editor wrapper: `wrapper/`
Wraps the editor backend codebase (`/editor`) and provides a JS-centric API for the web app to use as an entry point, unburdened by Rust's complex data types that are incompatible with JS data types. Bindings (JS functions that call into the Wasm module) are provided by [wasm-bindgen](https://rustwasm.github.io/docs/wasm-bindgen/) in concert with [wasm-pack](https://github.com/rustwasm/wasm-pack).
-1
View File
@@ -7,7 +7,6 @@ import https from "https";
import path from "path";
import { fileURLToPath } from "url";
import zlib from "zlib";
import * as tar from "tar";
const __filename = fileURLToPath(import.meta.url);
+26 -10
View File
@@ -6,6 +6,17 @@ import pluginSvelte from "eslint-plugin-svelte";
import globals from "globals";
import ts from "typescript-eslint";
const importOrder = {
alphabetize: { order: "asc", caseInsensitive: true },
"newlines-between": "never",
warnOnUnassignedImports: true,
pathGroups: [
{ pattern: "/**", group: "internal" },
{ pattern: "/../**", group: "internal" },
],
pathGroupsExcludedImportTypes: [],
};
export default defineConfig([
js.configs.recommended,
ts.configs.recommended,
@@ -52,7 +63,15 @@ export default defineConfig([
"no-bitwise": "off",
"no-shadow": "off",
"no-use-before-define": "off",
"no-restricted-imports": ["error", { patterns: [".*", "!@graphite/*"] }],
"no-restricted-imports": [
"error",
{
patterns: [
{ group: ["./**", "../**"], message: "\nImports must be absolute (e.g. '/src/<subpath>') not relative (e.g. './<subpath>')." },
{ group: ["src/**", "assets/**", "wrapper/**"], message: "\nLocal imports must start with '/' (e.g. '/src/<subpath>' not 'src/<subpath>')." },
],
},
],
// TypeScript plugin config (for TS-specific linting)
"@typescript-eslint/indent": "off",
@@ -70,6 +89,7 @@ export default defineConfig([
ignoreRestSiblings: true,
},
],
"@typescript-eslint/no-non-null-assertion": "error",
"@typescript-eslint/consistent-type-imports": "error",
"@typescript-eslint/consistent-type-definitions": ["error", "type"],
"@typescript-eslint/consistent-type-assertions": ["error", { assertionStyle: "never" }],
@@ -94,17 +114,13 @@ export default defineConfig([
"import/prefer-default-export": "off",
"import/no-relative-packages": "error",
"import/no-named-as-default-member": "off",
"import/order": [
"error",
{
alphabetize: { order: "asc", caseInsensitive: true },
pathGroups: [{ pattern: "**/*.svelte", group: "unknown", position: "after" }],
"newlines-between": "always-and-inside-groups",
warnOnUnassignedImports: true,
},
],
"import/order": ["error", importOrder],
},
},
{
files: ["**/icons.ts"],
rules: { "import/order": ["error", { ...importOrder, "newlines-between": "ignore" }] },
},
{
files: ["**/*.svelte"],
languageOptions: {
+1 -5
View File
@@ -32,11 +32,7 @@ if (isInstallNeeded()) {
console.log("Finished installing npm packages.");
} catch (_) {
// eslint-disable-next-line no-console
console.error(
"\n\n" +
"------------------------------------------------------------> " +
"Failed to install npm packages. Please delete the `node_modules` folder and run `npm install` from the `/frontend` directory.",
);
console.error("\n\n--------------------> Failed to install npm packages. Please delete `/frontend/node_modules` then try again.\n\n");
process.exit(1);
}
} else {
+1281 -1361
View File
File diff suppressed because it is too large. Load diff
+20 -26
View File
@@ -19,46 +19,40 @@
"fix": "eslint --fix",
"---------- INTERNAL ----------": "",
"setup": "node package-installer.js && node branding-installer.js",
"native:build-dev": "wasm-pack build ./wasm --dev --target=web --no-default-features --features native && vite build --mode native",
"native:build-production": "wasm-pack build ./wasm --release --target=web --no-default-features --features native && vite build --mode native",
"wasm:build-dev": "wasm-pack build ./wasm --dev --target=web",
"wasm:build-production": "wasm-pack build ./wasm --release --target=web",
"wasm:watch-dev": "cargo watch --postpone --watch-when-idle --workdir=wasm --shell \"wasm-pack build . --dev --target=web -- --color=always\"",
"wasm:watch-production": "cargo watch --postpone --watch-when-idle --workdir=wasm --shell \"wasm-pack build . --release --target=web -- --color=always\""
"native:build-dev": "wasm-pack build ./wrapper --dev --target=web --no-default-features --features native && vite build --mode native",
"native:build-production": "wasm-pack build ./wrapper --release --target=web --no-default-features --features native && vite build --mode native",
"wasm:build-dev": "wasm-pack build ./wrapper --dev --target=web",
"wasm:build-production": "wasm-pack build ./wrapper --release --target=web",
"wasm:watch-dev": "cargo watch --postpone --watch-when-idle --workdir=wrapper --shell \"wasm-pack build . --dev --target=web -- --color=always\"",
"wasm:watch-production": "cargo watch --postpone --watch-when-idle --workdir=wrapper --shell \"wasm-pack build . --release --target=web -- --color=always\""
},
"//": "NOTE: `source-sans-pro` is never to be upgraded to 3.x because that renders a pixel above its intended position.",
"//": "NOTE: `source-sans-pro` is never to be upgraded to 3.x because that renders 1px above its intended position.",
"dependencies": {
"idb-keyval": "^6.2.2",
"source-code-pro": "2.42.0",
"source-sans-pro": "2.45.0"
},
"devDependencies": {
"@eslint/compat": "^2.0.1",
"@eslint/eslintrc": "^3.3.3",
"@eslint/js": "^9.39.2",
"@sveltejs/vite-plugin-svelte": "^6.2.4",
"@types/node": "^25.0.9",
"buffer": "^6.0.3",
"@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.5.0",
"concurrently": "^9.2.1",
"eslint": "^9.39.2",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-prettier": "^5.5.5",
"eslint-plugin-svelte": "^3.14.0",
"globals": "^17.0.0",
"svelte-check": "^4.4.4",
"eslint-plugin-svelte": "^3.16.0",
"globals": "^17.4.0",
"license-checker-rseidelsohn": "^4.4.2",
"postcss": "^8.5.6",
"prettier": "^3.8.0",
"prettier-plugin-svelte": "^3.4.1",
"process": "^0.11.10",
"sass": "^1.97.2",
"svelte": "5.47.1",
"prettier": "^3.8.1",
"prettier-plugin-svelte": "^3.5.1",
"sass": "^1.98.0",
"svelte": "^5.54.1",
"svelte-check": "^4.4.5",
"svelte-preprocess": "^6.0.3",
"tar": "^7.5.4",
"ts-node": "^10.9.2",
"tar": "^7.5.12",
"typescript": "^5.9.3",
"typescript-eslint": "^8.53.1",
"vite": "^7.3.1",
"typescript-eslint": "^8.57.1",
"vite": "^8.0.1",
"vite-multiple-assets": "2.2.6"
},
"homepage": "https://graphite.art",
+27 -12
View File
@@ -1,25 +1,40 @@
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import Editor from "/src/components/Editor.svelte";
import { createSubscriptionsRouter } from "/src/subscriptions-router";
import type { MessageName, SubscriptionsRouter } from "/src/subscriptions-router";
import { loadDemoArtwork } from "/src/utility-functions/network";
import { operatingSystem } from "/src/utility-functions/platform";
import init, { EditorWrapper, receiveNativeMessage } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { FrontendMessage } from "/wrapper/pkg/graphite_wasm_wrapper";
import { initWasm, createEditor } from "@graphite/editor";
import type { Editor as GraphiteEditor } from "@graphite/editor";
import Editor from "@graphite/components/Editor.svelte";
let editor: GraphiteEditor | undefined = undefined;
let subscriptions: SubscriptionsRouter | undefined = undefined;
let editor: EditorWrapper | undefined = undefined;
onMount(async () => {
await initWasm();
// Initialize the editor wrapper
const wrapper = await init();
for (const [name, f] of Object.entries(wrapper)) {
if (name.startsWith("__node_registry")) f();
}
window.imageCanvases = {};
window.receiveNativeMessage = receiveNativeMessage;
editor = createEditor();
// Create the editor and subscriptions router
const randomSeed = BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER));
subscriptions = createSubscriptionsRouter();
editor = EditorWrapper.create(operatingSystem(), randomSeed, (messageType: MessageName, messageData: FrontendMessage) => {
subscriptions?.handleFrontendMessage(messageType, messageData);
});
await loadDemoArtwork(editor);
});
onDestroy(() => {
// Destroy the Wasm editor handle
editor?.handle.free();
editor?.free();
});
</script>
{#if editor !== undefined}
<Editor {editor} />
{#if subscriptions !== undefined && editor !== undefined}
<Editor {subscriptions} {editor} />
{/if}
+14 -22
View File
@@ -2,47 +2,39 @@
## Svelte components: `components/`
Svelte components that build the Graphite editor GUI. These each contain a TypeScript section, a Svelte-templated HTML template section, and an SCSS stylesheet section. The aim is to avoid implementing much editor business logic here, just enough to make things interactive and communicate to the backend where the real business logic should occur.
Svelte components that build the Graphite editor GUI from layouts, panels, widgets, and menus. These each contain a TypeScript section, a Svelte-templated HTML template section, and an SCSS stylesheet section. The aim is to avoid implementing much editor business logic here, just enough to make things interactive and communicate to the backend where the real business logic should occur.
## I/O managers: `io-managers/`
## Managers: `managers/`
TypeScript files which manage the input/output of browser APIs and link this functionality with the editor backend. These files subscribe to backend events to execute JS APIs, and in response to these APIs or user interactions, they may call functions into the backend (defined in `/frontend/wasm/editor_api.rs`).
TypeScript files, constructed by the editor frontend, which manage the input/output of browser APIs and link this functionality with the editor backend. These files subscribe to frontend messages to execute JS APIs, and in response to these APIs or user interactions, they may call functions in the backend (defined in `/frontend/wrapper/editor_wrapper.rs`).
Each I/O manager is a self-contained module where one instance is created in `Editor.svelte` when it's mounted to the DOM at app startup.
Each manager module stores its dependencies (like `subscriptionsRouter` and `editorWrapper`) in module-level variables and exports a `create*()` and `destroy*()` function pair. `Editor.svelte` calls each `create*()` constructor in its `onMount` and calls each `destroy*()` in its `onDestroy`. Managers replace themselves during HMR updates if they are modified live during development.
During development when HMR (hot-module replacement) occurs, these are also unmounted to clean up after themselves, so they can be mounted again with the updated code. Therefore, any side-effects that these managers cause (e.g. adding event listeners to the page) need a destructor function that cleans them up. The destructor function, when applicable, is returned by the module and automatically called in `Editor.svelte` on unmount.
## Stores: `stores/`
## State providers: `state-providers/`
TypeScript files, constructed by the editor frontend, which provide reactive state to Svelte components. Each module persists a Svelte writable store at module level (surviving HMR via `import.meta.hot.data`) and exports a `create*()` function that sets up frontend message subscriptions and returns `{ subscribe }` (the shape required by Svelte's custom store contract). A corresponding `destroy*()` function is also exported. Some stores also export standalone action functions (like `createCrashDialog()` or `toggleFullscreen()`) as module-level exports.
TypeScript files which provide reactive state and importable functions to Svelte components. Each module defines a Svelte writable store `const { subscribe, update } = writable({ .. });` and exports the `subscribe` method from the module in the returned object. Other functions may also be defined in the module and exported after `subscribe`, which provide a way for Svelte components to call functions to manipulate the state.
In `Editor.svelte`, each store is created synchronously during component initialization (not in `onMount`, since child components need `getContext` access during their own initialization) and passed to Svelte's `setContext()`. Components access stores via calls like `getContext<DialogStore>("dialog")`. Unlike managers, stores do not replace themselves during HMR; instead, `Editor.svelte` is remounted to replace them entirely.
In `Editor.svelte`, an instance of each of these are given to Svelte's `setContext()` function. This allows any component to access the state provider instance using `const exampleStateProvider = getContext<ExampleStateProvider>("exampleStateProvider");`.
## *Managers vs. stores*
## *I/O managers vs. state providers*
*Some state providers, similarly to I/O managers, may subscribe to backend events, call functions from `editor_api.rs` into the backend, and interact with browser APIs and user input. The difference is that state providers are meant to be made available to components via `getContext()` to use them for reactive state, while I/O managers are meant to be self-contained systems that operate for the lifetime of the application and aren't touched by Svelte components.*
*Both managers and stores subscribe to frontend messages and may interact with browser APIs. The difference is that stores expose reactive state to components via `setContext()`/`getContext()`, while managers are self-contained systems that operate for the lifetime of the application and aren't accessed by Svelte components.*
## Utility functions: `utility-functions/`
TypeScript files which define and `export` individual helper functions for use elsewhere in the codebase. These files should not persist state outside each function.
## Wasm editor: `editor.ts`
## Subscriptions router: `subscriptions-router.ts`
Instantiates the Wasm and editor backend instances. The function `initWasm()` asynchronously constructs and initializes an instance of the Wasm bindings JS module provided by wasm-bindgen/wasm-pack. The function `createEditor()` constructs an instance of the editor backend. In theory there could be multiple editor instances sharing the same Wasm module instance. The function returns an object where `raw` is the Wasm memory, `handle` provides access to callable backend functions, and `subscriptions` is the subscription router (described below).
`initWasm()` occurs in `main.ts` right before the Svelte application is mounted, then `createEditor()` is run in `Editor.svelte` during the Svelte app's creation. Similarly to the state providers described above, the editor is given via `setContext()` so other components can get it via `getContext` and call functions on `editor.handle` or `editor.subscriptions`.
## Subscription router: `subscription-router.ts`
Associates messages from the backend with subscribers in the frontend, and routes messages to subscriber callbacks. This module provides a `subscribeFrontendMessage(messageType, callback)` function which JS code throughout the frontend can call to be registered as the exclusive handler for a chosen message type. The router's other function, `handleFrontendMessage(messageType, messageData)`, is called via the callback passed to `EditorHandle.create()` in `editor.ts` when the backend sends a `FrontendMessage`. When this occurs, the subscription router delivers the message to the subscriber by executing its registered `callback` function.
Associates messages from the backend with subscribers in the frontend, and routes messages to subscriber callbacks. This module provides a `subscribeFrontendMessage(messageType, callback)` function which JS code throughout the frontend can call to be registered as the exclusive handler for a chosen message type. The router's other function, `handleFrontendMessage(messageType, messageData)`, is called via the callback passed to `EditorWrapper.create()` in `App.svelte` when the backend sends a `FrontendMessage`. When this occurs, the subscriptions router delivers the message to the subscriber by executing its registered `callback` function.
## Svelte app entry point: `App.svelte`
The entry point for the Svelte application.
The entry point for the Svelte application. Initializes and creates the `EditorWrapper` backend instance and the subscriptions router and renders `Editor.svelte` once both are ready. The `EditorWrapper` is the wasm-bindgen interface to the Rust editor backend (defined in `/frontend/wrapper/editor_wrapper.rs`), providing access to callable backend functions. Both the editor and subscriptions router are passed as props to `Editor.svelte` and set as Svelte contexts for use throughout the component tree.
## Editor base instance: `Editor.svelte`
This is where we define global CSS style rules, create/destroy the editor instance, construct/destruct the I/O managers, and construct and `setContext()` the state providers.
This is where we define global CSS style rules, construct all stores and managers, set store contexts for component access, and call each module's `destroy*()` function on unmount (on HMR during development).
## Global type augmentations: `global.d.ts`
@@ -50,4 +42,4 @@ Extends built-in browser type definitions using TypeScript's interface merging.
## JS bundle entry point: `main.ts`
The entry point for the entire project's code bundle. Here we simply mount the Svelte application with `export default mount(App, { target: document.body });`.
The entry point for the entire project's code bundle. Mounts the Svelte application with `export default mount(App, { target: document.body })`.
+67 -53
View File
@@ -1,61 +1,75 @@
<script lang="ts">
import { onMount, onDestroy, setContext } from "svelte";
import MainWindow from "/src/components/window/MainWindow.svelte";
import { createClipboardManager, destroyClipboardManager } from "/src/managers/clipboard";
import { createFontsManager, destroyFontsManager } from "/src/managers/fonts";
import { createHyperlinkManager, destroyHyperlinkManager } from "/src/managers/hyperlink";
import { createInputManager, destroyInputManager } from "/src/managers/input";
import { createLocalizationManager, destroyLocalizationManager } from "/src/managers/localization";
import { createPanicManager, destroyPanicManager } from "/src/managers/panic";
import { createPersistenceManager, destroyPersistenceManager } from "/src/managers/persistence";
import { createAppWindowStore, destroyAppWindowStore } from "/src/stores/app-window";
import { createDialogStore, destroyDialogStore } from "/src/stores/dialog";
import { createDocumentStore, destroyDocumentStore } from "/src/stores/document";
import { createFullscreenStore, destroyFullscreenStore } from "/src/stores/fullscreen";
import { createNodeGraphStore, destroyNodeGraphStore } from "/src/stores/node-graph";
import { createPortfolioStore, destroyPortfolioStore } from "/src/stores/portfolio";
import { createTooltipStore, destroyTooltipStore } from "/src/stores/tooltip";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { Editor } from "@graphite/editor";
import { createClipboardManager } from "@graphite/io-managers/clipboard";
import { createHyperlinkManager } from "@graphite/io-managers/hyperlink";
import { createInputManager } from "@graphite/io-managers/input";
import { createLocalizationManager } from "@graphite/io-managers/localization";
import { createPanicManager } from "@graphite/io-managers/panic";
import { createPersistenceManager } from "@graphite/io-managers/persistence";
import { createAppWindowState } from "@graphite/state-providers/app-window";
import { createDialogState } from "@graphite/state-providers/dialog";
import { createDocumentState } from "@graphite/state-providers/document";
import { createFontsManager } from "/src/io-managers/fonts";
import { createFullscreenState } from "@graphite/state-providers/fullscreen";
import { createNodeGraphState } from "@graphite/state-providers/node-graph";
import { createPortfolioState } from "@graphite/state-providers/portfolio";
import { createTooltipState } from "@graphite/state-providers/tooltip";
import MainWindow from "@graphite/components/window/MainWindow.svelte";
// Graphite Wasm editor
export let editor: Editor;
// Graphite Wasm editor and subscriptions router
export let subscriptions: SubscriptionsRouter;
export let editor: EditorWrapper;
setContext("subscriptions", subscriptions);
setContext("editor", editor);
// State provider systems
let dialog = createDialogState(editor);
setContext("dialog", dialog);
let tooltip = createTooltipState(editor);
setContext("tooltip", tooltip);
let document = createDocumentState(editor);
setContext("document", document);
let fullscreen = createFullscreenState(editor);
setContext("fullscreen", fullscreen);
let nodeGraph = createNodeGraphState(editor);
setContext("nodeGraph", nodeGraph);
let portfolio = createPortfolioState(editor);
setContext("portfolio", portfolio);
let appWindow = createAppWindowState(editor);
setContext("appWindow", appWindow);
// Initialize managers, which are isolated systems that subscribe to backend messages to link them to browser API functionality (like JS events, IndexedDB, etc.)
createClipboardManager(editor);
createHyperlinkManager(editor);
createLocalizationManager(editor);
createPanicManager(editor, dialog);
createPersistenceManager(editor, portfolio);
createFontsManager(editor);
let inputManagerDestructor = createInputManager(editor, dialog, portfolio, document, fullscreen);
const stores = {
dialog: createDialogStore(subscriptions, editor),
tooltip: createTooltipStore(subscriptions),
document: createDocumentStore(subscriptions),
fullscreen: createFullscreenStore(subscriptions),
nodeGraph: createNodeGraphStore(subscriptions),
portfolio: createPortfolioStore(subscriptions, editor),
appWindow: createAppWindowStore(subscriptions),
};
Object.entries(stores).forEach(([key, store]) => setContext(key, store));
onMount(() => {
// Initialize certain setup tasks required by the editor backend to be ready for the user now that the frontend is ready
editor.handle.initAfterFrontendReady();
createClipboardManager(subscriptions, editor);
createHyperlinkManager(subscriptions);
createLocalizationManager(subscriptions, editor);
createPanicManager(subscriptions);
createPersistenceManager(subscriptions, editor, stores.portfolio);
createFontsManager(subscriptions, editor);
createInputManager(subscriptions, editor, stores.dialog, stores.portfolio, stores.document);
// Initialize certain setup tasks required by the editor backend to be ready for the user now that the frontend is ready.
// The backend handles idempotency, so this is safe to call again during HMR re-mounts.
editor.initAfterFrontendReady();
// Re-send all UI layouts from Rust so the frontend has them after an HMR re-mount
editor.resendAllLayouts();
});
onDestroy(() => {
// Call the destructor for each manager
inputManagerDestructor();
// Stores
destroyDialogStore();
destroyTooltipStore();
destroyDocumentStore();
destroyFullscreenStore();
destroyNodeGraphStore();
destroyPortfolioStore();
destroyAppWindowStore();
// Managers
destroyClipboardManager();
destroyHyperlinkManager();
destroyLocalizationManager();
destroyPanicManager();
destroyPersistenceManager();
destroyFontsManager();
destroyInputManager();
});
</script>
@@ -330,7 +344,7 @@
font-weight: 400;
font-style: normal;
font-stretch: normal;
src: url("@graphite/../node_modules/source-sans-pro/WOFF2/TTF/SourceSansPro-Regular.ttf.woff2") format("woff2");
src: url("/node_modules/source-sans-pro/WOFF2/TTF/SourceSansPro-Regular.ttf.woff2") format("woff2");
}
@font-face {
@@ -338,7 +352,7 @@
font-weight: 400;
font-style: italic;
font-stretch: normal;
src: url("@graphite/../node_modules/source-sans-pro/WOFF2/TTF/SourceSansPro-It.ttf.woff2") format("woff2");
src: url("/node_modules/source-sans-pro/WOFF2/TTF/SourceSansPro-It.ttf.woff2") format("woff2");
}
@font-face {
@@ -346,7 +360,7 @@
font-weight: 700;
font-style: normal;
font-stretch: normal;
src: url("@graphite/../node_modules/source-sans-pro/WOFF2/TTF/SourceSansPro-Bold.ttf.woff2") format("woff2");
src: url("/node_modules/source-sans-pro/WOFF2/TTF/SourceSansPro-Bold.ttf.woff2") format("woff2");
}
@font-face {
@@ -354,7 +368,7 @@
font-weight: 700;
font-style: italic;
font-stretch: normal;
src: url("@graphite/../node_modules/source-sans-pro/WOFF2/TTF/SourceSansPro-BoldIt.ttf.woff2") format("woff2");
src: url("/node_modules/source-sans-pro/WOFF2/TTF/SourceSansPro-BoldIt.ttf.woff2") format("woff2");
}
@font-face {
@@ -362,6 +376,6 @@
font-weight: 400;
font-style: normal;
font-stretch: normal;
src: url("@graphite/../node_modules/source-code-pro/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2") format("woff2");
src: url("/node_modules/source-code-pro/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2") format("woff2");
}
</style>
@@ -1,9 +1,16 @@
<script lang="ts">
import { getContext, onDestroy, createEventDispatcher, tick } from "svelte";
import { isPlatformNative } from "@graphite/../wasm/pkg/graphite_wasm";
import type { FillChoice, MenuDirection, Color } from "@graphite/../wasm/pkg/graphite_wasm";
import type { TooltipState } from "@graphite/state-providers/tooltip";
import FloatingMenu, { preventEscapeClosingParentFloatingMenu } from "/src/components/layout/FloatingMenu.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import NumberInput from "/src/components/widgets/inputs/NumberInput.svelte";
import SpectrumInput, { MAX_MIDPOINT, MIN_MIDPOINT } from "/src/components/widgets/inputs/SpectrumInput.svelte";
import TextInput from "/src/components/widgets/inputs/TextInput.svelte";
import Separator from "/src/components/widgets/labels/Separator.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { TooltipStore } from "/src/stores/tooltip";
import type { HSV, RGB } from "/src/utility-functions/colors";
import {
contrastingOutlineFactor,
fillChoiceColor,
@@ -20,19 +27,9 @@
colorOpaque,
colorEquals,
gradientFirstColor,
} from "@graphite/utility-functions/colors";
import type { HSV, RGB } from "@graphite/utility-functions/colors";
import { clamp } from "@graphite/utility-functions/math";
import FloatingMenu, { preventEscapeClosingParentFloatingMenu } from "@graphite/components/layout/FloatingMenu.svelte";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import IconButton from "@graphite/components/widgets/buttons/IconButton.svelte";
import NumberInput from "@graphite/components/widgets/inputs/NumberInput.svelte";
import SpectrumInput, { MAX_MIDPOINT, MIN_MIDPOINT } from "@graphite/components/widgets/inputs/SpectrumInput.svelte";
import TextInput from "@graphite/components/widgets/inputs/TextInput.svelte";
import Separator from "@graphite/components/widgets/labels/Separator.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
} from "/src/utility-functions/colors";
import { isPlatformNative } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { FillChoice, MenuDirection, Color } from "/wrapper/pkg/graphite_wasm_wrapper";
type PresetColors = "None" | "Black" | "White" | "Red" | "Yellow" | "Green" | "Cyan" | "Blue" | "Magenta";
@@ -57,7 +54,7 @@
];
const dispatch = createEventDispatcher<{ colorOrGradient: FillChoice; startHistoryTransaction: undefined; commitHistoryTransaction: undefined }>();
const tooltip = getContext<TooltipState>("tooltip");
const tooltip = getContext<TooltipStore>("tooltip");
export let colorOrGradient: FillChoice;
export let allowNone = false;
@@ -438,6 +435,10 @@
setOldHSVA(hsv.h, hsv.s, hsv.v, color.alpha, false);
}
function clamp(value: number, min = 0, max = 1): number {
return Math.max(min, Math.min(value, max));
}
export function div(): HTMLDivElement | undefined {
return self?.div();
}
@@ -1,20 +1,17 @@
<script lang="ts">
import { getContext, onMount } from "svelte";
import FloatingMenu from "/src/components/layout/FloatingMenu.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import type { DialogStore } from "/src/stores/dialog";
import { crashReportUrl } from "/src/utility-functions/crash-report";
import { wipeDocuments } from "/src/utility-functions/persistence";
import { githubUrl } from "@graphite/io-managers/panic";
import { wipeDocuments } from "@graphite/io-managers/persistence";
import type { DialogState } from "@graphite/state-providers/dialog";
import FloatingMenu from "@graphite/components/layout/FloatingMenu.svelte";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import TextButton from "@graphite/components/widgets/buttons/TextButton.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
import WidgetLayout from "@graphite/components/widgets/WidgetLayout.svelte";
const dialog = getContext<DialogState>("dialog");
const dialog = getContext<DialogStore>("dialog");
let self: FloatingMenu | undefined;
@@ -43,7 +40,7 @@
<div class="widget-layout details">
<div class="widget-span row"><TextLabel bold={true}>The editor crashed — sorry about that</TextLabel></div>
<div class="widget-span row"><TextLabel>Please report this by filing an issue on GitHub:</TextLabel></div>
<div class="widget-span row"><TextButton label="Report Bug" icon="Warning" flush={true} action={() => window.open(githubUrl($dialog.panicDetails), "_blank")} /></div>
<div class="widget-span row"><TextButton label="Report Bug" icon="Warning" flush={true} action={() => window.open(crashReportUrl($dialog.panicDetails), "_blank")} /></div>
<div class="widget-span row"><TextLabel multiline={true}>Reload the editor to continue. If this occurs<br />immediately on repeated reloads, clear storage:</TextLabel></div>
<div class="widget-span row">
<TextButton
@@ -9,13 +9,9 @@
<script lang="ts">
import { onMount } from "svelte";
import FloatingMenu from "/src/components/layout/FloatingMenu.svelte";
import FloatingMenu from "@graphite/components/layout/FloatingMenu.svelte";
const temporaryCanvas = document.createElement("canvas");
temporaryCanvas.width = ZOOM_WINDOW_DIMENSIONS;
temporaryCanvas.height = ZOOM_WINDOW_DIMENSIONS;
let temporaryCanvas: HTMLCanvasElement | undefined;
let zoomPreviewCanvas: HTMLCanvasElement | undefined;
export let imageData: ImageData | undefined = undefined;
@@ -31,6 +27,11 @@
if (!zoomPreviewCanvas) return;
const context = zoomPreviewCanvas.getContext("2d");
if (!temporaryCanvas) {
temporaryCanvas = document.createElement("canvas");
temporaryCanvas.width = ZOOM_WINDOW_DIMENSIONS;
temporaryCanvas.height = ZOOM_WINDOW_DIMENSIONS;
}
const temporaryContext = temporaryCanvas.getContext("2d");
if (!imageData || !context || !temporaryContext) return;
@@ -2,18 +2,16 @@
<script lang="ts">
import { createEventDispatcher, tick, onDestroy, onMount } from "svelte";
import type { MenuListEntry, MenuDirection } from "@graphite/../wasm/pkg/graphite_wasm";
import MenuList from "@graphite/components/floating-menus/MenuList.svelte";
import FloatingMenu from "@graphite/components/layout/FloatingMenu.svelte";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import TextInput from "@graphite/components/widgets/inputs/TextInput.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import Separator from "@graphite/components/widgets/labels/Separator.svelte";
import ShortcutLabel from "@graphite/components/widgets/labels/ShortcutLabel.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
import MenuList from "/src/components/floating-menus/MenuList.svelte";
import FloatingMenu from "/src/components/layout/FloatingMenu.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import TextInput from "/src/components/widgets/inputs/TextInput.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import Separator from "/src/components/widgets/labels/Separator.svelte";
import ShortcutLabel from "/src/components/widgets/labels/ShortcutLabel.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { MenuListEntry, MenuDirection } from "/wrapper/pkg/graphite_wasm_wrapper";
let self: FloatingMenu | undefined;
let scroller: LayoutCol | undefined;
@@ -47,6 +45,8 @@
let reactiveEntries = entries;
let highlighted: MenuListEntry | undefined = activeEntry;
let virtualScrollingEntriesStart = 0;
let keydownListenerAdded = false;
let destroyed = false;
// `watchOpen` is called only when `open` is changed from outside this component
$: watchOpen(open);
@@ -67,11 +67,15 @@
// TODO: The current approach is hacky and blocks the allowances for shortcuts like the key to open the browser's dev tools.
onMount(async () => {
await tick();
if (open && !inNestedMenuList()) addEventListener("keydown", keydown);
if (!destroyed && open && !inNestedMenuList() && !keydownListenerAdded) {
addEventListener("keydown", keydown);
keydownListenerAdded = true;
}
});
onDestroy(async () => {
await tick();
if (!inNestedMenuList()) removeEventListener("keydown", keydown);
onDestroy(() => {
removeEventListener("keydown", keydown);
// Set the destroyed status in the closure kept by the awaited `tick()` in `onMount` in case that delayed run occurs after the component is destroyed
destroyed = true;
});
function inNestedMenuList(): boolean {
@@ -129,8 +133,13 @@
}
function watchOpen(open: boolean) {
if (open && !inNestedMenuList()) addEventListener("keydown", keydown);
else if (!inNestedMenuList()) removeEventListener("keydown", keydown);
if (open && !inNestedMenuList() && !keydownListenerAdded) {
addEventListener("keydown", keydown);
keydownListenerAdded = true;
} else if (!open && !inNestedMenuList() && keydownListenerAdded) {
removeEventListener("keydown", keydown);
keydownListenerAdded = false;
}
highlighted = activeEntry;
dispatch("open", open);
@@ -1,17 +1,15 @@
<script lang="ts">
import { createEventDispatcher, getContext, onMount } from "svelte";
import { SvelteMap } from "svelte/reactivity";
import type { FrontendNodeType } from "@graphite/../wasm/pkg/graphite_wasm";
import type { NodeGraphState } from "@graphite/state-providers/node-graph";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import TextButton from "@graphite/components/widgets/buttons/TextButton.svelte";
import TextInput from "@graphite/components/widgets/inputs/TextInput.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
import TextInput from "/src/components/widgets/inputs/TextInput.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { NodeGraphStore } from "/src/stores/node-graph";
import type { FrontendNodeType } from "/wrapper/pkg/graphite_wasm_wrapper";
const dispatch = createEventDispatcher<{ selectNodeType: string }>();
const nodeGraph = getContext<NodeGraphState>("nodeGraph");
const nodeGraph = getContext<NodeGraphStore>("nodeGraph");
// Content
export let disabled = false;
@@ -1,17 +1,14 @@
<script lang="ts">
import { getContext } from "svelte";
import FloatingMenu from "/src/components/layout/FloatingMenu.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import ShortcutLabel from "/src/components/widgets/labels/ShortcutLabel.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { TooltipStore } from "/src/stores/tooltip";
import type { EditorWrapper, LabeledShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { LabeledShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import type { TooltipState } from "@graphite/state-providers/tooltip";
import FloatingMenu from "@graphite/components/layout/FloatingMenu.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import ShortcutLabel from "@graphite/components/widgets/labels/ShortcutLabel.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
const tooltip = getContext<TooltipState>("tooltip");
const editor = getContext<Editor>("editor");
const tooltip = getContext<TooltipStore>("tooltip");
const editor = getContext<EditorWrapper>("editor");
let self: FloatingMenu | undefined;
@@ -32,7 +29,7 @@
// TODO: Once all TODOs are replaced with real text, remove this function
function filterTodo(text: string | undefined): string | undefined {
if (text?.trim().toUpperCase() === "TODO" && !editor.handle.inDevelopmentMode()) return "";
if (text?.trim().toUpperCase() === "TODO" && !editor.inDevelopmentMode()) return "";
return text;
}
@@ -17,12 +17,10 @@
</script>
<script lang="ts">
import { onMount, afterUpdate, createEventDispatcher, tick } from "svelte";
import type { MenuDirection } from "@graphite/../wasm/pkg/graphite_wasm";
import { browserVersion } from "@graphite/utility-functions/platform";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import { onMount, onDestroy, afterUpdate, createEventDispatcher, tick } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import { browserVersion } from "/src/utility-functions/platform";
import type { MenuDirection } from "/wrapper/pkg/graphite_wasm_wrapper";
const BUTTON_LEFT = 0;
const POINTER_STRAY_DISTANCE = 100;
@@ -54,9 +52,11 @@
// tell the floating menu content to use it as a min-width so the floating menu is at least the width of the parent element's floating menu spawner.
// This is the opposite concern of the natural width measurement system, which gets the natural width of the floating menu content in order for the
// spawner widget to optionally set its min-size to the floating menu's natural width.
let containerResizeObserver = new ResizeObserver((entries: ResizeObserverEntry[]) => {
const containerResizeObserver = new ResizeObserver((entries: ResizeObserverEntry[]) => {
resizeObserverCallback(entries);
});
let dialogResizeObserver: ResizeObserver | undefined;
let wasOpen = open;
let measuringOngoing = false;
let measuringOngoingGuard = false;
@@ -79,16 +79,7 @@
// Called only when `open` is changed from outside this component
async function watchOpenChange(isOpen: boolean) {
// Mitigate a Safari rendering bug which clips the floating menu extending beyond a scrollable container.
// The bug is possibly related to <https://bugs.webkit.org/show_bug.cgi?id=160953>, but in our case it happens when `overflow` of a parent is `auto` rather than `hidden`.
if (browserVersion().toLowerCase().includes("safari")) {
const scrollable = self?.closest("[data-scrollable-x], [data-scrollable-y]");
if (scrollable instanceof HTMLElement) {
// The issue exists when the container is set to `overflow: auto` but fine when `overflow: hidden`. So this workaround temporarily sets
// the scrollable container to `overflow: hidden`, thus removing the scrollbars and ability to scroll until the floating menu is closed.
scrollable.style.overflow = isOpen ? "hidden" : "";
}
}
setSafariScrollableOverflow(isOpen);
// Switching from closed to open
if (isOpen && !wasOpen) {
@@ -129,12 +120,22 @@
wasOpen = isOpen;
}
// Mitigate a Safari rendering bug which clips the floating menu extending beyond a scrollable container. The bug is possibly related to
// <https://bugs.webkit.org/show_bug.cgi?id=160953>, but in our case it happens when `overflow` of a parent is `auto` rather than `hidden`.
// The issue exists when the container is set to `overflow: auto` but fine when `overflow: hidden`. So this workaround temporarily sets
// the scrollable container to `overflow: hidden`, thus removing the scrollbars and ability to scroll until the floating menu is closed.
function setSafariScrollableOverflow(hidden: boolean) {
if (!browserVersion().toLowerCase().includes("safari")) return;
const scrollable = self?.closest("[data-scrollable-x], [data-scrollable-y]");
if (scrollable instanceof HTMLElement) scrollable.style.overflow = hidden ? "hidden" : "";
}
onMount(() => {
// Measure the content and round up its width and height to the nearest even integer.
// This solves antialiasing issues when the content isn't cleanly divisible by 2 and gets translated by (-50%, -50%) causing all its content to be blurry.
const floatingMenuContentDiv = floatingMenuContent?.div?.();
if (type === "Dialog" && floatingMenuContentDiv) {
const resizeObserver = new ResizeObserver((entries) => {
dialogResizeObserver = new ResizeObserver((entries) => {
entries.forEach((entry) => {
const existingWidth = Number(floatingMenuContentDiv.style.getPropertyValue("--even-integer-subpixel-expansion-x"));
const existingHeight = Number(floatingMenuContentDiv.style.getPropertyValue("--even-integer-subpixel-expansion-y"));
@@ -153,10 +154,23 @@
floatingMenuContentDiv.style.setProperty("--even-integer-subpixel-expansion-y", `${targetHeight - height}`);
});
});
resizeObserver.observe(floatingMenuContentDiv);
dialogResizeObserver.observe(floatingMenuContentDiv);
}
});
onDestroy(() => {
containerResizeObserver.disconnect();
dialogResizeObserver?.disconnect();
window.removeEventListener("pointermove", pointerMoveHandler);
window.removeEventListener("keydown", keyDownHandler);
window.removeEventListener("pointerdown", pointerDownHandler);
window.removeEventListener("pointerup", pointerUpHandler);
window.removeEventListener("click", clickHandlerCapture, true);
// Revert Safari overflow workaround if the menu was open when destroyed
if (open) setSafariScrollableOverflow(false);
});
afterUpdate(() => {
// Gets the client bounds of the elements and apply relevant styles to them.
// TODO: Use DOM attribute bindings more whilst not causing recursive updates. Turning measuring on and off both causes the component to change,
@@ -321,7 +335,7 @@
// POINTER STRAY
// Close the floating menu if the pointer has strayed far enough from its bounds (and it's not hovering over its own spawner)
const notHoveringOverOwnSpawner = ownSpawner !== targetSpawner || (ownSpawner === undefined && targetSpawner === undefined);
const notHoveringOverOwnSpawner = ownSpawner !== targetSpawner;
if (strayCloses && notHoveringOverOwnSpawner && isPointerEventOutsideFloatingMenu(e, POINTER_STRAY_DISTANCE)) {
// TODO: Extend this rectangle bounds check to all submenu bounds up the DOM tree since currently submenus disappear
// TODO: with zero stray distance if the cursor is further than the stray distance from only the top-level menu
@@ -1,5 +1,5 @@
<script lang="ts">
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
let className = "";
export { className as class };
@@ -1,5 +1,5 @@
<script lang="ts">
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
let className = "";
export { className as class };
+8 -10
View File
@@ -1,26 +1,24 @@
<script lang="ts">
import { getContext, onMount, onDestroy } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import { patchLayout } from "/src/utility-functions/widgets";
import type { Layout } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { Layout } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import { patchLayout } from "@graphite/utility-functions/widgets";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import WidgetLayout from "@graphite/components/widgets/WidgetLayout.svelte";
const editor = getContext<Editor>("editor");
const subscriptions = getContext<SubscriptionsRouter>("subscriptions");
let dataPanelLayout: Layout = [];
onMount(() => {
editor.subscriptions.subscribeLayoutUpdate("DataPanel", (data) => {
subscriptions.subscribeLayoutUpdate("DataPanel", (data) => {
patchLayout(dataPanelLayout, data);
dataPanelLayout = dataPanelLayout;
});
});
onDestroy(() => {
editor.subscriptions.unsubscribeLayoutUpdate("DataPanel");
subscriptions.unsubscribeLayoutUpdate("DataPanel");
});
</script>
+77 -57
View File
@@ -1,34 +1,33 @@
<script lang="ts">
import { getContext, onMount, onDestroy, tick } from "svelte";
import type { Color, MenuDirection, MouseCursorIcon } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import type { AppWindowState } from "@graphite/state-providers/app-window";
import type { DocumentState } from "@graphite/state-providers/document";
import type { MessageBody } from "@graphite/subscription-router";
import { fillChoiceColor, createColor } from "@graphite/utility-functions/colors";
import { pasteFile } from "@graphite/utility-functions/files";
import { textInputCleanup } from "@graphite/utility-functions/keyboard-entry";
import { rasterizeSVGCanvas } from "@graphite/utility-functions/rasterization";
import { setupViewportResizeObserver, cleanupViewportResizeObserver } from "@graphite/utility-functions/viewports";
import ColorPicker from "@graphite/components/floating-menus/ColorPicker.svelte";
import EyedropperPreview, { ZOOM_WINDOW_DIMENSIONS } from "@graphite/components/floating-menus/EyedropperPreview.svelte";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import Graph from "@graphite/components/views/Graph.svelte";
import RulerInput from "@graphite/components/widgets/inputs/RulerInput.svelte";
import ScrollbarInput from "@graphite/components/widgets/inputs/ScrollbarInput.svelte";
import WidgetLayout from "@graphite/components/widgets/WidgetLayout.svelte";
import ColorPicker from "/src/components/floating-menus/ColorPicker.svelte";
import EyedropperPreview, { ZOOM_WINDOW_DIMENSIONS } from "/src/components/floating-menus/EyedropperPreview.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import Graph from "/src/components/views/Graph.svelte";
import RulerInput from "/src/components/widgets/inputs/RulerInput.svelte";
import ScrollbarInput from "/src/components/widgets/inputs/ScrollbarInput.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import type { AppWindowStore } from "/src/stores/app-window";
import type { DocumentStore } from "/src/stores/document";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import type { MessageBody } from "/src/subscriptions-router";
import { fillChoiceColor, createColor } from "/src/utility-functions/colors";
import { pasteFile } from "/src/utility-functions/files";
import { textInputCleanup } from "/src/utility-functions/keyboard-entry";
import { rasterizeSVGCanvas } from "/src/utility-functions/rasterization";
import { setupViewportResizeObserver } from "/src/utility-functions/viewports";
import type { Color, EditorWrapper, MenuDirection, MouseCursorIcon } from "/wrapper/pkg/graphite_wasm_wrapper";
let rulerHorizontal: RulerInput | undefined;
let rulerVertical: RulerInput | undefined;
let viewport: HTMLDivElement | undefined;
let gradientStopPicker: ColorPicker | undefined;
const editor = getContext<Editor>("editor");
const appWindow = getContext<AppWindowState>("appWindow");
const document = getContext<DocumentState>("document");
const subscriptions = getContext<SubscriptionsRouter>("subscriptions");
const editor = getContext<EditorWrapper>("editor");
const appWindow = getContext<AppWindowStore>("appWindow");
const document = getContext<DocumentStore>("document");
// Interactive text editing
let textInput: undefined | HTMLDivElement = undefined;
@@ -74,6 +73,10 @@
let canvasHeight: number | undefined = undefined;
let devicePixelRatio: number | undefined;
let removeUpdatePixelRatio: (() => void) | undefined;
let viewportResizeObserver: ResizeObserver | undefined;
let cleanupViewportResizeObserver: (() => void) | undefined;
let addedFontFaces: FontFace[] = [];
// Dimension is rounded up to the nearest even number because resizing is centered, and dividing an odd number by 2 for centering causes antialiasing
$: canvasWidthRoundedToEven = canvasWidth && (canvasWidth % 2 === 1 ? canvasWidth + 1 : canvasWidth);
@@ -138,13 +141,13 @@
function panCanvasX(newValue: number) {
const delta = newValue - scrollbarPos.x;
scrollbarPos.x = newValue;
editor.handle.panCanvas(-delta * scrollbarMultiplier.x, 0);
editor.panCanvas(-delta * scrollbarMultiplier.x, 0);
}
function panCanvasY(newValue: number) {
const delta = newValue - scrollbarPos.y;
scrollbarPos.y = newValue;
editor.handle.panCanvas(0, -delta * scrollbarMultiplier.y);
editor.panCanvas(0, -delta * scrollbarMultiplier.y);
}
function canvasPointerDown(e: PointerEvent) {
@@ -338,7 +341,7 @@
export function triggerTextCommit() {
if (!textInput) return;
const textCleaned = textInputCleanup(textInput.innerText);
editor.handle.onChangeText(textCleaned, false);
editor.onChangeText(textCleaned, false);
}
export async function displayEditableTextbox(data: MessageBody<"DisplayEditableTextbox">) {
@@ -368,14 +371,16 @@
textInput.oninput = () => {
if (!textInput) return;
editor.handle.updateBounds(textInputCleanup(textInput.innerText));
editor.updateBounds(textInputCleanup(textInput.innerText));
};
textInputMatrix = data.transform;
if (data.fontData.length > 0 && data.fontData.buffer instanceof ArrayBuffer) {
const fontView = new Uint8Array(data.fontData.buffer, data.fontData.byteOffset, data.fontData.byteLength);
window.document.fonts.add(new FontFace("text-font", fontView));
const face = new FontFace("text-font", fontView);
window.document.fonts.add(face);
addedFontFaces.push(face);
textInput.style.fontFamily = "text-font";
}
@@ -436,7 +441,6 @@
// Not compatible with Safari:
// <https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#browser_compatibility>
// <https://bugs.webkit.org/show_bug.cgi?id=124862>
let removeUpdatePixelRatio: (() => void) | undefined = undefined;
const updatePixelRatio = () => {
removeUpdatePixelRatio?.();
const mediaQueryList = matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
@@ -449,12 +453,12 @@
updatePixelRatio();
// Update rendered SVGs
editor.subscriptions.subscribeFrontendMessage("UpdateDocumentArtwork", async (data) => {
subscriptions.subscribeFrontendMessage("UpdateDocumentArtwork", async (data) => {
await tick();
updateDocumentArtwork(data.svg);
});
editor.subscriptions.subscribeFrontendMessage("UpdateEyedropperSamplingState", async (data) => {
subscriptions.subscribeFrontendMessage("UpdateEyedropperSamplingState", async (data) => {
await tick();
const { image, mousePosition, primaryColor, secondaryColor, setColorChoice } = data;
@@ -462,25 +466,25 @@
const rgb = await updateEyedropperSamplingState(imageData, mousePosition, primaryColor, secondaryColor);
if (setColorChoice && rgb) {
if (setColorChoice === "Primary") editor.handle.updatePrimaryColor(...rgb, 1);
if (setColorChoice === "Secondary") editor.handle.updateSecondaryColor(...rgb, 1);
if (setColorChoice === "Primary") editor.updatePrimaryColor(...rgb, 1);
if (setColorChoice === "Secondary") editor.updateSecondaryColor(...rgb, 1);
}
});
// Gradient stop color picker
editor.subscriptions.subscribeFrontendMessage("UpdateGradientStopColorPickerPosition", (data) => {
subscriptions.subscribeFrontendMessage("UpdateGradientStopColorPickerPosition", (data) => {
gradientStopPickerColor = data.color;
gradientStopPickerPosition = { x: data.position[0], y: data.position[1] };
});
// Update scrollbars and rulers
editor.subscriptions.subscribeFrontendMessage("UpdateDocumentScrollbars", async (data) => {
subscriptions.subscribeFrontendMessage("UpdateDocumentScrollbars", async (data) => {
await tick();
const { position, size, multiplier } = data;
updateDocumentScrollbars(position, size, multiplier);
});
editor.subscriptions.subscribeFrontendMessage("UpdateDocumentRulers", async (data) => {
subscriptions.subscribeFrontendMessage("UpdateDocumentRulers", async (data) => {
await tick();
const { origin, spacing, interval, visible } = data;
@@ -488,36 +492,38 @@
});
// Update mouse cursor icon
editor.subscriptions.subscribeFrontendMessage("UpdateMouseCursor", async (data) => {
subscriptions.subscribeFrontendMessage("UpdateMouseCursor", async (data) => {
await tick();
updateMouseCursor(data.cursor);
});
// Text entry
editor.subscriptions.subscribeFrontendMessage("TriggerTextCommit", async () => {
subscriptions.subscribeFrontendMessage("TriggerTextCommit", async () => {
await tick();
triggerTextCommit();
});
editor.subscriptions.subscribeFrontendMessage("DisplayEditableTextbox", async (data) => {
subscriptions.subscribeFrontendMessage("DisplayEditableTextbox", async (data) => {
await tick();
displayEditableTextbox(data);
});
editor.subscriptions.subscribeFrontendMessage("DisplayEditableTextboxUpdateFontData", async (data) => {
subscriptions.subscribeFrontendMessage("DisplayEditableTextboxUpdateFontData", async (data) => {
await tick();
if (textInput && data.fontData.length > 0 && data.fontData.buffer instanceof ArrayBuffer) {
const fontView = new Uint8Array(data.fontData.buffer, data.fontData.byteOffset, data.fontData.byteLength);
window.document.fonts.add(new FontFace("text-font", fontView));
const face = new FontFace("text-font", fontView);
window.document.fonts.add(face);
addedFontFaces.push(face);
textInput.style.fontFamily = "text-font";
}
});
editor.subscriptions.subscribeFrontendMessage("DisplayEditableTextboxTransform", async (data) => {
subscriptions.subscribeFrontendMessage("DisplayEditableTextboxTransform", async (data) => {
textInputMatrix = data.transform;
});
editor.subscriptions.subscribeFrontendMessage("DisplayRemoveEditableTextbox", async () => {
subscriptions.subscribeFrontendMessage("DisplayRemoveEditableTextbox", async () => {
await tick();
displayRemoveEditableTextbox();
@@ -525,18 +531,32 @@
// Setup ResizeObserver for pixel-perfect viewport tracking with physical dimensions
// This must happen in onMount to ensure the viewport container element exists
setupViewportResizeObserver(editor);
cleanupViewportResizeObserver = setupViewportResizeObserver(editor);
// Also observe the inner viewport for canvas sizing and ruler updates
const viewportResizeObserver = new ResizeObserver(() => {
viewportResizeObserver = new ResizeObserver(() => {
updateViewportInfo();
});
if (viewport) viewportResizeObserver.observe(viewport);
});
onDestroy(() => {
// Cleanup the viewport resize observer
cleanupViewportResizeObserver();
cleanupViewportResizeObserver?.();
viewportResizeObserver?.disconnect();
removeUpdatePixelRatio?.();
addedFontFaces.forEach((face) => window.document.fonts.delete(face));
subscriptions.unsubscribeFrontendMessage("UpdateDocumentArtwork");
subscriptions.unsubscribeFrontendMessage("UpdateEyedropperSamplingState");
subscriptions.unsubscribeFrontendMessage("UpdateGradientStopColorPickerPosition");
subscriptions.unsubscribeFrontendMessage("UpdateDocumentScrollbars");
subscriptions.unsubscribeFrontendMessage("UpdateDocumentRulers");
subscriptions.unsubscribeFrontendMessage("UpdateMouseCursor");
subscriptions.unsubscribeFrontendMessage("TriggerTextCommit");
subscriptions.unsubscribeFrontendMessage("DisplayEditableTextbox");
subscriptions.unsubscribeFrontendMessage("DisplayEditableTextboxUpdateFontData");
subscriptions.unsubscribeFrontendMessage("DisplayEditableTextboxTransform");
subscriptions.unsubscribeFrontendMessage("DisplayRemoveEditableTextbox");
});
</script>
@@ -607,7 +627,7 @@
open={Boolean(gradientStopPickerPosition && gradientStopPickerColor)}
on:open={({ detail }) => {
if (!detail) {
editor.handle.closeGradientStopColorPicker();
editor.closeGradientStopColorPicker();
gradientStopPickerPosition = undefined;
gradientStopPickerColor = undefined;
}
@@ -615,10 +635,10 @@
colorOrGradient={{ Solid: gradientStopPickerColor || createColor(0, 0, 0, 1) }}
on:colorOrGradient={({ detail }) => {
const color = fillChoiceColor(detail);
if (color) editor.handle.updateGradientStopColor(color.red, color.green, color.blue, color.alpha);
if (color) editor.updateGradientStopColor(color.red, color.green, color.blue, color.alpha);
}}
on:startHistoryTransaction={() => editor.handle.startGradientStopColorTransaction()}
on:commitHistoryTransaction={() => editor.handle.commitGradientStopColorTransaction()}
on:startHistoryTransaction={() => editor.startGradientStopColorTransaction()}
on:commitHistoryTransaction={() => editor.commitGradientStopColorTransaction()}
bind:this={gradientStopPicker}
/>
</div>
@@ -661,10 +681,10 @@
direction="Vertical"
thumbLength={scrollbarSize.y}
thumbPosition={scrollbarPos.y}
on:trackShift={({ detail }) => editor.handle.panCanvasByFraction(0, detail)}
on:trackShift={({ detail }) => editor.panCanvasByFraction(0, detail)}
on:thumbPosition={({ detail }) => panCanvasY(detail)}
on:thumbDragStart={() => editor.handle.panCanvasAbortPrepare(false)}
on:thumbDragAbort={() => editor.handle.panCanvasAbort(false)}
on:thumbDragStart={() => editor.panCanvasAbortPrepare(false)}
on:thumbDragAbort={() => editor.panCanvasAbort(false)}
/>
</LayoutCol>
</LayoutRow>
@@ -673,10 +693,10 @@
direction="Horizontal"
thumbLength={scrollbarSize.x}
thumbPosition={scrollbarPos.x}
on:trackShift={({ detail }) => editor.handle.panCanvasByFraction(detail, 0)}
on:trackShift={({ detail }) => editor.panCanvasByFraction(detail, 0)}
on:thumbPosition={({ detail }) => panCanvasX(detail)}
on:thumbDragStart={() => editor.handle.panCanvasAbortPrepare(true)}
on:thumbDragAbort={() => editor.handle.panCanvasAbort(true)}
on:thumbDragStart={() => editor.panCanvasAbortPrepare(true)}
on:thumbDragAbort={() => editor.panCanvasAbort(true)}
/>
</LayoutRow>
</LayoutCol>
+36 -37
View File
@@ -1,21 +1,19 @@
<script lang="ts">
import { getContext, onMount, onDestroy, tick } from "svelte";
import { SvelteMap } from "svelte/reactivity";
import type { LayerPanelEntry, LayerStructureEntry, Layout } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import type { NodeGraphState } from "@graphite/state-providers/node-graph";
import type { TooltipState } from "@graphite/state-providers/tooltip";
import { pasteFile } from "@graphite/utility-functions/files";
import { operatingSystem } from "@graphite/utility-functions/platform";
import { patchLayout } from "@graphite/utility-functions/widgets";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import IconButton from "@graphite/components/widgets/buttons/IconButton.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import Separator from "@graphite/components/widgets/labels/Separator.svelte";
import WidgetLayout from "@graphite/components/widgets/WidgetLayout.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import Separator from "/src/components/widgets/labels/Separator.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import type { NodeGraphStore } from "/src/stores/node-graph";
import type { TooltipStore } from "/src/stores/tooltip";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import { pasteFile } from "/src/utility-functions/files";
import { operatingSystem } from "/src/utility-functions/platform";
import { patchLayout } from "/src/utility-functions/widgets";
import type { EditorWrapper, LayerPanelEntry, LayerStructureEntry, Layout } from "/wrapper/pkg/graphite_wasm_wrapper";
type LayerListingInfo = {
folderIndex: number;
@@ -41,9 +39,10 @@
startY: number;
};
const editor = getContext<Editor>("editor");
const nodeGraph = getContext<NodeGraphState>("nodeGraph");
const tooltip = getContext<TooltipState>("tooltip");
const subscriptions = getContext<SubscriptionsRouter>("subscriptions");
const editor = getContext<EditorWrapper>("editor");
const nodeGraph = getContext<NodeGraphStore>("nodeGraph");
const tooltip = getContext<TooltipStore>("tooltip");
let list: LayoutCol | undefined;
@@ -69,26 +68,26 @@
let layersPanelBottomBarLayout: Layout = [];
onMount(() => {
editor.subscriptions.subscribeLayoutUpdate("LayersPanelControlLeftBar", (data) => {
subscriptions.subscribeLayoutUpdate("LayersPanelControlLeftBar", (data) => {
patchLayout(layersPanelControlBarLeftLayout, data);
layersPanelControlBarLeftLayout = layersPanelControlBarLeftLayout;
});
editor.subscriptions.subscribeLayoutUpdate("LayersPanelControlRightBar", (data) => {
subscriptions.subscribeLayoutUpdate("LayersPanelControlRightBar", (data) => {
patchLayout(layersPanelControlBarRightLayout, data);
layersPanelControlBarRightLayout = layersPanelControlBarRightLayout;
});
editor.subscriptions.subscribeLayoutUpdate("LayersPanelBottomBar", (data) => {
subscriptions.subscribeLayoutUpdate("LayersPanelBottomBar", (data) => {
patchLayout(layersPanelBottomBarLayout, data);
layersPanelBottomBarLayout = layersPanelBottomBarLayout;
});
editor.subscriptions.subscribeFrontendMessage("UpdateDocumentLayerStructure", (data) => {
subscriptions.subscribeFrontendMessage("UpdateDocumentLayerStructure", (data) => {
rebuildLayerHierarchy(data.layerStructure);
});
editor.subscriptions.subscribeFrontendMessage("UpdateDocumentLayerDetails", (data) => {
subscriptions.subscribeFrontendMessage("UpdateDocumentLayerDetails", (data) => {
const targetLayer = data.data;
const targetId = targetLayer.id;
@@ -107,11 +106,11 @@
});
onDestroy(() => {
editor.subscriptions.unsubscribeLayoutUpdate("LayersPanelControlLeftBar");
editor.subscriptions.unsubscribeLayoutUpdate("LayersPanelControlRightBar");
editor.subscriptions.unsubscribeLayoutUpdate("LayersPanelBottomBar");
editor.subscriptions.unsubscribeFrontendMessage("UpdateDocumentLayerStructure");
editor.subscriptions.unsubscribeFrontendMessage("UpdateDocumentLayerDetails");
subscriptions.unsubscribeLayoutUpdate("LayersPanelControlLeftBar");
subscriptions.unsubscribeLayoutUpdate("LayersPanelControlRightBar");
subscriptions.unsubscribeLayoutUpdate("LayersPanelBottomBar");
subscriptions.unsubscribeFrontendMessage("UpdateDocumentLayerStructure");
subscriptions.unsubscribeFrontendMessage("UpdateDocumentLayerDetails");
removeEventListener("pointerup", draggingPointerUp);
removeEventListener("pointermove", draggingPointerMove);
@@ -125,17 +124,17 @@
});
function toggleNodeVisibilityLayerPanel(id: bigint) {
editor.handle.toggleNodeVisibilityLayerPanel(id);
editor.toggleNodeVisibilityLayerPanel(id);
}
function toggleLayerLock(id: bigint) {
editor.handle.toggleLayerLock(id);
editor.toggleLayerLock(id);
}
function handleExpandArrowClickWithModifiers(e: MouseEvent, id: bigint) {
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
const collapseRecursive = e.altKey || accel;
editor.handle.toggleLayerExpansion(id, collapseRecursive);
editor.toggleLayerExpansion(id, collapseRecursive);
e.stopPropagation();
}
@@ -162,7 +161,7 @@
layers = layers;
const name = (e.target instanceof HTMLInputElement && e.target.value) || "";
editor.handle.setLayerName(listing.entry.id, name);
editor.setLayerName(listing.entry.id, name);
listing.entry.alias = name;
}
@@ -200,7 +199,7 @@
}
function clipLayer(listing: LayerListingInfo) {
editor.handle.clipLayer(listing.entry.id);
editor.clipLayer(listing.entry.id);
}
function clippingKeyPress(e: KeyboardEvent) {
@@ -247,7 +246,7 @@
// Don't select while we are entering text to rename the layer
if (listing.editingName) return;
editor.handle.selectLayer(listing.entry.id, accel, shift);
editor.selectLayer(listing.entry.id, accel, shift);
}
async function deselectAllLayers() {
@@ -256,7 +255,7 @@
return;
}
editor.handle.deselectAllLayers();
editor.deselectAllLayers();
}
function calculateDragIndex(tree: LayoutCol, clientY: number, select?: () => void): DraggingData {
@@ -389,7 +388,7 @@
// Commit the move
select?.();
editor.handle.moveLayerInTree(insertParentId, insertIndex);
editor.moveLayerInTree(insertParentId, insertIndex);
// Prevent the subsequent click event from processing
justFinishedDrag = true;
@@ -445,7 +444,7 @@
const inputElement = document.activeElement;
if (inputElement instanceof HTMLInputElement) {
const name = inputElement.value || "";
editor.handle.setLayerName(currentListing.entry.id, name);
editor.setLayerName(currentListing.entry.id, name);
currentListing.entry.alias = name;
}
@@ -1,26 +1,24 @@
<script lang="ts">
import { getContext, onMount, onDestroy } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import { patchLayout } from "/src/utility-functions/widgets";
import type { Layout } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { Layout } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import { patchLayout } from "@graphite/utility-functions/widgets";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import WidgetLayout from "@graphite/components/widgets/WidgetLayout.svelte";
const editor = getContext<Editor>("editor");
const subscriptions = getContext<SubscriptionsRouter>("subscriptions");
let propertiesPanelLayout: Layout = [];
onMount(() => {
editor.subscriptions.subscribeLayoutUpdate("PropertiesPanel", (data) => {
subscriptions.subscribeLayoutUpdate("PropertiesPanel", (data) => {
patchLayout(propertiesPanelLayout, data);
propertiesPanelLayout = propertiesPanelLayout;
});
});
onDestroy(() => {
editor.subscriptions.unsubscribeLayoutUpdate("PropertiesPanel");
subscriptions.unsubscribeLayoutUpdate("PropertiesPanel");
});
</script>
+14 -15
View File
@@ -1,31 +1,30 @@
<script lang="ts">
import { getContext, onMount, onDestroy } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import { pasteFile } from "/src/utility-functions/files";
import { patchLayout } from "/src/utility-functions/widgets";
import { isPlatformNative } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { EditorWrapper, Layout } from "/wrapper/pkg/graphite_wasm_wrapper";
import { isPlatformNative } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Layout } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import { pasteFile } from "@graphite/utility-functions/files";
import { patchLayout } from "@graphite/utility-functions/widgets";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
import WidgetLayout from "@graphite/components/widgets/WidgetLayout.svelte";
const editor = getContext<Editor>("editor");
const subscriptions = getContext<SubscriptionsRouter>("subscriptions");
const editor = getContext<EditorWrapper>("editor");
let welcomePanelButtonsLayout: Layout = [];
onMount(() => {
editor.subscriptions.subscribeLayoutUpdate("WelcomeScreenButtons", (data) => {
subscriptions.subscribeLayoutUpdate("WelcomeScreenButtons", (data) => {
patchLayout(welcomePanelButtonsLayout, data);
welcomePanelButtonsLayout = welcomePanelButtonsLayout;
});
});
onDestroy(() => {
editor.subscriptions.unsubscribeLayoutUpdate("WelcomeScreenButtons");
subscriptions.unsubscribeLayoutUpdate("WelcomeScreenButtons");
});
function dropFile(e: DragEvent) {
+32 -34
View File
@@ -2,26 +2,24 @@
import { getContext } from "svelte";
import { cubicInOut } from "svelte/easing";
import { fade } from "svelte/transition";
import type { FrontendGraphInput, FrontendGraphOutput, FrontendNode } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import type { DocumentState } from "@graphite/state-providers/document";
import type { NodeGraphState } from "@graphite/state-providers/node-graph";
import NodeCatalog from "@graphite/components/floating-menus/NodeCatalog.svelte";
import FloatingMenu from "@graphite/components/layout/FloatingMenu.svelte";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import IconButton from "@graphite/components/widgets/buttons/IconButton.svelte";
import TextButton from "@graphite/components/widgets/buttons/TextButton.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
import NodeCatalog from "/src/components/floating-menus/NodeCatalog.svelte";
import FloatingMenu from "/src/components/layout/FloatingMenu.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { DocumentStore } from "/src/stores/document";
import type { NodeGraphStore } from "/src/stores/node-graph";
import { closeContextMenu } from "/src/stores/node-graph";
import type { EditorWrapper, FrontendGraphInput, FrontendGraphOutput, FrontendNode } from "/wrapper/pkg/graphite_wasm_wrapper";
const GRID_COLLAPSE_SPACING = 10;
const GRID_SIZE = 24;
const FADE_TRANSITION = { duration: 200, easing: cubicInOut };
const editor = getContext<Editor>("editor");
const nodeGraph = getContext<NodeGraphState>("nodeGraph");
const documentState = getContext<DocumentState>("document");
const editor = getContext<EditorWrapper>("editor");
const nodeGraph = getContext<NodeGraphStore>("nodeGraph");
const documentState = getContext<DocumentStore>("document");
let graph: HTMLDivElement | undefined;
@@ -29,7 +27,7 @@
$: gridDotRadius = 1 + Math.floor($nodeGraph.transform.scale - 0.5 + 0.001) / 2;
// Close the context menu when the graph view overlay is closed
$: if (!$documentState.graphViewOverlayOpen) nodeGraph.closeContextMenu();
$: if (!$documentState.graphViewOverlayOpen) closeContextMenu();
let inputElement: HTMLInputElement;
let hoveringImportIndex: number | undefined = undefined;
@@ -82,7 +80,7 @@
if (editingNameImportIndex !== undefined) {
if (!(event.target instanceof HTMLInputElement)) return;
let text = event.target.value;
editor.handle.setImportName(editingNameImportIndex, text);
editor.setImportName(editingNameImportIndex, text);
editingNameImportIndex = undefined;
}
}
@@ -91,7 +89,7 @@
if (editingNameExportIndex !== undefined) {
if (!(event.target instanceof HTMLInputElement)) return;
let text = event.target.value;
editor.handle.setExportName(editingNameExportIndex, text);
editor.setExportName(editingNameExportIndex, text);
editingNameExportIndex = undefined;
}
}
@@ -110,7 +108,7 @@
function createNode(identifier: string) {
if ($nodeGraph.contextMenuInformation === undefined) return;
editor.handle.createNode(identifier, $nodeGraph.contextMenuInformation.contextMenuCoordinates[0], $nodeGraph.contextMenuInformation.contextMenuCoordinates[1]);
editor.createNode(identifier, $nodeGraph.contextMenuInformation.contextMenuCoordinates[0], $nodeGraph.contextMenuInformation.contextMenuCoordinates[1]);
}
function nodeBorderMask(nodeWidth: number, primaryInputExists: boolean, exposedSecondaryInputs: number, primaryOutputExists: boolean, exposedSecondaryOutputs: number): string {
@@ -173,11 +171,11 @@
}
function outputConnectedToText(output: FrontendGraphOutput): string {
return editor.handle.inDevelopmentMode() ? output.connectedTo.join("\n") : "";
return editor.inDevelopmentMode() ? output.connectedTo.join("\n") : "";
}
function inputConnectedToText(input: FrontendGraphInput): string {
return editor.handle.inDevelopmentMode() ? input.connectedTo : "";
return editor.inDevelopmentMode() ? input.connectedTo : "";
}
function zipWithUndefined(arr1: FrontendGraphInput[], arr2: FrontendGraphOutput[]) {
@@ -219,8 +217,8 @@
<TextButton
label="Merge Selected Nodes"
action={() => {
editor.handle.mergeSelectedNodes();
nodeGraph.closeContextMenu();
editor.mergeSelectedNodes();
closeContextMenu();
}}
flush={true}
/>
@@ -229,9 +227,9 @@
label={currentlyIsNode ? "Display as Layer" : "Display as Node"}
action={() => {
if ($nodeGraph.contextMenuInformation?.contextMenuData.type === "ModifyNode") {
editor.handle.setToNodeOrLayer($nodeGraph.contextMenuInformation.contextMenuData.data.nodeId, currentlyIsNode);
editor.setToNodeOrLayer($nodeGraph.contextMenuInformation.contextMenuData.data.nodeId, currentlyIsNode);
}
nodeGraph.closeContextMenu();
closeContextMenu();
}}
disabled={!$nodeGraph.contextMenuInformation.contextMenuData.data.canBeLayer}
flush={true}
@@ -243,11 +241,11 @@
label={allLocked ? "Unlock" : "Lock"}
action={() => {
if ($nodeGraph.selected.includes(nodeId)) {
editor.handle.toggleSelectedLocked();
editor.toggleSelectedLocked();
} else {
editor.handle.toggleLayerLock(nodeId);
editor.toggleLayerLock(nodeId);
}
nodeGraph.closeContextMenu();
closeContextMenu();
}}
flush={true}
/>
@@ -382,7 +380,7 @@
style:--offset-top={($nodeGraph.updateImportsExports.importPosition[1] - 12) / 24}
style:--offset-left={($nodeGraph.updateImportsExports.importPosition[0] - 12) / 24}
>
<IconButton size={24} icon="Add" action={() => editor.handle.addPrimaryImport()} />
<IconButton size={24} icon="Add" action={() => editor.addPrimaryImport()} />
</div>
{/if}
{/each}
@@ -453,7 +451,7 @@
style:--offset-left={($nodeGraph.updateImportsExports.exportPosition[0] - 12) / 24}
style:--offset-top={($nodeGraph.updateImportsExports.exportPosition[1] - 12) / 24}
>
<IconButton size={24} icon="Add" action={() => editor.handle.addPrimaryExport()} />
<IconButton size={24} icon="Add" action={() => editor.addPrimaryExport()} />
</div>
{/if}
{/each}
@@ -464,14 +462,14 @@
style:--offset-left={($nodeGraph.updateImportsExports.importPosition[0] - 12) / 24}
style:--offset-top={($nodeGraph.updateImportsExports.importPosition[1] - 12) / 24 + $nodeGraph.updateImportsExports.imports.length}
>
<IconButton size={24} icon="Add" action={() => editor.handle.addSecondaryImport()} />
<IconButton size={24} icon="Add" action={() => editor.addSecondaryImport()} />
</div>
<div
class="plus"
style:--offset-left={($nodeGraph.updateImportsExports.exportPosition[0] - 12) / 24}
style:--offset-top={($nodeGraph.updateImportsExports.exportPosition[1] - 12) / 24 + $nodeGraph.updateImportsExports.exports.length}
>
<IconButton size={24} icon="Add" action={() => editor.handle.addSecondaryExport()} />
<IconButton size={24} icon="Add" action={() => editor.addSecondaryExport()} />
</div>
{/if}
@@ -521,7 +519,7 @@
style:--node-chain-area-left-extension={layerChainWidth !== 0 ? layerChainWidth + 0.5 : 0}
data-tooltip-label={nodeNameTooltipLabel(node)}
data-tooltip-description={`
${(description || "").trim()}${editor.handle.inDevelopmentMode() ? `\n\nID: ${node.id}. Position: (${node.position[0]}, ${node.position[1]}).` : ""}
${(description || "").trim()}${editor.inDevelopmentMode() ? `\n\nID: ${node.id}. Position: (${node.position[0]}, ${node.position[1]}).` : ""}
`.trim()}
data-node={node.id}
>
@@ -684,7 +682,7 @@
style:--data-color-dim={`var(--color-data-${(node.primaryOutput?.dataType || "General").toLowerCase()}-dim)`}
data-tooltip-label={nodeNameTooltipLabel(node)}
data-tooltip-description={`
${(description || "").trim()}${editor.handle.inDevelopmentMode() ? `\n\nID: ${node.id}. Position: (${node.position[0]}, ${node.position[1]}).` : ""}
${(description || "").trim()}${editor.inDevelopmentMode() ? `\n\nID: ${node.id}. Position: (${node.position[0]}, ${node.position[1]}).` : ""}
`.trim()}
data-node={node.id}
>
@@ -1,9 +1,8 @@
<script lang="ts">
import type { Layout, LayoutTarget } from "@graphite/../wasm/pkg/graphite_wasm";
import WidgetSection from "@graphite/components/widgets/WidgetSection.svelte";
import WidgetSpan from "@graphite/components/widgets/WidgetSpan.svelte";
import WidgetTable from "@graphite/components/widgets/WidgetTable.svelte";
import WidgetSection from "/src/components/widgets/WidgetSection.svelte";
import WidgetSpan from "/src/components/widgets/WidgetSpan.svelte";
import WidgetTable from "/src/components/widgets/WidgetTable.svelte";
import type { Layout, LayoutTarget } from "/wrapper/pkg/graphite_wasm_wrapper";
export let layout: Layout;
export let layoutTarget: LayoutTarget;
@@ -1,13 +1,10 @@
<script lang="ts">
import { getContext } from "svelte";
import type { LayoutTarget, WidgetSection as WidgetSectionData } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import IconButton from "@graphite/components/widgets/buttons/IconButton.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
import WidgetSpan from "@graphite/components/widgets/WidgetSpan.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import WidgetSpan from "/src/components/widgets/WidgetSpan.svelte";
import type { EditorWrapper, LayoutTarget, WidgetSection as WidgetSectionData } from "/wrapper/pkg/graphite_wasm_wrapper";
export let widgetData: WidgetSectionData;
export let layoutTarget: LayoutTarget;
@@ -18,7 +15,7 @@
let expanded = true;
const editor = getContext<Editor>("editor");
const editor = getContext<EditorWrapper>("editor");
</script>
<!-- TODO: Implement collapsable sections with properties system -->
@@ -31,7 +28,7 @@
tooltipDescription={widgetData.pinned ? "Unpin this node so it's no longer shown here when nothing is selected." : "Pin this node so it's shown here when nothing is selected."}
size={24}
action={(e) => {
editor.handle.setNodePinned(widgetData.id, !widgetData.pinned);
editor.setNodePinned(widgetData.id, !widgetData.pinned);
e?.stopPropagation();
}}
class="show-only-on-hover"
@@ -41,7 +38,7 @@
tooltipDescription="Delete this node from the layer chain."
size={24}
action={(e) => {
editor.handle.deleteNode(widgetData.id);
editor.deleteNode(widgetData.id);
e?.stopPropagation();
}}
class="show-only-on-hover"
@@ -52,7 +49,7 @@
tooltipDescription={widgetData.visible ? "Hide this node." : "Show this node."}
size={24}
action={(e) => {
editor.handle.toggleNodeVisibilityLayerPanel(widgetData.id);
editor.toggleNodeVisibilityLayerPanel(widgetData.id);
e?.stopPropagation();
}}
class={widgetData.visible ? "show-only-on-hover" : ""}
@@ -1,33 +1,29 @@
<script lang="ts">
import { getContext } from "svelte";
import type { LayoutTarget, Widget, WidgetInstance } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import { parseFillChoice } from "@graphite/utility-functions/colors";
import { debouncer } from "@graphite/utility-functions/debounce";
import NodeCatalog from "@graphite/components/floating-menus/NodeCatalog.svelte";
import BreadcrumbTrailButtons from "@graphite/components/widgets/buttons/BreadcrumbTrailButtons.svelte";
import IconButton from "@graphite/components/widgets/buttons/IconButton.svelte";
import ImageButton from "@graphite/components/widgets/buttons/ImageButton.svelte";
import ParameterExposeButton from "@graphite/components/widgets/buttons/ParameterExposeButton.svelte";
import PopoverButton from "@graphite/components/widgets/buttons/PopoverButton.svelte";
import TextButton from "@graphite/components/widgets/buttons/TextButton.svelte";
import CheckboxInput from "@graphite/components/widgets/inputs/CheckboxInput.svelte";
import ColorInput from "@graphite/components/widgets/inputs/ColorInput.svelte";
import CurveInput from "@graphite/components/widgets/inputs/CurveInput.svelte";
import DropdownInput from "@graphite/components/widgets/inputs/DropdownInput.svelte";
import NumberInput from "@graphite/components/widgets/inputs/NumberInput.svelte";
import RadioInput from "@graphite/components/widgets/inputs/RadioInput.svelte";
import ReferencePointInput from "@graphite/components/widgets/inputs/ReferencePointInput.svelte";
import TextAreaInput from "@graphite/components/widgets/inputs/TextAreaInput.svelte";
import TextInput from "@graphite/components/widgets/inputs/TextInput.svelte";
import WorkingColorsInput from "@graphite/components/widgets/inputs/WorkingColorsInput.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import ImageLabel from "@graphite/components/widgets/labels/ImageLabel.svelte";
import Separator from "@graphite/components/widgets/labels/Separator.svelte";
import ShortcutLabel from "@graphite/components/widgets/labels/ShortcutLabel.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
import NodeCatalog from "/src/components/floating-menus/NodeCatalog.svelte";
import BreadcrumbTrailButtons from "/src/components/widgets/buttons/BreadcrumbTrailButtons.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import ImageButton from "/src/components/widgets/buttons/ImageButton.svelte";
import ParameterExposeButton from "/src/components/widgets/buttons/ParameterExposeButton.svelte";
import PopoverButton from "/src/components/widgets/buttons/PopoverButton.svelte";
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
import CheckboxInput from "/src/components/widgets/inputs/CheckboxInput.svelte";
import ColorInput from "/src/components/widgets/inputs/ColorInput.svelte";
import CurveInput from "/src/components/widgets/inputs/CurveInput.svelte";
import DropdownInput from "/src/components/widgets/inputs/DropdownInput.svelte";
import NumberInput from "/src/components/widgets/inputs/NumberInput.svelte";
import RadioInput from "/src/components/widgets/inputs/RadioInput.svelte";
import ReferencePointInput from "/src/components/widgets/inputs/ReferencePointInput.svelte";
import TextAreaInput from "/src/components/widgets/inputs/TextAreaInput.svelte";
import TextInput from "/src/components/widgets/inputs/TextInput.svelte";
import WorkingColorsInput from "/src/components/widgets/inputs/WorkingColorsInput.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import ImageLabel from "/src/components/widgets/labels/ImageLabel.svelte";
import Separator from "/src/components/widgets/labels/Separator.svelte";
import ShortcutLabel from "/src/components/widgets/labels/ShortcutLabel.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import { parseFillChoice } from "/src/utility-functions/colors";
import type { EditorWrapper, LayoutTarget, Widget, WidgetInstance } from "/wrapper/pkg/graphite_wasm_wrapper";
// Extract the discriminant key names from the Widget tagged enum union (e.g. "TextButton" | "CheckboxInput" | ...)
type WidgetKind = Widget extends infer T ? (T extends Record<infer K, unknown> ? K & string : never) : never;
@@ -36,7 +32,7 @@
// A Widget tagged enum unwrapped into a correlated [kind, props] tuple
type UnwrappedWidget = { [K in WidgetKind]: [kind: K, props: WidgetProps<K>] }[WidgetKind];
const editor = getContext<Editor>("editor");
const editor = getContext<EditorWrapper>("editor");
export let widgets: WidgetInstance[];
export let direction: "row" | "column";
@@ -53,15 +49,15 @@
.join(" ");
function widgetValueCommit(widgetIndex: number, value: unknown) {
editor.handle.widgetValueCommit(layoutTarget, widgets[widgetIndex].widgetId, value);
editor.widgetValueCommit(layoutTarget, widgets[widgetIndex].widgetId, value);
}
function widgetValueUpdate(widgetIndex: number, value: unknown, resendWidget: boolean) {
editor.handle.widgetValueUpdate(layoutTarget, widgets[widgetIndex].widgetId, value, resendWidget);
editor.widgetValueUpdate(layoutTarget, widgets[widgetIndex].widgetId, value, resendWidget);
}
function widgetValueCommitAndUpdate(widgetIndex: number, value: unknown, resendWidget: boolean) {
editor.handle.widgetValueCommitAndUpdate(layoutTarget, widgets[widgetIndex].widgetId, value, resendWidget);
editor.widgetValueCommitAndUpdate(layoutTarget, widgets[widgetIndex].widgetId, value, resendWidget);
}
// Extracts the kind and props from a Widget tagged enum, validated against the widget registry.
@@ -137,7 +133,7 @@
getProps: (props, index) => ({
...props,
$$events: {
value: (e: CustomEvent) => debouncer((value: unknown) => widgetValueCommitAndUpdate(index, value, false), { debounceTime: 120 }).debounceUpdateValue(e.detail),
value: (e: CustomEvent) => widgetValueCommitAndUpdate(index, e.detail, false),
},
}),
},
@@ -202,7 +198,7 @@
incrementCallbackIncrease: () => widgetValueCommitAndUpdate(index, "Increment", false),
incrementCallbackDecrease: () => widgetValueCommitAndUpdate(index, "Decrement", false),
$$events: {
value: (e: CustomEvent) => debouncer((value: unknown) => widgetValueUpdate(index, value, true)).debounceUpdateValue(e.detail),
value: (e: CustomEvent) => widgetValueUpdate(index, e.detail, true),
startHistoryTransaction: () => widgetValueCommit(index, props.value),
},
}),
@@ -1,7 +1,6 @@
<script lang="ts">
import type { LayoutTarget, WidgetTable } from "@graphite/../wasm/pkg/graphite_wasm";
import WidgetSpan from "@graphite/components/widgets/WidgetSpan.svelte";
import WidgetSpan from "/src/components/widgets/WidgetSpan.svelte";
import type { LayoutTarget, WidgetTable } from "/wrapper/pkg/graphite_wasm_wrapper";
export let widgetData: WidgetTable;
export let layoutTarget: LayoutTarget;
@@ -1,8 +1,7 @@
<script lang="ts">
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import TextButton from "@graphite/components/widgets/buttons/TextButton.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
// Content
export let labels: string[];
@@ -1,8 +1,7 @@
<script lang="ts">
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { IconName, IconSize } from "@graphite/icons";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import type { IconName, IconSize } from "/src/icons";
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
// Content
export let icon: IconName;
@@ -1,6 +1,6 @@
<script lang="ts">
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import { IMAGE_BASE64_STRINGS } from "@graphite/utility-functions/images";
import { IMAGE_BASE64_STRINGS } from "/src/utility-functions/images";
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
let className = "";
export { className as class };
@@ -1,7 +1,6 @@
<script lang="ts">
import type { FrontendGraphDataType, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import type { FrontendGraphDataType, ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
// Content
export let exposed: boolean;
@@ -1,12 +1,11 @@
<script lang="ts">
import type { MenuDirection, ActionShortcut, Layout, LayoutTarget } from "@graphite/../wasm/pkg/graphite_wasm";
import type { IconName, PopoverButtonStyle } from "@graphite/icons";
import FloatingMenu from "@graphite/components/layout/FloatingMenu.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import IconButton from "@graphite/components/widgets/buttons/IconButton.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import WidgetLayout from "@graphite/components/widgets/WidgetLayout.svelte";
import FloatingMenu from "/src/components/layout/FloatingMenu.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import type { IconName, PopoverButtonStyle } from "/src/icons";
import type { MenuDirection, ActionShortcut, Layout, LayoutTarget } from "/wrapper/pkg/graphite_wasm_wrapper";
export let layoutTarget: LayoutTarget;
@@ -1,13 +1,11 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { MenuListEntry, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { IconName } from "@graphite/icons";
import MenuList from "@graphite/components/floating-menus/MenuList.svelte";
import ConditionalWrapper from "@graphite/components/layout/ConditionalWrapper.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
import MenuList from "/src/components/floating-menus/MenuList.svelte";
import ConditionalWrapper from "/src/components/layout/ConditionalWrapper.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { IconName } from "/src/icons";
import type { MenuListEntry, ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
const dispatch = createEventDispatcher<{ selectedEntryValuePath: string[] }>();
@@ -1,11 +1,9 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { IconName } from "@graphite/icons";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import type { IconName } from "/src/icons";
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
const dispatch = createEventDispatcher<{ checked: boolean }>();
const backupId = String(Math.random()).substring(2);
@@ -1,11 +1,9 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { FillChoice, MenuDirection, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import { contrastingOutlineFactor, fillChoiceColor, fillChoiceGradientStops, colorToHexOptionalAlpha, gradientToLinearGradientCSS } from "@graphite/utility-functions/colors";
import ColorPicker from "@graphite/components/floating-menus/ColorPicker.svelte";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import ColorPicker from "/src/components/floating-menus/ColorPicker.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import { contrastingOutlineFactor, fillChoiceColor, fillChoiceGradientStops, colorToHexOptionalAlpha, gradientToLinearGradientCSS } from "/src/utility-functions/colors";
import type { FillChoice, MenuDirection, ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
const dispatch = createEventDispatcher<{ value: FillChoice; startHistoryTransaction: undefined }>();
@@ -1,10 +1,7 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { Curve, CurveManipulatorGroup, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import { clamp } from "@graphite/utility-functions/math";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import type { Curve, CurveManipulatorGroup, ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
const dispatch = createEventDispatcher<{
value: Curve;
@@ -185,6 +182,10 @@
dAttribute = recalculateSvgPath();
updateCurve();
}
function clamp(value: number, min = 0, max = 1): number {
return Math.max(min, Math.min(value, max));
}
</script>
<LayoutRow class="curve-input" {tooltipLabel} {tooltipDescription} {tooltipShortcut}>
@@ -1,12 +1,10 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { MenuListEntry, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import MenuList from "@graphite/components/floating-menus/MenuList.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
import MenuList from "/src/components/floating-menus/MenuList.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { MenuListEntry, ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
const DASH_ENTRY: MenuListEntry = {
value: "",
@@ -1,11 +1,9 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import { operatingSystem } from "@graphite/utility-functions/platform";
import { preventEscapeClosingParentFloatingMenu } from "@graphite/components/layout/FloatingMenu.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import { preventEscapeClosingParentFloatingMenu } from "/src/components/layout/FloatingMenu.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import { operatingSystem } from "/src/utility-functions/platform";
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
const dispatch = createEventDispatcher<{
value: string;
@@ -1,14 +1,11 @@
<script lang="ts">
import { createEventDispatcher, onMount, onDestroy, getContext } from "svelte";
import { evaluateMathExpression, isPlatformNative } from "@graphite/../wasm/pkg/graphite_wasm";
import type { NumberInputMode, NumberInputIncrementBehavior, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import { PRESS_REPEAT_DELAY_MS, PRESS_REPEAT_INTERVAL_MS } from "@graphite/io-managers/input";
import { browserVersion } from "@graphite/utility-functions/platform";
import { preventEscapeClosingParentFloatingMenu } from "@graphite/components/layout/FloatingMenu.svelte";
import FieldInput from "@graphite/components/widgets/inputs/FieldInput.svelte";
import { preventEscapeClosingParentFloatingMenu } from "/src/components/layout/FloatingMenu.svelte";
import FieldInput from "/src/components/widgets/inputs/FieldInput.svelte";
import { PRESS_REPEAT_DELAY_MS, PRESS_REPEAT_INTERVAL_MS } from "/src/managers/input";
import { browserVersion } from "/src/utility-functions/platform";
import { evaluateMathExpression, isPlatformNative } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { ActionShortcut, EditorWrapper, NumberInputIncrementBehavior, NumberInputMode } from "/wrapper/pkg/graphite_wasm_wrapper";
const BUTTONS_LEFT = 0b0000_0001;
const BUTTONS_RIGHT = 0b0000_0010;
@@ -17,7 +14,7 @@
const dispatch = createEventDispatcher<{ value: number | undefined; startHistoryTransaction: undefined }>();
const editor = getContext<Editor>("editor");
const editor = getContext<EditorWrapper>("editor");
// Content
/// When `value` is not provided (i.e. it's `undefined`), a dash is displayed.
@@ -87,6 +84,12 @@
let shiftKeyDown = false;
// Track whether the Ctrl key is currently held down.
let ctrlKeyDown = false;
// Cleanup function for active drag interactions, called on destroy to prevent leaked listeners
let activeDragCleanup: (() => void) | undefined;
// Track the slider abort state for cleanup on destroy
let sliderResetAbortHandler: (() => void) | undefined;
let sliderAbortTimeout1: ReturnType<typeof setTimeout> | undefined;
let sliderAbortTimeout2: ReturnType<typeof setTimeout> | undefined;
$: watchValue(value, unit);
$: sliderStepValue = isInteger ? (step === undefined ? 1 : step) : "any";
@@ -107,10 +110,31 @@
addEventListener("mousemove", trackShiftAndCtrl);
});
onDestroy(() => {
clearTimeout(repeatTimeout);
clearTimeout(sliderAbortTimeout1);
clearTimeout(sliderAbortTimeout2);
activeDragCleanup?.();
// Exit pointer lock if active (non-Safari path)
if (document.pointerLockElement) document.exitPointerLock();
// Remove Safari cursor-hidden workaround class if present
const isSafari = browserVersion().toLowerCase().includes("safari");
if (isSafari) document.body.classList.remove("cursor-hidden");
// Clean up any listeners related to tracking the Shift and Ctrl keys
removeEventListener("keydown", trackShiftAndCtrl);
removeEventListener("keyup", trackShiftAndCtrl);
removeEventListener("mousemove", trackShiftAndCtrl);
clearTimeout(repeatTimeout);
// Clean up any slider-related listeners that may be active
removeEventListener("mousedown", sliderAbortFromMousedown);
removeEventListener("keydown", sliderAbortFromMousedown);
removeEventListener("pointermove", sliderAbortFromDragging);
removeEventListener("keydown", sliderAbortFromDragging);
removeEventListener("keydown", incrementPressAbort);
if (sliderResetAbortHandler) removeEventListener("pointerup", sliderResetAbortHandler);
});
// ===============================
@@ -297,7 +321,7 @@
pressingArrow = false;
clearTimeout(repeatTimeout);
updateValue(initialValueBeforeDragging);
removeEventListener("keydown", onIncrementPointerUp);
removeEventListener("keydown", incrementPressAbort);
}
// =======================================
@@ -333,10 +357,9 @@
alreadyActedGuard = true;
isDragging = true;
beginDrag(e);
removeEventListener("pointermove", onMove);
removeEventListener("pointerup", onUp);
activeDragCleanup?.();
beginDrag(e);
};
// If it's a mouseup, we'll begin editing the text field.
const onUp = () => {
@@ -346,11 +369,15 @@
isDragging = false;
self?.focus();
removeEventListener("pointermove", onMove);
removeEventListener("pointerup", onUp);
activeDragCleanup?.();
};
addEventListener("pointermove", onMove);
addEventListener("pointerup", onUp);
activeDragCleanup = () => {
removeEventListener("pointermove", onMove);
removeEventListener("pointerup", onUp);
activeDragCleanup = undefined;
};
}
function beginDrag(e: PointerEvent) {
@@ -378,7 +405,7 @@
// Enter dragging state
if (usePointerLock) target.requestPointerLock();
if (isPlatformNative()) {
editor.handle.appWindowPointerLock();
editor.appWindowPointerLock();
}
initialValueBeforeDragging = value;
cumulativeDragDelta = 0;
@@ -449,16 +476,20 @@
cumulativeDragDelta = 0;
// Clean up the event listeners.
removeEventListener("pointerup", pointerUp);
removeEventListener("pointermove", pointerMove);
removeEventListener("pointerlockmove", pointerLockMove);
if (usePointerLock) document.removeEventListener("pointerlockchange", pointerLockChange);
activeDragCleanup?.();
};
addEventListener("pointerup", pointerUp);
addEventListener("pointermove", pointerMove);
addEventListener("pointerlockmove", pointerLockMove);
if (usePointerLock) document.addEventListener("pointerlockchange", pointerLockChange);
activeDragCleanup = () => {
removeEventListener("pointerup", pointerUp);
removeEventListener("pointermove", pointerMove);
removeEventListener("pointerlockmove", pointerLockMove);
if (usePointerLock) document.removeEventListener("pointerlockchange", pointerLockChange);
activeDragCleanup = undefined;
};
}
function pointerLockMoveUpdate(delta: number, slow: boolean, snapping: boolean, initialValue: number) {
@@ -657,7 +688,7 @@
// End the user's drag by instantaneously disabling and re-enabling the range input element
if (inputRangeElement) inputRangeElement.disabled = true;
setTimeout(() => {
sliderAbortTimeout1 = setTimeout(() => {
if (inputRangeElement) inputRangeElement.disabled = false;
}, 0);
@@ -680,11 +711,13 @@
// dragging the slider, hitting Escape, then releasing the mouse button. This results in being transferred by `onSliderInput()` to the
// "Deciding" state when we should remain in the "Ready" state as set here. (For debugging, this can be visualized in CSS by
// recoloring the fake slider handle, which is shown in the "Deciding" state.)
setTimeout(() => (rangeSliderClickDragState = "Ready"), 0);
sliderAbortTimeout2 = setTimeout(() => (rangeSliderClickDragState = "Ready"), 0);
// Clean up the event listener that was used to call this function.
removeEventListener("pointerup", sliderResetAbort);
sliderResetAbortHandler = undefined;
};
sliderResetAbortHandler = sliderResetAbort;
addEventListener("pointerup", sliderResetAbort);
// Clean up the event listeners that were for tracking an abort while dragging the slider, now that we're no longer dragging it.
@@ -1,11 +1,9 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { RadioEntryData } from "@graphite/../wasm/pkg/graphite_wasm";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { RadioEntryData } from "/wrapper/pkg/graphite_wasm_wrapper";
const dispatch = createEventDispatcher<{ selectedIndex: number }>();
@@ -1,7 +1,6 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { ReferencePoint, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { ReferencePoint, ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
const dispatch = createEventDispatcher<{ value: ReferencePoint }>();
@@ -1,7 +1,6 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import { PRESS_REPEAT_DELAY_MS, PRESS_REPEAT_INTERVAL_MS, PRESS_REPEAT_INTERVAL_RAPID_MS } from "@graphite/io-managers/input";
import { createEventDispatcher, onDestroy } from "svelte";
import { PRESS_REPEAT_DELAY_MS, PRESS_REPEAT_INTERVAL_MS, PRESS_REPEAT_INTERVAL_RAPID_MS } from "/src/managers/input";
const ARROW_CLICK_DISTANCE = 0.05;
const ARROW_REPEAT_DISTANCE = 0.01;
@@ -187,6 +186,10 @@
if (e.key === "Escape") abortInteraction();
}
onDestroy(() => {
removeEvents();
});
function addEvents() {
window.addEventListener("pointerup", onPointerUp);
window.addEventListener("pointermove", onPointerMove);
@@ -4,15 +4,13 @@
</script>
<script lang="ts">
import { createEventDispatcher, onDestroy } from "svelte";
import { evaluateGradientAtPosition } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Color, GradientStops } from "@graphite/../wasm/pkg/graphite_wasm";
import { colorToHexOptionalAlpha, colorToRgbCSS, gradientFirstColor, gradientLastColor, gradientToLinearGradientCSS } from "@graphite/utility-functions/colors";
import { preventEscapeClosingParentFloatingMenu } from "@graphite/components/layout/FloatingMenu.svelte";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import { createEventDispatcher, onMount, onDestroy } from "svelte";
import { preventEscapeClosingParentFloatingMenu } from "/src/components/layout/FloatingMenu.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import { colorToHexOptionalAlpha, colorToRgbCSS, gradientFirstColor, gradientLastColor, gradientToLinearGradientCSS } from "/src/utility-functions/colors";
import { evaluateGradientAtPosition } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { Color, GradientStops } from "/wrapper/pkg/graphite_wasm_wrapper";
const BUTTON_LEFT = 0;
const BUTTON_RIGHT = 2;
@@ -338,7 +336,9 @@
document.removeEventListener("keydown", onKeyDown);
}
document.addEventListener("keydown", deleteStop);
onMount(() => {
document.addEventListener("keydown", deleteStop);
});
onDestroy(() => {
removeEvents();
document.removeEventListener("keydown", deleteStop);
@@ -1,9 +1,7 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import FieldInput from "@graphite/components/widgets/inputs/FieldInput.svelte";
import FieldInput from "/src/components/widgets/inputs/FieldInput.svelte";
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
const dispatch = createEventDispatcher<{ commitText: string }>();
@@ -1,9 +1,7 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import FieldInput from "@graphite/components/widgets/inputs/FieldInput.svelte";
import FieldInput from "/src/components/widgets/inputs/FieldInput.svelte";
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
const dispatch = createEventDispatcher<{ commitText: string }>();
@@ -1,15 +1,12 @@
<script lang="ts">
import { getContext } from "svelte";
import ColorPicker from "/src/components/floating-menus/ColorPicker.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import { fillChoiceColor, colorToRgbaCSS } from "/src/utility-functions/colors";
import type { Color, EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { Color } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import { fillChoiceColor, colorToRgbaCSS } from "@graphite/utility-functions/colors";
import ColorPicker from "@graphite/components/floating-menus/ColorPicker.svelte";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
const editor = getContext<Editor>("editor");
const editor = getContext<EditorWrapper>("editor");
// Content
export let primary: Color;
@@ -29,11 +26,11 @@
}
function primaryColorChanged(color: Color) {
editor.handle.updatePrimaryColor(color.red, color.green, color.blue, color.alpha);
editor.updatePrimaryColor(color.red, color.green, color.blue, color.alpha);
}
function secondaryColorChanged(color: Color) {
editor.handle.updateSecondaryColor(color.red, color.green, color.blue, color.alpha);
editor.updateSecondaryColor(color.red, color.green, color.blue, color.alpha);
}
</script>
@@ -1,9 +1,8 @@
<script lang="ts">
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import { ICONS, ICON_SVG_STRINGS } from "@graphite/icons";
import type { IconName } from "@graphite/icons";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import { ICONS, ICON_SVG_STRINGS } from "/src/icons";
import type { IconName } from "/src/icons";
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
let className = "";
export { className as class };
@@ -1,5 +1,5 @@
<script lang="ts">
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
let className = "";
export { className as class };
@@ -1,5 +1,5 @@
<script lang="ts">
import type { SeparatorDirection, SeparatorStyle } from "@graphite/../wasm/pkg/graphite_wasm";
import type { SeparatorDirection, SeparatorStyle } from "/wrapper/pkg/graphite_wasm_wrapper";
// Content
export let direction: SeparatorDirection = "Horizontal";
@@ -1,11 +1,10 @@
<script lang="ts">
import type { ActionShortcut, Key, LabeledShortcut, MouseMotion } from "@graphite/../wasm/pkg/graphite_wasm";
import type { IconName } from "@graphite/icons";
import { operatingSystem } from "@graphite/utility-functions/platform";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { IconName } from "/src/icons";
import { operatingSystem } from "/src/utility-functions/platform";
import type { ActionShortcut, Key, LabeledShortcut, MouseMotion } from "/wrapper/pkg/graphite_wasm_wrapper";
// Content
export let shortcut: ActionShortcut;
@@ -1,7 +1,6 @@
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
let className = "";
export { className as class };
@@ -62,7 +61,10 @@
}
onMount(() => watchForCheckbox(forCheckbox));
onDestroy(() => watchForCheckbox(undefined));
onDestroy(() => {
handlePointerLeave();
watchForCheckbox(undefined);
});
</script>
<label
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff. Show more