Skip to content

Commit

Permalink
fix(open cdb): move window api to useeffect (#362)
Browse files Browse the repository at this point in the history
  • Loading branch information
danilowoz authored Feb 8, 2022
1 parent 17355ee commit 7b40dc2
Showing 1 changed file with 15 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,23 +38,32 @@ const getFileParameters = (
export const UnstyledOpenInCodeSandboxButton: React.FC<
React.HtmlHTMLAttributes<unknown>
> = ({ children, ...props }) => {
const [paramsValues, setParamsValues] = React.useState("");
const { sandpack } = useSandpack();
const formRef = React.useRef<HTMLFormElement>(null);

const [paramsValues, setParamsValues] = React.useState<URLSearchParams>();

React.useEffect(
function debounce() {
const timer = setTimeout(() => {
const params = getFileParameters(sandpack.files, sandpack.environment);

setParamsValues(params);
const searchParams = new URLSearchParams({
parameters: params,
query: new URLSearchParams({
file: sandpack.activePath,
"from-sandpack": "true",
}).toString(),
});

setParamsValues(searchParams);
}, 600);

return (): void => {
clearTimeout(timer);
};
},
[sandpack.environment, sandpack.files]
[sandpack.activePath, sandpack.environment, sandpack.files]
);

// Register the usage of the codesandbox link
Expand All @@ -63,19 +72,11 @@ export const UnstyledOpenInCodeSandboxButton: React.FC<
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const searchParams = new URLSearchParams({
parameters: paramsValues,
query: new URLSearchParams({
file: sandpack.activePath,
"from-sandpack": "true",
}).toString(),
});

/**
* This is a safe limit to avoid too long requests (401),
* as all parameters are attached in the URL
*/
if (paramsValues.length > 1500) {
if ((paramsValues?.get?.("parameters")?.length ?? 0) > 1500) {
return (
<button
onClick={(): void => formRef.current?.submit()}
Expand All @@ -84,7 +85,7 @@ export const UnstyledOpenInCodeSandboxButton: React.FC<
>
<form ref={formRef} action={CSB_URL} method="POST" target="_blank">
{Array.from(
searchParams as unknown as Array<[string, string]>,
paramsValues as unknown as Array<[string, string]>,
([k, v]) => (
<input key={k} name={k} type="hidden" value={v} />
)
Expand All @@ -97,7 +98,7 @@ export const UnstyledOpenInCodeSandboxButton: React.FC<

return (
<a
href={`${CSB_URL}?${searchParams.toString()}`}
href={`${CSB_URL}?${paramsValues?.toString()}`}
rel="noreferrer noopener"
target="_blank"
title="Open in CodeSandbox"
Expand Down

0 comments on commit 7b40dc2

Please sign in to comment.