fix(editor): improve status display of attachments and images (#12573)

Closes: [BS-3564](https://linear.app/affine-design/issue/BS-3564/ui-embed-view-报错-ui-加-title)
Closes: [BS-3454](https://linear.app/affine-design/issue/BS-3454/点击-reload-后应该隐藏-attachment-embed-view-左下角-status(待新状态))

<img width="807" alt="Screenshot 2025-05-28 at 17 23 26" src="https://github.com/user-attachments/assets/9ecc29f8-73c6-4441-bc38-dfe9bd876542" />

<img width="820" alt="Screenshot 2025-05-28 at 17 45 37" src="https://github.com/user-attachments/assets/68e6db17-a814-4df4-a9fa-067ca03dec30" />

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

## Summary by CodeRabbit

- **New Features**
  - Added support for retrying failed uploads of attachments and images, allowing users to re-upload files directly from the error status interface.
  - The error status dialog now dynamically displays "Retry" for upload failures and "Reload" for download failures, with appropriate actions for each.
- **Enhancements**
  - Improved clarity and consistency in file type display and icon usage for attachments and citations.
  - Button labels in the attachment interface now have capitalized text for better readability.
- **Bug Fixes**
  - Streamlined error handling and status updates for attachment and image uploads/downloads, reducing redundant UI elements.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
fundon
2025-05-29 02:18:50 +00:00
parent de00040389
commit 5590cdd8f1
11 changed files with 159 additions and 47 deletions

View File

@@ -64,6 +64,11 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
return this.resourceController.blobUrl$.value; return this.resourceController.blobUrl$.value;
} }
get filetype() {
const name = this.model.props.name$.value;
return name.split('.').pop() ?? '';
}
protected containerStyleMap = styleMap({ protected containerStyleMap = styleMap({
position: 'relative', position: 'relative',
width: '100%', width: '100%',
@@ -212,13 +217,23 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
); );
}; };
protected renderReloadButton = () => { protected renderNormalButton = (needUpload: boolean) => {
const label = needUpload ? 'retry' : 'reload';
const run = async () => {
if (needUpload) {
await this.resourceController.upload();
return;
}
this.refreshData();
};
return html` return html`
<button <button
class="affine-attachment-content-button" class="affine-attachment-content-button"
@click=${(event: MouseEvent) => { @click=${(event: MouseEvent) => {
event.stopPropagation(); event.stopPropagation();
this.refreshData(); run().catch(console.error);
{ {
const mode = const mode =
@@ -230,21 +245,28 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
segment, segment,
page: `${segment} editor`, page: `${segment} editor`,
module: 'attachment', module: 'attachment',
control: 'reload', control: label,
category: 'card', category: 'card',
type: this.model.props.name.split('.').pop() ?? '', type: this.filetype,
}); });
} }
}} }}
> >
${ResetIcon()} Reload ${ResetIcon()} ${label}
</button> </button>
`; `;
}; };
protected renderWithHorizontal( protected renderWithHorizontal(
classInfo: ClassInfo, classInfo: ClassInfo,
{ icon, title, description, kind, state }: AttachmentResolvedStateInfo {
icon,
title,
description,
kind,
state,
needUpload,
}: AttachmentResolvedStateInfo
) { ) {
return html` return html`
<div class=${classMap(classInfo)}> <div class=${classMap(classInfo)}>
@@ -261,7 +283,7 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
${description} ${description}
</div> </div>
${choose(state, [ ${choose(state, [
['error', this.renderReloadButton], ['error', () => this.renderNormalButton(needUpload)],
['error:oversize', this.renderUpgradeButton], ['error:oversize', this.renderUpgradeButton],
])} ])}
</div> </div>
@@ -274,7 +296,14 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
protected renderWithVertical( protected renderWithVertical(
classInfo: ClassInfo, classInfo: ClassInfo,
{ icon, title, description, kind, state }: AttachmentResolvedStateInfo {
icon,
title,
description,
kind,
state,
needUpload,
}: AttachmentResolvedStateInfo
) { ) {
return html` return html`
<div class=${classMap(classInfo)}> <div class=${classMap(classInfo)}>
@@ -294,7 +323,7 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
<div class="affine-attachment-banner"> <div class="affine-attachment-banner">
${kind} ${kind}
${choose(state, [ ${choose(state, [
['error', this.renderReloadButton], ['error', () => this.renderNormalButton(needUpload)],
['error:oversize', this.renderUpgradeButton], ['error:oversize', this.renderUpgradeButton],
])} ])}
</div> </div>
@@ -305,7 +334,7 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
protected resolvedState$ = computed<AttachmentResolvedStateInfo>(() => { protected resolvedState$ = computed<AttachmentResolvedStateInfo>(() => {
const size = this.model.props.size; const size = this.model.props.size;
const name = this.model.props.name$.value; const name = this.model.props.name$.value;
const kind = getAttachmentFileIcon(name.split('.').pop() ?? ''); const kind = getAttachmentFileIcon(this.filetype);
const resolvedState = this.resourceController.resolveStateWith({ const resolvedState = this.resourceController.resolveStateWith({
loadingIcon: LoadingIcon(), loadingIcon: LoadingIcon(),
@@ -359,11 +388,16 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
const message = resolvedState.description; const message = resolvedState.description;
if (!message) return null; if (!message) return null;
const needUpload = resolvedState.needUpload;
const action = () =>
needUpload ? this.resourceController.upload() : this.reload();
return html` return html`
<affine-resource-status <affine-resource-status
class="affine-attachment-embed-status" class="affine-attachment-embed-status"
.message=${message} .message=${message}
.reload=${() => this.reload()} .needUpload=${needUpload}
.action=${action}
></affine-resource-status> ></affine-resource-status>
`; `;
})} })}
@@ -372,10 +406,10 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
private readonly _renderCitation = () => { private readonly _renderCitation = () => {
const { name, footnoteIdentifier } = this.model.props; const { name, footnoteIdentifier } = this.model.props;
const fileType = name.split('.').pop() ?? ''; const icon = getAttachmentFileIcon(this.filetype);
const fileTypeIcon = getAttachmentFileIcon(fileType);
return html`<affine-citation-card return html`<affine-citation-card
.icon=${fileTypeIcon} .icon=${icon}
.citationTitle=${name} .citationTitle=${name}
.citationIdentifier=${footnoteIdentifier} .citationIdentifier=${footnoteIdentifier}
.active=${this.selected$.value} .active=${this.selected$.value}

View File

@@ -91,6 +91,7 @@ export const styles = css`
font-size: var(--affine-font-xs); font-size: var(--affine-font-xs);
font-style: normal; font-style: normal;
font-weight: 500; font-weight: 500;
text-transform: capitalize;
line-height: 20px; line-height: 20px;
svg { svg {

View File

@@ -359,7 +359,9 @@ export class ImageBlockPageComponent extends SignalWatcher(
? ImageSelectedRect(this._doc.readonly) ? ImageSelectedRect(this._doc.readonly)
: null; : null;
const { loading, error, icon, description } = this.state; const blobUrl = this.block.blobUrl;
const caption = this.block.model.props.caption$.value ?? 'Image';
const { loading, error, icon, description, needUpload } = this.state;
return html` return html`
<div class="resizable-img" style=${styleMap(imageSize)}> <div class="resizable-img" style=${styleMap(imageSize)}>
@@ -367,8 +369,8 @@ export class ImageBlockPageComponent extends SignalWatcher(
class="drag-target" class="drag-target"
draggable="false" draggable="false"
loading="lazy" loading="lazy"
src=${this.block.blobUrl} src=${blobUrl}
alt=${this.block.model.props.caption$.value ?? 'Image'} alt=${caption}
@error=${this._handleError} @error=${this._handleError}
/> />
@@ -377,12 +379,16 @@ export class ImageBlockPageComponent extends SignalWatcher(
${when(loading, () => html`<div class="loading">${icon}</div>`)} ${when(loading, () => html`<div class="loading">${icon}</div>`)}
${when( ${when(
error && description, Boolean(error && description),
() => () =>
html`<affine-resource-status html`<affine-resource-status
class="affine-image-status" class="affine-image-status"
.message=${description} .message=${description}
.reload=${() => this.block.refreshData()} .needUpload=${needUpload}
.action=${() =>
needUpload
? this.block.resourceController.upload()
: this.block.refreshData()}
></affine-resource-status>` ></affine-resource-status>`
)} )}
`; `;

View File

@@ -137,6 +137,8 @@ export class ImageEdgelessBlockComponent extends GfxBlockComponent<ImageBlockMod
description: formatSize(size), description: formatSize(size),
}); });
const { loading, icon, description, error, needUpload } = resovledState;
return html` return html`
<div class="affine-image-container" style=${containerStyleMap}> <div class="affine-image-container" style=${containerStyleMap}>
${when( ${when(
@@ -152,17 +154,18 @@ export class ImageEdgelessBlockComponent extends GfxBlockComponent<ImageBlockMod
@error=${this._handleError} @error=${this._handleError}
/> />
</div> </div>
${when(loading, () => html`<div class="loading">${icon}</div>`)}
${when( ${when(
resovledState.loading, Boolean(error && description),
() => html`<div class="loading">${resovledState.icon}</div>`
)}
${when(
resovledState.error && resovledState.description,
() => () =>
html`<affine-resource-status html`<affine-resource-status
class="affine-image-status" class="affine-image-status"
.message=${resovledState.description} .message=${description}
.reload=${() => this.refreshData()} .needUpload=${needUpload}
.action=${() =>
needUpload
? this.resourceController.upload()
: this.refreshData()}
></affine-resource-status>` ></affine-resource-status>`
)} )}
`, `,

View File

@@ -28,6 +28,7 @@ export type ResolvedStateInfoPart = {
error: boolean; error: boolean;
state: StateKind; state: StateKind;
url: string | null; url: string | null;
needUpload: boolean;
}; };
export type ResolvedStateInfo = StateInfo & ResolvedStateInfoPart; export type ResolvedStateInfo = StateInfo & ResolvedStateInfoPart;
@@ -41,6 +42,7 @@ export class ResourceController implements Disposable {
readonly resolvedState$ = computed<ResolvedStateInfoPart>(() => { readonly resolvedState$ = computed<ResolvedStateInfoPart>(() => {
const url = this.blobUrl$.value; const url = this.blobUrl$.value;
const { const {
needUpload = false,
uploading = false, uploading = false,
downloading = false, downloading = false,
overSize = false, overSize = false,
@@ -57,7 +59,13 @@ export class ResourceController implements Disposable {
const loading = state === 'uploading' || state === 'loading'; const loading = state === 'uploading' || state === 'loading';
return { error: hasError, loading, state, url }; return {
error: hasError,
needUpload,
loading,
state,
url,
};
}); });
private engine?: BlobEngine; private engine?: BlobEngine;
@@ -92,7 +100,8 @@ export class ResourceController implements Disposable {
errorIcon?: TemplateResult; errorIcon?: TemplateResult;
} & StateInfo } & StateInfo
): ResolvedStateInfo { ): ResolvedStateInfo {
const { error, loading, state, url } = this.resolvedState$.value; const { error, loading, state, url, needUpload } =
this.resolvedState$.value;
const { icon, title, description, loadingIcon, errorIcon } = info; const { icon, title, description, loadingIcon, errorIcon } = info;
@@ -104,11 +113,11 @@ export class ResourceController implements Disposable {
title, title,
description, description,
url, url,
needUpload,
}; };
if (loading) { if (loading) {
result.icon = loadingIcon ?? icon; result.icon = loadingIcon ?? icon;
result.title = state === 'uploading' ? 'Uploading...' : 'Loading...';
} else if (error) { } else if (error) {
result.icon = errorIcon ?? icon; result.icon = errorIcon ?? icon;
result.description = this.state$.value.errorMessage ?? description; result.description = this.state$.value.errorMessage ?? description;
@@ -130,13 +139,15 @@ export class ResourceController implements Disposable {
if (!blobState$) return; if (!blobState$) return;
const subscription = blobState$.subscribe(state => { const subscription = blobState$.subscribe(state => {
let { uploading, downloading } = state; let { uploading, downloading, errorMessage } = state;
if (state.overSize || state.errorMessage) { if (state.overSize) {
uploading = false; uploading = false;
downloading = false; downloading = false;
} else if ((uploading || downloading) && errorMessage) {
errorMessage = null;
} }
this.updateState({ ...state, uploading, downloading }); this.updateState({ ...state, uploading, downloading, errorMessage });
}); });
return () => subscription.unsubscribe(); return () => subscription.unsubscribe();
@@ -178,6 +189,9 @@ export class ResourceController implements Disposable {
} }
async refreshUrlWith(type?: string) { async refreshUrlWith(type?: string) {
// Resets the state.
this.state$.value = {};
const url = await this.createUrlWith(type); const url = await this.createUrlWith(type);
if (!url) return; if (!url) return;
@@ -191,6 +205,21 @@ export class ResourceController implements Disposable {
URL.revokeObjectURL(prevUrl); URL.revokeObjectURL(prevUrl);
} }
// Re-upload to the server.
async upload() {
const blobId = this.blobId$.peek();
if (!blobId) return;
const state = this.state$.peek();
if (!state.needUpload) return;
if (state.uploading) return;
// Resets the state.
this.state$.value = {};
return await this.engine?.upload(blobId);
}
dispose() { dispose() {
const url = this.blobUrl$.peek(); const url = this.blobUrl$.peek();
if (!url) return; if (!url) return;

View File

@@ -2,7 +2,7 @@ import {
fontBaseStyle, fontBaseStyle,
panelBaseColorsStyle, panelBaseColorsStyle,
} from '@blocksuite/affine-shared/styles'; } from '@blocksuite/affine-shared/styles';
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme'; import { unsafeCSSVar, unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { import {
createButtonPopper, createButtonPopper,
stopPropagation, stopPropagation,
@@ -15,7 +15,8 @@ import { property, query } from 'lit/decorators.js';
@requiredProperties({ @requiredProperties({
message: PropTypes.string, message: PropTypes.string,
reload: PropTypes.instanceOf(Function), needUpload: PropTypes.boolean,
action: PropTypes.instanceOf(Function),
}) })
export class ResourceStatus extends WithDisposable(LitElement) { export class ResourceStatus extends WithDisposable(LitElement) {
static override styles = css` static override styles = css`
@@ -32,7 +33,7 @@ export class ResourceStatus extends WithDisposable(LitElement) {
cursor: pointer; cursor: pointer;
color: ${unsafeCSSVarV2('button/pureWhiteText')}; color: ${unsafeCSSVarV2('button/pureWhiteText')};
background: ${unsafeCSSVarV2('status/error')}; background: ${unsafeCSSVarV2('status/error')};
box-shadow: var(--affine-overlay-shadow); box-shadow: ${unsafeCSSVar('overlayShadow')};
} }
${panelBaseColorsStyle('.popper')} ${panelBaseColorsStyle('.popper')}
@@ -43,28 +44,36 @@ export class ResourceStatus extends WithDisposable(LitElement) {
padding: 8px; padding: 8px;
border-radius: 8px; border-radius: 8px;
width: 260px; width: 260px;
font-size: var(--affine-font-sm);
font-style: normal; font-style: normal;
font-weight: 400; font-weight: 400;
line-height: 22px; line-height: 22px;
font-size: ${unsafeCSSVar('fontSm')};
&[data-show] { &[data-show] {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 8px; gap: 4px;
} }
} }
.header {
font-weight: 500;
}
.content { .content {
font-feature-settings:
'liga' off,
'clig' off;
color: ${unsafeCSSVarV2('text/primary')}; color: ${unsafeCSSVarV2('text/primary')};
} }
.footer { .footer {
display: flex; display: flex;
justify-content: flex-end; justify-content: flex-end;
margin-top: 4px;
} }
button.reload { button.action {
display: flex; display: flex;
align-items: center; align-items: center;
padding: 2px 12px; padding: 2px 12px;
@@ -102,23 +111,35 @@ export class ResourceStatus extends WithDisposable(LitElement) {
this._popper?.toggle(); this._popper?.toggle();
}); });
this.disposables.addFromEvent( this.disposables.addFromEvent(
this._reloadButton, this._actionButton,
'click', 'click',
(_: MouseEvent) => { (_: MouseEvent) => {
this._popper?.hide(); this._popper?.hide();
this.reload(); this.action();
} }
); );
this.disposables.add(() => this._popper?.dispose()); this.disposables.add(() => this._popper?.dispose());
} }
override render() { override render() {
const { message, needUpload } = this;
const { type, label } = needUpload
? {
type: 'Upload',
label: 'Retry',
}
: {
type: 'Download',
label: 'Reload',
};
return html` return html`
<button class="status">${InformationIcon()}</button> <button class="status">${InformationIcon()}</button>
<div class="popper"> <div class="popper">
<div class="content">${this.message}</div> <div class="header">${type} failed</div>
<div class="content">${message}</div>
<div class="footer"> <div class="footer">
<button class="reload">Reload</button> <button class="action">${label}</button>
</div> </div>
</div> </div>
`; `;
@@ -130,12 +151,15 @@ export class ResourceStatus extends WithDisposable(LitElement) {
@query('button.status') @query('button.status')
private accessor _trigger!: HTMLButtonElement; private accessor _trigger!: HTMLButtonElement;
@query('button.reload') @query('button.action')
private accessor _reloadButton!: HTMLButtonElement; private accessor _actionButton!: HTMLButtonElement;
@property({ attribute: false }) @property({ attribute: false })
accessor message!: string; accessor message!: string;
@property({ attribute: false }) @property({ attribute: false })
accessor reload!: () => void; accessor needUpload!: boolean;
@property({ attribute: false })
accessor action!: () => void;
} }

View File

@@ -65,7 +65,7 @@ export interface AttachmentReloadedEvent extends TelemetryEvent {
page: 'doc editor' | 'whiteboard editor'; page: 'doc editor' | 'whiteboard editor';
segment: 'doc' | 'whiteboard'; segment: 'doc' | 'whiteboard';
module: 'attachment'; module: 'attachment';
control: 'reload'; control: 'reload' | 'retry';
category: 'card' | 'embed'; category: 'card' | 'embed';
type: string; // file type type: string; // file type
} }

View File

@@ -108,6 +108,10 @@ export class BlobEngine {
return this.main.blobState$?.(key) ?? null; return this.main.blobState$?.(key) ?? null;
} }
upload(key: string) {
return this.main.upload?.(key) ?? null;
}
start() { start() {
if (this._abort) { if (this._abort) {
return; return;

View File

@@ -5,6 +5,8 @@ export interface BlobState {
downloading: boolean; downloading: boolean;
errorMessage?: string | null; errorMessage?: string | null;
overSize: boolean; overSize: boolean;
needUpload: boolean;
needDownload: boolean;
} }
export interface BlobSource { export interface BlobSource {
@@ -16,4 +18,6 @@ export interface BlobSource {
list: () => Promise<string[]>; list: () => Promise<string[]>;
// This state is only available when uploading to the server or downloading from the server. // This state is only available when uploading to the server or downloading from the server.
blobState$?: (key: string) => Observable<BlobState> | null; blobState$?: (key: string) => Observable<BlobState> | null;
// Re-upload to the server.
upload?: (key: string) => Promise<boolean>;
} }

View File

@@ -112,7 +112,13 @@ export class MockServerBlobSource implements BlobSource {
} }
function defaultState(): BlobState { function defaultState(): BlobState {
return { uploading: false, downloading: false, overSize: false }; return {
uploading: false,
downloading: false,
overSize: false,
needDownload: false,
needUpload: false,
};
} }
function nextState( function nextState(

View File

@@ -58,6 +58,7 @@ export class Workspace extends Entity {
}, },
/* eslint-disable rxjs/finnish */ /* eslint-disable rxjs/finnish */
blobState$: key => this.engine.blob.blobState$(key), blobState$: key => this.engine.blob.blobState$(key),
upload: key => this.engine.blob.upload(key),
name: 'blob', name: 'blob',
readonly: false, readonly: false,
}, },