Compare commits

...
5 Commits
Author SHA1 Message Date
jaredandClaude Opus 4.8 360e72f73c a11y(polls): associate voter list with its answer for screen readers
CI / Trigger Desktop Build (push) Successful in 6s
CI / Build & Quality Checks (push) Successful in 10m46s
From review: the per-answer voter line sat inside the radiogroup with no
association, so a screen-reader user on the radio didn't hear who voted. Add
aria-describedby from each answer to its voter line (id poll-voters-<eventId>-
<answerId>) and prefix the line with "Voted by" for a clearer announcement.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-10 22:00:27 -04:00
jaredandClaude Opus 4.8 1aaea09fc9 feat(polls): "See who voted" — per-answer voter list
The poll card showed vote counts but never who voted, even though
computePollState already parses a sender for every response. Surface it:

- tallyResponses now also returns voters: Map<answerId, senderId[]>, built in the
  same latest-response-per-sender loop as the counts, so voters can never disagree
  with the numbers (voters.get(id).length === counts.get(id)). +5 unit tests.
- PollContent adds a "Show who voted" toggle, shown only when results are visible
  (disclosed live, or undisclosed after end — so a secret ballot stays secret).
  When on, each answer lists its voters' display names (getMemberName), rendered
  as a sibling of the answer button so the radiogroup keyboard model is untouched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-10 21:56:50 -04:00
jaredandClaude Opus 4.8 5cce94edba refactor(notifications): quiet-hours uses shared tested time-window helper
isInQuietHours was a hand-rolled, untested duplicate of the overnight-window
logic. Replace it with the shared, unit-tested isWithinTimeWindow (utils/
timeWindow.ts) - identical behavior for valid HH:MM inputs, more robust on
malformed ones (returns false rather than doing NaN math), and now covered by
timeWindow.test.ts. One implementation instead of two.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-10 20:43:08 -04:00
jaredandClaude Opus 4.8 f155a4dc22 feat(threads): up-arrow edits your last thread reply (+ fix cross-fire)
The thread composer reused RoomInput's hardcoded editableName="RoomInput", so
the main timeline's global up-arrow "edit last message" handler fired while
focused in a thread composer and targeted the MAIN timeline's last message
(wrong), and there was no up-arrow edit for the thread itself.

- Make editableName a RoomInput prop (default "RoomInput"); the thread composer
  passes "ThreadInput", so the two up-arrow handlers never cross-fire.
- Add an up-arrow-edit handler to ThreadTimeline (parity with RoomTimeline):
  empty thread composer + Up -> edit the latest editable reply in that thread,
  using thread.liveTimeline + canEditEvent + setEditId.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-10 20:28:26 -04:00
jaredandClaude Opus 4.8 61f1733f50 feat(notifications): cross-platform "Pause Notifications" / snooze
Manual DND only existed via the desktop tray (manualDndAtom), so web/mobile
users had no way to pause notifications, and there was no snooze-for-a-duration
anywhere. Add a "Pause Notifications" control in Settings > Notifications:

- Presets: 30 min / 1 hour / 4 hours / Until 8 AM / Until I resume, plus Resume;
  live "Paused until ..." status that flips back on when the snooze lapses.
- Persisted snooze instant (cinny_notification_snooze_until_v1) so it survives a
  reload; 0 = off, SNOOZE_INDEFINITE = until resumed.
- Feeds the existing notification gate (ClientNonUIFeatures, both the message and
  invite monitors) alongside Focus Assist / manual DND / Quiet Hours, suppressing
  notify() and playSound().
- Pure helpers isSnoozeActive/nextTimeAtHour/SNOOZE_INDEFINITE in utils/snooze.ts
  (+5 unit tests); persisted atom in state/notificationSnooze.ts.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-10 19:08:02 -04:00
12 changed files with 322 additions and 25 deletions

No files matched your search

+11 -1
View File
@@ -864,10 +864,11 @@ player.kick).
- **Vote / change / clear** in place — sends stable `m.poll.response` (`m.selections`); latest response per voter wins; clearing removes you from the tally. Multi-choice enforces `max_selections` ("Select up to N").
- **Disclosed vs undisclosed** — undisclosed polls hide counts/percentages/bars (and the vote total) until the poll ends; disclosed polls show live results.
- **See who voted** — a "Show who voted" toggle (shown only when results are visible, i.e. disclosed live or undisclosed-after-end) reveals the voter names under each answer. The voter list rides the same tally as the counts (`voters: Map<answerId, senderId[]>` populated in `tallyResponses`'s latest-response-per-sender loop), so it can never disagree with the numbers; a re-vote moves the voter, and a cleared vote drops them. Names via `getMemberName`; undisclosed polls stay secret until close.
- **End a poll** — the poll's creator or a moderator (redact power) can end it via an inline confirm; sends stable `m.poll.end`. Ended polls lock voting, show "Poll closed · Final results", reveal results, and highlight the winner(s) (ties supported). Only responses cast on/before the end event count.
- **Cross-client** — reads **both** the stable (`m.poll`/`m.id`/`m.selections`) and unstable (`org.matrix.msc3381.poll.*`) wire formats by hand (matrix-js-sdk 41.7.0's poll parsers only speak unstable), and uses the SDK `Poll` model for end-event validation (creator / redact-PL) + before-end response filtering. Polls authored in Element render/vote/end correctly and vice-versa.
- **Accessibility** — `radiogroup`/`radio` (single, with arrow-key roving) or `group`/`checkbox` (multi) semantics, `aria-checked`/`aria-disabled`, winner announced to AT.
- Pure tally/visibility/winner + wire-format parsing live in `utils/poll.ts` (+ `poll.test.ts`, 14 tests incl. the stable/unstable round-trip).
- Pure tally/visibility/winner/voters + wire-format parsing live in `utils/poll.ts` (+ `poll.test.ts`, 18 tests incl. the stable/unstable round-trip and voter attribution).
### Voice Message Playback (waveform + speed)
@@ -901,6 +902,8 @@ Root messages in the main timeline show a **"N replies · time"** chip (server-a
The panel embeds the full composer (uploads, emoji, stickers, GIFs, voice, location, polls) with drafts, reply state, and upload queues **isolated per thread** (`roomId::threadRootId` keys). Replies-to-replies produce spec-correct `m.thread` + `m.in_reply_to` (`is_falling_back: false`). Scheduling and slash commands are disabled inside threads (v1).
**↑ to edit last reply**: pressing Up-arrow in the empty thread composer opens the editor on your most recent editable reply *in that thread* — parity with the main timeline. The thread composer carries a distinct `editableName="ThreadInput"` so the main timeline's global up-arrow handler and the thread's no longer cross-fire (previously the thread composer had the same name, so Up-arrow there wrongly targeted the main timeline's last message).
### Notifications (Slack-style, P4-1)
By default you're notified for a thread reply only when you **participate** in that thread (you've posted in it) or the reply **@mentions** you — other threads accumulate quietly behind their chip badges. Every thread can be overridden from the bell menu in the panel header: **Default (participating) / All replies / Mentions only / Mute**. Modes sync across your devices (`io.lotus.thread_notifications` account data, auto-pruned). Muting a thread silences notifications and sounds, removes the chip's unread badge (a small bell-mute glyph shows instead), and subtracts that thread from the room's sidebar unread badge (client-side — other Matrix clients on the account still count it).
@@ -1259,6 +1262,13 @@ Accessible via **Room/Space Settings → Policy Lists** (admin only).
- Gates both `notify()` (visual/OS notifications) and `playSound()` (audio alerts)
- When active, notifications are silently dropped rather than queued
### Pause Notifications (snooze)
- A **cross-platform** "Pause Notifications" control in **Settings → Notifications** (the desktop-tray Do Not Disturb only worked on the desktop app; web/mobile had no manual pause).
- Quick presets: 30 minutes / 1 hour / 4 hours / Until 8 AM / **Until I resume** (indefinite), plus a **Resume** button; the tile shows the live "Paused until …" status (via `formatFriendlyDateTime`) and flips back to "on" the moment the snooze lapses.
- Persisted (`cinny_notification_snooze_until_v1`) as the epoch-ms instant to pause until (`0` = off), so a snooze survives a reload. Feeds the same notification gate as Focus Assist / Quiet Hours (`ClientNonUIFeatures`), suppressing both `notify()` and `playSound()`.
- Pure, unit-tested helpers `isSnoozeActive` / `nextTimeAtHour` / `SNOOZE_INDEFINITE` in `src/app/utils/snooze.ts` (`snooze.test.ts`); persisted atom in `src/app/state/notificationSnooze.ts`.
### Full Push Rule Editor
A complete UI for managing Matrix push notification rules:
@@ -4,6 +4,7 @@ import { Box, Chip, color, config, Icon, Icons, Text, toRem } from 'folds';
import { RelationsEvent } from 'matrix-js-sdk/lib/models/relations';
import { MatrixEvent, Room, RoomEvent, PollEvent } from 'matrix-js-sdk';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { getMemberName } from '../../../utils/room';
import {
ParsedPoll,
PollResponse,
@@ -16,7 +17,12 @@ import {
winningAnswerIds,
} from '../../../utils/poll';
const EMPTY_TALLY: PollTally = { counts: new Map(), myVotes: new Set(), total: 0 };
const EMPTY_TALLY: PollTally = {
counts: new Map(),
voters: new Map(),
myVotes: new Set(),
total: 0,
};
type PollState = { tally: PollTally; isEnded: boolean };
@@ -106,6 +112,7 @@ export function PollContent({
const [pending, setPending] = useState<Set<string> | null>(null);
const [confirmEnd, setConfirmEnd] = useState(false);
const [ending, setEnding] = useState(false);
const [showVoters, setShowVoters] = useState(false);
const refresh = useCallback(() => {
if (!eventId || !parsed) return;
@@ -194,8 +201,11 @@ export function PollContent({
const canEnd = !!eventId && !isEnded && (senderId === mx.getUserId() || canRedact);
const myVotes = pending ?? tally.myVotes;
const { counts, total } = tally;
const { counts, total, voters } = tally;
const winners = isEnded && showResults ? new Set(winningAnswerIds(counts)) : new Set<string>();
// Voter identities are shown under the same rule as the counts: disclosed polls
// reveal them live, undisclosed polls only once ended.
const canShowVoters = showResults && total > 0;
const handleVote = (answerId: string) => {
if (!roomId || !eventId || !canVote) return;
@@ -320,8 +330,8 @@ export function PollContent({
? 0
: -1;
return (
<React.Fragment key={id}>
<button
key={id}
type="button"
data-poll-answer
data-selected={selected}
@@ -329,6 +339,11 @@ export function PollContent({
aria-checked={selected}
aria-disabled={!canVote}
aria-label={isWinner ? `${text}, winning answer` : undefined}
aria-describedby={
showVoters && canShowVoters && (voters.get(id)?.length ?? 0) > 0
? `poll-voters-${eventId}-${id}`
: undefined
}
tabIndex={tabIndex}
onClick={canVote ? () => handleVote(id) : undefined}
style={{
@@ -416,9 +431,33 @@ export function PollContent({
)}
</span>
</button>
{showVoters && canShowVoters && (voters.get(id)?.length ?? 0) > 0 && (
<Text
id={`poll-voters-${eventId}-${id}`}
size="T200"
priority="300"
style={{ padding: `0 ${config.space.S300} ${config.space.S100}` }}
>
{`Voted by ${(voters.get(id) ?? []).map((s) => getMemberName(room, s)).join(', ')}`}
</Text>
)}
</React.Fragment>
);
})}
</Box>
{canShowVoters && (
<Box>
<Chip
variant={showVoters ? 'Primary' : 'SurfaceVariant'}
radii="Pill"
aria-pressed={showVoters}
onClick={() => setShowVoters((v) => !v)}
before={<Icon size="50" src={Icons.User} />}
>
<Text size="T200">{showVoters ? 'Hide voters' : 'Show who voted'}</Text>
</Chip>
</Box>
)}
<Box alignItems="Center" justifyContent="SpaceBetween" gap="200">
<Text size="T200" priority="300" style={{ minWidth: 0 }}>
<i>{footerNote}</i>
+6 -2
View File
@@ -151,9 +151,13 @@ interface RoomInputProps {
roomId: string;
room: Room;
threadRootId?: string;
// Identifies this composer to global key handlers (e.g. the up-arrow "edit last
// message" handler). Threads pass a distinct name so the main timeline's handler
// doesn't fire for the thread composer, and vice-versa.
editableName?: string;
}
export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
({ editor, fileDropContainerRef, roomId, room, threadRootId }, ref) => {
({ editor, fileDropContainerRef, roomId, room, threadRootId, editableName = 'RoomInput' }, ref) => {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline');
@@ -981,7 +985,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
)}
<ScheduledMessagesTray roomId={roomId} />
<CustomEditor
editableName="RoomInput"
editableName={editableName}
editor={editor}
placeholder="Send a message..."
onKeyDown={handleKeyDown}
@@ -196,6 +196,7 @@ export function ThreadPanel({ room, threadId, requestClose }: ThreadPanelProps)
roomId={room.roomId}
threadRootId={threadId}
editor={editor}
editableName="ThreadInput"
fileDropContainerRef={fileDropContainerRef}
/>
</Box>
@@ -32,11 +32,12 @@ import { useAtomValue, useSetAtom } from 'jotai';
import { Badge, Box, Chip, Icon, Icons, Line, Scroll, Spinner, Text, color, config } from 'folds';
import classNames from 'classnames';
import { Opts as LinkifyOpts } from 'linkifyjs';
import { isKeyHotkey } from 'is-hotkey';
import { eventWithShortcode, factoryEventSentBy } from '../../../utils/matrix';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { useVirtualPaginator, ItemRange } from '../../../hooks/useVirtualPaginator';
import { useAlive } from '../../../hooks/useAlive';
import { scrollToBottom } from '../../../utils/dom';
import { editableActiveElement, scrollToBottom } from '../../../utils/dom';
import {
DefaultPlaceholder,
MessageBase,
@@ -55,9 +56,11 @@ import {
renderMatrixMention,
} from '../../../plugins/react-custom-html-parser';
import {
canEditEvent,
decryptAllTimelineEvent,
getEditedEvent,
getEventReactions,
getLatestEditableEvt,
getMemberName,
getReactionContent,
reactionOrEditEvent,
@@ -76,7 +79,8 @@ import {
today,
yesterday,
} from '../../../utils/time';
import { createMentionElement, moveCursor } from '../../../components/editor';
import { createMentionElement, isEmptyEditor, moveCursor } from '../../../components/editor';
import { useKeyDown } from '../../../hooks/useKeyDown';
import { roomIdToReplyDraftAtomFamily } from '../../../state/room/roomInputDrafts';
import { usePowerLevelsContext } from '../../../hooks/usePowerLevels';
import { GetContentCallback, MessageEvent, StateEvent } from '../../../../types/matrix/room';
@@ -580,6 +584,32 @@ export function ThreadTimeline({ room, thread, editor }: ThreadTimelineProps) {
[editor],
);
// Up-arrow in the (empty) thread composer edits your last editable reply in
// this thread — parity with the main timeline. Gated on the thread composer's
// distinct editableName so it and the main handler never cross-fire.
useKeyDown(
window,
useCallback(
(evt) => {
if (
isKeyHotkey('arrowup', evt) &&
editableActiveElement() &&
document.activeElement?.getAttribute('data-editable-name') === 'ThreadInput' &&
isEmptyEditor(editor)
) {
const editableEvt = getLatestEditableEvt(thread.liveTimeline, (mEvt) =>
canEditEvent(mx, mEvt),
);
const editableEvtId = editableEvt?.getId();
if (!editableEvtId) return;
setEditId(editableEvtId);
evt.preventDefault();
}
},
[mx, thread, editor],
),
);
const handleOpenReply: MouseEventHandler = useCallback(
(evt) => {
const targetId = evt.currentTarget.getAttribute('data-event-id');
@@ -1,12 +1,20 @@
import React, { useCallback } from 'react';
import { Box, Text, Switch, Button, color, config, Spinner } from 'folds';
import React, { useCallback, useEffect, useState } from 'react';
import { Box, Text, Switch, Button, Chip, Icon, Icons, color, config, Spinner } from 'folds';
import { IPusherRequest } from 'matrix-js-sdk';
import { useAtomValue, useSetAtom } from 'jotai';
import { NOTIFICATION_SOUND_MAP } from '../../../utils/notificationSounds';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../styles.css';
import { SettingTile } from '../../../components/setting-tile';
import { useSetting } from '../../../state/hooks/settings';
import { settingsAtom } from '../../../state/settings';
import {
isSnoozeActive,
nextTimeAtHour,
notificationSnoozeUntilAtom,
SNOOZE_INDEFINITE,
} from '../../../state/notificationSnooze';
import { formatFriendlyDateTime } from '../../../utils/datetimeInput';
import { getNotificationState, usePermissionState } from '../../../hooks/usePermission';
import { useEmailNotifications } from '../../../hooks/useEmailNotifications';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
@@ -120,6 +128,72 @@ const selectStyle: React.CSSProperties = {
outline: 'none',
};
const SNOOZE_PRESETS: Array<{ label: string; resolve: (now: number) => number }> = [
{ label: '30 minutes', resolve: (now) => now + 30 * 60_000 },
{ label: '1 hour', resolve: (now) => now + 60 * 60_000 },
{ label: '4 hours', resolve: (now) => now + 4 * 60 * 60_000 },
{ label: 'Until 8 AM', resolve: (now) => nextTimeAtHour(8, now) },
{ label: 'Until I resume', resolve: () => SNOOZE_INDEFINITE },
];
// Cross-platform "pause notifications" — sets a snooze instant that the
// notification gate (ClientNonUIFeatures) reads to suppress alerts + sounds.
function PauseNotifications() {
const snoozeUntil = useAtomValue(notificationSnoozeUntilAtom);
const setSnoozeUntil = useSetAtom(notificationSnoozeUntilAtom);
// While paused, tick so the status flips to "on" the moment the snooze lapses.
const [, setTick] = useState(0);
const active = isSnoozeActive(snoozeUntil);
useEffect(() => {
if (!active) return undefined;
const id = setInterval(() => setTick((n) => n + 1), 30_000);
return () => clearInterval(id);
}, [active]);
const status = !active
? 'Notifications are on.'
: snoozeUntil >= SNOOZE_INDEFINITE
? 'Paused until you resume.'
: `Paused until ${formatFriendlyDateTime(snoozeUntil)}.`;
return (
<SettingTile
title="Pause Notifications"
description={
<span style={active ? { color: color.Warning.Main } : undefined}>{status}</span>
}
after={
active ? (
<Button
size="300"
variant="Secondary"
fill="Soft"
radii="300"
onClick={() => setSnoozeUntil(0)}
before={<Icon size="100" src={Icons.BellRing} />}
>
<Text size="B300">Resume</Text>
</Button>
) : undefined
}
>
<Box gap="200" wrap="Wrap" style={{ marginTop: config.space.S200 }}>
{SNOOZE_PRESETS.map((preset) => (
<Chip
key={preset.label}
variant="SurfaceVariant"
radii="Pill"
onClick={() => setSnoozeUntil(preset.resolve(Date.now()))}
>
<Text size="B300">{preset.label}</Text>
</Chip>
))}
</Box>
</SettingTile>
);
}
export function SystemNotification() {
const notifPermission = usePermissionState('notifications', getNotificationState());
const [showNotifications, setShowNotifications] = useSetting(settingsAtom, 'showNotifications');
@@ -174,6 +248,14 @@ export function SystemNotification() {
}
/>
</SequenceCard>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<PauseNotifications />
</SequenceCard>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
+10 -14
View File
@@ -14,6 +14,8 @@ import {
} from 'matrix-js-sdk';
import { focusAssistActiveAtom } from '../../state/focusAssist';
import { manualDndAtom } from '../../state/manualDnd';
import { isSnoozeActive, notificationSnoozeUntilAtom } from '../../state/notificationSnooze';
import { isWithinTimeWindow } from '../../utils/timeWindow';
import { roomToUnreadAtom } from '../../state/room/roomToUnread';
import LogoSVG from '../../../../public/res/lotus.png';
import LogoUnreadSVG from '../../../../public/res/lotus-unread.png';
@@ -68,18 +70,6 @@ import {
// the async invite-atom population lands first and isn't mistaken for new invites.
const INVITE_NOTIFY_ARM_DELAY_MS = 3000;
function isInQuietHours(start: string, end: string): boolean {
const now = new Date();
const [sh, sm] = start.split(':').map(Number);
const [eh, em] = end.split(':').map(Number);
const cur = now.getHours() * 60 + now.getMinutes();
const s = sh! * 60 + (sm ?? 0);
const e = eh! * 60 + (em ?? 0);
// start===end means zero-length window → treat as disabled (no quiet hours)
if (s === e) return false;
return s < e ? cur >= s && cur < e : cur >= s || cur < e;
}
function SystemEmojiFeature() {
const [twitterEmoji] = useSetting(settingsAtom, 'twitterEmoji');
@@ -157,6 +147,7 @@ function InviteNotifications() {
const [quietHoursEnabled] = useSetting(settingsAtom, 'quietHoursEnabled');
const focusAssistActive = useAtomValue(focusAssistActiveAtom);
const manualDnd = useAtomValue(manualDndAtom);
const snoozeUntil = useAtomValue(notificationSnoozeUntilAtom);
const [quietHoursStart] = useSetting(settingsAtom, 'quietHoursStart');
const [quietHoursEnd] = useSetting(settingsAtom, 'quietHoursEnd');
const [inviteSoundId] = useSetting(settingsAtom, 'inviteSoundId');
@@ -256,7 +247,8 @@ function InviteNotifications() {
const quietActive =
focusAssistActive ||
manualDnd ||
(quietHoursEnabled && isInQuietHours(quietHoursStart, quietHoursEnd));
isSnoozeActive(snoozeUntil) ||
(quietHoursEnabled && isWithinTimeWindow(quietHoursStart, quietHoursEnd));
if (quietActive) return;
if (showNotifications && notificationPermission('granted')) {
@@ -276,6 +268,7 @@ function InviteNotifications() {
quietHoursEnd,
focusAssistActive,
manualDnd,
snoozeUntil,
inviteSoundId,
]);
@@ -389,6 +382,7 @@ function MessageNotifications() {
const [quietHoursEnabled] = useSetting(settingsAtom, 'quietHoursEnabled');
const focusAssistActive = useAtomValue(focusAssistActiveAtom);
const manualDnd = useAtomValue(manualDndAtom);
const snoozeUntil = useAtomValue(notificationSnoozeUntilAtom);
const [quietHoursStart] = useSetting(settingsAtom, 'quietHoursStart');
const [quietHoursEnd] = useSetting(settingsAtom, 'quietHoursEnd');
const [messageSoundId] = useSetting(settingsAtom, 'messageSoundId');
@@ -533,7 +527,8 @@ function MessageNotifications() {
const quietActive =
focusAssistActive ||
manualDnd ||
(quietHoursEnabled && isInQuietHours(quietHoursStart, quietHoursEnd));
isSnoozeActive(snoozeUntil) ||
(quietHoursEnabled && isWithinTimeWindow(quietHoursStart, quietHoursEnd));
if (quietActive) return;
if (showNotifications && notificationPermission('granted')) {
@@ -569,6 +564,7 @@ function MessageNotifications() {
quietHoursEnd,
focusAssistActive,
manualDnd,
snoozeUntil,
messageSoundId,
],
);
+22
View File
@@ -0,0 +1,22 @@
import { atomWithStorage, createJSONStorage } from 'jotai/utils';
/**
* Cross-platform "pause notifications" / snooze.
*
* Unlike `manualDndAtom` (which only mirrors the desktop tray toggle and is
* session-only), this is a user-set snooze that works on web/mobile/desktop and
* survives a reload. The value is the epoch-ms instant until which notifications
* are paused; `0` means not snoozed. `SNOOZE_INDEFINITE` represents "paused until
* I turn it back on".
*
* The pure helpers live in `utils/snooze.ts` (unit-tested); re-exported here so
* consumers have a single import site.
*/
export { SNOOZE_INDEFINITE, isSnoozeActive, nextTimeAtHour } from '../utils/snooze';
export const notificationSnoozeUntilAtom = atomWithStorage<number>(
'cinny_notification_snooze_until_v1',
0,
createJSONStorage(() => localStorage),
{ getOnInit: true },
);
+45
View File
@@ -70,6 +70,51 @@ test('tallyResponses: re-voting after an empty clear counts the newest non-empty
assert.equal(total, 1);
});
test('tallyResponses: voters list the senders per answer, consistent with counts', () => {
const responses: PollResponse[] = [
{ sender: '@a:s', ts: 1, answerIds: ['1'] },
{ sender: '@b:s', ts: 1, answerIds: ['1'] },
{ sender: '@c:s', ts: 1, answerIds: ['2'] },
];
const { counts, voters } = tallyResponses(responses, me);
assert.deepEqual([...(voters.get('1') ?? [])].sort(), ['@a:s', '@b:s']);
assert.deepEqual(voters.get('2'), ['@c:s']);
// voters must always agree with counts
for (const [id, list] of voters) {
assert.equal(list.length, counts.get(id));
}
});
test('tallyResponses: a re-vote moves the sender to the new answer in voters', () => {
const responses: PollResponse[] = [
{ sender: '@a:s', ts: 1, answerIds: ['1'] },
{ sender: '@a:s', ts: 5, answerIds: ['2'] }, // changed vote
];
const { voters } = tallyResponses(responses, me);
assert.equal(voters.get('1'), undefined); // no longer under the old answer
assert.deepEqual(voters.get('2'), ['@a:s']);
});
test('tallyResponses: a cleared latest response drops the sender from every voter list', () => {
const responses: PollResponse[] = [
{ sender: '@a:s', ts: 1, answerIds: ['1', '2'] },
{ sender: '@a:s', ts: 2, answerIds: [] }, // cleared
];
const { voters } = tallyResponses(responses, me);
assert.equal(voters.get('1'), undefined);
assert.equal(voters.get('2'), undefined);
});
test('tallyResponses: multi-select lists a sender under each chosen answer', () => {
const responses: PollResponse[] = [
{ sender: '@a:s', ts: 1, answerIds: ['1', '3'] },
{ sender: '@b:s', ts: 1, answerIds: ['3'] },
];
const { voters } = tallyResponses(responses, me);
assert.deepEqual(voters.get('1'), ['@a:s']);
assert.deepEqual([...(voters.get('3') ?? [])].sort(), ['@a:s', '@b:s']);
});
test('resultsVisible: disclosed always, undisclosed only when ended', () => {
assert.equal(resultsVisible(false, false), true); // disclosed, open
assert.equal(resultsVisible(false, true), true); // disclosed, ended
+8 -1
View File
@@ -102,6 +102,9 @@ export type PollResponse = {
export type PollTally = {
/** answerId → number of voters who selected it. */
counts: Map<string, number>;
/** answerId → the sender ids who selected it (latest response per sender). Always
* consistent with `counts` — `voters.get(id).length === counts.get(id)`. */
voters: Map<string, string[]>;
/** answer ids the current user selected (from their latest response). */
myVotes: Set<string>;
/** number of distinct voters counted. */
@@ -126,6 +129,7 @@ export function tallyResponses(responses: PollResponse[], myUserId: string): Pol
}
const counts = new Map<string, number>();
const voters = new Map<string, string[]>();
const myVotes = new Set<string>();
let total = 0;
for (const [sender, r] of latestBySender) {
@@ -133,11 +137,14 @@ export function tallyResponses(responses: PollResponse[], myUserId: string): Pol
total += 1;
for (const id of r.answerIds) {
counts.set(id, (counts.get(id) ?? 0) + 1);
const list = voters.get(id);
if (list) list.push(sender);
else voters.set(id, [sender]);
if (sender === myUserId) myVotes.add(id);
}
}
return { counts, myVotes, total };
return { counts, voters, myVotes, total };
}
/**
+40
View File
@@ -0,0 +1,40 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { isSnoozeActive, nextTimeAtHour, SNOOZE_INDEFINITE } from './snooze';
test('isSnoozeActive: future instant is active, past/zero is not', () => {
const now = 1_000_000;
assert.equal(isSnoozeActive(now + 1, now), true);
assert.equal(isSnoozeActive(now, now), false);
assert.equal(isSnoozeActive(now - 1, now), false);
assert.equal(isSnoozeActive(0, now), false);
});
test('isSnoozeActive: SNOOZE_INDEFINITE stays active far into the future', () => {
const farFuture = Date.UTC(2100, 0, 1);
assert.equal(isSnoozeActive(SNOOZE_INDEFINITE, farFuture), true);
});
test('nextTimeAtHour: picks today when the hour is still ahead', () => {
const now = new Date(2026, 0, 5, 6, 30).getTime(); // 06:30 local
const target = nextTimeAtHour(8, now);
const d = new Date(target);
assert.equal(d.getHours(), 8);
assert.equal(d.getMinutes(), 0);
assert.equal(d.getDate(), 5); // still today
assert.ok(target > now);
});
test('nextTimeAtHour: rolls to tomorrow when the hour has passed', () => {
const now = new Date(2026, 0, 5, 9, 0).getTime(); // 09:00 local, past 08:00
const target = nextTimeAtHour(8, now);
const d = new Date(target);
assert.equal(d.getHours(), 8);
assert.equal(d.getDate(), 6); // tomorrow
});
test('nextTimeAtHour: exactly at the hour rolls to tomorrow (soonest future)', () => {
const now = new Date(2026, 0, 5, 8, 0).getTime(); // exactly 08:00
const target = nextTimeAtHour(8, now);
assert.equal(new Date(target).getDate(), 6);
});
+21
View File
@@ -0,0 +1,21 @@
// Pure helpers for the cross-platform "pause notifications" / snooze feature.
// Kept free of jotai/localStorage so they're unit-testable in isolation; the
// persisted atom lives in state/notificationSnooze.ts.
// Represents "paused until I turn it back on" (a far-future instant).
export const SNOOZE_INDEFINITE = Number.MAX_SAFE_INTEGER;
// Is the snooze currently active (i.e. suppressing notifications)?
export function isSnoozeActive(until: number, now: number = Date.now()): boolean {
return until > now;
}
// The soonest future instant at the given local hour (0-23), minute 0 — used for
// the "Until 8 AM" preset. If that hour has already passed today, rolls to
// tomorrow.
export function nextTimeAtHour(hour: number, now: number = Date.now()): number {
const d = new Date(now);
d.setHours(hour, 0, 0, 0);
if (d.getTime() <= now) d.setDate(d.getDate() + 1);
return d.getTime();
}