Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion packages/comment-widget/src/base-comment-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ export class BaseCommentItem extends LitElement {
@property({ type: Boolean })
private: boolean | undefined;

@property({ type: Boolean })
editing = false;

@consume({ context: configMapDataContext })
@state()
configMapData: ConfigMapData | undefined;
Expand Down Expand Up @@ -107,7 +110,12 @@ export class BaseCommentItem extends LitElement {
${when(!this.approved, () => html`<div class="item-meta-info text-xs text-text-3">${msg('Reviewing')}</div>`)}
</div>

<div class="item-content mt-2.5 space-y-2.5"><slot name="pre-content"></slot><comment-content .content=${this.content}></comment-content></div>
<div class="item-content mt-2.5 space-y-2.5 ${this.editing ? 'item-content-editing' : ''}"><slot name="pre-content"></slot>${when(
this.editing,
() => html`<slot name="content-edit"></slot>`,
() =>
html`<comment-content .content=${this.content}></comment-content>`
)}</div>

<div class="item-actions mt-2 flex items-center gap-3">
<slot name="action"></slot>
Expand All @@ -126,6 +134,11 @@ export class BaseCommentItem extends LitElement {
contain-intrinsic-size: auto 4em;
}

/* Paint containment would clip the focus ring of the slotted editor. */
.item-content-editing {
content-visibility: visible;
}

.animate-breath {
animation: breath 1s ease-in-out infinite;
}
Expand Down
323 changes: 323 additions & 0 deletions packages/comment-widget/src/comment-edit-form.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,323 @@
import type { CommentVo, ReplyVo } from '@halo-dev/api-client';
import { consume } from '@lit/context';
import { msg } from '@lit/localize';
import { css, html, LitElement } from 'lit';
import { property, state } from 'lit/decorators.js';
import { createRef, type Ref, ref } from 'lit/directives/ref.js';
import { when } from 'lit/directives/when.js';
import { FetchError } from 'ofetch';
import type { CommentEditor } from './comment-editor';
import { baseUrlContext, configMapDataContext, toastContext } from './context';
import type { ToastManager } from './lit-toast';
import baseStyles from './styles/base';
import type { ConfigMapData } from './types';
import {
fetchCommentContent,
updateCommentContent,
} from './utils/comment-management';
import './comment-editor';
import './loading-block';
import './icons/icon-loading';
import { cleanHtml, toEditorContent } from './utils/html';

export class CommentEditForm extends LitElement {
@consume({ context: baseUrlContext })
@state()
baseUrl = '';

@consume({ context: configMapDataContext })
@state()
configMapData: ConfigMapData | undefined;

@consume({ context: toastContext, subscribe: true })
@state()
toastManager: ToastManager | undefined;

@property({ attribute: false })
target: CommentVo | ReplyVo | undefined;

@property()
resource: 'comments' | 'replies' = 'comments';

@state()
private loading = true;

@state()
private deleted = false;

@state()
private loadFailed = false;

@state()
private version: number | undefined;

@state()
private content = '';

@state()
private saving = false;

@state()
private errorMessage = '';

private initialRaw = '';

private editorContent = '';

private baseline = '';

private editorRef: Ref<CommentEditor> = createRef<CommentEditor>();

override connectedCallback(): void {
super.connectedCallback();
this.addEventListener('keydown', this.onKeydown);
void this.loadLatest();
}

override disconnectedCallback(): void {
this.removeEventListener('keydown', this.onKeydown);
super.disconnectedCallback();
}

private onKeydown = (event: KeyboardEvent) => {
if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
event.preventDefault();
void this.handleSave();
}
};

private async loadLatest() {
if (!this.target) {
this.loading = false;
this.loadFailed = true;
return;
}
this.loading = true;
this.loadFailed = false;
try {
const latest = await fetchCommentContent(
this.baseUrl,
this.resource,
this.target.metadata.name
);
if (latest.metadata.deletionTimestamp) {
this.deleted = true;
return;
}
this.version = latest.metadata.version ?? undefined;
this.initialRaw = latest.spec.raw || '';
this.editorContent = toEditorContent(this.initialRaw);
this.content = this.initialRaw;
} catch {
this.loadFailed = true;
Comment thread
ruibaby marked this conversation as resolved.
} finally {
this.loading = false;
}
if (!this.loadFailed && !this.deleted) {
void this.focusEditor();
}
}

private async focusEditor() {
await this.updateComplete;
const editor = this.editorRef.value;
if (!editor) {
return;
}
// The editor is created asynchronously after its dynamic imports resolve.
for (let i = 0; i < 100 && !editor.editor && this.isConnected; i++) {
await new Promise((resolve) => setTimeout(resolve, 50));
}
Comment thread
ruibaby marked this conversation as resolved.
if (this.isConnected && editor.editor) {
// The editor normalizes the initial content (e.g. wrapping plain text
// in a paragraph), so the serialized HTML differs from the raw source.
// Record it as the baseline for the dirty check to avoid treating an
// unchanged or undone document as modified.
this.baseline = cleanHtml(editor.editor.getHTML());
if (this.content === this.initialRaw) {
this.content = this.baseline;
}
editor.setFocus();
}
}

private onEditorUpdate(
event: CustomEvent<{ content: string; characterCount: number }>
) {
this.content = event.detail.content;
this.errorMessage = '';
}

private get hasContent() {
const body = new DOMParser().parseFromString(
this.content,
'text/html'
).body;
return (
!!body.textContent?.replaceAll('\u00a0', ' ').trim() ||
Array.from(body.querySelectorAll('img[src]')).some((image) =>
image.getAttribute('src')?.trim()
)
);
}

private get dirty() {
return this.baseline !== '' && this.content !== this.baseline;
}

private get canSave() {
return (
!this.saving &&
this.version !== undefined &&
this.dirty &&
this.hasContent
);
}

private async handleSave() {
if (!this.canSave || !this.target) {
return;
}
this.saving = true;
this.errorMessage = '';
try {
await updateCommentContent(
this.baseUrl,
this.resource,
this.target.metadata.name,
{
raw: this.content,
content: this.content,
version: this.version as number,
}
);
this.toastManager?.success(msg('Comment updated successfully'));
this.dispatchEvent(
new CustomEvent('comment-managed', {
bubbles: true,
composed: true,
detail: {
action: 'edit',
restoreFocus: false,
Comment thread
ruibaby marked this conversation as resolved.
commentName:
this.resource === 'replies'
? (this.target as ReplyVo).spec.commentName
: undefined,
},
})
);
this.dispatchEvent(
new CustomEvent('edit-close', { bubbles: true, composed: true })
);
} catch (error) {
const status =
error instanceof FetchError ? error.response?.status : undefined;
this.errorMessage =
status === 409
? msg(
'This comment or reply has changed. Copy your draft, then reopen the editor to load the latest version.'
)
: status === 404
? msg(
'Could not save. The comment may have been deleted, or the current Halo version does not support editing. Your draft has been kept.'
)
: msg('Could not save. Your draft has been kept.');
this.saving = false;
}
}

private handleCancel() {
if (this.dirty && !window.confirm(msg('Discard your changes?'))) {
return;
}
this.dispatchEvent(
new CustomEvent('edit-close', { bubbles: true, composed: true })
);
}

override render() {
if (this.loading) {
return html`<loading-block></loading-block>
<div class="edit-form-actions mt-2 flex justify-end items-center gap-2">
${this.renderCancelButton()}
</div>`;
}
if (this.deleted) {
return html`<div class="edit-form-message text-sm text-text-3 py-2" role="alert">
${msg('This comment or reply has been deleted.')}
</div>
${this.renderCancelButton()}`;
}
if (this.loadFailed) {
return html`<div class="edit-form-message text-sm text-text-3 py-2" role="alert">
${msg('Failed to load the latest content. Please try again later.')}
</div>
<div class="edit-form-actions mt-2 flex justify-end items-center gap-2">
${this.renderCancelButton()}
<button
type="button"
@click=${() => void this.loadLatest()}
class="edit-form-retry outline-none focus-visible:shadow-input h-9 text-sm inline-flex items-center justify-center gap-2 bg-primary-1 text-white px-4 rounded-base hover:opacity-80 transition-[opacity,box-shadow]"
>
${msg('Retry')}
</button>
</div>`;
}
return html`
<comment-editor
${ref(this.editorRef)}
.initialContent=${this.editorContent}
Comment thread
ruibaby marked this conversation as resolved.
.disabled=${this.saving}
.enableEmoji=${this.configMapData?.editor?.enableEmoji !== false}
@update=${this.onEditorUpdate}
></comment-editor>
${when(
this.errorMessage,
() =>
html`<p role="alert" class="text-sm text-red-500 mt-2">${this.errorMessage}</p>`
)}
<div class="edit-form-actions mt-2 flex justify-end items-center gap-2">
${this.renderCancelButton()}
<button
type="button"
?disabled=${!this.canSave}
@click=${this.handleSave}
class="edit-form-submit outline-none focus-visible:shadow-input h-9 text-sm inline-flex items-center justify-center gap-2 bg-primary-1 text-white px-4 rounded-base hover:opacity-80 transition-[opacity,box-shadow] disabled:opacity-50 disabled:cursor-not-allowed"
>
${when(this.saving, () => html`<icon-loading></icon-loading>`)}
${msg('Save')}
</button>
</div>
`;
}

private renderCancelButton() {
return html`<button
type="button"
?disabled=${this.saving}
@click=${this.handleCancel}
class="edit-form-cancel outline-none focus-visible:shadow-input h-9 px-3 text-sm text-text-2 hover:text-text-1 hover:bg-muted-3 rounded-base transition-[color,background-color,box-shadow] disabled:opacity-50"
>
${msg('Cancel')}
</button>`;
}

static override styles = [
...baseStyles,
css`
:host {
display: block;
}
@unocss-placeholder;
`,
];
}

customElements.get('comment-edit-form') ||
customElements.define('comment-edit-form', CommentEditForm);

declare global {
interface HTMLElementTagNameMap {
'comment-edit-form': CommentEditForm;
}
}
Loading
Loading