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
@@ -64,6 +64,11 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
return this.resourceController.blobUrl$.value;
}
get filetype() {
const name = this.model.props.name$.value;
return name.split('.').pop() ?? '';
}
protected containerStyleMap = styleMap({
position: 'relative',
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`
<button
class="affine-attachment-content-button"
@click=${(event: MouseEvent) => {
event.stopPropagation();
this.refreshData();
run().catch(console.error);
{
const mode =
@@ -230,21 +245,28 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
segment,
page: `${segment} editor`,
module: 'attachment',
control: 'reload',
control: label,
category: 'card',
type: this.model.props.name.split('.').pop() ?? '',
type: this.filetype,
});
}
}}
>
${ResetIcon()} Reload
${ResetIcon()} ${label}
</button>
`;
};
protected renderWithHorizontal(
classInfo: ClassInfo,
{ icon, title, description, kind, state }: AttachmentResolvedStateInfo
{
icon,
title,
description,
kind,
state,
needUpload,
}: AttachmentResolvedStateInfo
) {
return html`
<div class=${classMap(classInfo)}>
@@ -261,7 +283,7 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
${description}
</div>
${choose(state, [
['error', this.renderReloadButton],
['error', () => this.renderNormalButton(needUpload)],
['error:oversize', this.renderUpgradeButton],
])}
</div>
@@ -274,7 +296,14 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
protected renderWithVertical(
classInfo: ClassInfo,
{ icon, title, description, kind, state }: AttachmentResolvedStateInfo
{
icon,
title,
description,
kind,
state,
needUpload,
}: AttachmentResolvedStateInfo
) {
return html`
<div class=${classMap(classInfo)}>
@@ -294,7 +323,7 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
<div class="affine-attachment-banner">
${kind}
${choose(state, [
['error', this.renderReloadButton],
['error', () => this.renderNormalButton(needUpload)],
['error:oversize', this.renderUpgradeButton],
])}
</div>
@@ -305,7 +334,7 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
protected resolvedState$ = computed<AttachmentResolvedStateInfo>(() => {
const size = this.model.props.size;
const name = this.model.props.name$.value;
const kind = getAttachmentFileIcon(name.split('.').pop() ?? '');
const kind = getAttachmentFileIcon(this.filetype);
const resolvedState = this.resourceController.resolveStateWith({
loadingIcon: LoadingIcon(),
@@ -359,11 +388,16 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
const message = resolvedState.description;
if (!message) return null;
const needUpload = resolvedState.needUpload;
const action = () =>
needUpload ? this.resourceController.upload() : this.reload();
return html`
<affine-resource-status
class="affine-attachment-embed-status"
.message=${message}
.reload=${() => this.reload()}
.needUpload=${needUpload}
.action=${action}
></affine-resource-status>
`;
})}
@@ -372,10 +406,10 @@ export class AttachmentBlockComponent extends CaptionedBlockComponent<Attachment
private readonly _renderCitation = () => {
const { name, footnoteIdentifier } = this.model.props;
const fileType = name.split('.').pop() ?? '';
const fileTypeIcon = getAttachmentFileIcon(fileType);
const icon = getAttachmentFileIcon(this.filetype);
return html`<affine-citation-card
.icon=${fileTypeIcon}
.icon=${icon}
.citationTitle=${name}
.citationIdentifier=${footnoteIdentifier}
.active=${this.selected$.value}
@@ -91,6 +91,7 @@ export const styles = css`
font-size: var(--affine-font-xs);
font-style: normal;
font-weight: 500;
text-transform: capitalize;
line-height: 20px;
svg {
@@ -359,7 +359,9 @@ export class ImageBlockPageComponent extends SignalWatcher(
? ImageSelectedRect(this._doc.readonly)
: 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`
<div class="resizable-img" style=${styleMap(imageSize)}>
@@ -367,8 +369,8 @@ export class ImageBlockPageComponent extends SignalWatcher(
class="drag-target"
draggable="false"
loading="lazy"
src=${this.block.blobUrl}
alt=${this.block.model.props.caption$.value ?? 'Image'}
src=${blobUrl}
alt=${caption}
@error=${this._handleError}
/>
@@ -377,12 +379,16 @@ export class ImageBlockPageComponent extends SignalWatcher(
${when(loading, () => html`<div class="loading">${icon}</div>`)}
${when(
error && description,
Boolean(error && description),
() =>
html`<affine-resource-status
class="affine-image-status"
.message=${description}
.reload=${() => this.block.refreshData()}
.needUpload=${needUpload}
.action=${() =>
needUpload
? this.block.resourceController.upload()
: this.block.refreshData()}
></affine-resource-status>`
)}
`;
@@ -137,6 +137,8 @@ export class ImageEdgelessBlockComponent extends GfxBlockComponent<ImageBlockMod
description: formatSize(size),
});
const { loading, icon, description, error, needUpload } = resovledState;
return html`
<div class="affine-image-container" style=${containerStyleMap}>
${when(
@@ -152,17 +154,18 @@ export class ImageEdgelessBlockComponent extends GfxBlockComponent<ImageBlockMod
@error=${this._handleError}
/>
</div>
${when(loading, () => html`<div class="loading">${icon}</div>`)}
${when(
resovledState.loading,
() => html`<div class="loading">${resovledState.icon}</div>`
)}
${when(
resovledState.error && resovledState.description,
Boolean(error && description),
() =>
html`<affine-resource-status
class="affine-image-status"
.message=${resovledState.description}
.reload=${() => this.refreshData()}
.message=${description}
.needUpload=${needUpload}
.action=${() =>
needUpload
? this.resourceController.upload()
: this.refreshData()}
></affine-resource-status>`
)}
`,
@@ -28,6 +28,7 @@ export type ResolvedStateInfoPart = {
error: boolean;
state: StateKind;
url: string | null;
needUpload: boolean;
};
export type ResolvedStateInfo = StateInfo & ResolvedStateInfoPart;
@@ -41,6 +42,7 @@ export class ResourceController implements Disposable {
readonly resolvedState$ = computed<ResolvedStateInfoPart>(() => {
const url = this.blobUrl$.value;
const {
needUpload = false,
uploading = false,
downloading = false,
overSize = false,
@@ -57,7 +59,13 @@ export class ResourceController implements Disposable {
const loading = state === 'uploading' || state === 'loading';
return { error: hasError, loading, state, url };
return {
error: hasError,
needUpload,
loading,
state,
url,
};
});
private engine?: BlobEngine;
@@ -92,7 +100,8 @@ export class ResourceController implements Disposable {
errorIcon?: TemplateResult;
} & StateInfo
): 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;
@@ -104,11 +113,11 @@ export class ResourceController implements Disposable {
title,
description,
url,
needUpload,
};
if (loading) {
result.icon = loadingIcon ?? icon;
result.title = state === 'uploading' ? 'Uploading...' : 'Loading...';
} else if (error) {
result.icon = errorIcon ?? icon;
result.description = this.state$.value.errorMessage ?? description;
@@ -130,13 +139,15 @@ export class ResourceController implements Disposable {
if (!blobState$) return;
const subscription = blobState$.subscribe(state => {
let { uploading, downloading } = state;
if (state.overSize || state.errorMessage) {
let { uploading, downloading, errorMessage } = state;
if (state.overSize) {
uploading = false;
downloading = false;
} else if ((uploading || downloading) && errorMessage) {
errorMessage = null;
}
this.updateState({ ...state, uploading, downloading });
this.updateState({ ...state, uploading, downloading, errorMessage });
});
return () => subscription.unsubscribe();
@@ -178,6 +189,9 @@ export class ResourceController implements Disposable {
}
async refreshUrlWith(type?: string) {
// Resets the state.
this.state$.value = {};
const url = await this.createUrlWith(type);
if (!url) return;
@@ -191,6 +205,21 @@ export class ResourceController implements Disposable {
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() {
const url = this.blobUrl$.peek();
if (!url) return;
@@ -2,7 +2,7 @@ import {
fontBaseStyle,
panelBaseColorsStyle,
} from '@blocksuite/affine-shared/styles';
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { unsafeCSSVar, unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import {
createButtonPopper,
stopPropagation,
@@ -15,7 +15,8 @@ import { property, query } from 'lit/decorators.js';
@requiredProperties({
message: PropTypes.string,
reload: PropTypes.instanceOf(Function),
needUpload: PropTypes.boolean,
action: PropTypes.instanceOf(Function),
})
export class ResourceStatus extends WithDisposable(LitElement) {
static override styles = css`
@@ -32,7 +33,7 @@ export class ResourceStatus extends WithDisposable(LitElement) {
cursor: pointer;
color: ${unsafeCSSVarV2('button/pureWhiteText')};
background: ${unsafeCSSVarV2('status/error')};
box-shadow: var(--affine-overlay-shadow);
box-shadow: ${unsafeCSSVar('overlayShadow')};
}
${panelBaseColorsStyle('.popper')}
@@ -43,28 +44,36 @@ export class ResourceStatus extends WithDisposable(LitElement) {
padding: 8px;
border-radius: 8px;
width: 260px;
font-size: var(--affine-font-sm);
font-style: normal;
font-weight: 400;
line-height: 22px;
font-size: ${unsafeCSSVar('fontSm')};
&[data-show] {
display: flex;
flex-direction: column;
gap: 8px;
gap: 4px;
}
}
.header {
font-weight: 500;
}
.content {
font-feature-settings:
'liga' off,
'clig' off;
color: ${unsafeCSSVarV2('text/primary')};
}
.footer {
display: flex;
justify-content: flex-end;
margin-top: 4px;
}
button.reload {
button.action {
display: flex;
align-items: center;
padding: 2px 12px;
@@ -102,23 +111,35 @@ export class ResourceStatus extends WithDisposable(LitElement) {
this._popper?.toggle();
});
this.disposables.addFromEvent(
this._reloadButton,
this._actionButton,
'click',
(_: MouseEvent) => {
this._popper?.hide();
this.reload();
this.action();
}
);
this.disposables.add(() => this._popper?.dispose());
}
override render() {
const { message, needUpload } = this;
const { type, label } = needUpload
? {
type: 'Upload',
label: 'Retry',
}
: {
type: 'Download',
label: 'Reload',
};
return html`
<button class="status">${InformationIcon()}</button>
<div class="popper">
<div class="content">${this.message}</div>
<div class="header">${type} failed</div>
<div class="content">${message}</div>
<div class="footer">
<button class="reload">Reload</button>
<button class="action">${label}</button>
</div>
</div>
`;
@@ -130,12 +151,15 @@ export class ResourceStatus extends WithDisposable(LitElement) {
@query('button.status')
private accessor _trigger!: HTMLButtonElement;
@query('button.reload')
private accessor _reloadButton!: HTMLButtonElement;
@query('button.action')
private accessor _actionButton!: HTMLButtonElement;
@property({ attribute: false })
accessor message!: string;
@property({ attribute: false })
accessor reload!: () => void;
accessor needUpload!: boolean;
@property({ attribute: false })
accessor action!: () => void;
}
@@ -65,7 +65,7 @@ export interface AttachmentReloadedEvent extends TelemetryEvent {
page: 'doc editor' | 'whiteboard editor';
segment: 'doc' | 'whiteboard';
module: 'attachment';
control: 'reload';
control: 'reload' | 'retry';
category: 'card' | 'embed';
type: string; // file type
}
@@ -108,6 +108,10 @@ export class BlobEngine {
return this.main.blobState$?.(key) ?? null;
}
upload(key: string) {
return this.main.upload?.(key) ?? null;
}
start() {
if (this._abort) {
return;
@@ -5,6 +5,8 @@ export interface BlobState {
downloading: boolean;
errorMessage?: string | null;
overSize: boolean;
needUpload: boolean;
needDownload: boolean;
}
export interface BlobSource {
@@ -16,4 +18,6 @@ export interface BlobSource {
list: () => Promise<string[]>;
// This state is only available when uploading to the server or downloading from the server.
blobState$?: (key: string) => Observable<BlobState> | null;
// Re-upload to the server.
upload?: (key: string) => Promise<boolean>;
}
@@ -112,7 +112,13 @@ export class MockServerBlobSource implements BlobSource {
}
function defaultState(): BlobState {
return { uploading: false, downloading: false, overSize: false };
return {
uploading: false,
downloading: false,
overSize: false,
needDownload: false,
needUpload: false,
};
}
function nextState(
@@ -58,6 +58,7 @@ export class Workspace extends Entity {
},
/* eslint-disable rxjs/finnish */
blobState$: key => this.engine.blob.blobState$(key),
upload: key => this.engine.blob.upload(key),
name: 'blob',
readonly: false,
},