From 63285b806838ce74db46b73a9fa357adf629bb3a Mon Sep 17 00:00:00 2001 From: Wenjie Zhang Date: Fri, 5 Jun 2026 21:02:13 +0800 Subject: [PATCH] =?UTF-8?q?refactor(web):=20=E4=BD=BF=E7=94=A8=20DiceBear?= =?UTF-8?q?=20=E7=94=9F=E6=88=90=E9=BB=98=E8=AE=A4=E5=A4=B4=E5=83=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- web/src/utils/__tests__/pixelAvatar.test.js | 21 ++++--- web/src/utils/pixelAvatar.js | 65 +-------------------- 2 files changed, 16 insertions(+), 70 deletions(-) diff --git a/web/src/utils/__tests__/pixelAvatar.test.js b/web/src/utils/__tests__/pixelAvatar.test.js index 96b70591..5bf2aae3 100644 --- a/web/src/utils/__tests__/pixelAvatar.test.js +++ b/web/src/utils/__tests__/pixelAvatar.test.js @@ -1,7 +1,7 @@ import assert from 'node:assert/strict' import { generatePixelAvatar } from '../pixelAvatar.js' -const decodeAvatarSvg = (avatar) => decodeURIComponent(avatar.replace('data:image/svg+xml,', '')) +const DICEBEAR_GLYPHS_AVATAR_BASE_URL = 'https://api.dicebear.com/10.x/glyphs/svg' const run = () => { { @@ -20,15 +20,22 @@ const run = () => { { const avatar = generatePixelAvatar('user-003') - assert.ok(avatar.startsWith('data:image/svg+xml,'), 'Should return an SVG data URL') - console.log('T3 Data URL prefix: PASS') + assert.equal( + avatar, + `${DICEBEAR_GLYPHS_AVATAR_BASE_URL}?seed=user-003`, + 'Should return a DiceBear glyphs avatar URL' + ) + console.log('T3 DiceBear URL: PASS') } { - const svg = decodeAvatarSvg(generatePixelAvatar('user-004')) - assert.ok(svg.includes(' { if (id === null || id === undefined || String(id).trim() === '') { @@ -23,52 +7,7 @@ const normalizeSeed = (id) => { return String(id).trim() } -const hashSeed = (seed) => { - let hash = 2166136261 - - for (let i = 0; i < seed.length; i += 1) { - hash ^= seed.charCodeAt(i) - hash = Math.imul(hash, 16777619) - } - - return hash >>> 0 -} - -const buildCells = (hash) => { - const cells = [] - - for (let row = 0; row < GRID_SIZE; row += 1) { - for (let col = 0; col < MIRROR_COLUMNS; col += 1) { - const bitIndex = row * MIRROR_COLUMNS + col - const filled = ((hash >>> bitIndex) & 1) === 1 - - if (!filled) continue - - cells.push([col, row]) - - const mirroredCol = GRID_SIZE - col - 1 - if (mirroredCol !== col) { - cells.push([mirroredCol, row]) - } - } - } - - if (cells.length === 0) { - cells.push([2, 2]) - } - - return cells -} - export const generatePixelAvatar = (id) => { const seed = normalizeSeed(id) - const hash = hashSeed(seed) - const color = COLOR_PALETTE[(hash >>> 16) % COLOR_PALETTE.length] - const cells = buildCells(hash) - .map(([x, y]) => ``) - .join('') - - const svg = `${cells}` - - return `data:image/svg+xml,${encodeURIComponent(svg)}` + return `${DICEBEAR_GLYPHS_AVATAR_BASE_URL}?seed=${encodeURIComponent(seed)}` }