Add Discourse notifications widget

This commit is contained in:
raucao committed 2026-10-02 12:45:36 +02:00
1 parent 960e3e4b75
commit cb4373d05b
12 files changed
+911 -2

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
import Component from '@glimmer/component';
import { service } from '@ember/service';
import NotificationsGroup from './notifications/group.gjs';
export default class NotificationsComponent extends Component {
@service notifications;
<template>
{{#if this.notifications.groups.length}}
<div class="flex items-start gap-4" data-test-notifications ...attributes>
{{#each this.notifications.groups as |group|}}
<NotificationsGroup @id={{group.id}} @items={{group.items}} />
{{/each}}
</div>
{{/if}}
</template>
}
+16
View File
@@ -0,0 +1,16 @@
import Component from '@glimmer/component';
import GenericItem from './item.gjs';
export default class NotificationsGroupComponent extends Component {
get itemComponent() {
return this.args.itemComponent ?? GenericItem;
}
<template>
<div class="flex items-center gap-2" data-group={{@id}} ...attributes>
{{#each @items as |item|}}
<this.itemComponent @item={{item}} />
{{/each}}
</div>
</template>
}
+82
View File
@@ -0,0 +1,82 @@
import Component from '@glimmer/component';
export default class NotificationsItemComponent extends Component {
get label() {
return this.args.item?.label ?? 'Notifications';
}
get unreadCount() {
return this.args.item?.unreadCount ?? 0;
}
get hasUnread() {
return this.unreadCount > 0;
}
get isLoading() {
return this.args.item?.status === 'loading';
}
get isError() {
return this.args.item?.status === 'error';
}
get iconClass() {
if (this.isError) {
return 'text-red-300';
}
if (this.hasUnread) {
return 'text-indigo-400';
}
return 'text-white';
}
get tooltip() {
if (this.isError && this.args.item?.error) {
return `${this.label} — ${this.args.item.error}`;
}
return this.label;
}
<template>
<a
href={{@item.href}}
target="_blank"
rel="noopener noreferrer"
title={{this.tooltip}}
aria-label={{this.tooltip}}
data-status={{@item.status}}
data-error-type={{@item.errorType}}
class="flex items-center gap-1 rounded-md border border-white/40 bg-gray-950/20 p-1.5 text-white backdrop-blur transition-colors hover:bg-gray-950/40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white
{{if this.isError 'border-red-400/70'}}"
...attributes
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
aria-hidden="true"
class="size-6 shrink-0 {{this.iconClass}}"
>
<path
d="M14.857 17.082a23.848 23.848 0 0 0 5.454-1.31A8.967 8.967 0 0 1 18 9.75V9A6 6 0 0 0 6 9v.75a8.967 8.967 0 0 1-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 0 1-5.714 0m5.714 0a3 3 0 1 1-5.714 0"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
{{#if this.isLoading}}
<span
class="text-xs text-white/60"
data-test-notifications-loading
>…</span>
{{else if this.hasUnread}}
<span
class="rounded-full bg-indigo-500 px-1.5 text-xs font-semibold tabular-nums"
data-test-notifications-count
>{{this.unreadCount}}</span>
{{/if}}
</a>
</template>
}
+12
View File
@@ -0,0 +1,12 @@
export const NOTIFICATION_GROUPS = [
{
id: 'discourse',
label: 'Discourse',
integrationTypes: ['discourse'],
},
{
id: 'code-forge',
label: 'Code Forges',
integrationTypes: ['github', 'gitea'],
},
];
+39
View File
@@ -0,0 +1,39 @@
import Service from '@ember/service';
export class HttpError extends Error {
constructor(status) {
super(`Request failed with status ${status}`);
this.name = 'HttpError';
this.status = status;
}
}
export class NetworkError extends Error {
constructor(cause) {
super('Request failed before a response was received');
this.name = 'NetworkError';
this.cause = cause;
}
}
// Single seam for outbound requests. When Dashtab ships as a browser
// extension, this is the one place that needs to branch to service-worker
// messaging (e.g. chrome.runtime.sendMessage) so privileged cross-origin
// fetches can use the extension's host permissions instead of CORS.
export default class HttpService extends Service {
async requestJson(url, options = {}) {
let response;
try {
response = await fetch(url, options);
} catch (err) {
throw new NetworkError(err);
}
if (!response.ok) {
throw new HttpError(response.status);
}
return response.json();
}
}
+226
View File
@@ -0,0 +1,226 @@
import Service, { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { NOTIFICATION_GROUPS } from '../config/notifications';
import { HttpError } from './http';
export const NOTIFICATIONS_DEFAULT_INTERVAL = 60000;
async function fetchDiscourseNotifications(integration, http) {
const data = await http.requestJson(`${integration.url}/notifications.json`, {
headers: {
'User-Api-Key': integration.apiKey,
'User-Api-Client-Id': integration.clientId,
},
});
const notifications = (data.notifications ?? []).map((notification) => ({
id: notification.id,
title:
notification.data?.topic_title ??
notification.data?.badge_name ??
'Notification',
read: Boolean(notification.read),
createdAt: notification.created_at,
topicId: notification.topic_id,
}));
return {
unreadCount: notifications.filter((notification) => !notification.read)
.length,
notifications,
};
}
const ADAPTERS = {
discourse: fetchDiscourseNotifications,
};
function labelForUrl(url) {
try {
return new URL(url).hostname;
} catch {
return url;
}
}
function hrefForIntegration(integration) {
if (integration.type === 'discourse' && integration.url) {
return `${integration.url}/notifications`;
}
return integration.url ?? null;
}
export default class NotificationsService extends Service {
@service storage;
@service http;
@tracked sources = [];
@tracked loading = false;
@tracked error = null;
intervalId = null;
fetching = false;
ready = null;
integrationBySourceId = new Map();
constructor() {
super(...arguments);
this.ready = this.load();
}
async load() {
try {
const keys = await this.storage.keys('integrations');
const integrations = await Promise.all(
keys.map(async (key) => ({
key,
data: await this.storage.get('integrations', key),
}))
);
this.sources = integrations
.filter(({ data }) => this.isSupportedIntegration(data))
.map(({ key, data }) => this.buildSource(key, data));
if (this.sources.length > 0) {
this.startPolling();
}
} catch (err) {
console.error('Error loading notification sources:', err);
this.error = 'Unable to load notification sources';
}
}
isSupportedIntegration(integration) {
return (
integration?.status === 'active' &&
NOTIFICATION_GROUPS.some((group) =>
group.integrationTypes.includes(integration.type)
)
);
}
buildSource(key, integration) {
this.integrationBySourceId.set(key, integration);
return {
id: key,
type: integration.type,
groupId: this.groupIdForType(integration.type),
label: labelForUrl(integration.url),
href: hrefForIntegration(integration),
unreadCount: 0,
status: 'loading',
error: null,
errorType: null,
notifications: [],
};
}
groupIdForType(type) {
const group = NOTIFICATION_GROUPS.find((candidate) =>
candidate.integrationTypes.includes(type)
);
return group ? group.id : 'other';
}
get groups() {
return NOTIFICATION_GROUPS.map((group) => ({
id: group.id,
label: group.label,
items: this.sources.filter((source) => source.groupId === group.id),
})).filter((group) => group.items.length > 0);
}
updateSource(id, changes) {
this.sources = this.sources.map((source) =>
source.id === id ? { ...source, ...changes } : source
);
}
async fetchAll() {
if (this.fetching) {
return;
}
this.fetching = true;
this.loading = true;
try {
await Promise.all(this.sources.map((source) => this.fetchSource(source)));
} finally {
this.fetching = false;
this.loading = false;
}
}
async fetchSource(source) {
const adapter = ADAPTERS[source.type];
if (!adapter) {
this.updateSource(source.id, { status: 'ready' });
return;
}
try {
const result = await adapter(
this.integrationBySourceId.get(source.id),
this.http
);
this.updateSource(source.id, {
status: 'ready',
error: null,
errorType: null,
unreadCount: result.unreadCount,
notifications: result.notifications,
});
} catch (err) {
console.error(`Error fetching ${source.type} notifications:`, err);
this.updateSource(source.id, {
status: 'error',
...this.classifyError(err),
});
}
}
classifyError(err) {
if (
err instanceof HttpError &&
(err.status === 401 || err.status === 403)
) {
return {
errorType: 'unauthorized',
error: 'Reconnect this forum',
};
}
if (err instanceof HttpError) {
return {
errorType: 'http',
error: `Forum returned ${err.status}`,
};
}
return {
errorType: 'unreachable',
error: 'Notifications blocked — enable CORS on the forum or open it',
};
}
startPolling() {
this.stopPolling();
this.fetchAll();
this.intervalId = setInterval(() => {
this.fetchAll();
}, NOTIFICATIONS_DEFAULT_INTERVAL);
}
stopPolling() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
willDestroy() {
this.stopPolling();
super.willDestroy();
}
}
+7 -2
View File
@@ -2,6 +2,7 @@ import { pageTitle } from 'ember-page-title';
import { on } from '@ember/modifier';
import DefaultClock from '../components/default-clock.gjs';
import BitcoinTicker from '../components/bitcoin-ticker.gjs';
import Notifications from '../components/notifications.gjs';
import ModalDialog from '../components/modal-dialog.gjs';
import ModalStepOne from '../components/modal-step-one.gjs';
import { default as SettingsAddIntegrationList } from '../components/settings/add-integration/list.gjs';
@@ -10,7 +11,7 @@ import { default as SettingsAddIntegrationList } from '../components/settings/ad
{{pageTitle "New Tab"}}
<div
class="col-start-3 row-start-1 flex items-start justify-end gap-4 pt-12 pr-12"
class="col-start-2 row-start-3 flex items-end justify-center gap-4 pb-12"
>
<button
command="show-modal"
@@ -27,6 +28,10 @@ import { default as SettingsAddIntegrationList } from '../components/settings/ad
/>
</div>
<div class="col-start-3 row-start-1 flex items-start justify-end pt-12 pr-12">
<Notifications />
</div>
<div class="col-start-2 row-start-1 flex items-start justify-center pt-12">
<BitcoinTicker />
</div>
@@ -36,7 +41,7 @@ import { default as SettingsAddIntegrationList } from '../components/settings/ad
</div>
<div
class="col-start-2 row-start-3 flex items-end justify-center gap-4 pb-12"
class="col-start-3 row-start-3 flex items-end justify-end gap-4 pb-12 pr-12"
>
<button
command="show-modal"
@@ -0,0 +1,70 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render } from '@ember/test-helpers';
import { tracked } from '@glimmer/tracking';
import Notifications from 'dashtab/components/notifications';
class FakeNotificationsService {
@tracked groups = [];
}
module('Integration | Component | notifications', function (hooks) {
setupRenderingTest(hooks);
test('it renders nothing when there are no sources', async function (assert) {
const notifications = new FakeNotificationsService();
this.owner.register('service:notifications', notifications, {
instantiate: false,
});
await render(<template><Notifications /></template>);
assert.dom('[data-test-notifications]').doesNotExist();
});
test('it renders a group per notification source group', async function (assert) {
const notifications = new FakeNotificationsService();
notifications.groups = [
{
id: 'discourse',
label: 'Discourse',
items: [
{
id: 'discourse-abc',
type: 'discourse',
label: 'forum.example.com',
href: 'https://forum.example.com/notifications',
status: 'ready',
unreadCount: 3,
},
],
},
{
id: 'code-forge',
label: 'Code Forges',
items: [
{
id: 'gitea-1',
type: 'gitea',
label: 'git.example.com',
href: 'https://git.example.com',
status: 'ready',
unreadCount: 0,
},
],
},
];
this.owner.register('service:notifications', notifications, {
instantiate: false,
});
await render(<template><Notifications /></template>);
assert.dom('[data-test-notifications]').exists();
assert.dom('[data-group="discourse"]').exists();
assert.dom('[data-group="code-forge"]').exists();
assert.dom('a').exists({ count: 2 });
assert.dom('[data-test-notifications-count]').hasText('3');
});
});
@@ -0,0 +1,51 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render } from '@ember/test-helpers';
import NotificationsGroup from 'dashtab/components/notifications/group';
module('Integration | Component | notifications/group', function (hooks) {
setupRenderingTest(hooks);
test('it renders an item per source without a visible label', async function (assert) {
this.set('items', [
{
id: 'discourse-abc',
label: 'forum.example.com',
href: 'https://forum.example.com/notifications',
status: 'ready',
unreadCount: 2,
},
{
id: 'discourse-def',
label: 'meta.example.com',
href: 'https://meta.example.com/notifications',
status: 'ready',
unreadCount: 0,
},
]);
await render(
<template>
<NotificationsGroup @id="discourse" @items={{this.items}} />
</template>
);
assert.dom('[data-group="discourse"]').exists();
assert.dom('a').exists({ count: 2 });
assert.dom('[data-group="discourse"]').doesNotContainText('Discourse');
assert.dom('[data-group="discourse"]').doesNotContainText('forum');
});
test('it renders nothing when there are no items', async function (assert) {
this.set('items', []);
await render(
<template>
<NotificationsGroup @id="discourse" @items={{this.items}} />
</template>
);
assert.dom('[data-group="discourse"]').exists();
assert.dom('a').doesNotExist();
});
});
@@ -0,0 +1,84 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render } from '@ember/test-helpers';
import NotificationItem from 'dashtab/components/notifications/item';
module('Integration | Component | notifications/item', function (hooks) {
setupRenderingTest(hooks);
test('it renders a link to the source with an unread count', async function (assert) {
this.set('item', {
id: 'discourse-abc',
type: 'discourse',
label: 'forum.example.com',
href: 'https://forum.example.com/notifications',
status: 'ready',
unreadCount: 3,
});
await render(<template><NotificationItem @item={{this.item}} /></template>);
assert
.dom('a')
.hasAttribute('href', 'https://forum.example.com/notifications');
assert.dom('a').hasAttribute('target', '_blank');
assert.dom('a').hasAttribute('rel', 'noopener noreferrer');
assert.dom('a').hasAttribute('title', 'forum.example.com');
assert.dom('a').hasAttribute('aria-label', 'forum.example.com');
assert.dom('[data-test-notifications-count]').hasText('3');
assert.dom('a svg').hasClass('text-indigo-400');
assert.dom('a svg').doesNotHaveClass('text-white');
});
test('it hides the count when there are no unread notifications', async function (assert) {
this.set('item', {
label: 'forum.example.com',
href: 'https://forum.example.com/notifications',
status: 'ready',
unreadCount: 0,
});
await render(<template><NotificationItem @item={{this.item}} /></template>);
assert.dom('[data-test-notifications-count]').doesNotExist();
assert.dom('[data-test-notifications-loading]').doesNotExist();
assert.dom('a svg').hasClass('text-white');
});
test('it shows a loading placeholder before the first fetch', async function (assert) {
this.set('item', {
label: 'forum.example.com',
href: 'https://forum.example.com/notifications',
status: 'loading',
unreadCount: 0,
});
await render(<template><NotificationItem @item={{this.item}} /></template>);
assert.dom('[data-test-notifications-loading]').exists();
});
test('it explains an unreachable source in the tooltip', async function (assert) {
this.set('item', {
label: 'forum.example.com',
href: 'https://forum.example.com/notifications',
status: 'error',
errorType: 'unreachable',
error: 'Notifications blocked — enable CORS on the forum or open it',
unreadCount: 0,
});
await render(<template><NotificationItem @item={{this.item}} /></template>);
assert.dom('a').hasAttribute('data-status', 'error');
assert.dom('a').hasAttribute('data-error-type', 'unreachable');
assert
.dom('a')
.hasAttribute(
'title',
'forum.example.com — Notifications blocked — enable CORS on the forum or open it'
);
assert.dom('a').hasAttribute('href');
assert.dom('a svg').hasClass('text-red-300');
});
});
+69
View File
@@ -0,0 +1,69 @@
import { module, test } from 'qunit';
import { setupTest } from 'dashtab/tests/helpers';
import { HttpError, NetworkError } from 'dashtab/services/http';
module('Unit | Service | http', function (hooks) {
setupTest(hooks);
let originalFetch;
hooks.beforeEach(function () {
originalFetch = globalThis.fetch;
});
hooks.afterEach(function () {
globalThis.fetch = originalFetch;
});
test('it exists', function (assert) {
let service = this.owner.lookup('service:http');
assert.ok(service);
});
test('it parses a successful JSON response', async function (assert) {
globalThis.fetch = async () => ({
ok: true,
json: async () => ({ value: 42 }),
});
const http = this.owner.lookup('service:http');
const data = await http.requestJson('https://example.com/data.json');
assert.deepEqual(data, { value: 42 });
});
test('it throws HttpError on a non-ok response', async function (assert) {
globalThis.fetch = async () => ({
ok: false,
status: 401,
json: async () => ({}),
});
const http = this.owner.lookup('service:http');
await assert.rejects(
http.requestJson('https://example.com/data.json'),
(err) => {
assert.true(err instanceof HttpError);
assert.strictEqual(err.status, 401);
return true;
}
);
});
test('it throws NetworkError when the request cannot be made', async function (assert) {
globalThis.fetch = async () => {
throw new TypeError('Failed to fetch');
};
const http = this.owner.lookup('service:http');
await assert.rejects(
http.requestJson('https://example.com/data.json'),
(err) => {
assert.true(err instanceof NetworkError);
return true;
}
);
});
});
+238
View File
@@ -0,0 +1,238 @@
import { module, test } from 'qunit';
import { setupTest } from 'dashtab/tests/helpers';
module('Unit | Service | notifications', function (hooks) {
setupTest(hooks);
let originalFetch;
let originalConsoleError;
hooks.beforeEach(function () {
originalFetch = globalThis.fetch;
originalConsoleError = console.error;
console.error = () => {};
});
hooks.afterEach(function () {
globalThis.fetch = originalFetch;
console.error = originalConsoleError;
});
test('it exists', function (assert) {
let service = this.owner.lookup('service:notifications');
assert.ok(service);
});
test('load groups active supported integrations', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {
type: 'discourse',
status: 'active',
url: 'https://forum.example.com',
apiKey: 'key',
clientId: 'abc',
});
await storage.set('integrations', 'bitcoin', {
type: 'bitcoin',
status: 'active',
});
await storage.set('integrations', 'discourse-pending', {
type: 'discourse',
status: 'pending',
url: 'https://pending.example.com',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
assert.strictEqual(service.sources.length, 1);
const groups = service.groups;
assert.strictEqual(groups.length, 1);
assert.strictEqual(groups[0].id, 'discourse');
assert.strictEqual(groups[0].label, 'Discourse');
assert.strictEqual(groups[0].items.length, 1);
const [item] = groups[0].items;
assert.strictEqual(item.label, 'forum.example.com');
assert.strictEqual(item.href, 'https://forum.example.com/notifications');
assert.strictEqual(item.status, 'loading');
service.stopPolling();
});
test('load starts polling when there are sources', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {
type: 'discourse',
status: 'active',
url: 'https://forum.example.com',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
assert.ok(service.intervalId);
service.stopPolling();
});
test('fetchSource normalizes a discourse response', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {
type: 'discourse',
status: 'active',
url: 'https://forum.example.com',
apiKey: 'key',
clientId: 'abc',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
let requestedUrl;
let requestedHeaders;
globalThis.fetch = async (url, options) => {
requestedUrl = url;
requestedHeaders = options.headers;
return {
ok: true,
json: async () => ({
notifications: [
{
id: 1,
read: false,
created_at: '2024-01-02T00:00:00.000Z',
topic_id: 5,
data: { topic_title: 'Hello there' },
},
{
id: 2,
read: true,
created_at: '2024-01-01T00:00:00.000Z',
topic_id: 4,
data: { badge_name: 'Nice' },
},
],
}),
};
};
await service.fetchSource(service.sources[0]);
assert.strictEqual(
requestedUrl,
'https://forum.example.com/notifications.json'
);
assert.strictEqual(requestedHeaders['User-Api-Key'], 'key');
assert.strictEqual(requestedHeaders['User-Api-Client-Id'], 'abc');
const [source] = service.sources;
assert.strictEqual(source.status, 'ready');
assert.strictEqual(source.unreadCount, 1);
assert.strictEqual(source.notifications.length, 2);
assert.strictEqual(source.notifications[0].title, 'Hello there');
assert.strictEqual(source.notifications[1].title, 'Nice');
});
test('fetchSource marks an unreachable source when the request fails', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {
type: 'discourse',
status: 'active',
url: 'https://forum.example.com',
apiKey: 'key',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
globalThis.fetch = async () => {
throw new TypeError('Failed to fetch');
};
await service.fetchSource(service.sources[0]);
const [source] = service.sources;
assert.strictEqual(source.status, 'error');
assert.strictEqual(source.errorType, 'unreachable');
assert.strictEqual(source.unreadCount, 0);
});
test('fetchSource flags an unauthorized response', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {
type: 'discourse',
status: 'active',
url: 'https://forum.example.com',
apiKey: 'expired',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
globalThis.fetch = async () => ({
ok: false,
status: 401,
json: async () => ({}),
});
await service.fetchSource(service.sources[0]);
const [source] = service.sources;
assert.strictEqual(source.status, 'error');
assert.strictEqual(source.errorType, 'unauthorized');
assert.strictEqual(source.error, 'Reconnect this forum');
});
test('fetchSource flags other HTTP failures', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {
type: 'discourse',
status: 'active',
url: 'https://forum.example.com',
apiKey: 'key',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
globalThis.fetch = async () => ({
ok: false,
status: 500,
json: async () => ({}),
});
await service.fetchSource(service.sources[0]);
const [source] = service.sources;
assert.strictEqual(source.status, 'error');
assert.strictEqual(source.errorType, 'http');
assert.strictEqual(source.error, 'Forum returned 500');
});
test('stopPolling clears the interval', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {
type: 'discourse',
status: 'active',
url: 'https://forum.example.com',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
service.startPolling();
assert.ok(service.intervalId);
service.stopPolling();
assert.strictEqual(service.intervalId, null);
});
});