// Shared helpers for islands: REST calls with the shell's nonce, Lucide icons from the map PHP // localized (window.dashbread.icons), and the header badge updater the vanilla shell also uses. import { __, _n, sprintf } from '@wordpress/i18n'; export const cfg = window.dashbread || {}; export async function api(path, opts = {}) { const res = await fetch(cfg.rest + path, { credentials: 'same-origin', headers: { 'X-WP-Nonce': cfg.nonce, 'Content-Type': 'application/json', ...(opts.headers || {}) }, ...opts, }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data?.message || sprintf( /* translators: %s: HTTP status code */ __('Request failed (%s)', 'dashbread'), res.status )); return data; } /** `svg` (inner markup the server already resolved, e.g. a notification's iconSvg) wins over the localized map. */ export function Icon({ name, svg = '', size = 18, className = 'sui-i' }) { const inner = svg || (cfg.icons && cfg.icons[name]) || cfg.icons?.circle || cfg.icons?.bell || ''; return ; } /** Relative time from an ISO date, for lists that refresh in place without a server round trip. */ export function ago(iso) { const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000); if (s < 60) return __('just now', 'dashbread'); const m = s / 60; if (m < 60) return sprintf( /* translators: %s: number of minutes */ _n('%s min ago', '%s min ago', Math.floor(m), 'dashbread'), Math.floor(m) ); const h = m / 60; if (h < 24) return sprintf( /* translators: %s: number of hours */ _n('%s hr ago', '%s hrs ago', Math.floor(h), 'dashbread'), Math.floor(h) ); const d = h / 24; if (d < 30) return sprintf( /* translators: %s: number of days */ _n('%s day ago', '%s days ago', Math.floor(d), 'dashbread'), Math.floor(d) ); return new Date(iso).toLocaleDateString(document.documentElement.lang || undefined); } export function setBadge(n) { document.querySelectorAll('[data-sui-badge="notifications"]').forEach((b) => { b.textContent = n > 99 ? '99+' : String(n); if (n > 0) b.removeAttribute('hidden'); else b.setAttribute('hidden', ''); }); }