Skip to content

Commit ee2a535

Browse files
committed
feat: save editor states in url
1 parent bff84cf commit ee2a535

File tree

4 files changed

+50
-3
lines changed

4 files changed

+50
-3
lines changed

package-lock.json

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
"codemirror": "5.53.2",
1414
"dom-accessibility-api": "^0.4.3",
1515
"lodash.debounce": "4.0.8",
16+
"lz-string": "^1.4.4",
1617
"pretty-format": "26.0.1",
1718
"react": "^16.13.1",
1819
"react-dom": "^16.13.1"

src/components/App.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,13 @@ import parser from '../parser';
88
import { initialValues } from '../constants';
99
import { useAppContext } from './Context';
1010
import HtmlPreview from './HtmlPreview';
11+
import state from '../lib/state';
12+
13+
const savedState = state.load();
1114

1215
function App() {
13-
const [html, setHtml] = useState(initialValues.html);
14-
const [js, setJs] = useState(initialValues.js);
16+
const [html, setHtml] = useState(savedState.html || initialValues.html);
17+
const [js, setJs] = useState(savedState.js || initialValues.js);
1518

1619
const {
1720
htmlEditorRef,
@@ -26,6 +29,7 @@ function App() {
2629
setParsed(parsed);
2730

2831
parsed.targets?.forEach((el) => el.classList.add('highlight'));
32+
state.save({ html, js });
2933

3034
return () => {
3135
parsed.targets?.forEach((el) => el.classList.remove('highlight'));
@@ -53,7 +57,7 @@ function App() {
5357
<div>
5458
<Editor
5559
mode="javascript"
56-
initialValue={initialValues.js}
60+
initialValue={js}
5761
onChange={setJs}
5862
ref={jsEditorRef}
5963
/>

src/lib/state.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import {
2+
compressToEncodedURIComponent,
3+
decompressFromEncodedURIComponent,
4+
} from 'lz-string';
5+
6+
function unindent(string) {
7+
return string.replace(/[ \t]*[\n][ \t]*/g, '\n');
8+
}
9+
10+
function save({ html, js }) {
11+
const state = [
12+
compressToEncodedURIComponent(unindent(html)),
13+
compressToEncodedURIComponent(unindent(js)),
14+
].join('&');
15+
16+
history.replaceState(null, '', window.location.pathname + '#' + state);
17+
}
18+
19+
function load() {
20+
const [htmlCompressed, jsCompressed] = window.location.hash
21+
.slice(1)
22+
.split('&');
23+
24+
console.log('load', { htmlCompressed, jsCompressed });
25+
26+
return {
27+
html: htmlCompressed && decompressFromEncodedURIComponent(htmlCompressed),
28+
js: jsCompressed && decompressFromEncodedURIComponent(jsCompressed),
29+
};
30+
}
31+
32+
const state = {
33+
save,
34+
load,
35+
};
36+
37+
export default state;

0 commit comments

Comments
 (0)