refactor(channels): shared tag-mutation hook + a channel_detail tag_ids test (R8 review)

Address the two remaining review findings on the tag work:
- extract useChannelTagActions — the optimistic attach/detach + create-and-attach flow that
  the channel manager and the channel detail page had copy-pasted; the cache-shape-specific
  optimistic update is injected (manager maps a ManagedChannel[]; detail patches one
  ChannelDetail), so the two stay in sync;
- add a DB-lane test asserting GET /api/channels/{id} returns exactly this user's personal
  tag links — not another user's, not the auto/system (user_id NULL) links.
This commit is contained in:
2026-07-30 23:33:50 +02:00
parent 3352d0095c
commit f091247624
4 changed files with 132 additions and 59 deletions
+43
View File
@@ -0,0 +1,43 @@
import { useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { api } from "./api";
import { qk } from "./queryKeys";
import { notify } from "./notifications";
/** The shared channel-tag mutation flow used by both the channel manager and the channel detail
* page: optimistic attach/detach + a create-then-attach shortcut, with the cache-shape-specific
* optimistic update injected (the manager maps over a ManagedChannel[]; the detail patches one
* ChannelDetail). Keeps the two call sites from drifting. */
export function useChannelTagActions(opts: {
/** Apply the optimistic tag change to whichever cache the caller owns. `attach` true = add. */
optimisticToggle: (channelId: string, tagId: number, attach: boolean) => void;
/** Called after the attach/detach lands (e.g. sync a sibling cache). Optional. */
onSuccess?: (channelId: string) => void;
/** Called if the attach/detach fails — revert by refetching the owning cache. */
onError: (channelId: string) => void;
}) {
const qc = useQueryClient();
const { t } = useTranslation();
const toggleTag = (channelId: string, tagId: number, hasTag: boolean) => {
opts.optimisticToggle(channelId, tagId, !hasTag);
const call = hasTag
? api.detachChannelTag(channelId, tagId)
: api.attachChannelTag(channelId, tagId);
call.then(() => opts.onSuccess?.(channelId)).catch(() => opts.onError(channelId));
};
// Create a brand-new personal tag and attach it in one step (so tagging doesn't require the
// top-of-page "Manage tags" dialog first). Refresh the tag catalog so it appears everywhere.
const createAndAttachTag = (channelId: string, name: string) => {
api
.createTag({ name })
.then((tag) => {
qc.invalidateQueries({ queryKey: qk.tags() });
toggleTag(channelId, tag.id, false);
})
.catch(() => notify({ level: "error", message: t("channels.tags.createFailed") }));
};
return { toggleTag, createAndAttachTag };
}