From 35a6a0c4e5518bd643c7ab98e1f23afa8d2335ee Mon Sep 17 00:00:00 2001 From: Recursing Date: Tue, 21 Jun 2022 23:09:42 +0200 Subject: [PATCH] Save playground state in URL, for easy sharing fix ssr --- .../src/components/SquigglePlayground.tsx | 9 ++++- packages/website/src/pages/playground.js | 35 ++++++++++++++++--- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/packages/components/src/components/SquigglePlayground.tsx b/packages/components/src/components/SquigglePlayground.tsx index cf0544f6..f67220f9 100644 --- a/packages/components/src/components/SquigglePlayground.tsx +++ b/packages/components/src/components/SquigglePlayground.tsx @@ -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 = ({ showSummary = false, code: controlledCode, onCodeChange, + onSettingsChange, showEditor = true, }) => { const [uncontrolledCode, setUncontrolledCode] = useState( @@ -233,6 +235,11 @@ export const SquigglePlayground: FC = ({ const vars = useWatch({ control, }); + + useEffect(() => { + onSettingsChange?.(vars); + }, [vars]); + const chartSettings = { start: Number(vars.diagramStart), stop: Number(vars.diagramStop), diff --git a/packages/website/src/pages/playground.js b/packages/website/src/pages/playground.js index c3760c10..efbbac13 100644 --- a/packages/website/src/pages/playground.js +++ b/packages/website/src/pages/playground.js @@ -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 (
- +
);