toot-script-condivisione-su.../src/stores/saved-instances.ts

49 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-09-02 16:17:15 +02:00
/*!
* This file is part of ShareFedi
* https://github.com/kytta/share2fedi
*
* SPDX-FileCopyrightText: © 2023 Nikita Karamov <me@kytta.dev>
* SPDX-License-Identifier: AGPL-3.0-only
*/
2023-03-27 20:26:49 +02:00
import { persistentAtom } from "@nanostores/persistent";
2023-09-02 17:53:16 +02:00
import { getUrlDomain } from "@lib/url";
2023-08-26 15:56:50 +02:00
import { action, onMount } from "nanostores";
2023-03-27 20:26:49 +02:00
2023-08-26 15:56:50 +02:00
const OLD_LOCAL_STORAGE_KEY = "recentInstances";
const LOCAL_STORAGE_KEY = "savedInstances";
const CAPACITY = 5;
2023-03-27 20:26:49 +02:00
2023-08-26 15:56:50 +02:00
export const $savedInstances = persistentAtom<Set<string>>(
2023-03-27 20:26:49 +02:00
LOCAL_STORAGE_KEY,
new Set(),
{
encode: (set) => JSON.stringify([...set]),
2023-08-26 15:56:50 +02:00
decode: (value) => new Set(JSON.parse(value)),
2023-03-27 20:26:49 +02:00
},
);
2023-08-26 15:56:50 +02:00
onMount($savedInstances, () => {
// XXX: The conversion to a domain need to be done to support legacy
// users, who may have full URLs in their Storage
const oldItem = localStorage.getItem(OLD_LOCAL_STORAGE_KEY);
if (!oldItem) {
return;
}
$savedInstances.set(
2023-03-27 20:26:49 +02:00
new Set(
2023-08-26 15:56:50 +02:00
JSON.parse(oldItem).map((instanceUrl: string) =>
getUrlDomain(instanceUrl),
2023-03-27 21:25:26 +02:00
),
2023-03-27 20:26:49 +02:00
),
);
2023-08-26 15:56:50 +02:00
localStorage.removeItem(OLD_LOCAL_STORAGE_KEY);
});
export const save = action($savedInstances, "save", (store, instance) => {
store.set(
new Set([getUrlDomain(instance), ...store.get()].slice(0, CAPACITY)),
);
});