diff --git a/.changeset/product-switcher-badges.md b/.changeset/product-switcher-badges.md new file mode 100644 index 0000000..90ec294 --- /dev/null +++ b/.changeset/product-switcher-badges.md @@ -0,0 +1,5 @@ +--- +'@dskripchenko/ui': minor +--- + +`UidProductSwitcher`: a product's count over its icon (`badge`, never on the current one; `badgeLabel` names it for screen readers; the compact button gets a dot). `useProductBadges(products, { current })` asks the organization's other products for their counts (`GET /api/v1/badge/count` with the session) every minute and when the tab comes back. diff --git a/src/composables/useProductBadges.spec.ts b/src/composables/useProductBadges.spec.ts new file mode 100644 index 0000000..b0b42c6 --- /dev/null +++ b/src/composables/useProductBadges.spec.ts @@ -0,0 +1,70 @@ +import { mount, flushPromises } from '@vue/test-utils' +import { defineComponent, h, ref } from 'vue' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useProductBadges, type ProductAddress } from './useProductBadges.js' + +function host(products: ProductAddress[], fetchFn: typeof fetch) { + let counts: ReturnType | undefined + const wrapper = mount( + defineComponent({ + setup() { + counts = useProductBadges(ref(products), { current: 'platform', fetch: fetchFn, interval: 1000 }) + return () => h('div') + }, + }), + ) + return { wrapper, counts: () => counts!.value } +} + +const answer = (body: unknown, ok = true) => Promise.resolve({ ok, json: () => Promise.resolve(body) } as Response) + +describe('useProductBadges', () => { + afterEach(() => vi.useRealTimers()) + + it('asks every other product for its count with the session, not the current one', async () => { + const fetchFn = vi.fn((url: string) => + url.startsWith('https://messenger.') ? answer({ success: true, payload: { count: 4 } }) : answer({ success: true, payload: { count: 0 } }), + ) as unknown as typeof fetch + const { counts } = host( + [ + { key: 'platform', url: 'https://platform.example.test' }, + { key: 'messenger', url: 'https://messenger.example.test' }, + { key: 'tracker', url: 'https://tracker.example.test/' }, + ], + fetchFn, + ) + await flushPromises() + expect(counts()).toEqual({ messenger: 4 }) + const calls = (fetchFn as unknown as { mock: { calls: [string, RequestInit][] } }).mock.calls + expect(calls.map((c) => c[0])).toEqual(['https://messenger.example.test/api/v1/badge/count', 'https://tracker.example.test/api/v1/badge/count']) + expect(calls[0]![1].credentials).toBe('include') + }) + + it('gives no count for a product that is down, signed out or answers something else', async () => { + const fetchFn = vi.fn((url: string) => + url.startsWith('https://messenger.') ? Promise.reject(new Error('down')) : url.startsWith('https://tracker.') ? answer({}, false) : answer({ success: true, payload: { count: 'many' } }), + ) as unknown as typeof fetch + const { counts } = host( + [ + { key: 'messenger', url: 'https://messenger.example.test' }, + { key: 'tracker', url: 'https://tracker.example.test' }, + { key: 'portal', url: 'https://portal.example.test' }, + ], + fetchFn, + ) + await flushPromises() + expect(counts()).toEqual({}) + }) + + it('asks again on its interval', async () => { + vi.useFakeTimers() + let n = 1 + const fetchFn = vi.fn(() => answer({ success: true, payload: { count: n++ } })) as unknown as typeof fetch + const { counts } = host([{ key: 'messenger', url: 'https://messenger.example.test' }], fetchFn) + await flushPromises() + expect(counts()).toEqual({ messenger: 1 }) + vi.advanceTimersByTime(1000) + await flushPromises() + expect(counts()).toEqual({ messenger: 2 }) + }) +}) diff --git a/src/composables/useProductBadges.ts b/src/composables/useProductBadges.ts new file mode 100644 index 0000000..45467b6 --- /dev/null +++ b/src/composables/useProductBadges.ts @@ -0,0 +1,79 @@ +import { onBeforeUnmount, onMounted, ref, unref, watch, type MaybeRef, type Ref } from 'vue' + +/** A product of the organization as the switcher gets it: its key and its address. */ +export interface ProductAddress { + key: string + url: string +} + +export interface UseProductBadgesOptions { + /** The product the person is in: its count is on its own bell, it is not asked. */ + current: string + /** Where a product answers its count, from its address. Default: `/api/v1/badge/count`. */ + path?: string + /** How often to ask, in ms. Default: a minute; also when the tab comes back. */ + interval?: number + /** The fetch to use (tests). Default: the global one. */ + fetch?: typeof fetch +} + +/** `{ success, payload: { count } }` — the count; anything else is no count. */ +function countOf(body: unknown): number | null { + if (!body || typeof body !== 'object') return null + const payload = (body as { payload?: unknown }).payload + const count = payload && typeof payload === 'object' ? (payload as { count?: unknown }).count : undefined + return typeof count === 'number' && Number.isFinite(count) && count >= 0 ? Math.floor(count) : null +} + +/** + * What waits for the person in the organization's other products: each one is + * asked for its count with the person's session there (`credentials: include`; + * the product lets its sibling products read the answer). A product that does + * not answer — down, signed out, without the method — has no count. + */ +export function useProductBadges(products: MaybeRef, options: UseProductBadgesOptions): Ref> { + const counts = ref>({}) + const path = options.path ?? '/api/v1/badge/count' + const interval = options.interval ?? 60_000 + let timer: ReturnType | undefined + let asking = 0 + + async function ask(): Promise { + const run = ++asking + const doFetch = options.fetch ?? (typeof fetch === 'undefined' ? undefined : fetch) + if (!doFetch) return + const others = unref(products).filter((p) => p.key !== options.current && /^https?:\/\//.test(p.url)) + const answers = await Promise.all( + others.map(async (p): Promise<[string, number | null]> => { + try { + const res = await doFetch(new URL(path, p.url).toString(), { credentials: 'include', headers: { Accept: 'application/json' } }) + return [p.key, res.ok ? countOf(await res.json()) : null] + } catch { + return [p.key, null] + } + }), + ) + // A later round has started: this one's answers are stale. + if (run !== asking) return + const next: Record = {} + for (const [key, count] of answers) if (count !== null && count > 0) next[key] = count + counts.value = next + } + + const onVisible = (): void => { + if (typeof document !== 'undefined' && document.visibilityState === 'visible') void ask() + } + + onMounted(() => { + void ask() + timer = setInterval(() => void ask(), interval) + if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisible) + }) + onBeforeUnmount(() => { + if (timer) clearInterval(timer) + if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisible) + }) + watch(() => unref(products).map((p) => `${p.key}=${p.url}`).join(' '), () => void ask()) + + return counts +} diff --git a/src/index.ts b/src/index.ts index a5c644c..6c509a0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -483,6 +483,8 @@ export type { UidLocale, UidPartialLocale, UidMediaLocale } from './locales/inde export { useTheme } from './composables/useTheme.js' export { useColorTheme, resetColorTheme, COLOR_THEME_STORAGE_KEY } from './composables/useColorTheme.js' export type { ThemeChoice, UseColorThemeOptions } from './composables/useColorTheme.js' +export { useProductBadges } from './composables/useProductBadges.js' +export type { ProductAddress, UseProductBadgesOptions } from './composables/useProductBadges.js' export { shouldSignInSilently, silentSignInUrl } from './utils/silentSignIn.js' export type { SilentSignInState } from './utils/silentSignIn.js' export { trackFocusModality } from './composables/useFocusModality.js' diff --git a/src/patterns/ProductSwitcher/UidProductSwitcher.css b/src/patterns/ProductSwitcher/UidProductSwitcher.css index 7e3379f..75de9d4 100644 --- a/src/patterns/ProductSwitcher/UidProductSwitcher.css +++ b/src/patterns/ProductSwitcher/UidProductSwitcher.css @@ -61,3 +61,13 @@ font-weight: var(--uid-font-weight-semibold); text-transform: uppercase; } + +/* A product's count over its icon, on the corner as on the bell, a size smaller. */ +.uid-product-switcher__badge { + --uid-notif-badge-size: 16px; +} + +.uid-product-switcher__badge .uid-notification-badge__count { + padding: 0 4px; + font-size: 10px; +} diff --git a/src/patterns/ProductSwitcher/UidProductSwitcher.spec.ts b/src/patterns/ProductSwitcher/UidProductSwitcher.spec.ts index 762f627..9ab398e 100644 --- a/src/patterns/ProductSwitcher/UidProductSwitcher.spec.ts +++ b/src/patterns/ProductSwitcher/UidProductSwitcher.spec.ts @@ -40,4 +40,29 @@ describe('UidProductSwitcher', () => { const wrapper = mount(UidProductSwitcher, { props: { items: [{ key: 'a', label: 'Alpha', href: '/a' }] } }) expect(wrapper.find('.uid-product-switcher__letter').text()).toBe('A') }) + + it('shows what waits in another product over its icon, never on the current one', () => { + const wrapper = mount(UidProductSwitcher, { + props: { + items: [{ ...items[0]!, badge: 3 }, { ...items[1]!, badge: 5 }], + badgeLabel: (name: string, n: number) => `${name}, ${n} new`, + }, + }) + expect(wrapper.find('[data-test="product-badge-docs"] .uid-notification-badge__count').text()).toBe('3') + expect(wrapper.find('[data-test="product-badge-tasks"] .uid-notification-badge__count').exists()).toBe(false) + expect(wrapper.findAll('a')[0]?.attributes('aria-label')).toBe('Docs, 3 new') + expect(wrapper.findAll('a')[1]?.attributes('aria-label')).toBe('Tasks') + }) + + it('shows no count for nothing, and 99+ for a lot', () => { + const none = mount(UidProductSwitcher, { props: { items: [{ ...items[0]!, badge: 0 }, items[1]!] } }) + expect(none.find('.uid-notification-badge__count').exists()).toBe(false) + const many = mount(UidProductSwitcher, { props: { items: [{ ...items[0]!, badge: 250 }, items[1]!] } }) + expect(many.find('.uid-notification-badge__count').text()).toBe('99+') + }) + + it('marks the compact button when something waits in another product', () => { + const wrapper = mount(UidProductSwitcher, { props: { items: [{ ...items[0]!, badge: 2 }, items[1]!], compact: true } }) + expect(wrapper.find('.uid-notification-badge__dot').exists()).toBe(true) + }) }) diff --git a/src/patterns/ProductSwitcher/UidProductSwitcher.vue b/src/patterns/ProductSwitcher/UidProductSwitcher.vue index c5cc4cc..5407566 100644 --- a/src/patterns/ProductSwitcher/UidProductSwitcher.vue +++ b/src/patterns/ProductSwitcher/UidProductSwitcher.vue @@ -1,6 +1,7 @@