Skip to content
Merged
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
76 changes: 76 additions & 0 deletions wxt/entrypoints/background/dailySchedule.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,19 @@ describe('scheduleDailyCheckAlarm', () => {

// "Claim points" alone (no daily set, no daily searches) still needs the
// once-per-day gate to run, so it has to arm the alarm on its own too.
// This runs on every worker start, and re-creating an alarm restarts its
// countdown, so a worker woken more often than every 6 hours used to keep
// pushing the day check back.
it('leaves an already armed alarm on its schedule', async () => {
await seed({});
const when = Date.now() + 60 * 60 * 1000;
await fakeBrowser.alarms.create('dailyCheck', { when, periodInMinutes: 360 });

await scheduleDailyCheckAlarm();

expect((await fakeBrowser.alarms.get('dailyCheck'))?.scheduledTime).toBe(when);
});

it('arms the alarm when only "Claim points" is enabled', async () => {
await seed({ active: false, autoDaily: false, claimPoints: true });

Expand Down Expand Up @@ -310,6 +323,69 @@ describe('handleDailyCheckAlarm', () => {
expect(await getStorageItem<string>('lastOpened', StorageValues.SYNC)).toBe(new Date().toLocaleDateString());
});

// On a morning start Chrome can deliver onStartup and the daily-check alarm
// that came due overnight together. Both used to read yesterday's date before
// either recorded today, so the dashboard and the searches opened twice.
it('starts today\'s run once when startup and the alarm arrive together', async () => {
const urls = trackCreatedTabs();
await seed({ lastOpened: new Date(0).toLocaleDateString() });

await Promise.all([handleStartup(), handleDailyCheckAlarm({ name: 'dailyCheck' })]);
await flushPendingWork();

expect(urls.filter((url) => url === DASHBOARD_URL)).toHaveLength(1);
expect(urls.filter((url) => url.startsWith('https://www.bing.com/search?q='))).toHaveLength(1);
});

// The alarm can win the race outright: its run is already going when the
// startup handler's "leftover run" cleanup comes along, which used to stop it
// after the first search.
it('keeps a run the alarm started just before the startup handler ran', async () => {
trackCreatedTabs();
await seed({ lastOpened: new Date(0).toLocaleDateString() });

await handleDailyCheckAlarm({ name: 'dailyCheck' });
await handleStartup();
await flushPendingWork();

expect(await getStorageItem<boolean>('isSearching', StorageValues.SYNC)).toBe(true);
expect(await fakeBrowser.alarms.get('openTabAlarm')).toBeDefined();
});

it('starts the run once and keeps it when the alarm is delivered first', async () => {
const urls = trackCreatedTabs();
await seed({ lastOpened: new Date(0).toLocaleDateString() });

await Promise.all([handleDailyCheckAlarm({ name: 'dailyCheck' }), handleStartup()]);
await flushPendingWork();

expect(urls.filter((url) => url.startsWith('https://www.bing.com/search?q='))).toHaveLength(1);
expect(await getStorageItem<boolean>('isSearching', StorageValues.SYNC)).toBe(true);
});

it('keeps taking daily checks after one of them fails', async () => {
await seed({ autoDaily: false, lastOpened: new Date(0).toLocaleDateString() });
vi.spyOn(fakeBrowser.tabs, 'create').mockRejectedValueOnce(new Error('tab refused'));

await expect(handleDailyCheckAlarm({ name: 'dailyCheck' })).rejects.toThrow('tab refused');
const urls = trackCreatedTabs();
await handleDailyCheckAlarm({ name: 'dailyCheck' });

expect(urls.some((url) => url.startsWith('https://www.bing.com/search?q='))).toBe(true);
});

it('still stops a run left over from before the browser restarted', async () => {
trackCreatedTabs();
await seed({ active: false, autoDaily: false, isSearching: true, currentSearch: 3 });
await setStorageItems({ runStartedAt: 0 }, StorageValues.LOCAL);
await fakeBrowser.alarms.create('openTabAlarm', { delayInMinutes: 1 });

await handleStartup();

expect(await getStorageItem<boolean>('isSearching', StorageValues.SYNC)).toBe(false);
expect(await fakeBrowser.alarms.get('openTabAlarm')).toBeUndefined();
});

it('does nothing when today has already run', async () => {
const urls = trackCreatedTabs();
await seed({ lastOpened: new Date().toLocaleDateString() });
Expand Down
67 changes: 53 additions & 14 deletions wxt/entrypoints/background/dailySchedule.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { storage } from '#imports';
import { browser } from 'wxt/browser';
import { getStorageItems, setStorageItem, setStorageItems } from '@/entrypoints/hooks/useStorage';
import { getStorageItem, getStorageItems, setStorageItem, setStorageItems } from '@/entrypoints/hooks/useStorage';
import { StorageValues } from '@/entrypoints/enums/storageValues';
import { toInt } from '@/entrypoints/utils/search';
import { DEFAULTS } from '@/entrypoints/utils/settings';
Expand All @@ -18,6 +18,24 @@ const DAILY_CHECK_ALARM = 'dailyCheck';
// gate periodically so the day rollover is caught without needing a restart.
const DAILY_CHECK_PERIOD_MINUTES = 360;

// When runRewards last started something (local area). Compared with when this
// worker started, it tells a run begun in this session from one left over from
// before a browser restart.
const RUN_STARTED_AT_KEY = 'runStartedAt';
const WORKER_STARTED_AT = Date.now();

// The startup handler and the daily-check alarm both run the once-a-day check,
// and on a morning start Chrome can deliver both together: the alarm came due
// while the browser was closed. Each waits for the one before it to finish, so
// the second sees today's date and the run happens once.
let dailyQueue: Promise<unknown> = Promise.resolve();

function oneAtATime<T>(task: () => Promise<T>): Promise<T> {
const result = dailyQueue.then(task, task);
dailyQueue = result.catch(() => {});
return result;
}

// Runs whatever the user has enabled: the dashboard visit if "Daily set" or
// "Claim points" is on, and the Bing searches if "Daily searches" is on. Both
// the automatic daily trigger and the popup's "Get rewards" button call this, so
Expand All @@ -41,6 +59,8 @@ export async function runRewards(): Promise<void> {
// meant not a single search ran that day. One tab covers both dashboard
// jobs — two would fight over the foreground, and the SPA only renders while
// it is visible.
const isStartingAnything = isDailySetEnabled || isClaimEnabled || (isSearchesEnabled && searches > 0);
if (isStartingAnything) await setStorageItem(RUN_STARTED_AT_KEY, Date.now());
if (isDailySetEnabled || isClaimEnabled) {
void openDailyRewards({
doDailySet: isDailySetEnabled,
Expand All @@ -52,7 +72,11 @@ export async function runRewards(): Promise<void> {
}
}

export async function checkLastOpened(): Promise<void> {
export function checkLastOpened(): Promise<void> {
return oneAtATime(runIfNewDay);
}

async function runIfNewDay(): Promise<void> {
const today = new Date().toLocaleDateString();
const s = await getStorageItems(['lastOpened'], StorageValues.SYNC);
if (s.lastOpened !== today) {
Expand All @@ -75,7 +99,11 @@ export async function scheduleDailyCheckAlarm(): Promise<void> {
(s.autoDaily ?? DEFAULTS.autoDaily) ||
(s.claimPoints ?? DEFAULTS.claimPoints);
if (isEnabled) {
browser.alarms.create(DAILY_CHECK_ALARM, { periodInMinutes: DAILY_CHECK_PERIOD_MINUTES });
// This runs on every worker start, and re-creating an alarm restarts its
// countdown, so one that is already armed keeps its schedule.
if (!(await browser.alarms.get(DAILY_CHECK_ALARM))) {
browser.alarms.create(DAILY_CHECK_ALARM, { periodInMinutes: DAILY_CHECK_PERIOD_MINUTES });
}
} else {
await browser.alarms.clear(DAILY_CHECK_ALARM);
}
Expand Down Expand Up @@ -120,16 +148,27 @@ export async function handleInstallOrUpdate(details: { reason: string }): Promis
}

export async function handleStartup(): Promise<void> {
// A search run never survives a browser restart, so clear its state *before*
// today's run is considered: alarms outlive the session and would resume
// opening Bing tabs on their own, and resetting the flag afterwards used to
// clobber the `isSearching` that a fresh run had just set.
await stopSearches();
await setStorageItems({ currentSearch: 0 }, StorageValues.SYNC);
// Tab ids do not survive a browser restart, so anything still registered for
// cleanup points at tabs that no longer exist.
await clearTrackedTabs();
const s = await getStorageItems(['active', 'autoDaily', 'claimPoints'], StorageValues.SYNC);
if (s.active || s.autoDaily || s.claimPoints) await checkLastOpened();
await oneAtATime(async () => {
// A search run never survives a browser restart, so clear its state *before*
// today's run is considered: alarms outlive the session and would resume
// opening Bing tabs on their own, and resetting the flag afterwards used to
// clobber the `isSearching` that a fresh run had just set. The daily-check
// alarm can start today's run just before this gets its turn, though, and
// that run belongs to this session, so it is left alone.
if (!(await hasRunStartedInThisWorker())) {
await stopSearches();
await setStorageItems({ currentSearch: 0 }, StorageValues.SYNC);
// Tab ids do not survive a browser restart, so anything still registered
// for cleanup points at tabs that no longer exist.
await clearTrackedTabs();
}
const s = await getStorageItems(['active', 'autoDaily', 'claimPoints'], StorageValues.SYNC);
if (s.active || s.autoDaily || s.claimPoints) await runIfNewDay();
});
await scheduleDailyCheckAlarm();
}

async function hasRunStartedInThisWorker(): Promise<boolean> {
const startedAt = await getStorageItem<number>(RUN_STARTED_AT_KEY);
return Number.isFinite(startedAt) && (startedAt as number) >= WORKER_STARTED_AT;
}
13 changes: 13 additions & 0 deletions wxt/entrypoints/components/HeartIcon.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
interface HeartIconProps {
className?: string;
size: number;
}

// GitHub Sponsors' heart. Decorative: every use sits beside text that says "Sponsor".
export default function HeartIcon({ className, size }: HeartIconProps) {
return (
<svg className={className} viewBox="0 0 16 16" width={size} height={size} aria-hidden="true">
<path d="M8 14.25.345 6.595a4.25 4.25 0 0 1 6.01-6.01L8 2.23 9.645.585a4.25 4.25 0 0 1 6.01 6.01Z" />
</svg>
);
}
2 changes: 1 addition & 1 deletion wxt/entrypoints/components/PhoneAppTile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export default function PhoneAppTile() {
<div className="phone-app-text">
<p className="prompt-card-title">Get the Android app</p>
<p className="prompt-card-body">Scan with your phone, or</p>
<a href={PHONE_APP_URL} className="prompt-card-primary phone-app-link" target="_blank" rel="noopener noreferrer">
<a href={PHONE_APP_URL} className="phone-app-link" target="_blank" rel="noopener noreferrer">
Open Google Play
</a>
</div>
Expand Down
35 changes: 22 additions & 13 deletions wxt/entrypoints/components/PromptCard.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,38 @@
import type { ReactNode } from 'react';
import HeartIcon from './HeartIcon';

interface PromptCardProps {
// Names the region for screen readers' landmark lists.
label: string;
title: ReactNode;
body: ReactNode;
onDismiss: () => void;
// The card's actions, primary first.
children: ReactNode;
// The ask itself, rendered before "Not now".
action: ReactNode;
// An optional quiet link after "Not now".
link?: ReactNode;
// The sponsor ask gets the header Sponsor button's pink, as a thank-you rather
// than another settings box.
isSponsor?: boolean;
}

// Shared shell for the popup's one-time asks: title, one line of text, actions.
// The dismiss button sits top-right but comes last in the DOM, so screen readers
// and Tab reach the ask and its actions before "Not now".
export default function PromptCard({ label, title, body, onDismiss, children }: PromptCardProps) {
// Shared shell for the popup's one-time asks, matching Prolific Studies Notifier's:
// title, one line of text, then the ask and a "Not now" of equal weight side by side.
export default function PromptCard({ label, title, body, onDismiss, action, link, isSponsor = false }: PromptCardProps) {
return (
<div className="prompt-card" role="region" aria-label={label}>
<div className={isSponsor ? 'prompt-card prompt-card--sponsor' : 'prompt-card'} role="region" aria-label={label}>
{isSponsor && (
<span className="prompt-card-badge" aria-hidden="true">
<HeartIcon size={16} />
</span>
)}
<h2 className="prompt-card-title">{title}</h2>
<p className="prompt-card-body">{body}</p>
<div className="prompt-card-actions">{children}</div>
<button type="button" className="prompt-card-dismiss" onClick={onDismiss} aria-label="Not now" title="Not now">
<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">
<path d="M3.5 3.5l9 9m0-9-9 9" />
</svg>
</button>
<div className="prompt-card-actions">
{action}
<button type="button" className="prompt-card-button prompt-card-button--quiet" onClick={onDismiss}>Not now</button>
{link}
</div>
</div>
);
}
122 changes: 122 additions & 0 deletions wxt/entrypoints/components/PromptCards.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { act, createElement, type ReactElement } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import ReviewPromptCard from './ReviewPromptCard';
import SponsorMilestoneCard from './SponsorMilestoneCard';
import { ISSUES_URL } from '@/entrypoints/utils/reviewPrompt';

// Tells React these renders run inside act(), so state updates flush synchronously.
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

let host: HTMLDivElement;
let root: Root;

function render(element: ReactElement): void {
act(() => root.render(element));
}

function buttonNamed(name: string): HTMLButtonElement {
const match = [...host.querySelectorAll('button')].find((b) => b.textContent?.trim() === name);
if (!match) throw new Error(`No button named "${name}"`);
return match;
}

function card(): HTMLElement {
return host.querySelector<HTMLElement>('[role="region"]')!;
}

beforeEach(() => {
host = document.createElement('div');
document.body.appendChild(host);
root = createRoot(host);
});

afterEach(() => {
act(() => root.unmount());
host.remove();
});

describe('ReviewPromptCard', () => {
it('asks about the extension by the name shown in the popup header', () => {
render(createElement(ReviewPromptCard, { onRate: vi.fn(), onDismiss: vi.fn() }));

expect(card().getAttribute('aria-label')).toBe('Rate this extension');
expect(card().querySelector('h2')?.textContent).toBe('Enjoying Search automatic rewards?');
});

it('rates from the primary button', () => {
const onRate = vi.fn();
render(createElement(ReviewPromptCard, { onRate, onDismiss: vi.fn() }));

act(() => buttonNamed('Rate it').click());

expect(onRate).toHaveBeenCalledOnce();
});

it('dismisses from a visible "Not now" button beside the rate button', () => {
const onDismiss = vi.fn();
render(createElement(ReviewPromptCard, { onRate: vi.fn(), onDismiss }));

const buttons = [...host.querySelectorAll('button')].map((b) => b.textContent?.trim());
expect(buttons).toEqual(['Rate it', 'Not now']);

act(() => buttonNamed('Not now').click());

expect(onDismiss).toHaveBeenCalledOnce();
});

it('links problem reports to GitHub issues in a new tab', () => {
render(createElement(ReviewPromptCard, { onRate: vi.fn(), onDismiss: vi.fn() }));

const link = host.querySelector('a')!;
expect(link.textContent).toBe('Not working? Report it');
expect(link.getAttribute('href')).toBe(ISSUES_URL);
expect(link.getAttribute('target')).toBe('_blank');
expect(link.getAttribute('rel')).toContain('noopener');
});
});

describe('SponsorMilestoneCard', () => {
it('thanks the user with their run count, highlighted', () => {
render(createElement(SponsorMilestoneCard, { completedRuns: 30, onSponsor: vi.fn(), onDismiss: vi.fn() }));

expect(card().getAttribute('aria-label')).toBe('Support this extension');
const title = card().querySelector('h2')!;
expect(title.textContent).toBe('30 search runs done for you');
expect(title.querySelector('strong')?.textContent).toBe('30');
});

it('says why sponsoring matters', () => {
render(createElement(SponsorMilestoneCard, { completedRuns: 30, onSponsor: vi.fn(), onDismiss: vi.fn() }));

expect(card().querySelector('p')?.textContent).toBe('Free and built in my spare time. Sponsoring keeps it working when Bing changes.');
});

it('shows a decorative heart badge hidden from screen readers', () => {
render(createElement(SponsorMilestoneCard, { completedRuns: 30, onSponsor: vi.fn(), onDismiss: vi.fn() }));

const badge = card().querySelector('.prompt-card-badge')!;
expect(badge.getAttribute('aria-hidden')).toBe('true');
});

it('sponsors from the primary button', () => {
const onSponsor = vi.fn();
render(createElement(SponsorMilestoneCard, { completedRuns: 30, onSponsor, onDismiss: vi.fn() }));

act(() => buttonNamed('Sponsor from $2').click());

expect(onSponsor).toHaveBeenCalledOnce();
});

it('dismisses from a visible "Not now" button after the sponsor button', () => {
const onDismiss = vi.fn();
render(createElement(SponsorMilestoneCard, { completedRuns: 30, onSponsor: vi.fn(), onDismiss }));

const buttons = [...host.querySelectorAll('button')].map((b) => b.textContent?.trim());
expect(buttons).toEqual(['Sponsor from $2', 'Not now']);

act(() => buttonNamed('Not now').click());

expect(onDismiss).toHaveBeenCalledOnce();
});
});
Loading
Loading