Composer.tsx59 lines, 1.6 KB
| 1 | import { useMutation, useQueryClient } from '@tanstack/react-query' |
| 2 | import { useState } from 'react' |
| 3 | import { getSession, request } from '../../lib/api' |
| 4 | |
| 5 | // The server's limit. posts.Create counts characters, not bytes, and |
| 6 | // so does [...body]. |
| 7 | const max = 280 |
| 8 | |
| 9 | export function Composer() { |
| 10 | const [body, setBody] = useState('') |
| 11 | const client = useQueryClient() |
| 12 | const me = getSession() |
| 13 | const post = useMutation({ |
| 14 | mutationFn: () => |
| 15 | request('/posts', { method: 'POST', json: { body } }), |
| 16 | onSuccess: () => { |
| 17 | setBody('') |
| 18 | client.invalidateQueries({ |
| 19 | queryKey: ['posts', `@${me?.handle}`], |
| 20 | }) |
| 21 | }, |
| 22 | }) |
| 23 | const left = max - [...body].length |
| 24 | |
| 25 | return ( |
| 26 | <form |
| 27 | action={() => post.mutate()} |
| 28 | className="border-b border-line px-4 py-3" |
| 29 | > |
| 30 | <label htmlFor="body" className="sr-only"> |
| 31 | New post |
| 32 | </label> |
| 33 | <textarea |
| 34 | id="body" |
| 35 | value={body} |
| 36 | onChange={(e) => setBody(e.target.value)} |
| 37 | placeholder="Say something, quietly." |
| 38 | className="field field-sizing-content min-h-16 resize-none |
| 39 | border-0 px-0 text-base outline-offset-4" |
| 40 | /> |
| 41 | <div className="flex items-center justify-end gap-3 text-sm"> |
| 42 | {post.isError && ( |
| 43 | <p role="alert" className="mr-auto text-accent-ink"> |
| 44 | {post.error.message} |
| 45 | </p> |
| 46 | )} |
| 47 | <span className={left < 0 ? 'text-accent-ink' : 'text-mute'}> |
| 48 | {left} |
| 49 | </span> |
| 50 | <button |
| 51 | className="btn" |
| 52 | disabled={!body.trim() || left < 0 || post.isPending} |
| 53 | > |
| 54 | Post |
| 55 | </button> |
| 56 | </div> |
| 57 | </form> |
| 58 | ) |
| 59 | } |