Add site icon fetching/caching, Discourse icons
This commit is contained in:
1 parent
a271d1148f
commit
8a0d8dde36
12 files changed
+648
-30
No files matched your search
@@ -1,4 +1,8 @@
|
||||
import Component from '@glimmer/component';
|
||||
import setStyle from '../../modifiers/set-style';
|
||||
|
||||
const SAFE_COLOR =
|
||||
/^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%]+\)|hsla?\([\d\s.,%]+\)|[a-z]+)$/i;
|
||||
|
||||
export default class NotificationsItemComponent extends Component {
|
||||
get label() {
|
||||
@@ -17,14 +21,30 @@ export default class NotificationsItemComponent extends Component {
|
||||
return this.args.item?.status === 'error';
|
||||
}
|
||||
|
||||
get iconClass() {
|
||||
if (this.isError) {
|
||||
return 'text-red-300';
|
||||
get icon() {
|
||||
return this.args.item?.icon;
|
||||
}
|
||||
|
||||
get initial() {
|
||||
const first = this.label.trim()?.[0];
|
||||
return first ? first.toUpperCase() : '?';
|
||||
}
|
||||
|
||||
get imageClass() {
|
||||
return this.icon?.maskable
|
||||
? 'size-full object-cover'
|
||||
: 'size-7 rounded-md object-contain';
|
||||
}
|
||||
|
||||
// The theme color comes from the remote site, so only pass through values
|
||||
// that look like plain CSS colors.
|
||||
get tileColor() {
|
||||
const color = this.icon?.themeColor;
|
||||
if (typeof color !== 'string') {
|
||||
return undefined;
|
||||
}
|
||||
if (this.hasUnread) {
|
||||
return 'text-indigo-400';
|
||||
}
|
||||
return 'text-white';
|
||||
const trimmed = color.trim();
|
||||
return SAFE_COLOR.test(trimmed) ? trimmed : undefined;
|
||||
}
|
||||
|
||||
get tooltip() {
|
||||
@@ -41,28 +61,34 @@ export default class NotificationsItemComponent extends Component {
|
||||
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'}}"
|
||||
class="relative block size-10 shrink-0 rounded-xl text-white focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white"
|
||||
...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}}"
|
||||
<span
|
||||
data-test-notifications-tile
|
||||
class="flex size-full items-center justify-center overflow-hidden rounded-xl border border-white/40 bg-gray-950/40 backdrop-blur transition-colors hover:border-white/60
|
||||
{{if this.isError 'ring-2 ring-red-400/70'}}"
|
||||
{{setStyle "background-color" this.tileColor}}
|
||||
>
|
||||
<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.icon}}
|
||||
<img
|
||||
src={{this.icon.dataUrl}}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
data-test-notifications-icon
|
||||
class={{this.imageClass}}
|
||||
/>
|
||||
{{else}}
|
||||
<span
|
||||
data-test-notifications-fallback
|
||||
class="flex size-full items-center justify-center bg-indigo-500 text-sm font-semibold"
|
||||
>{{this.initial}}</span>
|
||||
{{/if}}
|
||||
</span>
|
||||
|
||||
{{#if this.hasUnread}}
|
||||
<span
|
||||
class="rounded-full bg-indigo-500 px-1.5 text-xs font-semibold tabular-nums"
|
||||
class="absolute -right-1 -bottom-1 rounded-full bg-red-500 px-1 text-xs font-semibold tabular-nums text-white ring-2 ring-gray-950"
|
||||
data-test-notifications-count
|
||||
>{{this.unreadCount}}</span>
|
||||
{{/if}}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { modifier } from 'ember-modifier';
|
||||
|
||||
// Sets a single CSS property through the CSSOM (not a template-bound style
|
||||
// attribute) so the browser validates the value and Ember's XSS-prone style
|
||||
// binding deprecation is avoided.
|
||||
export default modifier((element, [property, value]) => {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
element.style.removeProperty(property);
|
||||
return;
|
||||
}
|
||||
|
||||
element.style.setProperty(property, String(value));
|
||||
});
|
||||
+14
-2
@@ -37,7 +37,7 @@ export function proxiedUrl(url, base) {
|
||||
export default class HttpService extends Service {
|
||||
corsProxyBase = config.corsProxy ?? null;
|
||||
|
||||
async requestJson(url, options = {}) {
|
||||
async request(url, options = {}) {
|
||||
const target = proxiedUrl(url, this.corsProxyBase);
|
||||
const headers = { ...(options.headers ?? {}) };
|
||||
|
||||
@@ -57,7 +57,19 @@ export default class HttpService extends Service {
|
||||
throw new HttpError(response.status, ...(await errorDetails(response)));
|
||||
}
|
||||
|
||||
return response.json();
|
||||
return response;
|
||||
}
|
||||
|
||||
async requestJson(url, options = {}) {
|
||||
return (await this.request(url, options)).json();
|
||||
}
|
||||
|
||||
async requestText(url, options = {}) {
|
||||
return (await this.request(url, options)).text();
|
||||
}
|
||||
|
||||
async requestBlob(url, options = {}) {
|
||||
return (await this.request(url, options)).blob();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ function hrefForIntegration(integration) {
|
||||
export default class NotificationsService extends Service {
|
||||
@service storage;
|
||||
@service http;
|
||||
@service siteIcons;
|
||||
|
||||
@tracked sources = [];
|
||||
@tracked loading = false;
|
||||
@@ -82,6 +83,8 @@ export default class NotificationsService extends Service {
|
||||
.filter(({ data }) => this.isSupportedIntegration(data))
|
||||
.map(({ key, data }) => this.buildSource(key, data));
|
||||
|
||||
this.resolveIcons();
|
||||
|
||||
if (this.sources.length > 0) {
|
||||
this.startPolling();
|
||||
}
|
||||
@@ -125,6 +128,22 @@ export default class NotificationsService extends Service {
|
||||
return group ? group.id : 'other';
|
||||
}
|
||||
|
||||
// Best-effort: attach a cached site icon to every source that has a URL.
|
||||
// Runs in the background so slow/broken icon discovery never blocks the
|
||||
// notification poll.
|
||||
async resolveIcons() {
|
||||
await Promise.all(
|
||||
this.sources
|
||||
.filter((source) => source.url)
|
||||
.map(async (source) => {
|
||||
const icon = await this.siteIcons.iconFor(source.url);
|
||||
if (icon) {
|
||||
this.updateSource(source.id, { icon });
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
get groups() {
|
||||
return NOTIFICATION_GROUPS.map((group) => ({
|
||||
id: group.id,
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
import Service, { service } from '@ember/service';
|
||||
|
||||
// Icons rarely change, so a week-old record is good enough until we lazily
|
||||
// revalidate it in the background.
|
||||
export const SITE_ICON_TTL = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
// The dashboard tiles render around 56px, so aim for something crisp on
|
||||
// higher-density displays without pulling down 1024px art.
|
||||
export const SITE_ICON_TARGET_SIZE = 192;
|
||||
|
||||
export function normalizeOrigin(value) {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new URL(value).origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveUrl(href, base) {
|
||||
try {
|
||||
return new URL(href, base).href;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseWidth(sizes) {
|
||||
const match = /(\d+)x(\d+)/.exec(sizes ?? '');
|
||||
// "any" (usually SVG) has no intrinsic size.
|
||||
if (!match) {
|
||||
return 0;
|
||||
}
|
||||
return Number(match[1]);
|
||||
}
|
||||
|
||||
function relTokens(link) {
|
||||
return (link.getAttribute('rel') ?? '').toLowerCase().split(/\s+/);
|
||||
}
|
||||
|
||||
function candidateScore(candidate, target) {
|
||||
let score = 0;
|
||||
|
||||
// A maskable icon is authored for a safe area, which is exactly what our
|
||||
// rounded-square tile needs, so it outranks everything else.
|
||||
if (candidate.maskable) {
|
||||
score += 1000;
|
||||
}
|
||||
if (candidate.type === 'image/svg+xml') {
|
||||
score += 400;
|
||||
}
|
||||
if (candidate.rel === 'apple-touch-icon') {
|
||||
score += 200;
|
||||
} else if (candidate.rel === 'icon') {
|
||||
score += 50;
|
||||
}
|
||||
|
||||
const width = candidate.width ?? 0;
|
||||
if (width === 0) {
|
||||
score += candidate.type === 'image/svg+xml' ? 100 : 0;
|
||||
} else if (width >= target) {
|
||||
score += 200 - Math.min(width - target, 300) / 5;
|
||||
} else {
|
||||
score += width / 4;
|
||||
}
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
function toDataUrl(blob) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result);
|
||||
reader.onerror = () =>
|
||||
reject(reader.error ?? new Error('Unable to read icon'));
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
}
|
||||
|
||||
function fallbackCandidates(origin) {
|
||||
return [
|
||||
{
|
||||
url: `${origin}/apple-touch-icon.png`,
|
||||
rel: 'fallback',
|
||||
type: 'image/png',
|
||||
width: 0,
|
||||
maskable: false,
|
||||
},
|
||||
{
|
||||
url: `${origin}/favicon.ico`,
|
||||
rel: 'fallback',
|
||||
type: 'image/x-icon',
|
||||
width: 0,
|
||||
maskable: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export default class SiteIconsService extends Service {
|
||||
@service storage;
|
||||
@service http;
|
||||
|
||||
inFlight = new Map();
|
||||
|
||||
// Resolves a site's best icon, caching the bytes in IndexedDB. Returns
|
||||
// `undefined` when nothing usable could be discovered. Always resolves;
|
||||
// callers can render a fallback and should never need to catch.
|
||||
async iconFor(urlOrOrigin, { refresh = false } = {}) {
|
||||
const origin = normalizeOrigin(urlOrOrigin);
|
||||
if (!origin) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const cached = refresh ? null : await this.storage.get('icons', origin);
|
||||
if (cached && !this.isStale(cached)) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
if (this.inFlight.has(origin)) {
|
||||
return cached ?? this.inFlight.get(origin);
|
||||
}
|
||||
|
||||
const work = this.resolve(origin, cached);
|
||||
this.inFlight.set(origin, work);
|
||||
|
||||
// Serve a stale-but-usable icon immediately while the refresh runs.
|
||||
return cached ?? work;
|
||||
}
|
||||
|
||||
async refresh(urlOrOrigin) {
|
||||
return this.iconFor(urlOrOrigin, { refresh: true });
|
||||
}
|
||||
|
||||
async resolve(origin, cached) {
|
||||
try {
|
||||
const { candidates, themeColor } = await this.discover(origin);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const blob = await this.http.requestBlob(candidate.url);
|
||||
const dataUrl = await toDataUrl(blob);
|
||||
|
||||
const record = {
|
||||
origin,
|
||||
href: candidate.url,
|
||||
dataUrl,
|
||||
mime: blob.type || candidate.type || null,
|
||||
maskable: candidate.maskable,
|
||||
width: candidate.width || null,
|
||||
themeColor,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
|
||||
await this.storage.set('icons', origin, record);
|
||||
return record;
|
||||
} catch {
|
||||
// Try the next candidate.
|
||||
}
|
||||
}
|
||||
|
||||
return cached ?? undefined;
|
||||
} catch {
|
||||
return cached ?? undefined;
|
||||
} finally {
|
||||
this.inFlight.delete(origin);
|
||||
}
|
||||
}
|
||||
|
||||
async discover(origin) {
|
||||
let html;
|
||||
|
||||
try {
|
||||
html = await this.http.requestText(`${origin}/`);
|
||||
} catch {
|
||||
return { candidates: fallbackCandidates(origin), themeColor: null };
|
||||
}
|
||||
|
||||
const doc = new DOMParser().parseFromString(html, 'text/html');
|
||||
let themeColor =
|
||||
doc
|
||||
.querySelector('meta[name="theme-color"]')
|
||||
?.getAttribute('content')
|
||||
?.trim() || null;
|
||||
|
||||
const candidates = [];
|
||||
|
||||
for (const link of doc.querySelectorAll('link[rel]')) {
|
||||
const rels = relTokens(link);
|
||||
const isApple = rels.includes('apple-touch-icon');
|
||||
const isIcon = rels.includes('icon');
|
||||
|
||||
if (!isApple && !isIcon) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const href = link.getAttribute('href');
|
||||
const url = href && resolveUrl(href, `${origin}/`);
|
||||
if (!url) {
|
||||
continue;
|
||||
}
|
||||
|
||||
candidates.push({
|
||||
url,
|
||||
rel: isApple ? 'apple-touch-icon' : 'icon',
|
||||
type: link.getAttribute('type') || null,
|
||||
width: parseWidth(link.getAttribute('sizes')),
|
||||
maskable: false,
|
||||
});
|
||||
}
|
||||
|
||||
const manifestHref = doc
|
||||
.querySelector('link[rel="manifest"]')
|
||||
?.getAttribute('href');
|
||||
const manifestUrl = manifestHref && resolveUrl(manifestHref, `${origin}/`);
|
||||
|
||||
if (manifestUrl) {
|
||||
try {
|
||||
const manifest = await this.http.requestJson(manifestUrl);
|
||||
|
||||
if (!themeColor && manifest?.theme_color) {
|
||||
themeColor = String(manifest.theme_color);
|
||||
}
|
||||
|
||||
for (const icon of manifest?.icons ?? []) {
|
||||
const url = icon?.src && resolveUrl(icon.src, manifestUrl);
|
||||
if (!url) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const purpose = String(icon.purpose ?? 'any').toLowerCase();
|
||||
|
||||
candidates.push({
|
||||
url,
|
||||
rel: 'manifest',
|
||||
type: icon.type || null,
|
||||
width: parseWidth(icon.sizes),
|
||||
maskable: purpose.split(/\s+/).includes('maskable'),
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// A broken manifest shouldn't stop us from using link tags.
|
||||
}
|
||||
}
|
||||
|
||||
candidates.push(...fallbackCandidates(origin));
|
||||
|
||||
const seen = new Set();
|
||||
const unique = candidates.filter((candidate) => {
|
||||
if (seen.has(candidate.url)) {
|
||||
return false;
|
||||
}
|
||||
seen.add(candidate.url);
|
||||
return true;
|
||||
});
|
||||
|
||||
unique.sort(
|
||||
(a, b) =>
|
||||
candidateScore(b, SITE_ICON_TARGET_SIZE) -
|
||||
candidateScore(a, SITE_ICON_TARGET_SIZE)
|
||||
);
|
||||
|
||||
return { candidates: unique, themeColor };
|
||||
}
|
||||
|
||||
isStale(record) {
|
||||
return !record?.updatedAt || Date.now() - record.updatedAt > SITE_ICON_TTL;
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ export default class StorageService extends Service {
|
||||
{ name: 'preferences', storeName: 'prefs' },
|
||||
{ name: 'integrations', storeName: 'integrations' },
|
||||
{ name: 'settings', storeName: 'settings' },
|
||||
{ name: 'icons', storeName: 'icons' },
|
||||
];
|
||||
|
||||
dbConfigs.forEach(({ name, storeName }) => {
|
||||
|
||||
@@ -23,8 +23,68 @@ module('Integration | Component | notifications/item', function (hooks) {
|
||||
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');
|
||||
assert.dom('[data-test-notifications-fallback]').hasText('F');
|
||||
});
|
||||
|
||||
test('it renders the fetched site icon when one is available', async function (assert) {
|
||||
this.set('item', {
|
||||
id: 'discourse-abc',
|
||||
label: 'forum.example.com',
|
||||
href: 'https://forum.example.com',
|
||||
status: 'ready',
|
||||
unreadCount: 1,
|
||||
icon: {
|
||||
dataUrl: 'data:image/png;base64,abc',
|
||||
maskable: true,
|
||||
themeColor: '#1d4ed8',
|
||||
},
|
||||
});
|
||||
|
||||
await render(<template><NotificationItem @item={{this.item}} /></template>);
|
||||
|
||||
assert.dom('[data-test-notifications-icon]').exists();
|
||||
assert.dom('[data-test-notifications-fallback]').doesNotExist();
|
||||
assert
|
||||
.dom('[data-test-notifications-icon]')
|
||||
.hasAttribute('src', 'data:image/png;base64,abc');
|
||||
assert.dom('[data-test-notifications-icon]').hasClass('object-cover');
|
||||
assert
|
||||
.dom('[data-test-notifications-tile]')
|
||||
.hasAttribute('style', /background-color:\s*rgb\(29, 78, 216\)/);
|
||||
});
|
||||
|
||||
test('it fits a non-maskable icon inside the tile', async function (assert) {
|
||||
this.set('item', {
|
||||
label: 'forum.example.com',
|
||||
href: 'https://forum.example.com',
|
||||
status: 'ready',
|
||||
icon: { dataUrl: 'data:image/png;base64,abc', maskable: false },
|
||||
});
|
||||
|
||||
await render(<template><NotificationItem @item={{this.item}} /></template>);
|
||||
|
||||
assert.dom('[data-test-notifications-icon]').hasClass('object-contain');
|
||||
assert.dom('[data-test-notifications-icon]').hasClass('rounded-md');
|
||||
assert.dom('[data-test-notifications-icon]').doesNotHaveClass('size-full');
|
||||
});
|
||||
|
||||
test('it ignores a theme color that is not a plain CSS color', async function (assert) {
|
||||
this.set('item', {
|
||||
label: 'forum.example.com',
|
||||
href: 'https://forum.example.com',
|
||||
status: 'ready',
|
||||
icon: {
|
||||
dataUrl: 'data:image/png;base64,abc',
|
||||
maskable: true,
|
||||
themeColor: 'red; background-image: url(evil)',
|
||||
},
|
||||
});
|
||||
|
||||
await render(<template><NotificationItem @item={{this.item}} /></template>);
|
||||
|
||||
assert
|
||||
.dom('[data-test-notifications-tile]')
|
||||
.doesNotHaveAttribute('style', /background-color/);
|
||||
});
|
||||
|
||||
test('it hides the count when there are no unread notifications', async function (assert) {
|
||||
@@ -38,7 +98,7 @@ module('Integration | Component | notifications/item', function (hooks) {
|
||||
await render(<template><NotificationItem @item={{this.item}} /></template>);
|
||||
|
||||
assert.dom('[data-test-notifications-count]').doesNotExist();
|
||||
assert.dom('a svg').hasClass('text-white');
|
||||
assert.dom('[data-test-notifications-fallback]').exists();
|
||||
});
|
||||
|
||||
test('it explains an unreachable source in the tooltip', async function (assert) {
|
||||
@@ -62,6 +122,5 @@ module('Integration | Component | notifications/item', function (hooks) {
|
||||
'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');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { module, test } from 'qunit';
|
||||
import { setupRenderingTest } from 'dashtab/tests/helpers';
|
||||
import { render } from '@ember/test-helpers';
|
||||
import setStyle from 'dashtab/modifiers/set-style';
|
||||
|
||||
module('Integration | Modifier | set-style', function (hooks) {
|
||||
setupRenderingTest(hooks);
|
||||
|
||||
test('it sets a CSS property', async function (assert) {
|
||||
this.set('color', '#ff0000');
|
||||
|
||||
await render(
|
||||
<template>
|
||||
<div data-test-target {{setStyle "background-color" this.color}}></div>
|
||||
</template>
|
||||
);
|
||||
|
||||
assert
|
||||
.dom('[data-test-target]')
|
||||
.hasAttribute('style', /background-color:\s*rgb\(255, 0, 0\)/);
|
||||
});
|
||||
|
||||
test('it removes the property when the value is empty', async function (assert) {
|
||||
this.set('color', undefined);
|
||||
|
||||
await render(
|
||||
<template>
|
||||
<div data-test-target {{setStyle "background-color" this.color}}></div>
|
||||
</template>
|
||||
);
|
||||
|
||||
assert
|
||||
.dom('[data-test-target]')
|
||||
.doesNotHaveAttribute('style', /background-color/);
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,31 @@ module('Unit | Service | http', function (hooks) {
|
||||
assert.deepEqual(data, { value: 42 });
|
||||
});
|
||||
|
||||
test('it parses a successful text response', async function (assert) {
|
||||
globalThis.fetch = async () => ({
|
||||
ok: true,
|
||||
text: async () => '<html></html>',
|
||||
});
|
||||
|
||||
const http = this.owner.lookup('service:http');
|
||||
const text = await http.requestText('https://example.com/');
|
||||
|
||||
assert.strictEqual(text, '<html></html>');
|
||||
});
|
||||
|
||||
test('it returns a blob for a successful binary response', async function (assert) {
|
||||
const expected = new Blob(['icon'], { type: 'image/png' });
|
||||
globalThis.fetch = async () => ({
|
||||
ok: true,
|
||||
blob: async () => expected,
|
||||
});
|
||||
|
||||
const http = this.owner.lookup('service:http');
|
||||
const blob = await http.requestBlob('https://example.com/favicon.ico');
|
||||
|
||||
assert.strictEqual(blob, expected);
|
||||
});
|
||||
|
||||
test('it throws HttpError on a non-ok response', async function (assert) {
|
||||
globalThis.fetch = async () => ({
|
||||
ok: false,
|
||||
|
||||
@@ -14,6 +14,9 @@ module('Unit | Service | notifications', function (hooks) {
|
||||
|
||||
const storage = this.owner.lookup('service:storage');
|
||||
await storage.clear('integrations');
|
||||
|
||||
const siteIcons = this.owner.lookup('service:site-icons');
|
||||
siteIcons.iconFor = async () => undefined;
|
||||
});
|
||||
|
||||
hooks.afterEach(function () {
|
||||
@@ -82,6 +85,30 @@ module('Unit | Service | notifications', function (hooks) {
|
||||
service.stopPolling();
|
||||
});
|
||||
|
||||
test('resolveIcons attaches a fetched icon to the source', 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 icon = { dataUrl: 'data:image/png;base64,x', maskable: true };
|
||||
const siteIcons = this.owner.lookup('service:site-icons');
|
||||
siteIcons.iconFor = async () => icon;
|
||||
|
||||
const service = this.owner.lookup('service:notifications');
|
||||
service.fetchAll = async () => {};
|
||||
await service.ready;
|
||||
await service.resolveIcons();
|
||||
|
||||
assert.deepEqual(service.sources[0].icon, icon);
|
||||
|
||||
service.stopPolling();
|
||||
});
|
||||
|
||||
test('fetchSource normalizes a discourse response', async function (assert) {
|
||||
const storage = this.owner.lookup('service:storage');
|
||||
await storage.set('integrations', 'discourse-abc', {
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { module, test } from 'qunit';
|
||||
import { setupTest } from 'dashtab/tests/helpers';
|
||||
import { normalizeOrigin } from 'dashtab/services/site-icons';
|
||||
|
||||
function blob(content, type) {
|
||||
return new Blob([content], { type });
|
||||
}
|
||||
|
||||
module('Unit | Service | site-icons', function (hooks) {
|
||||
setupTest(hooks);
|
||||
|
||||
hooks.beforeEach(async function () {
|
||||
const storage = this.owner.lookup('service:storage');
|
||||
await storage.clear('icons');
|
||||
});
|
||||
|
||||
test('normalizeOrigin derives an origin and rejects junk', function (assert) {
|
||||
assert.strictEqual(
|
||||
normalizeOrigin('https://forum.example.com/latest'),
|
||||
'https://forum.example.com'
|
||||
);
|
||||
assert.strictEqual(normalizeOrigin('nope'), null);
|
||||
assert.strictEqual(normalizeOrigin(''), null);
|
||||
});
|
||||
|
||||
test('it prefers a maskable manifest icon and caches the bytes', async function (assert) {
|
||||
const service = this.owner.lookup('service:site-icons');
|
||||
const requested = [];
|
||||
|
||||
service.http.requestText = async () =>
|
||||
'<html><head><link rel="manifest" href="/site.webmanifest"></head></html>';
|
||||
service.http.requestJson = async () => ({
|
||||
theme_color: '#0f172a',
|
||||
icons: [
|
||||
{ src: '/icon-192.png', sizes: '192x192', type: 'image/png' },
|
||||
{
|
||||
src: '/icon-maskable-512.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png',
|
||||
purpose: 'maskable',
|
||||
},
|
||||
],
|
||||
});
|
||||
service.http.requestBlob = async (url) => {
|
||||
requested.push(url);
|
||||
return blob('icon', 'image/png');
|
||||
};
|
||||
|
||||
const record = await service.iconFor('https://forum.example.com');
|
||||
|
||||
assert.strictEqual(
|
||||
record.href,
|
||||
'https://forum.example.com/icon-maskable-512.png'
|
||||
);
|
||||
assert.true(record.maskable);
|
||||
assert.strictEqual(record.themeColor, '#0f172a');
|
||||
assert.ok(record.dataUrl.startsWith('data:image/png'));
|
||||
assert.strictEqual(requested.length, 1);
|
||||
|
||||
const storage = this.owner.lookup('service:storage');
|
||||
assert.deepEqual(
|
||||
await storage.get('icons', 'https://forum.example.com'),
|
||||
record
|
||||
);
|
||||
|
||||
// A second lookup is served from the cache without touching the network.
|
||||
service.http.requestBlob = async () => {
|
||||
throw new Error('should not fetch again');
|
||||
};
|
||||
const cached = await service.iconFor('https://forum.example.com');
|
||||
assert.strictEqual(cached.href, record.href);
|
||||
});
|
||||
|
||||
test('it falls back to /favicon.ico when the HTML cannot be fetched', async function (assert) {
|
||||
const service = this.owner.lookup('service:site-icons');
|
||||
|
||||
service.http.requestText = async () => {
|
||||
throw new Error('blocked by CORS');
|
||||
};
|
||||
service.http.requestBlob = async (url) => {
|
||||
if (url.endsWith('/favicon.ico')) {
|
||||
return blob('icon', 'image/x-icon');
|
||||
}
|
||||
throw new Error('not found');
|
||||
};
|
||||
|
||||
const record = await service.iconFor('https://forum.example.com');
|
||||
|
||||
assert.strictEqual(record.href, 'https://forum.example.com/favicon.ico');
|
||||
assert.false(record.maskable);
|
||||
});
|
||||
|
||||
test('it resolves relative icon URLs against the site origin', async function (assert) {
|
||||
const service = this.owner.lookup('service:site-icons');
|
||||
|
||||
service.http.requestText = async () =>
|
||||
'<html><head><link rel="apple-touch-icon" href="/touch.png"></head></html>';
|
||||
service.http.requestBlob = async () => blob('icon', 'image/png');
|
||||
|
||||
const record = await service.iconFor('https://forum.example.com');
|
||||
|
||||
assert.strictEqual(record.href, 'https://forum.example.com/touch.png');
|
||||
});
|
||||
|
||||
test('it resolves nothing when every candidate fails', async function (assert) {
|
||||
const service = this.owner.lookup('service:site-icons');
|
||||
|
||||
service.http.requestText = async () => {
|
||||
throw new Error('blocked by CORS');
|
||||
};
|
||||
service.http.requestBlob = async () => {
|
||||
throw new Error('not found');
|
||||
};
|
||||
|
||||
const record = await service.iconFor('https://forum.example.com');
|
||||
|
||||
assert.strictEqual(record, undefined);
|
||||
});
|
||||
});
|
||||
@@ -4,9 +4,20 @@ import { setupTest } from 'dashtab/tests/helpers';
|
||||
module('Unit | Service | storage', function (hooks) {
|
||||
setupTest(hooks);
|
||||
|
||||
// TODO: Replace this with your real tests.
|
||||
test('it exists', function (assert) {
|
||||
let service = this.owner.lookup('service:storage');
|
||||
assert.ok(service);
|
||||
});
|
||||
|
||||
test('it round-trips the icons namespace', async function (assert) {
|
||||
const service = this.owner.lookup('service:storage');
|
||||
const key = 'https://forum.example.com';
|
||||
const record = { href: 'https://forum.example.com/icon.png' };
|
||||
|
||||
await service.set('icons', key, record);
|
||||
assert.deepEqual(await service.get('icons', key), record);
|
||||
|
||||
await service.remove('icons', key);
|
||||
assert.strictEqual(await service.get('icons', key), null);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user