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
20 changes: 19 additions & 1 deletion apps/community/src/components/content/composer-recovery.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,13 @@ export function ComposerRecovery({
const latest = useRef('')
const saved = useRef('')
const submitting = useRef(false)
const held = useRef(false)
const [recovery, setRecovery] = useState<Backup | null>(null)
const [saveState, setSaveState] = useState<SaveState>('idle')

const persist = useCallback(async () => {
const form = root.current?.closest('form')
if (form === null || form === undefined) return
if (form === null || form === undefined || held.current) return
const payload = readPayload(form, { ...scope, title: '', message: '', prefixId: null })
const next = signature(payload)
latest.current = next
Expand Down Expand Up @@ -134,6 +135,8 @@ export function ComposerRecovery({

let timer: ReturnType<typeof setTimeout> | undefined
const onInput = () => {
submitting.current = false
held.current = false
const payload = readPayload(form, { ...scope, title: '', message: '', prefixId: null })
latest.current = signature(payload)
try {
Expand All @@ -146,6 +149,12 @@ export function ComposerRecovery({
timer = setTimeout(() => void persist(), AUTOSAVE_DELAY_MS)
}
const onBlur = () => void persist()
const onPointerDown = (event: Event) => {
const target = event.target
if (target instanceof Element && target.closest('button[type="submit"]') !== null) {
held.current = true
}
}
const onSubmit = (event: SubmitEvent) => {
const submitter = event.submitter
submitting.current =
Expand All @@ -163,19 +172,28 @@ export function ComposerRecovery({

form.addEventListener('input', onInput)
form.addEventListener('blur', onBlur, true)
form.addEventListener('pointerdown', onPointerDown, true)
form.addEventListener('submit', onSubmit)
window.addEventListener('pagehide', onPageHide)
window.addEventListener('beforeunload', onBeforeUnload)
return () => {
clearTimeout(timer)
form.removeEventListener('input', onInput)
form.removeEventListener('blur', onBlur, true)
form.removeEventListener('pointerdown', onPointerDown, true)
form.removeEventListener('submit', onSubmit)
window.removeEventListener('pagehide', onPageHide)
window.removeEventListener('beforeunload', onBeforeUnload)
}
}, [persist, scope, serverUpdatedAt, storageKey])

useEffect(
() => () => {
if (submitting.current) localStorage.removeItem(storageKey)
},
[storageKey],
)

function restore(): void {
const form = root.current?.closest('form')
if (form === null || form === undefined || recovery === null) return
Expand Down
51 changes: 51 additions & 0 deletions apps/community/src/view/content-copy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { readFileSync } from 'node:fs'

import { describe, expect, it } from 'vitest'

import { editPostFormCopy, newThreadFormCopy, replyFormCopy } from './content-copy'

function keysReadFromTheCopyProp(component: string): string[] {
const source = readFileSync(
new URL(`../components/content/${component}`, import.meta.url),
'utf8',
)
const keys = new Set<string>()

for (const match of source.matchAll(/(?:format)?fromCopy\(\s*copy,\s*'([\w.-]+)'/g)) {
const key = match[1]
if (key !== undefined) keys.add(key)
}

return [...keys].sort()
}

const RECOVERY = keysReadFromTheCopyProp('composer-recovery.tsx')

const BUNDLES = [
{ name: 'replyFormCopy', copy: replyFormCopy(), components: ['reply-form.tsx'] },
{ name: 'newThreadFormCopy', copy: newThreadFormCopy(), components: ['new-thread-form.tsx'] },
{ name: 'editPostFormCopy', copy: editPostFormCopy(), components: ['edit-post-form.tsx'] },
] as const

describe('the copy a composer is handed', () => {
it('finds the keys the autosave notice reads', () => {
expect(RECOVERY).toContain('composer.autosave.saved')
expect(RECOVERY.length).toBeGreaterThan(3)
})

for (const bundle of BUNDLES) {
const wanted = [
...bundle.components.flatMap(keysReadFromTheCopyProp),
...(bundle.name === 'editPostFormCopy' ? [] : RECOVERY),
]

it.each(wanted)(`${bundle.name} carries %s`, (key) => {
expect(Object.keys(bundle.copy)).toContain(key)
})

it.each(wanted)(`${bundle.name} resolves %s to prose, not the key`, (key) => {
expect(bundle.copy[key]).not.toBe(key)
expect(bundle.copy[key] ?? '').not.toBe('')
})
}
})
17 changes: 11 additions & 6 deletions apps/community/src/view/content-copy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,20 @@ import type { Translator } from '@meith/i18n'
import { copyFor, patternCopy, splitAround } from './copy'
import { untranslated } from './time'

const RECOVERY_KEYS = [
'composer.autosave.failed',
'composer.autosave.saved',
'composer.autosave.saving',
'composer.recovery.available',
'composer.recovery.discard',
'composer.recovery.restore',
] as const

export function replyFormCopy(t: Translator = untranslated()): Readonly<Record<string, string>> {
return copyFor(
[
...RECOVERY_KEYS,
'composer.draftSaved',
'composer.autosave.failed',
'composer.autosave.saved',
'composer.autosave.saving',
'composer.recovery.available',
'composer.recovery.discard',
'composer.recovery.restore',
'composer.notifyReplies',
'composer.reply.submit',
'composer.reply.write',
Expand Down Expand Up @@ -44,6 +48,7 @@ export function newThreadFormCopy(
return {
...copyFor(
[
...RECOVERY_KEYS,
'composer.draftSaved',
'composer.notifyReplies',
'composer.newThread.subject',
Expand Down
17 changes: 17 additions & 0 deletions docs/guides/community/formatting.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,23 @@ the file still also appears in the attachment list once the post is
saved. An id you did not upload yourself never resolves to anything in
somebody else's post — typing one by hand does not work.

## Drafts

The composer saves what you are writing without being asked. A second or
so after you stop typing, and again whenever a field loses focus, it
sends the subject and the message to the board and says **Saved just
now.** underneath. One draft is kept per forum for a thread you have not
posted yet, and one per thread for a reply; reopening the composer fills
it back in. **Save draft** does the same on demand.

A copy is also kept in the browser, and it is the one that survives a
crashed tab or a lost connection. Reopen the composer and it offers to
**restore** what it kept, or to **discard** it.

Posting clears both, so the next thread you start in that forum begins
empty. With scripting off there is no autosave and no recovery offer;
**Save draft** still works.

## Everything else stays server-rendered

None of the above needed a client-side markup renderer, a syntax-
Expand Down
34 changes: 34 additions & 0 deletions e2e/composer-drafts.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { expect, test } from '@playwright/test'

import { signUp } from './support/session'

const BACKUP_KEY = 'meith:composer:new-thread:200'

test('posting a thread clears the browser copy, so the next one starts empty', async ({ page }) => {
test.setTimeout(60_000)

await signUp(page, 'drafter')

await page.goto('/200-general/new')

const title = `A thread that autosaved ${Date.now()}`
await page.getByLabel('Subject').fill(title)
await page.getByLabel('Message').fill('This one was autosaved before it was posted.')

await expect(page.getByText('Saved just now.')).toBeVisible()
await expect
.poll(() => page.evaluate((key) => localStorage.getItem(key), BACKUP_KEY))
.not.toBeNull()

await page.getByRole('button', { name: 'Post thread' }).click()
await expect(page).toHaveURL(/\/thread\/\d+-/)

await expect.poll(() => page.evaluate((key) => localStorage.getItem(key), BACKUP_KEY)).toBeNull()

await page.goto('/200-general/new')

await expect(page.getByLabel('Subject')).toHaveValue('')
await expect(
page.getByText('A newer unsent version was recovered from this browser.'),
).toHaveCount(0)
})