43 lines
1.8 KiB
JavaScript
43 lines
1.8 KiB
JavaScript
const svgNS = "http://www.w3.org/2000/svg";
|
|
const palettes = [
|
|
["#394639", "#c2d39b"], ["#474033", "#e5c38b"],
|
|
["#3c414d", "#b9c9e4"], ["#493b42", "#e4b6c5"],
|
|
["#444333", "#e0d29a"], ["#354647", "#afd5ce"]
|
|
];
|
|
|
|
function element(tag, attributes = {}) {
|
|
const node = document.createElementNS(svgNS, tag);
|
|
for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, value);
|
|
return node;
|
|
}
|
|
|
|
export function initials(name) {
|
|
return (name.match(/[\p{L}\p{N}]+/gu) || []).slice(0, 2)
|
|
.map(part => Array.from(part)[0]).join("").toUpperCase();
|
|
}
|
|
|
|
export function paintAvatar(target, id, name) {
|
|
if (target.dataset.identity === id && target.dataset.name === name) return;
|
|
let hash = 2166136261;
|
|
for (const character of id) hash = Math.imul(hash ^ character.charCodeAt(0), 16777619) >>> 0;
|
|
const [background, foreground] = palettes[hash % palettes.length];
|
|
const svg = element("svg", { viewBox: "0 0 64 64", class: "avatar-art", "aria-hidden": "true" });
|
|
svg.append(element("rect", { width: 64, height: 64, rx: 20, fill: background }));
|
|
const patterns = [
|
|
"M-7 18Q21-7 39 9T74 18M-8 49Q21 27 40 44T74 49",
|
|
"M-3 3 28 3 64 39M-3 21 21 21 64 64M-3 39 14 39 39 64",
|
|
"M7 59Q-6 24 25 8Q60-7 70 26M-2 42Q23 69 54 49Q75 31 52 8"
|
|
];
|
|
svg.append(element("path", { d: patterns[(hash >>> 4) % patterns.length], fill: "none",
|
|
stroke: foreground, "stroke-width": 6, opacity: .12 }));
|
|
svg.append(element("circle", { cx: 50, cy: 13, r: 3, fill: foreground, opacity: .5 }));
|
|
const label = element("text", { x: 32, y: 34, fill: foreground,
|
|
"text-anchor": "middle", "dominant-baseline": "middle", "font-size": 22,
|
|
"font-family": "system-ui, sans-serif", "font-weight": 650 });
|
|
label.textContent = initials(name);
|
|
svg.append(label);
|
|
target.replaceChildren(svg);
|
|
target.dataset.identity = id;
|
|
target.dataset.name = name;
|
|
}
|