queue/source/settings/settings.ts

92 lines
2.3 KiB
TypeScript

import browser from 'webextension-polyfill';
import {migrate} from '@holllo/migration-helper';
import {History} from '../utilities/history.js';
import {
dataMigrations,
deserializeQueue,
serializeQueue,
} from './migrations.js';
export class Settings {
public static async fromSyncStorage(): Promise<Settings> {
const settings = new Settings();
const sync = await browser.storage.sync.get(null);
const migrated = (await migrate(
sync,
sync.version ?? settings.version,
dataMigrations,
)) as Record<string, any>;
settings.queue = deserializeQueue(migrated);
settings.version = migrated.version as string;
await settings.save();
return settings;
}
public manifest: browser.Manifest.ManifestBase;
public queue: Queue.Item[];
public version: string;
constructor() {
this.manifest = browser.runtime.getManifest();
this.queue = [];
this.version = '0.0.0';
}
public async insertQueueItem(text: string, url: string): Promise<void> {
const id = this.newQueueItemId();
const item: Queue.Item = {
added: new Date(),
id,
sortIndex: id,
text,
url,
};
this.queue.push(item);
await browser.storage.sync.set({
[`qi${id}`]: {
added: item.added.toISOString(),
id,
sortIndex: id,
text,
url,
},
});
}
public newQueueItemId(): number {
const item = this.queue.sort((a, b) => b.id - a.id)[0];
return item === undefined ? 1 : item.id + 1;
}
public nextQueueItem(): Queue.Item | undefined {
return this.queue.sort((a, b) => a.added.getTime() - b.added.getTime())[0];
}
public async removeQueueItem(id: number): Promise<void> {
const itemIndex = this.queue.findIndex((item) => item.id === id);
if (itemIndex === -1) {
console.error(`Tried to remove an item with unknown ID: ${id}`);
return;
}
const removedItems = this.queue.splice(itemIndex, 1);
await browser.storage.sync.remove(removedItems.map(({id}) => `qi${id}`));
const history = await History.fromLocalStorage();
await history.insertItems(removedItems);
}
public async save(): Promise<void> {
await browser.storage.sync.set({
...serializeQueue(this.queue),
version: this.version,
});
}
}