55 lines
1.7 KiB
JavaScript
55 lines
1.7 KiB
JavaScript
"use strict";
|
|
|
|
const HOST = "quick_profile";
|
|
|
|
async function callHost(msg) {
|
|
const reply = await browser.runtime.sendNativeMessage(HOST, msg);
|
|
if (!reply || !reply.ok) {
|
|
throw new Error(reply?.error || "no reply from native host");
|
|
}
|
|
return reply;
|
|
}
|
|
|
|
async function listProfiles() {
|
|
return (await callHost({ cmd: "list" })).profiles;
|
|
}
|
|
|
|
// Firefox's avatar SVGs paint the badge circle with context-fill and the
|
|
// glyph with context-stroke; chrome CSS supplies those from the profile
|
|
// theme. Outside chrome we substitute the colors directly.
|
|
function avatarDataURL(profile, size) {
|
|
const svg = profile.images?.[size];
|
|
if (!svg) {
|
|
return profile.images?.custom || null;
|
|
}
|
|
const colored = svg
|
|
.replaceAll("context-fill", profile.themeBg)
|
|
.replaceAll("context-stroke", profile.themeFg);
|
|
return "data:image/svg+xml;charset=utf-8," + encodeURIComponent(colored);
|
|
}
|
|
|
|
function loadImage(src) {
|
|
return new Promise((resolve, reject) => {
|
|
const img = new Image();
|
|
img.onload = () => resolve(img);
|
|
img.onerror = () => reject(new Error("failed to load avatar image"));
|
|
img.src = src;
|
|
});
|
|
}
|
|
|
|
async function renderIcon(profile, px) {
|
|
const canvas = document.createElement("canvas");
|
|
canvas.width = canvas.height = px;
|
|
const ctx = canvas.getContext("2d");
|
|
const isCustom = !profile.images?.["16"];
|
|
const img = await loadImage(avatarDataURL(profile, px <= 16 ? "16" : "48"));
|
|
if (isCustom) {
|
|
// Custom avatars are plain images: clip to a circle like Firefox does.
|
|
ctx.beginPath();
|
|
ctx.arc(px / 2, px / 2, px / 2, 0, 2 * Math.PI);
|
|
ctx.clip();
|
|
}
|
|
ctx.drawImage(img, 0, 0, px, px);
|
|
return ctx.getImageData(0, 0, px, px);
|
|
}
|