The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add `useKeyboardShortcut` for tag and link cards
Tim Wilsoncfecbc898b97
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tags/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tags/page-client.tsxindex a1440ac733..f793d5d0d6 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tags/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tags/page-client.tsx@@ -8,9 +8,18 @@ import EmptyState from "@/ui/shared/empty-state";import { CardList } from "@dub/ui";import { Tag } from "@dub/ui/src/icons";import { InfoTooltip, TooltipContent } from "@dub/ui/src/tooltip";+import { Dispatch, SetStateAction, createContext, useState } from "react";import { TagCard } from "./tag-card";import { TagCardPlaceholder } from "./tag-card-placeholder";+export const TagsListContext = createContext<{+ openMenuTagId: string | null;+ setOpenMenuTagId: Dispatch<SetStateAction<string | null>>;+}>({+ openMenuTagId: null,+ setOpenMenuTagId: () => {},+});+export default function WorkspaceTagsClient() {const { id: workspaceId } = useWorkspace();@@ -21,6 +30,8 @@ export default function WorkspaceTagsClient() {groupBy: "tagId",});+ const [openMenuTagId, setOpenMenuTagId] = useState<string | null>(null);+return (<><div className="grid gap-5">@@ -47,15 +58,17 @@ export default function WorkspaceTagsClient() {{workspaceId && <AddEditTagModal />}{loading || tags?.length ? (- <CardList variant="compact" loading={loading}>- {tags?.length- ? tags.map((tag) => (- <TagCard key={tag.id} tag={tag} tagsCount={tagsCount} />- ))- : Array.from({ length: 6 }).map((_, idx) => (- <TagCardPlaceholder key={idx} />- ))}- </CardList>+ <TagsListContext.Provider value={{ openMenuTagId, setOpenMenuTagId }}>+ <CardList variant="compact" loading={loading}>+ {tags?.length+ ? tags.map((tag) => (+ <TagCard key={tag.id} tag={tag} tagsCount={tagsCount} />+ ))+ : Array.from({ length: 6 }).map((_, idx) => (+ <TagCardPlaceholder key={idx} />+ ))}+ </CardList>+ </TagsListContext.Provider>) : (<div className="flex flex-col items-center gap-4 rounded-xl border border-gray-200 py-10"><EmptyState icon={Tag} title="No tags found for this workspace" />diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tags/tag-card.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tags/tag-card.tsxindex aabe1e7939..491e5c0a9d 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tags/tag-card.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tags/tag-card.tsx@@ -5,7 +5,7 @@ import { TagProps } from "@/lib/types";import TagBadge from "@/ui/links/tag-badge";import { useAddEditTagModal } from "@/ui/modals/add-edit-tag-modal";import { Delete, ThreeDots } from "@/ui/shared/icons";-import { Button, CardList, Popover } from "@dub/ui";+import { Button, CardList, Popover, useKeyboardShortcut } from "@dub/ui";import {CircleCheck,Copy,@@ -14,9 +14,10 @@ import {} from "@dub/ui/src/icons";import { cn, nFormatter } from "@dub/utils";import Link from "next/link";-import { useState } from "react";+import { useContext, useState } from "react";import { toast } from "sonner";import { mutate } from "swr";+import { TagsListContext } from "./page-client";export function TagCard({tag,@@ -29,7 +30,12 @@ export function TagCard({const linksCount = tagsCount?.find(({ tagId }) => tagId === tag.id)?._count;- const [openPopover, setOpenPopover] = useState(false);+ const { openMenuTagId, setOpenMenuTagId } = useContext(TagsListContext);+ const openPopover = openMenuTagId === tag.id;+ const setOpenPopover = (open: boolean) => {+ setOpenMenuTagId(open ? tag.id : null);+ };+const [processing, setProcessing] = useState(false);const { AddEditTagModal, setShowAddEditTagModal } = useAddEditTagModal({@@ -46,6 +52,13 @@ export function TagCard({};const handleDelete = async () => {+ if (+ !confirm(+ "Are you sure you want to delete this tag? All tagged links will be untagged, but they won't be deleted.",+ )+ )+ return;+setProcessing(true);fetch(`/api/tags/${tag.id}?workspaceId=${id}`, {method: "DELETE",@@ -128,12 +141,7 @@ export function TagCard({<Buttontext="Delete"variant="danger-outline"- onClick={() => {- setOpenPopover(false);- confirm(- "Are you sure you want to delete this tag? All tagged links will be untagged, but they won't be deleted.",- ) && handleDelete();- }}+ onClick={handleDelete}icon={<Delete className="h-4 w-4" />}shortcut="X"className="h-9 px-2 font-medium"@@ -163,7 +171,44 @@ export function TagCard({/></Popover></div>++ {/* Use consumer + separate component to use hovered state from CardList.Card context */}+ <CardList.Card.Context.Consumer>+ {({ hovered }) => (+ <TagCardKeyboardShortcuts+ enabled={openPopover || (hovered && openMenuTagId === null)}+ onKeyDown={(e) => {+ setOpenPopover(false);+ switch (e.key) {+ case "e":+ setShowAddEditTagModal(true);+ break;+ case "i":+ copyTagId();+ break;+ case "x":+ handleDelete();+ break;+ }+ }}+ />+ )}+ </CardList.Card.Context.Consumer></CardList.Card></>);}++function TagCardKeyboardShortcuts({+ enabled,+ onKeyDown,+}: {+ enabled: boolean;+ onKeyDown: (e: KeyboardEvent) => void;+}) {+ useKeyboardShortcut(["e", "i", "x"], onKeyDown, {+ enabled,+ });++ return null;+}diff --git a/apps/web/ui/links/link-controls.tsx b/apps/web/ui/links/link-controls.tsxindex 345d2ad69d..8ade719930 100644--- a/apps/web/ui/links/link-controls.tsx+++ b/apps/web/ui/links/link-controls.tsx@@ -9,12 +9,13 @@ import {PenWriting,Popover,SimpleTooltipContent,+ useKeyboardShortcut,} from "@dub/ui";import { BoxArchive, CircleCheck, Copy, QRCode } from "@dub/ui/src/icons";import { cn, isDubDomain, nanoid, punycode } from "@dub/utils";import { CopyPlus, Delete, FolderInput } from "lucide-react";import { useParams } from "next/navigation";-import { useContext, useEffect, useState } from "react";+import { useContext, useState } from "react";import { toast } from "sonner";import { mutate } from "swr";import { useTransferLinkModal } from "../modals/transfer-link-modal";@@ -77,22 +78,11 @@ export function LinkControls({ link }: { link: ResponseLink }) {},});- const onKeyDown = (e: any) => {- const key = e.key.toLowerCase();- const existingModalBackdrop = document.getElementById("modal-backdrop");- // only run shortcut logic if:- // - there's no active opened modal- // - the 3 dots menu is open- // - the link card is hovered and- // - the key pressed is one of the shortcuts- if (- !existingModalBackdrop &&- (openPopover || (hovered && openMenuLinkId === null)) &&- ["e", "d", "q", "a", "t", "i", "x"].includes(key)- ) {- e.preventDefault();+ useKeyboardShortcut(+ ["e", "d", "q", "a", "t", "i", "x"],+ (e) => {setOpenPopover(false);- switch (key) {+ switch (e.key) {case "e":setShowAddEditLinkModal(true);break;@@ -106,9 +96,7 @@ export function LinkControls({ link }: { link: ResponseLink }) {setShowArchiveLinkModal(true);break;case "t":- if (isDubDomain(link.domain)) {- setShowTransferLinkModal(true);- }+ if (isDubDomain(link.domain)) setShowTransferLinkModal(true);break;case "i":copyLinkId();@@ -117,15 +105,11 @@ export function LinkControls({ link }: { link: ResponseLink }) {setShowDeleteLinkModal(true);break;}- }- };-- useEffect(() => {- document.addEventListener("keydown", onKeyDown);- return () => {- document.removeEventListener("keydown", onKeyDown);- };- }, [onKeyDown]);+ },+ {+ enabled: openPopover || (hovered && openMenuLinkId === null),+ },+ );return (<div className="flex justify-end">diff --git a/packages/ui/src/card-list/card-list-card.tsx b/packages/ui/src/card-list/card-list-card.tsxindex 660e3ae8b3..0ede93872a 100644--- a/packages/ui/src/card-list/card-list-card.tsx+++ b/packages/ui/src/card-list/card-list-card.tsx@@ -1,6 +1,13 @@import { cn } from "@dub/utils";import { cva } from "class-variance-authority";-import { PropsWithChildren, createContext, useContext, useState } from "react";+import {+ PropsWithChildren,+ createContext,+ useContext,+ useEffect,+ useRef,+ useState,+} from "react";import { CardListContext } from "./card-list";const cardListCardVariants = cva("w-full group/card border-gray-200 bg-white", {@@ -32,10 +39,25 @@ export function CardListCard({}>) {const { variant } = useContext(CardListContext);+ const ref = useRef<HTMLLIElement>(null);+const [hovered, setHovered] = useState(false);+ // Detect when the card loses hover without an onPointerLeave (e.g. from a modal covering the element)+ useEffect(() => {+ if (!hovered || !ref.current) return;++ // Check every second while the card is expected to still be hovered+ const interval = setInterval(() => {+ if (ref.current?.matches(":hover") === false) setHovered(false);+ }, 1000);++ return () => clearInterval(interval);+ }, [hovered]);+return (<li+ ref={ref}className={cn(cardListCardVariants({ variant }), outerClassName)}onPointerEnter={() => setHovered(true)}onPointerLeave={() => setHovered(false)}diff --git a/packages/ui/src/hooks/use-keyboard-shortcut.tsx b/packages/ui/src/hooks/use-keyboard-shortcut.tsxindex 4673909712..f3a43a44a1 100644--- a/packages/ui/src/hooks/use-keyboard-shortcut.tsx+++ b/packages/ui/src/hooks/use-keyboard-shortcut.tsx@@ -13,7 +13,7 @@ import {type KeyboardShortcutListener = {id: string;- key: string;+ key: string | string[];callback: (e: KeyboardEvent) => void;enabled?: boolean;priority?: number;@@ -51,7 +51,9 @@ export function KeyboardShortcutProvider({// Find enabled listeners that match the keyconst matchingListeners = listeners.filter(- (l) => l.key === e.key && l.enabled !== false,+ (l) =>+ l.enabled !== false &&+ (Array.isArray(l.key) ? l.key.includes(e.key) : l.key === e.key),);if (!matchingListeners.length) return;@@ -89,16 +91,21 @@ export function useKeyboardShortcut(const { setListeners } = useContext(KeyboardShortcutContext);- const { current: callback } = useRef(callbackArg);+ // Use a ref rather than the callback directly in case it isn't stable+ const callbackRef = useRef(callbackArg);++ useEffect(() => {+ callbackRef.current = callbackArg;+ }, [callbackArg]);// Register/unregister the listeneruseEffect(() => {setListeners((prev) => [...prev.filter((listener) => listener.id !== id),- { id, key, callback, ...options },+ { id, key, callback: callbackRef.current, ...options },]);return () =>setListeners((prev) => prev.filter((listener) => listener.id !== id));- }, [key, callback, options.enabled, options.priority]);+ }, [JSON.stringify(key), options.enabled, options.priority]);}