Skip to content

Commit

Permalink
fix: Preserve extra params in URL (#170)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattcompiles committed Jun 25, 2020
1 parent 28b1f9a commit 3b1cabd
Show file tree
Hide file tree
Showing 9 changed files with 2,921 additions and 2,593 deletions.
2 changes: 2 additions & 0 deletions cypress/support/utils.js
Expand Up @@ -52,6 +52,7 @@ export const toggleSnippets = () =>
cy.get('[data-testid="toggleSnippets"]').click();

export const filterSnippets = (search) =>
// eslint-disable-next-line cypress/no-unnecessary-waiting
cy
.get('[data-testid="filterSnippets"]')
.type(search, { force: true })
Expand All @@ -74,6 +75,7 @@ export const assertSnippetCount = (count) =>

export const assertFirstFrameContains = (text) => {
getFirstFrame().then(($el) =>
// eslint-disable-next-line cypress/no-unnecessary-waiting
cy
.wrap($el.contents().find('body'))
.wait(WAIT_FOR_FRAME_TO_RENDER)
Expand Down
4 changes: 2 additions & 2 deletions src/Playroom/CodeEditor/CodeEditor.tsx
Expand Up @@ -103,7 +103,7 @@ export const CodeEditor = ({ code, onChange, previewCode, hints }: Props) => {
);

const [debouncedChange] = useDebouncedCallback(
(newCode) => onChange(newCode),
(newCode: string) => onChange(newCode),
100
);

Expand Down Expand Up @@ -218,6 +218,7 @@ export const CodeEditor = ({ code, onChange, previewCode, hints }: Props) => {
}, [highlightLineNumber]);

return (
// @ts-ignore
<ReactCodeMirror
editorDidMount={(editorInstance) => {
editorInstanceRef.current = editorInstance;
Expand All @@ -242,7 +243,6 @@ export const CodeEditor = ({ code, onChange, previewCode, hints }: Props) => {
}
});
}}
// @ts-ignore
options={{
mode: 'jsx',
autoCloseTags: true,
Expand Down
3 changes: 2 additions & 1 deletion src/Playroom/Preview.tsx
Expand Up @@ -25,7 +25,8 @@ export default ({ themes, components, FrameComponent }: PreviewProps) => {
(rawParams): PreviewState => {
if (rawParams.code) {
const result = JSON.parse(
lzString.decompressFromEncodedURIComponent(String(rawParams.code))
lzString.decompressFromEncodedURIComponent(String(rawParams.code)) ??
''
);

return {
Expand Down
4 changes: 3 additions & 1 deletion src/Playroom/PreviewPanel/PreviewPanel.tsx
Expand Up @@ -17,7 +17,9 @@ interface PreviewPanelProps {
export default ({ themes, visibleThemes }: PreviewPanelProps) => {
const defaultTheme =
visibleThemes && visibleThemes.length > 0 ? visibleThemes[0] : themes[0];
const [userSelectedTheme, setUserSelectedTheme] = useState();
const [userSelectedTheme, setUserSelectedTheme] = useState<
string | undefined
>();

const activeTheme = userSelectedTheme || defaultTheme;

Expand Down
15 changes: 9 additions & 6 deletions src/StoreContext/StoreContext.tsx
Expand Up @@ -12,9 +12,9 @@ import lzString from 'lz-string';
import dedent from 'dedent';
import { useDebouncedCallback } from 'use-debounce';

import { createUrl, CreateUrlOptions, Snippet } from '../../utils';
import { Snippet, compressParams } from '../../utils';
import { formatForInsertion, formatAndInsert } from '../utils/formatting';
import { getParamsFromQuery, replaceUrl } from '../utils/params';
import { getParamsFromQuery, updateUrlCode } from '../utils/params';
import { PlayroomProps } from '../Playroom/Playroom';
import { isValidLocation } from '../utils/cursor';
import playroomConfig from '../config';
Expand All @@ -30,8 +30,11 @@ const defaultPosition = 'bottom';

export type EditorPosition = 'bottom' | 'right' | 'undocked';

interface DebounceUpdateUrl
extends Partial<Omit<CreateUrlOptions, 'baseUrl'>> {}
interface DebounceUpdateUrl {
code?: string;
themes?: string[];
widths?: number[];
}

export interface CursorPosition {
line: number;
Expand Down Expand Up @@ -396,7 +399,7 @@ export const StoreProvider = ({
// they are also removed from the url. Replacing state
// with an empty string (returned from `createUrl`)
// does not do anything, so replacing with `#`
replaceUrl(createUrl({ ...params, paramType: playroomConfig.paramType }));
updateUrlCode(compressParams(params));
},
500
);
Expand All @@ -417,7 +420,7 @@ export const StoreProvider = ({
themes: parsedThemes,
widths: parsedWidths,
} = JSON.parse(
lzString.decompressFromEncodedURIComponent(String(params.code))
lzString.decompressFromEncodedURIComponent(String(params.code)) ?? ''
);

codeFromQuery = parsedCode;
Expand Down
16 changes: 15 additions & 1 deletion src/utils/params.ts
Expand Up @@ -6,7 +6,21 @@ import playroomConfig from '../config';

const history = createBrowserHistory();

export const replaceUrl = (url: string) => history.replace(url);
export function updateUrlCode(code: string) {
const { pathname } = history.location;

const existingQuery = getParamsFromQuery();

const newQuery = queryString.stringify({
...existingQuery,
code,
});

const params =
playroomConfig.paramType === 'hash' ? `#?${newQuery}` : `?${newQuery}`;

history.replace(`${pathname}${params}`);
}

export function getParamsFromQuery(location = history.location) {
try {
Expand Down
7 changes: 7 additions & 0 deletions utils/index.d.ts
Expand Up @@ -8,6 +8,13 @@ type Snippets = Snippet[];

type ParamType = 'hash' | 'search';

interface CompressParamsOptions {
code?: string;
themes?: string[];
widths?: number[];
}
export const compressParams: (options: CompressParamsOptions) => string;

interface CreateUrlOptions {
baseUrl?: string;
code?: string;
Expand Down
24 changes: 13 additions & 11 deletions utils/index.js
@@ -1,16 +1,21 @@
const lzString = require('lz-string');

const compressParams = ({ code, themes, widths }) => {
const data = JSON.stringify({
...(code ? { code } : {}),
...(themes ? { themes } : {}),
...(widths ? { widths } : {}),
});

return lzString.compressToEncodedURIComponent(data);
};

const createUrl = ({ baseUrl, code, themes, widths, paramType = 'hash' }) => {
let path = '';

if (code || themes || widths) {
const data = JSON.stringify({
...(code ? { code } : {}),
...(themes ? { themes } : {}),
...(widths ? { widths } : {}),
});
const compressedData = compressParams({ code, themes, widths });

const compressedData = lzString.compressToEncodedURIComponent(data);
path = `${paramType === 'hash' ? '#' : ''}?code=${compressedData}`;
}

Expand All @@ -27,12 +32,8 @@ const createPreviewUrl = ({ baseUrl, code, theme, paramType = 'hash' }) => {
let path = '';

if (code || theme) {
const data = JSON.stringify({
...(code ? { code } : {}),
...(theme ? { theme } : {}),
});
const compressedData = compressParams({ code, theme });

const compressedData = lzString.compressToEncodedURIComponent(data);
path = `/preview${paramType === 'hash' ? '#' : ''}?code=${compressedData}`;
}

Expand All @@ -46,6 +47,7 @@ const createPreviewUrl = ({ baseUrl, code, theme, paramType = 'hash' }) => {
};

module.exports = {
compressParams,
createUrl,
createPreviewUrl,
};

0 comments on commit 3b1cabd

Please sign in to comment.