mirror of
https://github.com/yu-i-i/overleaf-cep.git
synced 2026-11-12 21:23:45 +01:00
* save doc to session storage when offline * scope offline doc backup key to user id * clear offline doc backups on logout * handle anonymous users * include trackChanges GitOrigin-RevId: 3fe6a1523cb10cf76a1fcf4ee46790f6673bd84f
65 lines
1.7 KiB
TypeScript
65 lines
1.7 KiB
TypeScript
/**
|
|
* sessionStorage can throw browser exceptions, for example if it is full.
|
|
* We don't use sessionStorage for anything critical, so in that case just fail gracefully.
|
|
*/
|
|
|
|
import { debugConsole } from '@/utils/debugging'
|
|
|
|
/**
|
|
* Catch, log and otherwise ignore errors.
|
|
*
|
|
* @param {function} fn sessionStorage function to call
|
|
* @param {string?} key Key passed to the sessionStorage function (if any)
|
|
* @param {any?} value Value passed to the sessionStorage function (if any)
|
|
*/
|
|
const callSafe = function (
|
|
fn: (...args: any) => any,
|
|
key?: string,
|
|
value?: any
|
|
) {
|
|
try {
|
|
return fn(key, value)
|
|
} catch (e) {
|
|
debugConsole.error('sessionStorage exception', e)
|
|
return null
|
|
}
|
|
}
|
|
|
|
const getItem = function (key: string) {
|
|
const value = sessionStorage.getItem(key)
|
|
return value === null ? null : JSON.parse(value)
|
|
}
|
|
|
|
const setItem = function (key: string, value: any) {
|
|
sessionStorage.setItem(key, JSON.stringify(value))
|
|
}
|
|
|
|
const clear = function () {
|
|
sessionStorage.clear()
|
|
}
|
|
|
|
const removeItem = function (key: string) {
|
|
return sessionStorage.removeItem(key)
|
|
}
|
|
|
|
const removeByPrefix = function (prefix: string) {
|
|
const keys = []
|
|
for (let i = 0; i < sessionStorage.length; i++) {
|
|
const key = sessionStorage.key(i)
|
|
if (key !== null && key.startsWith(prefix)) {
|
|
keys.push(key)
|
|
}
|
|
}
|
|
keys.forEach(key => sessionStorage.removeItem(key))
|
|
}
|
|
|
|
const customSessionStorage = {
|
|
getItem: (key: string) => callSafe(getItem, key),
|
|
setItem: (key: string, value: any) => callSafe(setItem, key, value),
|
|
clear: () => callSafe(clear),
|
|
removeItem: (key: string) => callSafe(removeItem, key),
|
|
removeByPrefix: (prefix: string) => callSafe(removeByPrefix, prefix),
|
|
}
|
|
|
|
export default customSessionStorage
|