⚡️⚡️⚡️ 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
feat(extension): improved accessibility
daniel31x13168f1e710137
diff --git a/apps/extension/src/@/components/BookmarkForm.tsx b/apps/extension/src/@/components/BookmarkForm.tsxindex 9dc019b5..7818257d 100644--- a/apps/extension/src/@/components/BookmarkForm.tsx+++ b/apps/extension/src/@/components/BookmarkForm.tsx@@ -23,7 +23,7 @@ import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query";import { getConfig, isConfigured as getIsConfigured } from "../lib/config.ts";import { checkLinkExists, postLink } from "../lib/actions/links.ts";import { AxiosError } from "axios";-import { toast } from "../../hooks/use-toast.ts";+import { toast } from "../../hooks/useToast.ts";import { Toaster } from "./ui/Toaster.tsx";import { getCollections } from "../lib/actions/collections.ts";import { getShouldUseTagSearch, getTags } from "../lib/actions/tags.ts";diff --git a/apps/extension/src/@/components/CollectionInput.tsx b/apps/extension/src/@/components/CollectionInput.tsxindex 1f1c2f62..4f5c8ac1 100644--- a/apps/extension/src/@/components/CollectionInput.tsx+++ b/apps/extension/src/@/components/CollectionInput.tsx@@ -5,6 +5,7 @@ import { Button } from "./ui/Button.tsx";import { FormControl } from "./ui/Form.tsx";import { Popover, PopoverContent, PopoverTrigger } from "./ui/Popover.tsx";import { Collection } from "../lib/actions/collections.ts";+import { useListboxKeys } from "../../hooks/useListboxKeys.ts";type Props = {value?: { id?: number; ownerId?: number; name: string };@@ -52,21 +53,34 @@ export default function CollectionInput({onOpenChange(false);};+ const { activeIndex, listId, optionId, handleKeyDown } = useListboxKeys({+ options: filteredCollections,+ onEnter: (collection) => collection && handleSelect(collection),+ onClose: () => onOpenChange(false),+ });+const list = (<div+ onKeyDown={handleKeyDown}className={`flex h-full w-full flex-col overflow-hidden bg-popover text-popover-foreground ${fullScreen ? "rounded-none" : "rounded-md"}`}><div className="flex items-center border-b px-3">- <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />+ <Search aria-hidden className="mr-2 h-4 w-4 shrink-0 opacity-50" /><input+ autoFocus={fullScreen}+ role="combobox"+ aria-expanded+ aria-controls={listId}+ aria-autocomplete="list"+ aria-activedescendant={+ activeIndex === null ? undefined : optionId(activeIndex)+ }className="flex h-11 w-full min-w-[280px] bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground"placeholder="Search Collection..."value={search}onChange={(e) => setSearch(e.target.value)}- // Without this, Enter submits the form this input is nested in.- onKeyDown={(e) => e.key === "Enter" && e.preventDefault()}/></div>@@ -75,12 +89,21 @@ export default function CollectionInput({) : filteredCollections.length === 0 ? (<p className="py-6 text-center text-sm">No Collection found.</p>) : (- <div className="w-full overflow-hidden p-1 text-foreground">- {filteredCollections.map((collection) => (+ <div+ id={listId}+ role="listbox"+ className="w-full overflow-hidden p-1 text-foreground"+ >+ {filteredCollections.map((collection, index) => (<divkey={collection.id}+ id={optionId(index)}+ role="option"+ aria-selected={collection.name === value?.name}onClick={() => handleSelect(collection)}- className="relative flex cursor-pointer select-none flex-col items-start justify-start rounded-sm px-2 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground"+ className={`relative flex cursor-pointer select-none flex-col items-start justify-start rounded-sm px-2 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground ${+ index === activeIndex ? "bg-accent text-accent-foreground" : ""+ }`}><p>{collection.name}</p><p className="text-xs text-neutral-500">{collection.pathname}</p>@@ -98,27 +121,36 @@ export default function CollectionInput({<FormControl><Buttonvariant="outline"- role="combobox"+ aria-haspopup={fullScreen ? "dialog" : "listbox"}aria-expanded={open}className="w-full justify-between bg-neutral-100 dark:bg-neutral-900">{isLoading? "Unorganized": value?.name || "Select a collection..."}- <CaretSortIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />+ <CaretSortIcon+ aria-hidden+ className="ml-2 h-4 w-4 shrink-0 opacity-50"+ /></Button></FormControl></PopoverTrigger>{open &&(fullScreen ? (- <div className="fade-up fixed inset-0 z-50 h-full w-full overflow-y-auto bg-white">+ <div+ role="dialog"+ aria-modal+ aria-label="Select a collection"+ className="fade-up fixed inset-0 z-50 h-full w-full overflow-y-auto bg-white"+ ><Buttontype="button"+ aria-label="Close"className="absolute top-1 right-1 bg-transparent hover:bg-transparent hover:opacity-50 transition-colors ease-in-out duration-200"onClick={() => onOpenChange(false)}>- <X className="h-4 w-4 text-black dark:text-white" />+ <X aria-hidden className="h-4 w-4 text-black dark:text-white" /></Button>{list}</div>diff --git a/apps/extension/src/@/components/OptionsForm.tsx b/apps/extension/src/@/components/OptionsForm.tsxindex d5cc207a..415b1f2a 100644--- a/apps/extension/src/@/components/OptionsForm.tsx+++ b/apps/extension/src/@/components/OptionsForm.tsx@@ -8,48 +8,48 @@ import {FormItem,FormLabel,FormMessage,-} from './ui/Form.tsx';-import { useForm } from 'react-hook-form';-import { zodResolver } from '@hookform/resolvers/zod';+} from "./ui/Form.tsx";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";import {optionsFormInput,optionsFormSchema,optionsFormValues,-} from '../lib/validators/optionsForm.ts';-import { Input } from './ui/Input.tsx';-import { Button } from './ui/Button.tsx';-import { useMutation } from '@tanstack/react-query';-import { useEffect } from 'react';+} from "../lib/validators/optionsForm.ts";+import { Input } from "./ui/Input.tsx";+import { Button } from "./ui/Button.tsx";+import { useMutation } from "@tanstack/react-query";+import { useEffect } from "react";import {clearConfig,getConfig,isConfigured,saveConfig,-} from '../lib/config.ts';-import { Toaster } from './ui/Toaster.tsx';-import { toast } from '../../hooks/use-toast.ts';-import { AxiosError } from 'axios';-import { clearBookmarksMetadata } from '../lib/cache.ts';-import { getSession } from '../lib/auth/auth.ts';+} from "../lib/config.ts";+import { Toaster } from "./ui/Toaster.tsx";+import { toast } from "../../hooks/useToast.ts";+import { AxiosError } from "axios";+import { clearBookmarksMetadata } from "../lib/cache.ts";+import { getSession } from "../lib/auth/auth.ts";import {Select,SelectContent,SelectItem,SelectTrigger,SelectValue,-} from './ui/Select.tsx'; // Import the Select component+} from "./ui/Select.tsx";const OptionsForm = () => {const form = useForm<optionsFormInput, unknown, optionsFormValues>({resolver: zodResolver(optionsFormSchema),defaultValues: {- baseUrl: 'https://cloud.linkwarden.app',- method: 'username', // Default to 'username'- username: '',- password: '',- apiKey: '',+ baseUrl: "https://cloud.linkwarden.app",+ method: "username",+ username: "",+ password: "",+ apiKey: "",syncBookmarks: false,- defaultCollection: 'Unorganized',+ defaultCollection: "Unorganized",},});@@ -58,30 +58,30 @@ const OptionsForm = () => {const configured = await isConfigured();if (!configured) {- return new Error('Not configured');+ return new Error("Not configured");}return;},onError: () => {toast({- title: 'Error',+ title: "Error",description:"Either you didn't configure the extension or there was an error while trying to log out. Please try again.",- variant: 'destructive',+ variant: "destructive",});return;},onSuccess: async () => {// Reset the formform.reset({- baseUrl: '',- method: 'username',- username: '',- password: '',- apiKey: '',+ baseUrl: "",+ method: "username",+ username: "",+ password: "",+ apiKey: "",syncBookmarks: false,- defaultCollection: 'Unorganized',+ defaultCollection: "Unorganized",});await clearConfig();await clearBookmarksMetadata();@@ -91,10 +91,10 @@ const OptionsForm = () => {const { mutate: onSubmit, isPending } = useMutation({mutationFn: async (values: optionsFormValues) => {- values.baseUrl = values.baseUrl.replace(/\/$/, '');+ values.baseUrl = values.baseUrl.replace(/\/$/, "");// Do API call to test the connection and save the values- if (values.method === 'apiKey') {+ if (values.method === "apiKey") {return {...values,data: {@@ -116,7 +116,7 @@ const OptionsForm = () => {);if (session.status !== 200) {- throw new Error('Invalid credentials');+ throw new Error("Invalid credentials");}return {@@ -134,22 +134,22 @@ const OptionsForm = () => {if (error instanceof AxiosError) {if (error.response?.status === 401) {toast({- title: 'Error',- description: 'Invalid credentials or API Key',- variant: 'destructive',+ title: "Error",+ description: "Invalid credentials or API Key",+ variant: "destructive",});} else {toast({- title: 'Error',- description: 'Something went wrong, try again please.',- variant: 'destructive',+ title: "Error",+ description: "Something went wrong, try again please.",+ variant: "destructive",});}} else {toast({- title: 'Error',- description: 'Something went wrong, check your values are correct.',- variant: 'destructive',+ title: "Error",+ description: "Something went wrong, check your values are correct.",+ variant: "destructive",});}},@@ -159,16 +159,16 @@ const OptionsForm = () => {defaultCollection: values.defaultCollection,syncBookmarks: values.syncBookmarks,apiKey:- values.method === 'apiKey' && values.apiKey+ values.method === "apiKey" && values.apiKey? values.apiKey: values.data.response.token,});toast({- title: 'Saved',+ title: "Saved",description:- 'Your settings have been saved, you can now close this tab.',- variant: 'default',+ "Your settings have been saved, you can now close this tab.",+ variant: "default",});},});@@ -184,7 +184,7 @@ const OptionsForm = () => {}, [form]);const { handleSubmit, control, watch } = form;- const method = watch('method'); // Watch the 'method' field+ const method = watch("method");return (<div>@@ -242,7 +242,7 @@ const OptionsForm = () => {/>{/* Conditionally render API Key or Username/Password fields */}- {method === 'apiKey' ? (+ {method === "apiKey" ? (<FormFieldcontrol={control}name="apiKey"diff --git a/apps/extension/src/@/components/TagInput.tsx b/apps/extension/src/@/components/TagInput.tsxindex fec367e9..48d7cc33 100644--- a/apps/extension/src/@/components/TagInput.tsx+++ b/apps/extension/src/@/components/TagInput.tsx@@ -1,8 +1,10 @@import { UIEvent, useMemo, useState } from "react";import { Check, ChevronsUpDown, Search } from "lucide-react";import { Button } from "./ui/Button.tsx";+import { FormControl } from "./ui/Form.tsx";import { Popover, PopoverContent, PopoverTrigger } from "./ui/Popover.tsx";import { ResponseTags } from "../lib/actions/tags.ts";+import { useListboxKeys } from "../../hooks/useListboxKeys.ts";type Props = {value: { name: string; id?: number }[];@@ -54,6 +56,12 @@ export default function TagInput({onSearchChange?.("");};+ const { activeIndex, listId, optionId, handleKeyDown } = useListboxKeys({+ options: filteredTags,+ onEnter: (tag) => (tag ? handleToggleTag(tag) : handleAddSearchAsTag()),+ onClose: () => setOpen(false),+ });+const handleScroll = (e: UIEvent<HTMLDivElement>) => {if (!hasNextPage || isFetchingNextPage || !onReachEnd) return;@@ -66,24 +74,42 @@ export default function TagInput({<div className="min-w-full"><Popover open={open} onOpenChange={setOpen}><PopoverTrigger asChild>- <Button- variant="outline"- role="combobox"- aria-expanded={open}- className="w-full justify-between bg-neutral-100 dark:bg-neutral-900"- >- {value.length > 0- ? value.map((tag) => tag.name).join(", ")- : "Select tags..."}- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />- </Button>+ <FormControl>+ <Button+ variant="outline"+ aria-haspopup="listbox"+ aria-expanded={open}+ className="w-full justify-between bg-neutral-100 dark:bg-neutral-900"+ >+ {value.length > 0+ ? value.map((tag) => tag.name).join(", ")+ : "Select tags..."}+ <ChevronsUpDown+ aria-hidden+ className="ml-2 h-4 w-4 shrink-0 opacity-50"+ />+ </Button>+ </FormControl></PopoverTrigger><PopoverContent className="min-w-full p-0">- <div className="flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground">+ <div+ onKeyDown={handleKeyDown}+ className="flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground"+ ><div className="flex items-center border-b px-3">- <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />+ <Search+ aria-hidden+ className="mr-2 h-4 w-4 shrink-0 opacity-50"+ /><input+ role="combobox"+ aria-expanded+ aria-controls={listId}+ aria-autocomplete="list"+ aria-activedescendant={+ activeIndex === null ? undefined : optionId(activeIndex)+ }className="flex h-11 w-full min-w-[280px] bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground"placeholder="Search tag or add tag (Enter)"value={search}@@ -91,9 +117,6 @@ export default function TagInput({setSearch(e.target.value);onSearchChange?.(e.target.value);}}- onKeyDown={(e) => {- if (e.key === "Enter") handleAddSearchAsTag();- }}/></div>@@ -104,14 +127,27 @@ export default function TagInput({{filteredTags.length === 0 && !isFetchingNextPage ? (<p className="py-6 text-center text-sm">No tag found.</p>) : (- <div className="w-full overflow-hidden p-1 text-foreground">- {filteredTags.map((tag) => (+ <div+ id={listId}+ role="listbox"+ aria-multiselectable+ className="w-full overflow-hidden p-1 text-foreground"+ >+ {filteredTags.map((tag, index) => (<divkey={tag.name}+ id={optionId(index)}+ role="option"+ aria-selected={value.some((v) => v.name === tag.name)}onClick={() => handleToggleTag(tag)}- className="relative flex w-full cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground"+ className={`relative flex w-full cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground ${+ index === activeIndex+ ? "bg-accent text-accent-foreground"+ : ""+ }`}><Check+ aria-hiddenclassName={`mr-2 h-4 w-4 ${value.some((v) => v.name === tag.name)? "opacity-100"@@ -123,7 +159,12 @@ export default function TagInput({))}{isFetchingNextPage && (- <div className="relative flex w-full cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm opacity-50">+ <div+ role="option"+ aria-disabled+ aria-selected={false}+ className="relative flex w-full cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm opacity-50"+ >Loading more tags...</div>)}diff --git a/apps/extension/src/@/components/ui/Toaster.tsx b/apps/extension/src/@/components/ui/Toaster.tsxindex ba71acb5..56091b07 100644--- a/apps/extension/src/@/components/ui/Toaster.tsx+++ b/apps/extension/src/@/components/ui/Toaster.tsx@@ -5,18 +5,18 @@ import {ToastProvider,ToastTitle,ToastViewport,-} from '../ui/Toast';-import { useToast } from '../../../hooks/use-toast';+} from "../ui/Toast";+import { useToast } from "../../../hooks/useToast";export function Toaster() {const { toasts } = useToast();return (<ToastProvider>- {toasts.map(function({ id, title, description, action, ...props }) {+ {toasts.map(function ({ id, title, description, action, ...props }) {return (<Toast key={id} {...props}>- <div className='grid gap-1'>+ <div className="grid gap-1">{title && <ToastTitle>{title}</ToastTitle>}{description && (<ToastDescription>{description}</ToastDescription>diff --git a/apps/extension/src/hooks/useListboxKeys.ts b/apps/extension/src/hooks/useListboxKeys.tsnew file mode 100644index 00000000..68deec66--- /dev/null+++ b/apps/extension/src/hooks/useListboxKeys.ts@@ -0,0 +1,49 @@+import { KeyboardEvent, useEffect, useId, useState } from "react";++type Props<T> = {+ options: T[];+ onEnter: (option: T | null) => void;+ onClose: () => void;+};++export function useListboxKeys<T>({ options, onEnter, onClose }: Props<T>) {+ const [activeIndex, setActiveIndex] = useState<number | null>(null);+ const listId = useId();++ const optionId = (index: number) => `${listId}-${index}`;++ useEffect(() => setActiveIndex(null), [options]);++ useEffect(() => {+ if (activeIndex === null) return;++ document+ .getElementById(`${listId}-${activeIndex}`)+ ?.scrollIntoView({ block: "nearest" });+ }, [activeIndex, listId]);++ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {+ e.preventDefault();++ if (!options.length) return;++ const step = e.key === "ArrowDown" ? 1 : -1;++ setActiveIndex((index) =>+ index === null+ ? step === 1+ ? 0+ : options.length - 1+ : (index + step + options.length) % options.length+ );+ } else if (e.key === "Enter") {+ e.preventDefault();+ onEnter(activeIndex === null ? null : options[activeIndex]);+ } else if (e.key === "Escape") {+ onClose();+ }+ };++ return { activeIndex, listId, optionId, handleKeyDown };+}diff --git a/apps/extension/src/hooks/use-toast.ts b/apps/extension/src/hooks/useToast.tssimilarity index 69%rename from apps/extension/src/hooks/use-toast.tsrename to apps/extension/src/hooks/useToast.tsindex b6eecd4a..b15e8e48 100644--- a/apps/extension/src/hooks/use-toast.ts+++ b/apps/extension/src/hooks/useToast.ts@@ -1,26 +1,25 @@-// Inspired by react-hot-toast library-import * as React from 'react';+import * as React from "react";import type {ToastActionElement,ToastProps,-} from '../@/components/ui/Toast.tsx';+} from "../@/components/ui/Toast.tsx";const TOAST_LIMIT = 1;const TOAST_REMOVE_DELAY = 1000000;type ToasterToast = ToastProps & {- id: string- title?: React.ReactNode- description?: React.ReactNode- action?: ToastActionElement-}+ id: string;+ title?: React.ReactNode;+ description?: React.ReactNode;+ action?: ToastActionElement;+};const actionTypes = {- ADD_TOAST: 'ADD_TOAST',- UPDATE_TOAST: 'UPDATE_TOAST',- DISMISS_TOAST: 'DISMISS_TOAST',- REMOVE_TOAST: 'REMOVE_TOAST',+ ADD_TOAST: "ADD_TOAST",+ UPDATE_TOAST: "UPDATE_TOAST",+ DISMISS_TOAST: "DISMISS_TOAST",+ REMOVE_TOAST: "REMOVE_TOAST",} as const;let count = 0;@@ -30,25 +29,25 @@ function genId() {return count.toString();}-type ActionType = typeof actionTypes+type ActionType = typeof actionTypes;type Action =| {- type: ActionType['ADD_TOAST']- toast: ToasterToast-}+ type: ActionType["ADD_TOAST"];+ toast: ToasterToast;+ }| {- type: ActionType['UPDATE_TOAST']- toast: Partial<ToasterToast>-}+ type: ActionType["UPDATE_TOAST"];+ toast: Partial<ToasterToast>;+ }| {- type: ActionType['DISMISS_TOAST']- toastId?: ToasterToast['id']-}+ type: ActionType["DISMISS_TOAST"];+ toastId?: ToasterToast["id"];+ }| {- type: ActionType['REMOVE_TOAST']- toastId?: ToasterToast['id']-}+ type: ActionType["REMOVE_TOAST"];+ toastId?: ToasterToast["id"];+ };interface State {toasts: ToasterToast[];@@ -64,7 +63,7 @@ const addToRemoveQueue = (toastId: string) => {const timeout = setTimeout(() => {toastTimeouts.delete(toastId);dispatch({- type: 'REMOVE_TOAST',+ type: "REMOVE_TOAST",toastId: toastId,});}, TOAST_REMOVE_DELAY);@@ -74,25 +73,23 @@ const addToRemoveQueue = (toastId: string) => {export const reducer = (state: State, action: Action): State => {switch (action.type) {- case 'ADD_TOAST':+ case "ADD_TOAST":return {...state,toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),};- case 'UPDATE_TOAST':+ case "UPDATE_TOAST":return {...state,toasts: state.toasts.map((t) =>- t.id === action.toast.id ? { ...t, ...action.toast } : t,+ t.id === action.toast.id ? { ...t, ...action.toast } : t),};- case 'DISMISS_TOAST': {+ case "DISMISS_TOAST": {const { toastId } = action;- // ! Side effects ! - This could be extracted into a dismissToast() action,- // but I'll keep it here for simplicityif (toastId) {addToRemoveQueue(toastId);} else {@@ -106,14 +103,14 @@ export const reducer = (state: State, action: Action): State => {toasts: state.toasts.map((t) =>t.id === toastId || toastId === undefined? {- ...t,- open: false,- }- : t,+ ...t,+ open: false,+ }+ : t),};}- case 'REMOVE_TOAST':+ case "REMOVE_TOAST":if (action.toastId === undefined) {return {...state,@@ -138,20 +135,20 @@ function dispatch(action: Action) {});}-type Toast = Omit<ToasterToast, 'id'>+type Toast = Omit<ToasterToast, "id">;function toast({ ...props }: Toast) {const id = genId();const update = (props: ToasterToast) =>dispatch({- type: 'UPDATE_TOAST',+ type: "UPDATE_TOAST",toast: { ...props, id },});- const dismiss = () => dispatch({ type: 'DISMISS_TOAST', toastId: id });+ const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id });dispatch({- type: 'ADD_TOAST',+ type: "ADD_TOAST",toast: {...props,id,@@ -185,7 +182,7 @@ function useToast() {return {...state,toast,- dismiss: (toastId?: string) => dispatch({ type: 'DISMISS_TOAST', toastId }),+ dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),};}