Readme

tldraw example with builder, for consistent React versions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/** @jsxImportSource https://esm.sh/react@18.3.1 **/
import build from "https://esm.sh/build";
const ret = await build({
dependencies: {
"react-dom": "18.3.1",
"react": "18.3.1",
"tldraw": "2.3.0",
"@reecelucas/react-use-hotkeys": "2.0.0",
},
source: `
export * as ReactDOM from "react-dom";
export * as React from "react";
export * as tldraw from "tldraw";
import useHotkeys from "@reecelucas/react-use-hotkeys";
export { useHotkeys };
`,
});
const {
ReactDOM,
React,
tldraw,
useHotkeys,
} = await import(ret.url + "?bundle-deps");
const { useCallback, useRef, useEffect } = React;
const {
Tldraw,
useEditor,
useToasts,
createShapeId,
BaseBoxShapeUtil,
DefaultSpinner,
HTMLContainer,
SvgExportContext,
TLBaseShape,
TldrawUiIcon,
Vec,
stopEventPropagation,
toDomPrecision,
useIsEditing,
useValue,
sortByIndex,
} = tldraw;
function MakeRealButton() {
const editor = useEditor();
const { addToast } = useToasts();
const handleClick = useCallback(async () => {
try {
const selectedShapes = editor.getSelectedShapes();
if (selectedShapes.length === 0) throw Error("First select something to make real.");
const { maxX, midY } = editor.getSelectionPageBounds();
const text = `export default async function main(req: Request): Promise<Response> {
return new Response("Hello, World!", {
headers: { "Content-Type": "text/plain" },
});
}`;
let previewHeight = (540 * 2) / 3;
let previewWidth = (960 * 2) / 3;
// const highestPreview = selectedShapes
// .filter((s) => s.type === "preview")
// .sort(sortByIndex)
// .reverse()[0];
// if (highestPreview) {
// previewHeight = highestPreview.props.h;
// previewWidth = highestPreview.props.w;
// }
const prompt = `Make an HTTP Val that outputs HTML (there is no need to import stevekrouse/html).\n`
+ selectedShapes.filter((s) => s.type === "text").map((s) => s.props.text).join("\n");
const loadValName = selectedShapes.filter((s) =>
s.type === "preview" && s.props.finishedValName
).map((s) => s.props.finishedValName)[0] || "";
const newShapeId = createShapeId();
editor.createShape({
id: `${newShapeId}_preview`,
type: "preview",
x: maxX + 60,
y: midY - previewHeight / 2,
props: {
prompt,
loadValName,
w: previewWidth,
h: previewHeight,
iframeWidth: 800,
source: "",
},
meta: {},
});
} catch (e: any) {
console.error(e);
addToast({
title: "Something went wrong",
description: `${e.message.slice(0, 200)}`,
});
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
July 24, 2024