| 1 | "use client"; |
| 2 | |
| 3 | import { ProfileAvatar } from |
| 4 | import { useDebouncedValue } |
| 5 | import { keepPreviousData, useQuery |
| 6 | import { |
| 7 | Bold, |
| 8 | Code, |
| 9 | GitPullRequest, |
| 10 | Heading, |
| 11 | Italic, |
| 12 | Link, |
| 13 | List, |
| 14 | ListChecks, |
| 15 | ListOrdered, |
| 16 | type LucideIcon, |
| 17 | CircleDot, |
| 18 | Paperclip, |
| 19 | Quote, |
| 20 | } from "lucide-react"; |
| 21 | import { useRef, useState |
| 22 | import { toast } |
| 23 | |
| 24 | import { Markdown } |
| 25 | import { Button } |
| 26 | import { Tabs, TabsList |
| 27 | import { apiErrorMessage } |
| 28 | import { |
| 29 | completeMention, |
| 30 | type Edit, |
| 31 | type Format, |
| 32 | formatEdit, |
| 33 | type Mention, |
| 34 | mentionAt, |
| 35 | uploadPlaceholder, |
| 36 | } from "@/lib/markdown-editor"; |
| 37 | import { suggestIssues, suggestUsers |
| 38 | import { cn } |
| 39 | import { uploadAttachment } |
| 40 | |
| 41 | const TOOLBAR: [ |
| 42 | [ |
| 43 | ["heading", Heading |
| 44 | ["bold", Bold |
| 45 | ["italic", Italic |
| 46 | ], |
| 47 | [ |
| 48 | ["quote", Quote |
| 49 | ["code", Code |
| 50 | ["link", Link |
| 51 | ], |
| 52 | [ |
| 53 | ["bulleted", List |
| 54 | ["numbered", ListOrdered |
| 55 | ["task", ListChecks |
| 56 | ], |
| 57 | ]; |
| 58 | |
| 59 | const SHORTCUTS: Record |
| 60 | KeyB: "bold", |
| 61 | KeyI: "italic", |
| 62 | KeyE: "code", |
| 63 | KeyK: "link", |
| 64 | "Shift+Digit8": "bulleted", |
| 65 | "Shift+Digit7": "numbered", |
| 66 | }; |
| 67 | |
| 68 | type Suggestion |
| 69 | | Awaited |
| 70 | | Awaited |
| 71 | |
| 72 | /** What completing to `suggestion` types after its `@` or `#`. */ |
| 73 | const completionOf = ( |
| 74 | "username" in suggestion |
| 75 | |
| 76 | /** The one place Ghost takes Markdown: Write and Preview tabs, a formatting toolbar and shortcuts, `@` and `#` completion, and files attached by dropping, pasting or picking them. */ |
| 77 | export function MarkdownEditor({ |
| 78 | value, |
| 79 | onChange, |
| 80 | repository, |
| 81 | id, |
| 82 | placeholder = "Markdown is supported." |
| 83 | rows = 4, |
| 84 | maxLength = 20000, |
| 85 | disabled = false, |
| 86 | autoFocus = false, |
| 87 | invalid = false, |
| 88 | }: { |
| 89 | value: string |
| 90 | onChange: (value |
| 91 | /** Where the text will live: previews link its references, `@` and `#` complete from it, and files are attached to it. */ |
| 92 | repository: { |
| 93 | id?: string |
| 94 | placeholder?: string |
| 95 | rows?: number |
| 96 | maxLength?: number |
| 97 | disabled?: boolean |
| 98 | autoFocus?: boolean |
| 99 | invalid?: boolean |
| 100 | }) { |
| 101 | const textarea = |
| 102 | const picker = |
| 103 | const [tab, |
| 104 | const [mention, |
| 105 | const [highlighted, |
| 106 | const [uploads, |
| 107 | const [dragging, |
| 108 | |
| 109 | const [typed] |
| 110 | mention ? `${mention |
| 111 | { wait: 150 }, |
| 112 | ); |
| 113 | const { data: |
| 114 | queryKey: [ |
| 115 | "markdown-suggestions", |
| 116 | repository.username, |
| 117 | repository.repo, |
| 118 | typed, |
| 119 | ], |
| 120 | enabled: Boolean(mention |
| 121 | placeholderData: keepPreviousData, |
| 122 | staleTime: 30_000, |
| 123 | queryFn: (): Promise |
| 124 | typed.startsWith("@ |
| 125 | ? suggestUsers(repository, |
| 126 | : suggestIssues(repository, |
| 127 | }); |
| 128 | // the list for the last thing typed stays up while the next loads, but never under the other trigger |
| 129 | const open = |
| 130 | mention !== null && |
| 131 | suggestions.length > 0 |
| 132 | "username" in suggestions |
| 133 | |
| 134 | /** Applies an edit through the browser's own editing, so ⌘Z undoes it like typing. */ |
| 135 | function apply(edit |
| 136 | const element = |
| 137 | if (!element) |
| 138 | element.focus(); |
| 139 | element.setSelectionRange(edit |
| 140 | if (!document.execCommand |
| 141 | element.setRangeText(edit |
| 142 | element.dispatchEvent(new |
| 143 | } |
| 144 | element.setSelectionRange(edit |
| 145 | trackMention(element); |
| 146 | } |
| 147 | |
| 148 | function format(as |
| 149 | const element = |
| 150 | if (!element) |
| 151 | apply( |
| 152 | formatEdit( |
| 153 | element.value, |
| 154 | element.selectionStart, |
| 155 | element.selectionEnd, |
| 156 | as, |
| 157 | ), |
| 158 | ); |
| 159 | } |
| 160 | |
| 161 | function trackMention(element |
| 162 | const next = |
| 163 | element.selectionStart === |
| 164 | ? mentionAt(element. |
| 165 | : null; |
| 166 | setMention(next); |
| 167 | if (next?.start |
| 168 | } |
| 169 | |
| 170 | function complete(suggestion |
| 171 | const element = |
| 172 | if (!element || |
| 173 | apply( |
| 174 | completeMention( |
| 175 | element.value, |
| 176 | mention, |
| 177 | element.selectionStart, |
| 178 | completionOf(suggestion), |
| 179 | ), |
| 180 | ); |
| 181 | setMention(null); |
| 182 | } |
| 183 | |
| 184 | /** Swaps a placeholder for what replaced it without moving the caret, wherever the person has typed since. */ |
| 185 | function replacePlaceholder(placeholder |
| 186 | const element = |
| 187 | const at = |
| 188 | if (!element || |
| 189 | element.setRangeText(replacement |
| 190 | element.dispatchEvent(new |
| 191 | } |
| 192 | |
| 193 | function attach(files |
| 194 | const element = |
| 195 | if (!element || |
| 196 | setTab("write"); |
| 197 | const placeholders = |
| 198 | const before = |
| 199 | const lead = |
| 200 | apply({ |
| 201 | start: element.selectionStart |
| 202 | end: element.selectionEnd |
| 203 | insert: `${lead}${ |
| 204 | selectionStart: |
| 205 | element.selectionStart + |
| 206 | lead.length + |
| 207 | placeholders.join("\n |
| 208 | 1, |
| 209 | selectionEnd: |
| 210 | element.selectionStart + |
| 211 | lead.length + |
| 212 | placeholders.join("\n |
| 213 | 1, |
| 214 | }); |
| 215 | |
| 216 | setUploads((count) |
| 217 | files.forEach((file |
| 218 | uploadAttachment({ ...repository |
| 219 | .then((markdown) |
| 220 | .catch((error: |
| 221 | replacePlaceholder(placeholders[index |
| 222 | toast.error(apiErrorMessage |
| 223 | }) |
| 224 | .finally(() => |
| 225 | }); |
| 226 | } |
| 227 | |
| 228 | function onKeyDown(event |
| 229 | if (open) { |
| 230 | const step = |
| 231 | if (step) { |
| 232 | event.preventDefault(); |
| 233 | setHighlighted( |
| 234 | (index) => |
| 235 | ); |
| 236 | return; |
| 237 | } |
| 238 | if (event.key |
| 239 | event.preventDefault(); |
| 240 | complete(suggestions[Math |
| 241 | return; |
| 242 | } |
| 243 | if (event.key |
| 244 | event.preventDefault(); |
| 245 | setMention(null); |
| 246 | return; |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | if (!(event. |
| 251 | if (event.key |
| 252 | event.preventDefault(); |
| 253 | event.currentTarget.form |
| 254 | return; |
| 255 | } |
| 256 | const shortcut = |
| 257 | SHORTCUTS[event.shiftKey |
| 258 | if (shortcut) { |
| 259 | event.preventDefault(); |
| 260 | format(shortcut); |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | return ( |
| 265 | <div |
| 266 | className={cn( |
| 267 | "flex flex-col rounded-lg border border-input transition-colors focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 dark:bg-input/30", |
| 268 | invalid && "border-destructive ring-3 ring-destructive/20" |
| 269 | dragging && "border-primary bg-primary/5" |
| 270 | )} |
| 271 | onDragOver={(event) |
| 272 | if (disabled || ! |
| 273 | event.preventDefault(); |
| 274 | setDragging(true); |
| 275 | }} |
| 276 | onDragLeave={() => |
| 277 | onDrop={(event) |
| 278 | setDragging(false); |
| 279 | if (disabled || event |
| 280 | event.preventDefault(); |
| 281 | attach([...event. |
| 282 | }} |
| 283 | > |
| 284 | <div className="flex flex-wrap items-center justify-between gap-2 border-b px-2 py-1.5 |
| 285 | <Tabs value={ |
| 286 | <TabsList> |
| 287 | <TabsTrigger value=" |
| 288 | <TabsTrigger value=" |
| 289 | </TabsList> |
| 290 | </Tabs> |
| 291 | {tab === "write |
| 292 | <div |
| 293 | className="flex flex-wrap items-center gap-0.5" |
| 294 | role="toolbar" |
| 295 | aria-label="Formatting" |
| 296 | > |
| 297 | {TOOLBAR.map(( |
| 298 | <div |
| 299 | key={index} |
| 300 | className="flex items-center gap-0.5 not-first:border-l not-first:pl-0.5" |
| 301 | > |
| 302 | {group.map(( |
| 303 | <Button |
| 304 | key={as} |
| 305 | type="button" |
| 306 | variant="ghost" |
| 307 | size="icon-xs" |
| 308 | title={label} |
| 309 | aria-label={label} |
| 310 | disabled={disabled} |
| 311 | // keep the selection the button acts on |
| 312 | onMouseDown={(event) |
| 313 | onClick={() => |
| 314 | > |
| 315 | <Icon /> |
| 316 | </Button> |
| 317 | ))} |
| 318 | </div> |
| 319 | ))} |
| 320 | <div className="flex items-center border-l pl-0.5 |
| 321 | <Button |
| 322 | type="button" |
| 323 | variant="ghost" |
| 324 | size="icon-xs" |
| 325 | title="Attach files" |
| 326 | aria-label="Attach files" |
| 327 | disabled={disabled} |
| 328 | onClick={() => |
| 329 | > |
| 330 | <Paperclip /> |
| 331 | </Button> |
| 332 | </div> |
| 333 | </div> |
| 334 | )} |
| 335 | </div> |
| 336 | |
| 337 | <div className="relative |
| 338 | <textarea |
| 339 | ref={(element) |
| 340 | textarea.current = |
| 341 | // A post must not go out with an upload's placeholder in it; the form's own validation holds it back. |
| 342 | element?.setCustomValidity( |
| 343 | uploads > 0 ? |
| 344 | ); |
| 345 | }} |
| 346 | id={id} |
| 347 | value={value} |
| 348 | onChange={(event) |
| 349 | onChange(event.target |
| 350 | trackMention(event.target |
| 351 | }} |
| 352 | onSelect={(event) |
| 353 | onBlur={() => |
| 354 | onKeyDown={onKeyDown} |
| 355 | onPaste={(event) |
| 356 | const files = [ |
| 357 | if (files.length === |
| 358 | event.preventDefault(); |
| 359 | attach(files); |
| 360 | }} |
| 361 | rows={rows} |
| 362 | maxLength={maxLength} |
| 363 | placeholder={placeholder} |
| 364 | disabled={disabled} |
| 365 | autoFocus={autoFocus} |
| 366 | aria-invalid={invalid} |
| 367 | className={cn( |
| 368 | "field-sizing-content block max-h-[60vh] w-full resize-y bg-transparent px-3 py-2 text-base outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50 md:text-sm", |
| 369 | // hidden rather than unmounted, so uploads finishing during a preview still find their placeholders |
| 370 | tab !== "write" |
| 371 | )} |
| 372 | style={{ minHeight: |
| 373 | /> |
| 374 | |
| 375 | {open && tab |
| 376 | <ul |
| 377 | role="listbox" |
| 378 | className="absolute inset-x-2 top-full z-50 mt-1 max-w-sm overflow-hidden rounded-lg bg-popover p-1 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10" |
| 379 | > |
| 380 | {suggestions.map(( |
| 381 | <li |
| 382 | key={completionOf(suggestion |
| 383 | role="option" |
| 384 | aria-selected={index === |
| 385 | className={cn( |
| 386 | "flex cursor-default items-center gap-2 rounded-md px-2 py-1", |
| 387 | index === highlighted |
| 388 | )} |
| 389 | onMouseEnter={() => |
| 390 | // before the textarea's blur closes the list |
| 391 | onMouseDown={(event) |
| 392 | event.preventDefault(); |
| 393 | complete(suggestion); |
| 394 | }} |
| 395 | > |
| 396 | {"username" in suggestion |
| 397 | <> |
| 398 | <ProfileAvatar |
| 399 | name={suggestion.username |
| 400 | image={suggestion.image |
| 401 | className="size-5" |
| 402 | fallbackClassName="text-[10px]" |
| 403 | /> |
| 404 | <span className="font-medium |
| 405 | <span className="truncate text-muted-foreground |
| 406 | {suggestion.name} |
| 407 | </span> |
| 408 | </> |
| 409 | ) : ( |
| 410 | <> |
| 411 | {suggestion.isPullRequest ? |
| 412 | <GitPullRequest className=" |
| 413 | ) : ( |
| 414 | <CircleDot className=" |
| 415 | )} |
| 416 | <span className="font-medium |
| 417 | <span className="truncate text-muted-foreground |
| 418 | {suggestion.title} |
| 419 | </span> |
| 420 | </> |
| 421 | )} |
| 422 | </li> |
| 423 | ))} |
| 424 | </ul> |
| 425 | )} |
| 426 | </div> |
| 427 | |
| 428 | {tab === "preview |
| 429 | <div className="min-h-24 px-3 py-2 text-sm |
| 430 | {value.trim() |
| 431 | <Markdown repository={ |
| 432 | ) : ( |
| 433 | <p className="text-muted-foreground |
| 434 | )} |
| 435 | </div> |
| 436 | )} |
| 437 | |
| 438 | <div className="flex items-center justify-between gap-2 border-t px-3 py-1.5 text-xs text-muted-foreground |
| 439 | <span> |
| 440 | {uploads > 0 |
| 441 | ? `Uploading ${uploads} |
| 442 | : "Attach files by dragging, pasting or "} |
| 443 | {uploads === 0 |
| 444 | <button |
| 445 | type="button" |
| 446 | className="text-primary hover:underline disabled:opacity-50" |
| 447 | disabled={disabled} |
| 448 | onClick={() => |
| 449 | > |
| 450 | selecting them |
| 451 | </button> |
| 452 | )} |
| 453 | </span> |
| 454 | <span>Markdown supported</span> |
| 455 | <input |
| 456 | ref={picker} |
| 457 | type="file" |
| 458 | multiple |
| 459 | hidden |
| 460 | onChange={(event) |
| 461 | attach([...(event |
| 462 | event.target.value |
| 463 | }} |
| 464 | /> |
| 465 | </div> |
| 466 | </div> |
| 467 | ); |
| 468 | } |