Save playground state in URL, for easy sharing
fix ssr
This commit is contained in:
parent
f365cdef70
commit
35a6a0c4e5
|
@ -1,4 +1,4 @@
|
|||
import React, { FC, Fragment, useState } from "react";
|
||||
import React, { FC, Fragment, useState, useEffect } from "react";
|
||||
import ReactDOM from "react-dom";
|
||||
import { Path, useForm, UseFormRegister, useWatch } from "react-hook-form";
|
||||
import * as yup from "yup";
|
||||
|
@ -35,6 +35,7 @@ interface PlaygroundProps {
|
|||
/** If code is set, component becomes controlled */
|
||||
code?: string;
|
||||
onCodeChange?(expr: string): void;
|
||||
onSettingsChange?(settings: any): void;
|
||||
/** Should we show the editor? */
|
||||
showEditor?: boolean;
|
||||
}
|
||||
|
@ -205,6 +206,7 @@ export const SquigglePlayground: FC<PlaygroundProps> = ({
|
|||
showSummary = false,
|
||||
code: controlledCode,
|
||||
onCodeChange,
|
||||
onSettingsChange,
|
||||
showEditor = true,
|
||||
}) => {
|
||||
const [uncontrolledCode, setUncontrolledCode] = useState(
|
||||
|
@ -233,6 +235,11 @@ export const SquigglePlayground: FC<PlaygroundProps> = ({
|
|||
const vars = useWatch({
|
||||
control,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
onSettingsChange?.(vars);
|
||||
}, [vars]);
|
||||
|
||||
const chartSettings = {
|
||||
start: Number(vars.diagramStart),
|
||||
stop: Number(vars.diagramStop),
|
||||
|
|
|
@ -2,7 +2,36 @@ import React from "react";
|
|||
import Layout from "@theme/Layout";
|
||||
import { SquigglePlayground } from "../components/SquigglePlayground";
|
||||
|
||||
function getHashData() {
|
||||
if (typeof window === "undefined") {
|
||||
return {};
|
||||
}
|
||||
try {
|
||||
return JSON.parse(window.decodeURIComponent(window.location.hash.slice(1)));
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function setHashData(Data) {
|
||||
window.location.hash = window.encodeURIComponent(
|
||||
JSON.stringify({ ...getHashData(), ...Data })
|
||||
);
|
||||
}
|
||||
|
||||
export default function PlaygroundPage() {
|
||||
const playgroundProps = {
|
||||
initialSquiggleString: "normal(0,1)",
|
||||
height: 700,
|
||||
showTypes: true,
|
||||
...getHashData(),
|
||||
onCodeChange: (code) => setHashData({ initialSquiggleString: code }),
|
||||
onSettingsChange: (settings) => {
|
||||
const { showTypes, showControls, showSummary, showEditor } = settings;
|
||||
setHashData({ showTypes, showControls, showSummary, showEditor });
|
||||
},
|
||||
};
|
||||
return (
|
||||
<Layout title="Playground" description="Squiggle Playground">
|
||||
<div
|
||||
|
@ -10,11 +39,7 @@ export default function PlaygroundPage() {
|
|||
maxWidth: 2000,
|
||||
}}
|
||||
>
|
||||
<SquigglePlayground
|
||||
initialSquiggleString="normal(0,1)"
|
||||
height={700}
|
||||
showTypes={true}
|
||||
/>
|
||||
<SquigglePlayground {...playgroundProps} />
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
|
|
Loading…
Reference in New Issue
Block a user