8058
Ir
irvc / files
irvc / web / src / components / Composer.tsx
10.3 KB
1import { 2 useEffect, 3 useRef, 4 useState, 5 type ClipboardEvent, 6 type FormEvent, 7 type KeyboardEvent, 8} from "react"; 9import { ImagePlus, SendHorizontal, Smile, X } from "lucide-react"; 10import { cn } from "cn"; 11import { Button, IconButton } from "@/ui"; 12import { api, gifs, upload } from "../lib/api"; 13import { toast } from "../lib/toast"; 14import type { Channel, Gif, UserSummary } from "../lib/types"; 15 16const maxInputHeight = 200; 17const maxSuggestions = 8; 18 19export default function Composer({ 20 channel, 21 users, 22 onEditLast, 23 onCollapse, 24 onTyping, 25}: { 26 channel: Channel; 27 users: UserSummary[]; 28 onEditLast: () => void; 29 onCollapse: () => void; 30 onTyping: () => void; 31}) { 32 const [body, setBody] = useState(""); 33 const [mention, setMention] = useState<{ query: string; start: number; index: number } | null>( 34 null, 35 ); 36 const [picker, setPicker] = useState<{ gifs: Gif[]; query: string } | null>(null); 37 const textarea = useRef<HTMLTextAreaElement>(null); 38 const file = useRef<HTMLInputElement>(null); 39 40 useEffect(() => { 41 const el = textarea.current; 42 if (!el) return; 43 el.style.height = "auto"; 44 el.style.height = `${Math.min(el.scrollHeight, maxInputHeight)}px`; 45 }, [body]); 46 47 function insert(text: string) { 48 const el = textarea.current; 49 if (!el) return setBody((b) => b + text); 50 const { selectionStart: start, selectionEnd: end } = el; 51 setBody((b) => b.slice(0, start) + text + b.slice(end)); 52 } 53 54 function suggest(query: string) { 55 const q = query.toLowerCase(); 56 return users.filter((u) => u.username.toLowerCase().startsWith(q)).slice(0, maxSuggestions); 57 } 58 59 // detectMention looks for an "@partial" token ending at the caret. 60 function detectMention(value: string, caret: number) { 61 const query = /(?:^|\s)@([\w-]*)$/.exec(value.slice(0, caret))?.[1]; 62 setMention( 63 query !== undefined && suggest(query).length > 0 64 ? { query, start: caret - query.length, index: 0 } 65 : null, 66 ); 67 } 68 69 function chooseMention(name: string) { 70 const el = textarea.current; 71 if (!el || !mention) return; 72 const caret = el.selectionStart ?? body.length; 73 setBody(body.slice(0, mention.start) + name + " " + body.slice(caret)); 74 setMention(null); 75 const pos = mention.start + name.length + 1; 76 requestAnimationFrame(() => { 77 el.focus(); 78 el.setSelectionRange(pos, pos); 79 }); 80 } 81 82 // media reports whether a file is worth uploading: a raster image or a 83 // browser-playable video. The name check catches files the browser gave no 84 // type, so the server can refuse them out loud instead of them vanishing. 85 const media = (f: File) => 86 f.type.startsWith("image/") || f.type.startsWith("video/") || /\.(png|jpe?g|gif|webp|mp4|webm)$/i.test(f.name); 87 88 async function attach(files: File[]) { 89 const failed: string[] = []; 90 for (const f of files) { 91 if (!media(f)) continue; 92 try { 93 const { url } = await upload(f); 94 insert(`\n`); 95 } catch (e) { 96 // a failed upload should not block the rest, but say why 97 failed.push(e instanceof Error ? e.message : "could not upload"); 98 } 99 } 100 if (failed.length === 1) toast(failed[0]); 101 else if (failed.length > 1) toast(`${failed.length} uploads failed: ${failed[0]}`); 102 } 103 104 async function openGifs(query: string) { 105 try { 106 setPicker({ gifs: await gifs(query), query }); 107 } catch { 108 // the picker simply stays closed 109 } 110 } 111 112 function pickGif(g: Gif) { 113 insert(`\n`); 114 setPicker(null); 115 textarea.current?.focus(); 116 } 117 118 async function send() { 119 const text = body.trim(); 120 if (!text) return; 121 setBody(""); 122 setMention(null); 123 if (text === "/collapse") return onCollapse(); 124 const gif = /^\/gif(?:\s+(.*))?$/.exec(text); 125 if (gif) return void openGifs(gif[1]?.trim() ?? ""); 126 try { 127 await api(`/channels/${channel.id}/messages`, { 128 method: "POST", 129 body: JSON.stringify({ body: text }), 130 }); 131 } catch (e) { 132 setBody(text); 133 toast(e instanceof Error ? e.message : "could not send message"); 134 } 135 } 136 137 function onKeyDown(e: KeyboardEvent<HTMLTextAreaElement>) { 138 const matches = mention ? suggest(mention.query) : []; 139 if (mention && matches.length > 0) { 140 const keys = ["ArrowDown", "ArrowUp", "Enter", "Tab", "Escape"]; 141 if (keys.includes(e.key)) { 142 e.preventDefault(); 143 if (e.key === "ArrowDown") 144 setMention({ ...mention, index: (mention.index + 1) % matches.length }); 145 else if (e.key === "ArrowUp") 146 setMention({ ...mention, index: (mention.index - 1 + matches.length) % matches.length }); 147 else if (e.key === "Escape") setMention(null); 148 else chooseMention(matches[mention.index].username); 149 return; 150 } 151 } 152 if (e.key === "ArrowUp" && !body) { 153 e.preventDefault(); 154 onEditLast(); 155 } else if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) { 156 e.preventDefault(); 157 send(); 158 } 159 } 160 161 // Media pasted anywhere in the composer is uploaded and inlined. 162 function onPaste(e: ClipboardEvent<HTMLTextAreaElement>) { 163 const files = [...e.clipboardData.files].filter(media); 164 if (files.length === 0) return; 165 e.preventDefault(); 166 attach(files); 167 } 168 169 // Dropping media anywhere on the page attaches it. The listener is 170 // registered once and reads attach through a ref. 171 const attachRef = useRef(attach); 172 attachRef.current = attach; 173 useEffect(() => { 174 const files = (e: DragEvent) => e.dataTransfer?.types.includes("Files") ?? false; 175 const onDragOver = (e: DragEvent) => { 176 if (files(e)) e.preventDefault(); 177 }; 178 const onDrop = (e: DragEvent) => { 179 if (!files(e)) return; 180 e.preventDefault(); 181 attachRef.current([...(e.dataTransfer?.files ?? [])]); 182 }; 183 window.addEventListener("dragover", onDragOver); 184 window.addEventListener("drop", onDrop); 185 return () => { 186 window.removeEventListener("dragover", onDragOver); 187 window.removeEventListener("drop", onDrop); 188 }; 189 }, []); 190 191 return ( 192 <div className="relative shrink-0 px-2 pt-1 pb-2 md:px-3 md:pb-3"> 193 {picker && ( 194 <GifPicker 195 state={picker} 196 onChange={setPicker} 197 onSearch={openGifs} 198 onPick={pickGif} 199 onClose={() => setPicker(null)} 200 /> 201 )} 202 {mention && suggest(mention.query).length > 0 && ( 203 <div className="absolute bottom-full left-2 z-40 mb-1 w-56 overflow-hidden rounded-lg border border-line bg-raised py-1 shadow-xl md:left-3"> 204 {suggest(mention.query).map((u, i) => ( 205 <button 206 key={u.id} 207 type="button" 208 onMouseDown={(e) => e.preventDefault()} 209 onClick={() => chooseMention(u.username)} 210 className={cn("menu-item", i === mention.index && "bg-surface")} 211 > 212 {u.username} 213 </button> 214 ))} 215 </div> 216 )} 217 <form 218 onSubmit={(e: FormEvent) => { 219 e.preventDefault(); 220 send(); 221 }} 222 className="flex items-end gap-1.5 rounded-lg border border-line bg-raised p-1.5 focus-within:border-accent" 223 > 224 <input 225 ref={file} 226 type="file" 227 accept="image/*,video/*" 228 multiple 229 hidden 230 onChange={(e) => { 231 attach([...(e.target.files ?? [])]); 232 e.target.value = ""; 233 }} 234 /> 235 <IconButton 236 label="attach media" 237 size="sm" 238 onClick={() => file.current?.click()} 239 className="mb-0.5" 240 > 241 <ImagePlus /> 242 </IconButton> 243 <IconButton label="gif picker" size="sm" className="mb-0.5" onClick={() => openGifs("")}> 244 <Smile /> 245 </IconButton> 246 <textarea 247 ref={textarea} 248 rows={1} 249 placeholder={`message ${channel.type === "dm" ? "@" : "#"}${channel.name}`} 250 value={body} 251 onChange={(e) => { 252 setBody(e.target.value); 253 if (e.target.value.trim()) onTyping(); 254 detectMention(e.target.value, e.target.selectionStart ?? e.target.value.length); 255 }} 256 onKeyDown={onKeyDown} 257 onPaste={onPaste} 258 className="max-h-[200px] min-h-7 flex-1 resize-none self-center bg-transparent py-1 text-base leading-6 outline-none md:text-sm" 259 /> 260 <Button 261 type="submit" 262 variant="primary" 263 size="sm" 264 className="mb-0.5" 265 disabled={!body.trim()} 266 aria-label="send message" 267 > 268 <SendHorizontal /> 269 </Button> 270 </form> 271 </div> 272 ); 273} 274 275function GifPicker({ 276 state, 277 onChange, 278 onSearch, 279 onPick, 280 onClose, 281}: { 282 state: { gifs: Gif[]; query: string }; 283 onChange: (state: { gifs: Gif[]; query: string }) => void; 284 onSearch: (query: string) => void; 285 onPick: (g: Gif) => void; 286 onClose: () => void; 287}) { 288 return ( 289 <div className="absolute right-2 bottom-full z-40 mb-1 w-[min(24rem,calc(100vw-1rem))] rounded-lg border border-line bg-raised p-2 shadow-xl md:right-3"> 290 <div className="flex items-center gap-1.5"> 291 <input 292 autoFocus 293 value={state.query} 294 onChange={(e) => onChange({ ...state, query: e.target.value })} 295 onKeyDown={(e) => { 296 if (e.key === "Enter") { 297 e.preventDefault(); 298 onSearch(state.query.trim()); 299 } else if (e.key === "Escape") { 300 e.preventDefault(); 301 onClose(); 302 } 303 }} 304 placeholder="search gifs" 305 className="input input-md" 306 /> 307 <IconButton label="close gif picker" size="sm" onClick={onClose}> 308 <X /> 309 </IconButton> 310 </div> 311 {state.gifs.length === 0 ? ( 312 <p className="px-1 py-3 text-sm text-faint">no results</p> 313 ) : ( 314 <div className="mt-1.5 grid max-h-72 grid-cols-3 gap-1 overflow-y-auto"> 315 {state.gifs.map((g) => ( 316 <button 317 key={g.url} 318 type="button" 319 onClick={() => onPick(g)} 320 className="overflow-hidden rounded-md border border-line transition-colors hover:border-accent/60" 321 > 322 <img src={g.preview} alt="" loading="lazy" className="h-24 w-full object-cover" /> 323 </button> 324 ))} 325 </div> 326 )} 327 </div> 328 ); 329}