Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/local storage #20

Merged
merged 5 commits into from
Nov 11, 2023
Merged
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
1,296 changes: 1,286 additions & 10 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,10 @@
"devDependencies": {
"@playwright/test": "1.39.0",
"@technologiestiftung/semantic-release-config": "1.2.4",
"@testing-library/react": "14.1.0",
"@types/lodash.debounce": "4.0.9",
"@types/node": "20.9.0",
"jsdom": "22.1.0",
"mkdirp": "3.0.1",
"netlify-cli": "17.1.0",
"shx": "0.3.4",
Expand Down
58 changes: 25 additions & 33 deletions src/components/Sandbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,51 +9,35 @@ import globals from "@types/p5/global.d.ts?raw";
import constants from "@types/p5/constants.d.ts?raw";
//@ts-ignore
import index from "@types/p5/index.d.ts?raw";
//@ts-ignore
import literals from "@types/p5/literals.d.ts?raw";
//@ts-ignore
import sound from "@types/p5/lib/addons/p5.sound.d.ts?raw";
import { useLocalStorage } from "../hooks/use-local-storage";
import { iframeSource } from "../lib/iframe-source";
interface SandboxProps {
title: string;
description: string;
initialCode: string;
disableStorage: boolean;
}

export default function Sandbox(props: SandboxProps) {
export default function Sandbox({ disableStorage, initialCode }: SandboxProps) {
const iframeRef = React.useRef(null);
const [code, setCode] = React.useState(props.initialCode);

const [code, setCode] = useLocalStorage(
"p5.inpayjamas.dev",
initialCode,
disableStorage,
);

const debouncedSetCode = debounce((value) => setCode(value), 500);

React.useEffect(() => {
console.log("code changed");
if (iframeRef.current) {
const iframe = iframeRef.current;

const source = /* html */ `
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/iframe.css">
<script src="${import.meta.env.PUBLIC_BASE_URL}/lib/p5.js"></script>

<style>
body {
font-family: "Inter", sans-serif;
overflow: hidden;
}
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
/* remove default padding */
padding: 0;
/* remove default margins */
margin: 0 auto;
}</style>
</head>
<body>
<div id="sketch"></div>
<script defer>${code}</script>
</body>
</html>
`;
const source = iframeSource(code);
const iframeParent = iframe.parentElement;

if (iframeParent) {
Expand Down Expand Up @@ -99,11 +83,19 @@ export default function Sandbox(props: SandboxProps) {
constants,
"@types/p5/constants.d.ts",
);
monaco.languages.typescript.javascriptDefaults.addExtraLib(
literals,
"@types/p5/literals.d.ts",
);

monaco.languages.typescript.javascriptDefaults.addExtraLib(
index,
"@types/p5/index.d.ts",
);
monaco.languages.typescript.javascriptDefaults.addExtraLib(
sound,
"@types/p5/lib/addons/p5.sound.d.ts",
);
monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
...monaco.languages.typescript.javascriptDefaults.getCompilerOptions(),
checkJs: true, // need this
Expand Down Expand Up @@ -144,7 +136,7 @@ export default function Sandbox(props: SandboxProps) {
tabSize: 2,
accessibilitySupport: "on",
}}
defaultValue={props.initialCode}
defaultValue={code}
onChange={handleEditorChange}
onMount={handleEditorDidMount}
beforeMount={handleEditorWillMount}
Expand Down
35 changes: 35 additions & 0 deletions src/hooks/use-local-storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import React from "react";

export function useLocalStorage(
key: string,
initialValue: string,
disableStorage: boolean,
): [string, React.Dispatch<React.SetStateAction<string>>] {
const [value, setValue] = React.useState(initialValue);
const [noStorage, setNoStorage] = React.useState(disableStorage);

React.useEffect(() => {
const urlParams = new URLSearchParams(window.location.search);
const noStorageParam = urlParams.get("disable-storage");
if (noStorageParam !== null) {
setNoStorage(noStorageParam === "true");
}
}, []);

React.useEffect(() => {
if (!noStorage) {
const storedValue = localStorage.getItem(key);
if (storedValue !== null) {
setValue(storedValue);
}
}
}, [noStorage]);

React.useEffect(() => {
if (!noStorage) {
localStorage.setItem(key, value);
}
}, [key, value, noStorage]);

return [value, setValue];
}
35 changes: 35 additions & 0 deletions src/lib/iframe-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
export function iframeSource(code: string) {
return /* html */ `
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/iframe.css">
<script src="${import.meta.env.PUBLIC_BASE_URL}/lib/p5.js"></script>

<style>
body {
font-family: system-ui, sans-serif;
overflow: hidden;
}
pre, code {
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', Menlo, Consolas, 'DejaVu Sans Mono', monospace;
font-weight: normal;
}
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
/* remove default padding */
padding: 0;
/* remove default margins */
margin: 0 auto;
}</style>
</head>
<body>
<div id="sketch"></div>
<script defer>${code}</script>
</body>
</html>
`;
}
1 change: 1 addition & 0 deletions src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import Sandbox from "../components/Sandbox.tsx";
<Sandbox
title="Draft"
description="draft"
disableStorage={false}
initialCode={`
//@ts-check
function setup(){
Expand Down
34 changes: 34 additions & 0 deletions test/iframe-source.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { expect, test } from "vitest";
import { iframeSource } from "../src/lib/iframe-source";

test("iframeSource returns a string", () => {
const result = iframeSource('console.log("Hello, World!");');
expect(typeof result).toBe("string");
});

test("iframeSource includes the passed code", () => {
const code = 'console.log("Hello, World!");';
const result = iframeSource(code);
expect(result).toContain(code);
});

test("iframeSource includes necessary HTML tags", () => {
const result = iframeSource('console.log("Hello, World!");');
expect(result).toContain("<!DOCTYPE html>");
expect(result).toContain("<html>");
expect(result).toContain("</html>");
expect(result).toContain("<head>");
expect(result).toContain("</head>");
expect(result).toContain("<body>");
expect(result).toContain("</body>");
expect(result).toContain('<div id="sketch">');
expect(result).toContain("</div>");
expect(result).toContain(
`<script src="${import.meta.env.PUBLIC_BASE_URL}/lib/p5.js">`,
);
expect(result).toContain("</script>");
expect(result).toContain("<script defer>");
expect(result).toContain("</script>");
expect(result).toContain("<style>");
expect(result).toContain("</style>");
});
36 changes: 36 additions & 0 deletions test/use-local-storage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { cleanup, renderHook } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useLocalStorage } from "../src/hooks/use-local-storage";

const mocks = vi.hoisted(() => {
return {
getItem: vi.fn(),
setItem: vi.fn(),
};
});

describe("useLocalStorage", () => {
afterEach(cleanup);
it("sets the initial value", () => {
const { result } = renderHook(() =>
useLocalStorage("test", "initial", false),
);
expect(result.current[0]).toBe("initial");
});

it("loads from local storage on mount", () => {
localStorage.setItem("test", "stored value");
const { result } = renderHook(() =>
useLocalStorage("test", "initial", false),
);
expect(result.current[0]).toBe("stored value");
});

it("does not load from local storage on mount when disableStorage is set", () => {
localStorage.setItem("test", "stored value");
const { result } = renderHook(() =>
useLocalStorage("test", "initial", true),
);
expect(result.current[0]).toBe("initial");
});
});
1 change: 1 addition & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { getViteConfig } from "astro/config";

export default getViteConfig({
test: {
environment: "jsdom",
exclude: [
"**/e2e/**",
"**/tests-examples/**",
Expand Down