-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
41 lines (36 loc) · 1.21 KB
/
index.ts
File metadata and controls
41 lines (36 loc) · 1.21 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
/**
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
/**
* @param app app ID, e.g. "mail"
* @param key name of the property
* @param fallback optional parameter to use as default value
* @throws if the key can't be found
*/
export function loadState<T>(app: string, key: string, fallback?: T): T {
const selector = `#initial-state-${app}-${key}`
if (window._nc_initial_state?.has(selector)) {
return window._nc_initial_state.get(selector) as T
} else if (!window._nc_initial_state) {
window._nc_initial_state = new Map<string, unknown>()
}
const elem = document.querySelector<HTMLInputElement>(selector)
if (elem === null) {
if (fallback !== undefined) {
return fallback
}
throw new Error(`Could not find initial state ${key} of ${app}`)
}
try {
const parsedValue = JSON.parse(atob(elem.value))
window._nc_initial_state.set(selector, parsedValue)
return parsedValue
} catch (error) {
console.error('[@nextcloud/initial-state] Could not parse initial state', { key, app, error })
if (fallback !== undefined) {
return fallback
}
throw new Error(`Could not parse initial state ${key} of ${app}`, { cause: error })
}
}