Skip to content

Commit

Permalink
feat: support url search param (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
ZLY201 committed Nov 4, 2023
1 parent 708bd47 commit 47409cf
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
2 changes: 2 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import settingList from '@src/utils/setting';
import Question from '@src/modules/Question';
import localCache from '@src/utils/local-cache';
import Results from '@src/modules/Results';
import { setCurrentProblemForUrl } from '@src/utils/url';
import styles from './index.module.less';
import './global.less';

Expand Down Expand Up @@ -40,6 +41,7 @@ function App() {
context.currentProblem !== update.currentProblem
) {
updateCache(update.currentProblem.key);
setCurrentProblemForUrl(update.currentProblem.key);
}
setContext({
...context,
Expand Down
17 changes: 14 additions & 3 deletions src/utils/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import React from 'react';
import localCache from '@src/utils/local-cache';
import { getProblems, Problem } from '@src/utils/problems';
import { Setting } from '@src/utils/setting';
import {
getCurrentProblemFromUrl,
setCurrentProblemForUrl,
} from '@src/utils/url';

export type Context = {
setting: Setting;
Expand All @@ -13,12 +17,19 @@ export type SetContext = React.Dispatch<Partial<Context>>;

export function getContext(): Context {
const problems = getProblems();
const { currentProblem: key = problems[0].key } =
localCache.getProblemCacheJson();
const { currentProblem: key } = localCache.getProblemCacheJson();
const urlCurrentProblem = getCurrentProblemFromUrl();
const searchKey = urlCurrentProblem || key;
const currentProblem = problems.filter(
problem => problem.key === searchKey,
)[0];
if (currentProblem === undefined) {
setCurrentProblemForUrl(problems[0].key);
}
return {
setting: localCache.getSettingCache(),
problems,
currentProblem: problems.filter(problem => problem.key === key)[0]!,
currentProblem: currentProblem || problems[0],
};
}

Expand Down
14 changes: 14 additions & 0 deletions src/utils/url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const enum URL_SEARCH_PARAMS_KEY {
problem = 'problem',
}

export function getCurrentProblemFromUrl() {
const url = new URL(window.location.href);
return url.searchParams.get(URL_SEARCH_PARAMS_KEY.problem);
}

export function setCurrentProblemForUrl(key: string) {
const url = new URL(window.location.href);
url.searchParams.set(URL_SEARCH_PARAMS_KEY.problem, key);
window.history.pushState({}, '', url);
}

0 comments on commit 47409cf

Please sign in to comment.