codo_textarea wip

This commit is contained in:
dylan
2024-03-31 21:25:54 -07:00
parent b88bd7fe1e
commit ef62037515
6 changed files with 73 additions and 15 deletions

View File

@@ -9,16 +9,45 @@ type Pico8ConsoleImperatives = {
export const Pico8Console = forwardRef((props: { carts: PicoCart[] }, forwardedRef: ForwardedRef<Pico8ConsoleImperatives>) => {
const {carts} = props;
const [playing, setPlaying] = useState(false);
const playingRef = useRef(false);
const ref = useRef<HTMLDivElement>(null);
const listeners = useRef<Partial<{
keydown: null | ((ev: KeyboardEvent) => void)
}>>({});
const [handle, setHandle] = useState<PicoPlayerHandle | null>(null);
const attachConsole = useCallback(async () => {
const picoConsole = await makePicoConsole({
carts,
});
const codoTextarea: HTMLTextAreaElement = (picoConsole.rawModule as any).codo_textarea;
picoConsole.canvas.addEventListener('click', () => {
codoTextarea.focus();
codoTextarea.select();
})
if (ref.current) {
ref.current.appendChild(picoConsole.canvas);
ref.current.appendChild(codoTextarea);
}
setHandle(picoConsole);
listeners.current.keydown = function (event) {
console.log("keydown", event.key);
if (!playingRef.current) {
return;
}
console.log(picoConsole.state);
if (picoConsole.state.hasFocus) {
console.log("hasFocus");
// block only cursors, M R P, tab
if (["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "M", "R", "P", "m", "r", "p", "Tab"].includes(event.key)) {
console.log("preventDefault");
event.preventDefault();
}
}
};
document.addEventListener('keydown',
listeners.current.keydown,
{passive: false}
);
}, [carts]);
useImperativeHandle(forwardedRef, () => ({
getPicoConsoleHandle() {
@@ -26,12 +55,17 @@ export const Pico8Console = forwardRef((props: { carts: PicoCart[] }, forwardedR
}
}), [handle]);
useEffect(() => {
if (playing) {
if (playing && playingRef.current) {
attachConsole();
return () => {
playingRef.current = false;
if (ref.current) {
ref.current.innerHTML = "";
}
if (listeners.current.keydown) {
document.removeEventListener("keydown", listeners.current.keydown);
listeners.current.keydown = null;
}
}
}
}, [playing, attachConsole]);
@@ -50,7 +84,7 @@ export const Pico8Console = forwardRef((props: { carts: PicoCart[] }, forwardedR
color: white;
cursor: pointer;
`}
onClick={() => {setPlaying(true)}}
onClick={() => {playingRef.current = true; setPlaying(true)}}
>
Play!
</div>