|
| 1 | +import type { SerializedEditorState } from 'lexical' |
| 2 | +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' |
| 3 | + |
| 4 | +import { RichEditor } from '../vendor/rich-editor/core/RichEditor' |
| 5 | + |
| 6 | +type Variant = 'article' | 'note' |
| 7 | + |
| 8 | +interface DocumentResponse { |
| 9 | + lexical: SerializedEditorState |
| 10 | + variant: Variant |
| 11 | + fileName: string |
| 12 | +} |
| 13 | + |
| 14 | +type Theme = 'light' | 'dark' |
| 15 | + |
| 16 | +const isMac = |
| 17 | + typeof navigator !== 'undefined' && |
| 18 | + /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent) |
| 19 | + |
| 20 | +const saveLabel = isMac ? '⌘S' : 'Ctrl+S' |
| 21 | + |
| 22 | +const useTheme = (): Theme => { |
| 23 | + const [theme, setTheme] = useState<Theme>(() => |
| 24 | + window.matchMedia('(prefers-color-scheme: dark)').matches |
| 25 | + ? 'dark' |
| 26 | + : 'light', |
| 27 | + ) |
| 28 | + useEffect(() => { |
| 29 | + const mq = window.matchMedia('(prefers-color-scheme: dark)') |
| 30 | + const onChange = () => { |
| 31 | + const next = mq.matches ? 'dark' : 'light' |
| 32 | + setTheme(next) |
| 33 | + document.documentElement.classList.toggle('dark', next === 'dark') |
| 34 | + } |
| 35 | + mq.addEventListener('change', onChange) |
| 36 | + return () => mq.removeEventListener('change', onChange) |
| 37 | + }, []) |
| 38 | + return theme |
| 39 | +} |
| 40 | + |
| 41 | +export function AuthorApp() { |
| 42 | + const theme = useTheme() |
| 43 | + const [doc, setDoc] = useState<DocumentResponse | null>(null) |
| 44 | + const [loadError, setLoadError] = useState<string | null>(null) |
| 45 | + const [state, setState] = useState<SerializedEditorState | null>(null) |
| 46 | + const [saved, setSaved] = useState('') |
| 47 | + const [saveError, setSaveError] = useState<string | null>(null) |
| 48 | + const [saving, setSaving] = useState(false) |
| 49 | + const hydrated = useRef(false) |
| 50 | + |
| 51 | + useEffect(() => { |
| 52 | + let cancelled = false |
| 53 | + void fetch('/api/document') |
| 54 | + .then(async (res) => { |
| 55 | + const json = (await res.json()) as |
| 56 | + DocumentResponse | { error?: { message?: string } } |
| 57 | + if (!res.ok) { |
| 58 | + throw new Error( |
| 59 | + 'error' in json && json.error?.message |
| 60 | + ? json.error.message |
| 61 | + : `load failed (${res.status})`, |
| 62 | + ) |
| 63 | + } |
| 64 | + return json as DocumentResponse |
| 65 | + }) |
| 66 | + .then((next) => { |
| 67 | + if (cancelled) return |
| 68 | + setDoc(next) |
| 69 | + setState(next.lexical) |
| 70 | + setSaved(JSON.stringify(next.lexical)) |
| 71 | + hydrated.current = false |
| 72 | + }) |
| 73 | + .catch((err: unknown) => { |
| 74 | + if (cancelled) return |
| 75 | + setLoadError(err instanceof Error ? err.message : String(err)) |
| 76 | + }) |
| 77 | + return () => { |
| 78 | + cancelled = true |
| 79 | + } |
| 80 | + }, []) |
| 81 | + |
| 82 | + const dirty = useMemo( |
| 83 | + () => state !== null && JSON.stringify(state) !== saved, |
| 84 | + [state, saved], |
| 85 | + ) |
| 86 | + |
| 87 | + const save = useCallback(async () => { |
| 88 | + if (!state) return |
| 89 | + setSaving(true) |
| 90 | + setSaveError(null) |
| 91 | + try { |
| 92 | + const res = await fetch('/api/document', { |
| 93 | + method: 'PUT', |
| 94 | + headers: { 'content-type': 'application/json' }, |
| 95 | + body: JSON.stringify({ lexical: state }), |
| 96 | + }) |
| 97 | + const json = (await res.json()) as { error?: { message?: string } } |
| 98 | + if (!res.ok) { |
| 99 | + throw new Error(json.error?.message ?? `save failed (${res.status})`) |
| 100 | + } |
| 101 | + setSaved(JSON.stringify(state)) |
| 102 | + } catch (err) { |
| 103 | + setSaveError(err instanceof Error ? err.message : String(err)) |
| 104 | + } finally { |
| 105 | + setSaving(false) |
| 106 | + } |
| 107 | + }, [state]) |
| 108 | + |
| 109 | + useEffect(() => { |
| 110 | + const onKey = (event: KeyboardEvent) => { |
| 111 | + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 's') { |
| 112 | + event.preventDefault() |
| 113 | + void save() |
| 114 | + } |
| 115 | + } |
| 116 | + window.addEventListener('keydown', onKey) |
| 117 | + return () => window.removeEventListener('keydown', onKey) |
| 118 | + }, [save]) |
| 119 | + |
| 120 | + useEffect(() => { |
| 121 | + if (!dirty) return |
| 122 | + const onUnload = (event: BeforeUnloadEvent) => { |
| 123 | + event.preventDefault() |
| 124 | + event.returnValue = '' |
| 125 | + } |
| 126 | + window.addEventListener('beforeunload', onUnload) |
| 127 | + return () => window.removeEventListener('beforeunload', onUnload) |
| 128 | + }, [dirty]) |
| 129 | + |
| 130 | + if (loadError) { |
| 131 | + return ( |
| 132 | + <div className="flex min-h-dvh items-center justify-center bg-surface-page text-sm text-red-700 dark:text-red-400"> |
| 133 | + {loadError} |
| 134 | + </div> |
| 135 | + ) |
| 136 | + } |
| 137 | + |
| 138 | + if (!doc || !state) { |
| 139 | + return ( |
| 140 | + <div className="flex min-h-dvh items-center justify-center bg-surface-page text-sm text-fg-muted"> |
| 141 | + 加载中… |
| 142 | + </div> |
| 143 | + ) |
| 144 | + } |
| 145 | + |
| 146 | + const canSave = (dirty || Boolean(saveError)) && !saving |
| 147 | + |
| 148 | + return ( |
| 149 | + <div className="flex min-h-dvh flex-col bg-surface-page text-fg"> |
| 150 | + <header className="flex h-11 shrink-0 items-center gap-2.5 border-b border-border bg-surface-card px-3"> |
| 151 | + {dirty ? ( |
| 152 | + <span className="size-1.5 shrink-0 rounded-full bg-accent" /> |
| 153 | + ) : null} |
| 154 | + <span className="truncate text-sm text-fg-muted">{doc.fileName}</span> |
| 155 | + {saveError ? ( |
| 156 | + <span className="min-w-0 flex-1 truncate text-sm text-red-700 dark:text-red-400"> |
| 157 | + {saveError} |
| 158 | + </span> |
| 159 | + ) : ( |
| 160 | + <span className="flex-1" /> |
| 161 | + )} |
| 162 | + <button |
| 163 | + type="button" |
| 164 | + disabled={!canSave} |
| 165 | + onClick={() => void save()} |
| 166 | + className="rounded-sm bg-accent px-2.5 py-1 text-sm font-medium text-white disabled:bg-surface-inset disabled:text-fg-subtle" |
| 167 | + > |
| 168 | + {saveError ? '重试' : '保存'} |
| 169 | + <span className="ml-1 text-[10px] font-normal opacity-70"> |
| 170 | + {saveLabel} |
| 171 | + </span> |
| 172 | + </button> |
| 173 | + </header> |
| 174 | + <div className="min-h-0 flex-1 overflow-auto"> |
| 175 | + <RichEditor |
| 176 | + theme={theme} |
| 177 | + variant={doc.variant} |
| 178 | + initialValue={doc.lexical} |
| 179 | + onChange={(value) => { |
| 180 | + setState(value) |
| 181 | + if (!hydrated.current) { |
| 182 | + hydrated.current = true |
| 183 | + setSaved(JSON.stringify(value)) |
| 184 | + } |
| 185 | + }} |
| 186 | + /> |
| 187 | + </div> |
| 188 | + </div> |
| 189 | + ) |
| 190 | +} |
0 commit comments