Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ export default defineConfig({
],
host: true, // Allow access from non-localhost domains
cors: true, // Allow CORS (optional)
headers: {
"Access-Control-Allow-Origin": "*"
}
},
optimizeDeps: {
exclude: ['https']
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"build": "astro build && node scripts/patch-vercel-config.mjs",
"test": "bun run ./tests/sprigfuzzy.js",
"test:unit": "cross-env PUBLIC_MAX_ITERATIONS=2000 PUBLIC_MAX_LOOP_TIME_MS=1500 vitest"
},
Expand Down
30 changes: 30 additions & 0 deletions scripts/patch-vercel-config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { existsSync, readFileSync, writeFileSync } from 'node:fs'

const configPath = new URL('../.vercel/output/config.json', import.meta.url)

if (!existsSync(configPath)) process.exit(0)

const config = JSON.parse(readFileSync(configPath, 'utf8'))
const routes = Array.isArray(config.routes) ? config.routes : []
const astroAssetsRouteIndex = routes.findIndex((route) => route.src === '^/_astro/(.*)$')
const astroAssetsRoute = astroAssetsRouteIndex >= 0 ? routes[astroAssetsRouteIndex] : null

if (astroAssetsRoute) {
astroAssetsRoute.headers = {
...astroAssetsRoute.headers,
'Access-Control-Allow-Origin': 'null',
'Access-Control-Allow-Credentials': 'true',
'Cross-Origin-Resource-Policy': 'cross-origin',
}

routes.splice(astroAssetsRouteIndex, 1)

const filesystemIndex = routes.findIndex((route) => route.handle === 'filesystem')
if (filesystemIndex >= 0) {
routes.splice(filesystemIndex, 0, astroAssetsRoute)
} else {
routes.unshift(astroAssetsRoute)
}
}

writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`)
41 changes: 21 additions & 20 deletions src/components/big-interactive-pages/desktop-player.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {useEffect, useRef} from 'preact/hooks'
import { runGame } from '../../lib/engine'
import styles from './desktop-player.module.css'
import {
IoExpandOutline,
Expand All @@ -22,6 +21,9 @@ import {exitFullscreen, fullscreenElement, requestFullscreen} from "../../lib/ut
import Button from "../design-system/button";
import {VscLoading} from "react-icons/vsc";
import {upload, uploadState} from "../../lib/upload";
import SandboxedGameFrame from "./sandboxed-game-frame";
import type { SandboxedGameControllerHandle } from "../../lib/engine/sandbox-controller";
import { logInfo } from "../popups-etc/help";

interface DesktopPlayerProps {
code: string
Expand All @@ -33,17 +35,17 @@ interface DesktopPlayerProps {
}

export default function DesktopPlayer(props: DesktopPlayerProps) {
const screen = useRef<HTMLCanvasElement>(null)
const player = useRef<SandboxedGameControllerHandle | null>(null)
const outputArea = useRef<HTMLDivElement>(null);
const screenContainer = useRef<HTMLDivElement>(null);
const screenControls = useRef<HTMLDivElement>(null);
const playerVersion = useSignal(0);

// acts a bit like a timer; if >0, shake game canvas
// activated when a game is run to show it's being run
const screenShake = useSignal(0);

const onStop = async () => {
if (!screen.current) return;
if (cleanupRef.value) cleanupRef.value?.();
};

Expand All @@ -53,14 +55,13 @@ export default function DesktopPlayer(props: DesktopPlayerProps) {
});

const onRun = async () => {
if (!screen.current) return;
if (!player.current) return;
if (cleanupRef.value) cleanupRef.value?.();
errorLog.value = [];
const res = runGame(props.code, screen.current!, (error) => {
errorLog.value = [...errorLog.value, error];
});
logInfo.value = [];
player.current.run(props.code);

screen.current!.focus();
player.current.focus();
if (screenShake) {
screenShake.value++;
}
Expand All @@ -70,16 +71,12 @@ export default function DesktopPlayer(props: DesktopPlayerProps) {
}
}, 200);

cleanupRef.value = res?.cleanup;
if (res && res.error) {
console.error(res.error.raw);
errorLog.value = [...errorLog.value, res.error];
}
cleanupRef.value = () => player.current?.stop();
};

useEffect(() => {
onRun()
}, [props.code])
}, [props.code, playerVersion.value])

// mouse move timeout for auto-hiding fullscreen controls
const mouseMoveTimeout = useSignal(0);
Expand Down Expand Up @@ -166,8 +163,8 @@ export default function DesktopPlayer(props: DesktopPlayerProps) {
maxHeight: canvasScreenSize.value.maxHeight,
} : {}} className={styles.screenContainer}>
<div className={styles.canvasWrapper}>
<canvas
className={`${styles.screen} ${
<SandboxedGameFrame
class={`${styles.screen} ${
screenShake.value > 0 ? "shake" : ""
}`}
style={outputArea.current ? {
Expand All @@ -176,10 +173,14 @@ export default function DesktopPlayer(props: DesktopPlayerProps) {
width: (1.25 * canvasScreenSize.value.height),
maxWidth: "100%",
} : {}}
ref={screen}
tabIndex={0}
width="1000"
height="800"
onController={(controller) => {
player.current = controller;
playerVersion.value++;
}}
onError={(error) => {
console.error(error.raw);
errorLog.value = [...errorLog.value, error];
}}
/>
</div>
<div ref={screenControls} className={`${styles.screenControls} ${showFullscreenControls.value && styles.enabled}`}>
Expand Down
39 changes: 17 additions & 22 deletions src/components/big-interactive-pages/editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ import {
useSignalEffect,
} from "@preact/signals";
import { useEffect, useRef, useState} from "preact/hooks";
import { codeMirror, errorLog, isNewSaveStrat, muted, type PersistenceState, type RoomState, screenRef, cleanupRef, reviewState } from "../../lib/state";
import { codeMirror, errorLog, gamePlayerRef, isNewSaveStrat, muted, type PersistenceState, type RoomState, cleanupRef, reviewState } from "../../lib/state";
import EditorModal from "../popups-etc/editor-modal";
import { runGame, _performSyntaxCheck } from "../../lib/engine";
import { _performSyntaxCheck } from "../../lib/engine";
import DraftWarningModal from "../popups-etc/draft-warning";
import { debounce } from "throttle-debounce";
import Help from "../popups-etc/help";
import Help, { logInfo } from "../popups-etc/help";
import { collapseRanges } from "../../lib/codemirror/util";
import { defaultExampleCode } from "../../lib/examples";
import MigrateToast from "../popups-etc/migrate-toast";
Expand All @@ -33,6 +33,7 @@ import OutOfSpaceModal from "../popups-etc/out-of-space";
import RoomPasswordPopup from "../popups-etc/room-password";
import KeyBindingsModal from '../popups-etc/KeyBindingsModal'
import { PersistenceStateKind } from "../../lib/state";
import SandboxedGameFrame from "./sandboxed-game-frame";

let screenShakeSignal: Signal<number> | null = null;

Expand All @@ -47,16 +48,15 @@ const performSyntaxCheck = () => {

export const onRun = async () => {
foldAllTemplateLiterals();
if (!screenRef.value) return;
if (!gamePlayerRef.value) return;

if (cleanupRef.value) cleanupRef.value();
errorLog.value = [];
logInfo.value = [];
const code = codeMirror.value?.state.doc.toString() ?? "";
const res = runGame(code, screenRef.value, (error) => {
errorLog.value = [...errorLog.value, error];
});
gamePlayerRef.value.run(code);

screenRef.value.focus();
gamePlayerRef.value.focus();
if (screenShakeSignal) {
screenShakeSignal.value++;
}
Expand All @@ -66,11 +66,7 @@ export const onRun = async () => {
}
}, 200);

cleanupRef.value = res?.cleanup;
if (res && res.error) {
console.error(res.error.raw);
errorLog.value = [...errorLog.value, res.error];
}
cleanupRef.value = () => gamePlayerRef.value?.stop();
};

interface EditorProps {
Expand Down Expand Up @@ -449,17 +445,13 @@ export default function Editor({ persistenceState, cookies, roomState, review }:
}, []);

useEffect(() => {
screenRef.value = screen.current;

screenShakeSignal = screenShake;
});
useEffect(() => () => cleanupRef.value?.(), []);
// We like running games!
const screen = useRef<HTMLCanvasElement>(null);
const screenShake = useSignal(0);

const onStop = async () => {
if (!screen.current) return;
if (cleanupRef.value) cleanupRef.value?.();
};

Expand Down Expand Up @@ -661,7 +653,7 @@ export default function Editor({ persistenceState, cookies, roomState, review }:
maxHeight: canvasScreenSize.value.maxHeight,
} : {} }>
<div class={styles.canvasWrapper}>
<canvas
<SandboxedGameFrame
class={`${styles.screen} ${
screenShake.value > 0 ? "shake" : ""
}`}
Expand All @@ -671,10 +663,13 @@ export default function Editor({ persistenceState, cookies, roomState, review }:
width: (1.25 * canvasScreenSize.value.height),
maxWidth: "100%",
}: { } }
ref={screen}
tabIndex={0}
width="1000"
height="800"
onController={(controller) => {
gamePlayerRef.value = controller;
}}
onError={(error) => {
console.error(error.raw);
errorLog.value = [...errorLog.value, error];
}}
/>
</div>
<div ref={screenControls} class={styles.screenControls}>
Expand Down
26 changes: 17 additions & 9 deletions src/components/big-interactive-pages/mobile-player.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { useSignal } from '@preact/signals'
import { useEffect, useRef } from 'preact/hooks'
import { runGame } from '../../lib/engine'
import styles from './mobile-player.module.css'
import {exitFullscreen, fullscreenElement, requestFullscreen} from "../../lib/utils/fullscreen";
import SandboxedGameFrame from './sandboxed-game-frame'
import type { SandboxedGameControllerHandle } from '../../lib/engine/sandbox-controller'

interface MobilePlayerProps {
code: string
Expand All @@ -11,23 +12,23 @@ interface MobilePlayerProps {
}

export default function MobilePlayer(props: MobilePlayerProps) {
const screen = useRef<HTMLCanvasElement>(null)
const player = useRef<SandboxedGameControllerHandle | null>(null)
const cleanup = useRef<(() => void) | null>(null);
const playerVersion = useSignal(0);

const run = () => {
if (cleanup.current) cleanup.current();
const res = runGame(props.code, screen.current!, (_) => { })
if (res?.error) console.error(res.error.raw)
cleanup.current = res!.cleanup;
return res?.cleanup
player.current?.run(props.code)
cleanup.current = () => player.current?.stop();
return cleanup.current
}

useEffect(() => {
return run()
}, [props.code])
}, [props.code, playerVersion.value])

const pressKey = (key: string) => {
screen.current!.dispatchEvent(new KeyboardEvent('keydown', { key }))
player.current?.sendKey(key)
}

const keyTouches = useSignal<Record<string, number>>({})
Expand Down Expand Up @@ -79,7 +80,14 @@ export default function MobilePlayer(props: MobilePlayerProps) {

<div class={styles.player} id="player">
<div class={styles.screenContainer}>
<canvas class={styles.screen} ref={screen} width='1000' height='800' />
<SandboxedGameFrame
class={styles.screen}
onController={(controller) => {
player.current = controller;
playerVersion.value++;
}}
onError={(error) => console.error(error.raw)}
/>
</div>


Expand Down
57 changes: 57 additions & 0 deletions src/components/big-interactive-pages/sandboxed-game-frame.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { useEffect, useRef } from 'preact/hooks'
import type { JSX } from 'preact'
import { bitmaps, muted, type NormalizedError } from '../../lib/state'
import { SandboxedGameController, type SandboxedGameControllerHandle } from '../../lib/engine/sandbox-controller'
import { logInfo } from '../popups-etc/help'

interface SandboxedGameFrameProps {
class?: string
style?: JSX.CSSProperties
title?: string
onController?: (controller: SandboxedGameControllerHandle | null) => void
onError?: (error: NormalizedError) => void
}

export default function SandboxedGameFrame(props: SandboxedGameFrameProps) {
const iframe = useRef<HTMLIFrameElement>(null)
const controller = useRef<SandboxedGameController | null>(null)
const sandboxFlags = import.meta.env.DEV ? 'allow-scripts allow-same-origin' : 'allow-scripts'

useEffect(() => {
if (!iframe.current) return

controller.current = new SandboxedGameController(iframe.current, {
onError: props.onError,
onConsole: ({ args, nums, isErr }) => {
logInfo.value = [...logInfo.value, { args, nums, isErr }]
},
onBitmaps: (_bitmaps) => {
bitmaps.value = _bitmaps
},
})
props.onController?.(controller.current)

return () => {
controller.current?.destroy()
controller.current = null
props.onController?.(null)
}
}, [])

useEffect(() => {
controller.current?.setMuted(muted.value)
}, [muted.value])

return (
<iframe
ref={iframe}
class={props.class}
style={props.style}
src="/game-sandbox"
title={props.title ?? 'Sprig game sandbox'}
sandbox={sandboxFlags}
referrerPolicy="no-referrer"
onLoad={() => controller.current?.markReady()}
/>
)
}
Loading
Loading