-
Notifications
You must be signed in to change notification settings - Fork 261
Expand file tree
/
Copy pathindex.jsx
More file actions
174 lines (162 loc) · 5.91 KB
/
index.jsx
File metadata and controls
174 lines (162 loc) · 5.91 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import { useState, useEffect, useRef } from "preact/hooks";
import { useLiveRegion } from '../hooks/useLiveRegion';
import CodeMirror, { EditorView } from "@uiw/react-codemirror";
import { javascript } from "@codemirror/lang-javascript";
import { cdnLibraryUrl, cdnSoundUrl, cdnWebGPUUrl } from "@/src/globals/globals";
import { CodeFrame } from "./frame";
import { CopyCodeButton } from "../CopyCodeButton";
import CircleButton from "../CircleButton";
import { Icon } from "../Icon";
/*
* A more featured code embed component that uses CodeMirror
*
* Props: {
* initialValue?: string;
* editable: boolean;
* previewable: boolean;
* previewHeight?: number;
* previewWidth?: number;
* base?: string;
* lazyLoad?: boolean;
* TODO: refactor this prop behavior
* allowSideBySide?: boolean
* fullWidth?: boolean
* includeSound?: boolean
* scripts?: string[]
* }
*/
export const CodeEmbed = (props) => {
const { ref: liveRegionRef, announce } = useLiveRegion();
const [rendered, setRendered] = useState(false);
const initialCode = props.initialValue ?? "";
// Source code from Google Docs sometimes uses a unicode non-breaking space
// instead of a normal one, but these break the code frame, so we replace them here.
// We also replace them in CodeFrame, but replacing here too ensures people don't
// accidentally copy-and-paste them out of the embedded editor.
const [codeString, setCodeString] = useState(
initialCode.replace(/\u00A0/g, " "),
);
let { previewWidth, previewHeight } = props;
const canvasMatch = /createCanvas\(\s*(\d+),\s*(\d+)\s*(?:,\s*(?:\w+\.)?(?:P2D|WEBGL|WEBGPU)\s*)?\)/m.exec(initialCode);
if (canvasMatch) {
previewWidth = previewWidth || parseFloat(canvasMatch[1]);
previewHeight = previewHeight || parseFloat(canvasMatch[2]);
}
const largeSketch = previewWidth && previewWidth > 770 - 60;
// Quick hack to make room for DOM that gets added below the canvas by default
const domMatch = /create(Button|Select|P|Div|Input|ColorPicker)/.exec(initialCode);
if (domMatch && previewHeight) {
previewHeight += 100;
}
const codeFrameRef = useRef(null);
const updateOrReRun = () => {
if (codeString === previewCodeString) {
setPreviewCodeString("");
requestAnimationFrame(() => setPreviewCodeString(codeString));
} else {
setPreviewCodeString(codeString);
}
announce("Sketch is running");
};
const [previewCodeString, setPreviewCodeString] = useState(codeString);
useEffect(() => {
setRendered(true);
// Includes p5.min.js script to be used by `CodeFrame` iframe(s)
if (!document.getElementById("p5ScriptTag")) {
const p5ScriptElement = document.createElement("script");
p5ScriptElement.id = "p5ScriptTag";
p5ScriptElement.src = cdnLibraryUrl;
document.head.appendChild(p5ScriptElement);
}
}, []);
if (!rendered) return <div className="code-placeholder" />;
return (
<div
className={`my-md flex w-full flex-col gap-[20px] overflow-hidden ${props.allowSideBySide ? "lg:flex-row" : ""} ${props.fullWidth ? "full-width" : ""}`}
>
{props.previewable ? (
<div
className={`ml-0 flex w-fit gap-[20px] ${largeSketch ? "flex-col" : (props.allowSideBySide ? "" : "flex-col lg:flex-row")}`}
>
<div>
<CodeFrame
jsCode={previewCodeString}
width={previewWidth}
height={previewHeight}
base={props.base}
frameRef={codeFrameRef}
lazyLoad={props.lazyLoad}
scripts={[
...(props.includeSound ? [cdnSoundUrl] : []),
...(props.includeWebGPU ? [cdnWebGPUUrl] : []),
...(props.scripts ?? []),
]}
/>
</div>
<div className={`flex gap-2.5 ${largeSketch ? "flex-row" : "md:flex-row lg:flex-col"}`}>
<CircleButton
className="bg-bg-gray-40"
onClick={updateOrReRun}
ariaLabel="Run sketch"
>
<Icon kind="play" />
</CircleButton>
<CircleButton
className="bg-bg-gray-40"
onClick={() => {
setPreviewCodeString("");
announce("Sketch stopped");
}}
ariaLabel="Stop sketch"
>
<Icon kind="stop" />
</CircleButton>
</div>
</div>
) : null}
<div className="code-editor-container relative w-full">
<CodeMirror
value={codeString}
theme="light"
width="100%"
minimalSetup={{
highlightSpecialChars: false,
history: false,
drawSelection: true,
syntaxHighlighting: true,
defaultKeymap: true,
historyKeymap: true,
}}
basicSetup={{
lineNumbers: false,
foldGutter: false,
autocompletion: false,
}}
indentWithTab={false}
extensions={[javascript(), EditorView.lineWrapping]}
onChange={(val) => setCodeString(val)}
editable={props.editable}
onCreateEditor={(editorView) =>
(editorView.contentDOM.ariaLabel = "Code Editor")
}
/>
<div className="absolute right-0 top-0 flex flex-col gap-xs p-xs md:flex-row">
<CopyCodeButton textToCopy={codeString || initialCode} />
<CircleButton
onClick={() => {
setCodeString(initialCode);
setPreviewCodeString(initialCode);
announce("Code reset to initial value.");
}}
ariaLabel="Reset code to initial value"
className="bg-white text-black"
>
<Icon kind="refresh" />
</CircleButton>
</div>
</div>
<span ref={liveRegionRef} aria-live="polite" class="sr-only" />
</div>
);
};
export default CodeEmbed;