commit
133a175a60
|
|
@ -1,15 +1,11 @@
|
|||
dist/
|
||||
.DS_Store
|
||||
bun.lockb
|
||||
yarn.lock
|
||||
|
||||
# Logs
|
||||
|
||||
logs
|
||||
_.log
|
||||
npm-debug.log_
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
|
|
@ -93,9 +89,7 @@ web_modules/
|
|||
|
||||
\*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variable files
|
||||
|
||||
|
|
@ -163,16 +157,7 @@ dist
|
|||
|
||||
.vscode-test
|
||||
|
||||
# yarn v2
|
||||
|
||||
.yarn/cache
|
||||
.yarn/unplugged
|
||||
.yarn/build-state.yml
|
||||
.yarn/install-state.gz
|
||||
.pnp.\*
|
||||
|
||||
.wrangler/
|
||||
.*.md
|
||||
|
||||
# Vercel
|
||||
.vercel/
|
||||
|
|
@ -192,3 +177,5 @@ dist
|
|||
|
||||
# Keep example file
|
||||
!.env.example
|
||||
|
||||
package-lock.json
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
legacy-peer-deps=true
|
||||
strict-peer-dependencies=false
|
||||
auto-install-peers=true
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"semi": false,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
import matter from "gray-matter";
|
||||
import { markdownToHtml } from "./markdownToHtml";
|
||||
import path from "path";
|
||||
|
||||
export const markdownPlugin = {
|
||||
name: "markdown-plugin",
|
||||
enforce: "pre",
|
||||
transform(code, id) {
|
||||
if (id.endsWith(".md")) {
|
||||
const { data, content } = matter(code);
|
||||
const filename = path.basename(id, ".md");
|
||||
const html = markdownToHtml(filename, content);
|
||||
return `export const html = ${JSON.stringify(html)};
|
||||
export const data = ${JSON.stringify(data)};`;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
import MarkdownIt from "markdown-it";
|
||||
// import markdownItLatex from "markdown-it-latex";
|
||||
import markdownLatex from "markdown-it-latex2img";
|
||||
|
||||
const md = new MarkdownIt({
|
||||
html: true,
|
||||
breaks: true,
|
||||
linkify: true,
|
||||
});
|
||||
|
||||
md.use(
|
||||
markdownLatex,
|
||||
// {style: "width: 200%; height: 200%;",}
|
||||
);
|
||||
|
||||
// const mediaSrc = (folderName, fileName) => {
|
||||
// return `/posts/${folderName}/${fileName}`;
|
||||
// };
|
||||
|
||||
md.renderer.rules.code_block = (tokens, idx, options, env, self) => {
|
||||
console.log("tokens", tokens);
|
||||
return `<code>${tokens[idx].content}</code>`;
|
||||
};
|
||||
md.renderer.rules.image = (tokens, idx, options, env, self) => {
|
||||
const token = tokens[idx];
|
||||
const src = token.attrGet("src");
|
||||
const alt = token.content;
|
||||
const postName = env.postName;
|
||||
const formattedSrc = `/posts/${postName}/${src}`;
|
||||
|
||||
if (src.endsWith(".mp4") || src.endsWith(".mov")) {
|
||||
return `<video controls loop>
|
||||
<source src="${formattedSrc}" type="video/mp4">
|
||||
</video>`;
|
||||
}
|
||||
|
||||
return `<img src="${formattedSrc}" alt="${alt}" />`;
|
||||
};
|
||||
|
||||
export function markdownToHtml(postName, content) {
|
||||
return md.render(content, { postName: postName });
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
{
|
||||
"folders": [
|
||||
{
|
||||
"path": "."
|
||||
},
|
||||
{
|
||||
"name": "jeffemmett.com",
|
||||
"path": "../jeffemmett.com"
|
||||
}
|
||||
],
|
||||
"settings": {}
|
||||
}
|
||||
|
|
@ -5,8 +5,6 @@
|
|||
<title>Jeff Emmett</title>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||||
<link rel="icon" type="image/x-icon" href="/favicon.ico?v=4" />
|
||||
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=4" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
|
|
|
|||
34
package.json
34
package.json
|
|
@ -4,19 +4,17 @@
|
|||
"description": "Jeff Emmett's personal website",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "concurrently --kill-others --names client,worker --prefix-colors blue,red \"yarn dev:client\" \"yarn dev:worker\"",
|
||||
"dev": "concurrently --kill-others --names client,worker --prefix-colors blue,red \"npm run dev:client\" \"npm run dev:worker\"",
|
||||
"dev:client": "vite --host --port 5173",
|
||||
"dev:worker": "wrangler dev --local --port 5172 --ip 0.0.0.0",
|
||||
"build": "tsc && vite build && wrangler deploy",
|
||||
"lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview",
|
||||
"deploy": "yarn build && vercel deploy --prod"
|
||||
"deploy": "tsc && vite build && vercel deploy --prod && wrangler deploy"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "Jeff Emmett",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@dimforge/rapier2d": "^0.11.2",
|
||||
"@tldraw/assets": "^3.6.0",
|
||||
"@tldraw/sync": "^3.6.0",
|
||||
"@tldraw/sync-core": "^3.6.0",
|
||||
|
|
@ -25,40 +23,26 @@
|
|||
"@types/markdown-it": "^14.1.1",
|
||||
"@vercel/analytics": "^1.2.2",
|
||||
"cloudflare-workers-unfurl": "^0.0.7",
|
||||
"crdts": "^0.2.0",
|
||||
"gray-matter": "^4.0.3",
|
||||
"itty-router": "^5.0.17",
|
||||
"lodash.throttle": "^4.1.1",
|
||||
"markdown-it": "^14.1.0",
|
||||
"markdown-it-latex2img": "^0.0.6",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-error-boundary": "^4.1.2",
|
||||
"react-router-dom": "^6.22.3",
|
||||
"react-router-dom": "^7.0.2",
|
||||
"tldraw": "^3.6.0",
|
||||
"use-local-storage-state": "^19.5.0",
|
||||
"vercel": "^39.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "1.4.1",
|
||||
"@cloudflare/types": "^6.0.0",
|
||||
"@cloudflare/workers-types": "^4.20240821.1",
|
||||
"@types/lodash.throttle": "^4",
|
||||
"@types/react": "^18.2.15",
|
||||
"@types/react-dom": "^18.2.7",
|
||||
"@typescript-eslint/eslint-plugin": "^5.59.0",
|
||||
"@typescript-eslint/parser": "^5.59.0",
|
||||
"@types/react": "^19.0.1",
|
||||
"@types/react-dom": "^19.0.1",
|
||||
"@vitejs/plugin-react": "^4.0.3",
|
||||
"@vitejs/plugin-react-swc": "^3.6.0",
|
||||
"concurrently": "^8.2.2",
|
||||
"eslint": "^8.38.0",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-react-refresh": "^0.3.4",
|
||||
"concurrently": "^9.1.0",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^5.3.3",
|
||||
"vite-plugin-static-copy": "^1.0.6",
|
||||
"vite-plugin-top-level-await": "^1.3.1",
|
||||
"vite-plugin-wasm": "^3.2.2",
|
||||
"vite": "^6.0.3",
|
||||
"wrangler": "^3.88.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
221
src/App.tsx
221
src/App.tsx
|
|
@ -1,158 +1,91 @@
|
|||
import { inject } from '@vercel/analytics';
|
||||
import "tldraw/tldraw.css";
|
||||
import { inject } from "@vercel/analytics"
|
||||
import "tldraw/tldraw.css"
|
||||
import "@/css/style.css"
|
||||
import { useEffect, useState } from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import { Default } from "@/components/Default";
|
||||
import { Canvas } from "@/components/Canvas";
|
||||
import { Toggle } from "@/components/Toggle";
|
||||
import { useCanvas } from "@/hooks/useCanvas"
|
||||
import { createShapes } from "@/utils/utils";
|
||||
import { BrowserRouter, Route, Routes } from 'react-router-dom';
|
||||
import { Contact } from "@/components/Contact";
|
||||
import { Post } from '@/components/Post';
|
||||
import { Board } from './components/Board';
|
||||
import { Inbox } from './components/Inbox';
|
||||
import { Books } from './components/Books';
|
||||
import {
|
||||
BindingUtil,
|
||||
Editor,
|
||||
IndexKey,
|
||||
TLBaseBinding,
|
||||
TLBaseShape,
|
||||
Tldraw,
|
||||
TLShapeId,
|
||||
} from 'tldraw';
|
||||
import { components, uiOverrides } from './ui-overrides';
|
||||
import { ChatBoxShape } from './shapes/ChatBoxShapeUtil';
|
||||
import { VideoChatShape } from './shapes/VideoChatShapeUtil';
|
||||
import { ChatBoxTool } from './tools/ChatBoxTool';
|
||||
import { VideoChatTool } from './tools/VideoChatTool';
|
||||
import { Default } from "@/routes/Default"
|
||||
import { BrowserRouter, Route, Routes } from "react-router-dom"
|
||||
import { Contact } from "@/routes/Contact"
|
||||
import { Board } from "./routes/Board"
|
||||
import { Inbox } from "./routes/Inbox"
|
||||
import { Editor, Tldraw, TLShapeId } from "tldraw"
|
||||
import { components, overrides } from "./ui-overrides"
|
||||
import { ChatBoxShape } from "./shapes/ChatBoxShapeUtil"
|
||||
import { VideoChatShape } from "./shapes/VideoChatShapeUtil"
|
||||
import { ChatBoxTool } from "./tools/ChatBoxTool"
|
||||
import { VideoChatTool } from "./tools/VideoChatTool"
|
||||
import { EmbedTool } from "./tools/EmbedTool"
|
||||
import { EmbedShape } from "./shapes/EmbedShapeUtil"
|
||||
import { createRoot } from "react-dom/client"
|
||||
|
||||
inject();
|
||||
inject()
|
||||
|
||||
// The container shapes that can contain element shapes
|
||||
const CONTAINER_PADDING = 24;
|
||||
const customShapeUtils = [ChatBoxShape, VideoChatShape, EmbedShape]
|
||||
const customTools = [ChatBoxTool, VideoChatTool, EmbedTool]
|
||||
|
||||
type ContainerShape = TLBaseShape<'element', { height: number; width: number }>;
|
||||
|
||||
// ... existing code for ContainerShapeUtil ...
|
||||
|
||||
// The element shapes that can be placed inside the container shapes
|
||||
type ElementShape = TLBaseShape<'element', { color: string }>;
|
||||
|
||||
// ... existing code for ElementShapeUtil ...
|
||||
|
||||
// The binding between the element shapes and the container shapes
|
||||
type LayoutBinding = TLBaseBinding<
|
||||
'layout',
|
||||
{
|
||||
index: IndexKey;
|
||||
placeholder: boolean;
|
||||
}
|
||||
>;
|
||||
|
||||
const customShapeUtils = [ChatBoxShape, VideoChatShape];
|
||||
const customTools = [ChatBoxTool, VideoChatTool];
|
||||
|
||||
// [2]
|
||||
export default function InteractiveShapeExample() {
|
||||
return (
|
||||
<div className="tldraw__editor">
|
||||
<Tldraw
|
||||
shapeUtils={customShapeUtils}
|
||||
tools={customTools}
|
||||
overrides={uiOverrides}
|
||||
components={components}
|
||||
onMount={(editor) => {
|
||||
handleInitialShapeLoad(editor);
|
||||
editor.createShape({ type: 'my-interactive-shape', x: 100, y: 100 });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className="tldraw__editor">
|
||||
<Tldraw
|
||||
shapeUtils={customShapeUtils}
|
||||
tools={customTools}
|
||||
overrides={overrides}
|
||||
components={components}
|
||||
onMount={(editor) => {
|
||||
handleInitialShapeLoad(editor)
|
||||
editor.createShape({ type: "my-interactive-shape", x: 100, y: 100 })
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Add this function before or after InteractiveShapeExample
|
||||
const handleInitialShapeLoad = (editor: Editor) => {
|
||||
const url = new URL(window.location.href);
|
||||
const shapeId = url.searchParams.get('shapeId') || url.searchParams.get('frameId');
|
||||
const x = url.searchParams.get('x');
|
||||
const y = url.searchParams.get('y');
|
||||
const zoom = url.searchParams.get('zoom');
|
||||
const url = new URL(window.location.href)
|
||||
const shapeId =
|
||||
url.searchParams.get("shapeId") || url.searchParams.get("frameId")
|
||||
const x = url.searchParams.get("x")
|
||||
const y = url.searchParams.get("y")
|
||||
const zoom = url.searchParams.get("zoom")
|
||||
|
||||
if (shapeId) {
|
||||
console.log('Found shapeId in URL:', shapeId);
|
||||
const shape = editor.getShape(shapeId as TLShapeId);
|
||||
if (shapeId) {
|
||||
console.log("Found shapeId in URL:", shapeId)
|
||||
const shape = editor.getShape(shapeId as TLShapeId)
|
||||
|
||||
if (shape) {
|
||||
console.log('Found shape:', shape);
|
||||
if (x && y && zoom) {
|
||||
console.log('Setting camera to:', { x, y, zoom });
|
||||
editor.setCamera({
|
||||
x: parseFloat(x),
|
||||
y: parseFloat(y),
|
||||
z: parseFloat(zoom)
|
||||
});
|
||||
} else {
|
||||
console.log('Zooming to shape bounds');
|
||||
editor.zoomToBounds(editor.getShapeGeometry(shape).bounds, {
|
||||
targetZoom: 1,
|
||||
//padding: 32
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.warn('Shape not found in the editor');
|
||||
}
|
||||
} else {
|
||||
console.warn('No shapeId found in the URL');
|
||||
}
|
||||
if (shape) {
|
||||
console.log("Found shape:", shape)
|
||||
if (x && y && zoom) {
|
||||
console.log("Setting camera to:", { x, y, zoom })
|
||||
editor.setCamera({
|
||||
x: parseFloat(x),
|
||||
y: parseFloat(y),
|
||||
z: parseFloat(zoom),
|
||||
})
|
||||
} else {
|
||||
console.log("Zooming to shape bounds")
|
||||
editor.zoomToBounds(editor.getShapeGeometry(shape).bounds, {
|
||||
targetZoom: 1,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
console.warn("Shape not found in the editor")
|
||||
}
|
||||
} else {
|
||||
console.warn("No shapeId found in the URL")
|
||||
}
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root")!).render(<App />);
|
||||
createRoot(document.getElementById("root")!).render(<App />)
|
||||
|
||||
function App() {
|
||||
|
||||
return (
|
||||
// <React.StrictMode>
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/card/contact" element={<Contact />} />
|
||||
<Route path="/posts/:slug" element={<Post />} />
|
||||
<Route path="/board/:slug" element={<Board />} />
|
||||
<Route path="/inbox" element={<Inbox />} />
|
||||
<Route path="/books" element={<Books />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
// </React.StrictMode>
|
||||
);
|
||||
};
|
||||
|
||||
function Home() {
|
||||
const { isCanvasEnabled, elementsInfo } = useCanvas();
|
||||
const shapes = createShapes(elementsInfo)
|
||||
const [isEditorMounted, setIsEditorMounted] = useState(false);
|
||||
|
||||
//console.log("THIS WORKS SO FAR")
|
||||
|
||||
useEffect(() => {
|
||||
const handleEditorDidMount = () => {
|
||||
setIsEditorMounted(true);
|
||||
};
|
||||
|
||||
window.addEventListener('editorDidMountEvent', handleEditorDidMount);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('editorDidMountEvent', handleEditorDidMount);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<><Toggle />
|
||||
<div style={{ zIndex: 999999 }} className={`${isCanvasEnabled && isEditorMounted ? 'transparent' : ''}`}>
|
||||
{<Default />}
|
||||
</div>
|
||||
{isCanvasEnabled && elementsInfo.length > 0 ? <Canvas shapes={shapes} /> : null}</>
|
||||
)
|
||||
}
|
||||
return (
|
||||
// <React.StrictMode>
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="/" element={<Default />} />
|
||||
<Route path="/contact" element={<Contact />} />
|
||||
<Route path="/board/:slug" element={<Board />} />
|
||||
<Route path="/inbox" element={<Inbox />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
// </React.StrictMode>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
49322
src/canvas01.ts
49322
src/canvas01.ts
File diff suppressed because it is too large
Load Diff
|
|
@ -1,37 +0,0 @@
|
|||
import { AssetRecordType, TLAsset, TLBookmarkAsset, getHashForString } from 'tldraw'
|
||||
|
||||
// How does our server handle bookmark unfurling?
|
||||
export async function getBookmarkPreview({ url }: { url: string }): Promise<TLAsset> {
|
||||
// we start with an empty asset record
|
||||
const asset: TLBookmarkAsset = {
|
||||
id: AssetRecordType.createId(getHashForString(url)),
|
||||
typeName: 'asset',
|
||||
type: 'bookmark',
|
||||
meta: {},
|
||||
props: {
|
||||
src: url,
|
||||
description: '',
|
||||
image: '',
|
||||
favicon: '',
|
||||
title: '',
|
||||
},
|
||||
}
|
||||
|
||||
try {
|
||||
// try to fetch the preview data from the server
|
||||
const response = await fetch(
|
||||
`${process.env.TLDRAW_WORKER_URL}/unfurl?url=${encodeURIComponent(url)}`
|
||||
)
|
||||
const data = await response.json() as {description: string, image: string, favicon: string, title: string}
|
||||
|
||||
// fill in our asset with whatever info we found
|
||||
asset.props.description = data?.description ?? ''
|
||||
asset.props.image = data?.image ?? ''
|
||||
asset.props.favicon = data?.favicon ?? ''
|
||||
asset.props.title = data?.title ?? ''
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
|
||||
return asset
|
||||
}
|
||||
|
|
@ -1,173 +0,0 @@
|
|||
import { useSync } from '@tldraw/sync'
|
||||
import { useMemo } from 'react'
|
||||
import {
|
||||
AssetRecordType,
|
||||
getHashForString,
|
||||
TLBookmarkAsset,
|
||||
TLRecord,
|
||||
Tldraw,
|
||||
Editor,
|
||||
TLFrameShape,
|
||||
TLUiEventSource,
|
||||
} from 'tldraw'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { ChatBoxTool } from '@/tools/ChatBoxTool'
|
||||
import { ChatBoxShape } from '@/shapes/ChatBoxShapeUtil'
|
||||
import { VideoChatTool } from '@/tools/VideoChatTool'
|
||||
import { VideoChatShape } from '@/shapes/VideoChatShapeUtil'
|
||||
import { multiplayerAssetStore } from '../client/multiplayerAssetStore'
|
||||
import { customSchema } from '../../worker/TldrawDurableObject'
|
||||
import { EmbedShape } from '@/shapes/EmbedShapeUtil'
|
||||
import { EmbedTool } from '@/tools/EmbedTool'
|
||||
import { defaultShapeUtils, defaultBindingUtils } from 'tldraw'
|
||||
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { ChatBox } from '@/shapes/ChatBoxShapeUtil';
|
||||
import { components, uiOverrides } from '@/ui-overrides'
|
||||
import { useCameraControls } from '@/hooks/useCameraControls'
|
||||
import { zoomToSelection } from '../ui-overrides'
|
||||
|
||||
// Default to production URL if env var isn't available
|
||||
export const WORKER_URL = 'https://jeffemmett-canvas.jeffemmett.workers.dev';
|
||||
|
||||
const shapeUtils = [ChatBoxShape, VideoChatShape, EmbedShape]
|
||||
const tools = [ChatBoxTool, VideoChatTool, EmbedTool]; // Array of tools
|
||||
|
||||
|
||||
export function Board() {
|
||||
const { slug } = useParams<{ slug: string }>();
|
||||
const roomId = slug || 'default-room';
|
||||
|
||||
const storeConfig = useMemo(() => ({
|
||||
uri: `${WORKER_URL}/connect/${roomId}`,
|
||||
assets: multiplayerAssetStore,
|
||||
shapeUtils: [...shapeUtils, ...defaultShapeUtils],
|
||||
bindingUtils: [...defaultBindingUtils],
|
||||
}), [roomId]);
|
||||
|
||||
const store = useSync(storeConfig);
|
||||
const [editor, setEditor] = useState<Editor | null>(null)
|
||||
const { zoomToFrame, copyFrameLink, copyLocationLink, revertCamera } = useCameraControls(editor)
|
||||
|
||||
return (
|
||||
<div style={{ position: 'fixed', inset: 0 }}>
|
||||
<Tldraw
|
||||
store={store.store}
|
||||
shapeUtils={shapeUtils}
|
||||
tools={tools}
|
||||
components={components}
|
||||
overrides={{
|
||||
tools: (editor, baseTools) => ({
|
||||
...baseTools,
|
||||
ChatBox: {
|
||||
id: 'ChatBox',
|
||||
icon: 'chat',
|
||||
label: 'Chat',
|
||||
kbd: 'c',
|
||||
readonlyOk: true,
|
||||
onSelect: () => {
|
||||
editor.setCurrentTool('ChatBox')
|
||||
},
|
||||
},
|
||||
VideoChat: {
|
||||
id: 'VideoChat',
|
||||
icon: 'video',
|
||||
label: 'Video Chat',
|
||||
kbd: 'v',
|
||||
readonlyOk: true,
|
||||
onSelect: () => {
|
||||
editor.setCurrentTool('VideoChat')
|
||||
},
|
||||
},
|
||||
Embed: {
|
||||
id: 'Embed',
|
||||
icon: 'embed',
|
||||
label: 'Embed',
|
||||
kbd: 'e',
|
||||
readonlyOk: true,
|
||||
onSelect: () => {
|
||||
editor.setCurrentTool('Embed')
|
||||
},
|
||||
},
|
||||
}),
|
||||
actions: (editor, actions) => ({
|
||||
...actions,
|
||||
'zoomToShape': {
|
||||
id: 'zoom-to-shape',
|
||||
label: 'Zoom to Selection',
|
||||
kbd: 'z',
|
||||
onSelect: () => {
|
||||
if (editor.getSelectedShapeIds().length > 0) {
|
||||
zoomToSelection(editor);
|
||||
editor.setCurrentTool('select');
|
||||
}
|
||||
},
|
||||
readonlyOk: true,
|
||||
},
|
||||
'copyLinkToCurrentView': {
|
||||
id: 'copy-link-to-current-view',
|
||||
label: 'Copy Link to Current View',
|
||||
kbd: 'c',
|
||||
onSelect: () => {
|
||||
const camera = editor.getCamera();
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('x', camera.x.toString());
|
||||
url.searchParams.set('y', camera.y.toString());
|
||||
url.searchParams.set('zoom', camera.z.toString());
|
||||
navigator.clipboard.writeText(url.toString());
|
||||
editor.setCurrentTool('select');
|
||||
},
|
||||
readonlyOk: true,
|
||||
},
|
||||
'revertCamera': {
|
||||
id: 'revert-camera',
|
||||
label: 'Revert Camera',
|
||||
kbd: 'b',
|
||||
onSelect: () => {
|
||||
revertCamera();
|
||||
editor.setCurrentTool('select');
|
||||
},
|
||||
readonlyOk: true,
|
||||
},
|
||||
}),
|
||||
}}
|
||||
onMount={(editor) => {
|
||||
setEditor(editor)
|
||||
editor.registerExternalAssetHandler('url', unfurlBookmarkUrl)
|
||||
editor.setCurrentTool('hand')
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// How does our server handle bookmark unfurling?
|
||||
async function unfurlBookmarkUrl({ url }: { url: string }): Promise<TLBookmarkAsset> {
|
||||
const asset: TLBookmarkAsset = {
|
||||
id: AssetRecordType.createId(getHashForString(url)),
|
||||
typeName: 'asset',
|
||||
type: 'bookmark',
|
||||
meta: {},
|
||||
props: {
|
||||
src: url,
|
||||
description: '',
|
||||
image: '',
|
||||
favicon: '',
|
||||
title: '',
|
||||
},
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${WORKER_URL}/unfurl?url=${encodeURIComponent(url)}`)
|
||||
const data = await response.json() as { description: string, image: string, favicon: string, title: string }
|
||||
|
||||
asset.props.description = data?.description ?? ''
|
||||
asset.props.image = data?.image ?? ''
|
||||
asset.props.favicon = data?.favicon ?? ''
|
||||
asset.props.title = data?.title ?? ''
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
|
||||
return asset
|
||||
}
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
|
||||
import { Editor, Tldraw } from "tldraw";
|
||||
import { canvas } from "@/canvas01";
|
||||
|
||||
export function Books() {
|
||||
return (
|
||||
<div className="tldraw__editor">
|
||||
<Tldraw
|
||||
onMount={(editor: Editor) => {
|
||||
editor.putContentOntoCurrentPage(canvas as any)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
import { Editor, Tldraw, TLShape, TLUiComponents } from "tldraw";
|
||||
import { SimController } from "@/physics/PhysicsControls";
|
||||
import { HTMLShapeUtil } from "@/utils/HTMLShapeUtil";
|
||||
|
||||
const components: TLUiComponents = {
|
||||
HelpMenu: null,
|
||||
StylePanel: null,
|
||||
PageMenu: null,
|
||||
NavigationPanel: null,
|
||||
DebugMenu: null,
|
||||
//ContextMenu: null,
|
||||
ActionsMenu: null,
|
||||
QuickActions: null,
|
||||
MainMenu: null,
|
||||
MenuPanel: null,
|
||||
}
|
||||
|
||||
export function Canvas({ shapes }: { shapes: TLShape[]; }) {
|
||||
|
||||
return (
|
||||
<div className="tldraw__editor">
|
||||
<Tldraw
|
||||
components={components}
|
||||
shapeUtils={[HTMLShapeUtil]}
|
||||
onMount={(_: Editor) => {
|
||||
window.dispatchEvent(new CustomEvent('editorDidMountEvent'));
|
||||
}}
|
||||
>
|
||||
<SimController shapes={shapes} />
|
||||
</Tldraw>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
export function Contact() {
|
||||
return (
|
||||
<main>
|
||||
<header>
|
||||
<a href="/">
|
||||
Jeff Emmett
|
||||
</a>
|
||||
</header>
|
||||
<h1>Contact</h1>
|
||||
<p>Twitter: <a href="https://twitter.com/jeffemmett">@jeffemmett</a></p>
|
||||
<p>BlueSky: <a href="https://bsky.app/profile/jeffemmett.bsky.social">@jeffemnmett.bsky.social</a></p>
|
||||
<p>Mastodon: <a href="https://social.coop/@jeffemmett">@jeffemmett@social.coop</a></p>
|
||||
<p>Email: <a href="mailto:jeffemmett@gmail.com">jeffemmett@gmail.com</a></p>
|
||||
<p>GitHub: <a href="https://github.com/Jeff-Emmett">Jeff-Emmett</a></p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,68 +0,0 @@
|
|||
export function Default() {
|
||||
return (
|
||||
<main>
|
||||
<header>
|
||||
Jeff Emmett
|
||||
</header>
|
||||
<h2>Hello! 👋🍄</h2>
|
||||
<p>
|
||||
My research investigates the intersection of mycelium and emancipatory technologies.
|
||||
I am interested in the potential of new convivial tooling as a medium for group
|
||||
consensus building and collective action, in order to empower communities of practice to address their own challenges.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
My current focus is basic research into the nature of digital
|
||||
organisation, developing prototype toolkits to improve shared
|
||||
infrastructure, and applying this research to the design of new
|
||||
systems and protocols which support the self-organisation of knowledge
|
||||
and emergent response to local needs.
|
||||
</p>
|
||||
|
||||
<h2>My work</h2>
|
||||
<p>
|
||||
Alongside my independent work, I am a researcher and engineering communicator at <a href="https://block.science/">Block Science</a>, an advisor to the Active Inference Lab, Commons Stack, and the Trusted Seed. I am also an occasional collaborator with <a href="https://economicspace.agency/">ECSA</a>.
|
||||
</p>
|
||||
|
||||
<h2>Get in touch</h2>
|
||||
<p>
|
||||
I am on Twitter <a href="https://twitter.com/jeffemmett">@jeffemmett</a>,
|
||||
Mastodon <a href="https://social.coop/@jeffemmett">@jeffemmett@social.coop</a> and GitHub <a href="https://github.com/Jeff-Emmett">@Jeff-Emmett</a>.
|
||||
</p>
|
||||
|
||||
<span className="dinkus">***</span>
|
||||
|
||||
<h2>Talks</h2>
|
||||
<ol reversed>
|
||||
<li><a
|
||||
href="https://www.teamhuman.fm/episodes/238-jeff-emmett">MycoPunk Futures on Team Human with Douglas Rushkoff</a> (<a href="artifact/tft-rocks-integration-domain.pdf">slides</a>)
|
||||
</li>
|
||||
<li><a
|
||||
href="https://www.youtube.com/watch?v=AFJFDajuCSg">Exploring MycoFi on the Greenpill Network with Kevin Owocki</a> (<a href="artifact/tft-rocks-integration-domain.pdf">slides</a>)
|
||||
</li>
|
||||
<li><a
|
||||
href="https://youtu.be/9ad2EJhMbZ8">Re-imagining Human Value on the Telos Podcast with Rieki & Brandonfrom SEEDS</a> (<a href="artifact/tft-rocks-integration-domain.pdf">slides</a>)
|
||||
</li>
|
||||
<li><a
|
||||
href="https://www.youtube.com/watch?v=i8qcg7FfpLM&t=1348s">Move Slow & Fix Things: Design Patterns from Nature</a> (<a href="artifact/tft-rocks-integration-domain.pdf">slides</a>)
|
||||
</li>
|
||||
<li><a
|
||||
href="https://podcasters.spotify.com/pod/show/theownershipeconomy/episodes/Episode-009---Localized-Democracy-and-Public-Goods-with-Token-Engineering--with-Jeff-Emmett-of-The-Commons-Stack--BlockScience-Labs-e1ggkqo">Localized Democracy and Public Goods with Token Engineering on the Ownership Economy</a> (<a href="artifact/tft-rocks-integration-domain.pdf">slides</a>)
|
||||
</li>
|
||||
<li><a
|
||||
href="https://youtu.be/kxcat-XBWas">A Discussion on Warm Data with Nora Bateson on Systems Innovation</a></li>
|
||||
</ol>
|
||||
<h2>Writing</h2>
|
||||
<ol reversed>
|
||||
<li><a
|
||||
href="https://www.mycofi.art">Exploring MycoFi: Mycelial Design Patterns for Web3 & Beyond</a></li>
|
||||
<li><a
|
||||
href="https://www.frontiersin.org/journals/blockchain/articles/10.3389/fbloc.2021.578721/full">Challenges & Approaches to Scaling the Global Commons</a></li>
|
||||
<li><a
|
||||
href="https://allthingsdecent.substack.com/p/mycoeconomics-and-permaculture-currencies">From Monoculture to Permaculture Currencies: A Glimpse of the Myco-Economic Future</a></li>
|
||||
<li><a
|
||||
href="https://medium.com/good-audience/rewriting-the-story-of-human-collaboration-c33a8a4cd5b8">Rewriting the Story of Human Collaboration</a></li>
|
||||
</ol>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,74 +0,0 @@
|
|||
import { createShapeId, Editor, Tldraw, TLGeoShape, TLShapePartial } from "tldraw";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
export function Inbox() {
|
||||
const editorRef = useRef<Editor | null>(null);
|
||||
|
||||
const updateEmails = async (editor: Editor) => {
|
||||
try {
|
||||
const response = await fetch('https://jeffemmett-canvas.web.val.run', {
|
||||
method: 'GET',
|
||||
});
|
||||
const messages = await response.json() as { id: string, from: string, subject: string, text: string }[];
|
||||
|
||||
for (let i = 0; i < messages.length; i++) {
|
||||
const message = messages[i];
|
||||
const messageId = message.id;
|
||||
const parsedEmailName = message.from.match(/^([^<]+)/)?.[1]?.trim() || message.from.match(/[^<@]+(?=@)/)?.[0] || message.from;
|
||||
const messageText = `from: ${parsedEmailName}\nsubject: ${message.subject}\n\n${message.text}`
|
||||
const shapeWidth = 500
|
||||
const shapeHeight = 300
|
||||
const spacing = 50
|
||||
const shape: TLShapePartial<TLGeoShape> = {
|
||||
id: createShapeId(),
|
||||
type: 'geo',
|
||||
x: shapeWidth * (i % 5) + spacing * (i % 5),
|
||||
y: shapeHeight * Math.floor(i / 5) + spacing * Math.floor(i / 5),
|
||||
props: {
|
||||
w: shapeWidth,
|
||||
h: shapeHeight,
|
||||
text: messageText,
|
||||
align:'start',
|
||||
verticalAlign:'start'
|
||||
},
|
||||
meta: {
|
||||
id: messageId
|
||||
}
|
||||
}
|
||||
let found = false;
|
||||
for (const s of editor.getCurrentPageShapes()) {
|
||||
if (s.meta.id === messageId) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
editor.createShape(shape)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching data:', error);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const intervalId = setInterval(() => {
|
||||
if (editorRef.current) {
|
||||
updateEmails(editorRef.current);
|
||||
}
|
||||
}, 5*1000);
|
||||
|
||||
return () => clearInterval(intervalId);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="tldraw__editor">
|
||||
<Tldraw
|
||||
onMount={(editor: Editor) => {
|
||||
editorRef.current = editor;
|
||||
updateEmails(editor);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
import { calcReadingTime } from '@/utils/readingTime';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
|
||||
export function Post() {
|
||||
const { slug } = useParams<{ slug: string }>();
|
||||
const [post, setPost] = useState<{ html: string, data: Record<string, any> } | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
import(`../posts/${slug}.md`)
|
||||
.then((module) => {
|
||||
setPost({ html: module.html, data: module.data });
|
||||
setIsLoading(false);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('Failed to load post:', error);
|
||||
setIsLoading(false);
|
||||
});
|
||||
}, [slug]);
|
||||
|
||||
|
||||
if (isLoading) {
|
||||
return <div className='loading'>hold on...</div>;
|
||||
}
|
||||
|
||||
if (!post) {
|
||||
return <div className='loading'>post not found :(</div>;
|
||||
}
|
||||
|
||||
document.title = post.data.title;
|
||||
|
||||
return (
|
||||
<main>
|
||||
<header>
|
||||
<a href="/" style={{ textDecoration: 'none' }}>Jeff Emmett</a>
|
||||
</header>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
|
||||
<h1>{post.data.title}</h1>
|
||||
<span style={{ opacity: '0.5' }}>{calcReadingTime(post.html)}</span>
|
||||
</div>
|
||||
<div dangerouslySetInnerHTML={{ __html: post.html }} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
export function Toggle() {
|
||||
return (
|
||||
<>
|
||||
<button id="toggle-canvas" onClick={() => window.dispatchEvent(new CustomEvent('toggleCanvasEvent'))}>
|
||||
<img src="/canvas-button.svg" alt="Toggle Canvas" />
|
||||
</button>
|
||||
<button id="toggle-physics" className="hidden" onClick={() => window.dispatchEvent(new CustomEvent('togglePhysicsEvent'))}>
|
||||
<img src="/gravity-button.svg" alt="Toggle Physics" />
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,129 +1,127 @@
|
|||
import { useEffect } from 'react';
|
||||
import { Editor, TLEventMap, TLFrameShape, TLParentId } from 'tldraw';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { useEffect } from "react"
|
||||
import { Editor, TLEventMap, TLFrameShape, TLParentId } from "tldraw"
|
||||
import { useSearchParams } from "react-router-dom"
|
||||
|
||||
// Define camera state interface
|
||||
interface CameraState {
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
x: number
|
||||
y: number
|
||||
z: number
|
||||
}
|
||||
|
||||
const MAX_HISTORY = 10;
|
||||
let cameraHistory: CameraState[] = [];
|
||||
const MAX_HISTORY = 10
|
||||
let cameraHistory: CameraState[] = []
|
||||
|
||||
// TODO: use this
|
||||
|
||||
// Improved camera change tracking with debouncing
|
||||
const trackCameraChange = (editor: Editor) => {
|
||||
const currentCamera = editor.getCamera();
|
||||
const lastPosition = cameraHistory[cameraHistory.length - 1];
|
||||
const currentCamera = editor.getCamera()
|
||||
const lastPosition = cameraHistory[cameraHistory.length - 1]
|
||||
|
||||
// Store any viewport change that's not from a revert operation
|
||||
if (!lastPosition ||
|
||||
currentCamera.x !== lastPosition.x ||
|
||||
currentCamera.y !== lastPosition.y ||
|
||||
currentCamera.z !== lastPosition.z) {
|
||||
cameraHistory.push({ ...currentCamera });
|
||||
if (cameraHistory.length > MAX_HISTORY) {
|
||||
cameraHistory.shift();
|
||||
}
|
||||
// Store any viewport change that's not from a revert operation
|
||||
if (
|
||||
!lastPosition ||
|
||||
currentCamera.x !== lastPosition.x ||
|
||||
currentCamera.y !== lastPosition.y ||
|
||||
currentCamera.z !== lastPosition.z
|
||||
) {
|
||||
cameraHistory.push({ ...currentCamera })
|
||||
if (cameraHistory.length > MAX_HISTORY) {
|
||||
cameraHistory.shift()
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function useCameraControls(editor: Editor | null) {
|
||||
const [searchParams] = useSearchParams();
|
||||
const [searchParams] = useSearchParams()
|
||||
|
||||
// Handle URL-based camera positioning
|
||||
useEffect(() => {
|
||||
if (!editor) return;
|
||||
// Handle URL-based camera positioning
|
||||
useEffect(() => {
|
||||
if (!editor) return
|
||||
|
||||
const frameId = searchParams.get('frameId');
|
||||
const x = searchParams.get('x');
|
||||
const y = searchParams.get('y');
|
||||
const zoom = searchParams.get('zoom');
|
||||
const frameId = searchParams.get("frameId")
|
||||
const x = searchParams.get("x")
|
||||
const y = searchParams.get("y")
|
||||
const zoom = searchParams.get("zoom")
|
||||
|
||||
if (x && y && zoom) {
|
||||
editor.setCamera({
|
||||
x: parseFloat(x),
|
||||
y: parseFloat(y),
|
||||
z: parseFloat(zoom)
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (x && y && zoom) {
|
||||
editor.setCamera({
|
||||
x: parseFloat(x),
|
||||
y: parseFloat(y),
|
||||
z: parseFloat(zoom),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (frameId) {
|
||||
const frame = editor.getShape(frameId as TLParentId) as TLFrameShape;
|
||||
if (!frame) {
|
||||
console.warn('Frame not found:', frameId);
|
||||
return;
|
||||
}
|
||||
if (frameId) {
|
||||
const frame = editor.getShape(frameId as TLParentId) as TLFrameShape
|
||||
if (!frame) {
|
||||
console.warn("Frame not found:", frameId)
|
||||
return
|
||||
}
|
||||
|
||||
// Use editor's built-in zoomToBounds with animation
|
||||
editor.zoomToBounds(
|
||||
editor.getShapePageBounds(frame)!,
|
||||
{
|
||||
inset: 32,
|
||||
animation: { duration: 500 }
|
||||
}
|
||||
);
|
||||
}
|
||||
}, [editor, searchParams]);
|
||||
// Use editor's built-in zoomToBounds with animation
|
||||
editor.zoomToBounds(editor.getShapePageBounds(frame)!, {
|
||||
inset: 32,
|
||||
animation: { duration: 500 },
|
||||
})
|
||||
}
|
||||
}, [editor, searchParams])
|
||||
|
||||
// Track camera changes
|
||||
useEffect(() => {
|
||||
if (!editor) return;
|
||||
// Track camera changes
|
||||
useEffect(() => {
|
||||
if (!editor) return
|
||||
|
||||
const handler = () => {
|
||||
trackCameraChange(editor);
|
||||
};
|
||||
const handler = () => {
|
||||
trackCameraChange(editor)
|
||||
}
|
||||
|
||||
// Track both viewport changes and user interaction end
|
||||
editor.on('viewportChange' as keyof TLEventMap, handler);
|
||||
editor.on('userChangeEnd' as keyof TLEventMap, handler);
|
||||
// Track both viewport changes and user interaction end
|
||||
editor.on("viewportChange" as keyof TLEventMap, handler)
|
||||
editor.on("userChangeEnd" as keyof TLEventMap, handler)
|
||||
|
||||
return () => {
|
||||
editor.off('viewportChange' as keyof TLEventMap, handler);
|
||||
editor.off('userChangeEnd' as keyof TLEventMap, handler);
|
||||
};
|
||||
}, [editor]);
|
||||
return () => {
|
||||
editor.off("viewportChange" as keyof TLEventMap, handler)
|
||||
editor.off("userChangeEnd" as keyof TLEventMap, handler)
|
||||
}
|
||||
}, [editor])
|
||||
|
||||
// Enhanced camera control functions
|
||||
return {
|
||||
zoomToFrame: (frameId: string) => {
|
||||
if (!editor) return;
|
||||
const frame = editor.getShape(frameId as TLParentId) as TLFrameShape;
|
||||
if (!frame) return;
|
||||
// Enhanced camera control functions
|
||||
return {
|
||||
zoomToFrame: (frameId: string) => {
|
||||
if (!editor) return
|
||||
const frame = editor.getShape(frameId as TLParentId) as TLFrameShape
|
||||
if (!frame) return
|
||||
|
||||
editor.zoomToBounds(
|
||||
editor.getShapePageBounds(frame)!,
|
||||
{
|
||||
inset: 32,
|
||||
animation: { duration: 500 }
|
||||
}
|
||||
);
|
||||
},
|
||||
editor.zoomToBounds(editor.getShapePageBounds(frame)!, {
|
||||
inset: 32,
|
||||
animation: { duration: 500 },
|
||||
})
|
||||
},
|
||||
|
||||
copyFrameLink: (frameId: string) => {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('frameId', frameId);
|
||||
navigator.clipboard.writeText(url.toString());
|
||||
},
|
||||
copyFrameLink: (frameId: string) => {
|
||||
const url = new URL(window.location.href)
|
||||
url.searchParams.set("frameId", frameId)
|
||||
navigator.clipboard.writeText(url.toString())
|
||||
},
|
||||
|
||||
copyLocationLink: () => {
|
||||
if (!editor) return;
|
||||
const camera = editor.getCamera();
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('x', camera.x.toString());
|
||||
url.searchParams.set('y', camera.y.toString());
|
||||
url.searchParams.set('zoom', camera.z.toString());
|
||||
navigator.clipboard.writeText(url.toString());
|
||||
},
|
||||
copyLocationLink: () => {
|
||||
if (!editor) return
|
||||
const camera = editor.getCamera()
|
||||
const url = new URL(window.location.href)
|
||||
url.searchParams.set("x", camera.x.toString())
|
||||
url.searchParams.set("y", camera.y.toString())
|
||||
url.searchParams.set("zoom", camera.z.toString())
|
||||
navigator.clipboard.writeText(url.toString())
|
||||
},
|
||||
|
||||
revertCamera: () => {
|
||||
if (!editor || cameraHistory.length === 0) return;
|
||||
const previousCamera = cameraHistory.pop();
|
||||
if (previousCamera) {
|
||||
editor.setCamera(previousCamera, { animation: { duration: 200 } });
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
revertCamera: () => {
|
||||
if (!editor || cameraHistory.length === 0) return
|
||||
const previousCamera = cameraHistory.pop()
|
||||
if (previousCamera) {
|
||||
editor.setCamera(previousCamera, { animation: { duration: 200 } })
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,98 +0,0 @@
|
|||
import { useState, useEffect } from 'react';
|
||||
|
||||
interface ElementInfo {
|
||||
tagName: string;
|
||||
x: number;
|
||||
y: number;
|
||||
w: number;
|
||||
h: number;
|
||||
html: string;
|
||||
}
|
||||
|
||||
export function useCanvas() {
|
||||
const [isCanvasEnabled, setIsCanvasEnabled] = useState(false);
|
||||
const [elementsInfo, setElementsInfo] = useState<ElementInfo[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const toggleCanvas = async () => {
|
||||
if (!isCanvasEnabled) {
|
||||
const info = await gatherElementsInfo();
|
||||
setElementsInfo(info);
|
||||
setIsCanvasEnabled(true);
|
||||
document.body.classList.add('canvas-mode');
|
||||
} else {
|
||||
setElementsInfo([]);
|
||||
setIsCanvasEnabled(false);
|
||||
document.body.classList.remove('canvas-mode');
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('toggleCanvasEvent', toggleCanvas);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('toggleCanvasEvent', toggleCanvas);
|
||||
};
|
||||
}, [isCanvasEnabled]);
|
||||
|
||||
return { isCanvasEnabled, elementsInfo };
|
||||
}
|
||||
|
||||
async function gatherElementsInfo() {
|
||||
const rootElement = document.getElementsByTagName('main')[0];
|
||||
const info: any[] = [];
|
||||
if (rootElement) {
|
||||
for (const child of rootElement.children) {
|
||||
if (['BUTTON'].includes(child.tagName)) continue;
|
||||
const rect = child.getBoundingClientRect();
|
||||
let w = rect.width;
|
||||
if (!['P', 'UL', 'OL'].includes(child.tagName)) {
|
||||
w = measureElementTextWidth(child as HTMLElement);
|
||||
}
|
||||
// Check if the element is centered
|
||||
const computedStyle = window.getComputedStyle(child);
|
||||
let x = rect.left; // Default x position
|
||||
if (computedStyle.display === 'block' && computedStyle.textAlign === 'center') {
|
||||
// Adjust x position for centered elements
|
||||
const parentWidth = child.parentElement ? child.parentElement.getBoundingClientRect().width : 0;
|
||||
x = (parentWidth - w) / 2 + window.scrollX + (child.parentElement ? child.parentElement.getBoundingClientRect().left : 0);
|
||||
}
|
||||
|
||||
info.push({
|
||||
tagName: child.tagName,
|
||||
x: x,
|
||||
y: rect.top,
|
||||
w: w,
|
||||
h: rect.height,
|
||||
html: child.outerHTML
|
||||
});
|
||||
};
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
function measureElementTextWidth(element: HTMLElement) {
|
||||
// Create a temporary span element
|
||||
const tempElement = document.createElement('span');
|
||||
// Get the text content from the passed element
|
||||
tempElement.textContent = element.textContent || element.innerText;
|
||||
// Get the computed style of the passed element
|
||||
const computedStyle = window.getComputedStyle(element);
|
||||
// Apply relevant styles to the temporary element
|
||||
tempElement.style.font = computedStyle.font;
|
||||
tempElement.style.fontWeight = computedStyle.fontWeight;
|
||||
tempElement.style.fontSize = computedStyle.fontSize;
|
||||
tempElement.style.fontFamily = computedStyle.fontFamily;
|
||||
tempElement.style.letterSpacing = computedStyle.letterSpacing;
|
||||
// Ensure the temporary element is not visible in the viewport
|
||||
tempElement.style.position = 'absolute';
|
||||
tempElement.style.visibility = 'hidden';
|
||||
tempElement.style.whiteSpace = 'nowrap'; // Prevent text from wrapping
|
||||
// Append to the body to make measurements possible
|
||||
document.body.appendChild(tempElement);
|
||||
// Measure the width
|
||||
const width = tempElement.getBoundingClientRect().width;
|
||||
// Remove the temporary element from the document
|
||||
document.body.removeChild(tempElement);
|
||||
// Return the measured width
|
||||
return width === 0 ? 10 : width;
|
||||
}
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
import { Editor, TLUnknownShape, createShapeId, useEditor } from "tldraw";
|
||||
import { useEffect, useState } from "react";
|
||||
import { usePhysicsSimulation } from "./simulation";
|
||||
|
||||
export const SimController = ({ shapes }: { shapes: TLUnknownShape[] }) => {
|
||||
const editor = useEditor();
|
||||
const [isPhysicsActive, setIsPhysicsActive] = useState(false);
|
||||
const { addShapes, destroy } = usePhysicsSimulation(editor);
|
||||
|
||||
useEffect(() => {
|
||||
editor.createShapes(shapes)
|
||||
return () => { editor.deleteShapes(editor.getCurrentPageShapes()) }
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const togglePhysics = () => {
|
||||
setIsPhysicsActive((currentIsPhysicsActive) => {
|
||||
if (currentIsPhysicsActive) {
|
||||
destroy();
|
||||
return false;
|
||||
}
|
||||
createFloor(editor);
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
// Listen for the togglePhysicsEvent to enable/disable physics simulation
|
||||
window.addEventListener('togglePhysicsEvent', togglePhysics);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('togglePhysicsEvent', togglePhysics);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (isPhysicsActive) {
|
||||
addShapes(editor.getCurrentPageShapes()); // Activate physics simulation
|
||||
} else {
|
||||
destroy(); // Deactivate physics simulation
|
||||
}
|
||||
}, [isPhysicsActive, addShapes, shapes]);
|
||||
|
||||
return (<></>);
|
||||
};
|
||||
|
||||
function createFloor(editor: Editor) {
|
||||
|
||||
const viewBounds = editor.getViewportPageBounds();
|
||||
|
||||
editor.createShape({
|
||||
id: createShapeId(),
|
||||
type: 'geo',
|
||||
x: viewBounds.minX,
|
||||
y: viewBounds.maxY,
|
||||
props: {
|
||||
w: viewBounds.width,
|
||||
h: 50,
|
||||
color: 'grey',
|
||||
fill: 'solid'
|
||||
},
|
||||
meta: {
|
||||
fixed: true
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
export const GRAVITY = { x: 0.0, y: 98 };
|
||||
export const DEFAULT_RESTITUTION = 0;
|
||||
export const DEFAULT_FRICTION = 0.1;
|
||||
|
||||
export function isRigidbody(color: string) {
|
||||
return !color || color === "black" ? false : true;
|
||||
}
|
||||
export function getGravityFromColor(color: string) {
|
||||
return color === 'grey' ? 0 : 1
|
||||
}
|
||||
export function getRestitutionFromColor(color: string) {
|
||||
return color === "orange" ? 0.9 : 0;
|
||||
}
|
||||
export function getFrictionFromColor(color: string) {
|
||||
return color === "blue" ? 0.1 : 0.8;
|
||||
}
|
||||
export const MATERIAL = {
|
||||
defaultRestitution: 0,
|
||||
defaultFriction: 0.1,
|
||||
};
|
||||
export const CHARACTER = {
|
||||
up: { x: 0.0, y: -1.0 },
|
||||
additionalMass: 20,
|
||||
maxSlopeClimbAngle: 1,
|
||||
slideEnabled: true,
|
||||
minSlopeSlideAngle: 0.9,
|
||||
applyImpulsesToDynamicBodies: true,
|
||||
autostepHeight: 5,
|
||||
autostepMaxClimbAngle: 1,
|
||||
snapToGroundDistance: 3,
|
||||
maxMoveSpeedX: 100,
|
||||
moveAcceleration: 600,
|
||||
moveDeceleration: 500,
|
||||
jumpVelocity: 300,
|
||||
gravityMultiplier: 10,
|
||||
};
|
||||
|
|
@ -1,95 +0,0 @@
|
|||
import { Geometry2d, Vec, VecLike } from "tldraw";
|
||||
|
||||
type ShapeTransform = {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
rotation: number;
|
||||
parent?: Geometry2d;
|
||||
}
|
||||
|
||||
// Define rotatePoint as a standalone function
|
||||
const rotatePoint = (cx: number, cy: number, x: number, y: number, angle: number) => {
|
||||
const cos = Math.cos(angle);
|
||||
const sin = Math.sin(angle);
|
||||
return {
|
||||
x: cos * (x - cx) - sin * (y - cy) + cx,
|
||||
y: sin * (x - cx) + cos * (y - cy) + cy,
|
||||
};
|
||||
}
|
||||
|
||||
export const cornerToCenter = ({
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
rotation,
|
||||
parent
|
||||
}: ShapeTransform): { x: number; y: number } => {
|
||||
const centerX = x + width / 2;
|
||||
const centerY = y + height / 2;
|
||||
const rotatedCenter = rotatePoint(x, y, centerX, centerY, rotation);
|
||||
|
||||
if (parent) {
|
||||
rotatedCenter.x -= parent.center.x;
|
||||
rotatedCenter.y -= parent.center.y;
|
||||
}
|
||||
|
||||
return rotatedCenter;
|
||||
}
|
||||
|
||||
export const centerToCorner = ({
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
rotation,
|
||||
}: ShapeTransform): { x: number; y: number } => {
|
||||
|
||||
const cornerX = x - width / 2;
|
||||
const cornerY = y - height / 2;
|
||||
|
||||
return rotatePoint(x, y, cornerX, cornerY, rotation);
|
||||
}
|
||||
|
||||
export const getDisplacement = (
|
||||
velocity: VecLike,
|
||||
acceleration: VecLike,
|
||||
timeStep: number,
|
||||
speedLimitX: number,
|
||||
decelerationX: number,
|
||||
): VecLike => {
|
||||
let newVelocityX =
|
||||
acceleration.x === 0 && velocity.x !== 0
|
||||
? Math.max(Math.abs(velocity.x) - decelerationX * timeStep, 0) *
|
||||
Math.sign(velocity.x)
|
||||
: velocity.x + acceleration.x * timeStep;
|
||||
|
||||
newVelocityX =
|
||||
Math.min(Math.abs(newVelocityX), speedLimitX) * Math.sign(newVelocityX);
|
||||
|
||||
const averageVelocityX = (velocity.x + newVelocityX) / 2;
|
||||
const x = averageVelocityX * timeStep;
|
||||
const y =
|
||||
velocity.y * timeStep + 0.5 * acceleration.y * timeStep ** 2;
|
||||
|
||||
return { x, y }
|
||||
}
|
||||
|
||||
export const convertVerticesToFloat32Array = (
|
||||
vertices: Vec[],
|
||||
width: number,
|
||||
height: number,
|
||||
) => {
|
||||
const vec2Array = new Float32Array(vertices.length * 2);
|
||||
const hX = width / 2;
|
||||
const hY = height / 2;
|
||||
|
||||
for (let i = 0; i < vertices.length; i++) {
|
||||
vec2Array[i * 2] = vertices[i].x - hX;
|
||||
vec2Array[i * 2 + 1] = vertices[i].y - hY;
|
||||
}
|
||||
|
||||
return vec2Array;
|
||||
}
|
||||
|
|
@ -1,398 +0,0 @@
|
|||
import RAPIER from "@dimforge/rapier2d";
|
||||
import { CHARACTER, GRAVITY, MATERIAL, getFrictionFromColor, getGravityFromColor, getRestitutionFromColor, isRigidbody } from "./config";
|
||||
import { Editor, Geometry2d, TLDrawShape, TLGeoShape, TLGroupShape, TLShape, TLShapeId, VecLike } from "tldraw";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { centerToCorner, convertVerticesToFloat32Array, cornerToCenter, getDisplacement } from "./math";
|
||||
|
||||
type BodyWithShapeData = RAPIER.RigidBody & {
|
||||
userData: { id: TLShapeId; type: TLShape["type"]; w: number; h: number };
|
||||
};
|
||||
type RigidbodyLookup = { [key: TLShapeId]: RAPIER.RigidBody };
|
||||
|
||||
export class PhysicsWorld {
|
||||
private editor: Editor;
|
||||
private world: RAPIER.World;
|
||||
private rigidbodyLookup: RigidbodyLookup;
|
||||
private animFrame = -1; // Store the animation frame id
|
||||
private character: {
|
||||
rigidbody: RAPIER.RigidBody | null;
|
||||
collider: RAPIER.Collider | null;
|
||||
};
|
||||
constructor(editor: Editor) {
|
||||
this.editor = editor
|
||||
this.world = new RAPIER.World(GRAVITY)
|
||||
this.rigidbodyLookup = {}
|
||||
this.character = { rigidbody: null, collider: null }
|
||||
}
|
||||
|
||||
public start() {
|
||||
this.world = new RAPIER.World(GRAVITY);
|
||||
|
||||
const simLoop = () => {
|
||||
this.world.step();
|
||||
this.updateCharacterControllers();
|
||||
this.updateRigidbodies();
|
||||
this.animFrame = requestAnimationFrame(simLoop);
|
||||
};
|
||||
simLoop();
|
||||
return () => cancelAnimationFrame(this.animFrame);
|
||||
};
|
||||
|
||||
public stop() {
|
||||
if (this.animFrame !== -1) {
|
||||
cancelAnimationFrame(this.animFrame);
|
||||
this.animFrame = -1;
|
||||
}
|
||||
}
|
||||
|
||||
public addShapes(shapes: TLShape[]) {
|
||||
for (const shape of shapes) {
|
||||
if ('color' in shape.props && shape.props.color === "violet") {
|
||||
this.createCharacter(shape as TLGeoShape);
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (shape.type) {
|
||||
case "html":
|
||||
case "geo":
|
||||
case "image":
|
||||
case "video":
|
||||
this.createShape(shape as TLGeoShape);
|
||||
break;
|
||||
case "draw":
|
||||
this.createCompoundLine(shape as TLDrawShape);
|
||||
break;
|
||||
case "group":
|
||||
this.createGroup(shape as TLGroupShape);
|
||||
break;
|
||||
// Add cases for any new shape types here
|
||||
case "VideoChat":
|
||||
this.createShape (shape as TLGeoShape);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
createShape(shape: TLGeoShape | TLDrawShape) {
|
||||
if (!shape.meta.fixed) {
|
||||
const rb = this.createRigidbody(shape, 1);
|
||||
this.createCollider(shape, rb);
|
||||
}
|
||||
else {
|
||||
this.createCollider(shape);
|
||||
}
|
||||
}
|
||||
|
||||
createCharacter(characterShape: TLGeoShape) {
|
||||
const initialPosition = cornerToCenter({
|
||||
x: characterShape.x,
|
||||
y: characterShape.y,
|
||||
width: characterShape.props.w,
|
||||
height: characterShape.props.h,
|
||||
rotation: characterShape.rotation,
|
||||
});
|
||||
const vertices = this.editor.getShapeGeometry(characterShape).vertices;
|
||||
const vec2Array = convertVerticesToFloat32Array(
|
||||
vertices,
|
||||
characterShape.props.w,
|
||||
characterShape.props.h,
|
||||
);
|
||||
const colliderDesc = RAPIER.ColliderDesc.convexHull(vec2Array);
|
||||
if (!colliderDesc) {
|
||||
console.error("Failed to create collider description.");
|
||||
return;
|
||||
}
|
||||
const rigidBodyDesc = RAPIER.RigidBodyDesc.kinematicPositionBased()
|
||||
.setTranslation(initialPosition.x, initialPosition.y)
|
||||
.setAdditionalMass(CHARACTER.additionalMass);
|
||||
const charRigidbody = this.world.createRigidBody(rigidBodyDesc);
|
||||
const charCollider = this.world.createCollider(colliderDesc, charRigidbody);
|
||||
const char = this.world.createCharacterController(0.1);
|
||||
char.setUp(CHARACTER.up);
|
||||
char.setMaxSlopeClimbAngle(CHARACTER.maxSlopeClimbAngle);
|
||||
char.setSlideEnabled(CHARACTER.slideEnabled);
|
||||
char.setMinSlopeSlideAngle(CHARACTER.minSlopeSlideAngle);
|
||||
char.setApplyImpulsesToDynamicBodies(CHARACTER.applyImpulsesToDynamicBodies);
|
||||
char.enableAutostep(
|
||||
CHARACTER.autostepHeight,
|
||||
CHARACTER.autostepMaxClimbAngle,
|
||||
true,
|
||||
);
|
||||
char.enableSnapToGround(CHARACTER.snapToGroundDistance);
|
||||
// Setup references so we can update character position in sim loop
|
||||
this.character.rigidbody = charRigidbody;
|
||||
this.character.collider = charCollider;
|
||||
charRigidbody.userData = {
|
||||
id: characterShape.id,
|
||||
type: characterShape.type,
|
||||
w: characterShape.props.w,
|
||||
h: characterShape.props.h,
|
||||
};
|
||||
}
|
||||
|
||||
createGroup(group: TLGroupShape) {
|
||||
// create rigidbody for group
|
||||
const rigidbody = this.createRigidbody(group);
|
||||
const rigidbodyGeometry = this.editor.getShapeGeometry(group);
|
||||
|
||||
this.editor.getSortedChildIdsForParent(group.id).forEach((childId) => {
|
||||
// create collider for each
|
||||
const child = this.editor.getShape(childId);
|
||||
if (!child) return;
|
||||
const isRb = "color" in child.props && isRigidbody(child?.props.color);
|
||||
if (isRb) {
|
||||
this.createCollider(child, rigidbody, rigidbodyGeometry);
|
||||
} else {
|
||||
this.createCollider(child);
|
||||
}
|
||||
});
|
||||
}
|
||||
createCompoundLine(drawShape: TLDrawShape) {
|
||||
const rigidbody = this.createRigidbody(drawShape);
|
||||
const drawnGeo = this.editor.getShapeGeometry(drawShape);
|
||||
const verts = drawnGeo.vertices;
|
||||
// const isRb =
|
||||
// "color" in drawShape.props && isRigidbody(drawShape.props.color);
|
||||
const isRb = true;
|
||||
verts.forEach((point) => {
|
||||
if (isRb) this.createColliderAtPoint(point, drawShape, rigidbody);
|
||||
else this.createColliderAtPoint(point, drawShape);
|
||||
});
|
||||
}
|
||||
|
||||
updateRigidbodies() {
|
||||
this.world.bodies.forEach((rb) => {
|
||||
if (rb === this.character?.rigidbody) return;
|
||||
if (!rb.userData) return;
|
||||
const body = rb as BodyWithShapeData;
|
||||
const position = body.translation();
|
||||
const rotation = body.rotation();
|
||||
|
||||
const cornerPos = centerToCorner({
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
width: body.userData?.w,
|
||||
height: body.userData?.h,
|
||||
rotation: rotation,
|
||||
});
|
||||
|
||||
this.editor.updateShape({
|
||||
id: body.userData?.id,
|
||||
type: body.userData?.type,
|
||||
rotation: rotation,
|
||||
x: cornerPos.x,
|
||||
y: cornerPos.y,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
updateCharacterControllers() {
|
||||
const right = this.editor.inputs.keys.has("ArrowRight") ? 1 : 0;
|
||||
const left = this.editor.inputs.keys.has("ArrowLeft") ? -1 : 0;
|
||||
const acceleration: VecLike = {
|
||||
x: (right + left) * CHARACTER.moveAcceleration,
|
||||
y: CHARACTER.gravityMultiplier * GRAVITY.y,
|
||||
}
|
||||
|
||||
this.world.characterControllers.forEach((char) => {
|
||||
if (!this.character.rigidbody || !this.character.collider) return;
|
||||
const charRigidbody = this.character.rigidbody as BodyWithShapeData;
|
||||
const charCollider = this.character.collider;
|
||||
const grounded = char.computedGrounded();
|
||||
const isJumping = this.editor.inputs.keys.has("ArrowUp") && grounded;
|
||||
const velocity: VecLike = {
|
||||
x: charRigidbody.linvel().x,
|
||||
y: isJumping ? -CHARACTER.jumpVelocity : charRigidbody.linvel().y,
|
||||
}
|
||||
const displacement = getDisplacement(
|
||||
velocity,
|
||||
acceleration,
|
||||
1 / 60,
|
||||
CHARACTER.maxMoveSpeedX,
|
||||
CHARACTER.moveDeceleration,
|
||||
);
|
||||
|
||||
char.computeColliderMovement(
|
||||
charCollider as RAPIER.Collider, // The collider we would like to move.
|
||||
new RAPIER.Vector2(displacement.x, displacement.y),
|
||||
);
|
||||
const correctedDisplacement = char.computedMovement();
|
||||
const currentPos = charRigidbody.translation();
|
||||
const nextX = currentPos.x + correctedDisplacement.x;
|
||||
const nextY = currentPos.y + correctedDisplacement.y;
|
||||
charRigidbody?.setNextKinematicTranslation({ x: nextX, y: nextY });
|
||||
|
||||
const w = charRigidbody.userData.w;
|
||||
const h = charRigidbody.userData.h;
|
||||
this.editor.updateShape({
|
||||
id: charRigidbody.userData.id,
|
||||
type: charRigidbody.userData.type,
|
||||
x: nextX - w / 2,
|
||||
y: nextY - h / 2,
|
||||
});
|
||||
});
|
||||
}
|
||||
private getShapeDimensions(
|
||||
shape: TLShape,
|
||||
): { width: number; height: number } {
|
||||
const geo = this.editor.getShapeGeometry(shape);
|
||||
const width = geo.center.x * 2;
|
||||
const height = geo.center.y * 2;
|
||||
return { width, height };
|
||||
}
|
||||
private shouldConvexify(shape: TLShape): boolean {
|
||||
return !(
|
||||
shape.type === "geo" && (shape as TLGeoShape).props.geo === "rectangle"
|
||||
);
|
||||
}
|
||||
private createRigidbody(
|
||||
shape: TLShape,
|
||||
gravity = 1,
|
||||
): RAPIER.RigidBody {
|
||||
const dimensions = this.getShapeDimensions(shape);
|
||||
const centerPosition = cornerToCenter({
|
||||
x: shape.x,
|
||||
y: shape.y,
|
||||
width: dimensions.width,
|
||||
height: dimensions.height,
|
||||
rotation: shape.rotation,
|
||||
});
|
||||
const rigidBodyDesc = RAPIER.RigidBodyDesc.dynamic()
|
||||
.setTranslation(centerPosition.x, centerPosition.y)
|
||||
.setRotation(shape.rotation)
|
||||
.setGravityScale(gravity);
|
||||
const rigidbody = this.world.createRigidBody(rigidBodyDesc);
|
||||
this.rigidbodyLookup[shape.id] = rigidbody;
|
||||
rigidbody.userData = {
|
||||
id: shape.id,
|
||||
type: shape.type,
|
||||
w: dimensions.width,
|
||||
h: dimensions.height,
|
||||
};
|
||||
return rigidbody;
|
||||
}
|
||||
private createColliderAtPoint(
|
||||
point: VecLike,
|
||||
relativeToParent: TLDrawShape,
|
||||
parentRigidBody: RAPIER.RigidBody | null = null,
|
||||
) {
|
||||
const radius = 5;
|
||||
const parentGeo = this.editor.getShapeGeometry(relativeToParent);
|
||||
const center = cornerToCenter({
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
width: radius,
|
||||
height: radius,
|
||||
rotation: 0,
|
||||
parent: parentGeo,
|
||||
});
|
||||
let colliderDesc: RAPIER.ColliderDesc | null = null;
|
||||
colliderDesc = RAPIER.ColliderDesc.ball(radius);
|
||||
|
||||
if (!colliderDesc) {
|
||||
console.error("Failed to create collider description.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (parentRigidBody) {
|
||||
colliderDesc.setTranslation(center.x, center.y);
|
||||
this.world.createCollider(colliderDesc, parentRigidBody);
|
||||
} else {
|
||||
colliderDesc.setTranslation(
|
||||
relativeToParent.x + center.x,
|
||||
relativeToParent.y + center.y,
|
||||
);
|
||||
this.world.createCollider(colliderDesc);
|
||||
}
|
||||
}
|
||||
private createCollider(
|
||||
shape: TLShape,
|
||||
parentRigidBody: RAPIER.RigidBody | null = null,
|
||||
parentGeo: Geometry2d | null = null,
|
||||
) {
|
||||
const dimensions = this.getShapeDimensions(shape);
|
||||
const centerPosition = cornerToCenter({
|
||||
x: shape.x,
|
||||
y: shape.y,
|
||||
width: dimensions.width,
|
||||
height: dimensions.height,
|
||||
rotation: shape.rotation,
|
||||
parent: parentGeo || undefined,
|
||||
});
|
||||
|
||||
const restitution =
|
||||
"color" in shape.props
|
||||
? getRestitutionFromColor(shape.props.color)
|
||||
: MATERIAL.defaultRestitution;
|
||||
const friction =
|
||||
"color" in shape.props
|
||||
? getFrictionFromColor(shape.props.color)
|
||||
: MATERIAL.defaultFriction;
|
||||
|
||||
let colliderDesc: RAPIER.ColliderDesc | null = null;
|
||||
|
||||
if (this.shouldConvexify(shape)) {
|
||||
// Convert vertices for convex shapes
|
||||
const vertices = this.editor.getShapeGeometry(shape).vertices;
|
||||
const vec2Array = convertVerticesToFloat32Array(
|
||||
vertices,
|
||||
dimensions.width,
|
||||
dimensions.height,
|
||||
);
|
||||
colliderDesc = RAPIER.ColliderDesc.convexHull(vec2Array);
|
||||
} else {
|
||||
// Cuboid for rectangle shapes
|
||||
colliderDesc = RAPIER.ColliderDesc.cuboid(
|
||||
dimensions.width / 2,
|
||||
dimensions.height / 2,
|
||||
);
|
||||
}
|
||||
if (!colliderDesc) {
|
||||
console.error("Failed to create collider description.");
|
||||
return;
|
||||
}
|
||||
|
||||
colliderDesc
|
||||
.setRestitution(restitution)
|
||||
.setRestitutionCombineRule(RAPIER.CoefficientCombineRule.Max)
|
||||
.setFriction(friction)
|
||||
.setFrictionCombineRule(RAPIER.CoefficientCombineRule.Min);
|
||||
if (parentRigidBody) {
|
||||
if (parentGeo) {
|
||||
colliderDesc.setTranslation(centerPosition.x, centerPosition.y);
|
||||
colliderDesc.setRotation(shape.rotation);
|
||||
}
|
||||
this.world.createCollider(colliderDesc, parentRigidBody);
|
||||
} else {
|
||||
colliderDesc
|
||||
.setTranslation(centerPosition.x, centerPosition.y)
|
||||
.setRotation(shape.rotation);
|
||||
this.world.createCollider(colliderDesc);
|
||||
}
|
||||
}
|
||||
public setEditor(editor: Editor) {
|
||||
this.editor = editor;
|
||||
}
|
||||
}
|
||||
|
||||
export function usePhysicsSimulation(editor: Editor) {
|
||||
const sim = useRef<PhysicsWorld>(new PhysicsWorld(editor));
|
||||
|
||||
useEffect(() => {
|
||||
sim.current.start()
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
sim.current.setEditor(editor);
|
||||
}, [editor, sim]);
|
||||
|
||||
// Return any values or functions that the UI components might need
|
||||
return {
|
||||
addShapes: (shapes: TLShape[]) => sim.current.addShapes(shapes),
|
||||
destroy: () => {
|
||||
sim.current.stop()
|
||||
sim.current = new PhysicsWorld(editor); // Replace with a new instance
|
||||
sim.current.start()
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -1,120 +0,0 @@
|
|||
---
|
||||
title: Conviction Voting
|
||||
---
|
||||
|
||||
> this research is a work-in-progress (play with the [live demo](https://orionreed.github.io/scoped-propagators/))
|
||||
|
||||
## Abstract
|
||||
|
||||
Watch Conviction Voting in action in a bipartite graph, with the left half representing voters and the right half representing proposals supported by those voters.
|
||||
<iframe width="560" height="315" src="https://www.youtube.com/embed/WDkk3ZXoTn0" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
|
||||
|
||||
|
||||
https://blog.giveth.io/conviction-voting-a-novel-continuous-decision-making-alternative-to-governance-aa746cfb9475
|
||||
|
||||
https://medium.com/commonsstack/announcing-the-conviction-voting-cadcad-model-release-8e907ce67e4e
|
||||
|
||||
https://github.com/1Hive/conviction-voting-cadcad
|
||||
|
||||
|
||||

|
||||
|
||||
## Introduction
|
||||
A scoped propagator is formed of a function which takes a *source* and *target* node and returns an partial update to the *target* node, and a scope which defines some subset of events which trigger propagation.
|
||||
|
||||
the Scoped Propagator model is based on two key insights:
|
||||
1. by representing computation as mappings between nodes along edges, you do not need to know at design-time what node types exist.
|
||||
2. by scoping the propagation to events, you can augment nodes with interactive behaviour suitable for the environment in which SPs have been embedded.
|
||||
|
||||
Below are the four event scopes which are currently implemented, which I have found to be appropriate and useful for an infinite canvas environment.
|
||||
|
||||
| Scope | Firing Condition |
|
||||
|----------|----------|
|
||||
| change (default) | Properties of the source node change |
|
||||
| click | A source node is clicked |
|
||||
| tick | A tick (frame render) event fires |
|
||||
| geo | A node changes whose bounds overlap the target |
|
||||
|
||||
The syntax for SPs in this implementation is a *scope* followed by a *JS object literal*:
|
||||
```
|
||||
scope { property1: value1, property2: value2 }
|
||||
```
|
||||
Each propagator is passed the *source* and *target* nodes (named "from" and "to" for brevity) which can be accessed like so:
|
||||
```
|
||||
click {x: from.x + 10, rotation: to.rotation + 1 }
|
||||
```
|
||||
The propagator above will, when the source is clicked, set the targets `x` value to be 10 units greater than the source, and increment the targets rotation. Here is an example of this basic idea:
|
||||
|
||||

|
||||
|
||||
## Demonstration
|
||||
|
||||
By passing the target as well as the source node, it makes it trivial to create toggles and counters. We can do this by creating an arrow from a node *to itself* and getting a value from either the source or target nodes (which are now the same).
|
||||
|
||||
Note that by allowing nodes from `self -> self` we do not have to worry about the layout of nodes, as the arrow will move wherever the node moves. This is in contrast to, for example, needing to move a button node alongside the node of interest, or have some suitable grouping primitive available.
|
||||
|
||||

|
||||
|
||||
This is already sufficient for many primitive constraint-based layouts, with the caveat that constraints do not, without the addition of a backwards propagator, work in both directions.
|
||||
|
||||

|
||||
|
||||
Being able to take a property from one node, transform it, and set the property of another node to that value, is useful not just for adding behaviour but also for debugging. Here we are formatting the full properties of one node and setting the text property of the target whenever the source updates.
|
||||
|
||||

|
||||
|
||||
If we wish to create dynamic behaviours as a function of time, we can use an appropriate scope such as `tick` and pass a readonly `deltaTime` value to these propagators. Which here we are using to implement a classic linear interpolation equation.
|
||||
|
||||
Note that, as with all of the examples, 100% of the behaviour is encoded in the text of the arrows. This creates a kind of diagrammatic specification of behaviour, where all behaviours could be re-created from a static screenshot.
|
||||
|
||||

|
||||
|
||||
While pure functions make reasoning about a system of SPs easier, we may in practice want to allow side effects. Here we have extended the syntax to support arbitrary Javascript:
|
||||
|
||||
```
|
||||
scope () {
|
||||
/* arbitrary JS can be executed in this function body */
|
||||
|
||||
// optional return:
|
||||
return { /* update */ }
|
||||
}
|
||||
```
|
||||
|
||||
This is useful if we want to, for example, create utilities or DIY tools out of existing nodes, such as this "paintbrush" which creates a new shape at the top-left corner whenever the brush is not overlapping with another shape.
|
||||
|
||||

|
||||
|
||||
Scoped Propagators are interesting in part because of their ability to cross the boundaries of otherwise siloed systems and to do so without the use of an escape hatch — all additional behaviour happens in-situ, in the same environment as the interface elements, not from editing source code.
|
||||
|
||||
Here is an example of a Petri Net (left box) which is being mapped to a chart primitive (right box). By merit of knowing some specifics of both systems, an author can create a mapping from one to the other without any explicit relationship existing prior to the creation of the propagator (here mapping the number of tokens in a box to the height of a rectangle in a chart)
|
||||
|
||||
>NOTE: the syntax here is slightly older and not consistent with the other examples.
|
||||
|
||||

|
||||
|
||||
Let's now combine some of these examples to create something less trivial. In this example, we have:
|
||||
- a joystick (constrained to a box)
|
||||
- fish movement controlled by the joystick, based on the red circles position relative to the center of the joystick box
|
||||
- a shark with a fish follow behaviour
|
||||
- an on/off toggle
|
||||
- a dead state, which resets the score, and swaps the fish image source to a dead fish
|
||||
- a score counter which increments over time for as long as the fish is alive
|
||||
|
||||
This small game consists of nine relatively terse arrows, propagating between nodes of different types. Propagators were also used to build the game, as it was unclear if or how I could change an image source URL until I used a propagator to inspect the internal state of the image and discovered the property to change.
|
||||
|
||||

|
||||
|
||||
## Prior Work
|
||||
Scoped Propagators are related to [Propagator Networks](https://dspace.mit.edu/handle/1721.1/54635) but differ in three key ways:
|
||||
- propagation happens along *edges* instead of *nodes*
|
||||
- propagation is only fired when to a scope condition is met.
|
||||
- instead of stateful *cell nodes* and *propagator nodes*, all nodes can be stateful and can be of an arbitrary type
|
||||
|
||||
This is also not the first application of propagators to infinite canvas environments, [Dennis Hansen](https://x.com/dennizor/status/1793389346881417323) built [Holograph](https://www.holograph.so), an implementation of propagator networks in [tldraw](https://tldraw.com), and motivated the use of the term "propagator" in this model.
|
||||
|
||||
## Open Questions
|
||||
Many questions about this model have yet to be answered including questions of *function reuse*, modeling of *side-effects*, handling of *multi-input-multi-output* propagation (which is trivial in traditional propagator networks), and applications to other domains such as graph-databases.
|
||||
|
||||
This model has not yet been formalised, and while the propagators themselves can be simply expressed as a function $f(a,b) \mapsto b'$, I have not yet found an appropriate way to express *scopes* and the relationship between the two.
|
||||
|
||||
These questions, along with formalisation of the model and an examination of real-world usage is left to future work.
|
||||
|
|
@ -1,112 +0,0 @@
|
|||
---
|
||||
title: Scoped Propagators
|
||||
---
|
||||
|
||||
> this research is a work-in-progress (play with the [live demo](https://orionreed.github.io/scoped-propagators/))
|
||||
|
||||
## Abstract
|
||||
Graphs, as a model of computation and as a means of interaction and authorship, have found success in specific domains such as shader programming and signal processing. In these systems, computation is often expressed on nodes of specific types, with edges representing the flow of information. This is a powerful and general-purpose model, but is typically a closed-world environment where both node and edge types are decided at design-time. By choosing an alternate topology where computation is represented by edges, the incentive for a closed environment is reduced.
|
||||
|
||||
I present *Scoped Propagators (SPs)*, a programming model designed to be embedded within existing environments and user interfaces. By representing computation as mappings between nodes along edges, SPs make it possible to add behaviour and interactivity to environments which were not designed with liveness in mind. I demonstrate an implementation of the SP model in an infinite canvas environment, where users can create arrows between arbitrary shapes and define SPs as Javascript object literals on these arrows.
|
||||
|
||||

|
||||
|
||||
## Introduction
|
||||
A scoped propagator is formed of a function which takes a *source* and *target* node and returns an partial update to the *target* node, and a scope which defines some subset of events which trigger propagation.
|
||||
|
||||
the Scoped Propagator model is based on two key insights:
|
||||
1. by representing computation as mappings between nodes along edges, you do not need to know at design-time what node types exist.
|
||||
2. by scoping the propagation to events, you can augment nodes with interactive behaviour suitable for the environment in which SPs have been embedded.
|
||||
|
||||
Below are the four event scopes which are currently implemented, which I have found to be appropriate and useful for an infinite canvas environment.
|
||||
|
||||
| Scope | Firing Condition |
|
||||
|----------|----------|
|
||||
| change (default) | Properties of the source node change |
|
||||
| click | A source node is clicked |
|
||||
| tick | A tick (frame render) event fires |
|
||||
| geo | A node changes whose bounds overlap the target |
|
||||
|
||||
The syntax for SPs in this implementation is a *scope* followed by a *JS object literal*:
|
||||
```
|
||||
scope { property1: value1, property2: value2 }
|
||||
```
|
||||
Each propagator is passed the *source* and *target* nodes (named "from" and "to" for brevity) which can be accessed like so:
|
||||
```
|
||||
click {x: from.x + 10, rotation: to.rotation + 1 }
|
||||
```
|
||||
The propagator above will, when the source is clicked, set the targets `x` value to be 10 units greater than the source, and increment the targets rotation. Here is an example of this basic idea:
|
||||
|
||||

|
||||
|
||||
## Demonstration
|
||||
|
||||
By passing the target as well as the source node, it makes it trivial to create toggles and counters. We can do this by creating an arrow from a node *to itself* and getting a value from either the source or target nodes (which are now the same).
|
||||
|
||||
Note that by allowing nodes from `self -> self` we do not have to worry about the layout of nodes, as the arrow will move wherever the node moves. This is in contrast to, for example, needing to move a button node alongside the node of interest, or have some suitable grouping primitive available.
|
||||
|
||||

|
||||
|
||||
This is already sufficient for many primitive constraint-based layouts, with the caveat that constraints do not, without the addition of a backwards propagator, work in both directions.
|
||||
|
||||

|
||||
|
||||
Being able to take a property from one node, transform it, and set the property of another node to that value, is useful not just for adding behaviour but also for debugging. Here we are formatting the full properties of one node and setting the text property of the target whenever the source updates.
|
||||
|
||||

|
||||
|
||||
If we wish to create dynamic behaviours as a function of time, we can use an appropriate scope such as `tick` and pass a readonly `deltaTime` value to these propagators. Which here we are using to implement a classic linear interpolation equation.
|
||||
|
||||
Note that, as with all of the examples, 100% of the behaviour is encoded in the text of the arrows. This creates a kind of diagrammatic specification of behaviour, where all behaviours could be re-created from a static screenshot.
|
||||
|
||||

|
||||
|
||||
While pure functions make reasoning about a system of SPs easier, we may in practice want to allow side effects. Here we have extended the syntax to support arbitrary Javascript:
|
||||
|
||||
```
|
||||
scope () {
|
||||
/* arbitrary JS can be executed in this function body */
|
||||
|
||||
// optional return:
|
||||
return { /* update */ }
|
||||
}
|
||||
```
|
||||
|
||||
This is useful if we want to, for example, create utilities or DIY tools out of existing nodes, such as this "paintbrush" which creates a new shape at the top-left corner whenever the brush is not overlapping with another shape.
|
||||
|
||||

|
||||
|
||||
Scoped Propagators are interesting in part because of their ability to cross the boundaries of otherwise siloed systems and to do so without the use of an escape hatch — all additional behaviour happens in-situ, in the same environment as the interface elements, not from editing source code.
|
||||
|
||||
Here is an example of a Petri Net (left box) which is being mapped to a chart primitive (right box). By merit of knowing some specifics of both systems, an author can create a mapping from one to the other without any explicit relationship existing prior to the creation of the propagator (here mapping the number of tokens in a box to the height of a rectangle in a chart)
|
||||
|
||||
>NOTE: the syntax here is slightly older and not consistent with the other examples.
|
||||
|
||||

|
||||
|
||||
Let's now combine some of these examples to create something less trivial. In this example, we have:
|
||||
- a joystick (constrained to a box)
|
||||
- fish movement controlled by the joystick, based on the red circles position relative to the center of the joystick box
|
||||
- a shark with a fish follow behaviour
|
||||
- an on/off toggle
|
||||
- a dead state, which resets the score, and swaps the fish image source to a dead fish
|
||||
- a score counter which increments over time for as long as the fish is alive
|
||||
|
||||
This small game consists of nine relatively terse arrows, propagating between nodes of different types. Propagators were also used to build the game, as it was unclear if or how I could change an image source URL until I used a propagator to inspect the internal state of the image and discovered the property to change.
|
||||
|
||||

|
||||
|
||||
## Prior Work
|
||||
Scoped Propagators are related to [Propagator Networks](https://dspace.mit.edu/handle/1721.1/54635) but differ in three key ways:
|
||||
- propagation happens along *edges* instead of *nodes*
|
||||
- propagation is only fired when to a scope condition is met.
|
||||
- instead of stateful *cell nodes* and *propagator nodes*, all nodes can be stateful and can be of an arbitrary type
|
||||
|
||||
This is also not the first application of propagators to infinite canvas environments, [Dennis Hansen](https://x.com/dennizor/status/1793389346881417323) built [Holograph](https://www.holograph.so), an implementation of propagator networks in [tldraw](https://tldraw.com), and motivated the use of the term "propagator" in this model.
|
||||
|
||||
## Open Questions
|
||||
Many questions about this model have yet to be answered including questions of *function reuse*, modeling of *side-effects*, handling of *multi-input-multi-output* propagation (which is trivial in traditional propagator networks), and applications to other domains such as graph-databases.
|
||||
|
||||
This model has not yet been formalised, and while the propagators themselves can be simply expressed as a function $f(a,b) \mapsto b'$, I have not yet found an appropriate way to express *scopes* and the relationship between the two.
|
||||
|
||||
These questions, along with formalisation of the model and an examination of real-world usage is left to future work.
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:c8a5fea015bcf937fbce5b0a233067e31059fb2e4d0f32f6471395fb82c6407c
|
||||
size 1708542
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:8763ad95ef6e31e4c66f9298d0ad22296edd83ab2fd6d7aa1549c8845521c932
|
||||
size 61302
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:fbc1493d124f92abe9c35534b4b6dca4a8081c570f4e3f07c4d9559d60dea3eb
|
||||
size 87493
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:55e5c2ce64c027a808951ad11f8757f3a8d7d739639a72517a4b39c35aad815d
|
||||
size 21393177
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:0c27fbc53fb819ffc3f83a52a939c52bc5f92788e5212a602c31f94ff0f108d8
|
||||
size 386809
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:2f50fe4800e2a5957e0b96aa18121ea3dc40f514162914e9f771497e4cc54d1f
|
||||
size 224988
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:29771060ae2ddb4c8056b4a68e24da75066e96b0a9264ab5577efba66de34379
|
||||
size 131411
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:3725438bab72654d31e56303f4694cb481da03ed52668a3235c0510769e43ef2
|
||||
size 213429
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:6c4030b83ec1ae36a9475a1165dc791f8d651da70cae91c1ab90c50a54d5bbd3
|
||||
size 127229
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:c8140e8b76c29fa3c828553e8a6a87651af6e7ee18d1ccb82e79125eb532194b
|
||||
size 19738445
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:d63dd9f37a74b85680a7c1df823f69936619ecab5e8d4d06eeeedea4d908f1de
|
||||
size 18268955
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Generated by Pixelmator Pro 3.5.7 -->
|
||||
<svg width="293" height="293" viewBox="0 0 293 293" xmlns="http://www.w3.org/2000/svg">
|
||||
<path id="canvas-button" fill="none" stroke="#000000" stroke-width="22" stroke-linecap="round" stroke-linejoin="round" d="M 72.367233 280.871094 C 50.196026 280.871094 39.109756 280.870453 30.79781 276.215546 C 24.923391 272.92572 20.074295 268.07663 16.784464 262.202179 C 12.129553 253.890228 12.128906 242.80397 12.128906 220.632767 L 12.128906 195.152313 L 24.139235 195.152313 L 24.139235 229.431793 C 24.139235 243.943832 24.139042 251.199875 27.185894 256.640411 C 29.339237 260.485474 32.514515 263.660767 36.359585 265.814117 C 41.800129 268.860962 49.056156 268.860779 63.568214 268.860779 L 97.847694 268.860779 L 97.847694 280.871094 L 72.367233 280.871094 Z M 195.276031 280.871094 L 195.276031 268.860779 L 229.560684 268.860779 C 244.072723 268.860779 251.328766 268.860962 256.769318 265.814117 C 260.61441 263.660767 263.789673 260.485474 265.943024 256.640411 C 268.989868 251.199875 268.989685 243.943832 268.989685 229.431793 L 268.989685 195.152313 L 281 195.152313 L 281 220.632767 C 281 242.80397 280.999359 253.890228 276.344452 262.202179 C 273.054626 268.07663 268.205536 272.92572 262.331085 276.215546 C 254.019119 280.870453 242.932877 280.871094 220.761673 280.871094 L 195.276031 280.871094 Z M 12.128906 97.723969 L 12.128906 72.238327 C 12.128906 50.067123 12.129553 38.980881 16.784464 30.668915 C 20.074295 24.794464 24.923391 19.945404 30.79781 16.655548 C 39.109756 12.000641 50.196026 12 72.367233 12 L 97.847694 12 L 97.847694 24.010315 L 63.568214 24.010315 C 49.056156 24.010315 41.800129 24.010132 36.359585 27.056976 C 32.514519 29.210327 29.339237 32.38562 27.185894 36.230682 C 24.139044 41.671234 24.139235 48.927277 24.139235 63.439316 L 24.139235 97.723969 L 12.128906 97.723969 Z M 268.989685 97.723969 L 268.989685 63.439316 C 268.989685 48.927277 268.989868 41.671234 265.943024 36.230682 C 263.789673 32.38559 260.61438 29.210327 256.769318 27.056976 C 251.328766 24.010132 244.072723 24.010315 229.560684 24.010315 L 195.276031 24.010315 L 195.276031 12 L 220.761673 12 C 242.932877 12 254.019119 12.000641 262.331085 16.655548 C 268.205536 19.945374 273.054596 24.794464 276.344452 30.668915 C 280.999359 38.980881 281 50.067123 281 72.238327 L 281 97.723969 L 268.989685 97.723969 Z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.4 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 84 KiB |
|
|
@ -1,8 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Generated by Pixelmator Pro 3.5.7 -->
|
||||
<svg width="247" height="450" viewBox="0 0 247 450" xmlns="http://www.w3.org/2000/svg">
|
||||
<g id="gravity-button">
|
||||
<path id="secondary" fill="none" stroke="#000000" stroke-width="30" stroke-linecap="round" stroke-linejoin="round" d="M 123.166664 32.750031 L 123.166664 169.500031 M 214.333313 65.541687 L 214.333313 202.291687 M 32 65.541687 L 32 202.291687"/>
|
||||
<path id="primary" fill="none" stroke="#000000" stroke-width="30" stroke-linecap="round" stroke-linejoin="round" d="M 214.333313 341.833344 C 214.333313 392.183289 173.516632 433 123.166664 433 C 72.816711 433 32 392.183289 32 341.833344 C 32 291.483398 72.816711 250.666687 123.166664 250.666687 C 173.516632 250.666687 214.333313 291.483398 214.333313 341.833344 Z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 846 B |
|
|
@ -1,3 +0,0 @@
|
|||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:4b55a408375712bc169bc5c987d85c71c353028e611f216817f13ca0fb284604
|
||||
size 28423
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
import { useSync } from "@tldraw/sync"
|
||||
import { useMemo } from "react"
|
||||
import {
|
||||
AssetRecordType,
|
||||
getHashForString,
|
||||
TLBookmarkAsset,
|
||||
Tldraw,
|
||||
Editor,
|
||||
} from "tldraw"
|
||||
import { useParams } from "react-router-dom"
|
||||
import { ChatBoxTool } from "@/tools/ChatBoxTool"
|
||||
import { ChatBoxShape } from "@/shapes/ChatBoxShapeUtil"
|
||||
import { VideoChatTool } from "@/tools/VideoChatTool"
|
||||
import { VideoChatShape } from "@/shapes/VideoChatShapeUtil"
|
||||
import { multiplayerAssetStore } from "../utils/multiplayerAssetStore"
|
||||
import { EmbedShape } from "@/shapes/EmbedShapeUtil"
|
||||
import { EmbedTool } from "@/tools/EmbedTool"
|
||||
import { defaultShapeUtils, defaultBindingUtils } from "tldraw"
|
||||
import { useState } from "react"
|
||||
import { components, overrides } from "@/ui-overrides"
|
||||
|
||||
// Default to production URL if env var isn't available
|
||||
export const WORKER_URL = "https://jeffemmett-canvas.jeffemmett.workers.dev"
|
||||
|
||||
const shapeUtils = [ChatBoxShape, VideoChatShape, EmbedShape]
|
||||
const tools = [ChatBoxTool, VideoChatTool, EmbedTool] // Array of tools
|
||||
|
||||
export function Board() {
|
||||
const { slug } = useParams<{ slug: string }>()
|
||||
const roomId = slug || "default-room"
|
||||
|
||||
const storeConfig = useMemo(
|
||||
() => ({
|
||||
uri: `${WORKER_URL}/connect/${roomId}`,
|
||||
assets: multiplayerAssetStore,
|
||||
shapeUtils: [...shapeUtils, ...defaultShapeUtils],
|
||||
bindingUtils: [...defaultBindingUtils],
|
||||
}),
|
||||
[roomId],
|
||||
)
|
||||
|
||||
const store = useSync(storeConfig)
|
||||
const [editor, setEditor] = useState<Editor | null>(null)
|
||||
|
||||
return (
|
||||
<div style={{ position: "fixed", inset: 0 }}>
|
||||
<Tldraw
|
||||
store={store.store}
|
||||
shapeUtils={shapeUtils}
|
||||
tools={tools}
|
||||
components={components}
|
||||
overrides={overrides}
|
||||
onMount={(editor) => {
|
||||
setEditor(editor)
|
||||
editor.registerExternalAssetHandler("url", unfurlBookmarkUrl)
|
||||
editor.setCurrentTool("hand")
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// How does our server handle bookmark unfurling?
|
||||
async function unfurlBookmarkUrl({
|
||||
url,
|
||||
}: {
|
||||
url: string
|
||||
}): Promise<TLBookmarkAsset> {
|
||||
const asset: TLBookmarkAsset = {
|
||||
id: AssetRecordType.createId(getHashForString(url)),
|
||||
typeName: "asset",
|
||||
type: "bookmark",
|
||||
meta: {},
|
||||
props: {
|
||||
src: url,
|
||||
description: "",
|
||||
image: "",
|
||||
favicon: "",
|
||||
title: "",
|
||||
},
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${WORKER_URL}/unfurl?url=${encodeURIComponent(url)}`,
|
||||
)
|
||||
const data = (await response.json()) as {
|
||||
description: string
|
||||
image: string
|
||||
favicon: string
|
||||
title: string
|
||||
}
|
||||
|
||||
asset.props.description = data?.description ?? ""
|
||||
asset.props.image = data?.image ?? ""
|
||||
asset.props.favicon = data?.favicon ?? ""
|
||||
asset.props.title = data?.title ?? ""
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
|
||||
return asset
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
export function Contact() {
|
||||
return (
|
||||
<main>
|
||||
<header>
|
||||
<a href="/">Jeff Emmett</a>
|
||||
</header>
|
||||
<h1>Contact</h1>
|
||||
<p>
|
||||
Twitter: <a href="https://twitter.com/jeffemmett">@jeffemmett</a>
|
||||
</p>
|
||||
<p>
|
||||
BlueSky:{" "}
|
||||
<a href="https://bsky.app/profile/jeffemmett.bsky.social">
|
||||
@jeffemnmett.bsky.social
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Mastodon:{" "}
|
||||
<a href="https://social.coop/@jeffemmett">@jeffemmett@social.coop</a>
|
||||
</p>
|
||||
<p>
|
||||
Email: <a href="mailto:jeffemmett@gmail.com">jeffemmett@gmail.com</a>
|
||||
</p>
|
||||
<p>
|
||||
GitHub: <a href="https://github.com/Jeff-Emmett">Jeff-Emmett</a>
|
||||
</p>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
export function Default() {
|
||||
return (
|
||||
<main>
|
||||
<header>Jeff Emmett</header>
|
||||
<h2>Hello! 👋🍄</h2>
|
||||
<p>
|
||||
My research investigates the intersection of mycelium and emancipatory
|
||||
technologies. I am interested in the potential of new convivial tooling
|
||||
as a medium for group consensus building and collective action, in order
|
||||
to empower communities of practice to address their own challenges.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
My current focus is basic research into the nature of digital
|
||||
organisation, developing prototype toolkits to improve shared
|
||||
infrastructure, and applying this research to the design of new systems
|
||||
and protocols which support the self-organisation of knowledge and
|
||||
emergent response to local needs.
|
||||
</p>
|
||||
|
||||
<h2>My work</h2>
|
||||
<p>
|
||||
Alongside my independent work, I am a researcher and engineering
|
||||
communicator at <a href="https://block.science/">Block Science</a>, an
|
||||
advisor to the Active Inference Lab, Commons Stack, and the Trusted
|
||||
Seed. I am also an occasional collaborator with{" "}
|
||||
<a href="https://economicspace.agency/">ECSA</a>.
|
||||
</p>
|
||||
|
||||
<h2>Get in touch</h2>
|
||||
<p>
|
||||
I am on Twitter <a href="https://twitter.com/jeffemmett">@jeffemmett</a>
|
||||
, Mastodon{" "}
|
||||
<a href="https://social.coop/@jeffemmett">@jeffemmett@social.coop</a>{" "}
|
||||
and GitHub <a href="https://github.com/Jeff-Emmett">@Jeff-Emmett</a>.
|
||||
</p>
|
||||
|
||||
<span className="dinkus">***</span>
|
||||
|
||||
<h2>Talks</h2>
|
||||
<ol reversed>
|
||||
<li>
|
||||
<a href="https://www.teamhuman.fm/episodes/238-jeff-emmett">
|
||||
MycoPunk Futures on Team Human with Douglas Rushkoff
|
||||
</a>{" "}
|
||||
(<a href="artifact/tft-rocks-integration-domain.pdf">slides</a>)
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://www.youtube.com/watch?v=AFJFDajuCSg">
|
||||
Exploring MycoFi on the Greenpill Network with Kevin Owocki
|
||||
</a>{" "}
|
||||
(<a href="artifact/tft-rocks-integration-domain.pdf">slides</a>)
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://youtu.be/9ad2EJhMbZ8">
|
||||
Re-imagining Human Value on the Telos Podcast with Rieki &
|
||||
Brandonfrom SEEDS
|
||||
</a>{" "}
|
||||
(<a href="artifact/tft-rocks-integration-domain.pdf">slides</a>)
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://www.youtube.com/watch?v=i8qcg7FfpLM&t=1348s">
|
||||
Move Slow & Fix Things: Design Patterns from Nature
|
||||
</a>{" "}
|
||||
(<a href="artifact/tft-rocks-integration-domain.pdf">slides</a>)
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://podcasters.spotify.com/pod/show/theownershipeconomy/episodes/Episode-009---Localized-Democracy-and-Public-Goods-with-Token-Engineering--with-Jeff-Emmett-of-The-Commons-Stack--BlockScience-Labs-e1ggkqo">
|
||||
Localized Democracy and Public Goods with Token Engineering on the
|
||||
Ownership Economy
|
||||
</a>{" "}
|
||||
(<a href="artifact/tft-rocks-integration-domain.pdf">slides</a>)
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://youtu.be/kxcat-XBWas">
|
||||
A Discussion on Warm Data with Nora Bateson on Systems Innovation
|
||||
</a>
|
||||
</li>
|
||||
</ol>
|
||||
<h2>Writing</h2>
|
||||
<ol reversed>
|
||||
<li>
|
||||
<a href="https://www.mycofi.art">
|
||||
Exploring MycoFi: Mycelial Design Patterns for Web3 & Beyond
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://www.frontiersin.org/journals/blockchain/articles/10.3389/fbloc.2021.578721/full">
|
||||
Challenges & Approaches to Scaling the Global Commons
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://allthingsdecent.substack.com/p/mycoeconomics-and-permaculture-currencies">
|
||||
From Monoculture to Permaculture Currencies: A Glimpse of the
|
||||
Myco-Economic Future
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://medium.com/good-audience/rewriting-the-story-of-human-collaboration-c33a8a4cd5b8">
|
||||
Rewriting the Story of Human Collaboration
|
||||
</a>
|
||||
</li>
|
||||
</ol>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
import {
|
||||
createShapeId,
|
||||
Editor,
|
||||
Tldraw,
|
||||
TLGeoShape,
|
||||
TLShapePartial,
|
||||
} from "tldraw"
|
||||
import { useEffect, useRef } from "react"
|
||||
|
||||
export function Inbox() {
|
||||
const editorRef = useRef<Editor | null>(null)
|
||||
|
||||
const updateEmails = async (editor: Editor) => {
|
||||
try {
|
||||
const response = await fetch("https://jeffemmett-canvas.web.val.run", {
|
||||
method: "GET",
|
||||
})
|
||||
const messages = (await response.json()) as {
|
||||
id: string
|
||||
from: string
|
||||
subject: string
|
||||
text: string
|
||||
}[]
|
||||
|
||||
for (let i = 0; i < messages.length; i++) {
|
||||
const message = messages[i]
|
||||
const messageId = message.id
|
||||
const parsedEmailName =
|
||||
message.from.match(/^([^<]+)/)?.[1]?.trim() ||
|
||||
message.from.match(/[^<@]+(?=@)/)?.[0] ||
|
||||
message.from
|
||||
const messageText = `from: ${parsedEmailName}\nsubject: ${message.subject}\n\n${message.text}`
|
||||
const shapeWidth = 500
|
||||
const shapeHeight = 300
|
||||
const spacing = 50
|
||||
const shape: TLShapePartial<TLGeoShape> = {
|
||||
id: createShapeId(),
|
||||
type: "geo",
|
||||
x: shapeWidth * (i % 5) + spacing * (i % 5),
|
||||
y: shapeHeight * Math.floor(i / 5) + spacing * Math.floor(i / 5),
|
||||
props: {
|
||||
w: shapeWidth,
|
||||
h: shapeHeight,
|
||||
text: messageText,
|
||||
align: "start",
|
||||
verticalAlign: "start",
|
||||
},
|
||||
meta: {
|
||||
id: messageId,
|
||||
},
|
||||
}
|
||||
let found = false
|
||||
for (const s of editor.getCurrentPageShapes()) {
|
||||
if (s.meta.id === messageId) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
editor.createShape(shape)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching data:", error)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const intervalId = setInterval(() => {
|
||||
if (editorRef.current) {
|
||||
updateEmails(editorRef.current)
|
||||
}
|
||||
}, 5 * 1000)
|
||||
|
||||
return () => clearInterval(intervalId)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="tldraw__editor">
|
||||
<Tldraw
|
||||
onMount={(editor: Editor) => {
|
||||
editorRef.current = editor
|
||||
updateEmails(editor)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,153 @@
|
|||
|
||||
Yes, it is possible to allow users of your website to render their own Google Docs securely, but it requires additional steps to ensure privacy, user authentication, and proper permissions. Here's how you can set it up:
|
||||
|
||||
---
|
||||
|
||||
### Steps to Enable Users to Render Their Own Google Docs
|
||||
|
||||
#### 1. Enable Google Sign-In for Your Website
|
||||
- Users need to authenticate with their Google account to grant your app access to their documents.
|
||||
- Use the [Google Sign-In library](https://developers.google.com/identity/sign-in/web) to implement OAuth authentication.
|
||||
|
||||
Steps:
|
||||
- Include the Google Sign-In button on your site:
|
||||
<script src="https://apis.google.com/js/platform.js" async defer></script>
|
||||
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
|
||||
<div class="g-signin2" data-onsuccess="onSignIn"></div>
|
||||
|
||||
|
||||
- Handle the user's authentication token on sign-in:
|
||||
function onSignIn(googleUser) {
|
||||
var profile = googleUser.getBasicProfile();
|
||||
var idToken = googleUser.getAuthResponse().id_token;
|
||||
|
||||
// Send the token to your backend to authenticate and fetch user-specific documents
|
||||
fetch('/api/authenticate', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: idToken }),
|
||||
}).then(response => response.json())
|
||||
.then(data => console.log(data));
|
||||
}
|
||||
|
||||
|
||||
---
|
||||
|
||||
#### 2. Request Google Docs API Permissions
|
||||
- Once the user is authenticated, request permissions for the Google Docs API.
|
||||
- Scopes needed:
|
||||
|
||||
https://www.googleapis.com/auth/documents.readonly
|
||||
|
||||
|
||||
- Example request for API access:
|
||||
function requestDocsAccess() {
|
||||
gapi.auth2.getAuthInstance().signIn({
|
||||
scope: 'https://www.googleapis.com/auth/documents.readonly',
|
||||
}).then(() => {
|
||||
console.log('API access granted');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
---
|
||||
|
||||
#### 3. Fetch User's Document Content
|
||||
- After receiving user authorization, fetch their document content using the Google Docs API.
|
||||
- Example using JavaScript:
|
||||
gapi.client.load('docs', 'v1', function () {
|
||||
var request = gapi.client.docs.documents.get({
|
||||
documentId: 'USER_DOCUMENT_ID',
|
||||
});
|
||||
|
||||
request.execute(function (response) {
|
||||
console.log(response);
|
||||
// Render document content on your website
|
||||
document.getElementById('doc-container').innerHTML = response.body.content.map(
|
||||
item => item.paragraph.elements.map(
|
||||
el => el.textRun.content
|
||||
).join('')
|
||||
).join('<br>');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
- Ensure that USER_DOCUMENT_ID is input by the user (e.g., through a form field).
|
||||
|
||||
---
|
||||
|
||||
#### 4. Secure Your Backend
|
||||
- Create an API endpoint to handle requests for fetching document content.
|
||||
- Validate the user's Google token on your server using Google's token verification endpoint.
|
||||
- Use their authenticated token to call the Google Docs API and fetch the requested document.
|
||||
|
||||
Example in Python (using Flask):
|
||||
from google.oauth2 import id_token
|
||||
from google.auth.transport import requests
|
||||
from googleapiclient.discovery import build
|
||||
|
||||
@app.route('/api/fetch-doc', methods=['POST'])
|
||||
def fetch_doc():
|
||||
token = request.json.get('token')
|
||||
document_id = request.json.get('document_id')
|
||||
|
||||
# Verify token
|
||||
idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID)
|
||||
if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
|
||||
return 'Invalid token', 401
|
||||
|
||||
# Fetch the document
|
||||
creds = id_token.Credentials(token=token)
|
||||
service = build('docs', 'v1', credentials=creds)
|
||||
doc = service.documents().get(documentId=document_id).execute()
|
||||
|
||||
return jsonify(doc)
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
rohan mehta, [2024-11-21 4:42 PM]
|
||||
#### 5. Provide a Frontend UI
|
||||
- Allow users to input their Google Doc ID through a form.
|
||||
- Example:
|
||||
<input type="text" id="doc-id" placeholder="Enter your Google Doc ID">
|
||||
<button onclick="fetchDoc()">Render Doc</button>
|
||||
<div id="doc-container"></div>
|
||||
|
||||
|
||||
- JavaScript to send the document ID to your backend:
|
||||
function fetchDoc() {
|
||||
const docId = document.getElementById('doc-id').value;
|
||||
|
||||
fetch('/api/fetch-doc', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: userToken, document_id: docId }),
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
document.getElementById('doc-container').innerHTML = JSON.stringify(data);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Security and Privacy Considerations
|
||||
1. Authentication:
|
||||
- Verify each user's Google token before processing their request.
|
||||
- Only fetch documents they own or have shared with them.
|
||||
|
||||
2. Rate Limiting:
|
||||
- Implement rate limiting on your backend API to prevent abuse.
|
||||
|
||||
3. Permission Scope:
|
||||
- Use the minimal scope (documents.readonly) to ensure you can only read documents, not modify them.
|
||||
|
||||
4. Data Handling:
|
||||
- Never store user document content unless explicitly required and with user consent.
|
||||
|
||||
---
|
||||
|
||||
With this approach, each user will be able to render their own Google Docs securely while maintaining privacy. Let me know if you’d like a more detailed implementation in any specific programming language!
|
||||
|
|
@ -1,155 +1,191 @@
|
|||
import { useEffect, useRef, useState } from "react";
|
||||
import { BaseBoxShapeUtil, TLBaseShape } from "tldraw";
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { BaseBoxShapeUtil, TLBaseShape } from "tldraw"
|
||||
|
||||
export type IChatBoxShape = TLBaseShape<
|
||||
'ChatBox',
|
||||
{
|
||||
w: number
|
||||
h: number
|
||||
roomId: string
|
||||
userName: string
|
||||
}
|
||||
"ChatBox",
|
||||
{
|
||||
w: number
|
||||
h: number
|
||||
roomId: string
|
||||
userName: string
|
||||
}
|
||||
>
|
||||
|
||||
export class ChatBoxShape extends BaseBoxShapeUtil<IChatBoxShape> {
|
||||
static override type = 'ChatBox'
|
||||
static override type = "ChatBox"
|
||||
|
||||
getDefaultProps(): IChatBoxShape['props'] {
|
||||
return {
|
||||
roomId: 'default-room',
|
||||
w: 100,
|
||||
h: 100,
|
||||
userName: '',
|
||||
}
|
||||
getDefaultProps(): IChatBoxShape["props"] {
|
||||
return {
|
||||
roomId: "default-room",
|
||||
w: 100,
|
||||
h: 100,
|
||||
userName: "",
|
||||
}
|
||||
}
|
||||
|
||||
indicator(shape: IChatBoxShape) {
|
||||
return <rect x={0} y={0} width={shape.props.w} height={shape.props.h} />
|
||||
}
|
||||
indicator(shape: IChatBoxShape) {
|
||||
return <rect x={0} y={0} width={shape.props.w} height={shape.props.h} />
|
||||
}
|
||||
|
||||
component(shape: IChatBoxShape) {
|
||||
return (
|
||||
<ChatBox roomId={shape.props.roomId} w={shape.props.w} h={shape.props.h} userName="" />
|
||||
)
|
||||
}
|
||||
component(shape: IChatBoxShape) {
|
||||
return (
|
||||
<ChatBox
|
||||
roomId={shape.props.roomId}
|
||||
w={shape.props.w}
|
||||
h={shape.props.h}
|
||||
userName=""
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
interface Message {
|
||||
id: string;
|
||||
username: string;
|
||||
content: string;
|
||||
timestamp: Date;
|
||||
id: string
|
||||
username: string
|
||||
content: string
|
||||
timestamp: Date
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
// Update the ChatBox component to accept userName
|
||||
export const ChatBox: React.FC<IChatBoxShape['props']> = ({ roomId, w, h, userName }) => {
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [inputMessage, setInputMessage] = useState("");
|
||||
const [username, setUsername] = useState(userName);
|
||||
const messagesEndRef = useRef(null);
|
||||
export const ChatBox: React.FC<IChatBoxShape["props"]> = ({
|
||||
roomId,
|
||||
w,
|
||||
h,
|
||||
userName,
|
||||
}) => {
|
||||
const [messages, setMessages] = useState<Message[]>([])
|
||||
const [inputMessage, setInputMessage] = useState("")
|
||||
const [username, setUsername] = useState(userName)
|
||||
const messagesEndRef = useRef(null)
|
||||
|
||||
useEffect(() => {
|
||||
const storedUsername = localStorage.getItem("chatUsername");
|
||||
if (storedUsername) {
|
||||
setUsername(storedUsername);
|
||||
} else {
|
||||
const newUsername = `User${Math.floor(Math.random() * 1000)}`;
|
||||
setUsername(newUsername);
|
||||
localStorage.setItem("chatUsername", newUsername);
|
||||
}
|
||||
fetchMessages(roomId);
|
||||
const interval = setInterval(() => fetchMessages(roomId), 2000);
|
||||
useEffect(() => {
|
||||
const storedUsername = localStorage.getItem("chatUsername")
|
||||
if (storedUsername) {
|
||||
setUsername(storedUsername)
|
||||
} else {
|
||||
const newUsername = `User${Math.floor(Math.random() * 1000)}`
|
||||
setUsername(newUsername)
|
||||
localStorage.setItem("chatUsername", newUsername)
|
||||
}
|
||||
fetchMessages(roomId)
|
||||
const interval = setInterval(() => fetchMessages(roomId), 2000)
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [roomId]);
|
||||
return () => clearInterval(interval)
|
||||
}, [roomId])
|
||||
|
||||
useEffect(() => {
|
||||
if (messagesEndRef.current) {
|
||||
(messagesEndRef.current as HTMLElement).scrollIntoView({ behavior: "smooth" });
|
||||
}
|
||||
}, [messages]);
|
||||
useEffect(() => {
|
||||
if (messagesEndRef.current) {
|
||||
;(messagesEndRef.current as HTMLElement).scrollIntoView({
|
||||
behavior: "smooth",
|
||||
})
|
||||
}
|
||||
}, [messages])
|
||||
|
||||
const fetchMessages = async (roomId: string) => {
|
||||
try {
|
||||
const response = await fetch(`https://jeffemmett-realtimechatappwithpolling.web.val.run?action=getMessages&roomId=${roomId}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
const newMessages = await response.json() as Message[];
|
||||
setMessages(newMessages.map(msg => ({ ...msg, timestamp: new Date(msg.timestamp) })));
|
||||
} catch (error) {
|
||||
console.error('Error fetching messages:', error);
|
||||
}
|
||||
};
|
||||
const fetchMessages = async (roomId: string) => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`https://jeffemmett-realtimechatappwithpolling.web.val.run?action=getMessages&roomId=${roomId}`,
|
||||
)
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`)
|
||||
}
|
||||
const newMessages = (await response.json()) as Message[]
|
||||
setMessages(
|
||||
newMessages.map((msg) => ({
|
||||
...msg,
|
||||
timestamp: new Date(msg.timestamp),
|
||||
})),
|
||||
)
|
||||
} catch (error) {
|
||||
console.error("Error fetching messages:", error)
|
||||
}
|
||||
}
|
||||
|
||||
const sendMessage = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!inputMessage.trim()) return;
|
||||
await sendMessageToChat(roomId, username, inputMessage);
|
||||
setInputMessage("");
|
||||
fetchMessages(roomId);
|
||||
};
|
||||
const sendMessage = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!inputMessage.trim()) return
|
||||
await sendMessageToChat(roomId, username, inputMessage)
|
||||
setInputMessage("")
|
||||
fetchMessages(roomId)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="chat-container" style={{ pointerEvents: 'all', width: `${w}px`, height: `${h}px`, overflow: 'auto', touchAction: 'auto' }}>
|
||||
<div className="messages-container">
|
||||
{messages.map((msg) => (
|
||||
<div key={msg.id} className={`message ${msg.username === username ? 'own-message' : ''}`}>
|
||||
<div className="message-header">
|
||||
<strong>{msg.username}</strong>
|
||||
<span className="timestamp">{new Date(msg.timestamp).toLocaleTimeString()}</span>
|
||||
</div>
|
||||
<div className="message-content">{msg.content}</div>
|
||||
</div>
|
||||
))}
|
||||
<div ref={messagesEndRef} />
|
||||
return (
|
||||
<div
|
||||
className="chat-container"
|
||||
style={{
|
||||
pointerEvents: "all",
|
||||
width: `${w}px`,
|
||||
height: `${h}px`,
|
||||
overflow: "auto",
|
||||
touchAction: "auto",
|
||||
}}
|
||||
>
|
||||
<div className="messages-container">
|
||||
{messages.map((msg) => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={`message ${
|
||||
msg.username === username ? "own-message" : ""
|
||||
}`}
|
||||
>
|
||||
<div className="message-header">
|
||||
<strong>{msg.username}</strong>
|
||||
<span className="timestamp">
|
||||
{new Date(msg.timestamp).toLocaleTimeString()}
|
||||
</span>
|
||||
</div>
|
||||
<form onSubmit={sendMessage} className="input-form">
|
||||
<input
|
||||
type="text"
|
||||
value={inputMessage}
|
||||
onChange={(e) => setInputMessage(e.target.value)}
|
||||
placeholder="Type a message..."
|
||||
className="message-input"
|
||||
style={{ touchAction: 'manipulation' }}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
style={{ pointerEvents: 'all', touchAction: 'manipulation' }}
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
onTouchStart={(e) => e.stopPropagation()}
|
||||
className="send-button"
|
||||
>
|
||||
Send
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
<div className="message-content">{msg.content}</div>
|
||||
</div>
|
||||
))}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
<form onSubmit={sendMessage} className="input-form">
|
||||
<input
|
||||
type="text"
|
||||
value={inputMessage}
|
||||
onChange={(e) => setInputMessage(e.target.value)}
|
||||
placeholder="Type a message..."
|
||||
className="message-input"
|
||||
style={{ touchAction: "manipulation" }}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
style={{ pointerEvents: "all", touchAction: "manipulation" }}
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
onTouchStart={(e) => e.stopPropagation()}
|
||||
className="send-button"
|
||||
>
|
||||
Send
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
async function sendMessageToChat(roomId: string, username: string, content: string): Promise<void> {
|
||||
const apiUrl = 'https://jeffemmett-realtimechatappwithpolling.web.val.run'; // Replace with your actual Val Town URL
|
||||
async function sendMessageToChat(
|
||||
roomId: string,
|
||||
username: string,
|
||||
content: string,
|
||||
): Promise<void> {
|
||||
const apiUrl = "https://jeffemmett-realtimechatappwithpolling.web.val.run" // Replace with your actual Val Town URL
|
||||
|
||||
try {
|
||||
const response = await fetch(`${apiUrl}?action=sendMessage`, {
|
||||
method: 'POST',
|
||||
mode: 'no-cors',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
roomId,
|
||||
username,
|
||||
content,
|
||||
}),
|
||||
});
|
||||
try {
|
||||
const response = await fetch(`${apiUrl}?action=sendMessage`, {
|
||||
method: "POST",
|
||||
mode: "no-cors",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
roomId,
|
||||
username,
|
||||
content,
|
||||
}),
|
||||
})
|
||||
|
||||
const result = await response.text();
|
||||
console.log('Message sent successfully:', result);
|
||||
} catch (error) {
|
||||
console.error('Error sending message:', error);
|
||||
}
|
||||
}
|
||||
const result = await response.text()
|
||||
console.log("Message sent successfully:", result)
|
||||
} catch (error) {
|
||||
console.error("Error sending message:", error)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,159 +0,0 @@
|
|||
import { BaseBoxShapeUtil, TLBaseShape } from "tldraw";
|
||||
import { useCallback, useState } from "react";
|
||||
|
||||
export type IEmbedShape = TLBaseShape<
|
||||
'Embed',
|
||||
{
|
||||
w: number;
|
||||
h: number;
|
||||
url: string | null;
|
||||
}
|
||||
>;
|
||||
|
||||
export class EmbedShape extends BaseBoxShapeUtil<IEmbedShape> {
|
||||
static override type = 'Embed';
|
||||
|
||||
getDefaultProps(): IEmbedShape['props'] {
|
||||
return {
|
||||
url: null,
|
||||
w: 640,
|
||||
h: 480,
|
||||
};
|
||||
}
|
||||
|
||||
indicator(shape: IEmbedShape) {
|
||||
return (
|
||||
<g>
|
||||
<rect x={0} y={0} width={shape.props.w} height={shape.props.h} />
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
component(shape: IEmbedShape) {
|
||||
const [inputUrl, setInputUrl] = useState(shape.props.url || '');
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleSubmit = useCallback((e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
let completedUrl = inputUrl.startsWith('http://') || inputUrl.startsWith('https://') ? inputUrl : `https://${inputUrl}`;
|
||||
|
||||
// Handle YouTube links
|
||||
if (completedUrl.includes('youtube.com') || completedUrl.includes('youtu.be')) {
|
||||
const videoId = extractYouTubeVideoId(completedUrl);
|
||||
if (videoId) {
|
||||
completedUrl = `https://www.youtube.com/embed/${videoId}`;
|
||||
} else {
|
||||
setError('Invalid YouTube URL');
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Handle Google Docs links
|
||||
if (completedUrl.includes('docs.google.com')) {
|
||||
// Handle different types of Google Docs URLs
|
||||
if (completedUrl.includes('/document/d/')) {
|
||||
const docId = completedUrl.match(/\/document\/d\/([a-zA-Z0-9-_]+)/)?.[1];
|
||||
if (docId) {
|
||||
completedUrl = `https://docs.google.com/document/d/${docId}/edit`;
|
||||
} else {
|
||||
setError('Invalid Google Docs URL');
|
||||
return;
|
||||
}
|
||||
} else if (completedUrl.includes('/spreadsheets/d/')) {
|
||||
const docId = completedUrl.match(/\/spreadsheets\/d\/([a-zA-Z0-9-_]+)/)?.[1];
|
||||
if (docId) {
|
||||
completedUrl = `https://docs.google.com/spreadsheets/d/${docId}/edit`;
|
||||
} else {
|
||||
setError('Invalid Google Sheets URL');
|
||||
return;
|
||||
}
|
||||
} else if (completedUrl.includes('/presentation/d/')) {
|
||||
const docId = completedUrl.match(/\/presentation\/d\/([a-zA-Z0-9-_]+)/)?.[1];
|
||||
if (docId) {
|
||||
completedUrl = `https://docs.google.com/presentation/d/${docId}/embed`;
|
||||
} else {
|
||||
setError('Invalid Google Slides URL');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Add parameters for access
|
||||
completedUrl += '?authuser=0'; // Allow Google authentication
|
||||
}
|
||||
|
||||
this.editor.updateShape<IEmbedShape>({ id: shape.id, type: 'Embed', props: { ...shape.props, url: completedUrl } });
|
||||
|
||||
// Check if the URL is valid
|
||||
const isValidUrl = completedUrl.match(/(^\w+:|^)\/\//);
|
||||
if (!isValidUrl) {
|
||||
setError('Invalid website URL');
|
||||
} else {
|
||||
setError('');
|
||||
}
|
||||
}, [inputUrl]);
|
||||
|
||||
const extractYouTubeVideoId = (url: string): string | null => {
|
||||
const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
|
||||
const match = url.match(regExp);
|
||||
return (match && match[2].length === 11) ? match[2] : null;
|
||||
};
|
||||
|
||||
const wrapperStyle = {
|
||||
width: `${shape.props.w}px`,
|
||||
height: `${shape.props.h}px`,
|
||||
padding: '15px',
|
||||
boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
|
||||
backgroundColor: '#F0F0F0',
|
||||
borderRadius: '4px',
|
||||
};
|
||||
|
||||
const contentStyle = {
|
||||
pointerEvents: 'all' as const,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
border: '1px solid #D3D3D3',
|
||||
backgroundColor: '#FFFFFF',
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
overflow: 'hidden',
|
||||
};
|
||||
|
||||
if (!shape.props.url) {
|
||||
return (
|
||||
<div style={wrapperStyle}>
|
||||
<div style={contentStyle} onClick={() => document.querySelector('input')?.focus()}>
|
||||
<form onSubmit={handleSubmit} style={{ width: '100%', height: '100%', padding: '10px' }}>
|
||||
<input
|
||||
type="text"
|
||||
value={inputUrl}
|
||||
onChange={(e) => setInputUrl(e.target.value)}
|
||||
placeholder="Enter URL"
|
||||
style={{ width: '100%', height: '100%', border: 'none', padding: '10px' }}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleSubmit(e);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{error && <div style={{ color: 'red', marginTop: '10px' }}>{error}</div>}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={wrapperStyle}>
|
||||
<div style={contentStyle}>
|
||||
<iframe
|
||||
src={shape.props.url}
|
||||
width="100%"
|
||||
height="100%"
|
||||
style={{ border: 'none' }}
|
||||
allowFullScreen
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,138 +1,165 @@
|
|||
import { BaseBoxShapeUtil, TLBaseShape } from "tldraw";
|
||||
import { useCallback, useState } from "react";
|
||||
import { BaseBoxShapeUtil, TLBaseShape } from "tldraw"
|
||||
import { useCallback, useState } from "react"
|
||||
|
||||
export type IEmbedShape = TLBaseShape<
|
||||
'Embed',
|
||||
{
|
||||
w: number;
|
||||
h: number;
|
||||
url: string | null;
|
||||
}
|
||||
>;
|
||||
"Embed",
|
||||
{
|
||||
w: number
|
||||
h: number
|
||||
url: string | null
|
||||
}
|
||||
>
|
||||
|
||||
export class EmbedShape extends BaseBoxShapeUtil<IEmbedShape> {
|
||||
static override type = 'Embed';
|
||||
static override type = "Embed"
|
||||
|
||||
getDefaultProps(): IEmbedShape['props'] {
|
||||
return {
|
||||
url: null,
|
||||
w: 640,
|
||||
h: 480,
|
||||
};
|
||||
getDefaultProps(): IEmbedShape["props"] {
|
||||
return {
|
||||
url: null,
|
||||
w: 640,
|
||||
h: 480,
|
||||
}
|
||||
}
|
||||
|
||||
indicator(shape: IEmbedShape) {
|
||||
return (
|
||||
<g>
|
||||
<rect x={0} y={0} width={shape.props.w} height={shape.props.h} />
|
||||
</g>
|
||||
);
|
||||
}
|
||||
indicator(shape: IEmbedShape) {
|
||||
return (
|
||||
<g>
|
||||
<rect x={0} y={0} width={shape.props.w} height={shape.props.h} />
|
||||
</g>
|
||||
)
|
||||
}
|
||||
|
||||
component(shape: IEmbedShape) {
|
||||
const [inputUrl, setInputUrl] = useState(shape.props.url || '');
|
||||
const [error, setError] = useState('');
|
||||
component(shape: IEmbedShape) {
|
||||
const [inputUrl, setInputUrl] = useState(shape.props.url || "")
|
||||
const [error, setError] = useState("")
|
||||
|
||||
const handleSubmit = useCallback((e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
let completedUrl = inputUrl.startsWith('http://') || inputUrl.startsWith('https://') ? inputUrl : `https://${inputUrl}`;
|
||||
const handleSubmit = useCallback(
|
||||
(e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
let completedUrl =
|
||||
inputUrl.startsWith("http://") || inputUrl.startsWith("https://")
|
||||
? inputUrl
|
||||
: `https://${inputUrl}`
|
||||
|
||||
// Handle YouTube links
|
||||
if (completedUrl.includes('youtube.com') || completedUrl.includes('youtu.be')) {
|
||||
const videoId = extractYouTubeVideoId(completedUrl);
|
||||
if (videoId) {
|
||||
completedUrl = `https://www.youtube.com/embed/${videoId}`;
|
||||
} else {
|
||||
setError('Invalid YouTube URL');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle Google Docs links
|
||||
if (completedUrl.includes('docs.google.com')) {
|
||||
const docId = completedUrl.match(/\/d\/([a-zA-Z0-9-_]+)/)?.[1];
|
||||
if (docId) {
|
||||
completedUrl = `https://docs.google.com/document/d/${docId}/preview`;
|
||||
} else {
|
||||
setError('Invalid Google Docs URL');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this.editor.updateShape<IEmbedShape>({ id: shape.id, type: 'Embed', props: { ...shape.props, url: completedUrl } });
|
||||
|
||||
// Check if the URL is valid
|
||||
const isValidUrl = completedUrl.match(/(^\w+:|^)\/\//);
|
||||
if (!isValidUrl) {
|
||||
setError('Invalid website URL');
|
||||
} else {
|
||||
setError('');
|
||||
}
|
||||
}, [inputUrl]);
|
||||
|
||||
const extractYouTubeVideoId = (url: string): string | null => {
|
||||
const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
|
||||
const match = url.match(regExp);
|
||||
return (match && match[2].length === 11) ? match[2] : null;
|
||||
};
|
||||
|
||||
const wrapperStyle = {
|
||||
width: `${shape.props.w}px`,
|
||||
height: `${shape.props.h}px`,
|
||||
padding: '15px',
|
||||
boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
|
||||
backgroundColor: '#F0F0F0',
|
||||
borderRadius: '4px',
|
||||
};
|
||||
|
||||
const contentStyle = {
|
||||
pointerEvents: 'all' as const,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
border: '1px solid #D3D3D3',
|
||||
backgroundColor: '#FFFFFF',
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
overflow: 'hidden',
|
||||
};
|
||||
|
||||
if (!shape.props.url) {
|
||||
return (
|
||||
<div style={wrapperStyle}>
|
||||
<div style={contentStyle} onClick={() => document.querySelector('input')?.focus()}>
|
||||
<form onSubmit={handleSubmit} style={{ width: '100%', height: '100%', padding: '10px' }}>
|
||||
<input
|
||||
type="text"
|
||||
value={inputUrl}
|
||||
onChange={(e) => setInputUrl(e.target.value)}
|
||||
placeholder="Enter URL"
|
||||
style={{ width: '100%', height: '100%', border: 'none', padding: '10px' }}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleSubmit(e);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{error && <div style={{ color: 'red', marginTop: '10px' }}>{error}</div>}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
// Handle YouTube links
|
||||
if (
|
||||
completedUrl.includes("youtube.com") ||
|
||||
completedUrl.includes("youtu.be")
|
||||
) {
|
||||
const videoId = extractYouTubeVideoId(completedUrl)
|
||||
if (videoId) {
|
||||
completedUrl = `https://www.youtube.com/embed/${videoId}`
|
||||
} else {
|
||||
setError("Invalid YouTube URL")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={wrapperStyle}>
|
||||
<div style={contentStyle}>
|
||||
<iframe
|
||||
src={shape.props.url}
|
||||
width="100%"
|
||||
height="100%"
|
||||
style={{ border: 'none' }}
|
||||
allowFullScreen
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
// Handle Google Docs links
|
||||
if (completedUrl.includes("docs.google.com")) {
|
||||
const docId = completedUrl.match(/\/d\/([a-zA-Z0-9-_]+)/)?.[1]
|
||||
if (docId) {
|
||||
completedUrl = `https://docs.google.com/document/d/${docId}/preview`
|
||||
} else {
|
||||
setError("Invalid Google Docs URL")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
this.editor.updateShape<IEmbedShape>({
|
||||
id: shape.id,
|
||||
type: "Embed",
|
||||
props: { ...shape.props, url: completedUrl },
|
||||
})
|
||||
|
||||
// Check if the URL is valid
|
||||
const isValidUrl = completedUrl.match(/(^\w+:|^)\/\//)
|
||||
if (!isValidUrl) {
|
||||
setError("Invalid website URL")
|
||||
} else {
|
||||
setError("")
|
||||
}
|
||||
},
|
||||
[inputUrl],
|
||||
)
|
||||
|
||||
const extractYouTubeVideoId = (url: string): string | null => {
|
||||
const regExp =
|
||||
/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/
|
||||
const match = url.match(regExp)
|
||||
return match && match[2].length === 11 ? match[2] : null
|
||||
}
|
||||
|
||||
const wrapperStyle = {
|
||||
width: `${shape.props.w}px`,
|
||||
height: `${shape.props.h}px`,
|
||||
padding: "15px",
|
||||
boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
|
||||
backgroundColor: "#F0F0F0",
|
||||
borderRadius: "4px",
|
||||
}
|
||||
|
||||
const contentStyle = {
|
||||
pointerEvents: "all" as const,
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
border: "1px solid #D3D3D3",
|
||||
backgroundColor: "#FFFFFF",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
overflow: "hidden",
|
||||
}
|
||||
|
||||
if (!shape.props.url) {
|
||||
return (
|
||||
<div style={wrapperStyle}>
|
||||
<div
|
||||
style={contentStyle}
|
||||
onClick={() => document.querySelector("input")?.focus()}
|
||||
>
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
style={{ width: "100%", height: "100%", padding: "10px" }}
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
value={inputUrl}
|
||||
onChange={(e) => setInputUrl(e.target.value)}
|
||||
placeholder="Enter URL"
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
border: "none",
|
||||
padding: "10px",
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
handleSubmit(e)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{error && (
|
||||
<div style={{ color: "red", marginTop: "10px" }}>{error}</div>
|
||||
)}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={wrapperStyle}>
|
||||
<div style={contentStyle}>
|
||||
<iframe
|
||||
src={shape.props.url}
|
||||
width="100%"
|
||||
height="100%"
|
||||
style={{ border: "none" }}
|
||||
allowFullScreen
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,119 +1,124 @@
|
|||
import { BaseBoxShapeUtil, TLBaseShape } from "tldraw";
|
||||
import { useEffect, useState } from "react";
|
||||
import { WORKER_URL } from '../components/Board';
|
||||
import { BaseBoxShapeUtil, TLBaseShape } from "tldraw"
|
||||
import { useEffect, useState } from "react"
|
||||
import { WORKER_URL } from "../routes/Board"
|
||||
|
||||
export type IVideoChatShape = TLBaseShape<
|
||||
'VideoChat',
|
||||
{
|
||||
w: number;
|
||||
h: number;
|
||||
roomUrl: string | null;
|
||||
userName: string;
|
||||
}
|
||||
>;
|
||||
"VideoChat",
|
||||
{
|
||||
w: number
|
||||
h: number
|
||||
roomUrl: string | null
|
||||
userName: string
|
||||
}
|
||||
>
|
||||
|
||||
export class VideoChatShape extends BaseBoxShapeUtil<IVideoChatShape> {
|
||||
static override type = 'VideoChat';
|
||||
static override type = "VideoChat"
|
||||
|
||||
indicator(_shape: IVideoChatShape) {
|
||||
return null;
|
||||
}
|
||||
indicator(_shape: IVideoChatShape) {
|
||||
return null
|
||||
}
|
||||
|
||||
getDefaultProps(): IVideoChatShape['props'] {
|
||||
return {
|
||||
roomUrl: null,
|
||||
w: 640,
|
||||
h: 480,
|
||||
userName: ''
|
||||
};
|
||||
}
|
||||
getDefaultProps(): IVideoChatShape["props"] {
|
||||
return {
|
||||
roomUrl: null,
|
||||
w: 640,
|
||||
h: 480,
|
||||
userName: "",
|
||||
}
|
||||
}
|
||||
|
||||
async ensureRoomExists(shape: IVideoChatShape) {
|
||||
if (shape.props.roomUrl !== null) {
|
||||
return;
|
||||
}
|
||||
async ensureRoomExists(shape: IVideoChatShape) {
|
||||
if (shape.props.roomUrl !== null) {
|
||||
return
|
||||
}
|
||||
|
||||
const response = await fetch(`${WORKER_URL}/daily/rooms`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
properties: {
|
||||
enable_recording: true,
|
||||
max_participants: 8
|
||||
}
|
||||
})
|
||||
});
|
||||
const response = await fetch(`${WORKER_URL}/daily/rooms`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
properties: {
|
||||
enable_recording: true,
|
||||
max_participants: 8,
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
const data = await response.json();
|
||||
const data = await response.json()
|
||||
|
||||
this.editor.updateShape<IVideoChatShape>({
|
||||
id: shape.id,
|
||||
type: 'VideoChat',
|
||||
props: {
|
||||
...shape.props,
|
||||
roomUrl: (data as any).url
|
||||
}
|
||||
});
|
||||
}
|
||||
this.editor.updateShape<IVideoChatShape>({
|
||||
id: shape.id,
|
||||
type: "VideoChat",
|
||||
props: {
|
||||
...shape.props,
|
||||
roomUrl: (data as any).url,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
component(shape: IVideoChatShape) {
|
||||
const [isInRoom, setIsInRoom] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
component(shape: IVideoChatShape) {
|
||||
const [isInRoom, setIsInRoom] = useState(false)
|
||||
const [error, setError] = useState("")
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (isInRoom && shape.props.roomUrl) {
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://www.daily.co/static/call-machine.js';
|
||||
document.body.appendChild(script);
|
||||
useEffect(() => {
|
||||
if (isInRoom && shape.props.roomUrl) {
|
||||
const script = document.createElement("script")
|
||||
script.src = "https://www.daily.co/static/call-machine.js"
|
||||
document.body.appendChild(script)
|
||||
|
||||
script.onload = () => {
|
||||
// @ts-ignore
|
||||
window.DailyIframe.createFrame({
|
||||
iframeStyle: {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
border: '0',
|
||||
borderRadius: '4px'
|
||||
},
|
||||
showLeaveButton: true,
|
||||
showFullscreenButton: true
|
||||
}).join({ url: shape.props.roomUrl });
|
||||
};
|
||||
}
|
||||
}, [isInRoom, shape.props.roomUrl]);
|
||||
script.onload = () => {
|
||||
// @ts-ignore
|
||||
window.DailyIframe.createFrame({
|
||||
iframeStyle: {
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
border: "0",
|
||||
borderRadius: "4px",
|
||||
},
|
||||
showLeaveButton: true,
|
||||
showFullscreenButton: true,
|
||||
}).join({ url: shape.props.roomUrl })
|
||||
}
|
||||
}
|
||||
}, [isInRoom, shape.props.roomUrl])
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
pointerEvents: 'all',
|
||||
width: `${shape.props.w}px`,
|
||||
height: `${shape.props.h}px`,
|
||||
position: 'absolute',
|
||||
top: '10px',
|
||||
left: '10px',
|
||||
zIndex: 9999,
|
||||
padding: '15px',
|
||||
backgroundColor: '#F0F0F0',
|
||||
boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
|
||||
borderRadius: '4px',
|
||||
}}>
|
||||
{!isInRoom ? (
|
||||
<button
|
||||
onClick={() => setIsInRoom(true)}
|
||||
className="bg-blue-500 text-white px-4 py-2 rounded"
|
||||
>
|
||||
Join Room
|
||||
</button>
|
||||
) : (
|
||||
<div id="daily-call-iframe-container" style={{
|
||||
width: '100%',
|
||||
height: '100%'
|
||||
}} />
|
||||
)}
|
||||
{error && <p className="text-red-500 mt-2">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
pointerEvents: "all",
|
||||
width: `${shape.props.w}px`,
|
||||
height: `${shape.props.h}px`,
|
||||
position: "absolute",
|
||||
top: "10px",
|
||||
left: "10px",
|
||||
zIndex: 9999,
|
||||
padding: "15px",
|
||||
backgroundColor: "#F0F0F0",
|
||||
boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
|
||||
borderRadius: "4px",
|
||||
}}
|
||||
>
|
||||
{!isInRoom ? (
|
||||
<button
|
||||
onClick={() => setIsInRoom(true)}
|
||||
className="bg-blue-500 text-white px-4 py-2 rounded"
|
||||
>
|
||||
Join Room
|
||||
</button>
|
||||
) : (
|
||||
<div
|
||||
id="daily-call-iframe-container"
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{error && <p className="text-red-500 mt-2">{error}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -1,7 +1,7 @@
|
|||
import { BaseBoxShapeTool } from "tldraw";
|
||||
import { BaseBoxShapeTool } from "tldraw"
|
||||
|
||||
export class ChatBoxTool extends BaseBoxShapeTool {
|
||||
static override id = 'ChatBox'
|
||||
shapeType = 'ChatBox';
|
||||
override initial = 'idle';
|
||||
}
|
||||
static override id = "ChatBox"
|
||||
shapeType = "ChatBox"
|
||||
override initial = "idle"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,7 @@
|
|||
import { BaseBoxShapeTool } from "tldraw";
|
||||
import { BaseBoxShapeTool } from "tldraw"
|
||||
|
||||
export class EmbedTool extends BaseBoxShapeTool {
|
||||
static override id = 'Embed'
|
||||
shapeType = 'Embed';
|
||||
override initial = 'idle';
|
||||
|
||||
// Additional methods for handling video chat functionality can be added here
|
||||
}
|
||||
static override id = "Embed"
|
||||
shapeType = "Embed"
|
||||
override initial = "idle"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,7 @@
|
|||
import { BaseBoxShapeTool } from "tldraw";
|
||||
import { BaseBoxShapeTool } from "tldraw"
|
||||
|
||||
export class VideoChatTool extends BaseBoxShapeTool {
|
||||
static override id = 'VideoChat'
|
||||
shapeType = 'VideoChat';
|
||||
override initial = 'idle';
|
||||
|
||||
// Additional methods for handling video chat functionality can be added here
|
||||
}
|
||||
static override id = "VideoChat"
|
||||
shapeType = "VideoChat"
|
||||
override initial = "idle"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +0,0 @@
|
|||
declare module 'crdts/src/G-Set' {
|
||||
export default class GSet<T = any> {
|
||||
add(value: T): void;
|
||||
values(): Set<T>;
|
||||
}
|
||||
}
|
||||
|
|
@ -6,12 +6,10 @@ import {
|
|||
TldrawUiMenuItem,
|
||||
useEditor,
|
||||
useTools,
|
||||
TLShapeId,
|
||||
DefaultContextMenu,
|
||||
DefaultContextMenuContent,
|
||||
TLUiContextMenuProps,
|
||||
TldrawUiMenuGroup,
|
||||
TLShape,
|
||||
} from 'tldraw'
|
||||
import { CustomMainMenu } from './components/CustomMainMenu'
|
||||
import { Editor } from 'tldraw'
|
||||
|
|
@ -37,55 +35,6 @@ const storeCameraPosition = (editor: Editor) => {
|
|||
}
|
||||
};
|
||||
|
||||
const copyFrameLink = async (editor: Editor, frameId: string) => {
|
||||
console.log('Starting copyFrameLink with frameId:', frameId);
|
||||
|
||||
if (!editor.store.getSnapshot()) {
|
||||
console.warn('Store not ready');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const baseUrl = `${window.location.origin}${window.location.pathname}`;
|
||||
console.log('Base URL:', baseUrl);
|
||||
|
||||
const url = new URL(baseUrl);
|
||||
url.searchParams.set('frameId', frameId);
|
||||
|
||||
const frame = editor.getShape(frameId as TLShapeId);
|
||||
console.log('Found frame:', frame);
|
||||
|
||||
if (frame) {
|
||||
const camera = editor.getCamera();
|
||||
console.log('Camera position:', { x: camera.x, y: camera.y, zoom: camera.z });
|
||||
|
||||
url.searchParams.set('x', camera.x.toString());
|
||||
url.searchParams.set('y', camera.y.toString());
|
||||
url.searchParams.set('zoom', camera.z.toString());
|
||||
}
|
||||
|
||||
const finalUrl = url.toString();
|
||||
console.log('Final URL to copy:', finalUrl);
|
||||
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
console.log('Using modern clipboard API...');
|
||||
await navigator.clipboard.writeText(finalUrl);
|
||||
console.log('URL copied successfully using clipboard API');
|
||||
} else {
|
||||
console.log('Falling back to legacy clipboard method...');
|
||||
const textArea = document.createElement('textarea');
|
||||
textArea.value = finalUrl;
|
||||
document.body.appendChild(textArea);
|
||||
textArea.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(textArea);
|
||||
console.log('URL copied successfully using fallback method');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to copy to clipboard:', error);
|
||||
alert('Failed to copy link. Please check clipboard permissions.');
|
||||
}
|
||||
};
|
||||
|
||||
export const zoomToSelection = (editor: Editor) => {
|
||||
// Store camera position before zooming
|
||||
|
|
@ -154,7 +103,7 @@ export const zoomToSelection = (editor: Editor) => {
|
|||
const copyLinkToCurrentView = async (editor: Editor) => {
|
||||
console.log('Starting copyLinkToCurrentView');
|
||||
|
||||
if (!editor.store.getSnapshot()) {
|
||||
if (!editor.store.serialize()) {
|
||||
console.warn('Store not ready');
|
||||
return;
|
||||
}
|
||||
|
|
@ -184,10 +133,16 @@ const copyLinkToCurrentView = async (editor: Editor) => {
|
|||
const textArea = document.createElement('textarea');
|
||||
textArea.value = finalUrl;
|
||||
document.body.appendChild(textArea);
|
||||
textArea.select();
|
||||
document.execCommand('copy');
|
||||
try {
|
||||
await navigator.clipboard.writeText(textArea.value);
|
||||
console.log('URL copied successfully');
|
||||
} catch (err) {
|
||||
// Fallback for older browsers
|
||||
textArea.select();
|
||||
document.execCommand('copy');
|
||||
console.log('URL copied using fallback method');
|
||||
}
|
||||
document.body.removeChild(textArea);
|
||||
console.log('URL copied successfully using fallback method');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to copy to clipboard:', error);
|
||||
|
|
@ -226,7 +181,8 @@ const revertCamera = (editor: Editor) => {
|
|||
}
|
||||
};
|
||||
|
||||
export const uiOverrides: TLUiOverrides = {
|
||||
// Export a function that creates the uiOverrides
|
||||
export const overrides: TLUiOverrides = ({
|
||||
tools(editor, tools) {
|
||||
return {
|
||||
...tools,
|
||||
|
|
@ -257,74 +213,69 @@ export const uiOverrides: TLUiOverrides = {
|
|||
}
|
||||
},
|
||||
actions(editor, actions) {
|
||||
actions['copyFrameLink'] = {
|
||||
id: 'copy-frame-link',
|
||||
label: 'Copy Frame Link',
|
||||
onSelect: () => {
|
||||
const shape = editor.getSelectedShapes()[0]
|
||||
if (shape && shape.type === 'frame') {
|
||||
copyFrameLink(editor, shape.id)
|
||||
return {
|
||||
...actions,
|
||||
'zoomToSelection': {
|
||||
id: 'zoom-to-selection',
|
||||
label: 'Zoom to Selection',
|
||||
kbd: 'z',
|
||||
onSelect: () => {
|
||||
if (editor.getSelectedShapeIds().length > 0) {
|
||||
zoomToSelection(editor);
|
||||
}
|
||||
},
|
||||
readonlyOk: true,
|
||||
},
|
||||
'copyLinkToCurrentView': {
|
||||
id: 'copy-link-to-current-view',
|
||||
label: 'Copy Link to Current View',
|
||||
kbd: 's',
|
||||
onSelect: () => {
|
||||
copyLinkToCurrentView(editor);
|
||||
},
|
||||
readonlyOk: true,
|
||||
},
|
||||
'revertCamera': {
|
||||
id: 'revert-camera',
|
||||
label: 'Revert Camera',
|
||||
kbd: 'b',
|
||||
onSelect: () => {
|
||||
if (cameraHistory.length > 0) {
|
||||
revertCamera(editor);
|
||||
}
|
||||
},
|
||||
readonlyOk: true,
|
||||
},
|
||||
'lockToFrame': {
|
||||
id: 'lock-to-frame',
|
||||
label: 'Lock to Frame',
|
||||
kbd: 'l',
|
||||
onSelect: () => {
|
||||
const selectedShapes = editor.getSelectedShapes()
|
||||
if (selectedShapes.length === 0) return
|
||||
const selectedShape = selectedShapes[0]
|
||||
const isFrame = selectedShape.type === 'frame'
|
||||
const bounds = editor.getShapePageBounds(selectedShape)
|
||||
if (!isFrame || !bounds) return
|
||||
|
||||
editor.zoomToBounds(bounds, {
|
||||
animation: { duration: 300 },
|
||||
targetZoom: 1
|
||||
})
|
||||
editor.updateInstanceState({
|
||||
meta: { ...editor.getInstanceState().meta, lockedFrameId: selectedShape.id }
|
||||
})
|
||||
}
|
||||
},
|
||||
readonlyOk: true,
|
||||
}
|
||||
}
|
||||
|
||||
actions['zoomToFrame'] = {
|
||||
id: 'zoom-to-frame',
|
||||
label: 'Zoom to Frame',
|
||||
onSelect: () => {
|
||||
const shape = editor.getSelectedShapes()[0]
|
||||
if (shape && shape.type === 'frame') {
|
||||
zoomToSelection(editor)
|
||||
}
|
||||
},
|
||||
readonlyOk: true,
|
||||
}
|
||||
|
||||
actions['copyLinkToCurrentView'] = {
|
||||
id: 'copy-link-to-current-view',
|
||||
label: 'Copy Link to Current View',
|
||||
kbd: 'c',
|
||||
onSelect: () => {
|
||||
console.log('Creating link to current view');
|
||||
copyLinkToCurrentView(editor);
|
||||
},
|
||||
readonlyOk: true,
|
||||
}
|
||||
|
||||
actions['zoomToShape'] = {
|
||||
id: 'zoom-to-shape',
|
||||
label: 'Zoom to Selection',
|
||||
kbd: 'z',
|
||||
onSelect: () => {
|
||||
if (editor.getSelectedShapeIds().length > 0) {
|
||||
console.log('Zooming to selection');
|
||||
zoomToSelection(editor);
|
||||
}
|
||||
},
|
||||
readonlyOk: true,
|
||||
}
|
||||
|
||||
actions['revertCamera'] = {
|
||||
id: 'revert-camera',
|
||||
label: 'Revert Camera',
|
||||
kbd: 'b',
|
||||
onSelect: () => {
|
||||
if (cameraHistory.length > 0) {
|
||||
revertCamera(editor);
|
||||
}
|
||||
},
|
||||
readonlyOk: true,
|
||||
}
|
||||
|
||||
return actions
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
export const components: TLComponents = {
|
||||
Toolbar: function Toolbar() {
|
||||
const editor = useEditor()
|
||||
const tools = useTools()
|
||||
|
||||
return (
|
||||
<DefaultToolbar>
|
||||
<DefaultToolbarContent />
|
||||
|
|
@ -356,7 +307,7 @@ export const components: TLComponents = {
|
|||
)
|
||||
},
|
||||
MainMenu: CustomMainMenu,
|
||||
ContextMenu: function CustomContextMenu({ ...rest }) {
|
||||
ContextMenu: function CustomContextMenu(props: TLUiContextMenuProps) {
|
||||
const editor = useEditor()
|
||||
const hasSelection = editor.getSelectedShapeIds().length > 0
|
||||
const hasCameraHistory = cameraHistory.length > 0
|
||||
|
|
@ -364,101 +315,76 @@ export const components: TLComponents = {
|
|||
const isFrame = selectedShape?.type === 'frame'
|
||||
|
||||
return (
|
||||
<DefaultContextMenu {...rest}>
|
||||
<DefaultContextMenu {...props}>
|
||||
<DefaultContextMenuContent />
|
||||
|
||||
{/* Camera Controls */}
|
||||
<TldrawUiMenuItem
|
||||
id="zoom-to-selection"
|
||||
label="Zoom to Selection"
|
||||
icon="zoom-in"
|
||||
kbd="z"
|
||||
disabled={!hasSelection}
|
||||
onSelect={() => zoomToSelection(editor)}
|
||||
/>
|
||||
<TldrawUiMenuItem
|
||||
id="copy-link-to-current-view"
|
||||
label="Copy Link to Current View"
|
||||
icon="link"
|
||||
kbd="s"
|
||||
onSelect={() => copyLinkToCurrentView(editor)}
|
||||
/>
|
||||
<TldrawUiMenuItem
|
||||
id="revert-camera"
|
||||
label="Revert Camera"
|
||||
icon="undo"
|
||||
kbd="b"
|
||||
onSelect={() => {
|
||||
if (hasCameraHistory) {
|
||||
revertCamera(editor);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{/* Camera Controls Group */}
|
||||
<TldrawUiMenuGroup id="camera-controls">
|
||||
<TldrawUiMenuItem
|
||||
id="zoom-to-selection"
|
||||
label="Zoom to Selection"
|
||||
icon="zoom-in"
|
||||
kbd="z"
|
||||
disabled={!hasSelection}
|
||||
onSelect={() => zoomToSelection(editor)}
|
||||
/>
|
||||
<TldrawUiMenuItem
|
||||
id="copy-link-to-current-view"
|
||||
label="Copy Link to Current View"
|
||||
icon="link"
|
||||
kbd="s"
|
||||
onSelect={() => copyLinkToCurrentView(editor)}
|
||||
/>
|
||||
<TldrawUiMenuItem
|
||||
id="revert-camera"
|
||||
label="Revert Camera"
|
||||
icon="undo"
|
||||
kbd="b"
|
||||
disabled={!hasCameraHistory}
|
||||
onSelect={() => revertCamera(editor)}
|
||||
/>
|
||||
</TldrawUiMenuGroup>
|
||||
|
||||
{/* Shape Creation Tools */}
|
||||
<TldrawUiMenuItem
|
||||
id="video-chat"
|
||||
label="Create Video Chat"
|
||||
icon="video"
|
||||
kbd="v"
|
||||
onSelect={() => {
|
||||
editor.setCurrentTool('VideoChat');
|
||||
}}
|
||||
/>
|
||||
<TldrawUiMenuItem
|
||||
id="chat-box"
|
||||
label="Create Chat Box"
|
||||
icon="chat"
|
||||
kbd="c"
|
||||
onSelect={() => {
|
||||
editor.setCurrentTool('ChatBox');
|
||||
}}
|
||||
/>
|
||||
<TldrawUiMenuItem
|
||||
id="embed"
|
||||
label="Create Embed"
|
||||
icon="embed"
|
||||
kbd="e"
|
||||
onSelect={() => {
|
||||
editor.setCurrentTool('Embed');
|
||||
}}
|
||||
/>
|
||||
{/* Creation Tools Group */}
|
||||
<TldrawUiMenuGroup id="creation-tools">
|
||||
<TldrawUiMenuItem
|
||||
id="video-chat"
|
||||
label="Create Video Chat"
|
||||
icon="video"
|
||||
kbd="v"
|
||||
onSelect={() => { editor.setCurrentTool('VideoChat'); }}
|
||||
/>
|
||||
<TldrawUiMenuItem
|
||||
id="chat-box"
|
||||
label="Create Chat Box"
|
||||
icon="chat"
|
||||
kbd="c"
|
||||
onSelect={() => { editor.setCurrentTool('ChatBox'); }}
|
||||
/>
|
||||
<TldrawUiMenuItem
|
||||
id="embed"
|
||||
label="Create Embed"
|
||||
icon="embed"
|
||||
kbd="e"
|
||||
onSelect={() => { editor.setCurrentTool('Embed'); }}
|
||||
/>
|
||||
</TldrawUiMenuGroup>
|
||||
|
||||
{/* Frame Controls */}
|
||||
{isFrame && (
|
||||
<TldrawUiMenuGroup id="frame-controls">
|
||||
<TldrawUiMenuItem
|
||||
id="lock-to-frame"
|
||||
label="Lock to Frame"
|
||||
icon="lock"
|
||||
kbd="l"
|
||||
onSelect={() => {
|
||||
console.warn('lock to frame NOT IMPLEMENTED')
|
||||
}}
|
||||
/>
|
||||
</TldrawUiMenuGroup>
|
||||
)}
|
||||
</DefaultContextMenu>
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
const handleInitialShapeLoad = (editor: Editor) => {
|
||||
const url = new URL(window.location.href);
|
||||
|
||||
// Check for both shapeId and legacy frameId (for backwards compatibility)
|
||||
const shapeId = url.searchParams.get('shapeId') || url.searchParams.get('frameId');
|
||||
const x = url.searchParams.get('x');
|
||||
const y = url.searchParams.get('y');
|
||||
const zoom = url.searchParams.get('zoom');
|
||||
|
||||
if (shapeId) {
|
||||
console.log('Found shapeId in URL:', shapeId);
|
||||
const shape = editor.getShape(shapeId as TLShapeId);
|
||||
|
||||
if (shape) {
|
||||
console.log('Found shape:', shape);
|
||||
if (x && y && zoom) {
|
||||
console.log('Setting camera to:', { x, y, zoom });
|
||||
editor.setCamera({
|
||||
x: parseFloat(x),
|
||||
y: parseFloat(y),
|
||||
z: parseFloat(zoom)
|
||||
});
|
||||
} else {
|
||||
console.log('Zooming to shape bounds');
|
||||
editor.zoomToBounds(editor.getShapeGeometry(shape).bounds, {
|
||||
targetZoom: 1,
|
||||
//padding: 32
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.warn('Shape not found:', shapeId);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -1,83 +0,0 @@
|
|||
import {
|
||||
TLBaseShape,
|
||||
TLResizeHandle,
|
||||
BaseBoxShapeUtil,
|
||||
//TLShapeUtilFlag,
|
||||
resizeBox,
|
||||
VecModel,
|
||||
Box,
|
||||
TLResizeMode,
|
||||
Rectangle2d,
|
||||
} from 'tldraw'
|
||||
|
||||
export interface HTMLShape extends TLBaseShape<'html', { w: number; h: number, html: string }> {
|
||||
props: {
|
||||
w: number
|
||||
h: number
|
||||
html: string
|
||||
}
|
||||
}
|
||||
|
||||
export class HTMLShapeUtil extends BaseBoxShapeUtil<HTMLShape> {
|
||||
static override type = 'html' as const
|
||||
override canBind = () => true
|
||||
override canEdit = () => false
|
||||
override canResize = () => true
|
||||
override isAspectRatioLocked = () => false
|
||||
|
||||
getDefaultProps(): HTMLShape['props'] {
|
||||
return {
|
||||
w: 100,
|
||||
h: 100,
|
||||
html: "<div></div>"
|
||||
}
|
||||
}
|
||||
|
||||
override onBeforeUpdate = (prev: HTMLShape, next: HTMLShape): void => {
|
||||
if (prev.x !== next.x || prev.y !== next.y) {
|
||||
this.editor.bringToFront([next.id]);
|
||||
}
|
||||
}
|
||||
|
||||
override onResize = (
|
||||
shape: HTMLShape,
|
||||
info: {
|
||||
handle: TLResizeHandle;
|
||||
mode: TLResizeMode;
|
||||
initialBounds: Box;
|
||||
initialShape: HTMLShape;
|
||||
newPoint: VecModel;
|
||||
scaleX: number;
|
||||
scaleY: number;
|
||||
}
|
||||
) => {
|
||||
const element = document.getElementById(shape.id);
|
||||
if (!element || !element.parentElement) return resizeBox(shape, info);
|
||||
const { width, height } = element.parentElement.getBoundingClientRect();
|
||||
if (element) {
|
||||
const isOverflowing = element.scrollWidth > width || element.scrollHeight > height;
|
||||
if (isOverflowing) {
|
||||
element.parentElement?.classList.add('overflowing');
|
||||
} else {
|
||||
element.parentElement?.classList.remove('overflowing');
|
||||
}
|
||||
}
|
||||
return resizeBox(shape, info)
|
||||
}
|
||||
|
||||
getGeometry(shape: HTMLShape) {
|
||||
return new Rectangle2d({
|
||||
width: shape.props.w,
|
||||
height: shape.props.h,
|
||||
isFilled: true,
|
||||
})
|
||||
}
|
||||
|
||||
override component(shape: HTMLShape): JSX.Element {
|
||||
return <div id={shape.id} dangerouslySetInnerHTML={{ __html: shape.props.html }} />
|
||||
}
|
||||
|
||||
override indicator(shape: HTMLShape): JSX.Element {
|
||||
return <rect width={shape.props.w} height={shape.props.h} />
|
||||
}
|
||||
}
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
import { createShapePropsMigrationIds, createShapePropsMigrationSequence } from 'tldraw'
|
||||
|
||||
const versions = createShapePropsMigrationIds(
|
||||
// this must match the shape type in the shape definition
|
||||
'card',
|
||||
{
|
||||
AddSomeProperty: 1,
|
||||
}
|
||||
)
|
||||
|
||||
// Migrations for the custom card shape (optional but very helpful)
|
||||
export const cardShapeMigrations = createShapePropsMigrationSequence({
|
||||
sequence: [
|
||||
{
|
||||
id: versions.AddSomeProperty,
|
||||
up(props) {
|
||||
// it is safe to mutate the props object here
|
||||
props.someProperty = 'some value'
|
||||
},
|
||||
down(props) {
|
||||
delete props.someProperty
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
import { DefaultColorStyle, RecordProps, T } from 'tldraw'
|
||||
import { ICardShape } from './card-shape-types'
|
||||
|
||||
// Validation for our custom card shape's props, using one of tldraw's default styles
|
||||
export const cardShapeProps: RecordProps<ICardShape> = {
|
||||
w: T.number,
|
||||
h: T.number,
|
||||
color: DefaultColorStyle,
|
||||
}
|
||||
|
||||
// To generate your own custom styles, check out the custom styles example.
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
import { TLBaseShape, TLDefaultColorStyle } from 'tldraw'
|
||||
|
||||
// A type for our custom card shape
|
||||
export type ICardShape = TLBaseShape<
|
||||
'card',
|
||||
{
|
||||
w: number
|
||||
h: number
|
||||
color: TLDefaultColorStyle
|
||||
}
|
||||
>
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { TLAssetStore, uniqueId } from 'tldraw'
|
||||
import { WORKER_URL } from '../components/Board'
|
||||
import { WORKER_URL } from '../routes/Board'
|
||||
|
||||
export const multiplayerAssetStore: TLAssetStore = {
|
||||
async upload(_asset, file) {
|
||||
|
|
@ -1,120 +0,0 @@
|
|||
import { BaseBoxShapeUtil, HTMLContainer, RecordProps, T, TLBaseShape } from 'tldraw'
|
||||
|
||||
// There's a guide at the bottom of this file!
|
||||
|
||||
type IMyInteractiveShape = TLBaseShape<
|
||||
'my-interactive-shape',
|
||||
{
|
||||
w: number
|
||||
h: number
|
||||
checked: boolean
|
||||
text: string
|
||||
}
|
||||
>
|
||||
|
||||
export class myInteractiveShape extends BaseBoxShapeUtil<IMyInteractiveShape> {
|
||||
static override type = 'my-interactive-shape' as const
|
||||
static override props: RecordProps<IMyInteractiveShape> = {
|
||||
w: T.number,
|
||||
h: T.number,
|
||||
checked: T.boolean,
|
||||
text: T.string,
|
||||
}
|
||||
|
||||
getDefaultProps(): IMyInteractiveShape['props'] {
|
||||
return {
|
||||
w: 230,
|
||||
h: 230,
|
||||
checked: false,
|
||||
text: '',
|
||||
}
|
||||
}
|
||||
|
||||
// [1]
|
||||
component(shape: IMyInteractiveShape) {
|
||||
return (
|
||||
<HTMLContainer
|
||||
style={{
|
||||
padding: 16,
|
||||
height: shape.props.h,
|
||||
width: shape.props.w,
|
||||
// [a] This is where we allow pointer events on our shape
|
||||
pointerEvents: 'all',
|
||||
backgroundColor: '#efefef',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={shape.props.checked}
|
||||
onChange={() =>
|
||||
this.editor.updateShape<IMyInteractiveShape>({
|
||||
id: shape.id,
|
||||
type: 'my-interactive-shape',
|
||||
props: { checked: !shape.props.checked },
|
||||
})
|
||||
}
|
||||
// [b] This is where we stop event propagation
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
onTouchStart={(e) => e.stopPropagation()}
|
||||
onTouchEnd={(e) => e.stopPropagation()}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Enter a todo..."
|
||||
readOnly={shape.props.checked}
|
||||
value={shape.props.text}
|
||||
onChange={(e) =>
|
||||
this.editor.updateShape<IMyInteractiveShape>({
|
||||
id: shape.id,
|
||||
type: 'my-interactive-shape',
|
||||
props: { text: e.currentTarget.value },
|
||||
})
|
||||
}
|
||||
// [c]
|
||||
onPointerDown={(e) => {
|
||||
if (!shape.props.checked) {
|
||||
e.stopPropagation()
|
||||
}
|
||||
}}
|
||||
onTouchStart={(e) => {
|
||||
if (!shape.props.checked) {
|
||||
e.stopPropagation()
|
||||
}
|
||||
}}
|
||||
onTouchEnd={(e) => {
|
||||
if (!shape.props.checked) {
|
||||
e.stopPropagation()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</HTMLContainer>
|
||||
)
|
||||
}
|
||||
|
||||
// [5]
|
||||
indicator(shape: IMyInteractiveShape) {
|
||||
return <rect width={shape.props.w} height={shape.props.h} />
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
This is a custom shape, for a more in-depth look at how to create a custom shape,
|
||||
see our custom shape example.
|
||||
|
||||
[1]
|
||||
This is where we describe how our shape will render
|
||||
|
||||
[a] We need to set pointer-events to all so that we can interact with our shape. This CSS property is
|
||||
set to "none" off by default. We need to manually opt-in to accepting pointer events by setting it to
|
||||
'all' or 'auto'.
|
||||
|
||||
[b] We need to stop event propagation so that the editor doesn't select the shape
|
||||
when we click on the checkbox. The 'canvas container' forwards events that it receives
|
||||
on to the editor, so stopping propagation here prevents the event from reaching the canvas.
|
||||
|
||||
[c] If the shape is not checked, we stop event propagation so that the editor doesn't
|
||||
select the shape when we click on the input. If the shape is checked then we allow that event to
|
||||
propagate to the canvas and then get sent to the editor, triggering clicks or drags as usual.
|
||||
|
||||
*/
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
export const calcReadingTime = (text: string): string => {
|
||||
if (!text) return "∞ min read";
|
||||
|
||||
const wordsPerMinute = 300;
|
||||
const wordCount = text.split(/\s+/).length;
|
||||
const minutes = Math.ceil(wordCount / wordsPerMinute);
|
||||
|
||||
return `${minutes} min read`;
|
||||
};
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
import { createShapeId } from "tldraw";
|
||||
|
||||
export function createShapes(elementsInfo: any) {
|
||||
const shapes = elementsInfo.map((element: any) => ({
|
||||
id: createShapeId(),
|
||||
type: 'html',
|
||||
x: element.x,
|
||||
y: element.y,
|
||||
props: {
|
||||
w: element.w,
|
||||
h: element.h,
|
||||
html: element.html,
|
||||
}
|
||||
}));
|
||||
return shapes;
|
||||
}
|
||||
12
vercel.json
12
vercel.json
|
|
@ -1,13 +1,9 @@
|
|||
{
|
||||
"buildCommand": "yarn build",
|
||||
"installCommand": "yarn install",
|
||||
"buildCommand": "npm run build",
|
||||
"installCommand": "npm install",
|
||||
"framework": "vite",
|
||||
"outputDirectory": "dist",
|
||||
"rewrites": [
|
||||
{
|
||||
"source": "/posts/(.*)",
|
||||
"destination": "/"
|
||||
},
|
||||
{
|
||||
"source": "/board/(.*)",
|
||||
"destination": "/"
|
||||
|
|
@ -19,10 +15,6 @@
|
|||
{
|
||||
"source": "/inbox",
|
||||
"destination": "/"
|
||||
},
|
||||
{
|
||||
"source": "/books",
|
||||
"destination": "/"
|
||||
}
|
||||
],
|
||||
"headers": [
|
||||
|
|
|
|||
|
|
@ -1,41 +1,26 @@
|
|||
import { markdownPlugin } from './build/markdownPlugin';
|
||||
import { defineConfig, loadEnv } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import wasm from "vite-plugin-wasm";
|
||||
import topLevelAwait from "vite-plugin-top-level-await";
|
||||
import { viteStaticCopy } from 'vite-plugin-static-copy';
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
|
||||
export default defineConfig({
|
||||
envPrefix: ['VITE_'],
|
||||
plugins: [
|
||||
react(),
|
||||
wasm(),
|
||||
topLevelAwait(),
|
||||
markdownPlugin,
|
||||
viteStaticCopy({
|
||||
targets: [
|
||||
{
|
||||
src: 'src/posts/',
|
||||
dest: '.'
|
||||
}
|
||||
]
|
||||
})
|
||||
],
|
||||
envPrefix: ["VITE_"],
|
||||
plugins: [react()],
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
host: "0.0.0.0",
|
||||
port: 5173,
|
||||
},
|
||||
build: {
|
||||
sourcemap: true,
|
||||
},
|
||||
base: '/',
|
||||
publicDir: 'src/public',
|
||||
base: "/",
|
||||
publicDir: "src/public",
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': '/src',
|
||||
"@": "/src",
|
||||
},
|
||||
},
|
||||
define: {
|
||||
'import.meta.env.VITE_WORKER_URL': JSON.stringify(process.env.VITE_WORKER_URL)
|
||||
}
|
||||
"import.meta.env.VITE_WORKER_URL": JSON.stringify(
|
||||
process.env.VITE_WORKER_URL
|
||||
),
|
||||
},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -14,7 +14,6 @@ import { Environment } from './types'
|
|||
import { ChatBoxShape } from '@/shapes/ChatBoxShapeUtil'
|
||||
import { VideoChatShape } from '@/shapes/VideoChatShapeUtil'
|
||||
import { EmbedShape } from '@/shapes/EmbedShapeUtil'
|
||||
import GSet from 'crdts/src/G-Set'
|
||||
|
||||
// add custom shapes and bindings here if needed:
|
||||
export const customSchema = createTLSchema({
|
||||
|
|
@ -91,9 +90,8 @@ export class TldrawDurableObject {
|
|||
})
|
||||
.post('/room/:roomId', async (request) => {
|
||||
const records = await request.json() as TLRecord[]
|
||||
const mergedRecords = await this.mergeCrdtState(records)
|
||||
|
||||
return new Response(JSON.stringify(Array.from(mergedRecords)), {
|
||||
return new Response(JSON.stringify(Array.from(records)), {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Access-Control-Allow-Origin': request.headers.get('Origin') || '*',
|
||||
|
|
@ -221,22 +219,6 @@ export class TldrawDurableObject {
|
|||
await this.r2.put(`rooms/${this.roomId}`, snapshot)
|
||||
}, 10_000)
|
||||
|
||||
async mergeCrdtState(records: TLRecord[]) {
|
||||
const room = await this.getRoom();
|
||||
const gset = new GSet<TLRecord>();
|
||||
|
||||
const store = room.getCurrentSnapshot();
|
||||
if (!store) {
|
||||
throw new Error('Room store not initialized');
|
||||
}
|
||||
|
||||
// First cast to unknown, then to TLRecord
|
||||
store.documents.forEach((record) => gset.add(record as unknown as TLRecord));
|
||||
|
||||
// Merge new records
|
||||
records.forEach((record: TLRecord) => gset.add(record));
|
||||
return gset.values();
|
||||
}
|
||||
|
||||
// Add CORS headers for WebSocket upgrade
|
||||
handleWebSocket(request: Request) {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ main = "worker/worker.ts"
|
|||
compatibility_date = "2024-07-01"
|
||||
name = "jeffemmett-canvas"
|
||||
account_id = "0e7b3338d5278ed1b148e6456b940913"
|
||||
zone_id = "45c200f8dc2a01852e41b9bb09eb7359"
|
||||
|
||||
[vars]
|
||||
# Environment variables are managed in Cloudflare Dashboard
|
||||
|
|
|
|||
Loading…
Reference in New Issue