[0]);
+ const action = ctx.conversation.registerMessageAction.mock
+ .calls[0]?.[0] as MessageAction;
const connect = (scope: string, reminders: unknown) => {
snapshot = {
status: "ready",
@@ -109,7 +117,7 @@ function mount(notifications?: unknown) {
const dispose = () => {
for (const body of stop.splice(0)) body();
};
- return { submit, connect, dispose };
+ return { submit, connect, dispose, action };
}
const at = (seconds: number) => vi.setSystemTime(seconds * 1000);
@@ -131,6 +139,73 @@ afterEach(() => {
vi.unstubAllGlobals();
});
+it.each([
+ [undefined, true],
+ ["accepted", true],
+ ["seen", true],
+ ["sending", false],
+ ["unknown", false],
+ ["failed", false],
+] as const)("offers Remind me on a %s message: %s", (delivery, offered) => {
+ const { action } = mount();
+ const message = { id: "m", ...(delivery ? { delivery } : {}) };
+ expect(
+ action.matches(
+ message as ChannelMessage,
+ {
+ reminders: session(Promise.resolve([])).capability,
+ } as unknown as RelaySession,
+ ),
+ ).toBe(offered);
+ // Without the reminder store there is nothing to offer, delivered or not.
+ expect(action.matches(message as ChannelMessage, {} as RelaySession)).toBe(
+ false,
+ );
+});
+
+it("labels a message's mark with its earliest pending due time", () => {
+ const { action } = mount();
+ const Marker = action.marker;
+ if (!Marker) throw new Error("Remind me has no marker");
+ const reminder = (
+ id: string,
+ status: "pending" | "done",
+ notBefore?: number,
+ ) => ({
+ id,
+ eventId: id,
+ createdAt: 1,
+ status,
+ ...(notBefore !== undefined ? { notBefore } : {}),
+ target,
+ });
+ const markup = (reminders: unknown[]) => {
+ const state = { status: "ready", hydrated: true, reminders };
+ return renderToStaticMarkup(
+ createElement(Marker, {
+ message: { id: target.eventId } as ChannelMessage,
+ session: {
+ reminders: { subscribe: () => () => {}, snapshot: () => state },
+ } as unknown as RelaySession,
+ }),
+ );
+ };
+ const label = `Reminder set for ${formatDue(2_000_000_000)}`;
+ const marked = markup([
+ reminder("later", "pending", 2_100_000_000),
+ reminder("done", "done", 1_900_000_000),
+ reminder("sooner", "pending", 2_000_000_000),
+ ]);
+ expect(marked).toContain(`aria-label="${label}"`);
+ // Announced once: a title or hint would repeat the label as a description.
+ expect(marked).not.toMatch(/title=|tooltip-trigger/);
+ // A due time Date cannot show still marks the message.
+ expect(markup([reminder("far", "pending", 8_640_000_000_001)])).toContain(
+ 'aria-label="Reminder set"',
+ );
+ expect(markup([reminder("done", "done", 2_000_000_000)])).toBe("");
+});
+
it("notifies a reminder from slow history even after a live update moved the clock", async () => {
let resolveHistory: (events: RelayEvent[]) => void = () => {};
const model = session(new Promise((resolve) => (resolveHistory = resolve)));
diff --git a/src/bundled/reminders/index.tsx b/src/bundled/reminders/index.tsx
index 4d9466aaf7..2e2c0bd302 100644
--- a/src/bundled/reminders/index.tsx
+++ b/src/bundled/reminders/index.tsx
@@ -9,10 +9,12 @@ import { AlarmIcon } from "../../shared/design-system/icons/index";
import {
countDue,
dueSince,
+ formatDue,
+ isDisplayable,
navigableTarget,
nextDelay,
nowSeconds,
- pendingMessageIds,
+ pendingMessageDue,
} from "./model";
import { RemindDialog } from "./RemindDialog";
import { RemindersPage } from "./RemindersPage";
@@ -265,23 +267,30 @@ export const apply: PluginModule["apply"] = (ctx) => {
reminders?.snapshot ?? noState,
reminders?.snapshot ?? noState,
);
- return pendingMessageIds(state).has(message.id) ? (
-
+ const due = pendingMessageDue(state);
+ if (!due.has(message.id)) return null;
+ const at = due.get(message.id);
+ const label =
+ at !== undefined && isDisplayable(at)
+ ? `Reminder set for ${formatDue(at)}`
+ : "Reminder set";
+ // Labelled only: a title would repeat the label as its description.
+ return (
+
- ) : null;
+ );
}
ctx.conversation.registerMessageAction({
id: "remind-me",
title: "Remind me",
icon: () => ,
- matches: (_message, session) => !!session.reminders,
+ // Like Reply and Report: a message the relay never stored has nothing to
+ // come back to.
+ matches: (message, session) =>
+ !!session.reminders &&
+ (!message.delivery || ["accepted", "seen"].includes(message.delivery)),
component: RemindDialog,
marker: Marker,
});
diff --git a/src/bundled/reminders/model.test.ts b/src/bundled/reminders/model.test.ts
index 0baef1489f..3999421e96 100644
--- a/src/bundled/reminders/model.test.ts
+++ b/src/bundled/reminders/model.test.ts
@@ -13,7 +13,7 @@ import {
nextDelay,
nowSeconds,
parseCustomDateTime,
- pendingMessageIds,
+ pendingMessageDue,
presetHint,
shiftedFrom,
todayDateString,
@@ -137,18 +137,24 @@ describe("reminder targets", () => {
).toBeUndefined();
});
- it("marks a message only while its reminder is pending, once per snapshot", () => {
+ it("marks a message only while a reminder is pending, at its earliest due time, once per snapshot", () => {
const state = {
status: "ready" as const,
hydrated: true,
reminders: [
- reminder({ id: "a", target: target("m") }),
+ reminder({ id: "a", target: target("m"), notBefore: 300 }),
reminder({ id: "b", target: target("d"), status: "done" }),
reminder({ id: "c" }),
+ reminder({ id: "d", target: target("m"), notBefore: 200 }),
+ reminder({ id: "e", target: target("m") }),
+ reminder({ id: "f", target: target("n") }),
],
};
- expect([...pendingMessageIds(state)]).toEqual(["m"]);
- expect(pendingMessageIds(state)).toBe(pendingMessageIds(state));
+ expect([...pendingMessageDue(state)]).toEqual([
+ ["m", 200],
+ ["n", undefined],
+ ]);
+ expect(pendingMessageDue(state)).toBe(pendingMessageDue(state));
});
});
diff --git a/src/bundled/reminders/model.ts b/src/bundled/reminders/model.ts
index 5b57facae5..56b7bf97ec 100644
--- a/src/bundled/reminders/model.ts
+++ b/src/bundled/reminders/model.ts
@@ -39,21 +39,32 @@ export function nextDelay(reminders: readonly Reminder[], now: number) {
: Math.min((next - now) * 1000, MAX_DELAY_MS);
}
-const pendingIds = new WeakMap>();
-/** Message ids with a pending reminder, derived once per reminders snapshot. */
-export function pendingMessageIds(state: RemindersState) {
- let ids = pendingIds.get(state);
- if (!ids) {
- ids = new Set(
- state.reminders.flatMap((reminder) =>
- reminder.status === "pending" && reminder.target
- ? [reminder.target.eventId]
- : [],
- ),
- );
- pendingIds.set(state, ids);
+const pendingDue = new WeakMap<
+ RemindersState,
+ ReadonlyMap
+>();
+/**
+ * Each message with a pending reminder, mapped to its earliest due time,
+ * derived once per reminders snapshot.
+ */
+export function pendingMessageDue(state: RemindersState) {
+ let due = pendingDue.get(state);
+ if (!due) {
+ const next = new Map();
+ for (const { status, target, notBefore } of state.reminders) {
+ if (status !== "pending" || !target) continue;
+ const earliest = next.get(target.eventId);
+ next.set(
+ target.eventId,
+ earliest !== undefined && notBefore !== undefined
+ ? Math.min(earliest, notBefore)
+ : (notBefore ?? earliest),
+ );
+ }
+ due = next;
+ pendingDue.set(state, due);
}
- return ids;
+ return due;
}
export type ReminderGroup = Readonly<{ label: string; reminders: Reminder[] }>;
@@ -95,7 +106,7 @@ export function endOfToday() {
}
/** The given day offset at 9am local, rolled forward a day if already past. */
-function nextDayAt9am(dayOffset: number) {
+export function nextDayAt9am(dayOffset: number) {
const now = new Date();
const target = new Date(now);
target.setDate(target.getDate() + dayOffset);
@@ -116,10 +127,41 @@ export const TIME_PRESETS: readonly TimePreset[] = [
},
];
+const dateString = (date: Date) =>
+ `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
+
/** Today as local `YYYY-MM-DD`, for the custom date input. */
-export function todayDateString() {
- const now = new Date();
- return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
+export const todayDateString = () => dateString(new Date());
+
+/** A time as local custom date and time values. */
+export function customInputs(at: number) {
+ const due = new Date(at * 1000);
+ return { date: dateString(due), time: due.toTimeString().slice(0, 5) };
+}
+
+/** A due time as custom date and time values, while that minute is still ahead. */
+export function dueInputs(at: number | undefined) {
+ if (at === undefined || !isDisplayable(at)) return undefined;
+ const inputs = customInputs(at);
+ return parseCustomDateTime(inputs.date, inputs.time) === null
+ ? undefined
+ : inputs;
+}
+
+/**
+ * Custom values that may still be the ones `due` was shown as. Local values
+ * can't say which pass through an hour repeated by daylight saving they mean,
+ * and parse as the first, so values still showing `due` keep its time.
+ */
+export function parseCustomOrDue(
+ date: string,
+ time: string,
+ due: number | undefined,
+) {
+ const at = parseCustomDateTime(date, time);
+ if (at === null || due === undefined) return at;
+ const shown = customInputs(due);
+ return shown.date === date && shown.time === time ? due : at;
}
/** A strictly future local date and time in unix seconds, or null. */
diff --git a/src/features/messages/MessageRow.test.tsx b/src/features/messages/MessageRow.test.tsx
index e5be7946b7..c473b9d920 100644
--- a/src/features/messages/MessageRow.test.tsx
+++ b/src/features/messages/MessageRow.test.tsx
@@ -3,6 +3,7 @@ import {
createLocalAgentActivity,
REPLY_CORRELATION_MS,
} from "../agents/local-activity";
+import { readFileSync } from "node:fs";
import { StrictMode } from "react";
import { schnorr } from "@noble/curves/secp256k1.js";
import { bytesToHex } from "nostr-tools/utils";
@@ -47,6 +48,7 @@ import { MessageRow } from "./MessageRow";
import { MessageContextMenus } from "./MessageActionBar";
import { ReplySummary } from "./ReplySummary";
import { setClockPreference } from "../../shared/clock-preference";
+import styles from "./Messages.module.css";
import { MessageManagement } from "./MessageManagement";
import type { ChannelMessage, Profile } from "../relay/contracts";
import type { AttachmentRendererProps } from "../conversation/contracts";
@@ -2877,6 +2879,80 @@ it("contains a broken plugin message action to its own contribution", () => {
}
});
+it("shows a plugin mark on a grouped message, once, outside its hidden byline", () => {
+ let marked = true;
+ const action = {
+ id: "mark",
+ title: "Mark",
+ key: "test.plugin/mark",
+ pluginId: "test.plugin",
+ revision: "one",
+ matches: () => true,
+ component: () => null,
+ marker: () =>
+ marked ? : null,
+ };
+ const actions = [action];
+ const none: never[] = [];
+ const channelList = { channels: [], status: "ready" };
+ const session = {
+ viewer: "viewer",
+ presence: {
+ subscribe: () => () => {},
+ status: () => "unknown",
+ limited: () => false,
+ },
+ messages: { report: undefined },
+ channels: { subscribeList: () => () => {}, list: () => channelList },
+ } as unknown as RelaySession;
+ const props = {
+ row: { ...row, replyCount: 0 },
+ session,
+ profile: undefined,
+ media: () => undefined,
+ onOpenLink: () => false,
+ day: false,
+ retry: undefined,
+ extensions: {
+ tools: { snapshot: () => none, subscribe: () => () => {} },
+ inline: { snapshot: () => none, subscribe: () => () => {} },
+ actions: { snapshot: () => actions, subscribe: () => () => {} },
+ },
+ };
+ const mark = () => {
+ // Announced once: not also inside the screen-reader byline.
+ const [only, ...others] = screen.getAllByRole("img", {
+ name: "Reminder set for later",
+ });
+ expect(others).toEqual([]);
+ return only as HTMLElement;
+ };
+ try {
+ const view = renderDom();
+ // jsdom applies no CSS, so the hidden byline is found by its class.
+ expect(mark().closest(".sr-only")).toBeNull();
+ // A copy leaves the mark out, as it does the hidden byline.
+ expect(mark().closest(".select-none")).not.toBeNull();
+ // A leading row keeps its mark in the byline, beside the time.
+ view.rerender();
+ expect(mark().closest(".sr-only")).toBeNull();
+ expect(mark().parentElement?.querySelector("time")).not.toBeNull();
+ cleanup();
+ // A marker with nothing to show leaves an empty line, which collapses.
+ // jsdom applies no CSS, so the stylesheet's rule is read directly.
+ marked = false;
+ const { container } = renderDom(
+ ,
+ );
+ expect(container.querySelector(`.${styles.marks}`)).toBeEmptyDOMElement();
+ expect(
+ readFileSync("src/features/messages/Messages.module.css", "utf8"),
+ ).toMatch(/\.marks:empty\s*\{\s*display:\s*none;\s*\}/);
+ } finally {
+ cleanup();
+ }
+});
+
it("contains a throwing plugin action icon and opened component", async () => {
const broken = () => {
throw new Error("broken contribution");
diff --git a/src/features/messages/MessageRow.tsx b/src/features/messages/MessageRow.tsx
index 46f09b3230..0899aa3ded 100644
--- a/src/features/messages/MessageRow.tsx
+++ b/src/features/messages/MessageRow.tsx
@@ -595,6 +595,16 @@ function MessageRowContent({
),
);
+ const markers =
+ session &&
+ actions.map(
+ (action) =>
+ action.marker && (
+
+
+
+ ),
+ );
// A message renderer may draw some attachments itself. Its claims count only
// while its card is mounted, and they return to the host list while its
// fallback shows. A remounted card starts healthy and claims again.
@@ -1257,19 +1267,16 @@ function MessageRowContent({
)}
- {session &&
- actions.map(
- (action) =>
- action.marker && (
-
-
-
- ),
- )}
+ {!stackPrevious && markers}
+ {/* A continuation's byline is hidden, so its marks get their own
+ line; like that byline, a copy leaves them out. A marker may
+ render nothing, so the line collapses while empty. */}
+ {stackPrevious && markers?.some(Boolean) && (
+
+ {markers}
+
+ )}
{row.sentFromThread && (
diff --git a/src/features/messages/Messages.module.css b/src/features/messages/Messages.module.css
index 279754ca7a..69c5b145a0 100644
--- a/src/features/messages/Messages.module.css
+++ b/src/features/messages/Messages.module.css
@@ -231,6 +231,9 @@
line-height: var(--text-body-sm--line-height);
letter-spacing: var(--text-body-sm--letter-spacing);
}
+.marks:empty {
+ display: none;
+}
.byline time {
color: var(--text-subtle);
font-size: var(--text-caption);
diff --git a/tests/browser/reminders-layout.fixture.tsx b/tests/browser/reminders-layout.fixture.tsx
index d4e18973e2..cb3490d2b2 100644
--- a/tests/browser/reminders-layout.fixture.tsx
+++ b/tests/browser/reminders-layout.fixture.tsx
@@ -151,6 +151,8 @@ const reminders: Reminders = {
cancel: async (id) =>
update(id, { status: "cancelled", notBefore: undefined }),
};
+// Specs stand in for another device by writing to the store directly.
+Object.assign(window, { reminders });
const connection = {
status: "ready",
scope: `https://community.example:${viewer}`,
diff --git a/tests/browser/reminders-layout.spec.mjs b/tests/browser/reminders-layout.spec.mjs
index 0ea2e86cf7..cf60d4a1ff 100644
--- a/tests/browser/reminders-layout.spec.mjs
+++ b/tests/browser/reminders-layout.spec.mjs
@@ -380,3 +380,31 @@ test("due reminder counts fit the dock at every supported text size", async ({
}
expect(unexplained()).toEqual([]);
});
+
+test("Custom… returns focus to the page once its reminder was the last one", async ({
+ page,
+}) => {
+ const { errors } = watchPageErrors(page);
+ await page.goto(`${url}?width=900`);
+ await page
+ .getByRole("button", { name: "Snooze: Ada Lovelace" })
+ .first()
+ .click();
+ await page.getByRole("menuitem", { name: "Custom…" }).click();
+ const dialog = page.getByRole("dialog", { name: "Snooze reminder" });
+ await expect(dialog).toBeVisible();
+ // Another device cancels every reminder while the dialog is open.
+ await page.evaluate(async () => {
+ for (const id of ["ordinary", "unbroken"])
+ await window.reminders.cancel(id);
+ });
+ await expect(dialog.getByText("This reminder was cancelled.")).toBeVisible();
+ await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
+ await expect(dialog).toHaveCount(0);
+ await expect(page.getByText("No reminders yet")).toBeVisible();
+ // The empty list has nothing to focus, so the page takes focus, not .
+ await expect(
+ page.getByRole("region", { name: "Reminders" }).locator(":scope > div"),
+ ).toBeFocused();
+ expect(errors).toEqual([]);
+});