-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathLocationProvider.tsx
More file actions
217 lines (184 loc) · 6.96 KB
/
LocationProvider.tsx
File metadata and controls
217 lines (184 loc) · 6.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import { type ISelectionParams, type ISynctexBlock, isSameBlock } from "@fluffylabs/links-metadata";
import { type ReactNode, createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
import { deserializeLegacyLocation } from "../../utils/deserializeLegacyLocation";
import { type IMetadataContext, MetadataContext } from "../MetadataProvider/MetadataProvider";
import { useGetLocationParamsToHash } from "./hooks/useGetLocationParamsToHash";
import type { ILocationParams, SearchParams } from "./types";
import {
BASE64_VALIDATION_REGEX,
SEGMENT_SEPARATOR,
SELECTION_DECOMPOSE_PATTERN,
SELECTION_SEGMENT_INDEX,
VERSION_SEGMENT_INDEX,
} from "./utils/constants";
import { locationParamsToHash } from "./utils/locationParamsToHash";
export interface ILocationContext {
locationParams: ILocationParams;
setLocationParams: (newParams: ILocationParams) => void;
synctexBlocksToSelectionParams: (blocks: ISynctexBlock[]) => ISelectionParams;
getHashFromLocationParams: (params: ILocationParams) => string;
}
interface ILocationProviderProps {
children: ReactNode;
}
export const LocationContext = createContext<ILocationContext | null>(null);
export const useLocationContext = () => {
const context = useContext(LocationContext);
if (!context) {
throw new Error("useLocationContext must be used within a LocationProvider");
}
return context;
};
export function LocationProvider({ children }: ILocationProviderProps) {
const { metadata } = useContext(MetadataContext) as IMetadataContext;
const [locationParams, setLocationParams] = useState<ILocationParams>();
const { urlGetters } = useContext(MetadataContext) as IMetadataContext;
useEffect(() => {
if (
!window.location.hash.startsWith("#/") &&
BASE64_VALIDATION_REGEX.test(window.location.hash) &&
deserializeLegacyLocation(window.location.hash)
) {
window.location.replace(urlGetters.legacyReaderRedirect(window.location.hash));
}
}, [urlGetters]);
const handleSetLocationParams = useCallback(
(newParams?: ILocationParams) => {
if (!newParams) return;
const hash = locationParamsToHash(newParams, metadata);
window.location.hash = hash;
},
[metadata],
);
const { getHashFromLocationParams } = useGetLocationParamsToHash();
const handleHashChange = useCallback(() => {
const { rest: newHash, search, section } = extractSearchParams(window.location.hash);
if (!newHash.startsWith(SEGMENT_SEPARATOR)) {
const version = metadata.latest;
setLocationParams((params) => ({
...params,
version,
search,
section,
}));
handleSetLocationParams({ version, search, section });
return;
}
const rawParams = newHash.split(SEGMENT_SEPARATOR).slice(1);
const selectedVersion = rawParams[VERSION_SEGMENT_INDEX];
const fullVersion =
selectedVersion.length > 0
? Object.keys(metadata.versions).find((version) => version.startsWith(rawParams[VERSION_SEGMENT_INDEX])) ??
(metadata.nightly?.hash.startsWith(rawParams[VERSION_SEGMENT_INDEX]) ? metadata.nightly.hash : null)
: null;
if (!fullVersion) {
const version = metadata.latest;
setLocationParams((params) => ({
...params,
version,
search,
section,
}));
handleSetLocationParams({ version, search, section });
return;
}
const newLocationParams: ILocationParams = {
version: fullVersion,
search,
section,
};
if (rawParams[SELECTION_SEGMENT_INDEX]) {
const matchedHexSegments = [...rawParams[SELECTION_SEGMENT_INDEX].matchAll(SELECTION_DECOMPOSE_PATTERN)];
if (matchedHexSegments.length === 2) {
newLocationParams.selectionStart = decodePageNumberAndIndex(matchedHexSegments[0][0]);
newLocationParams.selectionEnd = decodePageNumberAndIndex(matchedHexSegments[1][0]);
}
}
// Update location but only if it has REALLY changed.
setLocationParams((params) => {
if (!isSameBlock(params?.selectionStart, newLocationParams.selectionStart)) {
return newLocationParams;
}
if (!isSameBlock(params?.selectionEnd, newLocationParams.selectionEnd)) {
return newLocationParams;
}
if (params?.version !== newLocationParams.version) {
return newLocationParams;
}
if (params?.search !== newLocationParams.search) {
return newLocationParams;
}
if (params?.section !== newLocationParams.section) {
return newLocationParams;
}
return params;
});
}, [handleSetLocationParams, metadata]);
const synctexBlocksToSelectionParams: ILocationContext["synctexBlocksToSelectionParams"] = useCallback((blocks) => {
const blockIds = blocks.map((block) => ({ pageNumber: block.pageNumber, index: block.index }));
const lowestBlockId = blockIds.reduce((result, blockId) => {
if (blockId.pageNumber < result.pageNumber) return blockId;
if (blockId.pageNumber === result.pageNumber && blockId.index < result.index) return blockId;
return result;
}, blockIds[0]);
const highestBlockId = blockIds.reduce((result, blockId) => {
if (blockId.pageNumber > result.pageNumber) return blockId;
if (blockId.pageNumber === result.pageNumber && blockId.index > result.index) return blockId;
return result;
}, blockIds[0]);
return {
selectionStart: lowestBlockId,
selectionEnd: highestBlockId,
};
}, []);
useEffect(() => {
window.addEventListener("hashchange", handleHashChange);
handleHashChange();
return () => {
window.removeEventListener("hashchange", handleHashChange);
};
}, [handleHashChange]);
const context = useMemo(() => {
if (!locationParams) {
return null;
}
return {
locationParams,
setLocationParams: handleSetLocationParams,
synctexBlocksToSelectionParams,
getHashFromLocationParams,
};
}, [locationParams, handleSetLocationParams, synctexBlocksToSelectionParams, getHashFromLocationParams]);
if (!context) {
return null;
}
return <LocationContext.Provider value={context}>{children}</LocationContext.Provider>;
}
function decodePageNumberAndIndex(s: string) {
if (s.length > 6) throw new Error("Pass exactly 6 hex characters");
const fromHex = (s: string) => Number(`0x${s}`);
const pageNumber = fromHex(s.substring(0, 2));
let index = fromHex(s.substring(2, 4));
index += fromHex(s.substring(4, 6)) << 8;
return { pageNumber, index };
}
function extractSearchParams(hash: string): SearchParams {
// skip the leading '/'
const [rest, searchParams] = hash.substring(1).split("?");
const result = {
rest,
v: undefined,
search: undefined,
section: undefined,
};
if (!searchParams) {
return result;
}
for (const v of searchParams.split("&")) {
const [key, val] = v.split("=");
if (key in result) {
(result as { [key: string]: string | undefined })[key] = decodeURIComponent(val);
}
}
return result;
}