fix(editor): unify file size formatting method (#12444)

Closes: [BS-3524](https://linear.app/affine-design/issue/BS-3524/统一文件大小单位,与-af-一致)

![Screenshot 2025-05-22 at 15.09.41.png](https://graphite-user-uploaded-assets-prod.s3.amazonaws.com/8ypiIKZXudF5a0tIgIzf/ddb6fa38-243f-4e65-b572-d476e3771d74.png)

![Screenshot 2025-05-22 at 15.09.48.png](https://graphite-user-uploaded-assets-prod.s3.amazonaws.com/8ypiIKZXudF5a0tIgIzf/5d182332-4d0a-419a-b206-df58552fe740.png)

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **Refactor**
  - Updated file size formatting throughout the app to use a new, consistent utility for displaying file sizes.
  - Improved clarity and uniformity of file size information in attachments, images, and related notifications.
  - Enhanced type support to explicitly allow null values for file size descriptions.
- **Bug Fixes**
  - Adjusted file size display in tests to match updated formatting standards.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
fundon
2025-05-23 06:33:30 +00:00
parent fd3a2756f8
commit d0539fde22
12 changed files with 21 additions and 52 deletions
@@ -22,7 +22,7 @@ import {
TelemetryProvider,
ThemeProvider,
} from '@blocksuite/affine-shared/services';
import { humanFileSize } from '@blocksuite/affine-shared/utils';
import { formatSize } from '@blocksuite/affine-shared/utils';
import {
AttachmentIcon,
ResetIcon,
@@ -316,7 +316,7 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
errorIcon: WarningIcon(),
icon: AttachmentIcon(),
title: name,
description: humanFileSize(size),
description: formatSize(size),
});
return { ...resolvedState, kind };
@@ -13,7 +13,7 @@ import {
FileSizeLimitProvider,
TelemetryProvider,
} from '@blocksuite/affine-shared/services';
import { humanFileSize } from '@blocksuite/affine-shared/utils';
import { formatSize } from '@blocksuite/affine-shared/utils';
import { Bound, type IVec, Vec } from '@blocksuite/global/gfx';
import type { BlockStdScope } from '@blocksuite/std';
import { GfxControllerIdentifier } from '@blocksuite/std/gfx';
@@ -93,7 +93,7 @@ function hasExceeded(
const exceeded = files.some(file => file.size > maxFileSize);
if (exceeded) {
const size = humanFileSize(maxFileSize, true, 0);
const size = formatSize(maxFileSize);
toast(std.host, `You can only upload files less than ${size}`);
}
@@ -9,7 +9,7 @@ import {
ThemeProvider,
ToolbarRegistryIdentifier,
} from '@blocksuite/affine-shared/services';
import { humanFileSize } from '@blocksuite/affine-shared/utils';
import { formatSize } from '@blocksuite/affine-shared/utils';
import { IS_MOBILE } from '@blocksuite/global/env';
import { BrokenImageIcon, ImageIcon } from '@blocksuite/icons/lit';
import { BlockSelection } from '@blocksuite/std';
@@ -142,7 +142,7 @@ export class ImageBlockComponent extends CaptionedBlockComponent<ImageBlockModel
errorIcon: BrokenImageIcon(),
icon: ImageIcon(),
title: 'Image',
description: humanFileSize(size),
description: formatSize(size),
});
return html`
@@ -8,7 +8,7 @@ import {
} from '@blocksuite/affine-model';
import { ThemeProvider } from '@blocksuite/affine-shared/services';
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { humanFileSize } from '@blocksuite/affine-shared/utils';
import { formatSize } from '@blocksuite/affine-shared/utils';
import { BrokenImageIcon, ImageIcon } from '@blocksuite/icons/lit';
import { GfxBlockComponent } from '@blocksuite/std';
import { GfxViewInteractionExtension } from '@blocksuite/std/gfx';
@@ -128,7 +128,7 @@ export class ImageEdgelessBlockComponent extends GfxBlockComponent<ImageBlockMod
errorIcon: BrokenImageIcon(),
icon: ImageIcon(),
title: 'Image',
description: humanFileSize(size),
description: formatSize(size),
});
return html`
+2 -2
View File
@@ -11,8 +11,8 @@ import {
NativeClipboardProvider,
} from '@blocksuite/affine-shared/services';
import {
formatSize,
getBlockProps,
humanFileSize,
isInsidePageEditor,
readImageSize,
transformModel,
@@ -241,7 +241,7 @@ function hasExceeded(
const exceeded = files.some(file => file.size > maxFileSize);
if (exceeded) {
const size = humanFileSize(maxFileSize, true, 0);
const size = formatSize(maxFileSize);
toast(std.host, `You can only upload files less than ${size}`);
}
@@ -20,7 +20,7 @@ export type StateKind =
export type StateInfo = {
icon: TemplateResult;
title?: string;
description?: string;
description?: string | null;
};
export type ResolvedStateInfoPart = {
+2
View File
@@ -22,6 +22,7 @@
"@types/hast": "^3.0.4",
"@types/lodash-es": "^4.17.12",
"@types/mdast": "^4.0.4",
"bytes": "^3.1.2",
"dompurify": "^3.2.4",
"fractional-indexing": "^3.2.0",
"lit": "^3.2.0",
@@ -70,6 +71,7 @@
"!dist/__tests__"
],
"devDependencies": {
"@types/bytes": "^3.1.5",
"vitest": "3.1.3"
},
"version": "0.21.0"
@@ -25,3 +25,4 @@ export * from './title';
export * from './url';
export * from './virtual-padding';
export * from './zod-schema';
export { default as formatSize } from 'bytes';
@@ -7,39 +7,3 @@ export function rangeWrap(n: number, min: number, max: number) {
n = (n - min + max) % max;
return min + (Number.isNaN(n) ? 0 : n);
}
/**
* Format bytes as human-readable text.
*
* @param bytes Number of bytes.
* @param si True to use metric (SI) units, aka powers of 1000. False to use
* binary (IEC), aka powers of 1024.
* @param dp Number of decimal places to display.
*
* @return Formatted string.
*
* Credit: https://stackoverflow.com/questions/10420352/converting-file-size-in-bytes-to-human-readable-string
*/
export function humanFileSize(bytes: number, si = true, dp = 1) {
const thresh = si ? 1000 : 1024;
if (Math.abs(bytes) < thresh) {
return bytes + ' bytes';
}
const units = si
? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
let u = -1;
const r = 10 ** dp;
do {
bytes /= thresh;
++u;
} while (
Math.round(Math.abs(bytes) * r) / r >= thresh &&
u < units.length - 1
);
return bytes.toFixed(dp) + ' ' + units[u];
}
@@ -1,7 +1,7 @@
import { getAttachmentFileIcon } from '@blocksuite/affine/components/icons';
import { SignalWatcher, WithDisposable } from '@blocksuite/affine/global/lit';
import type { AttachmentBlockModel } from '@blocksuite/affine-model';
import { humanFileSize } from '@blocksuite/affine-shared/utils';
import { formatSize } from '@blocksuite/affine-shared/utils';
import {
ArrowDownBigIcon,
ArrowUpBigIcon,
@@ -18,7 +18,7 @@ const DPI = window.devicePixelRatio;
type FileInfo = {
name: string;
size: string;
size: string | null;
isPDF: boolean;
icon: TemplateResult;
};
@@ -161,7 +161,7 @@ export class AttachmentViewerPanel extends SignalWatcher(
name,
icon,
isPDF,
size: humanFileSize(size),
size: formatSize(size),
};
if (!isPDF) return;
+2 -2
View File
@@ -143,7 +143,7 @@ test('can insert attachment from slash menu', async ({ page }, testInfo) => {
await waitLoading();
expect(await getName()).toBe(FILE_NAME);
expect(await getSize()).toBe('45.8 kB');
expect(await getSize()).toBe('44.73KB');
expect(await getPageSnapshot(page, true)).toMatchSnapshot(
`${testInfo.title}.json`
@@ -285,7 +285,7 @@ test(`support dragging attachment block directly`, async ({
await waitLoading();
expect(await getName()).toBe(FILE_NAME);
expect(await getSize()).toBe('45.8 kB');
expect(await getSize()).toBe('44.73KB');
expect(await getPageSnapshot(page, true)).toMatchSnapshot(
`${testInfo.title}_1.json`
+2
View File
@@ -3703,9 +3703,11 @@ __metadata:
"@lit/context": "npm:^1.1.2"
"@preact/signals-core": "npm:^1.8.0"
"@toeverything/theme": "npm:^1.1.14"
"@types/bytes": "npm:^3.1.5"
"@types/hast": "npm:^3.0.4"
"@types/lodash-es": "npm:^4.17.12"
"@types/mdast": "npm:^4.0.4"
bytes: "npm:^3.1.2"
dompurify: "npm:^3.2.4"
fractional-indexing: "npm:^3.2.0"
lit: "npm:^3.2.0"