Skip to content
This repository was archived by the owner on Sep 14, 2022. It is now read-only.

Commit fa0dcd1

Browse files
committed
feat: add sharable query params func (fixes #2)
1 parent dbd6192 commit fa0dcd1

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

src/App.tsx

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { Header } from "@/components/Header";
77
import { Fixed } from "@/components/Fixed";
88
import { loadDemoLinter, DemoLinter } from "@/lib/linter";
99
import { DEFAULT_CODE, DEFAULT_RULE_CONFIG } from "@/components/constants";
10+
import { queryParamsState } from "@/shared/query-params-state";
1011
import type { FC } from "react";
1112
import type { Linter } from "eslint";
1213
import "bootstrap/dist/css/bootstrap.min.css";
@@ -19,9 +20,10 @@ const parserOptions = {
1920
} as const;
2021

2122
export const App: FC = () => {
23+
const paramsState = queryParamsState.get();
2224
const [messages, setMessages] = useState<Linter.LintMessage[]>([]);
23-
const [code, setCode] = useState<string>(DEFAULT_CODE);
24-
const [rules, setRules] = useState(DEFAULT_RULE_CONFIG);
25+
const [code, setCode] = useState<string>(paramsState?.code || DEFAULT_CODE);
26+
const [rules, setRules] = useState(paramsState?.rules || DEFAULT_RULE_CONFIG);
2527
const [fixed, setFixed] = useState<string>("");
2628
const [linter, setLinter] = useState<DemoLinter | null>(null);
2729

@@ -43,12 +45,14 @@ export const App: FC = () => {
4345
<Container>
4446
<Row>
4547
<Col md={12}>
46-
<h5> Code</h5>
4748
<Tabs>
4849
<Tab eventKey="code" title="Code">
4950
<Editor
50-
initial={DEFAULT_CODE}
51-
onChange={setCode}
51+
initial={queryParamsState.get().code || DEFAULT_CODE}
52+
onChange={(code) => {
53+
queryParamsState.set({ code, rules });
54+
setCode(code);
55+
}}
5256
messages={messages}
5357
/>
5458
</Tab>
@@ -66,6 +70,7 @@ export const App: FC = () => {
6670
try {
6771
const rules = JSON.parse(rulesString);
6872
setRules(rules);
73+
queryParamsState.set({ code, rules });
6974
} catch {}
7075
}}
7176
/>

src/shared/query-params-state.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import queryString from "query-string";
2+
import type { Linter } from "eslint";
3+
4+
interface QueryParamsState {
5+
code?: string;
6+
rules?: Linter.RulesRecord;
7+
}
8+
9+
export const queryParamsState = {
10+
get(): QueryParamsState {
11+
try {
12+
const decoded = decodeURIComponent(
13+
escape(atob(location.hash.replace("#", "")))
14+
);
15+
return JSON.parse(decoded);
16+
} catch {}
17+
return {};
18+
},
19+
set(state: QueryParamsState): void {
20+
const encoded = btoa(unescape(encodeURIComponent(JSON.stringify(state))));
21+
location.hash = encoded;
22+
},
23+
};

0 commit comments

Comments
 (0)