From 5dc92d0e1acec752660341b8ce211a37cc0e7357 Mon Sep 17 00:00:00 2001 From: Bauke Date: Tue, 10 Oct 2023 17:49:29 +0200 Subject: [PATCH] Factor out creating new user label IDs. --- source/content-scripts/features/user-labels.tsx | 8 ++------ source/options/user-label-editor.tsx | 7 ++----- source/storage/user-label.ts | 10 ++++++++++ 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/source/content-scripts/features/user-labels.tsx b/source/content-scripts/features/user-labels.tsx index cec541c..bf3bc81 100644 --- a/source/content-scripts/features/user-labels.tsx +++ b/source/content-scripts/features/user-labels.tsx @@ -3,6 +3,7 @@ import {Component, render} from "preact"; import { type UserLabelsData, createValueUserLabel, + newUserLabelId, saveUserLabels, } from "../../storage/exports.js"; import { @@ -240,12 +241,7 @@ export class UserLabelsFeature extends Component { const {userLabels} = this.props; // If no ID is present then save a new label otherwise edit the existing one. if (id === undefined) { - let newId = 1; - if (userLabels.length > 0) { - newId = - userLabels.sort((a, b) => b.value.id - a.value.id)[0].value.id + 1; - } - + const newId = await newUserLabelId(); userLabels.push( await createValueUserLabel({ color, diff --git a/source/options/user-label-editor.tsx b/source/options/user-label-editor.tsx index 787261e..cee97fd 100644 --- a/source/options/user-label-editor.tsx +++ b/source/options/user-label-editor.tsx @@ -12,6 +12,7 @@ import { Feature, createValueUserLabel, saveUserLabels, + newUserLabelId, } from "../storage/exports.js"; import "../scss/index.scss"; import "../scss/user-label-editor.scss"; @@ -56,11 +57,7 @@ class App extends Component { username.toLowerCase() === newLabelUsername.toLowerCase(), ); - let id = 1; - if (userLabels.length > 0) { - id = userLabels.sort((a, b) => b.value.id - a.value.id)[0].value.id + 1; - } - + const id = await newUserLabelId(); userLabels.push( await createValueUserLabel({ color: "#ff00ff", diff --git a/source/storage/user-label.ts b/source/storage/user-label.ts index 2d7a759..146a32c 100644 --- a/source/storage/user-label.ts +++ b/source/storage/user-label.ts @@ -67,3 +67,13 @@ export async function saveUserLabels( await label.save(); } } + +export async function newUserLabelId(): Promise { + const userLabels = await collectUserLabels(); + let newId = 1; + if (userLabels.length > 0) { + newId = userLabels.sort((a, b) => b.value.id - a.value.id)[0].value.id + 1; + } + + return newId; +}