Skip to content

Commit

Permalink
feat(playground): add Reset button (#10934)
Browse files Browse the repository at this point in the history
* feat(playground): add Reset button

* fix(playground): remember initial content for reset

* fix(playground): hide "Reset" button on new playground

* fix(playground): clear should make Reset button disappear
  • Loading branch information
caugner authored May 2, 2024
1 parent afeb857 commit d316348
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions client/src/playground/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ export default function Playground() {
let [codeSrc, setCodeSrc] = useState<string | undefined>();
const [isEmpty, setIsEmpty] = useState<boolean>(true);
const subdomain = useRef<string>(crypto.randomUUID());
const [initialContent, setInitialContent] = useState<EditorContent | null>(
null
);
let { data: initialCode } = useSWRImmutable<EditorContent>(
!shared && gistId ? `/api/v1/play/${encodeURIComponent(gistId)}` : null,
async (url) => {
Expand Down Expand Up @@ -105,8 +108,13 @@ export default function Playground() {
const diaRef = useRef<HTMLDialogElement | null>(null);

useEffect(() => {
initialCode && store(SESSION_KEY, initialCode);
}, [initialCode]);
if (initialCode) {
store(SESSION_KEY, initialCode);
if (Object.values(initialCode).some(Boolean)) {
setInitialContent(structuredClone(initialCode));
}
}
}, [initialCode, setInitialContent]);

const getEditorContent = useCallback(() => {
const code = {
Expand Down Expand Up @@ -181,6 +189,17 @@ export default function Playground() {
setSearchParams([], { replace: true });
setCodeSrc(undefined);
setEditorContent({ html: HTML_DEFAULT, css: CSS_DEFAULT, js: JS_DEFAULT });
setInitialContent(null);

updateWithEditorContent();
};

const reset = async () => {
setEditorContent({
html: initialContent?.html || HTML_DEFAULT,
css: initialContent?.css || CSS_DEFAULT,
js: initialContent?.js || JS_DEFAULT,
});

updateWithEditorContent();
};
Expand All @@ -192,6 +211,13 @@ export default function Playground() {
}
};

const resetConfirm = async () => {
if (window.confirm("Do you really want to revert your changes?")) {
gleanClick(`${PLAYGROUND}: revert-click`);
await reset();
}
};

const updateWithEditorContent = () => {
const { html, css, js } = getEditorContent();
setIsEmpty(!html && !css && !js);
Expand Down Expand Up @@ -314,6 +340,16 @@ export default function Playground() {
>
clear
</Button>
{initialContent && (
<Button
type="secondary"
id="reset"
extraClasses="red"
onClickHandler={resetConfirm}
>
reset
</Button>
)}
</menu>
</aside>
<Editor
Expand Down

0 comments on commit d316348

Please sign in to comment.