Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/bundled/channels/ChannelLifecycleActions.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,35 @@ it("replaces Archive with Unarchive when the live channel is archived", () => {
screen.getByRole("button", { name: "Unarchive channel" }),
).toBeVisible();
});
it("keeps focus in the pane when a role change retires the focused action, unless it moved", async () => {
const host = session();
const pane = (role: ChannelSummary["viewerRole"]) => (
<>
<aside>
<button type="button">Settings tab</button>
<ChannelLifecycleActions
channel={channel({ viewerRole: role })}
session={host}
choose={vi.fn()}
/>
</aside>
<input aria-label="Elsewhere" />
</>
);
const view = render(pane("admin"));
screen.getByRole("button", { name: "Archive channel" }).focus();
view.rerender(pane("member"));
expect(screen.queryByRole("button", { name: "Archive channel" })).toBeNull();
await vi.waitFor(() =>
expect(screen.getByRole("button", { name: "Settings tab" })).toHaveFocus(),
);
view.rerender(pane("admin"));
screen.getByRole("button", { name: "Archive channel" }).focus();
screen.getByRole("textbox", { name: "Elsewhere" }).focus();
view.rerender(pane("member"));
await Promise.resolve();
expect(screen.getByRole("textbox", { name: "Elsewhere" })).toHaveFocus();
});
it("explains an unsupported host without a lookup or write", () => {
const host = session(false);
render(
Expand Down
28 changes: 26 additions & 2 deletions src/bundled/channels/ChannelLifecycleActions.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useCallback } from "react";
import type { ChannelSummary } from "../../features/relay/contracts";
import type { ChannelLifecycleAction } from "../../features/relay/channel-lifecycle-protocol";
import { Button } from "../../shared/design-system/ui/Button";
Expand All @@ -6,7 +7,10 @@ import {
SignOutIcon,
TrashIcon,
} from "../../shared/design-system/icons";
import type { LifecycleNoun } from "./ChannelLifecycleDialog";
import {
lifecycleFocusFallback,
type LifecycleNoun,
} from "./ChannelLifecycleDialog";
import { useLifecycleOffer, type LifecycleSession } from "./useLifecycleOffer";

/** The archived footer uses the same live permissions as Settings. */
Expand Down Expand Up @@ -48,18 +52,37 @@ export function ChannelLifecycleActions({
noun?: LifecycleNoun;
}) {
const permissions = useLifecycleOffer(session, channel);
// A refreshed or live role can retire the focused action. Ref cleanup runs
// before its button detaches, while it still owns focus; keep focus in the
// pane unless something else took it meanwhile.
const retire = useCallback((node: HTMLButtonElement | null) => {
if (!node) return;
return () => {
const document = node.ownerDocument;
if (document.activeElement !== node) return;
const fallback = lifecycleFocusFallback(node);
queueMicrotask(() => {
if (!node.isConnected && document.activeElement === document.body)
fallback?.focus({ preventScroll: true });
});
};
}, []);
if (!session.channelLifecycle.available)
return <p>Channel actions unavailable on this connection</p>;
return (
<>
{permissions?.canLeave && (
<Button onClick={(event) => choose("leave", event.currentTarget)}>
<Button
ref={retire}
onClick={(event) => choose("leave", event.currentTarget)}
>
<SignOutIcon size={16} aria-hidden="true" />
Leave {noun}
</Button>
)}
{(permissions?.canArchive || permissions?.canUnarchive) && (
<Button
ref={retire}
onClick={(event) =>
choose(
permissions.canUnarchive ? "unarchive" : "archive",
Expand All @@ -73,6 +96,7 @@ export function ChannelLifecycleActions({
)}
{permissions?.canDelete && (
<Button
ref={retire}
variant="destructive"
onClick={(event) => choose("delete", event.currentTarget)}
>
Expand Down
47 changes: 33 additions & 14 deletions src/bundled/channels/ChannelLifecycleDialog.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
} from "@testing-library/react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import {
ChannelLifecycleStale,
ChannelLifecycleUnconfirmed,
type ChannelLifecycleCapability,
} from "../../features/relay/channel-lifecycle";
Expand Down Expand Up @@ -174,10 +175,17 @@ it.each([
[
"a pause after a possible send",
new ChannelLifecycleUnconfirmed(new ApiPaused(1000)),
{ unconfirmed: true, refresh: true },
],
[
"a permission that changed before sending",
new ChannelLifecycleStale("This action is no longer permitted."),
{ unconfirmed: false, refresh: true },
],
[
"an unsent publication",
new PublishNotSent("Relay requests paused; retry in 1s"),
{ unconfirmed: false, refresh: false },
],
[
"an untyped error with pause text",
Expand All @@ -187,21 +195,32 @@ it.each([
429,
1000,
),
{ unconfirmed: false, refresh: false },
],
["any other failure", new Error("Relay rejected the request.")],
])("delete keeps the existing failure report for %s", async (_, error) => {
const lifecycle = capability();
lifecycle.run.mockRejectedValueOnce(error);
const { failed } = mount(lifecycle);
fireEvent.click(screen.getByRole("button", { name: "Delete channel" }));
await flush();
expect(failed).toHaveBeenCalledExactlyOnceWith(
"Delete channel failed",
error.message,
error instanceof ChannelLifecycleUnconfirmed,
);
expect(screen.queryByRole("button", { name: "Retry" })).toBeNull();
});
[
"any other failure",
new Error("Relay rejected the request."),
{ unconfirmed: false, refresh: false },
],
])(
"delete keeps the existing failure report for %s",
async (_, error, flags) => {
const lifecycle = capability();
lifecycle.run.mockRejectedValueOnce(error);
const { failed } = mount(lifecycle);
fireEvent.click(screen.getByRole("button", { name: "Delete channel" }));
await flush();
expect(failed).toHaveBeenCalledExactlyOnceWith(
"Delete channel failed",
error.message,
// Only an unconfirmed failure may have been applied; refreshing channels
// recovers any stale one, sent or not.
flags.unconfirmed,
flags.refresh,
);
expect(screen.queryByRole("button", { name: "Retry" })).toBeNull();
},
);

it.each([
["leave", "Leave channel"],
Expand Down
24 changes: 22 additions & 2 deletions src/bundled/channels/ChannelLifecycleDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { Button } from "../../shared/design-system/ui/Button";
import {
ChannelLifecycleStale,
ChannelLifecycleUnconfirmed,
type ChannelLifecycleCapability,
} from "../../features/relay/channel-lifecycle";
Expand All @@ -19,6 +20,18 @@ export const lifecycleNoun = (
channel: Readonly<{ channelType?: string | undefined }> | undefined,
): LifecycleNoun => (channel?.channelType === "solo" ? "chat" : "channel");

/** Where focus goes when a lifecycle trigger is retired. Settings actions can
* remount after an archive-state or role change; the tab header lives outside
* the settings aside. */
export const lifecycleFocusFallback = (trigger: HTMLElement) =>
trigger
.closest("[data-panel-workspace]")
?.querySelector<HTMLElement>(
'button[aria-label="Close Channel settings tab"]',
) ??
trigger.closest("aside")?.querySelector<HTMLElement>("button") ??
undefined;

const details = {
channel: {
archive:
Expand Down Expand Up @@ -100,8 +113,14 @@ export function ChannelLifecycleDialog({
onSubmit?(): void;
finalFocus?: DialogProps["finalFocus"];
/** `unconfirmed`: the relay may have applied it anyway
* (`ChannelLifecycleUnconfirmed`). */
failed?(title: string, message: string, unconfirmed: boolean): void;
* (`ChannelLifecycleUnconfirmed`). `refresh`: refreshing channels is the
* recovery (`ChannelLifecycleStale`, which every unconfirmed failure is). */
failed?(
title: string,
message: string,
unconfirmed: boolean,
refresh: boolean,
): void;
/** Already chosen without a dialog, as Undo is: run it on mount. */
confirmed?: boolean;
/** Offered from an immediate archive's result toast. */
Expand Down Expand Up @@ -206,6 +225,7 @@ export function ChannelLifecycleDialog({
`${copy.title} failed`,
message,
error instanceof ChannelLifecycleUnconfirmed,
error instanceof ChannelLifecycleStale,
);
else setError(message);
}
Expand Down
50 changes: 48 additions & 2 deletions src/bundled/channels/ChannelLifecycleMenu.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
import userEvent from "@testing-library/user-event";
import { ContextMenuRoot, MenuPopup } from "../../shared/design-system/ui/Menu";
import {
ChannelLifecycleStale,
ChannelLifecycleUnconfirmed,
type ChannelLifecycleCapability,
} from "../../features/relay/channel-lifecycle";
Expand Down Expand Up @@ -499,6 +500,48 @@ it("uncertain delivery reports refresh guidance in a toast without offering blin
expect(lifecycle.run).toHaveBeenCalledOnce();
});

it.each([
[
"a permission that changed",
new ChannelLifecycleStale(
"This action is no longer permitted. Refresh channels to see what you can do now.",
),
false,
],
[
"an unconfirmed result",
new ChannelLifecycleUnconfirmed("connection lost"),
true,
],
])("flags %s for a channel refresh", async (_, error, unconfirmed) => {
const lifecycle = capability();
lifecycle.run.mockRejectedValueOnce(error);
const failed = vi.fn();
render(
<ToastProvider>
<ChannelLifecycleDialog
channelId="id"
channelName="Fixture"
action="archive"
lifecycle={lifecycle}
close={() => {}}
completed={() => {}}
failed={failed}
/>
</ToastProvider>,
);
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Archive channel" }));
await waitFor(() =>
expect(failed).toHaveBeenCalledExactlyOnceWith(
"Archive channel failed",
error.message,
unconfirmed,
true,
),
);
});

it.each(
([{ action: "delete", label: "Delete channel" }] as const).flatMap(
({ action, label }) =>
Expand Down Expand Up @@ -683,8 +726,8 @@ it("chat archive runs without confirmation, then Undo unarchives from its result
completed();
setOpen(false);
}}
failed={(title, message) => {
failed(title, message);
failed={(title, message, unconfirmed, refresh) => {
failed(title, message, unconfirmed, refresh);
setOpen(false);
}}
undo={() => {
Expand Down Expand Up @@ -735,6 +778,9 @@ it("chat archive runs without confirmation, then Undo unarchives from its result
expect(failed).toHaveBeenCalledExactlyOnceWith(
"Unarchive chat failed",
"Relay rejected the request.",
false,
// A refusal is not stale state; refreshing channels would not help.
false,
),
);
await waitFor(() =>
Expand Down
44 changes: 41 additions & 3 deletions src/bundled/channels/ChannelSettingsPanel.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -616,22 +616,60 @@ it("runs the matching command, stays pending until it settles, then follows the
});

it.each([
// As the transport shows a refusal: the relay's words without their prefix.
[
"the relay's own reason",
new PublishRejected("rejected", "invalid: actor not authorized"),
"invalid: actor not authorized",
new PublishRejected(
"Actor not authorized",
"invalid: actor not authorized",
),
"Actor not authorized",
],
[
"the relay's forbidden reason",
new PublishRejected(
"Only owners and admins can change auto-join",
"forbidden: only owners and admins can change auto-join",
),
"Only owners and admins can change auto-join",
],
[
"a long relay reason, clipped,",
new PublishRejected(
`Actor not authorized ${"x".repeat(1000)}`,
`invalid: actor not authorized ${"x".repeat(1000)}`,
),
`Actor not authorized ${"x".repeat(1000)}`.slice(0, 256),
],
[
"the default reason",
new PublishRejected("rejected"),
"Only community owners and admins can change this.",
],
[
"the default reason for text that is not the relay's",
new PublishRejected(
"Relay rejected the message (403)",
"Forbidden by proxy",
),
"Only community owners and admins can change this.",
],
// `auth-required:` stays prefixed for writers to match on; it refuses the
// sign-in, so an owner is not told they lack the role.
[
"the relay's sign-in refusal",
new PublishRejected(
"auth-required: authentication required",
"auth-required: authentication required",
),
"Authentication required",
],
[
"a retry for an unconfirmed outcome",
// As the lifecycle owner throws it when readback never shows the flag.
new ChannelLifecycleUnconfirmed(
new Error(
"The relay accepted the request, but the change is not confirmed. Refresh channels before trying again.",
"The relay accepted the request, but the change is not confirmed.",
),
),
"Saved, but not confirmed yet. Try again to check.",
Expand Down
Loading
Loading