Skip to content

Commit cb5a4c4

Browse files
committed
Shareable url
1 parent ab47f5f commit cb5a4c4

File tree

3 files changed

+43
-7
lines changed

3 files changed

+43
-7
lines changed

playground/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
"@code-hike/mdx": "^0.5.1",
1212
"@mdx-js/mdx": "^2.1.1",
1313
"@monaco-editor/react": "^4.4.5",
14+
"lz-string": "^1.4.4",
1415
"react": "^17.0.2",
1516
"react-dom": "^17.0.2",
1617
"react-error-boundary": "^3.1.4"

playground/src/app.jsx

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import { useState } from "react";
1+
import React, { useState } from "react";
22
import { Editor } from "./editor";
3+
import { readHash, writeHash } from "./hash";
34
import { Preview } from "./preview";
45

56
const defaultCode = `
@@ -14,15 +15,22 @@ print("This is Code Hike")
1415
1516
`;
1617

17-
const defaultInput = {
18-
mdx: defaultCode,
19-
css: ".preview-container { border: 1px solid blue; }",
20-
config: { lineNumbers: false, showCopyButton: false },
21-
};
22-
2318
function App() {
19+
const defaultInput = React.useMemo(() => {
20+
return (
21+
readHash() || {
22+
mdx: defaultCode,
23+
css: ".preview-container { border: 1px solid blue; }",
24+
config: { lineNumbers: false, showCopyButton: false },
25+
}
26+
);
27+
}, []);
2428
const [input, setInput] = useState(defaultInput);
2529

30+
React.useEffect(() => {
31+
writeHash(input);
32+
}, [input]);
33+
2634
return (
2735
<div className="app">
2836
<header>

playground/src/hash.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import LZString from "lz-string";
2+
3+
export function toHash(input) {
4+
return LZString.compressToEncodedURIComponent(JSON.stringify(input));
5+
}
6+
7+
export function fromHash(hash) {
8+
return JSON.parse(LZString.decompressFromEncodedURIComponent(hash));
9+
}
10+
11+
export function writeHash(input) {
12+
const hash = toHash(input);
13+
window.location.hash = hash;
14+
}
15+
16+
export function readHash() {
17+
const hash = document.location.hash.slice(1);
18+
if (!hash) {
19+
return null;
20+
}
21+
22+
try {
23+
return fromHash(hash);
24+
} catch {
25+
return {};
26+
}
27+
}

0 commit comments

Comments
 (0)