Compare commits

..

No commits in common. "next" and "main" have entirely different histories.
next ... main

167 changed files with 22446 additions and 0 deletions

18
.drone.yml Normal file
View File

@ -0,0 +1,18 @@
kind: pipeline
name: web
type: docker
steps:
- name: deploy web
image: node:alpine
environment:
IS_PROD: true
TOKEN:
from_secret: VERCEL_TOKEN
when:
branch:
- main
commands:
- npm install -g vercel@latest
- cd web
- /bin/sh deploy.sh

50
.github/workflows/publish.yml vendored Normal file
View File

@ -0,0 +1,50 @@
name: "publish"
on:
push:
branches:
- release
jobs:
publish-tauri:
permissions:
contents: write
strategy:
fail-fast: false
matrix:
platform: [macos-latest, ubuntu-20.04, windows-latest]
runs-on: ${{ matrix.platform }}
defaults:
run:
working-directory: app
steps:
- uses: actions/checkout@v3
- name: setup node
uses: actions/setup-node@v3
with:
node-version: 16
- name: install Rust stable
uses: dtolnay/rust-toolchain@stable
- name: install dependencies (ubuntu only)
if: matrix.platform == 'ubuntu-20.04'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev libappindicator3-dev librsvg2-dev patchelf
- name: setup .npmrc
run: mv .npmrc.githubactions .npmrc
- name: install frontend dependencies
run: yarn install # change this to npm or pnpm depending on which one you use
env:
UNOM_PACKAGES_TOKEN: ${{ secrets.UNOM_PACKAGES_TOKEN }}
- uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
UNOM_PACKAGES_TOKEN: ${{ secrets.UNOM_PACKAGES_TOKEN }}
with:
tagName: app-v__VERSION__ # the action automatically replaces \_\_VERSION\_\_ with the app version
releaseName: "App v__VERSION__"
releaseBody: "See the assets to download this version and install."
releaseDraft: true
prerelease: false

39
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,39 @@
name: "test-on-pr"
on: [pull_request]
jobs:
test-app:
strategy:
fail-fast: false
matrix:
platform: [macos-latest, ubuntu-20.04, windows-latest]
runs-on: ${{ matrix.platform }}
defaults:
run:
working-directory: app
steps:
- uses: actions/checkout@v3
- name: setup node
uses: actions/setup-node@v3
with:
node-version: 16
- name: install Rust stable
uses: dtolnay/rust-toolchain@stable
- name: install dependencies (ubuntu only)
if: matrix.platform == 'ubuntu-20.04'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev libappindicator3-dev librsvg2-dev patchelf
- name: setup .npmrc
run: mv .npmrc.githubactions .npmrc
- name: install frontend dependencies
run: yarn install # change this to npm or pnpm depending on which one you use
env:
UNOM_PACKAGES_TOKEN: ${{ secrets.UNOM_PACKAGES_TOKEN }}
- uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
UNOM_PACKAGES_TOKEN: ${{ secrets.UNOM_PACKAGES_TOKEN }}

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.DS_Store

7
LICENSE.md Normal file
View File

@ -0,0 +1,7 @@
Copyright 2023 Enrico Bühler
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

24
app/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

4
app/.npmrc.githubactions Normal file
View File

@ -0,0 +1,4 @@
//packages.unom.io/:_authToken=${UNOM_PACKAGES_TOKEN}
registry=https://registry.npmjs.org/
@tempblade:registry=https://packages.unom.io
@unom:registry=https://packages.unom.io

6
app/.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"recommendations": [
"tauri-apps.tauri-vscode",
"rust-lang.rust-analyzer"
]
}

BIN
app/.yarn/install-state.gz Normal file

Binary file not shown.

1
app/.yarnrc.yml Normal file
View File

@ -0,0 +1 @@
nodeLinker: node-modules

11
app/README.md Normal file
View File

@ -0,0 +1,11 @@
# tempblade Creator
This is the directory containing the application. It uses tauri with react/vite.
## Commands
Start the dev server:
```yarn tauri dev```
Create a production build:
```yarn tauri build```

BIN
app/app-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

16
app/index.html Normal file
View File

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>tempblade Creator</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

67
app/package.json Normal file
View File

@ -0,0 +1,67 @@
{
"name": "app",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"tauri": "tauri"
},
"dependencies": {
"@radix-ui/colors": "^0.1.8",
"@radix-ui/react-form": "^0.0.2",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-menubar": "^1.0.2",
"@radix-ui/react-popover": "^1.0.6",
"@radix-ui/react-scroll-area": "^1.0.4",
"@radix-ui/react-select": "^1.2.2",
"@radix-ui/react-slider": "^1.1.1",
"@radix-ui/react-toggle-group": "^1.0.4",
"@radix-ui/react-toolbar": "^1.0.3",
"@tauri-apps/api": "^1.3.0",
"@tempblade/common": "^2.0.1",
"@types/d3-array": "^3.0.5",
"@types/lodash.set": "^4.3.7",
"@unom/style": "^0.2.14",
"@visx/axis": "^3.1.0",
"@visx/event": "^3.0.1",
"@visx/glyph": "^3.0.0",
"@visx/gradient": "^3.0.0",
"@visx/grid": "^3.0.1",
"@visx/group": "^3.0.0",
"@visx/responsive": "^3.0.0",
"@visx/scale": "^3.0.0",
"@visx/shape": "^3.0.0",
"@visx/tooltip": "^3.1.2",
"canvaskit-wasm": "^0.38.1",
"class-variance-authority": "^0.6.0",
"clsx": "^1.2.1",
"framer-motion": "^10.12.12",
"immer": "^10.0.2",
"lodash.set": "^4.3.2",
"lucide-react": "^0.229.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"tailwind-merge": "^1.12.0",
"tailwindcss-animate": "^1.0.5",
"uuid": "^9.0.0",
"zod": "^3.21.4",
"zustand": "^4.3.8"
},
"devDependencies": {
"@tauri-apps/cli": "^1.3.0",
"@types/node": "^18.7.10",
"@types/react": "^18.0.15",
"@types/react-dom": "^18.0.6",
"@types/uuid": "^9",
"@vitejs/plugin-react": "^3.0.0",
"autoprefixer": "^10.4.14",
"postcss": "^8.4.23",
"tailwindcss": "^3.3.2",
"typescript": "^4.9.5",
"vite": "^4.2.1",
"vite-tsconfig-paths": "^4.2.0"
}
}

6
app/postcss.config.js Normal file
View File

@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

BIN
app/public/canvaskit.wasm Normal file

Binary file not shown.

6
app/public/tauri.svg Normal file
View File

@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

1
app/public/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

4
app/src-tauri/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
# Generated by Cargo
# will have compiled files and executables
/target/

4061
app/src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

31
app/src-tauri/Cargo.toml Normal file
View File

@ -0,0 +1,31 @@
[package]
name = "tempblade-creator-app"
version = "0.0.0"
description = "An open motion design tool written in rust"
authors = ["enricobuehler"]
license = "BSD 3-Clause"
repository = "https://git.unom.io/tempblade/creator"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
tauri-build = { version = "1.4", features = [] }
[dependencies]
creator_core = { path = "../../lib/creator_rs", features = [
"fonts",
"parallelization",
"tauri",
], version = "*", package = "creator_rs" }
tauri = { version = "1.4", features = ["dialog-open", "dialog-save", "shell-open"] }
serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0"
tint = "1.0.0"
logging_timer = "1.1.0"
[features]
# this feature is used for production builds or when `devPath` points to the filesystem
# DO NOT REMOVE!!
custom-protocol = ["tauri/custom-protocol"]

3
app/src-tauri/build.rs Normal file
View File

@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 268 KiB

33
app/src-tauri/src/main.rs Normal file
View File

@ -0,0 +1,33 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use creator_core::{
__cmd__calculate_timeline_at_curr_frame, __cmd__get_system_families, __cmd__get_system_font,
__cmd__get_system_fonts, __cmd__get_values_at_frame_range_from_animated_float,
__cmd__get_values_at_frame_range_from_animated_float_vec2,
__cmd__get_values_at_frame_range_from_animated_float_vec3,
animation::{
primitives::values::animated_values::{
get_values_at_frame_range_from_animated_float,
get_values_at_frame_range_from_animated_float_vec2,
get_values_at_frame_range_from_animated_float_vec3,
},
timeline::calculate_timeline_at_curr_frame,
},
fonts::fonts::{get_system_families, get_system_font, get_system_fonts},
};
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![
calculate_timeline_at_curr_frame,
get_system_font,
get_system_families,
get_system_fonts,
get_values_at_frame_range_from_animated_float,
get_values_at_frame_range_from_animated_float_vec2,
get_values_at_frame_range_from_animated_float_vec3
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

View File

@ -0,0 +1,53 @@
{
"build": {
"beforeDevCommand": "yarn dev",
"beforeBuildCommand": "yarn build",
"devPath": "http://localhost:1420",
"distDir": "../dist",
"withGlobalTauri": false
},
"package": {
"productName": "tempblade Creator",
"version": "0.1.0"
},
"tauri": {
"allowlist": {
"all": false,
"dialog": {
"open": true,
"save": true
},
"shell": {
"all": false,
"open": true
}
},
"bundle": {
"active": true,
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"identifier": "com.tempblade.creator",
"targets": "all"
},
"security": {
"csp": null
},
"updater": {
"active": false
},
"windows": [
{
"fullscreen": false,
"resizable": true,
"title": "tempblade Creator",
"width": 1300,
"height": 900
}
]
}
}

7
app/src/App.css Normal file
View File

@ -0,0 +1,7 @@
.logo.vite:hover {
filter: drop-shadow(0 0 2em #747bff);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafb);
}

40
app/src/App.tsx Normal file
View File

@ -0,0 +1,40 @@
import "./App.css";
import Timeline from "./components/Timeline";
import Canvas from "./components/Canvas";
import Properties, { PropertiesContainer } from "components/Properties";
import ToolBar from "components/ToolBar";
import useKeyControls from "hooks/useKeyControls";
import { useFontsStore } from "stores/fonts.store";
import * as ScrollArea from "@radix-ui/react-scroll-area";
import ScrollBar from "components/ScrollArea";
export default function App() {
const fontsStoreDidInit = useFontsStore((store) => store.didInit);
useKeyControls();
return (
<div className="bg-neutral h-full w-full flex flex-col overflow-hidden">
{/* <MenuBar /> */}
<div className="flex flex-row flex-[1] overflow-hidden">
<ToolBar />
{fontsStoreDidInit && (
<ScrollArea.Root className="w-full">
<ScrollArea.Viewport className="w-full h-full">
<div className="flex w-full flex-col pl-4 gap-4 pr-4 overflow-x-hidden overflow-y-auto">
<div className="flex w-full gap-4 flex-col lg:flex-row justify-center items-center mt-4">
<Canvas />
<PropertiesContainer>
<Properties />
</PropertiesContainer>
</div>
<Timeline />
</div>
</ScrollArea.Viewport>
<ScrollBar />
</ScrollArea.Root>
)}
</div>
</div>
);
}

View File

@ -0,0 +1,40 @@
import { FC, useMemo } from "react";
import { useEffect, useRef, useState } from "react";
import { PlaybackService } from "services/playback.service";
type CanvasProps = {};
const CanvasComponent: FC<CanvasProps> = () => {
const canvas = useRef<HTMLCanvasElement>(null);
const [didInit, setDidInit] = useState(false);
const playbackService = useMemo(() => new PlaybackService(), []);
useEffect(() => {
if (canvas.current && !didInit) {
playbackService
.init(canvas.current)
.then(() => {
setDidInit(true);
})
.catch((e) => console.error(e));
}
}, []);
return (
<div
className="flex items-center justify-center"
style={{ width: "100%", height: "100%" }}
>
<canvas
style={{ width: "100%", height: "100%" }}
className="h-full object-contain"
height={720}
width={1280}
ref={canvas}
></canvas>
</div>
);
};
export default CanvasComponent;

View File

@ -0,0 +1,30 @@
import { useCallback, useState } from "react";
import { z } from "zod";
type FloatInputProps = {
value: number;
onChange: (value: number) => void;
id: string;
};
const FloatInput: React.FC<FloatInputProps> = ({ value, onChange, id }) => {
const [inputValue, setInputValue] = useState<string>(value.toString());
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const val = e.target.value.replace(",", ".");
setInputValue(val);
const nextValue = z.coerce.number().min(-9999).max(9999).safeParse(val);
if (nextValue.success) {
onChange(nextValue.data);
}
},
[setInputValue, onChange]
);
return <input id={id} onChange={handleInputChange} value={inputValue} />;
};
export default FloatInput;

View File

@ -0,0 +1,118 @@
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import { Check, ChevronDown } from "lucide-react";
import { cn } from "utils";
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"shadow-main/10 shadow-[0_0_0_1px]",
"flex h-10 w-full items-center justify-between rounded-md",
"text-main bg-transparent px-3 py-2 text-sm placeholder:text-main outline-none",
"disabled:cursor-not-allowed disabled:opacity-50 transition-all",
"focus:outline-none focus:ring-2 focus:ring-offset-1 focus:shadow-primary",
"focus:ring-primary",
"hover:shadow-primary/50",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 min-w-[8rem] overflow-hidden rounded-md border bg-neutral-accent",
"text-main shadow-md animate-in fade-in-80",
className
)}
{...props}
>
<SelectPrimitive.Viewport className={cn("p-1")}>
{children}
</SelectPrimitive.Viewport>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("py-1.5 pl-8 pr-2 text-sm text-main font-semibold", className)}
{...props}
/>
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none",
"focus:bg-primary focus:text-neutral dark:focus:text-main text-main data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText className="text-main">{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-slate-main", className)}
{...props}
/>
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
};

View File

@ -0,0 +1,9 @@
const Loading = () => {
return (
<div>
<h2>Lädt Skia...</h2>
</div>
);
};
export default Loading;

View File

@ -0,0 +1,129 @@
import { FC } from "react";
import * as Menubar from "@radix-ui/react-menubar";
import { ChevronRightIcon } from "@radix-ui/react-icons";
import { open, save } from "@tauri-apps/api/dialog";
const MenuBarTrigger: FC<{ label: string }> = ({ label }) => {
return (
<Menubar.Trigger className="py-2 dark:text-gray-300 px-3 transition-colors hover:bg-indigo-700 outline-none select-none font-medium leading-none rounded text-[13px] flex items-center justify-between gap-[2px]">
{label}
</Menubar.Trigger>
);
};
const MenuBarSubTrigger: FC<{ label: string }> = ({ label }) => {
return (
<Menubar.SubTrigger
className="group dark:text-gray-300 text-[13px] hover:bg-indigo-800 transition-colors leading-none
text-indigo11 rounded flex items-center h-[25px] px-[10px] relative select-none outline-none
data-[state=open]:bg-indigo data-[state=open]:text-white data-[highlighted]:bg-gradient-to-br
data-[highlighted]:from-indigo9 data-[highlighted]:to-indigo10 data-[highlighted]:text-indigo1
data-[highlighted]:data-[state=open]:text-indigo1 data-[disabled]:text-mauve8 data-[disabled]:pointer-events-none"
>
{label}
<div className="ml-auto pl-5 text-mauve9 group-data-[highlighted]:text-white group-data-[disabled]:text-mauve8">
<ChevronRightIcon />
</div>
</Menubar.SubTrigger>
);
};
const MenuBarItem: FC<{ label: string; onClick?: () => void }> = ({
label,
onClick,
}) => {
return (
<Menubar.Item
onClick={onClick}
className="group dark:text-white text-[13px] leading-none
rounded flex items-center h-[25px] px-[10px]
relative select-none outline-none hover:bg-indigo-800
data-[disabled]:pointer-events-none transition-colors"
>
{label}
</Menubar.Item>
);
};
const MenuBarSeperator = () => {
return <Menubar.Separator className="h-[1px] bg-slate-500 m-[5px]" />;
};
const MenuBar = () => {
const menuBarContentClassName =
"min-w-[220px] bg-gray-800 rounded-md p-[5px]";
const menuBarSubContentClassName =
"min-w-[220px] bg-gray-800 rounded-md p-[5px]";
return (
<Menubar.Root className="flex bg-gray-900 p-[3px] ">
<Menubar.Menu>
<MenuBarTrigger label="File" />
<Menubar.Portal>
<Menubar.Content
className={menuBarContentClassName}
align="start"
sideOffset={5}
alignOffset={-3}
>
<MenuBarItem label="New File" />
<MenuBarItem
onClick={() => open({ multiple: false })}
label="Open File"
/>
<MenuBarItem
onClick={() =>
save({
title: "Save Project",
defaultPath: "project.tbcp",
}).then((val) => {
console.log(val);
})
}
label="Save"
/>
<MenuBarItem onClick={() => save()} label="Save as" />
<MenuBarSeperator />
<Menubar.Sub>
<MenuBarSubTrigger label="Export as ..." />
<Menubar.Portal>
<Menubar.SubContent
className={menuBarSubContentClassName}
alignOffset={-5}
>
<MenuBarItem label=".mp4" />
<MenuBarItem label=".gif" />
<MenuBarItem label=".mov" />
<MenuBarItem label=".webm" />
<MenuBarItem label=".webp" />
</Menubar.SubContent>
</Menubar.Portal>
</Menubar.Sub>
</Menubar.Content>
</Menubar.Portal>
</Menubar.Menu>
<Menubar.Menu>
<MenuBarTrigger label="Edit" />
<Menubar.Portal>
<Menubar.Content
className={menuBarContentClassName}
align="start"
sideOffset={5}
alignOffset={-3}
>
<MenuBarItem label="Undo" />
<MenuBarItem label="Redo" />
<MenuBarItem label="Copy" />
<MenuBarItem label="Paste" />
</Menubar.Content>
</Menubar.Portal>
</Menubar.Menu>
</Menubar.Root>
);
};
export default MenuBar;

View File

@ -0,0 +1,15 @@
import { FC, ReactNode } from "react";
const Panel: FC<{ title: string; children: ReactNode }> = ({
title,
children,
}) => {
return (
<div>
<h3>{title}</h3>
<div>{children}</div>
</div>
);
};
export default Panel;

View File

@ -0,0 +1,41 @@
import * as React from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "utils";
import { Cross2Icon } from "@radix-ui/react-icons";
const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverArrow = PopoverPrimitive.Arrow;
const PopoverClose: React.FC<{ onClick?: () => void }> = ({ onClick }) => (
<PopoverPrimitive.Close
onClick={onClick}
className="rounded-full h-[25px] w-[25px] inline-flex items-center justify-center text-white absolute top-[5px] right-[5px] hover:bg-indigo-600 focus:shadow-[0_0_0_2px] focus:shadow-indigo-500 outline-none cursor-default"
aria-label="Close"
>
<Cross2Icon />
</PopoverPrimitive.Close>
);
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none animate-in data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
));
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
export { Popover, PopoverTrigger, PopoverClose, PopoverContent, PopoverArrow };

View File

@ -0,0 +1,255 @@
import { ease } from "@unom/style";
import { motion } from "framer-motion";
import {
AnimatedTextEntity,
AnimatedRectEntity,
AnimatedStaggeredTextEntity,
AnimatedEllipseEntity,
} from "primitives/AnimatedEntities";
import { Paint, PaintStyle, PaintStyleType } from "primitives/Paint";
import { FC } from "react";
import { z } from "zod";
import { ColorProperties } from "./Values";
import { PropertiesProps } from "./common";
import { useFontsStore } from "stores/fonts.store";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "components/Inputs/Select";
type TextPropertiesProps = PropertiesProps<z.input<typeof AnimatedTextEntity>>;
type StaggeredTextPropertiesProps = PropertiesProps<
z.input<typeof AnimatedStaggeredTextEntity>
>;
type PaintPropertiesProps = PropertiesProps<z.input<typeof Paint>>;
type RectPropertiesProps = PropertiesProps<z.input<typeof AnimatedRectEntity>>;
type EllipsePropertiesProps = PropertiesProps<
z.input<typeof AnimatedEllipseEntity>
>;
export const PaintProperties: FC<PaintPropertiesProps> = ({
entity,
onUpdate,
}) => {
return (
<div>
<fieldset>
<label htmlFor="paint-style-type">PaintStyle</label>
<Select
defaultValue={entity.style.type}
onValueChange={(value) => {
if (entity.style.type !== value) {
const paintStyle = { type: value };
const parsedPaintStyle = PaintStyle.parse(paintStyle);
onUpdate({ style: parsedPaintStyle });
}
}}
>
<SelectTrigger>
<SelectValue placeholder="Choose a paint style" />
</SelectTrigger>
<SelectContent id="paint-style-type" className="overflow-hidden">
{Object.keys(PaintStyleType.Values).map((paintStyleType) => (
<SelectItem value={paintStyleType}>{paintStyleType}</SelectItem>
))}
</SelectContent>
</Select>
</fieldset>
{entity.style.color && (
<ColorProperties
label="Color"
onUpdate={(color) =>
onUpdate({ ...entity, style: { ...entity.style, color } })
}
entity={entity.style.color}
/>
)}
</div>
);
};
export const TextProperties: FC<TextPropertiesProps> = ({
entity,
onUpdate,
}) => {
const { fonts } = useFontsStore();
return (
<motion.div
variants={{ enter: { opacity: 1, y: 0 }, from: { opacity: 0, y: 50 } }}
animate="enter"
initial="from"
transition={ease.quint(0.9).out}
>
<fieldset>
<label htmlFor="text-content">Text</label>
<input
id="text-content"
value={entity.text}
onChange={(e) => onUpdate({ ...entity, text: e.target.value })}
/>
</fieldset>
<fieldset>
<label htmlFor="text-size">Size</label>
<input
id="text-size"
value={entity.paint.size}
onChange={(e) =>
onUpdate({
...entity,
paint: { ...entity.paint, size: Number(e.target.value) },
})
}
/>
</fieldset>
<fieldset>
<label htmlFor="text-font">Font</label>
<Select
defaultValue={entity.paint.font_name}
onValueChange={(val) => {
onUpdate({
...entity,
cache: { valid: false },
paint: { ...entity.paint, font_name: val },
});
}}
>
<SelectTrigger>
<SelectValue placeholder="Choose a font" />
</SelectTrigger>
<SelectContent>
{fonts.map((font) => (
<SelectItem value={font}>{font}</SelectItem>
))}
</SelectContent>
</Select>
</fieldset>
</motion.div>
);
};
export const StaggeredTextProperties: FC<StaggeredTextPropertiesProps> = ({
entity,
onUpdate,
}) => {
const { fonts } = useFontsStore();
return (
<motion.div
variants={{ enter: { opacity: 1, y: 0 }, from: { opacity: 0, y: 50 } }}
animate="enter"
initial="from"
transition={ease.quint(0.9).out}
>
<fieldset>
<label htmlFor="staggered-text-content">Text</label>
<input
id="staggered-text-content"
value={entity.text}
onChange={(e) =>
onUpdate({
...entity,
text: e.target.value,
cache: { valid: false },
})
}
/>
</fieldset>
<fieldset>
<label htmlFor="staggered-text-letter-font">Font</label>
<Select
defaultValue={entity.letter.paint.font_name}
onValueChange={(val) => {
onUpdate({
...entity,
cache: { valid: false },
letter: {
...entity.letter,
paint: { ...entity.letter.paint, font_name: val },
},
});
}}
>
<SelectTrigger>
<SelectValue placeholder="Choose a font" />
</SelectTrigger>
<SelectContent className="overflow-hidden">
{fonts.map((font) => (
<SelectItem value={font}>{font}</SelectItem>
))}
</SelectContent>
</Select>
</fieldset>
<fieldset>
<label htmlFor="staggered-text-letter-size">Size</label>
<input
id="staggered-text-letter-size"
value={entity.letter.paint.size}
onChange={(e) =>
onUpdate({
...entity,
cache: { valid: false },
letter: {
...entity.letter,
paint: {
...entity.letter.paint,
size: Number(e.target.value),
},
},
})
}
/>
</fieldset>
<PaintProperties
entity={entity.letter.paint}
onUpdate={(paint) =>
onUpdate({
...entity,
letter: {
...entity.letter,
paint: { ...entity.letter.paint, ...paint },
},
})
}
/>
</motion.div>
);
};
export const RectProperties: FC<RectPropertiesProps> = ({
entity,
onUpdate,
}) => {
return (
<div className="dark:text-white">
<PaintProperties
entity={entity.paint}
onUpdate={(paint) =>
onUpdate({ ...entity, paint: { ...entity.paint, ...paint } })
}
/>
</div>
);
};
export const EllipseProperties: FC<EllipsePropertiesProps> = ({
entity,
onUpdate,
}) => {
return (
<div className="dark:text-white">
<PaintProperties
entity={entity.paint}
onUpdate={(paint) =>
onUpdate({ ...entity, paint: { ...entity.paint, ...paint } })
}
/>
</div>
);
};

View File

@ -0,0 +1,273 @@
import { AnimatedNumber, AnimatedVec2 } from "primitives/Values";
import { PropertiesProps } from "./common";
import { FC } from "react";
import { z } from "zod";
import { produce } from "immer";
import { Interpolation, InterpolationType } from "primitives/Interpolation";
import { Color, PaintStyle, PaintStyleType } from "primitives/Paint";
import { parseCssColor } from "@tempblade/common";
import { rgbToHex } from "utils";
import { SpringInterpolation } from "primitives/Interpolation";
import FloatInput from "components/Inputs/FloatInput";
import { Keyframe } from "primitives/Keyframe";
import {
Select,
SelectTrigger,
SelectValue,
SelectContent,
SelectItem,
} from "components/Inputs/Select";
const SpringInterpolationProperties: FC<
PropertiesProps<z.input<typeof SpringInterpolation>>
> = ({ entity, onUpdate }) => {
return <div></div>;
};
export const InterpolationProperties: FC<
PropertiesProps<z.input<typeof Interpolation>>
> = ({ entity, onUpdate }) => {
return (
<fieldset>
<label className="label" htmlFor="interpolation-type">
Interpolation Type
</label>
<Select
defaultValue={entity.type}
onValueChange={(value) => {
if (entity.type !== value) {
const interpolation = { type: value };
const parsedInterpolation = Interpolation.parse(interpolation);
onUpdate(parsedInterpolation);
}
}}
>
<SelectTrigger>
<SelectValue placeholder="Choose an interpolation type" />
</SelectTrigger>
<SelectContent id="interpolation-type" className="overflow-hidden">
{Object.keys(InterpolationType.Values).map((interpolationType) => (
<SelectItem key={interpolationType} value={interpolationType}>
{interpolationType}
</SelectItem>
))}
</SelectContent>
</Select>
</fieldset>
);
};
export const KeyframeProperties: FC<
PropertiesProps<z.input<typeof Keyframe>>
> = ({ entity, onUpdate }) => {
return (
<>
<fieldset>
<label htmlFor="keyframe-offset">Offset</label>
<FloatInput
value={entity.offset}
onChange={(value) =>
onUpdate(
produce(entity, (draft) => {
draft.offset = value;
})
)
}
id="keyframe-offset"
/>
</fieldset>
<fieldset>
<label>Value</label>
<FloatInput
value={entity.value}
onChange={(value) =>
onUpdate(
produce(entity, (draft) => {
draft.value = value;
})
)
}
id="keyframe-value"
/>
</fieldset>
{entity.interpolation && (
<InterpolationProperties
onUpdate={(updatedEntity) =>
onUpdate(
produce(entity, (draft) => {
draft.interpolation = updatedEntity;
})
)
}
entity={entity.interpolation}
/>
)}
</>
);
};
const AnimatedNumberProperties: FC<
PropertiesProps<z.input<typeof AnimatedNumber>> & { label: string }
> = ({ entity, onUpdate, label }) => {
return (
<div>
<span>{label}</span>
{entity.keyframes.values.map((keyframe, index) => {
return (
<div key={index}>
<KeyframeProperties
entity={keyframe}
onUpdate={(nextKeyframe) =>
onUpdate(
produce(entity, (draft) => {
draft.keyframes.values[index] = nextKeyframe;
})
)
}
/>
</div>
);
})}
</div>
);
};
export const ColorProperties: FC<
PropertiesProps<z.input<typeof Color>> & {
label: string;
mode?: "RGB" | "Picker";
}
> = ({ entity, onUpdate, mode = "Picker" }) => {
if (mode === "Picker") {
return (
<fieldset>
<label htmlFor="color">Color</label>
<input
id="color"
value={rgbToHex(entity.value[0], entity.value[1], entity.value[2])}
type="color"
style={{
border: "none",
width: 32,
height: 32,
backgroundColor: rgbToHex(
entity.value[0],
entity.value[1],
entity.value[2]
),
}}
onChange={(e) =>
onUpdate(
produce(entity, (draft) => {
const color = parseCssColor(e.target.value);
if (color) {
draft.value = [...color, 1.0];
}
})
)
}
/>
</fieldset>
);
}
return (
<label className="flex flex-col items-start">
<span className="label">Color</span>
<div className="flex flex-row gap-3">
<input
value={entity.value[0]}
type="number"
max={255}
onChange={(e) =>
onUpdate(
produce(entity, (draft) => {
draft.value[0] = Number(e.target.value);
})
)
}
/>
<input
value={entity.value[1]}
type="number"
max={255}
onChange={(e) =>
onUpdate(
produce(entity, (draft) => {
draft.value[1] = Number(e.target.value);
})
)
}
/>
<input
value={entity.value[2]}
type="number"
max={255}
onChange={(e) =>
onUpdate(
produce(entity, (draft) => {
draft.value[2] = Number(e.target.value);
})
)
}
/>
<input
value={entity.value[3]}
type="number"
max={1}
onChange={(e) =>
onUpdate(
produce(entity, (draft) => {
draft.value[3] = Number(e.target.value);
})
)
}
/>
</div>
</label>
);
};
export const AnimatedVec2Properties: FC<
PropertiesProps<z.input<typeof AnimatedVec2>> & { label: string }
> = ({ entity, onUpdate, label }) => {
return (
<div>
<label className="flex flex-col items-start">
<span className="label">{label}</span>
<AnimatedNumberProperties
entity={entity.keyframes[0]}
label="X"
onUpdate={(updatedEntity) =>
onUpdate(
produce(entity, (draft) => {
draft.keyframes[0] = {
...draft.keyframes[0],
...updatedEntity,
};
})
)
}
/>
<AnimatedNumberProperties
entity={entity.keyframes[1]}
label="Y"
onUpdate={(updatedEntity) =>
onUpdate(
produce(entity, (draft) => {
draft.keyframes[1] = {
...draft.keyframes[1],
...updatedEntity,
};
})
)
}
/>
</label>
</div>
);
};

View File

@ -0,0 +1,4 @@
export type PropertiesProps<E> = {
entity: E;
onUpdate: (entity: E) => void;
};

View File

@ -0,0 +1,83 @@
import { FC, ReactNode } from "react";
import { useEntitiesStore } from "stores/entities.store";
import { shallow } from "zustand/shallow";
import {
RectProperties,
EllipseProperties,
TextProperties,
StaggeredTextProperties,
} from "./Primitives";
const PropertiesContainer: FC<{ children: ReactNode }> = ({ children }) => {
return (
<div className="w-full rounded-md lg:h-[500px] overflow-auto border transition-colors focus-within:border-gray-400 border-gray-600 flex flex-col items-start p-4">
{children}
</div>
);
};
const Properties = () => {
const { selectedEntity, entities, updateEntity } = useEntitiesStore(
(store) => ({
updateEntity: store.updateEntity,
selectedEntity: store.selectedEntity,
entities: store.entities,
}),
shallow
);
const entity = selectedEntity !== undefined && entities[selectedEntity];
if (entity) {
switch (entity.type) {
case "StaggeredText":
return (
<StaggeredTextProperties
key={selectedEntity}
onUpdate={(entity) => updateEntity(selectedEntity, entity)}
entity={entity}
/>
);
case "Text":
return (
<TextProperties
key={selectedEntity}
onUpdate={(entity) => updateEntity(selectedEntity, entity)}
entity={entity}
/>
);
case "Rect":
return (
<RectProperties
key={selectedEntity}
onUpdate={(entity) => updateEntity(selectedEntity, entity)}
entity={entity}
/>
);
case "Ellipse":
return (
<EllipseProperties
key={selectedEntity}
onUpdate={(entity) => updateEntity(selectedEntity, entity)}
entity={entity}
/>
);
default:
return null;
}
}
return (
<div>
<h3>Wähle ein Element aus</h3>
</div>
);
};
export { PropertiesContainer };
export default Properties;

View File

@ -0,0 +1,17 @@
import * as ScrollArea from "@radix-ui/react-scroll-area";
import { FC } from "react";
const ScrollBar: FC<{ orientation?: "horizontal" | "vertical" }> = ({
orientation = "vertical",
}) => {
return (
<ScrollArea.Scrollbar
className="flex select-none touch-none p-0.5 bg-neutral-accent transition-colors duration-[160ms] ease-out data-[orientation=vertical]:w-2.5 data-[orientation=horizontal]:flex-col data-[orientation=horizontal]:h-2.5"
orientation={orientation}
>
<ScrollArea.Thumb className="flex-1 bg-main rounded-[10px] relative before:content-[''] before:absolute before:top-1/2 before:left-1/2 before:-translate-x-1/2 before:-translate-y-1/2 before:w-full before:h-full before:min-w-[44px] before:min-h-[44px]" />
</ScrollArea.Scrollbar>
);
};
export default ScrollBar;

View File

@ -0,0 +1,270 @@
import { ease } from "@unom/style";
import { PanInfo, motion } from "framer-motion";
import { AnimationData } from "primitives/AnimatedEntities";
import { Keyframe } from "primitives/Keyframe";
import { FC, useCallback, useMemo, useState } from "react";
import { z } from "zod";
import { TIMELINE_SCALE, calculateOffset } from "./common";
import { AnimatedNumber, AnimatedVec2, AnimatedVec3 } from "primitives/Values";
import { useKeyframeStore } from "stores/keyframe.store";
import { produce } from "immer";
import KeyframePopover from "./KeyframePopover";
import { Popover, PopoverContent, PopoverTrigger } from "components/Popover";
const KeyframeIndicator: FC<{
keyframe: z.input<typeof Keyframe>;
animationData: z.input<typeof AnimationData>;
onUpdate?: (e: z.input<typeof Keyframe>) => void;
}> = ({ keyframe, animationData, onUpdate }) => {
const { selectedKeyframe, selectKeyframe, deselectKeyframe } =
useKeyframeStore();
const handleUpdate = useCallback(
(info: PanInfo) => {
if (onUpdate) {
let offset = info.offset.x;
offset = calculateOffset(offset);
offset += keyframe.offset;
onUpdate({ ...keyframe, offset: offset < 0 ? 0 : offset });
}
},
[onUpdate, animationData, keyframe]
);
const handleValueUpdate = useCallback(
(keyframe: z.input<typeof Keyframe>) => {
if (onUpdate) {
onUpdate(keyframe);
}
},
[onUpdate]
);
const selected = useMemo(
() => selectedKeyframe === keyframe.id,
[keyframe.id, selectedKeyframe]
);
const [isDragged, setIsDragged] = useState(false);
return (
<>
<Popover modal={false} open={selected}>
<PopoverTrigger asChild>
<motion.div
drag="x"
variants={{
enter: {},
from: {},
exit: {},
tap: {},
drag: {},
}}
data-selected={selected}
onDragStart={() => setIsDragged(true)}
onDragEnd={(e, info) => {
e.preventDefault();
setIsDragged(false);
if (onUpdate) {
handleUpdate(info);
}
}}
dragConstraints={{ left: 0 }}
initial={{
x: (animationData.offset + keyframe.offset) * TIMELINE_SCALE + 2,
scale: 0,
}}
whileTap={{
scale: 1.6,
transition: {
scale: {
type: "spring",
stiffness: 200,
damping: 10,
mass: 1,
},
},
}}
animate={{
x: (animationData.offset + keyframe.offset) * TIMELINE_SCALE + 2,
scale: 1,
}}
transition={ease.quint(0.4).out}
onClick={() => {
if (isDragged) {
if (!selected) selectKeyframe(keyframe.id);
} else {
selected ? deselectKeyframe() : selectKeyframe(keyframe.id);
}
}}
className="h-full absolute z-30 select-none w-3 flex items-center justify-center filter
data-[selected=true]:drop-shadow-[0px_2px_6px_rgba(230,230,255,1)] transition-colors"
>
<motion.span
data-selected={selected}
className="bg-secondary
data-[selected=true]:bg-secondary
h-full transition-colors"
style={{
width: 10,
height: 10,
clipPath: "polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%)",
}}
/>
</motion.div>
</PopoverTrigger>
<PopoverContent className="w-80 backdrop-blur-md bg-neutral/50">
<KeyframePopover
onClose={() => deselectKeyframe()}
onUpdate={handleValueUpdate}
keyframe={keyframe}
/>
</PopoverContent>
</Popover>
</>
);
};
const AnimatedNumberKeyframeIndicator: FC<{
animatedNumber: z.input<typeof AnimatedNumber>;
animationData: z.input<typeof AnimationData>;
onUpdate: (e: z.input<typeof AnimatedNumber>) => void;
}> = ({ animatedNumber, animationData, onUpdate }) => {
return (
<>
{animatedNumber.keyframes.values.map((keyframe, index) => (
<KeyframeIndicator
onUpdate={(keyframe) =>
onUpdate(
produce(animatedNumber, (draft) => {
draft.keyframes.values[index] = keyframe;
})
)
}
key={keyframe.id}
keyframe={keyframe}
animationData={animationData}
/>
))}
</>
);
};
type DimensionsVec2 = "x" | "y";
const VEC2_DIMENSION_INDEX_MAPPING: Record<DimensionsVec2, number> = {
x: 0,
y: 1,
};
const AnimatedVec2KeyframeIndicator: FC<{
animatedVec2: z.input<typeof AnimatedVec2>;
dimension?: DimensionsVec2;
animationData: z.input<typeof AnimationData>;
onUpdate: (e: z.input<typeof AnimatedVec2>) => void;
}> = ({ animatedVec2, animationData, dimension, onUpdate }) => {
const handleUpdate = useCallback(
(
animatedNumber: z.input<typeof AnimatedNumber>,
dimensionIndex: number
) => {
onUpdate(
produce(animatedVec2, (draft) => {
draft.keyframes[dimensionIndex] = animatedNumber;
})
);
},
[animatedVec2]
);
if (dimension) {
return (
<AnimatedNumberKeyframeIndicator
animationData={animationData}
onUpdate={(animatedNumber) =>
handleUpdate(animatedNumber, VEC2_DIMENSION_INDEX_MAPPING[dimension])
}
animatedNumber={
animatedVec2.keyframes[VEC2_DIMENSION_INDEX_MAPPING[dimension]]
}
/>
);
}
return (
<>
{animatedVec2.keyframes.map((animatedNumber, index) => (
<AnimatedNumberKeyframeIndicator
onUpdate={(animatedNumber) => handleUpdate(animatedNumber, index)}
key={index}
animatedNumber={animatedNumber}
animationData={animationData}
/>
))}
</>
);
};
type DimensionsVec3 = "x" | "y" | "z";
const VEC3_DIMENSION_INDEX_MAPPING: Record<DimensionsVec3, number> = {
x: 0,
y: 1,
z: 2,
};
const AnimatedVec3KeyframeIndicator: FC<{
animatedVec3: z.input<typeof AnimatedVec3>;
animationData: z.input<typeof AnimationData>;
dimension?: DimensionsVec3;
onUpdate: (e: z.input<typeof AnimatedVec3>) => void;
}> = ({ animatedVec3, animationData, dimension, onUpdate }) => {
const handleUpdate = useCallback(
(
animatedNumber: z.input<typeof AnimatedNumber>,
dimensionIndex: number
) => {
onUpdate(
produce(animatedVec3, (draft) => {
draft.keyframes[dimensionIndex] = animatedNumber;
})
);
},
[animatedVec3]
);
if (dimension) {
return (
<AnimatedNumberKeyframeIndicator
animationData={animationData}
onUpdate={(animatedNumber) =>
handleUpdate(animatedNumber, VEC3_DIMENSION_INDEX_MAPPING[dimension])
}
animatedNumber={
animatedVec3.keyframes[VEC3_DIMENSION_INDEX_MAPPING[dimension]]
}
/>
);
}
return (
<>
{animatedVec3.keyframes.map((animatedNumber, index) => (
<AnimatedNumberKeyframeIndicator
key={index}
onUpdate={(animatedNumber) => handleUpdate(animatedNumber, index)}
animatedNumber={animatedNumber}
animationData={animationData}
/>
))}
</>
);
};
export {
AnimatedNumberKeyframeIndicator,
AnimatedVec3KeyframeIndicator,
AnimatedVec2KeyframeIndicator,
};
export default KeyframeIndicator;

View File

@ -0,0 +1,20 @@
import { PopoverClose } from "components/Popover";
import { KeyframeProperties } from "components/Properties/Values";
import { Keyframe } from "primitives/Keyframe";
import { FC } from "react";
import { z } from "zod";
const KeyframePopover: FC<{
keyframe: z.input<typeof Keyframe>;
onUpdate: (k: z.input<typeof Keyframe>) => void;
onClose: () => void;
}> = ({ keyframe, onUpdate, onClose }) => {
return (
<div>
<KeyframeProperties entity={keyframe} onUpdate={onUpdate} />
<PopoverClose onClick={onClose} />
</div>
);
};
export default KeyframePopover;

View File

@ -0,0 +1,35 @@
import { FC } from "react";
import * as Slider from "@radix-ui/react-slider";
import { useRenderStateStore } from "stores/render-state.store";
import { TIMELINE_SCALE } from "./common";
import { useTimelineStore } from "stores/timeline.store";
export type TimePickerProps = {};
const TimePicker: FC<TimePickerProps> = () => {
const { renderState, setCurrentFrame } = useRenderStateStore();
const timeline = useTimelineStore();
return (
<Slider.Root
className="relative flex items-center select-none touch-none h-5 shrink-0"
defaultValue={[50]}
style={{ width: TIMELINE_SCALE * 10 }}
value={[renderState.curr_frame]}
onValueChange={(val) => setCurrentFrame(val[0])}
max={timeline.fps * timeline.duration}
step={1}
aria-label="Current Frame"
>
<Slider.Track className="bg-neutral-accent relative grow rounded-full h-[3px]">
<Slider.Range className="absolute bg-main rounded-full h-full" />
</Slider.Track>
<Slider.Thumb
className="transition-colors block w-4 h-4 bg-main shadow-[0_2px_10px] shadow-main/20 rounded-[10px] hover:bg-secondary focus:outline-none focus:shadow-[0_0_0_2px] focus:shadow-main"
aria-label="Volume"
/>
</Slider.Root>
);
};
export default TimePicker;

View File

@ -0,0 +1,22 @@
import { useRenderStateStore } from "stores/render-state.store";
import { useTimelineStore } from "stores/timeline.store";
const Timestamp = () => {
const { renderState } = useRenderStateStore();
const timeline = useTimelineStore();
return (
<div>
<h3>
Frame {renderState.curr_frame} / {timeline.fps * timeline.duration}
</h3>
<h2 className="text-xl font-bold">
{(renderState.curr_frame / timeline.fps).toPrecision(3)} /{" "}
{timeline.duration.toPrecision(3)}
<span className="text-sm font-light">/ {timeline.fps}FPS</span>
</h2>
</div>
);
};
export default Timestamp;

View File

@ -0,0 +1,209 @@
import { ease } from "@unom/style";
import { useDragControls, Reorder, motion } from "framer-motion";
import { AnimationData, AnimatedEntity } from "primitives/AnimatedEntities";
import { FC, memo, useState, useMemo } from "react";
import { useEntitiesStore } from "stores/entities.store";
import { z } from "zod";
import { shallow } from "zustand/shallow";
import KeyframeIndicator from "./KeyframeIndicator";
import { TIMELINE_SCALE, calculateOffset } from "./common";
import { TriangleDownIcon } from "@radix-ui/react-icons";
import TrackPropertiesEditor from "./TrackDisplay/TrackPropertiesEditor";
import { cn, flattenedKeyframesByEntity } from "utils";
type TrackProps = {
animationData: z.input<typeof AnimationData>;
name: string;
index: number;
entity: z.input<typeof AnimatedEntity>;
};
const TrackDisplayTypeOptions = ["Default", "Graph"] as const;
export const TrackDisplayType = z.enum(TrackDisplayTypeOptions);
const Track: FC<TrackProps> = ({ animationData, index, name, entity }) => {
const controls = useDragControls();
const flattenedKeyframes = useMemo(
() => flattenedKeyframesByEntity(entity),
[entity]
);
const [isExpanded, setIsExpanded] = useState(false);
const { updateEntity, selectEntity, selectedEntity, deselectEntity } =
useEntitiesStore(
(store) => ({
updateEntity: store.updateEntity,
selectedEntity: store.selectedEntity,
selectEntity: store.selectEntity,
deselectEntity: store.deselectEntity,
}),
shallow
);
return (
<Reorder.Item
value={entity}
dragListener={false}
dragControls={controls}
onMouseDown={(e) => e.preventDefault()}
className="h-6 relative flex flex-1 flex-col gap-1 select-none"
>
<motion.div
layout
onMouseDown={(e) => e.preventDefault()}
className="flex flex-row gap-1 select-none"
>
<div
onMouseDown={(e) => e.preventDefault()}
onPointerDown={(e) => controls.start(e)}
className={`h-full transition-all rounded-sm min-w-[200px] p-1 px-2 flex flex-col ${
selectedEntity === index
? "bg-highlight text-neutral dark:text-main"
: "bg-neutral-accent text-main"
}`}
>
<div className="flex flex-row">
<motion.div
onClick={() => setIsExpanded(!isExpanded)}
className={cn("will-change-transform")}
animate={{ rotate: isExpanded ? 0 : -90 }}
>
<TriangleDownIcon width="32px" height="32px" />
</motion.div>
<h3
onClick={() =>
selectedEntity !== undefined && selectedEntity === index
? deselectEntity()
: selectEntity(index)
}
className="h-2 text-base leading-loose font-semibold select-none cursor-pointer"
>
{name}
</h3>
</div>
</div>
<div className="flex h-full w-full flex-row relative rounded-sm bg-neutral-accent/50 select-none shrink-0">
<div
className="absolute top-0 h-full bg-neutral-accent"
style={{ width: TIMELINE_SCALE * 10 }}
/>
{!isExpanded &&
flattenedKeyframes.map((keyframe, index) => (
<KeyframeIndicator
animationData={animationData}
keyframe={keyframe}
key={index}
/>
))}
<motion.div
drag="x"
animate={{
x: animationData.offset * TIMELINE_SCALE,
}}
whileHover={{
scale: 1.1,
}}
whileTap={{
scale: 0.9,
}}
onMouseDown={(e) => e.preventDefault()}
transition={ease.circ(0.6).out}
dragElastic={false}
dragConstraints={{ left: 0 }}
onDragEnd={(e, info) => {
let offset = info.offset.x;
offset = calculateOffset(offset);
const animationOffset =
animationData.offset + offset < 0
? 0
: animationData.offset + offset;
const duration = animationData.duration - offset;
updateEntity(index, {
animation_data: {
...animationData,
offset: animationOffset < 0 ? 0 : animationOffset,
duration: duration < 0 ? 0 : duration,
},
});
}}
className="z-10 w-4 bg-primary/50 h-full top-0 absolute rounded-md select-none cursor-w-resize"
/>
<motion.div
className="z-10 w-4 bg-primary/50 h-full top-0 absolute rounded-md select-none cursor-e-resize"
onMouseDown={(e) => e.preventDefault()}
drag="x"
animate={{
x:
(animationData.duration + animationData.offset) *
TIMELINE_SCALE -
16,
}}
whileHover={{
scale: 1.1,
}}
whileTap={{
scale: 0.9,
}}
transition={ease.circ(0.6).out}
dragConstraints={{ left: 0 }}
onDragEnd={(e, info) => {
let offset = info.offset.x;
offset = calculateOffset(offset);
const duration = animationData.duration + offset;
updateEntity(index, {
animation_data: {
...animationData,
duration: duration < 0 ? 0 : duration,
},
});
}}
/>
<motion.div
drag="x"
animate={{
width: animationData.duration * TIMELINE_SCALE,
x: animationData.offset * TIMELINE_SCALE,
}}
whileHover={{ scaleY: 1.1 }}
whileTap={{ scaleY: 0.9 }}
dragConstraints={{
left: 0,
}}
onMouseDown={(e) => e.preventDefault()}
transition={ease.circ(0.8).out}
onDragEnd={(_e, info) => {
let offset = info.offset.x;
offset = calculateOffset(offset);
offset += animationData.offset;
updateEntity(index, {
animation_data: {
...animationData,
offset: offset < 0 ? 0 : offset,
},
});
}}
className="z-5 h-full top-0 absolute rounded-md transition-colors bg-primary/30 hover:bg-primary/50 select-none cursor-grab"
></motion.div>
</div>
</motion.div>
{isExpanded && <TrackPropertiesEditor entity={entity} />}
</Reorder.Item>
);
};
export default memo(Track);

View File

@ -0,0 +1,64 @@
import { FC } from "react";
import { extent, bisector } from "d3-array";
import { curveNatural } from "@visx/curve";
import { scaleLinear } from "@visx/scale";
import { LinePath } from "@visx/shape";
import { Group } from "@visx/group";
const HEIGHT = 300;
const WIDTH = 1200;
type PropertyValue = {
value: number;
frame: number;
};
const getValue = (d: PropertyValue) => d.value;
const getFrame = (d: PropertyValue) => d.frame;
const PropertyGraph: FC<{
values: Array<{ frame: number; value: number }>;
}> = ({ values }) => {
const framesScale = scaleLinear({
range: [0, WIDTH],
domain: extent(values, getFrame) as [number, number],
nice: true,
});
const valuesScale = scaleLinear({
range: [HEIGHT, 0],
domain: extent(values, getValue) as [number, number],
nice: true,
});
return (
<Group>
<LinePath
curve={curveNatural}
stroke="white"
strokeWidth={3}
data={values}
x={(d) => framesScale(getFrame(d)) ?? 0}
y={(d) => valuesScale(getValue(d)) ?? 0}
/>
</Group>
);
};
const Graphs: FC<{ values: Array<Array<number>> }> = ({ values }) => {
return (
<svg width={WIDTH} height={HEIGHT}>
{values.map((propertyValues) => (
<PropertyGraph
values={propertyValues.map((val, index) => ({
frame: index,
value: val,
}))}
/>
))}
</svg>
);
};
export default Graphs;

View File

@ -0,0 +1,242 @@
import {
AnimatedEntity,
AnimationData,
getAnimatedPropertiesByAnimatedEntity,
} from "primitives/AnimatedEntities";
import { AnimatedProperty } from "primitives/AnimatedProperty";
import { AnimatedVec2, ValueType } from "primitives/Values";
import { FC, memo, useCallback, useMemo, useState } from "react";
import { z } from "zod";
import {
AnimatedNumberKeyframeIndicator,
AnimatedVec2KeyframeIndicator,
AnimatedVec3KeyframeIndicator,
} from "../KeyframeIndicator";
import { ToggleGroup, ToggleGroupItem } from "components/ToggleGroup";
import { produce } from "immer";
import set from "lodash.set";
import { useEntitiesStore } from "stores/entities.store";
import { AnimatedValue } from "primitives/Values";
import { motion } from "framer-motion";
import { ease } from "@unom/style";
import { TrackDisplayType } from "../Track";
import TrackPropertyGraph from "./TrackPropertyGraph";
import { LineChart } from "lucide-react";
type DisplayState = {
type: z.input<typeof TrackDisplayType>;
selectedAnimatedProperties: Array<number>;
};
const TrackAnimatedPropertyKeyframes: FC<{
animatedProperty: z.input<typeof AnimatedProperty>;
animationData: z.input<typeof AnimationData>;
onUpdate: (animatedProperty: z.input<typeof AnimatedProperty>) => void;
selectedDimension?: "x" | "y" | "z";
}> = ({ animatedProperty, animationData, selectedDimension, onUpdate }) => {
const handleUpdate = useCallback(
(animatedValue: z.input<typeof AnimatedValue>) => {
onUpdate({ ...animatedProperty, animatedValue });
},
[onUpdate, animatedProperty]
);
switch (animatedProperty.animatedValue.type) {
case "Number":
return (
<AnimatedNumberKeyframeIndicator
animatedNumber={animatedProperty.animatedValue}
animationData={animationData}
onUpdate={handleUpdate}
/>
);
case "Vec2":
return (
<AnimatedVec2KeyframeIndicator
dimension={selectedDimension !== "z" ? selectedDimension : undefined}
animatedVec2={animatedProperty.animatedValue}
animationData={animationData}
onUpdate={handleUpdate}
/>
);
case "Vec3":
return (
<AnimatedVec3KeyframeIndicator
dimension={selectedDimension}
animatedVec3={animatedProperty.animatedValue}
animationData={animationData}
onUpdate={handleUpdate}
/>
);
default:
return null;
}
};
const TrackAnimatedProperty: FC<{
animatedProperty: z.input<typeof AnimatedProperty>;
animationData: z.input<typeof AnimationData>;
displayState: DisplayState;
index: number;
onDisplayStateUpdate: (s: DisplayState) => void;
onUpdate: (e: z.input<typeof AnimatedProperty>) => void;
}> = ({
animatedProperty,
animationData,
onUpdate,
displayState,
index,
onDisplayStateUpdate,
}) => {
const [selectedDimension, setSelectedDimension] = useState<"x" | "y" | "z">();
return (
<motion.div
layout
transition={ease.quint(0.8).out}
variants={{ enter: { y: 0, opacity: 1 }, from: { y: -10, opacity: 0 } }}
className="flex flex-row bg-neutral-accent ml-2 align-center"
>
<div className="min-w-[195px] flex flex-row justify-between px-2">
<h4 className="text-main/70">{animatedProperty.label}</h4>
<ToggleGroup>
<ToggleGroupItem
onClick={() =>
selectedDimension === "x"
? setSelectedDimension(undefined)
: setSelectedDimension("x")
}
selected={selectedDimension === "x"}
>
X
</ToggleGroupItem>
<ToggleGroupItem
onClick={() =>
selectedDimension === "y"
? setSelectedDimension(undefined)
: setSelectedDimension("y")
}
selected={selectedDimension === "y"}
>
Y
</ToggleGroupItem>
{animatedProperty.animatedValue.type === ValueType.Enum.Vec3 && (
<ToggleGroupItem
onClick={() =>
selectedDimension === "z"
? setSelectedDimension(undefined)
: setSelectedDimension("z")
}
selected={selectedDimension === "z"}
>
Z
</ToggleGroupItem>
)}
<ToggleGroupItem
selected={displayState.selectedAnimatedProperties.includes(index)}
onClick={() => {
if (displayState.selectedAnimatedProperties.includes(index)) {
onDisplayStateUpdate({
...displayState,
selectedAnimatedProperties:
displayState.selectedAnimatedProperties.filter(
(index) => index !== index
),
});
} else {
onDisplayStateUpdate({
...displayState,
selectedAnimatedProperties: [
...displayState.selectedAnimatedProperties,
index,
],
});
}
}}
>
<LineChart />
</ToggleGroupItem>
</ToggleGroup>
</div>
<div className="relative">
<TrackAnimatedPropertyKeyframes
selectedDimension={
animatedProperty.animatedValue.type !== "Number"
? selectedDimension
: undefined
}
onUpdate={onUpdate}
animatedProperty={animatedProperty}
animationData={animationData}
/>
</div>
</motion.div>
);
};
const TrackPropertiesEditor: FC<{
entity: z.input<typeof AnimatedEntity>;
}> = ({ entity }) => {
const animatedProperties = useMemo(
() => getAnimatedPropertiesByAnimatedEntity(entity),
[entity]
);
const handleUpdate = useCallback(
(animatedProperty: z.input<typeof AnimatedProperty>) => {
const entitiesStore = useEntitiesStore.getState();
const nextValue = produce(entity, (draft) => {
const animatedValue = animatedProperty.animatedValue;
set(draft, animatedProperty.propertyPath, animatedValue);
});
const parsedEntity = AnimatedEntity.parse(nextValue);
entitiesStore.updateEntityById(parsedEntity.id, parsedEntity);
},
[entity]
);
const [displayState, setDisplayState] = useState<DisplayState>({
type: TrackDisplayType.Enum.Default,
selectedAnimatedProperties: [],
});
return (
<motion.div layout className="flex flex-row">
<motion.div
animate="enter"
initial="from"
variants={{ enter: {}, from: {} }}
transition={{ staggerChildren: 0.05 }}
className="flex flex-col gap-1"
>
{animatedProperties.map((animatedProperty, index) => (
<TrackAnimatedProperty
index={index}
onDisplayStateUpdate={setDisplayState}
displayState={displayState}
onUpdate={handleUpdate}
animationData={entity.animation_data}
key={index}
animatedProperty={animatedProperty}
/>
))}
</motion.div>
{displayState.selectedAnimatedProperties.length > 0 && (
<TrackPropertyGraph
animationData={entity.animation_data}
animatedProperties={displayState.selectedAnimatedProperties.map(
(index) => animatedProperties[index]
)}
/>
)}
</motion.div>
);
};
export default memo(TrackPropertiesEditor);

View File

@ -0,0 +1,108 @@
import { invoke } from "@tauri-apps/api";
import { AnimationData } from "primitives/AnimatedEntities";
import { AnimatedProperty } from "primitives/AnimatedProperty";
import { AnimatedValue, ValueType } from "primitives/Values";
import { FC, useEffect, useState } from "react";
import { z } from "zod";
import Graph from "./Graph";
type TrackPropertyPathProps = {
animatedProperties: Array<z.input<typeof AnimatedProperty>>;
animationData: z.input<typeof AnimationData>;
};
const TrackPropertyGraph: FC<TrackPropertyPathProps> = ({
animatedProperties,
animationData,
}) => {
const [values, setValues] = useState<Array<Array<number>>>([]);
useEffect(() => {
const tasks: Array<Promise<Array<Array<number>>>> = [];
animatedProperties.forEach((animatedProperty) => {
animatedProperty.animatedValue.type;
const animatedValue = animatedProperty.animatedValue;
const commonValues: {
animatedValue: z.input<typeof AnimatedValue>;
startFrame: number;
endFrame: number;
fps: number;
animationData: z.input<typeof AnimationData>;
} = {
animatedValue: AnimatedValue.parse(animatedValue),
startFrame: 0,
endFrame: 600,
fps: 60,
animationData: AnimationData.parse(animationData),
};
switch (animatedValue.type) {
case ValueType.Enum.Number:
tasks.push(
invoke(
"get_values_at_frame_range_from_animated_float",
commonValues
).then((data) => {
const numbers = data as Array<number>;
return [numbers];
})
);
break;
case ValueType.Enum.Vec2:
tasks.push(
invoke(
"get_values_at_frame_range_from_animated_float_vec2",
commonValues
).then((data) => {
const vectors = data as [Array<number>, Array<number>];
const xValues = vectors.map((vec2) => vec2[0]);
const yValues = vectors.map((vec2) => vec2[1]);
return [xValues, yValues];
})
);
break;
case ValueType.Enum.Vec3:
tasks.push(
invoke(
"get_values_at_frame_range_from_animated_float_vec3",
commonValues
).then((data) => {
const vectors = data as [
Array<number>,
Array<number>,
Array<number>
];
const xValues = vectors.map((vec2) => vec2[0]);
const yValues = vectors.map((vec2) => vec2[1]);
const zValues = vectors.map((vec2) => vec2[2]);
return [xValues, yValues, zValues];
})
);
break;
}
});
Promise.all(tasks).then((values) => {
const flatValues = values.flat();
console.log("flattened Values", flatValues);
setValues(flatValues);
});
}, animatedProperties);
return (
<div>
<Graph values={values} />
</div>
);
};
export default TrackPropertyGraph;

View File

@ -0,0 +1,7 @@
export const TIMELINE_SCALE = 100;
export const calculateOffset = (offset: number) => {
let nextOffset = offset / TIMELINE_SCALE;
return nextOffset;
};

View File

@ -0,0 +1,74 @@
import { FC } from "react";
import { Reorder } from "framer-motion";
import TimePicker from "./Timepicker";
import { useEntitiesStore } from "stores/entities.store";
import Timestamp from "./Timestamp";
import { PauseIcon, PlayIcon } from "@radix-ui/react-icons";
import { useRenderStateStore } from "stores/render-state.store";
import Track from "./Track";
import * as ScrollArea from "@radix-ui/react-scroll-area";
import ScrollBar from "components/ScrollArea";
export type AnimationEntity = {
offset: number;
duration: number;
};
type TimelineProps = {};
const Timeline: FC<TimelineProps> = () => {
const { entities, setEntities } = useEntitiesStore((store) => ({
entities: store.entities,
setEntities: store.setEntities,
}));
const { setPlaying } = useRenderStateStore((store) => ({
setPlaying: store.setPlaying,
}));
return (
<div className="flex flex-col grow shrink h-fit p-4 border transition-colors focus-within:border-gray-400 border-gray-600 rounded-md">
<div className="flex flex-row">
<div className="flex flex-row">
<button onClick={() => setPlaying(true)} className="w-8 h-8">
<PlayIcon className="text-main" width="100%" height="100%" />
</button>
<button onClick={() => setPlaying(false)} className="w-8 h-8">
<PauseIcon className="text-main" width="100%" height="100%" />
</button>
</div>
<Timestamp />
</div>
<ScrollArea.Root>
<ScrollArea.Viewport className="w-full h-full">
<div className="gap-1 w-full flex flex-col">
<div className="z-20 flex flex-row gap-1">
<div className="flex-shrink-0 min-w-[200px]" />
<TimePicker />
</div>
<Reorder.Group
className="gap-1 flex flex-col"
values={entities}
onReorder={setEntities}
>
{entities.map((entity, index) => (
<Track
entity={entity}
key={entity.id}
name={entity.type}
index={index}
animationData={entity.animation_data}
/>
))}
</Reorder.Group>
</div>
</ScrollArea.Viewport>
<div className="h-4 sticky bottom-0">
<ScrollBar orientation="horizontal" />
</div>
</ScrollArea.Root>
</div>
);
};
export default Timeline;

View File

@ -0,0 +1,41 @@
import { FC, ReactNode } from "react";
import * as ToggleGroupComponents from "@radix-ui/react-toggle-group";
import { motion } from "framer-motion";
const ToggleGroupItem: FC<{
children: ReactNode;
selected: boolean;
onClick?: () => void;
}> = ({ children, selected, onClick }) => {
return (
<ToggleGroupComponents.Item
data-selected={selected}
asChild
onClick={onClick}
className="hover:bg-primary/30 text-main data-[selected=true]:bg-primary/60
data-[selected=true]:text-indigo-200 flex h-6 w-6
items-center justify-center bg-neutral text-sm leading-4
first:rounded-l last:rounded-r focus:z-10 focus:shadow-[0_0_0_2px] focus:shadow-black
focus:outline-none transition-colors"
value="left"
aria-label="Left aligned"
>
<motion.button animate={{ scale: 1 }} whileTap={{ scale: 0.9 }}>
{children}
</motion.button>
</ToggleGroupComponents.Item>
);
};
const ToggleGroup: FC<{ children: ReactNode }> = ({ children }) => (
<ToggleGroupComponents.Root
className="inline-flex my-auto bg-neutral-accent h-fit rounded shadow-[0_2px_10px] shadow-black space-x-px"
type="single"
defaultValue="center"
aria-label="Text alignment"
>
{children}
</ToggleGroupComponents.Root>
);
export { ToggleGroup, ToggleGroupItem };

View File

@ -0,0 +1,92 @@
import {
BoxIcon,
CircleIcon,
CursorArrowIcon,
FontStyleIcon,
MixIcon,
Pencil1Icon,
Pencil2Icon,
SymbolIcon,
TextIcon,
} from "@radix-ui/react-icons";
import * as Toolbar from "@radix-ui/react-toolbar";
import { motion } from "framer-motion";
import { FC, ReactNode, useMemo, useState } from "react";
import { EntitiesService } from "services/entities.service";
const ToolBarButton: FC<{ children: ReactNode; onClick?: () => void }> = ({
children,
onClick,
}) => {
const [didHover, setDidHover] = useState(false);
return (
<Toolbar.Button
onClick={onClick}
onMouseOver={() => !didHover && setDidHover(true)}
asChild
className="text-main p-[10px] bg-neutral flex-shrink-0 flex-grow-0
basis-auto w-[40px] h-[40px] rounded inline-flex text-[13px] leading-none
items-center justify-center outline-none hover:bg-primary/50
transition-colors
focus:relative focus:shadow-[0_0_0_2px] focus:shadow-indigo"
>
<motion.button
animate={didHover ? "enter" : undefined}
whileTap="press"
variants={{
enter: { scale: 1 },
from: { scale: 0 },
press: { scale: 0.9 },
}}
>
{children}
</motion.button>
</Toolbar.Button>
);
};
const ToolBar = () => {
const entitiesService = useMemo(() => new EntitiesService(), []);
return (
<Toolbar.Root
asChild
className="bg-neutral-accent flex flex-col gap-1 p-1 h-full"
orientation="vertical"
>
<motion.div
animate="enter"
initial="from"
transition={{ staggerChildren: 0.1 }}
variants={{ enter: {}, from: {} }}
>
<ToolBarButton>
<CursorArrowIcon width="100%" height="100%" />
</ToolBarButton>
<Toolbar.Separator />
<ToolBarButton onClick={() => entitiesService.createRect()}>
<BoxIcon width="100%" height="100%" />
</ToolBarButton>
<ToolBarButton onClick={() => entitiesService.createEllipse()}>
<CircleIcon width="100%" height="100%" />
</ToolBarButton>
<ToolBarButton>
<Pencil1Icon width="100%" height="100%" />
</ToolBarButton>
<ToolBarButton>
<MixIcon width="100%" height="100%" />
</ToolBarButton>
<Toolbar.Separator />
<ToolBarButton onClick={() => entitiesService.createText()}>
<TextIcon width="100%" height="100%" />
</ToolBarButton>
<ToolBarButton onClick={() => entitiesService.createStaggeredText()}>
<FontStyleIcon width="100%" height="100%" />
</ToolBarButton>
</motion.div>
</Toolbar.Root>
);
};
export default ToolBar;

40
app/src/drawers/cache.ts Normal file
View File

@ -0,0 +1,40 @@
import { BaseEntity } from "primitives/Entities";
import { z } from "zod";
export interface EntityCache<T> {
build: () => T;
get: () => T | undefined;
set: (id: string, cache: T) => void;
cleanup: (cache: T) => void;
}
export function handleEntityCache<
E extends z.output<typeof BaseEntity>,
C,
EC extends EntityCache<C>
>(entity: E, cache: EC): C {
const cached = cache.get();
if (!entity.cache.valid) {
// console.log("Invalid cache");
if (cached) {
cache.cleanup(cached);
}
const nextCache = cache.build();
cache.set(entity.id, nextCache);
return nextCache;
} else {
if (!cached) {
const nextCache = cache.build();
cache.set(entity.id, nextCache);
return nextCache;
} else {
return cached;
}
}
}

257
app/src/drawers/draw.ts Normal file
View File

@ -0,0 +1,257 @@
import { invoke } from "@tauri-apps/api";
import InitCanvasKit, { Canvas, CanvasKit, Surface } from "canvaskit-wasm";
import { AnimatedEntities } from "primitives/AnimatedEntities";
import {
Entities,
EntityType,
StaggeredTextEntity,
TextEntity,
} from "primitives/Entities";
import { useRenderStateStore } from "stores/render-state.store";
import { useTimelineStore } from "stores/timeline.store";
import { z } from "zod";
import drawStaggeredText, {
StaggeredTextCache,
StaggeredTextEntityCache,
calculateLetters,
} from "./staggered-text";
import drawText, { TextCache, TextEntityCache, buildTextCache } from "./text";
import drawEllipse from "./ellipse";
import drawRect from "./rect";
import { useEntitiesStore } from "stores/entities.store";
import { handleEntityCache } from "./cache";
import { DependenciesService } from "services/dependencies.service";
import { RenderState } from "primitives/Timeline";
/**
*
* TODO Add more sophisticated dependency logic for e.g. dynamically loading fonts, images etc.
*/
export class Drawer {
private didLoad: boolean;
private entities: z.output<typeof Entities> | undefined;
private ckDidLoad: boolean;
drawCount: number;
private CanvasKit: CanvasKit | undefined;
cache: {
staggeredText: Map<string, StaggeredTextCache>;
text: Map<string, TextCache>;
};
surface: Surface | undefined;
fontData: ArrayBuffer | undefined;
raf: number | undefined;
isLocked: boolean;
dependenciesService: DependenciesService;
constructor() {
this.entities = undefined;
this.CanvasKit = undefined;
this.ckDidLoad = false;
this.drawCount = 0;
this.surface = undefined;
this.fontData = undefined;
this.cache = {
staggeredText: new Map(),
text: new Map(),
};
this.dependenciesService = new DependenciesService();
this.isLocked = false;
this.raf = undefined;
this.didLoad = this.ckDidLoad;
}
async init(canvas: HTMLCanvasElement) {
await this.loadCanvasKit(canvas);
this.didLoad = this.ckDidLoad;
}
async loadCanvasKit(canvas: HTMLCanvasElement) {
await InitCanvasKit({
locateFile: (file) => file,
}).then((CanvasKit) => {
if (canvas) {
const CSurface = CanvasKit.MakeWebGLCanvasSurface(canvas);
if (CSurface) {
this.CanvasKit = CanvasKit;
this.surface = CSurface;
this.ckDidLoad = true;
}
}
});
}
async calculateAnimatedEntities(
animatedEntities: z.input<typeof AnimatedEntities>,
renderState: z.output<typeof RenderState>
) {
const { fps, size, duration } = useTimelineStore.getState();
const parsedAnimatedEntities = AnimatedEntities.parse(animatedEntities);
const data = await invoke("calculate_timeline_at_curr_frame", {
timeline: {
entities: parsedAnimatedEntities,
render_state: renderState,
fps,
size,
duration,
},
});
const parsedEntities = Entities.parse(data);
return parsedEntities;
}
get isCached(): boolean {
if (this.entities) {
return this.entities.reduce(
(prev, curr) => prev && curr.cache.valid,
true
);
} else {
return false;
}
}
/**
* Updates the entities based on the input
*/
update(
animatedEntities: z.input<typeof AnimatedEntities>,
prepareDependencies: boolean
) {
// console.time("calculate");
if (this.didLoad) {
const renderState = useRenderStateStore.getState().renderState;
this.calculateAnimatedEntities(animatedEntities, renderState).then(
(entities) => {
this.entities = entities;
if (prepareDependencies) {
this.dependenciesService
.prepareForEntities(this.entities)
.then(() => {
this.requestRedraw(!this.isCached);
});
} else {
this.requestRedraw(!this.isCached);
}
}
);
} else {
// console.timeEnd("calculate");
}
}
requestRedraw(rebuild: boolean) {
if (this.didLoad && this.surface && !this.isLocked) {
if (rebuild && this.raf !== undefined) {
cancelAnimationFrame(this.raf);
// this.surface.flush();
this.raf = this.surface.requestAnimationFrame((canvas) =>
this.draw(canvas)
);
} else {
// this.surface.flush();
this.raf = this.surface.requestAnimationFrame((canvas) =>
this.draw(canvas)
);
}
}
}
draw(canvas: Canvas) {
if (this.CanvasKit && this.entities && !this.isLocked) {
this.isLocked = true;
//console.time("draw");
const CanvasKit = this.CanvasKit;
canvas.clear(CanvasKit.WHITE);
this.drawCount++;
[...this.entities].reverse().forEach((entity) => {
switch (entity.type) {
case EntityType.Enum.Rect:
drawRect(CanvasKit, canvas, entity);
break;
case EntityType.Enum.Ellipse:
drawEllipse(CanvasKit, canvas, entity);
break;
case EntityType.Enum.Text:
{
const cache = handleEntityCache<
z.output<typeof TextEntity>,
TextCache,
TextEntityCache
>(entity, {
build: () => {
const cache = buildTextCache(
CanvasKit,
entity,
this.dependenciesService.dependencies
);
useEntitiesStore
.getState()
.updateEntityById(entity.id, { cache: { valid: true } });
return cache;
},
get: () => this.cache.text.get(entity.id),
set: (id, cache) => this.cache.text.set(id, cache),
cleanup: (cache) => {
cache.fontManager.delete();
},
});
drawText(CanvasKit, canvas, entity, cache);
}
break;
case EntityType.Enum.StaggeredText:
{
const cache = handleEntityCache<
z.output<typeof StaggeredTextEntity>,
StaggeredTextCache,
StaggeredTextEntityCache
>(entity, {
build: () => {
const cache = calculateLetters(
CanvasKit,
entity,
this.dependenciesService.dependencies
);
useEntitiesStore
.getState()
.updateEntityById(entity.id, { cache: { valid: true } });
return cache;
},
get: () => this.cache.staggeredText.get(entity.id),
set: (id, cache) => this.cache.staggeredText.set(id, cache),
cleanup: (cache) => {
cache.font.delete();
cache.typeface.delete();
CanvasKit.Free(cache.glyphs);
},
});
drawStaggeredText(CanvasKit, canvas, entity, cache);
}
break;
default:
break;
}
});
this.isLocked = false;
//console.timeEnd("draw");
}
}
}

View File

@ -0,0 +1,27 @@
import { Canvas, CanvasKit, Surface } from "canvaskit-wasm";
import { BlurEffectLayer } from "primitives/Effects";
import { z } from "zod";
export default function applyBlur(
CanvasKit: CanvasKit,
canvas: Canvas,
surface: Surface,
options: z.input<typeof BlurEffectLayer>
) {
const image = surface.makeImageSnapshot();
if (image) {
const blurFilter = CanvasKit.ImageFilter.MakeBlur(
options.amountX,
options.amountY,
CanvasKit.TileMode[options.tileMode],
null
);
const paint = new CanvasKit.Paint();
paint.setImageFilter(blurFilter);
canvas.drawImage(image, 0, 0, paint);
}
}

View File

@ -0,0 +1,28 @@
import { convertToFloat } from "@tempblade/common";
import { Canvas, CanvasKit } from "canvaskit-wasm";
import { EllipseEntity } from "primitives/Entities";
import { z } from "zod";
import { buildPaintStyle } from "./paint";
export default function drawEllipse(
CanvasKit: CanvasKit,
canvas: Canvas,
entity: z.infer<typeof EllipseEntity>
) {
const paint = new CanvasKit.Paint();
buildPaintStyle(CanvasKit, paint, entity.paint);
const mappedPosition = entity.position.map(
(val, index) => val - entity.radius[index] * 0.5
);
const rect = CanvasKit.XYWHRect(
mappedPosition[0],
mappedPosition[1],
entity.radius[0],
entity.radius[1]
);
canvas.drawOval(rect, paint);
}

30
app/src/drawers/paint.ts Normal file
View File

@ -0,0 +1,30 @@
import { convertToFloat } from "@tempblade/common";
import { Paint as SkPaint, CanvasKit } from "canvaskit-wasm";
import { Paint } from "primitives/Paint";
import { z } from "zod";
export function buildPaintStyle(
CanvasKit: CanvasKit,
skPaint: SkPaint,
paint: z.output<typeof Paint>
) {
const color = convertToFloat(paint.style.color.value);
skPaint.setAntiAlias(true);
skPaint.setColor(color);
switch (paint.style.type) {
case "Fill":
skPaint.setStyle(CanvasKit.PaintStyle.Fill);
break;
case "Stroke":
skPaint.setStyle(CanvasKit.PaintStyle.Stroke);
skPaint.setStrokeWidth(paint.style.width);
break;
default:
console.error("Paint Style not supported!");
break;
}
}

43
app/src/drawers/rect.ts Normal file
View File

@ -0,0 +1,43 @@
import { Canvas, CanvasKit } from "canvaskit-wasm";
import { z } from "zod";
import { RectEntity } from "primitives/Entities";
import { buildPaintStyle } from "./paint";
export default function drawRect(
CanvasKit: CanvasKit,
canvas: Canvas,
entity: z.infer<typeof RectEntity>
) {
canvas.save();
const paint = new CanvasKit.Paint();
buildPaintStyle(CanvasKit, paint, entity.paint);
const mappedPosition = entity.position.map(
(val, index) => val - entity.size[index] * 0.5
);
const rect = CanvasKit.XYWHRect(
mappedPosition[0],
mappedPosition[1],
entity.size[0],
entity.size[1]
);
if (entity.transform) {
const origin = [0, entity.size[1]];
canvas.translate(origin[0], origin[1]);
canvas.scale(entity.transform.scale[0], entity.transform.scale[1]);
canvas.rotate;
canvas.translate(-origin[0], -origin[1]);
}
canvas.drawRect(rect, paint);
canvas.restore();
}

View File

@ -0,0 +1,302 @@
import {
Canvas,
CanvasKit,
Font,
FontMetrics,
MallocObj,
TypedArray,
Typeface,
} from "canvaskit-wasm";
import { StaggeredTextEntity } from "primitives/Entities";
import { z } from "zod";
import { buildPaintStyle } from "./paint";
import { EntityCache } from "./cache";
import { Dependencies } from "services/dependencies.service";
export type StaggeredTextCache = {
letterMeasures: Array<LetterMeasures>;
metrics: FontMetrics;
typeface: Typeface;
font: Font;
glyphs: MallocObj;
};
export type StaggeredTextEntityCache = EntityCache<StaggeredTextCache>;
function getUniqueCharacters(str: string): string {
const uniqueCharacters: string[] = [];
for (let i = 0; i < str.length; i++) {
const character = str[i];
if (!uniqueCharacters.includes(character)) {
uniqueCharacters.push(character);
}
}
return uniqueCharacters.join("");
}
function measureLetters(
glyphArr: TypedArray,
boundsById: Record<number, LetterBounds>,
maxWidth: number
): Array<LetterMeasures> {
const measuredLetters: Array<LetterMeasures> = [];
let currentWidth = 0;
let currentLine = 0;
for (let i = 0; i < glyphArr.length; i++) {
const nextGlyph = boundsById[glyphArr[i]];
const nextGlyphWidth = nextGlyph.x_advance;
currentWidth += nextGlyphWidth;
if (currentWidth > maxWidth) {
currentLine += 1;
currentWidth = 0;
}
measuredLetters.push({
bounds: nextGlyph,
line: currentLine,
offset: {
x: currentWidth - nextGlyphWidth,
},
});
}
return measuredLetters;
}
type LetterBounds = {
x: {
max: number;
min: number;
};
y: {
max: number;
min: number;
};
width: number;
height: number;
x_advance: number;
};
type LetterMeasures = {
offset: {
x: number;
};
line: number;
bounds: LetterBounds;
};
export function calculateLetters(
CanvasKit: CanvasKit,
entity: z.output<typeof StaggeredTextEntity>,
dependencies: Dependencies
): StaggeredTextCache {
const fontData = dependencies.fonts.get(
entity.letter.paint.font_name
) as ArrayBuffer;
const typeface = CanvasKit.Typeface.MakeFreeTypeFaceFromData(
fontData
) as Typeface;
const font = new CanvasKit.Font(typeface, entity.letter.paint.size);
const glyphIDs = font.getGlyphIDs(entity.text);
// font.setLinearMetrics(true);
font.setSubpixel(true);
font.setHinting(CanvasKit.FontHinting.None);
const alphabet = getUniqueCharacters(entity.text);
const ids = font.getGlyphIDs(alphabet);
const unknownCharacterGlyphID = ids[0];
const charsToGlyphIDs: Record<string, any> = {};
let glyphIdx = 0;
for (let i = 0; i < alphabet.length; i++) {
charsToGlyphIDs[alphabet[i]] = ids[glyphIdx];
if ((alphabet.codePointAt(i) as number) > 65535) {
i++; // skip the next index because that will be the second half of the code point.
}
glyphIdx++;
}
const metrics = font.getMetrics();
const bounds = font.getGlyphBounds(glyphIDs);
const widths = font.getGlyphWidths(glyphIDs);
const glyphMetricsByGlyphID: Record<number, LetterBounds> = {};
for (let i = 0; i < glyphIDs.length; i++) {
const id = glyphIDs[i];
const x_min = bounds[i * 4];
const x_max = bounds[i * 4 + 2];
const y_min = bounds[i * 4 + 3];
const y_max = bounds[i * 4 + 1];
const width = x_max - x_min;
const height = Math.abs(y_max - y_min);
glyphMetricsByGlyphID[id] = {
x: {
min: x_min,
max: x_max,
},
y: {
min: y_min,
max: y_max,
},
width,
height,
x_advance: widths[i],
};
}
const glyphs = CanvasKit.MallocGlyphIDs(entity.text.length);
let glyphArr = glyphs.toTypedArray();
const MAX_WIDTH = 900;
// Turn the code points into glyphs, accounting for up to 2 ligatures.
let shapedGlyphIdx = -1;
for (let i = 0; i < entity.text.length; i++) {
const char = entity.text[i];
shapedGlyphIdx++;
glyphArr[shapedGlyphIdx] = charsToGlyphIDs[char] || unknownCharacterGlyphID;
if ((entity.text.codePointAt(i) as number) > 65535) {
i++; // skip the next index because that will be the second half of the code point.
}
}
// Trim down our array of glyphs to only the amount we have after ligatures and code points
// that are > 16 bits.
glyphArr = glyphs.subarray(0, shapedGlyphIdx + 1);
// Break our glyphs into runs based on the maxWidth and the xAdvance.
const letterMeasures = measureLetters(
glyphArr,
glyphMetricsByGlyphID,
MAX_WIDTH
);
return { letterMeasures, metrics, font, typeface, glyphs };
}
export default function drawStaggeredText(
CanvasKit: CanvasKit,
canvas: Canvas,
entity: z.output<typeof StaggeredTextEntity>,
cache: StaggeredTextCache
) {
const paint = new CanvasKit.Paint();
const { letterMeasures: measuredLetters, font, glyphs, metrics } = cache;
buildPaintStyle(CanvasKit, paint, entity.letter.paint);
if (glyphs) {
// Draw all those runs.
for (let i = 0; i < measuredLetters.length; i++) {
const measuredLetter = measuredLetters[i];
const glyph = glyphs.subarray(i, i + 1);
const blob = CanvasKit.TextBlob.MakeFromGlyphs(
glyph as unknown as Array<number>,
font
);
if (blob) {
canvas.save();
const width = measuredLetters
.filter((letter) => letter.line === 0)
.reduce((prev, curr) => curr.bounds.x_advance + prev, 0);
const lineOffset = (entity.letter.paint.size / 2) * measuredLetter.line;
const entityOrigin = [
entity.origin[0] - width / 2,
entity.origin[1] + lineOffset,
];
const lineCount = measuredLetters
.map((e) => e.line)
.sort((a, b) => a - b)[measuredLetters.length - 1];
if (entity.letter.transform && entity.letter.transform[i]) {
const letterTransform = entity.letter.transform[i];
const letterOrigin = [0, 0];
let origin = letterOrigin.map(
(val, index) => val + entityOrigin[index]
);
// Calculate the spacing
const spacing =
measuredLetter.bounds.x_advance - measuredLetter.bounds.width;
//console.log(spacing);
// Center the origin
origin[0] =
origin[0] +
measuredLetter.bounds.width / 2 +
measuredLetter.offset.x +
letterTransform.translate[0];
origin[1] =
origin[1] -
metrics.descent +
lineOffset +
letterTransform.translate[1];
//console.log(measuredLetter.bounds);
canvas.translate(origin[0], origin[1]);
canvas.rotate(
letterTransform.rotate[2],
letterTransform.rotate[0],
letterTransform.rotate[1]
);
canvas.scale(letterTransform.scale[0], letterTransform.scale[1]);
canvas.translate(
letterTransform.translate[0],
letterTransform.translate[1]
);
canvas.translate(
-origin[0] + measuredLetter.offset.x,
-origin[1] + lineOffset
);
/* canvas.translate(
measuredLetter.offset.x + measuredLetter.bounds.width / 2,
0
); */
}
/* canvas.translate(
width * -0.5,
lineCount * (-entity.letter.paint.size / 2)
); */
canvas.drawTextBlob(blob, entityOrigin[0], entityOrigin[1], paint);
canvas.restore();
blob.delete();
}
}
}
}

67
app/src/drawers/text.ts Normal file
View File

@ -0,0 +1,67 @@
import { Canvas, CanvasKit, Font, FontMgr, Typeface } from "canvaskit-wasm";
import { TextEntity } from "primitives/Entities";
import { convertToFloat } from "@tempblade/common";
import { z } from "zod";
import { EntityCache } from "./cache";
import { Dependencies } from "services/dependencies.service";
import { buildPaintStyle } from "./paint";
export type TextCache = {
fontManager: FontMgr;
};
export type TextEntityCache = EntityCache<TextCache>;
export function buildTextCache(
CanvasKit: CanvasKit,
entity: z.output<typeof TextEntity>,
dependencies: Dependencies
): TextCache {
const fontData = dependencies.fonts.get(
entity.paint.font_name
) as ArrayBuffer;
const fontManager = CanvasKit.FontMgr.FromData(fontData) as FontMgr;
return {
fontManager,
};
}
export default function drawText(
CanvasKit: CanvasKit,
canvas: Canvas,
entity: z.output<typeof TextEntity>,
cache: TextCache
) {
canvas.save();
const paint = new CanvasKit.Paint();
const color = convertToFloat(entity.paint.style.color.value);
buildPaintStyle(CanvasKit, paint, entity.paint);
const pStyle = new CanvasKit.ParagraphStyle({
textStyle: {
color: color,
fontFamilies: [entity.paint.font_name],
fontSize: entity.paint.size,
},
textDirection: CanvasKit.TextDirection.LTR,
textAlign: CanvasKit.TextAlign[entity.paint.align],
});
const builder = CanvasKit.ParagraphBuilder.Make(pStyle, cache.fontManager);
builder.addText(entity.text);
const p = builder.build();
p.layout(900);
const height = p.getHeight() / 2;
const width = p.getMaxWidth() / 2;
canvas.drawParagraph(p, entity.origin[0] - width, entity.origin[1] - height);
canvas.restore();
builder.delete();
}

406
app/src/example.ts Normal file
View File

@ -0,0 +1,406 @@
import { AnimatedEntity } from "primitives/AnimatedEntities";
import { Color } from "primitives/Paint";
import { Timeline } from "primitives/Timeline";
import {
staticAnimatedNumber,
staticAnimatedVec2,
staticAnimatedVec3,
} from "primitives/Values";
import { z } from "zod";
import { v4 as uuid } from "uuid";
function buildRect1(
offset: number,
color: z.infer<typeof Color>
): z.input<typeof AnimatedEntity> {
return {
id: uuid(),
cache: {},
type: "Rect",
paint: {
style: {
type: "Stroke",
width: 50,
color,
},
},
size: {
type: "Vec2",
keyframes: [
{
type: "Number",
keyframes: {
values: [
{
id: uuid(),
interpolation: {
type: "EasingFunction",
easing_function: "CircOut",
},
value: 0.0,
offset: 0.0,
},
{
id: uuid(),
interpolation: {
type: "Linear",
},
value: 1280.0,
offset: 4.0,
},
],
},
},
staticAnimatedNumber(720),
],
},
origin: staticAnimatedVec2(1280 / 2, 720 / 2),
position: staticAnimatedVec2(0, 0),
animation_data: {
offset,
duration: 10.0,
},
};
}
function buildRect(
offset: number,
color: z.infer<typeof Color>
): z.input<typeof AnimatedEntity> {
return {
type: "Rect",
id: uuid(),
cache: {},
paint: {
style: {
type: "Fill",
color,
},
},
size: staticAnimatedVec2(1280, 720),
origin: staticAnimatedVec2(0, -720),
position: staticAnimatedVec2(1280 / 2, 720 / 2),
transform: {
type: "Transform",
translate: staticAnimatedVec2(0, 0),
rotate: staticAnimatedVec3(0, 0, 0),
skew: staticAnimatedVec2(0, 0),
scale: {
type: "Vec2",
keyframes: [
{
type: "Number",
keyframes: {
values: [
{
id: uuid(),
interpolation: {
type: "Linear",
},
value: 1.0,
offset: 0.0,
},
],
},
},
{
type: "Number",
keyframes: {
values: [
{
id: uuid(),
interpolation: {
type: "EasingFunction",
easing_function: "CircOut",
},
value: 0.0,
offset: 0.0,
},
{
id: uuid(),
interpolation: {
type: "Linear",
},
value: 1.0,
offset: 4.0,
},
],
},
},
],
},
},
animation_data: {
offset,
duration: 10.0,
},
};
}
function buildText(
text: string,
offset: number,
size: number,
y_offset: number,
color: z.infer<typeof Color>
): z.input<typeof AnimatedEntity> {
return {
type: "Text",
id: uuid(),
cache: {},
paint: {
style: {
type: "Fill",
color,
},
font_name: "Gilroy-Regular",
size,
align: "Center",
},
text,
animation_data: {
offset,
duration: 5.0,
},
origin: {
type: "Vec2",
keyframes: [
{
type: "Number",
keyframes: {
values: [
{
id: uuid(),
interpolation: {
type: "EasingFunction",
easing_function: "CircOut",
},
value: (1280 / 2) * -1 - 300,
offset: 0.0,
},
{
id: uuid(),
interpolation: {
type: "EasingFunction",
easing_function: "QuartOut",
},
value: 1280 / 2,
offset: 5.0,
},
],
},
},
staticAnimatedNumber(720 / 2 + y_offset),
],
},
};
}
function buildStaggeredText(
text: string,
offset: number,
color: z.input<typeof Color>
): z.input<typeof AnimatedEntity> {
return {
type: "StaggeredText",
text,
cache: { valid: false },
id: uuid(),
origin: staticAnimatedVec2(1280 / 2, 720 / 2),
transform: {
type: "Transform",
translate: staticAnimatedVec2(0, 0),
rotate: staticAnimatedVec3(0, 0, 0),
skew: staticAnimatedVec2(0, 0),
scale: staticAnimatedVec2(1, 1),
},
animation_data: {
offset,
duration: 5.0,
},
stagger: 0.1,
letter: {
paint: {
font_name: "Gilroy-Regular",
style: {
type: "Fill",
color,
},
size: 90,
align: "Center",
},
transform: {
type: "Transform",
translate: {
type: "Vec2",
keyframes: [
staticAnimatedNumber(0),
{
type: "Number",
keyframes: {
values: [
{
id: uuid(),
interpolation: {
type: "Spring",
damping: 15,
stiffness: 350,
mass: 1,
},
value: 200.0,
offset: 0.0,
},
{
id: uuid(),
interpolation: {
type: "Linear",
},
value: 0.0,
offset: 4.0,
},
],
},
},
],
},
rotate: {
type: "Vec3",
keyframes: [
staticAnimatedNumber(0),
staticAnimatedNumber(0),
{
type: "Number",
keyframes: {
values: [
{
id: uuid(),
interpolation: {
type: "Spring",
damping: 15,
stiffness: 150,
mass: 1,
},
value: -180.0,
offset: 0.0,
},
{
id: uuid(),
interpolation: {
type: "Linear",
},
value: 0.0,
offset: 4.0,
},
],
},
},
],
},
skew: staticAnimatedVec2(0, 0),
scale: {
type: "Vec2",
keyframes: [
{
type: "Number",
keyframes: {
values: [
{
id: uuid(),
interpolation: {
type: "EasingFunction",
easing_function: "CircOut",
},
value: 0.0,
offset: 0.0,
},
{
id: uuid(),
interpolation: {
type: "Linear",
},
value: 1.0,
offset: 2.0,
},
],
},
},
{
type: "Number",
keyframes: {
values: [
{
id: uuid(),
interpolation: {
type: "EasingFunction",
easing_function: "CircOut",
},
value: 0.0,
offset: 0.0,
},
{
id: uuid(),
interpolation: {
type: "Linear",
},
value: 1.0,
offset: 2.0,
},
],
},
},
],
},
},
},
};
}
export const EXAMPLE_ANIMATED_ENTITIES: Array<z.input<typeof AnimatedEntity>> =
[
buildStaggeredText("Work in Progress...", 2.0, {
value: [255, 255, 255, 1.0],
}),
// buildText("Wie gehts?", 2.5, 40, 40, { value: [200, 200, 200, 1.0] }),
buildRect(0.6, { value: [30, 30, 30, 1.0] }),
buildRect(0.4, { value: [20, 20, 20, 1.0] }),
buildRect(0.2, { value: [10, 10, 10, 1.0] }),
buildRect(0, { value: [0, 0, 0, 1.0] }),
];
export const EXAMPLE_ANIMATED_ENTITIES_2: Array<
z.input<typeof AnimatedEntity>
> = [
buildText("Kleine Dumpfkopf!", 1.0, 80, -30, {
value: [255, 255, 255, 1.0],
}),
// buildText("Wie gehts?", 1.5, 40, 30, { value: [255, 255, 255, 1.0] }),
buildRect(0.8, { value: [40, 40, 40, 1.0] }),
buildRect(0.6, { value: [30, 30, 30, 1.0] }),
buildRect(0.4, { value: [20, 20, 20, 1.0] }),
buildRect(0.2, { value: [10, 10, 10, 1.0] }),
buildRect(0, { value: [0, 0, 0, 1.0] }),
];
const ExampleTimeline: z.input<typeof Timeline> = {
size: [1920, 1080],
duration: 10.0,
render_state: {
curr_frame: 20,
},
fps: 120,
entities: EXAMPLE_ANIMATED_ENTITIES,
};
export { ExampleTimeline };

View File

@ -0,0 +1,33 @@
import { useCallback, useEffect } from "react";
import { useEntitiesStore } from "stores/entities.store";
import { useRenderStateStore } from "stores/render-state.store";
export default function useKeyControls() {
const handleKeyPress = useCallback((e: KeyboardEvent) => {
// Only run shortcuts if no input is focused
if (document.activeElement?.nodeName !== "INPUT") {
if (e.code === "Space") {
e.preventDefault();
useRenderStateStore.getState().togglePlaying();
}
if (e.code === "Backspace") {
const selectedEntity = useEntitiesStore.getState().selectedEntity;
if (selectedEntity !== undefined) {
useEntitiesStore.getState().deleteEntity(selectedEntity);
}
}
}
}, []);
useEffect(() => {
// attach the event listener
document.addEventListener("keydown", handleKeyPress);
// remove the event listener
return () => {
document.removeEventListener("keydown", handleKeyPress);
};
}, [handleKeyPress]);
}

53
app/src/hooks/useMap.ts Normal file
View File

@ -0,0 +1,53 @@
import { useCallback, useState } from "react";
export type MapOrEntries<K, V> = Map<K, V> | [K, V][];
// Public interface
export interface Actions<K, V> {
set: (key: K, value: V) => void;
setAll: (entries: MapOrEntries<K, V>) => void;
remove: (key: K) => void;
reset: Map<K, V>["clear"];
}
// We hide some setters from the returned map to disable autocompletion
type Return<K, V> = [
Omit<Map<K, V>, "set" | "clear" | "delete">,
Actions<K, V>
];
function useMap<K, V>(
initialState: MapOrEntries<K, V> = new Map()
): Return<K, V> {
const [map, setMap] = useState(new Map(initialState));
const actions: Actions<K, V> = {
set: useCallback((key, value) => {
setMap((prev) => {
const copy = new Map(prev);
copy.set(key, value);
return copy;
});
}, []),
setAll: useCallback((entries) => {
setMap(() => new Map(entries));
}, []),
remove: useCallback((key) => {
setMap((prev) => {
const copy = new Map(prev);
copy.delete(key);
return copy;
});
}, []),
reset: useCallback(() => {
setMap(() => new Map());
}, []),
};
return [map, actions];
}
export default useMap;

20
app/src/main.tsx Normal file
View File

@ -0,0 +1,20 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./styles.css";
import { useFontsStore } from "stores/fonts.store";
import { invoke } from "@tauri-apps/api";
invoke("get_system_families").then((data) => {
if (data && Array.isArray(data)) {
const fontsStore = useFontsStore.getState();
fontsStore.setFonts(data);
fontsStore.setDidInit(true);
}
});
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>
);

View File

@ -0,0 +1,194 @@
import { z } from "zod";
import {
BaseEntity,
EllipseEntity,
EntityType,
RectEntity,
TextEntity,
} from "./Entities";
import { AnimatedTransform, AnimatedVec2 } from "./Values";
import { TextPaint } from "./Paint";
import { AnimatedProperties } from "./AnimatedProperty";
export const AnimationData = z.object({
offset: z.number(),
duration: z.number(),
visible: z.boolean().optional().default(true),
});
export const AnimatedStaggeredTextEntity = BaseEntity.extend({
/** Transform applied to the whole layer. */
transform: AnimatedTransform,
/** The staggered delay that is applied for each letter. Gets multiplied by the index of the letter. */
stagger: z.number().min(0),
/** These properties get applied to each letter */
letter: z.object({
transform: AnimatedTransform,
paint: TextPaint,
}),
text: z.string(),
origin: AnimatedVec2,
animation_data: AnimationData,
type: z.literal(EntityType.Enum.StaggeredText),
});
export const AnimatedRectEntity = RectEntity.extend({
position: AnimatedVec2,
size: AnimatedVec2,
origin: AnimatedVec2,
transform: AnimatedTransform.optional(),
animation_data: AnimationData,
});
export const AnimatedTextEntity = TextEntity.extend({
origin: AnimatedVec2,
transform: AnimatedTransform.optional(),
animation_data: AnimationData,
});
export const AnimatedEllipseEntity = EllipseEntity.extend({
radius: AnimatedVec2,
position: AnimatedVec2,
origin: AnimatedVec2,
transform: AnimatedTransform.optional(),
animation_data: AnimationData,
});
export const AnimatedEntity = z.discriminatedUnion("type", [
AnimatedRectEntity,
AnimatedTextEntity,
AnimatedStaggeredTextEntity,
AnimatedEllipseEntity,
]);
export const AnimatedEntities = z.array(AnimatedEntity);
export function animatedTransformToAnimatedProperties(
animatedTransform: z.input<typeof AnimatedTransform>,
basePath?: string
): z.input<typeof AnimatedProperties> {
return [
{
animatedValue: animatedTransform.translate,
label: "Translation",
propertyPath: basePath
? basePath + ".transform.translate"
: "transform.translate",
},
{
animatedValue: animatedTransform.rotate,
label: "Rotation",
propertyPath: basePath
? basePath + ".transform.rotate"
: "transform.rotate",
},
{
animatedValue: animatedTransform.scale,
label: "Scale",
propertyPath: basePath
? basePath + ".transform.scale"
: "transform.scale",
},
{
animatedValue: animatedTransform.skew,
label: "Skew",
propertyPath: basePath ? basePath + ".transform.skew" : "transform.skew",
},
];
}
export function getAnimatedPropertiesByAnimatedEntity(
animatedEntity: z.input<typeof AnimatedEntity>
) {
const animatedProperties: z.input<typeof AnimatedProperties> = [];
switch (animatedEntity.type) {
case "Ellipse":
animatedProperties.push({
propertyPath: "origin",
animatedValue: animatedEntity.origin,
label: "Origin",
});
animatedProperties.push({
propertyPath: "radius",
animatedValue: animatedEntity.radius,
label: "Radius",
});
if (animatedEntity.transform) {
animatedProperties.push(
...animatedTransformToAnimatedProperties(animatedEntity.transform)
);
}
break;
case "Rect":
animatedProperties.push({
propertyPath: "origin",
animatedValue: animatedEntity.origin,
label: "Origin",
});
animatedProperties.push({
propertyPath: "size",
animatedValue: animatedEntity.size,
label: "Size",
});
if (animatedEntity.transform) {
animatedProperties.push(
...animatedTransformToAnimatedProperties(animatedEntity.transform)
);
}
break;
case "StaggeredText":
animatedProperties.push({
propertyPath: "origin",
animatedValue: animatedEntity.origin,
label: "Origin",
});
if (animatedEntity.transform) {
animatedProperties.push(
...animatedTransformToAnimatedProperties(animatedEntity.transform)
);
}
if (animatedEntity.letter.transform) {
animatedProperties.push(
...animatedTransformToAnimatedProperties(
animatedEntity.letter.transform,
"letter"
)
);
}
break;
case "Text":
animatedProperties.push({
propertyPath: "origin",
animatedValue: animatedEntity.origin,
label: "Origin",
});
if (animatedEntity.transform) {
animatedProperties.push(
...animatedTransformToAnimatedProperties(animatedEntity.transform)
);
}
break;
}
return animatedProperties;
}
export function getAnimatedPropertiesByAnimatedEnties(
animatedEntities: z.input<typeof AnimatedEntities>
) {
const animatedProperties: z.input<typeof AnimatedProperties> = [];
animatedEntities.forEach((aEnt) => {
animatedProperties.push(...getAnimatedPropertiesByAnimatedEntity(aEnt));
});
}

View File

@ -0,0 +1,10 @@
import { z } from "zod";
import { AnimatedValue } from "./Values";
export const AnimatedProperty = z.object({
propertyPath: z.string(),
animatedValue: AnimatedValue,
label: z.string(),
});
export const AnimatedProperties = z.array(AnimatedProperty);

View File

@ -0,0 +1,19 @@
import { z } from "zod";
export const EffectTypeOptions = ["Blur", "Erode", "Displace"] as const;
export const TileModeOptions = ["Clamp", "Decal", "Mirror", "Repeat"] as const;
export const EffectType = z.enum(EffectTypeOptions);
export const TileMode = z.enum(TileModeOptions);
export const EffectLayer = z.object({
entityId: z.string().uuid(),
});
export const BlurEffectLayer = EffectLayer.extend({
type: z.literal(EffectType.enum.Blur),
amountX: z.number().min(0),
amountY: z.number().min(0),
tileMode: TileMode,
});

View File

@ -0,0 +1,70 @@
import { z } from "zod";
import { Vec2, Vec3 } from "./Values";
import { Paint, TextPaint } from "./Paint";
const EntityTypeOptions = ["Text", "Ellipse", "Rect", "StaggeredText"] as const;
export const EntityType = z.enum(EntityTypeOptions);
export const Transform = z.object({
skew: Vec2,
rotate: Vec3,
translate: Vec2,
scale: Vec2,
});
export const Cache = z.object({
valid: z.boolean().optional().default(true),
});
export const BaseEntity = z.object({
id: z.string(),
cache: Cache,
});
export const GeometryEntity = BaseEntity.extend({
paint: Paint,
});
export const StaggeredTextEntity = BaseEntity.extend({
letter: z.object({
transform: z.array(Transform).optional(),
paint: TextPaint,
}),
origin: Vec2,
text: z.string(),
type: z.literal(EntityType.Enum.StaggeredText),
});
export const RectEntity = GeometryEntity.extend({
type: z.literal(EntityType.Enum.Rect),
size: Vec2,
position: Vec2,
origin: Vec2,
transform: z.nullable(Transform),
});
export const EllipseEntity = GeometryEntity.extend({
type: z.literal(EntityType.Enum.Ellipse),
radius: Vec2,
position: Vec2,
origin: Vec2,
transform: z.nullable(Transform),
});
export const TextEntity = BaseEntity.extend({
type: z.literal(EntityType.Enum.Text),
paint: TextPaint,
origin: Vec2,
text: z.string(),
transform: z.nullable(Transform),
});
export const Entity = z.discriminatedUnion("type", [
RectEntity,
EllipseEntity,
TextEntity,
StaggeredTextEntity,
]);
export const Entities = z.array(Entity);

View File

@ -0,0 +1,53 @@
import { z } from "zod";
const InterpolationTypeOptions = [
"Linear",
"Spring",
"EasingFunction",
] as const;
const EasingFunctionOptions = [
"QuintOut",
"QuintIn",
"QuintInOut",
"CircOut",
"CircIn",
"CircInOut",
"CubicOut",
"CubicIn",
"CubicInOut",
"ExpoOut",
"ExpoIn",
"ExpoInOut",
"QuadOut",
"QuadIn",
"QuadInOut",
"QuartOut",
"QuartIn",
"QuartInOut",
] as const;
export const EasingFunction = z.enum(EasingFunctionOptions);
export const InterpolationType = z.enum(InterpolationTypeOptions);
export const LinearInterpolation = z.object({
type: z.literal(InterpolationType.Enum.Linear),
});
export const EasingFunctionInterpolation = z.object({
type: z.literal(InterpolationType.Enum.EasingFunction),
easing_function: EasingFunction.default("CircOut"),
});
export const SpringInterpolation = z.object({
mass: z.number().default(1),
damping: z.number().default(15),
stiffness: z.number().default(200),
type: z.literal(InterpolationType.Enum.Spring),
});
export const Interpolation = z.discriminatedUnion("type", [
SpringInterpolation,
EasingFunctionInterpolation,
LinearInterpolation,
]);

View File

@ -0,0 +1,13 @@
import { z } from "zod";
import { Interpolation } from "./Interpolation";
export const Keyframe = z.object({
id: z.string().uuid(),
value: z.number(),
offset: z.number(),
interpolation: z.optional(Interpolation),
});
export const Keyframes = z.object({
values: z.array(Keyframe),
});

View File

@ -0,0 +1,50 @@
import { z } from "zod";
export const Color = z.object({
value: z.array(z.number().min(0).max(255)).max(4),
});
const PaintStyleTypeOptions = ["Fill", "Stroke"] as const;
export const PaintStyleType = z.enum(PaintStyleTypeOptions);
const ColorWithDefault = Color.optional().default({ value: [0, 0, 0, 1] });
export const StrokeStyle = z.object({
width: z.number().min(0).optional().default(10),
color: ColorWithDefault,
type: z.literal(PaintStyleType.Enum.Stroke),
});
export const FillStyle = z.object({
color: ColorWithDefault,
type: z.literal(PaintStyleType.Enum.Fill),
});
export const TextAlign = z.enum(["Left", "Center", "Right"]);
export const PaintStyle = z.discriminatedUnion("type", [
StrokeStyle,
FillStyle,
]);
export const Paint = z.object({
style: PaintStyle,
});
export const TextPaint = z.object({
style: PaintStyle,
align: TextAlign,
font_name: z.string(),
size: z.number().min(0),
});
/* const NestedFillStyle = FillStyle.omit({ type: true }).default({});
const NestedStrokeStyle = StrokeStyle.omit({ type: true }).default({});
export const StrokeAndFillStyle = z.object({
color: ColorWithDefault,
type: z.literal(PaintStyleType.Enum.StrokeAndFill),
fill: NestedFillStyle,
stroke: NestedStrokeStyle,
}); */

View File

@ -0,0 +1,14 @@
import { z } from "zod";
import { AnimatedEntities } from "./AnimatedEntities";
export const RenderState = z.object({
curr_frame: z.number(),
});
export const Timeline = z.object({
entities: AnimatedEntities,
render_state: RenderState,
duration: z.number(),
fps: z.number().int(),
size: z.array(z.number().int()).length(2),
});

View File

@ -0,0 +1,106 @@
import { z } from "zod";
import { Keyframes } from "./Keyframe";
import { v4 as uuid } from "uuid";
export const Vec2 = z.array(z.number()).length(2);
export const Vec3 = z.array(z.number()).length(3);
const ValueTypeOptions = ["Vec2", "Vec3", "Number"] as const;
export const ValueType = z.enum(ValueTypeOptions);
export const AnimatedNumber = z.object({
keyframes: Keyframes,
type: z.literal(ValueType.Enum.Number),
});
export const AnimatedVec2 = z.object({
keyframes: z.array(AnimatedNumber).length(2),
type: z.literal(ValueType.Enum.Vec2),
});
export const AnimatedVec3 = z.object({
keyframes: z.array(AnimatedNumber).length(3),
type: z.literal(ValueType.Enum.Vec3),
});
export const AnimatedTransform = z.object({
type: z.literal("Transform"),
/** Translates by the given animated vec2 */
translate: AnimatedVec2,
/** Skews by the given animated vec2 */
skew: AnimatedVec2,
/** Rotates by the given animated vec3 */
rotate: AnimatedVec3,
/** Scales on the x and y axis by the given animated vec2 */
scale: AnimatedVec2,
});
export const AnimatedValue = z.discriminatedUnion("type", [
AnimatedNumber,
AnimatedVec2,
AnimatedVec3,
AnimatedTransform,
]);
export function staticAnimatedNumber(
number: number
): z.infer<typeof AnimatedNumber> {
return {
type: ValueType.Enum.Number,
keyframes: {
values: [
{
id: uuid(),
interpolation: {
type: "Linear",
},
value: number,
offset: 0,
},
],
},
};
}
export function staticAnimatedVec2(
x: number,
y: number
): z.infer<typeof AnimatedVec2> {
return {
type: ValueType.Enum.Vec2,
keyframes: [staticAnimatedNumber(x), staticAnimatedNumber(y)],
};
}
export function staticAnimatedVec3(
x: number,
y: number,
z: number
): z.infer<typeof AnimatedVec3> {
return {
type: ValueType.Enum.Vec3,
keyframes: [
staticAnimatedNumber(x),
staticAnimatedNumber(y),
staticAnimatedNumber(z),
],
};
}
export function staticAnimatedTransform(
translate: [number, number],
scale: [number, number],
rotate: [number, number, number],
skew: [number, number]
): z.input<typeof AnimatedTransform> {
return {
type: "Transform",
translate: staticAnimatedVec2(...translate),
scale: staticAnimatedVec2(...scale),
rotate: staticAnimatedVec3(...rotate),
skew: staticAnimatedVec2(...skew),
};
}

View File

@ -0,0 +1,80 @@
import { invoke } from "@tauri-apps/api";
import { AnimatedEntities } from "primitives/AnimatedEntities";
import { Entities, EntityType } from "primitives/Entities";
import { z } from "zod";
function typedArrayToBuffer(array: Uint8Array): ArrayBuffer {
return array.buffer.slice(
array.byteOffset,
array.byteLength + array.byteOffset
);
}
export type Dependencies = {
fonts: Map<string, ArrayBuffer>;
};
export class DependenciesService {
dependencies: Dependencies;
constructor() {
this.dependencies = {
fonts: new Map(),
};
}
private async prepare(
entities: z.output<typeof Entities> | z.output<typeof AnimatedEntities>
) {
const fontNames = new Set<string>();
entities.forEach((entity) => {
switch (entity.type) {
case EntityType.Enum.Text:
fontNames.add(entity.paint.font_name);
break;
case EntityType.Enum.StaggeredText:
fontNames.add(entity.letter.paint.font_name);
break;
default:
break;
}
});
await this.loadFonts(fontNames);
return this.dependencies;
}
async prepareForEntities(entities: z.output<typeof Entities>) {
await this.prepare(entities);
}
async prepareForAnimatedEntities(
animatedEntities: z.output<typeof AnimatedEntities>
) {
await this.prepare(animatedEntities);
}
async loadFonts(fontNames: Set<string>) {
const resolveFonts: Array<Promise<void>> = [];
const loadFont = async (fontName: string) => {
return invoke("get_system_font", { fontName }).then((data) => {
if (Array.isArray(data)) {
const u8 = new Uint8Array(data as any);
const buffer = typedArrayToBuffer(u8);
this.dependencies.fonts.set(fontName, buffer);
}
});
};
fontNames.forEach((fontName) => {
if (!this.dependencies.fonts.has(fontName)) {
resolveFonts.push(loadFont(fontName));
}
});
await Promise.all(resolveFonts);
}
}

View File

@ -0,0 +1,124 @@
import { EntityType } from "primitives/Entities";
import { PaintStyleType, TextAlign } from "primitives/Paint";
import { staticAnimatedTransform, staticAnimatedVec2 } from "primitives/Values";
import { useEntitiesStore } from "stores/entities.store";
import { useTimelineStore } from "stores/timeline.store";
import { v4 as uuid } from "uuid";
export class EntitiesService {
get entitiesStore() {
return useEntitiesStore.getState();
}
private get timelineStore() {
return useTimelineStore.getState();
}
createUuid() {
return uuid();
}
createRect() {
return this.entitiesStore.createEntity({
type: EntityType.Enum.Rect,
id: this.createUuid(),
cache: {},
paint: {
style: {
type: PaintStyleType.Enum.Fill,
color: {
value: [233, 100, 150, 1.0],
},
},
},
size: staticAnimatedVec2(500, 500),
origin: staticAnimatedVec2(-250, -250),
position: staticAnimatedVec2(...this.timelineStore.size),
transform: staticAnimatedTransform([0, 0], [1, 1], [0, 0, 0], [0, 0]),
animation_data: {
offset: 0,
duration: 3,
},
});
}
createEllipse() {
return this.entitiesStore.createEntity({
type: EntityType.Enum.Ellipse,
id: this.createUuid(),
cache: {},
paint: {
style: {
type: PaintStyleType.Enum.Fill,
color: {
value: [233, 100, 150, 1.0],
},
},
},
radius: staticAnimatedVec2(500, 500),
origin: staticAnimatedVec2(-250, -250),
position: staticAnimatedVec2(...this.timelineStore.size),
transform: staticAnimatedTransform([0, 0], [1, 1], [0, 0, 0], [0, 0]),
animation_data: {
offset: 0,
duration: 3,
},
});
}
createText(text?: string) {
return this.entitiesStore.createEntity({
type: EntityType.Enum.Text,
id: this.createUuid(),
cache: {},
text: text || "Hallo Welt",
paint: {
align: TextAlign.Enum.Center,
size: 20,
font_name: "Helvetica-Bold",
style: {
type: PaintStyleType.Enum.Fill,
color: {
value: [233, 100, 150, 1.0],
},
},
},
origin: staticAnimatedVec2(-250, -250),
transform: staticAnimatedTransform([0, 0], [1, 1], [0, 0, 0], [0, 0]),
animation_data: {
offset: 0,
duration: 3,
},
});
}
createStaggeredText(text?: string) {
return this.entitiesStore.createEntity({
type: EntityType.Enum.StaggeredText,
id: this.createUuid(),
cache: {},
text: text || "Hallo Welt",
stagger: 0.1,
letter: {
paint: {
align: TextAlign.Enum.Center,
size: 20,
font_name: "Helvetica-Bold",
style: {
type: PaintStyleType.Enum.Fill,
color: {
value: [233, 100, 150, 1.0],
},
},
},
transform: staticAnimatedTransform([0, 0], [1, 1], [0, 0, 0], [0, 0]),
},
origin: staticAnimatedVec2(-250, -250),
transform: staticAnimatedTransform([0, 0], [1, 1], [0, 0, 0], [0, 0]),
animation_data: {
offset: 0,
duration: 3,
},
});
}
}

View File

@ -0,0 +1,106 @@
import { Drawer } from "drawers/draw";
import { AnimatedEntities } from "primitives/AnimatedEntities";
import { useEntitiesStore } from "stores/entities.store";
import { useRenderStateStore } from "stores/render-state.store";
import { useTimelineStore } from "stores/timeline.store";
export class PlaybackService {
drawer: Drawer;
lastDrawTime: number | undefined;
raf: number | undefined;
playing: boolean;
constructor() {
this.drawer = new Drawer();
this.lastDrawTime = undefined;
this.raf = undefined;
this.playing = false;
}
async init(canvas: HTMLCanvasElement) {
await this.drawer.init(canvas);
useRenderStateStore.subscribe((state) => {
if (!this.playing && state.playing) {
this.playing = true;
this.play();
}
if (this.playing && !state.playing) {
this.playing = false;
this.stop();
}
if (!this.playing && !state.playing) {
this.seek();
}
});
useEntitiesStore.subscribe((state) => {
if (!this.playing) {
this.seek();
}
});
this.seek();
}
play() {
this.drawer.dependenciesService.prepareForAnimatedEntities(
this.animatedEntities
);
const currentTime = window.performance.now();
this.lastDrawTime = currentTime;
this.playLoop(currentTime);
}
stop() {
if (this.raf !== undefined) {
cancelAnimationFrame(this.raf);
}
}
seek() {
this.drawer.update(this.animatedEntities, true);
}
get animatedEntities() {
return AnimatedEntities.parse(useEntitiesStore.getState().entities);
}
get timelineStore() {
return useTimelineStore.getState();
}
get fpsInterval() {
return 1000 / this.timelineStore.fps;
}
get currFrame() {
return useRenderStateStore.getState().renderState.curr_frame;
}
get totalFrameCount() {
return this.timelineStore.fps * this.timelineStore.duration;
}
playLoop(currentTime: number) {
this.raf = requestAnimationFrame(this.playLoop.bind(this));
if (this.lastDrawTime !== undefined) {
const elapsed = currentTime - this.lastDrawTime;
if (elapsed > this.fpsInterval) {
this.lastDrawTime = currentTime - (elapsed % this.fpsInterval);
const nextFrame =
this.currFrame + 1 < this.totalFrameCount ? this.currFrame + 1 : 0;
useRenderStateStore.getState().setCurrentFrame(nextFrame);
this.drawer.update(this.animatedEntities, false);
}
}
}
}

View File

@ -0,0 +1,27 @@
import { useTimelineStore } from "stores/timeline.store";
import { useEntitiesStore } from "stores/entities.store";
import { useRenderStateStore } from "stores/render-state.store";
import { z } from "zod";
import { Timeline } from "primitives/Timeline";
export class ProjectService {
public saveProject() {
const timelineStore = useTimelineStore.getState();
const entitiesStore = useEntitiesStore.getState();
const renderStateStore = useRenderStateStore.getState();
const timeline: z.input<typeof Timeline> = {
...timelineStore,
entities: entitiesStore.entities,
render_state: renderStateStore.renderState,
};
const parsedTimeline = Timeline.parse(timeline);
const serializedTimeline = JSON.stringify(parsedTimeline);
return serializedTimeline;
}
public loadProject() {}
}

View File

@ -0,0 +1,32 @@
import { Timeline } from "primitives/Timeline";
// TODO: publish package maybe provide wrapper etc.
import * as creatorWasm from "../../../lib/creator_rs/pkg";
import { z } from "zod";
import { useTimelineStore } from "stores/timeline.store";
import { useEntitiesStore } from "stores/entities.store";
import { useRenderStateStore } from "stores/render-state.store";
export class RenderService {
render() {
}
calculate() {
const timelineStore = useTimelineStore.getState();
const entitiesStore = useEntitiesStore.getState();
const renderStateStore = useRenderStateStore.getState();
let timeline: z.input<typeof Timeline> = {
...timelineStore,
entities: entitiesStore.entities,
render_state: renderStateStore.renderState
}
timeline = Timeline.parse(timeline);
const renderedEntities = creatorWasm.calculate_timeline_from_json_at_curr_frame(JSON.stringify(timeline));
console.log(renderedEntities);
}
}

View File

@ -0,0 +1,74 @@
import { EXAMPLE_ANIMATED_ENTITIES } from "example";
import { produce } from "immer";
import { AnimatedEntities, AnimatedEntity } from "primitives/AnimatedEntities";
import { z } from "zod";
import { create } from "zustand";
interface EntitiesStore {
entities: z.input<typeof AnimatedEntities>;
selectedEntity: number | undefined;
selectedKeyframe: string | undefined;
selectEntity: (index: number) => void;
deselectEntity: () => void;
setEntities: (entities: z.input<typeof AnimatedEntities>) => void;
updateEntity: (
index: number,
entity: Partial<z.input<typeof AnimatedEntity>>
) => void;
createEntity: (
entity: z.input<typeof AnimatedEntity>
) => z.input<typeof AnimatedEntity>;
deleteEntity: (index: number) => void;
updateEntityById: (
id: string,
entity: Partial<z.input<typeof AnimatedEntity>>
) => void;
}
const useEntitiesStore = create<EntitiesStore>((set, get) => ({
entities: EXAMPLE_ANIMATED_ENTITIES,
selectedKeyframe: undefined,
selectEntity: (index) => set(() => ({ selectedEntity: index })),
deselectEntity: () => set(() => ({ selectedEntity: undefined })),
selectedEntity: undefined,
setEntities: (entities) => {
console.log("set entities");
set({ entities });
},
createEntity: (entity) => {
set({ entities: [...get().entities, entity] });
return entity;
},
updateEntityById: (id, entity) =>
set(({ entities }) => {
const nextEntities = produce(entities, (draft) => {
const index = draft.findIndex((e) => e.id === id);
draft[index] = { ...draft[index], ...entity } as z.infer<
typeof AnimatedEntity
>;
});
return { entities: nextEntities };
}),
deleteEntity: (index) =>
set(({ entities }) => {
const nextEntities = produce(entities, (draft) => {
draft.splice(index, 1);
});
return { entities: nextEntities };
}),
updateEntity: (index, entity) =>
set(({ entities }) => {
const nextEntities = produce(entities, (draft) => {
draft[index] = { ...draft[index], ...entity } as z.infer<
typeof AnimatedEntity
>;
});
return { entities: nextEntities };
}),
}));
export { useEntitiesStore };

View File

@ -0,0 +1,17 @@
import { create } from "zustand";
interface FontsStore {
fonts: Array<string>;
didInit: boolean;
setDidInit: (didInit: boolean) => void;
setFonts: (fonts: Array<string>) => void;
}
const useFontsStore = create<FontsStore>((set) => ({
fonts: [],
didInit: false,
setDidInit: (didInit) => set({ didInit }),
setFonts: (fonts) => set({ fonts }),
}));
export { useFontsStore };

View File

@ -0,0 +1,15 @@
import { create } from "zustand";
interface KeyframeStore {
selectedKeyframe: string | undefined;
selectKeyframe: (id: string) => void;
deselectKeyframe: () => void;
}
const useKeyframeStore = create<KeyframeStore>((set) => ({
selectKeyframe: (id) => set({ selectedKeyframe: id }),
deselectKeyframe: () => set({ selectedKeyframe: undefined }),
selectedKeyframe: undefined,
}));
export { useKeyframeStore };

View File

@ -0,0 +1,30 @@
import { RenderState } from "primitives/Timeline";
import { z } from "zod";
import { create } from "zustand";
interface RenderStateStore {
renderState: z.infer<typeof RenderState>;
playing: boolean;
setPlaying: (playing: boolean) => void;
togglePlaying: () => void;
setCurrentFrame: (target: number) => void;
}
const useRenderStateStore = create<RenderStateStore>((set, get) => ({
renderState: {
curr_frame: 20,
},
playing: false,
togglePlaying: () => set({ playing: !get().playing }),
setPlaying: (playing) => set({ playing }),
setCurrentFrame: (target) =>
set((store) => {
store.renderState = {
curr_frame: target,
};
return { renderState: store.renderState };
}),
}));
export { useRenderStateStore };

View File

@ -0,0 +1,15 @@
import { create } from "zustand";
interface TimelineStore {
fps: number;
duration: number;
size: [number, number];
}
const useTimelineStore = create<TimelineStore>((set) => ({
fps: 60,
size: [1280, 720],
duration: 10.0,
}));
export { useTimelineStore };

98
app/src/styles.css Normal file
View File

@ -0,0 +1,98 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
h1 {
@apply text-2xl;
}
h2 {
@apply text-xl;
}
h3 {
@apply text-lg;
}
a {
@apply text-blue-600 underline;
}
input {
@apply box-border bg-transparent shadow-main/10 hover:shadow-primary/50
focus:ring-primary focus:ring-2 focus:ring-offset-1
focus:shadow-primary selection:bg-secondary selection:text-black
outline-none px-3 py-2 rounded-md shadow-[0_0_0_1px]
appearance-none items-center justify-center
w-full text-base leading-none transition-all;
}
select {
@apply appearance-none;
}
:root {
--color-main: 0 0% 0%;
--color-secondary: 0 0% 10%;
--color-neutral: 0 0% 100%;
--color-neutral-accent: 0 0% 90%;
--color-highlight: 0 0% 0%;
--color-primary: 222.2 47.4% 11.2%;
}
@media (prefers-color-scheme: dark) {
:root {
--color-main: 0 0% 100%;
--color-primary: 260 80% 50%;
--color-secondary: 260 50% 70%;
--color-neutral: 250 30% 8%;
--color-neutral-accent: 250 40% 12%;
--color-highlight: 250 20% 15%;
}
}
}
@layer base {
* {
@apply border-highlight;
}
body {
@apply bg-neutral text-main;
font-feature-settings: "rlig" 1, "calt" 1;
}
}
label {
@apply mb-1 text-sm opacity-70;
}
fieldset {
@apply mb-2 flex flex-col items-start;
}
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
html,
body,
#root {
width: 100%;
height: 100%;
overflow: hidden;
}

120
app/src/utils/index.ts Normal file
View File

@ -0,0 +1,120 @@
import { AnimatedEntity } from "primitives/AnimatedEntities";
import { Keyframe } from "primitives/Keyframe";
import { AnimatedNumber, AnimatedVec2, AnimatedVec3 } from "primitives/Values";
import { z } from "zod";
import { ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function flattenAnimatedNumberKeyframes(
aNumber: z.input<typeof AnimatedNumber>
): Array<z.input<typeof Keyframe>> {
return aNumber.keyframes.values;
}
function componentToHex(c: number) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
export function rgbToHex(r: number, g: number, b: number) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
export function flattenAnimatedVec2Keyframes(
aVec2: z.input<typeof AnimatedVec2>
): Array<z.input<typeof Keyframe>> {
const keyframes: Array<z.input<typeof Keyframe>> = [
...flattenAnimatedNumberKeyframes(aVec2.keyframes[0]),
...flattenAnimatedNumberKeyframes(aVec2.keyframes[1]),
];
return keyframes;
}
export function flattenAnimatedVec3Keyframes(
aVec3: z.input<typeof AnimatedVec3>
): Array<z.input<typeof Keyframe>> {
const keyframes: Array<z.input<typeof Keyframe>> = [
...flattenAnimatedNumberKeyframes(aVec3.keyframes[0]),
...flattenAnimatedNumberKeyframes(aVec3.keyframes[1]),
...flattenAnimatedNumberKeyframes(aVec3.keyframes[2]),
];
return keyframes;
}
export function flattenedKeyframesByEntity(
entity: z.input<typeof AnimatedEntity>
): Array<z.input<typeof Keyframe>> {
const keyframes: Array<z.input<typeof Keyframe>> = [];
switch (entity.type) {
case "Text":
keyframes.push(...flattenAnimatedVec2Keyframes(entity.origin));
break;
case "Rect":
keyframes.push(...flattenAnimatedVec2Keyframes(entity.position));
keyframes.push(...flattenAnimatedVec2Keyframes(entity.size));
break;
case "Ellipse":
keyframes.push(...flattenAnimatedVec2Keyframes(entity.position));
keyframes.push(...flattenAnimatedVec2Keyframes(entity.radius));
break;
case "StaggeredText":
keyframes.push(
...flattenAnimatedVec3Keyframes(entity.letter.transform.rotate)
);
keyframes.push(
...flattenAnimatedVec2Keyframes(entity.letter.transform.translate)
);
keyframes.push(
...flattenAnimatedVec2Keyframes(entity.letter.transform.skew)
);
keyframes.push(
...flattenAnimatedVec2Keyframes(entity.letter.transform.scale)
);
keyframes.push(...flattenAnimatedVec2Keyframes(entity.origin));
break;
default:
break;
}
return keyframes;
}
/**
* Set a value inside an object with its path: example: set({}, 'a.b.c', '...') => { a: { b: { c: '...' } } }
* If one of the keys in path doesn't exists in object, it'll be created.
*
* @param object Object to manipulate
* @param path Path to the object field that need to be created/updated
* @param value Value to set
*/
export function set(object: any, path: string, value: any) {
const decomposedPath = path.split(".");
const base = decomposedPath[0];
if (base === undefined) {
return object;
}
// assign an empty object in order to spread object
if (!object.hasOwnProperty(base)) {
object[base] = {};
}
// Determine if there is still layers to traverse
value =
decomposedPath.length <= 1
? value
: set(object[base], decomposedPath.slice(1).join("."), value);
return {
...object,
[base]: value,
};
}
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

1
app/src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="vite/client" />

Some files were not shown because too many files have changed in this diff Show More