Merge pull request 'Add custom site links with icon discovery and upload' (#5) from feature/2-custom_site_links into master

Reviewed-on: #5
This commit was merged in pull request #5.
This commit is contained in:
raucao committed 2026-11-13 17:20:08 +00:00
commit 88b25d620c
17 files changed
+1212 -13

No files matched your search

@@ -6,6 +6,10 @@ import { service } from '@ember/service';
import { formFor } from '../../../config/integration-forms';
import Avatar from './avatar.gjs';
// Generic "add anything" entries sort after the concrete integrations instead
// of among them.
const LAST_TYPES = new Set(['custom']);
export default class SettingsIntegrationsAddList extends Component {
@service modal;
@service integrations;
@@ -25,7 +29,16 @@ export default class SettingsIntegrationsAddList extends Component {
integration.instances.length
)
)
.sort((a, b) => a.label.localeCompare(b.label));
.sort((a, b) => {
const aLast = LAST_TYPES.has(a.id);
const bLast = LAST_TYPES.has(b.id);
if (aLast !== bLast) {
return aLast ? 1 : -1;
}
return a.label.localeCompare(b.label);
});
}
@action
@@ -0,0 +1,340 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { service } from '@ember/service';
import { on } from '@ember/modifier';
import { labelForUrl, normalizeSiteUrl } from '../../../utils/site-url';
// Add/edit a user-defined quick link. The site's own icon is discovered in the
// background (and previewed here); a custom upload can override it and is
// pinned until the user chooses "Use site's icon" again.
export default class SettingsIntegrationsCustomLinkForm extends Component {
@service sites;
@service siteIcons;
@service storage;
@tracked urlDraft = null;
@tracked nameDraft = null;
@tracked customIcon = null;
@tracked previewIcon = null;
@tracked previewLoading = false;
@tracked imgFailed = false;
@tracked error = null;
@tracked submitting = false;
constructor() {
super(...arguments);
this.customIcon = this.integration?.customIcon ?? null;
this.previewIcon = this.integration?.icon ?? null;
}
get integration() {
return this.args.props?.integration;
}
get isEdit() {
return this.args.props?.mode === 'edit';
}
get title() {
return this.isEdit ? 'Edit Link' : 'Add Custom Link';
}
get submitLabel() {
return this.isEdit ? 'Save' : 'Add';
}
get url() {
return this.urlDraft ?? this.integration?.url ?? '';
}
get name() {
return this.nameDraft ?? this.integration?.name ?? '';
}
get preview() {
return this.customIcon ?? this.previewIcon;
}
get hasPreview() {
return Boolean(this.preview?.dataUrl) && !this.imgFailed;
}
get imageClass() {
return this.preview?.maskable
? 'size-full object-cover'
: 'size-8 rounded-md object-contain';
}
get initial() {
const source = (this.name || labelForUrl(this.url) || '?').trim();
return source ? source[0].toUpperCase() : '?';
}
@action
updateUrl(event) {
this.urlDraft = event.target.value;
this.error = null;
}
@action
updateName(event) {
this.nameDraft = event.target.value;
}
// Preview the site's discovered icon after the user finishes typing a URL.
// Uses the cached resolver, so an unchanged edit never triggers a probe on
// its own.
@action
async previewFromUrl() {
const url = normalizeSiteUrl(this.url);
if (!url || this.customIcon) {
return;
}
this.previewLoading = true;
try {
const icon = await this.siteIcons.iconFor(url);
// The URL may have changed while discovery was in flight.
if (normalizeSiteUrl(this.url) !== url) {
return;
}
if (icon) {
this.previewIcon = icon;
this.imgFailed = false;
}
} finally {
this.previewLoading = false;
}
}
@action
async uploadIcon(event) {
const input = event.target;
const file = input.files?.[0];
// Reset so picking the same file again still fires `change`.
input.value = '';
if (!file) {
return;
}
this.error = null;
try {
this.customIcon = await this.siteIcons.iconFromFile(file);
this.imgFailed = false;
} catch (err) {
this.error = err?.message ?? 'Unable to use that image';
}
}
@action
useSiteIcon() {
this.customIcon = null;
this.imgFailed = false;
this.previewFromUrl();
}
@action
handleImageError() {
this.imgFailed = true;
}
@action
async handleSubmit(event) {
event.preventDefault();
this.error = null;
const url = normalizeSiteUrl(this.url);
if (!url) {
this.error = 'Please enter a valid website URL';
return;
}
this.submitting = true;
try {
const name = this.name.trim();
await this.storage.set('integrations', this.key(), {
type: 'custom',
status: 'active',
url,
...(name ? { name } : {}),
// Omitting `customIcon` clears a previously pinned icon.
...(this.customIcon ? { customIcon: this.customIcon } : {}),
createdAt: this.integration?.createdAt ?? Date.now(),
});
await this.sites.reload();
this.args.close?.();
} catch (err) {
console.error('Error saving custom link:', err);
this.error = 'Unable to save this link';
} finally {
this.submitting = false;
}
}
key() {
if (this.integration?.id) {
return this.integration.id;
}
const uuid =
globalThis.crypto?.randomUUID?.() ??
`${Date.now()}-${Math.random().toString(36).slice(2)}`;
return `custom-${uuid}`;
}
<template>
<div class="p-6">
<h3
id={{if @titleId @titleId "modal-title"}}
class="text-base font-semibold leading-6 text-gray-900"
>{{this.title}}</h3>
<div class="mt-2">
<p class="text-sm text-gray-500">
Add any website to your dashboard. Its icon is fetched automatically,
and you can upload your own if you prefer.
</p>
</div>
<form {{on "submit" this.handleSubmit}} class="mt-5">
<div class="space-y-5">
<div>
<label
for="custom-link-url"
class="block text-sm font-medium leading-6 text-gray-900"
>
Website URL
</label>
<div class="mt-2">
<input
type="text"
inputmode="url"
id="custom-link-url"
name="url"
value={{this.url}}
{{on "input" this.updateUrl}}
{{on "blur" this.previewFromUrl}}
placeholder="example.com"
class="block w-full rounded-md border-0 px-3 py-2 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600"
/>
</div>
<p class="mt-2 text-sm text-gray-500">
A full address; if you leave out the scheme, https is assumed.
</p>
</div>
<div>
<label
for="custom-link-name"
class="block text-sm font-medium leading-6 text-gray-900"
>
Name
</label>
<div class="mt-2">
<input
type="text"
id="custom-link-name"
name="name"
value={{this.name}}
{{on "input" this.updateName}}
placeholder={{labelForUrl this.url}}
class="block w-full rounded-md border-0 px-3 py-2 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600"
/>
</div>
<p class="mt-2 text-sm text-gray-500">
Optional. Defaults to the site's hostname.
</p>
</div>
<div class="flex items-center gap-4">
<div class="shrink-0">
{{#if this.hasPreview}}
<span
data-test-preview
class="icon-edge flex size-12 items-center justify-center overflow-hidden rounded-xl bg-gray-100"
>
<img
src={{this.preview.dataUrl}}
alt=""
aria-hidden="true"
data-test-preview-image
class={{this.imageClass}}
{{on "error" this.handleImageError}}
/>
</span>
{{else}}
<span
class="flex size-12 items-center justify-center overflow-hidden rounded-xl bg-indigo-500 text-sm font-semibold text-white"
data-test-preview
>{{this.initial}}</span>
{{/if}}
</div>
<div class="flex flex-wrap items-center gap-2">
<label
class="cursor-pointer rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50"
>
{{#if this.customIcon}}Replace icon{{else}}Upload icon{{/if}}
<input
type="file"
accept="image/*"
class="sr-only"
data-test-icon-upload
{{on "change" this.uploadIcon}}
/>
</label>
{{#if this.customIcon}}
<button
type="button"
data-test-use-site-icon
{{on "click" this.useSiteIcon}}
class="rounded-md px-3 py-2 text-sm font-semibold text-gray-600 hover:text-gray-900"
>
Use site's icon
</button>
{{/if}}
{{#if this.previewLoading}}
<span class="text-sm text-gray-500">Fetching icon…</span>
{{/if}}
</div>
</div>
{{#if this.error}}
<p class="text-sm text-red-600" data-test-error>{{this.error}}</p>
{{/if}}
</div>
<div class="mt-5 sm:mt-6 flex gap-3">
<button
type="submit"
disabled={{this.submitting}}
class="inline-flex w-full justify-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 disabled:opacity-50"
>
{{this.submitLabel}}
</button>
<button
type="button"
{{on "click" @close}}
class="inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50"
>
Cancel
</button>
</div>
</form>
</div>
</template>
}
+2
View File
@@ -7,6 +7,7 @@ import HomeAssistantForm from '../components/settings/integrations/home-assistan
import CalendarCaldavForm from '../components/settings/integrations/calendar-caldav-form.gjs';
import CalendarIcsForm from '../components/settings/integrations/calendar-ics-form.gjs';
import OpenRouterForm from '../components/settings/integrations/openrouter-form.gjs';
import CustomLinkForm from '../components/settings/integrations/custom-link-form.gjs';
const FORMS = {
discourse: DiscourseForm,
@@ -18,6 +19,7 @@ const FORMS = {
'calendar-caldav': CalendarCaldavForm,
'calendar-ics': CalendarIcsForm,
openrouter: OpenRouterForm,
custom: CustomLinkForm,
};
export function formFor(type) {
+16
View File
@@ -18,6 +18,10 @@ export const BITCOIN_ICON_PATH =
export const BITCOIN_ICON_TRANSFORM =
'translate(11.575 11.775) scale(1.5) translate(-11.575 -11.775)';
// Heroicons link (outline), a single path so it fits the registry avatar.
const CUSTOM_LINK_ICON_PATH =
'M13.19 8.688a4.5 4.5 0 0 1 1.242 7.244l-4.5 4.5a4.5 4.5 0 0 1-6.364-6.364l1.757-1.757m13.35-.622 1.757-1.757a4.5 4.5 0 0 0-6.364-6.364l-4.5 4.5a4.5 4.5 0 0 0 1.242 7.244';
export const FEEDBIN_ICON_URL = '/img/icons/feedbin.png';
// Official Discourse square icon, used for the Add/Manage lists and as the
@@ -138,6 +142,18 @@ export const INTEGRATIONS = [
hasSettings: true,
reconnectable: false,
},
{
id: 'custom',
label: 'Custom Link',
description: 'Add any website as a quick link',
colorClass: 'bg-slate-500',
iconPath: CUSTOM_LINK_ICON_PATH,
iconFill: false,
available: true,
supportsMultiple: true,
hasSettings: true,
reconnectable: false,
},
];
export function integrationFor(type) {
+7
View File
@@ -19,6 +19,13 @@ export const SITE_GROUPS = [
label: 'Home Assistant',
integrationTypes: ['homeassistant'],
},
// User-defined quick links. Appended last so the columns of existing users
// keep their order.
{
id: 'links',
label: 'Links',
integrationTypes: ['custom'],
},
];
// The integration types that appear as dashboard quick links.
+26
View File
@@ -151,6 +151,32 @@ const ADAPTERS = {
return this.sites.removeSource(instance.id);
},
},
custom: {
instances() {
return this.sites.all
.filter((site) => site.type === 'custom')
.map((site) => {
const integration = this.sites.integrationFor(site.id);
return {
id: site.id,
type: 'custom',
label: site.label,
// The built site's `url` is owned by icon discovery; read the
// stored fields from the raw record instead.
url: integration?.url,
name: integration?.name,
customIcon: integration?.customIcon,
icon: site.icon,
status: 'active',
canReconnect: false,
};
});
},
remove(instance) {
return this.sites.removeSource(instance.id);
},
},
bitcoin: {
instances() {
if (!this.bitcoin.enabled) {
+7
View File
@@ -1,4 +1,5 @@
import Service, { service } from '@ember/service';
import { readIconFile } from '../utils/image-file';
// Icons rarely change, so a week-old record is good enough until we lazily
// revalidate it in the background.
@@ -284,6 +285,12 @@ export default class SiteIconsService extends Service {
return this.iconFor(urlOrOrigin, { refresh: true });
}
// Turns a user-uploaded image file into an icon record for storage. Kept on
// this service so the form has a single icon seam (and tests can stub it).
async iconFromFile(file, options) {
return readIconFile(file, options);
}
async resolve(origin, cached) {
try {
const { candidates, themeColor } = await this.discover(origin);
+36 -12
View File
@@ -15,14 +15,7 @@ import {
HOME_ASSISTANT_ICON_URL,
} from '../config/home-assistant';
import { normalizeOrigin } from './site-icons';
function labelForUrl(url) {
try {
return new URL(url).hostname;
} catch {
return url;
}
}
import { labelForUrl } from '../utils/site-url';
function hrefForIntegration(integration) {
if (integration.type === 'discourse' && integration.url) {
@@ -178,6 +171,22 @@ export default class SitesService extends Service {
};
}
// A user-defined quick link. `url` is kept for icon discovery even when a
// custom icon is pinned; `resolveIcons` uses the `customIcon` flag below to
// leave the user's choice alone.
if (integration.type === 'custom') {
return {
id: key,
type: 'custom',
groupId: this.groupIdForType('custom'),
label: integration.name?.trim() || labelForUrl(integration.url),
url: integration.url,
href: integration.url,
icon: integration.customIcon,
customIcon: integration.customIcon,
};
}
return {
id: key,
type: integration.type,
@@ -202,15 +211,29 @@ export default class SitesService extends Service {
// Best-effort: attach a cached site icon to every site that has a URL. Runs in
// the background so slow/broken icon discovery never blocks the tile render.
// Sites with a user-pinned `customIcon` are skipped, and re-checked before
// writing back, so an in-flight discovery cannot clobber a freshly uploaded
// icon after an edit.
async resolveIcons() {
await Promise.all(
this.list
.filter((site) => site.url)
.filter((site) => site.url && !site.customIcon)
.map(async (site) => {
const icon = await this.siteIcons.iconFor(site.url);
if (icon) {
this.updateSite(site.id, { icon });
if (!icon) {
return;
}
const current = this.list.find(
(candidate) => candidate.id === site.id
);
if (!current || current.customIcon) {
return;
}
this.updateSite(site.id, { icon });
})
);
}
@@ -251,7 +274,8 @@ export default class SitesService extends Service {
const origin = normalizeOrigin(url);
const site = this.list.find(
(candidate) => normalizeOrigin(candidate.url) === origin
(candidate) =>
!candidate.customIcon && normalizeOrigin(candidate.url) === origin
);
if (site) {
+74
View File
@@ -0,0 +1,74 @@
// Uploaded icons are kept small so they don't bloat IndexedDB, and only ever
// rendered through an <img>, so no markup can be executed.
export const ICON_MAX_FILE_SIZE = 1024 * 1024;
// Match the size the favicon pipeline targets for crisp tiles on hidpi screens.
export const ICON_TARGET_SIZE = 192;
export class IconFileError extends Error {
constructor(message) {
super(message);
this.name = 'IconFileError';
}
}
function readAsDataUrl(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () =>
reject(reader.error ?? new IconFileError('Unable to read the image'));
reader.readAsDataURL(file);
});
}
// Turns an uploaded image file into an icon record ready for storage. Raster
// images larger than `targetSize` are downscaled; anything that cannot be
// decoded falls back to the original bytes so an upload never hard-fails.
export async function readIconFile(
file,
{ targetSize = ICON_TARGET_SIZE } = {}
) {
if (!file || !file.type?.startsWith('image/')) {
throw new IconFileError('Please choose an image file');
}
if (file.size > ICON_MAX_FILE_SIZE) {
throw new IconFileError('That image is too large (max 1 MB)');
}
const dataUrl = await readAsDataUrl(file);
// SVGs are already vector and typically tiny; leave them untouched.
if (file.type === 'image/svg+xml') {
return { dataUrl, maskable: false };
}
try {
const bitmap = await createImageBitmap(file);
const scale = Math.min(
1,
targetSize / Math.max(bitmap.width, bitmap.height)
);
if (scale >= 1) {
bitmap.close?.();
return { dataUrl, maskable: false };
}
const canvas = document.createElement('canvas');
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
canvas.height = Math.max(1, Math.round(bitmap.height * scale));
canvas
.getContext('2d')
.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
bitmap.close?.();
return { dataUrl: canvas.toDataURL('image/png'), maskable: false };
} catch {
// Decoding or canvas can fail (Firefox rejects SVG bitmaps, say); keep the
// original bytes.
return { dataUrl, maskable: false };
}
}
+56
View File
@@ -0,0 +1,56 @@
// A value with a bare host and port (`example.com:8080`) parses as a URL with
// an odd scheme, so recognize it explicitly before deciding it is a scheme.
const HOST_PORT = /^[^/\s]+:\d+(?:[/?#]|$)/;
function parseUrl(value) {
try {
return new URL(value);
} catch {
return null;
}
}
function isHttpUrl(url) {
return url.protocol === 'http:' || url.protocol === 'https:';
}
// Custom site links are typed by hand, so normalize them to an absolute
// http(s) URL before anything is stored or rendered. Only http(s) is allowed:
// a value like `javascript:` or `data:` must never reach an anchor's href.
export function normalizeSiteUrl(input) {
const value = (input ?? '').trim();
if (!value || /\s/.test(value)) {
return null;
}
let url = parseUrl(value);
if (!url || !isHttpUrl(url)) {
// A value with no scheme (`example.com`) or a bare host:port is assumed to
// be https. Any other explicit scheme (ftp:, javascript:, data:, …) is
// rejected by the checks below.
if (!url || HOST_PORT.test(value)) {
url = parseUrl(`https://${value}`);
}
}
if (!url || !isHttpUrl(url) || !url.hostname) {
return null;
}
// Never persist embedded credentials into a clickable link.
url.username = '';
url.password = '';
return url.href;
}
// The default label for a site, derived from its hostname.
export function labelForUrl(url) {
try {
return new URL(url).hostname;
} catch {
return url;
}
}
@@ -220,6 +220,29 @@ module(
assert.dom('[data-instance="github"] [data-test-settings]').exists();
});
test('it lists custom site links as editable', async function (assert) {
const sites = new FakeSitesService();
sites.all = [
{
id: 'custom-1',
type: 'custom',
label: 'Example',
href: 'https://example.com',
},
];
sites.records = {
'custom-1': { url: 'https://example.com', name: 'Example' },
};
register(this.owner, { sites });
await render(<template><SiteLinks /></template>);
assert.dom('[data-instance="custom-1"]').exists();
assert.dom('[data-instance="custom-1"]').containsText('Custom Link');
assert.dom('[data-instance="custom-1"] [data-test-settings]').exists();
});
test('editing a site link opens its form', async function (assert) {
const sites = new FakeSitesService();
sites.all = [
@@ -129,6 +129,11 @@ module(
)
.exists();
assert.dom('[data-add="homeassistant"]').doesNotHaveAttribute('disabled');
assert.dom().containsText('Custom Link');
assert.dom().containsText('Add any website as a quick link');
assert.dom('[data-add="custom"]').exists();
assert.dom('[data-add="custom"]').doesNotHaveAttribute('disabled');
});
test('it can be scoped to a subset of integration types', async function (assert) {
@@ -143,6 +148,7 @@ module(
assert.dom('[data-add="github"]').doesNotExist();
assert.dom('[data-add="homeassistant"]').doesNotExist();
assert.dom('[data-add="calendar-caldav"]').doesNotExist();
assert.dom('[data-add="custom"]').doesNotExist();
});
test('it sorts the available integrations by name', async function (assert) {
@@ -166,6 +172,19 @@ module(
]);
});
test('it sorts the generic Custom Link type last', async function (assert) {
register(this.owner);
const props = { types: ['custom', 'discourse', 'github'] };
await render(<template><List @props={{props}} /></template>);
const ids = [...this.element.querySelectorAll('[data-add]')].map(
(el) => el.dataset.add
);
assert.deepEqual(ids, ['discourse', 'github', 'custom']);
});
test('clicking an integration opens its add form', async function (assert) {
const { modal } = register(this.owner);
@@ -0,0 +1,295 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, fillIn, triggerEvent, click } from '@ember/test-helpers';
import CustomLinkForm from 'dashtab/components/settings/integrations/custom-link-form';
const noop = () => {};
// Real 1x1 images so the <img> actually loads (an invalid data URL fires
// `error` and the component falls back to the initial).
const PNG_ICON =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
const GIF_ICON =
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
function registerServices(owner, overrides = {}) {
const storage = overrides.storage ?? { set: async () => {} };
const sites = overrides.sites ?? { reload: async () => {} };
const siteIcons = overrides.siteIcons ?? {
iconFor: async () => undefined,
iconFromFile: async () => ({ dataUrl: PNG_ICON, maskable: false }),
};
owner.register('service:storage', storage, { instantiate: false });
owner.register('service:sites', sites, { instantiate: false });
owner.register('service:site-icons', siteIcons, { instantiate: false });
}
function selectFile(element, file) {
const input = element.querySelector('[data-test-icon-upload]');
const dataTransfer = new DataTransfer();
dataTransfer.items.add(file);
input.files = dataTransfer.files;
return triggerEvent(input, 'change');
}
module(
'Integration | Component | settings/integrations/custom-link-form',
function (hooks) {
setupRenderingTest(hooks);
test('it renders the add form', async function (assert) {
registerServices(this.owner);
await render(<template><CustomLinkForm @close={{noop}} /></template>);
assert.dom().containsText('Add Custom Link');
assert.dom('#custom-link-url').exists().hasValue('');
assert.dom('#custom-link-name').exists();
assert.dom('[data-test-icon-upload]').exists();
});
test('it places the icon controls after the URL and name fields', async function (assert) {
registerServices(this.owner);
await render(<template><CustomLinkForm @close={{noop}} /></template>);
const name = this.element.querySelector('#custom-link-name');
const upload = this.element.querySelector('[data-test-icon-upload]');
assert.true(
Boolean(
name.compareDocumentPosition(upload) &
Node.DOCUMENT_POSITION_FOLLOWING
),
'the icon controls come after the name field'
);
});
test('it rejects an empty or invalid URL without storing anything', async function (assert) {
const saved = [];
registerServices(this.owner, {
storage: { set: async (...args) => saved.push(args) },
});
await render(<template><CustomLinkForm @close={{noop}} /></template>);
await triggerEvent('form', 'submit');
assert
.dom('[data-test-error]')
.hasText('Please enter a valid website URL');
await fillIn('#custom-link-url', 'javascript:alert(1)');
await triggerEvent('form', 'submit');
assert
.dom('[data-test-error]')
.hasText('Please enter a valid website URL');
assert.strictEqual(saved.length, 0);
});
test('it stores a normalized record and reloads the sites', async function (assert) {
const saved = [];
let reloaded = 0;
let closed = false;
registerServices(this.owner, {
storage: {
set: async (namespace, key, value) =>
saved.push({ namespace, key, value }),
},
sites: {
reload: async () => {
reloaded++;
},
},
});
const closeDialog = () => {
closed = true;
};
await render(
<template><CustomLinkForm @close={{closeDialog}} /></template>
);
await fillIn('#custom-link-url', 'example.com/path');
await fillIn('#custom-link-name', 'Example');
await triggerEvent('form', 'submit');
assert.strictEqual(saved.length, 1);
assert.strictEqual(saved[0].namespace, 'integrations');
assert.true(saved[0].key.startsWith('custom-'));
assert.strictEqual(saved[0].value.type, 'custom');
assert.strictEqual(saved[0].value.status, 'active');
assert.strictEqual(saved[0].value.url, 'https://example.com/path');
assert.strictEqual(saved[0].value.name, 'Example');
assert.strictEqual(reloaded, 1);
assert.true(closed);
});
test('edit mode prefills and keeps the key, name and custom icon', async function (assert) {
const saved = [];
const customIcon = {
dataUrl: PNG_ICON,
maskable: false,
};
registerServices(this.owner, {
storage: {
set: async (namespace, key, value) =>
saved.push({ namespace, key, value }),
},
});
this.props = {
mode: 'edit',
integration: {
id: 'custom-1',
url: 'https://example.com/',
name: 'Example',
customIcon,
icon: customIcon,
},
};
await render(
<template>
<CustomLinkForm @props={{this.props}} @close={{noop}} />
</template>
);
assert.dom().containsText('Edit Link');
assert.dom('#custom-link-url').hasValue('https://example.com/');
assert.dom('#custom-link-name').hasValue('Example');
assert
.dom('[data-test-preview-image]')
.hasAttribute('src', customIcon.dataUrl);
await triggerEvent('form', 'submit');
assert.strictEqual(saved.length, 1);
assert.strictEqual(saved[0].key, 'custom-1');
assert.deepEqual(saved[0].value.customIcon, customIcon);
});
test('previews the discovered icon on URL blur', async function (assert) {
registerServices(this.owner, {
siteIcons: {
iconFor: async () => ({
dataUrl: GIF_ICON,
maskable: true,
}),
iconFromFile: async () => undefined,
},
});
await render(<template><CustomLinkForm @close={{noop}} /></template>);
await fillIn('#custom-link-url', 'example.com');
await triggerEvent('#custom-link-url', 'blur');
assert.dom('[data-test-preview-image]').hasAttribute('src', GIF_ICON);
});
test('uploading an icon shows it and stores it', async function (assert) {
const saved = [];
const uploaded = {
dataUrl: PNG_ICON,
maskable: false,
};
registerServices(this.owner, {
storage: {
set: async (namespace, key, value) =>
saved.push({ namespace, key, value }),
},
siteIcons: {
iconFor: async () => undefined,
iconFromFile: async () => uploaded,
},
});
await render(<template><CustomLinkForm @close={{noop}} /></template>);
await fillIn('#custom-link-url', 'example.com');
await selectFile(
this.element,
new File(['x'], 'icon.png', { type: 'image/png' })
);
assert
.dom('[data-test-preview-image]')
.hasAttribute('src', uploaded.dataUrl);
assert.dom('[data-test-use-site-icon]').exists();
await triggerEvent('form', 'submit');
assert.deepEqual(saved[0].value.customIcon, uploaded);
});
test('it surfaces an upload error', async function (assert) {
registerServices(this.owner, {
siteIcons: {
iconFor: async () => undefined,
iconFromFile: async () => {
throw new Error('Please choose an image file');
},
},
});
await render(<template><CustomLinkForm @close={{noop}} /></template>);
await selectFile(
this.element,
new File(['x'], 'notes.txt', { type: 'text/plain' })
);
assert.dom('[data-test-error]').hasText('Please choose an image file');
});
test('"Use site\'s icon" clears a pinned icon', async function (assert) {
const saved = [];
const customIcon = {
dataUrl: PNG_ICON,
maskable: false,
};
registerServices(this.owner, {
storage: {
set: async (namespace, key, value) =>
saved.push({ namespace, key, value }),
},
siteIcons: {
iconFor: async () => ({
dataUrl: GIF_ICON,
maskable: true,
}),
iconFromFile: async () => undefined,
},
});
this.props = {
mode: 'edit',
integration: {
id: 'custom-1',
url: 'https://example.com/',
customIcon,
icon: customIcon,
},
};
await render(
<template>
<CustomLinkForm @props={{this.props}} @close={{noop}} />
</template>
);
await click('[data-test-use-site-icon]');
assert.dom('[data-test-preview-image]').hasAttribute('src', GIF_ICON);
await triggerEvent('form', 'submit');
assert.strictEqual(saved[0].value.customIcon, undefined);
});
}
);
+52
View File
@@ -143,6 +143,13 @@ module('Unit | Service | integrations', function (hooks) {
assert.false(homeassistant.reconnectable);
assert.strictEqual(homeassistant.themeColor, '#18bcf2');
assert.strictEqual(homeassistant.instances.length, 0);
const custom = service.all.find((entry) => entry.id === 'custom');
assert.true(custom.available);
assert.true(custom.supportsMultiple);
assert.true(custom.hasSettings);
assert.false(custom.reconnectable);
assert.strictEqual(custom.instances.length, 0);
});
test('rows is empty when nothing is connected', function (assert) {
@@ -442,6 +449,51 @@ module('Unit | Service | integrations', function (hooks) {
assert.strictEqual(row.byline, 'ha.example.com');
});
test('custom adapter exposes the stored url, name and custom icon', async function (assert) {
const customIcon = {
dataUrl: 'data:image/png;base64,up',
maskable: false,
};
const sites = new FakeSitesService();
sites.all = [
{
id: 'custom-1',
type: 'custom',
label: 'Example',
href: 'https://example.com',
icon: customIcon,
},
];
sites.records = {
'custom-1': {
url: 'https://example.com',
name: 'Example',
customIcon,
},
};
const { sites: registeredSites } = register(this.owner, { sites });
const service = this.owner.lookup('service:integrations');
const custom = service.all.find((entry) => entry.id === 'custom');
assert.strictEqual(custom.instances.length, 1);
assert.strictEqual(custom.instances[0].id, 'custom-1');
assert.strictEqual(custom.instances[0].label, 'Example');
assert.strictEqual(custom.instances[0].url, 'https://example.com');
assert.strictEqual(custom.instances[0].name, 'Example');
assert.deepEqual(custom.instances[0].customIcon, customIcon);
assert.deepEqual(custom.instances[0].icon, customIcon);
assert.false(custom.instances[0].canReconnect);
const row = service.rows.find((entry) => entry.id === 'custom-1');
assert.strictEqual(row.label, 'Custom Link');
assert.strictEqual(row.byline, 'Example');
await service.remove({ type: 'custom', id: 'custom-1' });
assert.deepEqual(registeredSites.removed, ['custom-1']);
});
test('calendar adapters expose instances and remove', async function (assert) {
const calendar = new FakeCalendarService();
calendar.instancesByType['calendar-caldav'] = [
+121
View File
@@ -306,6 +306,127 @@ module('Unit | Service | sites', function (hooks) {
assert.deepEqual(service.all[0].icon, icon);
});
test('load builds a custom link with a hostname label and a discovery URL', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'custom-1', {
type: 'custom',
status: 'active',
url: 'https://news.example.com/top',
});
const service = this.owner.lookup('service:sites');
await service.ready;
assert.strictEqual(service.all.length, 1);
const [item] = service.all;
assert.strictEqual(item.type, 'custom');
assert.strictEqual(item.groupId, 'links');
assert.strictEqual(item.label, 'news.example.com');
assert.strictEqual(item.href, 'https://news.example.com/top');
assert.strictEqual(item.url, 'https://news.example.com/top');
assert.notOk(item.icon);
assert.notOk(item.customIcon);
const groups = service.groups;
assert.strictEqual(groups.length, 1);
assert.strictEqual(groups[0].id, 'links');
assert.strictEqual(groups[0].label, 'Links');
});
test('a custom link name overrides the hostname label', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'custom-1', {
type: 'custom',
status: 'active',
url: 'https://news.example.com',
name: ' Hacker News ',
});
const service = this.owner.lookup('service:sites');
await service.ready;
assert.strictEqual(service.all[0].label, 'Hacker News');
});
test('resolveIcons discovers an icon for a custom link without a pinned icon', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'custom-1', {
type: 'custom',
status: 'active',
url: 'https://news.example.com',
});
const fetched = {
dataUrl: 'data:image/png;base64,fetched',
maskable: true,
};
const siteIcons = this.owner.lookup('service:site-icons');
siteIcons.iconFor = async () => fetched;
const service = this.owner.lookup('service:sites');
await service.ready;
await service.resolveIcons();
assert.deepEqual(service.all[0].icon, fetched);
});
test('resolveIcons leaves a pinned custom icon alone', async function (assert) {
const storage = this.owner.lookup('service:storage');
const customIcon = { dataUrl: 'data:image/png;base64,up', maskable: false };
await storage.set('integrations', 'custom-1', {
type: 'custom',
status: 'active',
url: 'https://news.example.com',
customIcon,
});
const siteIcons = this.owner.lookup('service:site-icons');
let calls = 0;
siteIcons.iconFor = async () => {
calls++;
return { dataUrl: 'data:image/png;base64,fetched', maskable: true };
};
const service = this.owner.lookup('service:sites');
await service.ready;
await service.resolveIcons();
assert.strictEqual(calls, 0);
assert.deepEqual(service.all[0].icon, customIcon);
assert.deepEqual(service.all[0].customIcon, customIcon);
});
test('resolveIcons does not clobber a custom icon pinned while discovery was in flight', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'custom-1', {
type: 'custom',
status: 'active',
url: 'https://news.example.com',
});
let resolveDiscovery;
const siteIcons = this.owner.lookup('service:site-icons');
siteIcons.iconFor = () =>
new Promise((resolve) => {
resolveDiscovery = resolve;
});
const service = this.owner.lookup('service:sites');
await service.ready; // discovery is now pending on the controlled promise
const pinned = { dataUrl: 'data:image/png;base64,pinned', maskable: false };
service.updateSite('custom-1', { icon: pinned, customIcon: pinned });
resolveDiscovery({
dataUrl: 'data:image/png;base64,fetched',
maskable: true,
});
await new Promise((resolve) => setTimeout(resolve, 0));
assert.deepEqual(service.all[0].icon, pinned);
});
test('reload picks up newly added integrations', async function (assert) {
const storage = this.owner.lookup('service:storage');
const service = this.owner.lookup('service:sites');
+69
View File
@@ -0,0 +1,69 @@
import { module, test } from 'qunit';
import {
ICON_MAX_FILE_SIZE,
IconFileError,
readIconFile,
} from 'dashtab/utils/image-file';
function file(parts, name, type) {
return new File(parts, name, { type });
}
module('Unit | Utility | image-file', function () {
test('rejects a non-image file', async function (assert) {
await assert.rejects(
readIconFile(file(['hello'], 'notes.txt', 'text/plain')),
IconFileError,
'rejects the file'
);
});
test('rejects a file above the size cap', async function (assert) {
const big = file(
[new Uint8Array(ICON_MAX_FILE_SIZE + 1)],
'big.png',
'image/png'
);
await assert.rejects(
readIconFile(big),
IconFileError,
'rejects the oversized file'
);
});
test('keeps an SVG as its original data URL', async function (assert) {
const svg = file(
['<svg xmlns="http://www.w3.org/2000/svg"></svg>'],
'icon.svg',
'image/svg+xml'
);
const icon = await readIconFile(svg);
assert.true(icon.dataUrl.startsWith('data:image/svg+xml'));
assert.false(icon.maskable);
});
test('falls back to the original bytes when decoding fails', async function (assert) {
const original = globalThis.createImageBitmap;
globalThis.createImageBitmap = async () => {
throw new Error('cannot decode');
};
try {
const png = file(
[Uint8Array.from([0x89, 0x50, 0x4e, 0x47])],
'icon.png',
'image/png'
);
const icon = await readIconFile(png);
assert.true(icon.dataUrl.startsWith('data:image/png;base64,'));
assert.false(icon.maskable);
} finally {
globalThis.createImageBitmap = original;
}
});
});
+55
View File
@@ -0,0 +1,55 @@
import { module, test } from 'qunit';
import { labelForUrl, normalizeSiteUrl } from 'dashtab/utils/site-url';
module('Unit | Utility | site-url', function () {
test('prepends https when no scheme is given', function (assert) {
assert.strictEqual(normalizeSiteUrl('example.com'), 'https://example.com/');
assert.strictEqual(
normalizeSiteUrl('example.com/path'),
'https://example.com/path'
);
assert.strictEqual(
normalizeSiteUrl('example.com:8080'),
'https://example.com:8080/'
);
});
test('keeps an explicit http(s) URL and its path, query and port', function (assert) {
assert.strictEqual(
normalizeSiteUrl('http://example.com'),
'http://example.com/'
);
assert.strictEqual(
normalizeSiteUrl('https://example.com:8080/a?b=1'),
'https://example.com:8080/a?b=1'
);
});
test('rejects non-http(s) schemes', function (assert) {
assert.strictEqual(normalizeSiteUrl('ftp://example.com'), null);
assert.strictEqual(normalizeSiteUrl('javascript:alert(1)'), null);
assert.strictEqual(normalizeSiteUrl('data:text/html,hi'), null);
});
test('strips embedded credentials', function (assert) {
assert.strictEqual(
normalizeSiteUrl('https://user:pass@example.com/path'),
'https://example.com/path'
);
});
test('rejects empty, whitespace and unparseable values', function (assert) {
assert.strictEqual(normalizeSiteUrl(''), null);
assert.strictEqual(normalizeSiteUrl(' '), null);
assert.strictEqual(normalizeSiteUrl('not a url'), null);
assert.strictEqual(normalizeSiteUrl(undefined), null);
});
test('labelForUrl derives the hostname', function (assert) {
assert.strictEqual(
labelForUrl('https://forum.example.com/latest'),
'forum.example.com'
);
assert.strictEqual(labelForUrl('junk'), 'junk');
});
});