-
Notifications
You must be signed in to change notification settings - Fork 34
Support editing comments and replies on the frontend #247
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a375bf0
feat: support editing comments and replies on the frontend
ruibaby e68dda8
fix: address review findings in comment editing
ruibaby ab186fb
fix: preserve plain-text layout and improve edit dirty check
ruibaby d637f87
Merge remote-tracking branch 'origin/main' into feat/edit-comment-con…
ruibaby d43f286
Merge remote-tracking branch 'origin/main' into feat/edit-comment-con…
ruibaby File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } 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)); | ||
| } | ||
|
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, | ||
|
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} | ||
|
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; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.