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
5 changes: 5 additions & 0 deletions .changeset/product-switcher-badges.md
Original file line number Diff line number Diff line change
@@ -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.
70 changes: 70 additions & 0 deletions src/composables/useProductBadges.spec.ts
Original file line number Diff line number Diff line change
@@ -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<typeof useProductBadges> | 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 })
})
})
79 changes: 79 additions & 0 deletions src/composables/useProductBadges.ts
Original file line number Diff line number Diff line change
@@ -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<ProductAddress[]>, options: UseProductBadgesOptions): Ref<Record<string, number>> {
const counts = ref<Record<string, number>>({})
const path = options.path ?? '/api/v1/badge/count'
const interval = options.interval ?? 60_000
let timer: ReturnType<typeof setInterval> | undefined
let asking = 0

async function ask(): Promise<void> {
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<string, number> = {}
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
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
10 changes: 10 additions & 0 deletions src/patterns/ProductSwitcher/UidProductSwitcher.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
25 changes: 25 additions & 0 deletions src/patterns/ProductSwitcher/UidProductSwitcher.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})
50 changes: 38 additions & 12 deletions src/patterns/ProductSwitcher/UidProductSwitcher.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed, type Component } from 'vue'
import { ArrowLeftRight } from 'lucide-vue-next'
import UidNotificationBadge from '../../components/NotificationBadge/UidNotificationBadge.vue'
import './UidProductSwitcher.css'

export interface UidProductSwitcherItem {
Expand All @@ -14,6 +15,11 @@ export interface UidProductSwitcherItem {
icon?: Component
/** The product the person is in now. */
current?: boolean
/**
* What waits for the person in that product (its bell's count). Shown over
* the icon of another product; the current one keeps it on its own bell.
*/
badge?: number
}

export interface UidProductSwitcherProps {
Expand All @@ -24,15 +30,22 @@ export interface UidProductSwitcherProps {
label?: string
/** Title of a link: receives the item, returns e.g. "Open KB-12 in Docs". Defaults to the label. */
hint?: (item: UidProductSwitcherItem) => string
/** Accessible name of a product with a count: receives the name and the count, e.g. "Messenger, 3 new". */
badgeLabel?: (name: string, count: number) => string
}

const props = withDefaults(defineProps<UidProductSwitcherProps>(), {
compact: false,
label: 'Products',
hint: undefined,
badgeLabel: (name: string, count: number) => `${name}, ${count}`,
})

const title = (item: UidProductSwitcherItem): string => (props.hint ? props.hint(item) : item.label)
const count = (item: UidProductSwitcherItem): number => (item.current ? 0 : Math.max(0, Math.floor(item.badge ?? 0)))
const named = (item: UidProductSwitcherItem): string => (props.hint ? props.hint(item) : item.label)
const title = (item: UidProductSwitcherItem): string => (count(item) > 0 ? props.badgeLabel(named(item), count(item)) : named(item))
// The compact button stands for every other product: what waits in all of them.
const others = computed<number>(() => props.items.reduce((sum, item) => sum + count(item), 0))

// The compact button leads to the product after the current one.
const next = computed<UidProductSwitcherItem | undefined>(() => {
Expand All @@ -47,22 +60,34 @@ const next = computed<UidProductSwitcherItem | undefined>(() => {
:class="{ 'uid-product-switcher--compact': compact }"
:aria-label="label"
>
<a
<UidNotificationBadge
v-if="compact && next"
class="uid-product-switcher__toggle"
:href="next.href"
:title="title(next)"
:aria-label="title(next)"
:count="others"
dot
class="uid-product-switcher__badge"
>
<ArrowLeftRight
:size="16"
aria-hidden="true"
/>
</a>
<template v-else>
<a
class="uid-product-switcher__toggle"
:href="next.href"
:title="title(next)"
:aria-label="title(next)"
>
<ArrowLeftRight
:size="16"
aria-hidden="true"
/>
</a>
</UidNotificationBadge>
<template v-else>
<UidNotificationBadge
v-for="item in items"
:key="item.key"
:count="count(item)"
:max="99"
class="uid-product-switcher__badge"
:data-test="`product-badge-${item.key}`"
>
<a
class="uid-product-switcher__item"
:class="{ 'uid-product-switcher__item--current': item.current }"
:href="item.current ? undefined : item.href"
Expand All @@ -84,6 +109,7 @@ const next = computed<UidProductSwitcherItem | undefined>(() => {
aria-hidden="true"
>{{ item.label.charAt(0) }}</span>
</a>
</UidNotificationBadge>
</template>
</nav>
</template>
Loading