@mundogamernetwork/shared-ui 1.18.1 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -51,6 +51,7 @@ Todas filtram por `systemId` (platform_id) e compartilham a mesma estrutura visu
51
51
  ### Plugins
52
52
  - **echo.client** - Laravel Echo / Pusher com auto-reconnect
53
53
  - **auth.client** - Auto-fetch do usuário ao montar o app
54
+ - **presence.client** - Heartbeat de presença (desligado por padrão, ver "Presença")
54
55
 
55
56
  ### Middleware
56
57
  - **auth.global** - Proteção de rotas configurável via `protectedRoutes`
@@ -198,6 +199,30 @@ Também pode ser usado direto: `<MgWhatsNewModal :suppress="meuModalAberto" :blo
198
199
  - Preview do admin: rota `/whats-new-preview` (noindex). O pai (iframe) envia `postMessage({ type: "mg-whats-new-preview", payload, theme?, lang? })` e recebe `{ type: "mg-whats-new-preview-ready" }`. Para QA: `/whats-new-preview?demo=image|video|embed|text&lang=pt-BR&theme=dark`.
199
200
  - Testes: `yarn test` (vitest via npx) cobre markup seguro, rotas bloqueadas, elegibilidade, embeds e idiomas.
200
201
 
202
+ ### Presença (quem está online / quem sumiu)
203
+
204
+ O plugin `presence.client` avisa a API, a cada ~2 minutos e só com a aba visível, que o usuário logado está ativo na plataforma. O network-admin usa isso para mostrar "Online" e "Última atividade" na lista de usuários e para os fluxos de reativação.
205
+
206
+ **Desligado por padrão.** Ligue por front quando a API desse front já rodar a versão do api-main que guarda o heartbeat no Redis (antes disso cada ping vira uma escrita no Postgres). O plugin usa o `VITE_SYSTEM_ID` do front como plataforma.
207
+
208
+ ```ts
209
+ // nuxt.config.ts do app
210
+ runtimeConfig: {
211
+ public: {
212
+ mgSharedUi: {
213
+ systemId: '1', // opcional se VITE_SYSTEM_ID já estiver definido
214
+ presence: { enabled: true, intervalSeconds: 120 } // nunca abaixo de 60
215
+ }
216
+ }
217
+ }
218
+ ```
219
+
220
+ Ou, sem mexer no código (vale em runtime): `NUXT_PUBLIC_MG_SHARED_UI_PRESENCE_ENABLED=true`.
221
+
222
+ - Chama `POST /public/user-status/heartbeat` com `{ platform_id }`. Sem `systemId` numérico, o plugin não faz nada.
223
+ - Acompanha o login pelo store `auth-store`, então funciona também nos apps que têm cópia própria do store (academy, agency) com o mesmo id.
224
+ - Para ao receber 401/403 e volta no próximo login; falhas de rede ou 5xx são ignoradas.
225
+
201
226
  ## Sobrescrita (Override)
202
227
 
203
228
  Por ser um Nuxt Layer, qualquer arquivo pode ser sobrescrito no app consumidor. Basta criar o arquivo com o mesmo caminho:
@@ -1,6 +1,7 @@
1
1
  <script setup lang="ts">
2
2
  import { ref } from "vue";
3
3
  import { storeToRefs } from "pinia";
4
+ import { formatBadge } from "../../utils/whatsNew";
4
5
 
5
6
  const authStore = useAuthStore();
6
7
  const indexStore = useIndexStore();
@@ -9,6 +10,12 @@ const notificationsStore = useNotificationsStore();
9
10
  const { user, signedIn } = storeToRefs(authStore);
10
11
  const { notificationCount } = storeToRefs(notificationsStore);
11
12
 
13
+ // "Novidades" history: the unread number rides on the profile avatar (the drawer opens from the user menu).
14
+ const whatsNewStore = useWhatsNewStore();
15
+ const whatsNewCfg: any = useRuntimeConfig().public.mgSharedUi?.whatsNew ?? {};
16
+ const whatsNewHistory = whatsNewCfg.enabled !== false && whatsNewCfg.history !== false;
17
+ const whatsNewBadge = computed(() => (whatsNewHistory && signedIn.value ? formatBadge(whatsNewStore.unread) : ""));
18
+
12
19
  const runtimeConfig = useRuntimeConfig();
13
20
  const features = runtimeConfig.public.mgSharedUi?.features ?? {};
14
21
 
@@ -117,6 +124,7 @@ onMounted(() => {
117
124
  class="rounded-circle"
118
125
  @error="(e: Event) => { const t = e.target as HTMLImageElement; if (t) { t.onerror = null; t.src = '/imgs/default-avatar.png' } }"
119
126
  />
127
+ <span v-if="whatsNewBadge" class="badge" aria-hidden="true">{{ whatsNewBadge }}</span>
120
128
  </a>
121
129
  </li>
122
130
 
@@ -136,6 +144,9 @@ onMounted(() => {
136
144
  />
137
145
  </transition>
138
146
 
147
+ <!-- Drawer + reopened announcement of the "Novidades" history: outside the dropdown so they outlive it. -->
148
+ <MgWhatsNewHistory v-if="signedIn" />
149
+
139
150
  <transition name="fade">
140
151
  <MgNotificationsModal
141
152
  v-if="showNotifications"
@@ -26,6 +26,11 @@ const runtimeConfig = useRuntimeConfig();
26
26
  const accountsBaseUrl = runtimeConfig.public.mgSharedUi?.accountsBaseUrl || runtimeConfig.public.accountsBaseUrl;
27
27
  const supportUrl = `${accountsBaseUrl}/account/support/new`;
28
28
  const features = runtimeConfig.public.mgSharedUi?.features ?? {};
29
+ // "Novidades" history entry (drawer mounted by MgHeaderComponent). On unless the front switches it off.
30
+ const whatsNewConfig: any = runtimeConfig.public.mgSharedUi?.whatsNew ?? {};
31
+ const whatsNewHistory = whatsNewConfig.enabled !== false && whatsNewConfig.history !== false;
32
+ // The entry only shows when the drawer host is mounted (MgHeaderComponent does it); a custom header without it hides the entry.
33
+ const whatsNewStore = useWhatsNewStore();
29
34
  const pricingUrl = runtimeConfig.public.mgSharedUi?.pricingUrl || "";
30
35
  const { locale } = useI18n();
31
36
 
@@ -214,6 +219,10 @@ const handleToggleOnline = () => {
214
219
  </a>
215
220
  </div>
216
221
 
222
+ <div v-if="whatsNewHistory && whatsNewStore.hostMounted" class="row info-row">
223
+ <MgWhatsNewMenuItem @opened="emit('toggleVisible')" />
224
+ </div>
225
+
217
226
  <div class="row info-row">
218
227
  <a :href="accountsBaseUrl" target="_blank" class="btn btn-primary-outline mt-3">
219
228
  {{ $t("account_menu.buttons.manage_account") }}
@@ -0,0 +1,468 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * Side drawer with the history of announcements ("Novidades"). Reads the store directly; the host
4
+ * (<MgWhatsNewHistory />) decides what happens when a row is opened. Colours come only from the
5
+ * --mg-wn-* tokens, layout is logical (RTL aware), and the focus is trapped while it is open.
6
+ */
7
+ import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";
8
+ import { formatBadge, isRtl, parseRich, richToPlain, toApiLang, type WnHistoryItem } from "../../utils/whatsNew";
9
+ import { wnText, type WnTextKey } from "../../utils/whatsNewText";
10
+
11
+ const props = defineProps<{ locale: string }>();
12
+ const emit = defineEmits<{
13
+ (e: "close"): void;
14
+ (e: "open", item: WnHistoryItem): void;
15
+ (e: "more"): void;
16
+ (e: "retry"): void;
17
+ }>();
18
+
19
+ const store = useWhatsNewStore();
20
+ const uid = Math.random().toString(36).slice(2, 8);
21
+ const titleId = `mg-wn-drawer-title-${uid}`;
22
+
23
+ const panel = ref<HTMLElement | null>(null);
24
+ const titleEl = ref<HTMLElement | null>(null);
25
+ let returnFocusTo: HTMLElement | null = null;
26
+ let previousOverflow = "";
27
+
28
+ const t = (key: WnTextKey) => wnText(props.locale, key);
29
+ const dir = computed(() => (isRtl(props.locale) ? "rtl" : "ltr"));
30
+ const badge = computed(() => formatBadge(store.unread));
31
+ const hasMore = computed(() => !!store.historyMeta && store.historyMeta.page < store.historyMeta.last_page);
32
+ const loading = computed(() => store.historyStatus === "loading");
33
+
34
+ const dateFormat = computed(() => {
35
+ try {
36
+ return new Intl.DateTimeFormat(toApiLang(props.locale), { dateStyle: "medium" });
37
+ } catch {
38
+ return null;
39
+ }
40
+ });
41
+
42
+ function dateOf(iso: string | null): string {
43
+ if (!iso || !dateFormat.value) return "";
44
+ const d = new Date(iso);
45
+ return Number.isNaN(d.getTime()) ? "" : dateFormat.value.format(d);
46
+ }
47
+
48
+ function kindLabel(item: WnHistoryItem) {
49
+ return t(`kind_${item.kind}` as WnTextKey);
50
+ }
51
+
52
+ function rowLabel(item: WnHistoryItem) {
53
+ return [item.is_new ? t("history_new") : "", item.title, kindLabel(item), dateOf(item.published_at)]
54
+ .filter(Boolean)
55
+ .join(", ");
56
+ }
57
+
58
+ /** The list shows plain text: `**bold**` and `[text](url)` in the summary are flattened. */
59
+ function summaryOf(item: WnHistoryItem): string {
60
+ return richToPlain(parseRich(item.summary, false));
61
+ }
62
+
63
+ function onBackdrop(event: MouseEvent) {
64
+ if (event.target === event.currentTarget) emit("close");
65
+ }
66
+
67
+ // ── focus management ──────────────────────────────────────────────────────
68
+ const FOCUSABLE = 'a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])';
69
+
70
+ function focusables(): HTMLElement[] {
71
+ if (!panel.value) return [];
72
+ return Array.from(panel.value.querySelectorAll<HTMLElement>(FOCUSABLE)).filter((el) => el.getClientRects().length > 0);
73
+ }
74
+
75
+ function onKeydown(event: KeyboardEvent) {
76
+ // A reopened announcement sits on top with its own handler: leave Esc and Tab to it.
77
+ if (store.viewing) return;
78
+ if (event.key === "Escape") {
79
+ event.stopPropagation();
80
+ emit("close");
81
+ return;
82
+ }
83
+ if (event.key !== "Tab") return;
84
+ const items = focusables();
85
+ if (!items.length) {
86
+ event.preventDefault();
87
+ titleEl.value?.focus();
88
+ return;
89
+ }
90
+ const first = items[0];
91
+ const last = items[items.length - 1];
92
+ const active = document.activeElement as HTMLElement | null;
93
+ const inside = !!active && !!panel.value?.contains(active);
94
+ if (event.shiftKey && (active === first || active === titleEl.value || !inside)) {
95
+ event.preventDefault();
96
+ last.focus();
97
+ } else if (!event.shiftKey && (active === last || !inside)) {
98
+ event.preventDefault();
99
+ first.focus();
100
+ }
101
+ }
102
+
103
+ onMounted(async () => {
104
+ returnFocusTo = document.activeElement instanceof HTMLElement ? document.activeElement : null;
105
+ previousOverflow = document.documentElement.style.overflow;
106
+ document.documentElement.style.overflow = "hidden";
107
+ document.addEventListener("keydown", onKeydown, true);
108
+ await nextTick();
109
+ titleEl.value?.focus({ preventScroll: true });
110
+ });
111
+
112
+ onBeforeUnmount(() => {
113
+ document.removeEventListener("keydown", onKeydown, true);
114
+ document.documentElement.style.overflow = previousOverflow;
115
+ if (returnFocusTo && document.contains(returnFocusTo)) returnFocusTo.focus({ preventScroll: true });
116
+ });
117
+ </script>
118
+
119
+ <template>
120
+ <div class="mg-wn-drawer-overlay" data-mg-wn :dir="dir" @mousedown="onBackdrop">
121
+ <aside ref="panel" class="mg-wn-drawer" role="dialog" aria-modal="true" :aria-labelledby="titleId" :aria-busy="loading">
122
+ <header class="mg-wn-drawer__head">
123
+ <div class="mg-wn-drawer__head-text">
124
+ <h2 :id="titleId" ref="titleEl" class="mg-wn-drawer__title" tabindex="-1">
125
+ {{ t("history_title") }}
126
+ <span v-if="badge" class="mg-wn-drawer__count" :aria-label="`${store.unread} ${t('history_unread')}`">{{ badge }}</span>
127
+ </h2>
128
+ <p class="mg-wn-drawer__sub">{{ t("history_subtitle") }}</p>
129
+ </div>
130
+ <button type="button" class="mg-wn-drawer__x" :aria-label="t('close')" @click="emit('close')">
131
+ <span aria-hidden="true">✕</span>
132
+ </button>
133
+ </header>
134
+
135
+ <p v-if="store.openError" class="mg-wn-drawer__alert" role="alert">{{ t("history_open_error") }}</p>
136
+
137
+ <div class="mg-wn-drawer__body">
138
+ <p v-if="loading" class="mg-wn-drawer__state" role="status">{{ t("history_loading") }}</p>
139
+
140
+ <div v-else-if="store.historyStatus === 'error' && !store.history.length" class="mg-wn-drawer__state" role="alert">
141
+ <p>{{ t("history_error") }}</p>
142
+ <button type="button" class="mg-wn-drawer__btn" @click="emit('retry')">{{ t("history_retry") }}</button>
143
+ </div>
144
+
145
+ <p v-else-if="!store.history.length" class="mg-wn-drawer__state">{{ t("history_empty") }}</p>
146
+
147
+ <ul v-else class="mg-wn-drawer__list">
148
+ <li v-for="item in store.history" :key="item.id">
149
+ <button
150
+ type="button"
151
+ class="mg-wn-row"
152
+ :class="{ 'mg-wn-row--new': item.is_new }"
153
+ :aria-label="rowLabel(item)"
154
+ :aria-busy="store.openingId === item.id"
155
+ :disabled="store.openingId !== null"
156
+ @click="emit('open', item)"
157
+ >
158
+ <img v-if="item.thumb_url" :src="item.thumb_url" alt="" class="mg-wn-row__thumb" loading="lazy" width="72" height="72" />
159
+ <span class="mg-wn-row__text">
160
+ <span class="mg-wn-row__meta">
161
+ <span class="mg-wn-row__kind" :class="`mg-wn-row__kind--${item.kind}`">{{ kindLabel(item) }}</span>
162
+ <span v-if="dateOf(item.published_at)" class="mg-wn-row__date">{{ dateOf(item.published_at) }}</span>
163
+ <span v-if="item.is_new" class="mg-wn-row__new">{{ t("history_new") }}</span>
164
+ </span>
165
+ <span class="mg-wn-row__title">{{ item.title }}</span>
166
+ <span v-if="summaryOf(item)" class="mg-wn-row__summary">{{ summaryOf(item) }}</span>
167
+ </span>
168
+ </button>
169
+ </li>
170
+ </ul>
171
+
172
+ <div v-if="store.history.length && (hasMore || store.historyStatus === 'loadingMore' || store.historyStatus === 'error')" class="mg-wn-drawer__more">
173
+ <p v-if="store.historyStatus === 'loadingMore'" role="status">{{ t("history_loading") }}</p>
174
+ <template v-else-if="store.historyStatus === 'error'">
175
+ <p role="alert">{{ t("history_error") }}</p>
176
+ <button type="button" class="mg-wn-drawer__btn" @click="emit('more')">{{ t("history_retry") }}</button>
177
+ </template>
178
+ <button v-else type="button" class="mg-wn-drawer__btn" @click="emit('more')">{{ t("history_more") }}</button>
179
+ </div>
180
+ </div>
181
+ </aside>
182
+ </div>
183
+ </template>
184
+
185
+ <style lang="scss" scoped>
186
+ .mg-wn-drawer-overlay {
187
+ position: fixed;
188
+ inset: 0;
189
+ z-index: 10040; // under the announcement dialog (10050), which opens on top of the drawer
190
+ display: flex;
191
+ justify-content: flex-end; // inline-end: right in LTR, left in RTL
192
+ background: var(--mg-wn-overlay);
193
+ font-family: inherit;
194
+ }
195
+
196
+ .mg-wn-drawer {
197
+ display: flex;
198
+ flex-direction: column;
199
+ width: min(420px, 100vw);
200
+ height: 100%;
201
+ color: var(--mg-wn-text);
202
+ background: var(--mg-wn-surface);
203
+ border-inline-start: 1px solid var(--mg-wn-border);
204
+ box-shadow: 0 0 40px var(--mg-wn-shadow);
205
+ animation: mg-wn-drawer-in 0.2s ease-out;
206
+
207
+ &:focus-visible,
208
+ & :focus-visible {
209
+ outline: 2px solid var(--mg-wn-accent);
210
+ outline-offset: 2px;
211
+ }
212
+
213
+ &__head {
214
+ display: flex;
215
+ align-items: flex-start;
216
+ justify-content: space-between;
217
+ gap: 12px;
218
+ padding: 16px 18px 12px;
219
+ border-bottom: 1px solid var(--mg-wn-border);
220
+ }
221
+
222
+ &__head-text {
223
+ min-width: 0;
224
+ }
225
+
226
+ &__title {
227
+ display: flex;
228
+ align-items: center;
229
+ gap: 8px;
230
+ margin: 0;
231
+ font-size: 1.25rem;
232
+ line-height: 1.25;
233
+ font-weight: 700;
234
+
235
+ &:focus {
236
+ outline: none;
237
+ }
238
+ }
239
+
240
+ &__count {
241
+ min-width: 20px;
242
+ height: 20px;
243
+ padding: 0 6px;
244
+ display: inline-flex;
245
+ align-items: center;
246
+ justify-content: center;
247
+ font-size: 0.6875rem;
248
+ font-weight: 700;
249
+ color: var(--mg-wn-on-accent);
250
+ background: var(--mg-wn-accent);
251
+ }
252
+
253
+ &__sub {
254
+ margin: 4px 0 0;
255
+ font-size: 0.8125rem;
256
+ color: var(--mg-wn-text-muted);
257
+ }
258
+
259
+ &__x {
260
+ flex: none;
261
+ display: grid;
262
+ place-items: center;
263
+ width: 32px;
264
+ height: 32px;
265
+ padding: 0;
266
+ font-size: 0.875rem;
267
+ color: var(--mg-wn-text-muted);
268
+ background: transparent;
269
+ border: 1px solid var(--mg-wn-border);
270
+ border-radius: 0;
271
+ cursor: pointer;
272
+
273
+ &:hover {
274
+ color: var(--mg-wn-text);
275
+ background: var(--mg-wn-surface-2);
276
+ }
277
+ }
278
+
279
+ &__alert {
280
+ margin: 0;
281
+ padding: 10px 18px;
282
+ font-size: 0.8125rem;
283
+ color: var(--mg-wn-warning);
284
+ background: var(--mg-wn-surface-2);
285
+ border-bottom: 1px solid var(--mg-wn-border);
286
+ }
287
+
288
+ &__body {
289
+ flex: 1;
290
+ overflow-y: auto;
291
+ overscroll-behavior: contain;
292
+ }
293
+
294
+ &__state {
295
+ margin: 0;
296
+ padding: 32px 18px;
297
+ text-align: center;
298
+ font-size: 0.9rem;
299
+ color: var(--mg-wn-text-muted);
300
+
301
+ p {
302
+ margin: 0 0 12px;
303
+ }
304
+ }
305
+
306
+ &__list {
307
+ list-style: none;
308
+ margin: 0;
309
+ padding: 0;
310
+ }
311
+
312
+ &__more {
313
+ padding: 14px 18px 20px;
314
+ text-align: center;
315
+ font-size: 0.8125rem;
316
+ color: var(--mg-wn-text-muted);
317
+
318
+ p {
319
+ margin: 0 0 10px;
320
+ }
321
+ }
322
+
323
+ &__btn {
324
+ padding: 8px 16px;
325
+ font: inherit;
326
+ font-size: 0.8125rem;
327
+ font-weight: 600;
328
+ color: var(--mg-wn-accent);
329
+ background: transparent;
330
+ border: 1px solid var(--mg-wn-accent);
331
+ border-radius: 0;
332
+ cursor: pointer;
333
+
334
+ &:hover {
335
+ color: var(--mg-wn-on-accent);
336
+ background: var(--mg-wn-accent);
337
+ }
338
+ }
339
+ }
340
+
341
+ .mg-wn-row {
342
+ display: flex;
343
+ align-items: flex-start;
344
+ gap: 12px;
345
+ width: 100%;
346
+ padding: 14px 18px;
347
+ font: inherit;
348
+ text-align: start;
349
+ color: var(--mg-wn-text);
350
+ background: transparent;
351
+ border: 0;
352
+ border-bottom: 1px solid var(--mg-wn-border);
353
+ cursor: pointer;
354
+
355
+ &:hover:not(:disabled) {
356
+ background: var(--mg-wn-surface-2);
357
+ }
358
+
359
+ &:disabled {
360
+ cursor: progress;
361
+ opacity: 0.7;
362
+ }
363
+
364
+ &--new {
365
+ border-inline-start: 3px solid var(--mg-wn-accent);
366
+ padding-inline-start: 15px;
367
+ }
368
+
369
+ &__thumb {
370
+ flex: none;
371
+ width: 72px;
372
+ height: 72px;
373
+ object-fit: cover;
374
+ background: var(--mg-wn-media-bg);
375
+ }
376
+
377
+ &__text {
378
+ display: flex;
379
+ flex-direction: column;
380
+ gap: 4px;
381
+ min-width: 0;
382
+ }
383
+
384
+ &__meta {
385
+ display: flex;
386
+ flex-wrap: wrap;
387
+ align-items: center;
388
+ gap: 8px;
389
+ font-size: 0.6875rem;
390
+ }
391
+
392
+ &__kind {
393
+ font-weight: 700;
394
+ letter-spacing: 0.08em;
395
+ text-transform: uppercase;
396
+ color: var(--mg-wn-neutral);
397
+
398
+ &--release {
399
+ color: var(--mg-wn-accent);
400
+ }
401
+
402
+ &--launch {
403
+ color: var(--mg-wn-success);
404
+ }
405
+
406
+ &--maintenance {
407
+ color: var(--mg-wn-warning);
408
+ }
409
+ }
410
+
411
+ &__date {
412
+ color: var(--mg-wn-text-muted);
413
+ }
414
+
415
+ &__new {
416
+ padding: 1px 6px;
417
+ font-weight: 700;
418
+ color: var(--mg-wn-on-accent);
419
+ background: var(--mg-wn-accent);
420
+ }
421
+
422
+ &__title {
423
+ font-size: 0.95rem;
424
+ font-weight: 600;
425
+ line-height: 1.3;
426
+ overflow-wrap: anywhere;
427
+ }
428
+
429
+ &__summary {
430
+ display: -webkit-box;
431
+ -webkit-line-clamp: 2;
432
+ line-clamp: 2;
433
+ -webkit-box-orient: vertical;
434
+ overflow: hidden;
435
+ font-size: 0.8125rem;
436
+ line-height: 1.4;
437
+ color: var(--mg-wn-text-muted);
438
+ }
439
+ }
440
+
441
+ [dir="rtl"] .mg-wn-drawer {
442
+ animation-name: mg-wn-drawer-in-rtl;
443
+ }
444
+
445
+ @keyframes mg-wn-drawer-in {
446
+ from {
447
+ transform: translateX(100%);
448
+ }
449
+ to {
450
+ transform: translateX(0);
451
+ }
452
+ }
453
+
454
+ @keyframes mg-wn-drawer-in-rtl {
455
+ from {
456
+ transform: translateX(-100%);
457
+ }
458
+ to {
459
+ transform: translateX(0);
460
+ }
461
+ }
462
+
463
+ @media (prefers-reduced-motion: reduce) {
464
+ .mg-wn-drawer {
465
+ animation: none;
466
+ }
467
+ }
468
+ </style>
@@ -0,0 +1,120 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * Host of the "Novidades" history: the side drawer and the announcement dialog reopened from it. Mounted once by
4
+ * <MgHeaderComponent /> (outside the user dropdown, which unmounts when it closes) so both survive the menu.
5
+ * Also loads the unread number for the badge, once per login identity.
6
+ *
7
+ * Off with `mgSharedUi.whatsNew.history: false` (or `whatsNew.enabled: false`); the backend decides the content.
8
+ */
9
+ import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
10
+ import { storeToRefs } from "pinia";
11
+ import type { WnHistoryItem } from "../../utils/whatsNew";
12
+
13
+ const store = useWhatsNewStore();
14
+ const authStore = useAuthStore();
15
+ const { user, signedIn } = storeToRefs(authStore);
16
+ const router = useRouter();
17
+
18
+ const i18nLocale = (() => {
19
+ try {
20
+ return useI18n().locale;
21
+ } catch {
22
+ return ref("en");
23
+ }
24
+ })();
25
+ const localePath: ((p: string) => string) | null = (() => {
26
+ try {
27
+ return useLocalePath() as any;
28
+ } catch {
29
+ return null;
30
+ }
31
+ })();
32
+
33
+ const shared: any = useRuntimeConfig().public.mgSharedUi ?? {};
34
+ const cfg: any = shared.whatsNew ?? {};
35
+ // Same two values the store needs to call the API: without them there is nothing to open, so no entry is offered.
36
+ const configured = !!(shared.networkBaseUrl || import.meta.env.VITE_BASE_URL_NETWORK) && !!(shared.systemId || import.meta.env.VITE_SYSTEM_ID);
37
+ const enabled = cfg.enabled !== false && cfg.history !== false && configured;
38
+ const uiLocale = computed(() => i18nLocale.value || "en");
39
+ const identity = computed(() => (signedIn.value ? String(user.value?.uuid ?? user.value?.id ?? "user") : null));
40
+
41
+ onMounted(() => {
42
+ if (!enabled) return;
43
+ store.hostMounted = true;
44
+ if (identity.value) store.fetchUnread(identity.value);
45
+ });
46
+
47
+ onBeforeUnmount(() => {
48
+ store.hostMounted = false;
49
+ });
50
+
51
+ watch(identity, (id) => {
52
+ if (!enabled) return;
53
+ if (id) store.fetchUnread(id);
54
+ else store.resetHistory();
55
+ });
56
+
57
+ /** In-app path → final route, or null when this front has no such route (the link then renders as text). */
58
+ function resolveInternal(path: string): string | null {
59
+ if (!path.startsWith("/") || path.startsWith("//")) return null;
60
+ const target = localePath ? localePath(path) : path;
61
+ try {
62
+ const resolved = router.resolve(target);
63
+ const real = resolved.matched.some((m) => !/\(\.\*\)|:pathMatch|\*\*/.test(m.path));
64
+ return real ? target : null;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+
70
+ function onOpen(item: WnHistoryItem) {
71
+ void store.openItem(item, uiLocale.value);
72
+ }
73
+
74
+ // ── the reopened announcement (same dialog as the modal) ───────────────────
75
+ function onCta() {
76
+ if (store.viewing) store.trackFor(store.viewing, "cta_click");
77
+ store.closeViewing();
78
+ }
79
+
80
+ function onNavigate(path: string) {
81
+ // A link click is neither "seen" nor "dismissed": get out of the way and go.
82
+ store.closeViewing(false);
83
+ store.closeDrawer();
84
+ router.push(path);
85
+ }
86
+
87
+ function onLink(target: string) {
88
+ if (store.viewing) store.trackFor(store.viewing, "link_click", target);
89
+ }
90
+
91
+ function onVideoPlay() {
92
+ if (store.viewing) store.trackFor(store.viewing, "video_play");
93
+ }
94
+ </script>
95
+
96
+ <template>
97
+ <ClientOnly>
98
+ <Teleport to="body">
99
+ <MgWhatsNewDrawer
100
+ v-if="enabled && signedIn && store.drawerOpen"
101
+ :locale="uiLocale"
102
+ @close="store.closeDrawer()"
103
+ @open="onOpen"
104
+ @more="store.loadMoreHistory(uiLocale)"
105
+ @retry="store.fetchHistory(uiLocale, 1)"
106
+ />
107
+ <MgWhatsNewDialog
108
+ v-if="enabled && signedIn && store.viewing"
109
+ :post="store.viewing"
110
+ :locale="uiLocale"
111
+ :resolve-internal="resolveInternal"
112
+ @close="store.closeViewing()"
113
+ @cta="onCta"
114
+ @navigate="onNavigate"
115
+ @link="onLink"
116
+ @video-play="onVideoPlay"
117
+ />
118
+ </Teleport>
119
+ </ClientOnly>
120
+ </template>
@@ -0,0 +1,92 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * "Novidades" entry of the user menu: opens the history drawer and shows how many announcements the
4
+ * user has not seen yet. The drawer itself lives in <MgWhatsNewHistory /> (mounted by the header, outside the
5
+ * dropdown, so it survives the menu closing).
6
+ */
7
+ import { computed } from "vue";
8
+ import { formatBadge } from "../../utils/whatsNew";
9
+ import { wnText } from "../../utils/whatsNewText";
10
+
11
+ const emit = defineEmits<{ (e: "opened"): void }>();
12
+
13
+ const store = useWhatsNewStore();
14
+ const { locale } = useI18n();
15
+
16
+ const badge = computed(() => formatBadge(store.unread));
17
+ const label = computed(() => {
18
+ const base = wnText(locale.value, "menu_title");
19
+ return store.unread > 0 ? `${base}, ${store.unread} ${wnText(locale.value, "history_unread")}` : base;
20
+ });
21
+
22
+ function open() {
23
+ void store.openDrawer(locale.value);
24
+ emit("opened");
25
+ }
26
+ </script>
27
+
28
+ <template>
29
+ <button type="button" class="mg-wn-menu-item" :aria-label="label" aria-haspopup="dialog" @click="open">
30
+ <span class="mg-wn-menu-item__icon" aria-hidden="true">
31
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="square">
32
+ <path d="M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9L12 3z" />
33
+ <path d="M19 16l.8 2.2L22 19l-2.2.8L19 22l-.8-2.2L16 19l2.2-.8L19 16z" />
34
+ </svg>
35
+ </span>
36
+ <span class="mg-wn-menu-item__label">{{ wnText(locale, "menu_title") }}</span>
37
+ <span v-if="badge" class="mg-wn-menu-item__badge" aria-hidden="true">{{ badge }}</span>
38
+ </button>
39
+ </template>
40
+
41
+ <style lang="scss" scoped>
42
+ .mg-wn-menu-item {
43
+ display: flex;
44
+ align-items: center;
45
+ gap: 8px;
46
+ width: 100%;
47
+ padding: 6px 0;
48
+ font: inherit;
49
+ font-size: 0.8125rem;
50
+ text-align: start;
51
+ color: var(--secondary-info-fg, var(--inactive));
52
+ background: transparent;
53
+ border: 0;
54
+ cursor: pointer;
55
+
56
+ &:hover,
57
+ &:focus-visible {
58
+ color: var(--active);
59
+ }
60
+
61
+ &:focus-visible {
62
+ outline: 2px solid var(--mg-wn-accent);
63
+ outline-offset: 2px;
64
+ }
65
+
66
+ &__icon {
67
+ display: inline-flex;
68
+ flex: none;
69
+ }
70
+
71
+ &__label {
72
+ flex: 1;
73
+ min-width: 0;
74
+ }
75
+
76
+ &__badge {
77
+ flex: none;
78
+ min-width: 20px;
79
+ height: 20px;
80
+ padding: 0 6px;
81
+ display: inline-flex;
82
+ align-items: center;
83
+ justify-content: center;
84
+ font-size: 0.6875rem;
85
+ font-weight: 700;
86
+ line-height: 1;
87
+ color: var(--mg-wn-on-accent);
88
+ background: var(--mg-wn-accent);
89
+ border-radius: 0;
90
+ }
91
+ }
92
+ </style>
package/nuxt.config.ts CHANGED
@@ -157,12 +157,21 @@ export default defineNuxtConfig({
157
157
  // with no gamification data for its users can set this to false.
158
158
  gamification: true,
159
159
  },
160
+ // Presence: pings the API every couple of minutes while a signed-in user has a tab open, so the admin can
161
+ // show who is online and who stopped coming back. Off until a front opts in; the platform is the front's VITE_SYSTEM_ID.
162
+ // Turn on, no rebuild needed: NUXT_PUBLIC_MG_SHARED_UI_PRESENCE_ENABLED=true.
163
+ presence: {
164
+ enabled: false,
165
+ intervalSeconds: 120, // never below 60
166
+ },
160
167
  // "Novidades da Rede" modal, mounted by <MgBanners />. Routes are path
161
168
  // prefixes (locale prefix ignored); allowedRoutes empty = any logged-in
162
169
  // route that is not blocked. blockedRoutes add to the built-in list
163
170
  // (login, signup, checkout, payment, create/publish/upload...).
164
171
  whatsNew: {
165
172
  enabled: true,
173
+ // "Novidades" entry in the user menu + side drawer with the past announcements (needs a signed-in user).
174
+ history: true,
166
175
  allowedRoutes: [] as string[],
167
176
  blockedRoutes: [] as string[],
168
177
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mundogamernetwork/shared-ui",
3
- "version": "1.18.1",
3
+ "version": "1.19.0",
4
4
  "description": "Mundo Gamer Network - Shared UI Layer (Nuxt 3)",
5
5
  "type": "module",
6
6
  "main": "./nuxt.config.ts",
@@ -0,0 +1,50 @@
1
+ import { createPresenceHeartbeat } from "../utils/presenceHeartbeat";
2
+ import httpService from "../services/httpService";
3
+
4
+ /**
5
+ * Presence: tells the API this user is active on this platform, so the admin can see who is online and who stopped coming
6
+ * back (api-main: POST /public/user-status/heartbeat, buffered in Redis and flushed to Postgres in batches).
7
+ *
8
+ * Off by default. Turn it on per front with `runtimeConfig.public.mgSharedUi.presence.enabled`, or the env var
9
+ * NUXT_PUBLIC_MG_SHARED_UI_PRESENCE_ENABLED=true, once that front's API runs the version of api-main that buffers the
10
+ * heartbeat. The platform is mgSharedUi.systemId (VITE_SYSTEM_ID), the same id the user-status toggle already uses.
11
+ *
12
+ * It follows the persisted auth store by its id ("auth-store") instead of importing the store: a few fronts (academy, agency)
13
+ * keep their own copy of the store, with the same id, and this works with either.
14
+ */
15
+ export default defineNuxtPlugin({
16
+ name: "shared-ui-presence",
17
+ setup(nuxtApp) {
18
+ try {
19
+ const config = (useRuntimeConfig().public as any).mgSharedUi ?? {};
20
+ const presence = config.presence ?? {};
21
+ if (!presence.enabled) return;
22
+
23
+ const platformId = Number(config.systemId || import.meta.env.VITE_SYSTEM_ID);
24
+ if (!Number.isInteger(platformId) || platformId <= 0) return;
25
+
26
+ const pinia = (nuxtApp as any).$pinia;
27
+ if (!pinia) return;
28
+
29
+ // Never faster than once a minute, whatever a front configures: the API treats ~5 minutes as online.
30
+ const intervalMs = Math.max(60, Number(presence.intervalSeconds) || 120) * 1000;
31
+
32
+ const heartbeat = createPresenceHeartbeat({
33
+ intervalMs,
34
+ isVisible: () => document.visibilityState === "visible",
35
+ send: () => httpService.post("/public/user-status/heartbeat", { platform_id: platformId }),
36
+ });
37
+
38
+ watch(
39
+ () => pinia.state.value["auth-store"]?.signedIn,
40
+ (signedIn) => (signedIn ? heartbeat.start() : heartbeat.stop()),
41
+ { immediate: true },
42
+ );
43
+
44
+ document.addEventListener("visibilitychange", () => heartbeat.onVisible());
45
+ } catch (e) {
46
+ // Presence must never break a page.
47
+ console.warn("[shared-ui Presence] disabled:", e);
48
+ }
49
+ },
50
+ });
@@ -1,16 +1,21 @@
1
1
  import { defineStore } from "pinia";
2
2
  import {
3
+ WN_HISTORY_PAGE,
3
4
  WN_MAX_BATCH,
4
5
  chunkEvents,
5
6
  newDeviceId,
6
7
  toApiLang,
7
8
  type WnEventName,
9
+ type WnHistoryItem,
10
+ type WnHistoryMeta,
8
11
  type WnPost,
9
12
  type WnReceiptEvent,
10
13
  } from "../utils/whatsNew";
11
14
 
12
15
  const DEVICE_KEY = "mg_wn_device_id";
13
16
  const LAST_SHOWN_KEY = "mg_wn_last_shown_at";
17
+ /** The list in the drawer is reloaded when it is older than this on open. */
18
+ const HISTORY_STALE_MS = 60_000;
14
19
 
15
20
  function readStorage(key: string): string | null {
16
21
  try {
@@ -59,6 +64,21 @@ export const useWhatsNewStore = defineStore("whats-new-store", {
59
64
  loading: false,
60
65
  shownThisSession: false,
61
66
  open: false,
67
+ // ── history (menu entry + side drawer) ──
68
+ unread: 0,
69
+ unreadFor: null as string | null,
70
+ drawerOpen: false,
71
+ // <MgWhatsNewHistory /> is mounted: the menu entry only shows when something can open the drawer.
72
+ hostMounted: false,
73
+ history: [] as WnHistoryItem[],
74
+ historyMeta: null as WnHistoryMeta | null,
75
+ historyStatus: "idle" as "idle" | "loading" | "loadingMore" | "error",
76
+ historyLoadedAt: 0,
77
+ // A post reopened from the history. Separate from `post`, which belongs to the one-per-session queue.
78
+ viewing: null as WnPost | null,
79
+ viewingWasNew: false,
80
+ openingId: null as number | null,
81
+ openError: false,
62
82
  }),
63
83
 
64
84
  actions: {
@@ -108,6 +128,8 @@ export const useWhatsNewStore = defineStore("whats-new-store", {
108
128
  this.shownThisSession = true;
109
129
  writeStorage(LAST_SHOWN_KEY, String(Date.now()));
110
130
  this.track("view");
131
+ this.markSeenLocal(this.post.id);
132
+ this.refreshUnreadSoon();
111
133
  },
112
134
 
113
135
  hide() {
@@ -120,15 +142,19 @@ export const useWhatsNewStore = defineStore("whats-new-store", {
120
142
  this.remaining = 0;
121
143
  this.fetchedFor = null;
122
144
  this.open = false;
145
+ this.resetHistory();
123
146
  },
124
147
 
125
148
  track(event: WnEventName, target?: string) {
126
- if (!this.post) return;
149
+ if (this.post) this.trackFor(this.post, event, target);
150
+ },
151
+
152
+ trackFor(post: WnPost, event: WnEventName, target?: string) {
127
153
  const { platformId } = getConfig();
128
154
  if (!platformId) return;
129
155
  const entry: WnReceiptEvent = {
130
- post_id: this.post.id,
131
- post_version: this.post.version,
156
+ post_id: post.id,
157
+ post_version: post.version,
132
158
  event,
133
159
  platform_id: platformId,
134
160
  surface: "web",
@@ -141,6 +167,154 @@ export const useWhatsNewStore = defineStore("whats-new-store", {
141
167
  else if (!flushTimer) flushTimer = setTimeout(() => this.flush(), 1500);
142
168
  },
143
169
 
170
+ // ── history ───────────────────────────────────────────────────────────
171
+
172
+ resetHistory() {
173
+ this.unread = 0;
174
+ this.unreadFor = null;
175
+ this.drawerOpen = false;
176
+ this.history = [];
177
+ this.historyMeta = null;
178
+ this.historyStatus = "idle";
179
+ this.historyLoadedAt = 0;
180
+ this.viewing = null;
181
+ this.viewingWasNew = false;
182
+ this.openingId = null;
183
+ this.openError = false;
184
+ },
185
+
186
+ /** Badge number. One light call per login identity; `force` re-reads it (after a view or closing the drawer). */
187
+ async fetchUnread(identity: string, force = false) {
188
+ if (!force && this.unreadFor === identity) return;
189
+ const { networkBaseUrl, platformId } = getConfig();
190
+ if (!networkBaseUrl || !platformId) return;
191
+ this.unreadFor = identity;
192
+ try {
193
+ const params = new URLSearchParams({ platform_id: String(platformId), surface: "web" });
194
+ const res: any = await $fetch(`${networkBaseUrl}/whats-new/unread-count?${params.toString()}`, {
195
+ credentials: "include",
196
+ timeout: 8000,
197
+ retry: 0,
198
+ });
199
+ if (this.unreadFor !== identity) return; // user switched meanwhile
200
+ this.unread = Math.max(0, Number(res?.data?.count ?? 0));
201
+ } catch {
202
+ // Non-critical: no badge is better than a broken menu.
203
+ if (force) return;
204
+ this.unreadFor = null;
205
+ }
206
+ },
207
+
208
+ /** Re-reads the badge a moment after a `view` (the server may have retired older posts too). */
209
+ refreshUnreadSoon() {
210
+ const identity = this.unreadFor;
211
+ if (!identity || typeof window === "undefined") return;
212
+ setTimeout(() => this.fetchUnread(identity, true), 2500);
213
+ },
214
+
215
+ /** The user has just seen post `id`: update the list row and the badge without waiting for the server. */
216
+ markSeenLocal(id: number) {
217
+ const row = this.history.find((h) => h.id === id);
218
+ if (row) {
219
+ if (!row.is_new) return; // already counted
220
+ row.is_new = false;
221
+ row.seen_at = new Date().toISOString();
222
+ }
223
+ this.unread = Math.max(0, this.unread - 1);
224
+ },
225
+
226
+ async fetchHistory(locale: string, page = 1) {
227
+ const { networkBaseUrl, platformId } = getConfig();
228
+ if (!networkBaseUrl || !platformId) return;
229
+ const append = page > 1;
230
+ this.historyStatus = append ? "loadingMore" : "loading";
231
+ try {
232
+ const params = new URLSearchParams({
233
+ platform_id: String(platformId),
234
+ surface: "web",
235
+ lang: toApiLang(locale),
236
+ page: String(page),
237
+ per_page: String(WN_HISTORY_PAGE),
238
+ });
239
+ const res: any = await $fetch(`${networkBaseUrl}/whats-new?${params.toString()}`, {
240
+ credentials: "include",
241
+ timeout: 10000,
242
+ retry: 0,
243
+ });
244
+ const rows: WnHistoryItem[] = Array.isArray(res?.data) ? res.data : [];
245
+ if (append) {
246
+ const known = new Set(this.history.map((h) => h.id));
247
+ this.history = [...this.history, ...rows.filter((r) => !known.has(r.id))];
248
+ } else {
249
+ this.history = rows;
250
+ }
251
+ this.historyMeta = res?.meta ?? null;
252
+ if (this.historyMeta) this.unread = Math.max(0, Number(this.historyMeta.unread_count ?? 0));
253
+ this.historyLoadedAt = Date.now();
254
+ this.historyStatus = "idle";
255
+ } catch {
256
+ this.historyStatus = "error";
257
+ }
258
+ },
259
+
260
+ async openDrawer(locale: string) {
261
+ this.drawerOpen = true;
262
+ this.openError = false;
263
+ const stale = Date.now() - this.historyLoadedAt > HISTORY_STALE_MS;
264
+ if (this.historyStatus === "idle" && (!this.history.length || stale)) await this.fetchHistory(locale, 1);
265
+ else if (this.historyStatus === "error") await this.fetchHistory(locale, 1);
266
+ },
267
+
268
+ closeDrawer() {
269
+ this.drawerOpen = false;
270
+ },
271
+
272
+ async loadMoreHistory(locale: string) {
273
+ const meta = this.historyMeta;
274
+ if (!meta || this.historyStatus !== "idle" || meta.page >= meta.last_page) return;
275
+ await this.fetchHistory(locale, meta.page + 1);
276
+ },
277
+
278
+ /** Reopens one announcement from the list. Only the first time (`is_new`) counts as a `view`. */
279
+ async openItem(item: WnHistoryItem, locale: string) {
280
+ const { networkBaseUrl, platformId } = getConfig();
281
+ if (!networkBaseUrl || !platformId || this.openingId !== null) return;
282
+ this.openingId = item.id;
283
+ this.openError = false;
284
+ try {
285
+ const params = new URLSearchParams({
286
+ platform_id: String(platformId),
287
+ surface: "web",
288
+ lang: toApiLang(locale),
289
+ });
290
+ const res: any = await $fetch(`${networkBaseUrl}/whats-new/${item.id}?${params.toString()}`, {
291
+ credentials: "include",
292
+ timeout: 10000,
293
+ retry: 0,
294
+ });
295
+ if (!res?.data) throw new Error("empty");
296
+ this.viewing = res.data as WnPost;
297
+ this.viewingWasNew = item.is_new;
298
+ if (item.is_new) {
299
+ this.trackFor(this.viewing, "view");
300
+ this.markSeenLocal(item.id);
301
+ this.refreshUnreadSoon();
302
+ }
303
+ } catch {
304
+ this.openError = true;
305
+ } finally {
306
+ this.openingId = null;
307
+ }
308
+ },
309
+
310
+ /** Closing a reopened announcement. If it was new, the user has now dealt with it: `dismiss`. */
311
+ closeViewing(dismiss = true) {
312
+ if (dismiss && this.viewing && this.viewingWasNew) this.trackFor(this.viewing, "dismiss");
313
+ this.viewing = null;
314
+ this.viewingWasNew = false;
315
+ this.flush();
316
+ },
317
+
144
318
  /** Sends queued events in batches of ≤20. keepalive lets it survive a page unload. */
145
319
  flush() {
146
320
  if (flushTimer) {
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Keeps a signed-in user "present" on a platform by pinging the API about every couple of minutes.
3
+ *
4
+ * The scheduling is kept free of Nuxt and the DOM so it can be tested: the plugin hands it a `send` function and a
5
+ * visibility probe. Rules:
6
+ * - ping right away on start, then every `intervalMs` with a little jitter so a few thousand tabs do not all hit the API on
7
+ * the same second;
8
+ * - never ping a hidden tab; when it becomes visible again, ping at once if the last ping is already stale;
9
+ * - never overlap two pings;
10
+ * - a 401/403 means the session is gone: stop, and let the next sign-in start it again;
11
+ * - any other failure is ignored, presence is a convenience and must never surface an error to the user.
12
+ */
13
+ export interface PresenceHeartbeatOptions {
14
+ intervalMs: number;
15
+ send: () => Promise<unknown>;
16
+ isVisible: () => boolean;
17
+ /** Random in [0, 1); injectable for tests. */
18
+ random?: () => number;
19
+ now?: () => number;
20
+ }
21
+
22
+ /** +/- this fraction of the interval is added to every wait. */
23
+ const JITTER = 0.15;
24
+
25
+ export function createPresenceHeartbeat(options: PresenceHeartbeatOptions) {
26
+ const random = options.random ?? Math.random;
27
+ const now = options.now ?? Date.now;
28
+
29
+ let timer: ReturnType<typeof setTimeout> | null = null;
30
+ let running = false;
31
+ let inFlight = false;
32
+ let lastSentAt = 0;
33
+
34
+ const nextDelay = () => Math.round(options.intervalMs * (1 - JITTER + random() * 2 * JITTER));
35
+
36
+ const schedule = () => {
37
+ if (!running) return;
38
+ if (timer) clearTimeout(timer);
39
+ timer = setTimeout(tick, nextDelay());
40
+ };
41
+
42
+ const ping = async () => {
43
+ if (inFlight) return;
44
+ inFlight = true;
45
+ lastSentAt = now();
46
+ try {
47
+ await options.send();
48
+ } catch (error: any) {
49
+ const status = error?.response?.status;
50
+ if (status === 401 || status === 403) stop();
51
+ } finally {
52
+ inFlight = false;
53
+ }
54
+ };
55
+
56
+ async function tick() {
57
+ if (!running) return;
58
+ if (options.isVisible()) await ping();
59
+ schedule();
60
+ }
61
+
62
+ function start() {
63
+ if (running) return;
64
+ running = true;
65
+ if (options.isVisible()) void ping();
66
+ schedule();
67
+ }
68
+
69
+ function stop() {
70
+ running = false;
71
+ if (timer) clearTimeout(timer);
72
+ timer = null;
73
+ }
74
+
75
+ /** Call when the tab becomes visible: a tab hidden for a while should not wait out the rest of its timer. */
76
+ function onVisible() {
77
+ if (running && options.isVisible() && now() - lastSentAt >= options.intervalMs / 2) void ping();
78
+ }
79
+
80
+ return { start, stop, onVisible, isRunning: () => running };
81
+ }
package/utils/whatsNew.ts CHANGED
@@ -45,6 +45,37 @@ export interface WnPost {
45
45
  history_url: string | null;
46
46
  }
47
47
 
48
+ /** One row of the history list (GET /whats-new). `is_new` = the user has not seen it yet. */
49
+ export interface WnHistoryItem {
50
+ id: number;
51
+ version: number;
52
+ kind: WnPost["kind"];
53
+ title: string;
54
+ summary: string | null;
55
+ published_at: string | null;
56
+ thumb_url: string | null;
57
+ seen_at: string | null;
58
+ is_new: boolean;
59
+ }
60
+
61
+ export interface WnHistoryMeta {
62
+ total: number;
63
+ page: number;
64
+ per_page: number;
65
+ last_page: number;
66
+ unread_count: number;
67
+ }
68
+
69
+ /** Page size of the drawer list. */
70
+ export const WN_HISTORY_PAGE = 20;
71
+
72
+ /** Badge text: nothing at 0, "9+" from ten up so it never outgrows the menu row. */
73
+ export function formatBadge(count: number | null | undefined): string {
74
+ const n = Math.floor(Number(count) || 0);
75
+ if (n <= 0) return "";
76
+ return n > 9 ? "9+" : String(n);
77
+ }
78
+
48
79
  // ─── Inline markup: **bold** and [text](url) ────────────────────────────────
49
80
 
50
81
  /** The single link regex shared with every other client (see the contract). */
@@ -27,6 +27,18 @@ export const WN_MESSAGES = {
27
27
  follow: "Follow the network",
28
28
  new_tab: "opens in a new tab",
29
29
  media_label: "Media",
30
+ menu_title: "What's new",
31
+ history_title: "What's new",
32
+ history_subtitle: "Latest features and improvements",
33
+ history_empty: "Nothing new yet. Come back soon!",
34
+ history_error: "We could not load the news.",
35
+ history_retry: "Try again",
36
+ history_more: "Load more",
37
+ history_new: "New",
38
+ history_open: "Open",
39
+ history_unread: "unread",
40
+ history_loading: "Loading…",
41
+ history_open_error: "We could not open this announcement.",
30
42
  },
31
43
  "pt-BR": {
32
44
  title: "Novidades",
@@ -47,6 +59,18 @@ export const WN_MESSAGES = {
47
59
  follow: "Siga a rede",
48
60
  new_tab: "abre em uma nova aba",
49
61
  media_label: "Mídia",
62
+ menu_title: "Novidades",
63
+ history_title: "Novidades",
64
+ history_subtitle: "Últimos recursos e melhorias",
65
+ history_empty: "Nada de novo por enquanto. Volte logo!",
66
+ history_error: "Não foi possível carregar as novidades.",
67
+ history_retry: "Tentar de novo",
68
+ history_more: "Carregar mais",
69
+ history_new: "Nova",
70
+ history_open: "Abrir",
71
+ history_unread: "não lidas",
72
+ history_loading: "Carregando…",
73
+ history_open_error: "Não foi possível abrir este comunicado.",
50
74
  },
51
75
  "de": {
52
76
  title: "Neuigkeiten",
@@ -67,6 +91,18 @@ export const WN_MESSAGES = {
67
91
  follow: "Folge dem Netzwerk",
68
92
  new_tab: "öffnet in einem neuen Tab",
69
93
  media_label: "Medien",
94
+ menu_title: "Neuigkeiten",
95
+ history_title: "Neuigkeiten",
96
+ history_subtitle: "Neueste Funktionen und Verbesserungen",
97
+ history_empty: "Noch nichts Neues. Schau bald wieder vorbei!",
98
+ history_error: "Die Neuigkeiten konnten nicht geladen werden.",
99
+ history_retry: "Erneut versuchen",
100
+ history_more: "Mehr laden",
101
+ history_new: "Neu",
102
+ history_open: "Öffnen",
103
+ history_unread: "ungelesen",
104
+ history_loading: "Wird geladen…",
105
+ history_open_error: "Diese Mitteilung konnte nicht geöffnet werden.",
70
106
  },
71
107
  "es": {
72
108
  title: "Novedades",
@@ -87,6 +123,18 @@ export const WN_MESSAGES = {
87
123
  follow: "Sigue la red",
88
124
  new_tab: "se abre en una pestaña nueva",
89
125
  media_label: "Multimedia",
126
+ menu_title: "Novedades",
127
+ history_title: "Novedades",
128
+ history_subtitle: "Últimas funciones y mejoras",
129
+ history_empty: "Aún no hay novedades. ¡Vuelve pronto!",
130
+ history_error: "No se pudieron cargar las novedades.",
131
+ history_retry: "Reintentar",
132
+ history_more: "Cargar más",
133
+ history_new: "Nueva",
134
+ history_open: "Abrir",
135
+ history_unread: "sin leer",
136
+ history_loading: "Cargando…",
137
+ history_open_error: "No se pudo abrir este comunicado.",
90
138
  },
91
139
  "ro": {
92
140
  title: "Noutăți",
@@ -107,6 +155,18 @@ export const WN_MESSAGES = {
107
155
  follow: "Urmărește rețeaua",
108
156
  new_tab: "se deschide într-o filă nouă",
109
157
  media_label: "Media",
158
+ menu_title: "Noutăți",
159
+ history_title: "Noutăți",
160
+ history_subtitle: "Cele mai recente funcții și îmbunătățiri",
161
+ history_empty: "Nimic nou deocamdată. Revino curând!",
162
+ history_error: "Noutățile nu au putut fi încărcate.",
163
+ history_retry: "Încearcă din nou",
164
+ history_more: "Încarcă mai multe",
165
+ history_new: "Nou",
166
+ history_open: "Deschide",
167
+ history_unread: "necitite",
168
+ history_loading: "Se încarcă…",
169
+ history_open_error: "Acest anunț nu a putut fi deschis.",
110
170
  },
111
171
  "ar": {
112
172
  title: "الجديد",
@@ -127,6 +187,18 @@ export const WN_MESSAGES = {
127
187
  follow: "تابع الشبكة",
128
188
  new_tab: "يفتح في علامة تبويب جديدة",
129
189
  media_label: "وسائط",
190
+ menu_title: "الجديد",
191
+ history_title: "الجديد",
192
+ history_subtitle: "أحدث الميزات والتحسينات",
193
+ history_empty: "لا جديد بعد. عد قريبًا!",
194
+ history_error: "تعذّر تحميل الأخبار.",
195
+ history_retry: "حاول مرة أخرى",
196
+ history_more: "تحميل المزيد",
197
+ history_new: "جديد",
198
+ history_open: "فتح",
199
+ history_unread: "غير مقروءة",
200
+ history_loading: "جارٍ التحميل…",
201
+ history_open_error: "تعذّر فتح هذا الإعلان.",
130
202
  },
131
203
  } as const;
132
204