⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
use a hook to manage state for archival tags input
Isaac0123791b8a8a
diff --git a/components/InputSelect/ArchivalTagSelection.tsx b/components/InputSelect/ArchivalTagSelection.tsxindex 8833f27b..3f4a1854 100644--- a/components/InputSelect/ArchivalTagSelection.tsx+++ b/components/InputSelect/ArchivalTagSelection.tsx@@ -1,44 +1,39 @@-import { useEffect, useState } from "react";import CreatableSelect from "react-select/creatable";import { styles } from "./styles";-import { ArchivalTagOption } from "./types";-import { useTags } from "@/hooks/store/tags";import { useTranslation } from "next-i18next";+import { ArchivalTagOption } from "./types";import { Tag } from "@prisma/client";++export const transformTag = (tag: Tag) => ({+ label: tag.name,+ value: tag.id,+ archiveAsScreenshot: tag.archiveAsScreenshot || false,+ archiveAsMonolith: tag.archiveAsMonolith || false,+ archiveAsPDF: tag.archiveAsPDF || false,+ archiveAsReadable: tag.archiveAsReadable || false,+ archiveAsWaybackMachine: tag.archiveAsWaybackMachine || false,+ aiTag: tag.aiTag || false,+});++export const isArchivalTag = (tag: Tag) =>+ tag.archiveAsScreenshot ||+ tag.archiveAsMonolith ||+ tag.archiveAsPDF ||+ tag.archiveAsReadable ||+ tag.archiveAsWaybackMachine ||+ tag.aiTag;+type Props = {+ options: ArchivalTagOption[] | []onChange: (e: any) => void;- selectedTags: ArchivalTagOption[] | [];};export default function ArchivalTagSelection({- onChange,- selectedTags+ options,+ onChange}: Props) {- const { data: tags = [] } = useTags();const { t } = useTranslation();- const [options, setOptions] = useState<ArchivalTagOption[]>([]);-- useEffect(() => {- const formattedTags = tags.map((tag: Tag) => {- return {- value: tag.id,- label: tag.name,- archiveAsScreenshot: tag.archiveAsScreenshot || false,- archiveAsMonolith: tag.archiveAsMonolith || false,- archiveAsPDF: tag.archiveAsPDF || false,- archiveAsReadable: tag.archiveAsReadable || false,- archiveAsWaybackMachine: tag.archiveAsWaybackMachine || false,- aiTag: tag.aiTag || false- };- });-- const filteredTags = formattedTags.filter((tag) => {- return !selectedTags.find((selectedTag) => selectedTag.value === tag.value);- });-- setOptions(filteredTags);- }, [tags, selectedTags]);return (<CreatableSelectdiff --git a/components/InputSelect/types.ts b/components/InputSelect/types.tsindex 7ce74389..4ac48498 100644--- a/components/InputSelect/types.ts+++ b/components/InputSelect/types.ts@@ -1,15 +1,16 @@export interface Option {label: string;value?: string | number;+ __isNew__?: boolean;}export interface ArchivalTagOption extends Option {- archiveAsScreenshot: boolean | null;- archiveAsMonolith: boolean | null;- archiveAsPDF: boolean | null- archiveAsReadable: boolean | null;- archiveAsWaybackMachine: boolean | null;- aiTag: boolean | null;+ archiveAsScreenshot: boolean;+ archiveAsMonolith: boolean;+ archiveAsPDF: boolean;+ archiveAsReadable: boolean;+ archiveAsWaybackMachine: boolean;+ aiTag: boolean;}-export type ArchivalOptionKeys = keyof Omit<ArchivalTagOption, "label" | "value">;+export type ArchivalOptionKeys = keyof Omit<ArchivalTagOption, "label" | "value" | "__isNew__">;diff --git a/hooks/useArchivalTags.ts b/hooks/useArchivalTags.tsnew file mode 100644index 00000000..65e9fb80--- /dev/null+++ b/hooks/useArchivalTags.ts@@ -0,0 +1,101 @@+import { ArchivalOptionKeys, ArchivalTagOption } from '@/components/InputSelect/types';+import { Tag } from '@prisma/client';+import { useState, useEffect } from 'react';+import { useTranslation } from 'react-i18next';++const isArchivalTag = (tag: Tag) =>+ tag.archiveAsScreenshot ||+ tag.archiveAsMonolith ||+ tag.archiveAsPDF ||+ tag.archiveAsReadable ||+ tag.archiveAsWaybackMachine ||+ tag.aiTag;++const useArchivalTags = (initialTags: Tag[]) => {+ const [archivalTags, setArchivalTags] = useState<ArchivalTagOption[]>([]);+ const [options, setOptions] = useState<ArchivalTagOption[]>([]);+ const { t } = useTranslation();++ useEffect(() => {+ if (!initialTags) return;++ const transformTag = (tag: Tag): ArchivalTagOption => ({+ label: tag.name,+ value: tag.id,+ archiveAsScreenshot: tag.archiveAsScreenshot || false,+ archiveAsMonolith: tag.archiveAsMonolith || false,+ archiveAsPDF: tag.archiveAsPDF || false,+ archiveAsReadable: tag.archiveAsReadable || false,+ archiveAsWaybackMachine: tag.archiveAsWaybackMachine || false,+ aiTag: tag.aiTag || false,+ });++ const archival = initialTags.filter(isArchivalTag).map(transformTag);+ const nonArchival = initialTags.filter(tag => !isArchivalTag(tag)).map(transformTag);++ setArchivalTags(archival);+ setOptions(nonArchival);+ }, [initialTags]);++ const addTags = (newTags: ArchivalTagOption[]) => {+ console.log("newTags", newTags);+ const uniqueNewTags = newTags+ .filter(newTag => !archivalTags.some(existing => existing.label === newTag.label))+ .map(tag => ({+ ...tag,+ archiveAsScreenshot: tag.__isNew__ ? false : tag.archiveAsScreenshot,+ archiveAsMonolith: tag.__isNew__ ? false : tag.archiveAsMonolith,+ archiveAsPDF: tag.__isNew__ ? false : tag.archiveAsPDF,+ archiveAsReadable: tag.__isNew__ ? false : tag.archiveAsReadable,+ archiveAsWaybackMachine: tag.__isNew__ ? false : tag.archiveAsWaybackMachine,+ aiTag: tag.__isNew__ ? false : tag.aiTag,+ }));++ setArchivalTags(prev => [...prev, ...uniqueNewTags]);+ setOptions(prev => prev.filter(option => !newTags.some(({ label }) => label === option.label)));+ };++ const toggleOption = (tag: ArchivalTagOption, option: keyof ArchivalTagOption) => {+ setArchivalTags(prev => prev.map(t =>+ t.label === tag.label ? { ...t, [option]: !t[option] } : t+ ));+ };++ const removeTag = (tagToDelete: ArchivalTagOption) => {+ setArchivalTags(prev => prev.filter(tag => tag.label !== tagToDelete.label));++ if (!tagToDelete.__isNew__) {+ const resetTag: ArchivalTagOption = {+ ...tagToDelete,+ archiveAsScreenshot: false,+ archiveAsMonolith: false,+ archiveAsPDF: false,+ archiveAsReadable: false,+ archiveAsWaybackMachine: false,+ aiTag: false,+ };++ setOptions(prev => [...prev, resetTag]);+ }+ };++ const ARCHIVAL_OPTIONS: { type: ArchivalOptionKeys; icon: string; label: string }[] = [+ { type: "aiTag", icon: "bi-tag", label: t("ai_tagging") },+ { type: "archiveAsScreenshot", icon: "bi-file-earmark-image", label: t("screenshot") },+ { type: "archiveAsMonolith", icon: "bi-filetype-html", label: t("webpage") },+ { type: "archiveAsPDF", icon: "bi-file-earmark-pdf", label: t("pdf") },+ { type: "archiveAsReadable", icon: "bi-file-earmark-text", label: t("readable") },+ { type: "archiveAsWaybackMachine", icon: "bi-archive", label: t("archive_org_snapshot") },+ ];++ return {+ ARCHIVAL_OPTIONS,+ archivalTags,+ options,+ addTags,+ toggleOption,+ removeTag+ };+};++export { useArchivalTags };\ No newline at end of filediff --git a/pages/settings/preference.tsx b/pages/settings/preference.tsxindex 861c31f5..63a29d1c 100644--- a/pages/settings/preference.tsx+++ b/pages/settings/preference.tsx@@ -6,14 +6,14 @@ import Checkbox from "@/components/Checkbox";import useLocalSettingsStore from "@/store/localSettings";import { useTranslation } from "next-i18next";import getServerSideProps from "@/lib/client/getServerSideProps";-import { AiTaggingMethod, LinksRouteTo, Tag } from "@prisma/client";+import { AiTaggingMethod, LinksRouteTo } from "@prisma/client";import { useUpdateUser, useUser } from "@/hooks/store/user";import ArchivalTagSelection from "@/components/InputSelect/ArchivalTagSelection";import { useConfig } from "@/hooks/store/config";-import { ArchivalOptionKeys, ArchivalTagOption } from "@/components/InputSelect/types";import { useTags } from "@/hooks/store/tags";import { cn } from "@/lib/client/utils";import TagSelection from "@/components/InputSelect/TagSelection";+import { useArchivalTags } from "@/hooks/useArchivalTags";export default function Preference() {const { t } = useTranslation();@@ -21,6 +21,7 @@ export default function Preference() {const [submitLoader, setSubmitLoader] = useState(false);const { data: account } = useUser();const { data: tags } = useTags();+ const { ARCHIVAL_OPTIONS, archivalTags, options, addTags, toggleOption, removeTag } = useArchivalTags(tags ? tags : []);const updateUser = useUpdateUser();const [user, setUser] = useState(account);@@ -50,8 +51,6 @@ export default function Preference() {account.aiTaggingMethod);const [aiPredefinedTags, setAiPredefinedTags] = useState<string[]>();- const [archivalTags, setArchivalTags] = useState<ArchivalTagOption[]>([]);-const { data: config } = useConfig();useEffect(() => {@@ -104,25 +103,9 @@ export default function Preference() {}}, [account]);- useEffect(() => {- if (tags) {- setArchivalTags(- tags- .filter((tag: Tag) => tag.archiveAsScreenshot || tag.archiveAsMonolith || tag.archiveAsPDF || tag.archiveAsReadable || tag.archiveAsWaybackMachine || tag.aiTag)- .map((tag: Tag) => ({- label: tag.name,- value: tag.id,- archiveAsScreenshot: tag.archiveAsScreenshot,- archiveAsMonolith: tag.archiveAsMonolith,- archiveAsPDF: tag.archiveAsPDF,- archiveAsReadable: tag.archiveAsReadable,- archiveAsWaybackMachine: tag.archiveAsWaybackMachine,- aiTag: tag.aiTag,- }))- );- }- }, [tags]);-+ // Need to track the changes so we don't make useless API calls+ // tags.length !== archivalTags.length+ // also need to track the user object as wellconst submit = async () => {setSubmitLoader(true);@@ -131,7 +114,7 @@ export default function Preference() {await updateUser.mutateAsync({ ...user },{- onSettled: (data, error) => {+ onSettled: (_, error) => {setSubmitLoader(false);toast.dismiss(load);@@ -145,40 +128,6 @@ export default function Preference() {);};- const handleArchivalTagChange = (e: ArchivalTagOption[]) => {- const newTags = e;- const existingTags = archivalTags;-- // Filter out any new tags that already exist in archivalTags based on label- const uniqueNewTags = newTags.filter(newTag =>- !existingTags.some(existingTag => existingTag.label === newTag.label)- );-- setArchivalTags([...existingTags, ...uniqueNewTags]);- };-- const handleArchiveOptionChange = (tag: ArchivalTagOption, option: ArchivalOptionKeys) => {- const updatedTags = archivalTags?.map(t =>- t.label === tag.label ? { ...t, [option]: !t[option] } : t- );-- setArchivalTags(updatedTags);- };-- const handleDeleteTag = (tagToDelete: ArchivalTagOption) => {- const updatedTags = archivalTags?.filter(tag => tag.label !== tagToDelete.label);- setArchivalTags(updatedTags);- }-- const ARCHIVAL_OPTIONS: { type: ArchivalOptionKeys; icon: string; label: string }[] = [- { type: "aiTag", icon: "bi-tag", label: t("ai_tagging") },- { type: "archiveAsScreenshot", icon: "bi-file-earmark-image", label: t("screenshot") },- { type: "archiveAsMonolith", icon: "bi-filetype-html", label: t("webpage") },- { type: "archiveAsPDF", icon: "bi-file-earmark-pdf", label: t("pdf") },- { type: "archiveAsReadable", icon: "bi-file-earmark-text", label: t("readable") },- { type: "archiveAsWaybackMachine", icon: "bi-archive", label: t("archive_org_snapshot") },- ];-return (<SettingsLayout><p className="capitalize text-3xl font-thin inline">{t("preference")}</p>@@ -393,7 +342,7 @@ export default function Preference() {</div><p>{t("tag_settings")}</p><div className="p-3">- <ArchivalTagSelection onChange={handleArchivalTagChange} selectedTags={archivalTags} />+ <ArchivalTagSelection onChange={addTags} options={options} /><div className="flex flex-col gap-2">{archivalTags && archivalTags.map((tag) => (<div key={tag.label} className="w-full flex items-center justify-between bg-base-200 p-2 rounded first-of-type:mt-4">@@ -403,7 +352,7 @@ export default function Preference() {{ARCHIVAL_OPTIONS.map(({ type, icon, label }) => (<div key={type} className="tooltip tooltip-top" data-tip={label}><button- onClick={() => handleArchiveOptionChange(tag, type)}+ onClick={() => toggleOption(tag, type)}className={cn("py-1 px-2 bg-base-300 rounded", { "bg-primary bg-opacity-25": tag[type] })}><i className={`${icon} text-lg leading-none`}></i>@@ -412,7 +361,7 @@ export default function Preference() {))}</div><div className="tooltip tooltip-top" data-tip={t("delete")}>- <button className="py-1 px-2" onClick={() => handleDeleteTag(tag)}>+ <button className="py-1 px-2" onClick={() => removeTag(tag)}><i className="bi-x text-lg leading-none"></i></button></div>