2022-04-14 02:12:38 +03:00
const defaults = {
2022-05-05 21:30:21 +03:00
"server:apiBase" : ` ${ window . location . origin } /api/v1 ` ,
"server:gatewayBase" : ` ${ location . protocol === "https:" ? "wss" : "ws" } :// ${ location . host } /gateway ` ,
"auth:token" : "" ,
2022-08-04 02:00:55 +03:00
"ui:doAnimations" : true ,
"ui:theme" : "dark" ,
"state:openChannelId" : - 1 ,
"log:Gateway" : false ,
"log:Store" : false ,
"ui:stateful:presistSelectedChannel" : true
2022-04-14 02:12:38 +03:00
} ;
2022-05-05 16:31:10 +03:00
const store = new Map ( Object . entries ( defaults ) ) ;
const persistentProvider = localStorage ;
2022-05-06 01:55:21 +03:00
let didCacheProvider = false ;
2022-04-14 02:12:38 +03:00
2022-05-05 16:31:10 +03:00
export function setItem ( key , value ) {
store . set ( key , value ) ;
if ( persistentProvider ) {
persistentProvider . setItem ( key , typeof value === "string" ? value : JSON . stringify ( value ) ) ;
2022-04-14 02:12:38 +03:00
}
}
export function getItem ( key ) {
2022-05-06 01:55:21 +03:00
if ( ! didCacheProvider ) {
init ( ) ;
}
2022-05-05 16:31:10 +03:00
return store . get ( key ) ;
2022-04-14 02:12:38 +03:00
}
2022-05-05 16:31:10 +03:00
export function removeItem ( key ) {
store . delete ( key ) ;
if ( persistentProvider ) {
persistentProvider . removeItem ( key ) ;
}
2022-04-14 02:12:38 +03:00
}
2022-05-05 16:31:10 +03:00
export function init ( ) {
if ( ! persistentProvider )
return ;
2022-04-14 02:12:38 +03:00
2022-05-05 16:31:10 +03:00
store . forEach ( ( defaultValue , key ) => {
const override = persistentProvider . getItem ( key ) ;
if ( override !== null ) {
try {
store . set ( key , typeof defaultValue === "string" ? override : JSON . parse ( override ) ) ;
} catch ( o _O ) {
2022-05-05 21:30:21 +03:00
console . warn ( "[Storage]" , ` init(): An exception was thrown while parsing the value of key " ${ key } " from persistentProvider. The key " ${ key } " will be removed from persistentProvider. ` , o _O ) ;
persistentProvider . removeItem ( key ) ;
2022-05-05 16:31:10 +03:00
}
}
} ) ;
2022-05-06 01:55:21 +03:00
didCacheProvider = true ;
2022-04-14 02:12:38 +03:00
}
2022-04-19 21:21:55 +03:00
export function apiRoute ( fragment ) {
2022-05-05 21:30:21 +03:00
return ` ${ getItem ( "server:apiBase" ) } / ${ fragment } `
2022-04-14 02:12:38 +03:00
}