From 78ea35d202cac192945a3a8e3ff92e936dd226b4 Mon Sep 17 00:00:00 2001 From: Anye <53684988+Anyexyz@users.noreply.github.com> Date: Thu, 6 Nov 2025 22:44:29 +0800 Subject: [PATCH] Add number formatter web component to profile stats (#242) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在个人资料模块中,使用自定义元素 `` 来格式化显示的数字,使其更易读。该组件将大数字转换为简写形式(如 1K, 1M, 1B),提升用户体验。 ```release-note 优化个人资料小部件的数值显示 ``` --- src/components/number-formatter.ts | 44 ++++++++++++++++++++++++++ src/main.ts | 1 + templates/modules/widgets/profile.html | 24 +++++++------- 3 files changed, 58 insertions(+), 11 deletions(-) create mode 100644 src/components/number-formatter.ts diff --git a/src/components/number-formatter.ts b/src/components/number-formatter.ts new file mode 100644 index 0000000..b62bd1b --- /dev/null +++ b/src/components/number-formatter.ts @@ -0,0 +1,44 @@ +export default class NumberFormatterElement extends HTMLElement { + static get observedAttributes() { + return ["value"]; + } + + constructor() { + super(); + } + + connectedCallback() { + this.render(); + } + + attributeChangedCallback() { + this.render(); + } + + render() { + const value = this.getAttribute("value"); + if (value === null) { + this.textContent = "0"; + return; + } + + const num = parseInt(value, 10); + if (isNaN(num)) { + this.textContent = value; + return; + } + + this.textContent = this.formatNumber(num); + } + + formatNumber(num: number): string { + const formatter = new Intl.NumberFormat("en-US", { + notation: "compact", + compactDisplay: "short", + maximumFractionDigits: 1, + }); + return formatter.format(num); + } +} + +customElements.define("number-formatter", NumberFormatterElement); diff --git a/src/main.ts b/src/main.ts index 8e8eda0..a92bdb7 100644 --- a/src/main.ts +++ b/src/main.ts @@ -7,6 +7,7 @@ import colorSchemeSwitcher from "./alpine-data/color-scheme-switcher"; import upvote from "./alpine-data/upvote"; import share from "./alpine-data/share"; import uiPermission from "./alpine-data/ui-permission"; +import "./components/number-formatter"; window.Alpine = Alpine; diff --git a/templates/modules/widgets/profile.html b/templates/modules/widgets/profile.html index d36a7a0..a82f3cd 100644 --- a/templates/modules/widgets/profile.html +++ b/templates/modules/widgets/profile.html @@ -18,35 +18,37 @@
- + + +
- + + +
- + + +
- + + +