Bluesky app fork with some witchin' additions 馃挮
at main 551 lines 17 kB view raw
1import { 2 useCallback, 3 useEffect, 4 useImperativeHandle, 5 useMemo, 6 useRef, 7 useState, 8} from 'react' 9import {StyleSheet, View} from 'react-native' 10import Animated, {FadeIn, FadeOut} from 'react-native-reanimated' 11import {AppBskyRichtextFacet, RichText, UnicodeString} from '@atproto/api' 12import {Trans} from '@lingui/macro' 13import {Document} from '@tiptap/extension-document' 14import Hardbreak from '@tiptap/extension-hard-break' 15import History from '@tiptap/extension-history' 16import {Mention} from '@tiptap/extension-mention' 17import {Paragraph} from '@tiptap/extension-paragraph' 18import {Placeholder} from '@tiptap/extension-placeholder' 19import {Text as TiptapText} from '@tiptap/extension-text' 20import {generateJSON} from '@tiptap/html' 21import {Fragment, Node, Slice} from '@tiptap/pm/model' 22import {EditorContent, type JSONContent, useEditor} from '@tiptap/react' 23import Graphemer from 'graphemer' 24 25import {useColorSchemeStyle} from '#/lib/hooks/useColorSchemeStyle' 26import {blobToDataUri, isUriImage} from '#/lib/media/util' 27import {useActorAutocompleteFn} from '#/state/queries/actor-autocomplete' 28import { 29 type LinkFacetMatch, 30 suggestLinkCardUri, 31} from '#/view/com/composer/text-input/text-input-util' 32import {textInputWebEmitter} from '#/view/com/composer/text-input/textInputWebEmitter' 33import {atoms as a, useAlf} from '#/alf' 34import {normalizeTextStyles} from '#/alf/typography' 35import {Portal} from '#/components/Portal' 36import {Text} from '#/components/Typography' 37import {type TextInputProps} from './TextInput.types' 38import {type AutocompleteRef, createSuggestion} from './web/Autocomplete' 39import {type Emoji} from './web/EmojiPicker' 40import {LinkDecorator} from './web/LinkDecorator' 41import {TagDecorator} from './web/TagDecorator' 42 43export function TextInput({ 44 ref, 45 richtext, 46 placeholder, 47 webForceMinHeight, 48 hasRightPadding, 49 isActive, 50 setRichText, 51 onPhotoPasted, 52 onPressPublish, 53 onNewLink, 54 onFocus, 55}: TextInputProps) { 56 const {theme: t, fonts} = useAlf() 57 const autocomplete = useActorAutocompleteFn() 58 const modeClass = useColorSchemeStyle('ProseMirror-light', 'ProseMirror-dark') 59 60 const [isDropping, setIsDropping] = useState(false) 61 const autocompleteRef = useRef<AutocompleteRef>(null) 62 63 const extensions = useMemo( 64 () => [ 65 Document, 66 LinkDecorator, 67 TagDecorator, 68 Mention.configure({ 69 HTMLAttributes: { 70 class: 'mention', 71 }, 72 suggestion: createSuggestion({autocomplete, autocompleteRef}), 73 }), 74 Paragraph, 75 Placeholder.configure({ 76 placeholder, 77 }), 78 TiptapText, 79 History, 80 Hardbreak, 81 ], 82 [autocomplete, placeholder], 83 ) 84 85 useEffect(() => { 86 if (!isActive) { 87 return 88 } 89 textInputWebEmitter.addListener('publish', onPressPublish) 90 return () => { 91 textInputWebEmitter.removeListener('publish', onPressPublish) 92 } 93 }, [onPressPublish, isActive]) 94 95 useEffect(() => { 96 if (!isActive) { 97 return 98 } 99 textInputWebEmitter.addListener('media-pasted', onPhotoPasted) 100 return () => { 101 textInputWebEmitter.removeListener('media-pasted', onPhotoPasted) 102 } 103 }, [isActive, onPhotoPasted]) 104 105 useEffect(() => { 106 if (!isActive) { 107 return 108 } 109 110 const handleDrop = (event: DragEvent) => { 111 const transfer = event.dataTransfer 112 if (transfer) { 113 const items = transfer.items 114 115 getImageOrVideoFromUri(items, (uri: string) => { 116 textInputWebEmitter.emit('media-pasted', uri) 117 }) 118 } 119 120 event.preventDefault() 121 setIsDropping(false) 122 } 123 const handleDragEnter = (event: DragEvent) => { 124 const transfer = event.dataTransfer 125 126 event.preventDefault() 127 if (transfer && transfer.types.includes('Files')) { 128 setIsDropping(true) 129 } 130 } 131 const handleDragLeave = (event: DragEvent) => { 132 event.preventDefault() 133 setIsDropping(false) 134 } 135 136 document.body.addEventListener('drop', handleDrop) 137 document.body.addEventListener('dragenter', handleDragEnter) 138 document.body.addEventListener('dragover', handleDragEnter) 139 document.body.addEventListener('dragleave', handleDragLeave) 140 141 return () => { 142 document.body.removeEventListener('drop', handleDrop) 143 document.body.removeEventListener('dragenter', handleDragEnter) 144 document.body.removeEventListener('dragover', handleDragEnter) 145 document.body.removeEventListener('dragleave', handleDragLeave) 146 } 147 }, [setIsDropping, isActive]) 148 149 const pastSuggestedUris = useRef(new Set<string>()) 150 const prevDetectedUris = useRef(new Map<string, LinkFacetMatch>()) 151 const editor = useEditor( 152 { 153 extensions, 154 coreExtensionOptions: { 155 clipboardTextSerializer: { 156 blockSeparator: '\n', 157 }, 158 }, 159 onFocus() { 160 onFocus?.() 161 }, 162 editorProps: { 163 attributes: { 164 class: modeClass, 165 }, 166 clipboardTextParser: (text, context) => { 167 const blocks = text.split(/(?:\r\n?|\n)/) 168 const nodes: Node[] = blocks.map(line => { 169 return Node.fromJSON( 170 context.doc.type.schema, 171 line.length > 0 172 ? {type: 'paragraph', content: [{type: 'text', text: line}]} 173 : {type: 'paragraph', content: []}, 174 ) 175 }) 176 177 const fragment = Fragment.fromArray(nodes) 178 return Slice.maxOpen(fragment) 179 }, 180 handlePaste: (view, event) => { 181 const clipboardData = event.clipboardData 182 let preventDefault = false 183 184 if (clipboardData) { 185 if (clipboardData.types.includes('text/html')) { 186 // Rich-text formatting is pasted, try retrieving plain text 187 const text = clipboardData.getData('text/plain') 188 // `pasteText` will invoke this handler again, but `clipboardData` will be null. 189 view.pasteText(text) 190 preventDefault = true 191 } 192 getImageOrVideoFromUri(clipboardData.items, (uri: string) => { 193 textInputWebEmitter.emit('media-pasted', uri) 194 }) 195 if (preventDefault) { 196 // Return `true` to prevent ProseMirror's default paste behavior. 197 return true 198 } 199 } 200 }, 201 handleKeyDown: (view, event) => { 202 if ((event.metaKey || event.ctrlKey) && event.code === 'Enter') { 203 textInputWebEmitter.emit('publish') 204 return true 205 } 206 207 if ( 208 event.code === 'Backspace' && 209 !(event.metaKey || event.altKey || event.ctrlKey) 210 ) { 211 const isNotSelection = view.state.selection.empty 212 if (isNotSelection) { 213 const cursorPosition = view.state.selection.$anchor.pos 214 const textBefore = view.state.doc.textBetween( 215 0, 216 cursorPosition, 217 // important - use \n as a block separator, otherwise 218 // all the lines get mushed together -sfn 219 '\n', 220 ) 221 const graphemes = new Graphemer().splitGraphemes(textBefore) 222 223 if (graphemes.length > 0) { 224 const lastGrapheme = graphemes[graphemes.length - 1] 225 // deleteRange doesn't work on newlines, because tiptap 226 // treats them as separate 'blocks' and we're using \n 227 // as a stand-in. bail out if the last grapheme is a newline 228 // to let the default behavior handle it -sfn 229 if (lastGrapheme !== '\n') { 230 // otherwise, delete the last grapheme using deleteRange, 231 // so that emojis are deleted as a whole 232 const deleteFrom = cursorPosition - lastGrapheme.length 233 editor?.commands.deleteRange({ 234 from: deleteFrom, 235 to: cursorPosition, 236 }) 237 return true 238 } 239 } 240 } 241 } 242 }, 243 }, 244 content: generateJSON(textToHtml(richtext.text.toString()), extensions, { 245 preserveWhitespace: 'full', 246 }), 247 autofocus: 'end', 248 editable: true, 249 injectCSS: true, 250 shouldRerenderOnTransaction: false, 251 onCreate({editor: editorProp}) { 252 // HACK 253 // the 'enter' animation sometimes causes autofocus to fail 254 // (see Composer.web.tsx in shell) 255 // so we wait 200ms (the anim is 150ms) and then focus manually 256 // -prf 257 setTimeout(() => { 258 editorProp.chain().focus('end').run() 259 }, 200) 260 }, 261 onUpdate({editor: editorProp}) { 262 const json = editorProp.getJSON() 263 const newText = editorJsonToText(json) 264 const isPaste = window.event?.type === 'paste' 265 266 const newRt = new RichText({text: newText}) 267 newRt.detectFacetsWithoutResolution() 268 269 const markdownFacets: AppBskyRichtextFacet.Main[] = [] 270 const regex = /\[([^\]]+)\]\s*\(([^)]+)\)/g 271 let match 272 while ((match = regex.exec(newText)) !== null) { 273 const [fullMatch, _linkText, linkUrl] = match 274 const matchStart = match.index 275 const matchEnd = matchStart + fullMatch.length 276 const prefix = newText.slice(0, matchStart) 277 const matchStr = newText.slice(matchStart, matchEnd) 278 const byteStart = new UnicodeString(prefix).length 279 const byteEnd = byteStart + new UnicodeString(matchStr).length 280 281 let validUrl = linkUrl 282 if ( 283 !validUrl.startsWith('http://') && 284 !validUrl.startsWith('https://') && 285 !validUrl.startsWith('mailto:') 286 ) { 287 validUrl = `https://${validUrl}` 288 } 289 290 markdownFacets.push({ 291 index: {byteStart, byteEnd}, 292 features: [ 293 { $type: 'app.bsky.richtext.facet#link', uri: validUrl }, 294 ], 295 }) 296 } 297 298 if (markdownFacets.length > 0) { 299 const nonOverlapping = (newRt.facets || []).filter(f => { 300 return !markdownFacets.some(mf => { 301 return ( 302 (f.index.byteStart >= mf.index.byteStart && 303 f.index.byteStart < mf.index.byteEnd) || 304 (f.index.byteEnd > mf.index.byteStart && 305 f.index.byteEnd <= mf.index.byteEnd) || 306 (mf.index.byteStart >= f.index.byteStart && 307 mf.index.byteStart < f.index.byteEnd) 308 ) 309 }) 310 }) 311 newRt.facets = [...nonOverlapping, ...markdownFacets].sort( 312 (a, b) => a.index.byteStart - b.index.byteStart, 313 ) 314 } 315 316 setRichText(newRt) 317 318 const nextDetectedUris = new Map<string, LinkFacetMatch>() 319 if (newRt.facets) { 320 for (const facet of newRt.facets) { 321 for (const feature of facet.features) { 322 if (AppBskyRichtextFacet.isLink(feature)) { 323 nextDetectedUris.set(feature.uri, {facet, rt: newRt}) 324 } 325 } 326 } 327 } 328 329 const suggestedUri = suggestLinkCardUri( 330 isPaste, 331 nextDetectedUris, 332 prevDetectedUris.current, 333 pastSuggestedUris.current, 334 ) 335 prevDetectedUris.current = nextDetectedUris 336 if (suggestedUri) { 337 onNewLink(suggestedUri) 338 } 339 }, 340 }, 341 [modeClass], 342 ) 343 344 const onEmojiInserted = useCallback( 345 (emoji: Emoji) => { 346 editor?.chain().focus().insertContent(emoji.native).run() 347 }, 348 [editor], 349 ) 350 useEffect(() => { 351 if (!isActive) { 352 return 353 } 354 textInputWebEmitter.addListener('emoji-inserted', onEmojiInserted) 355 return () => { 356 textInputWebEmitter.removeListener('emoji-inserted', onEmojiInserted) 357 } 358 }, [onEmojiInserted, isActive]) 359 360 useImperativeHandle(ref, () => ({ 361 focus: () => { 362 editor?.chain().focus() 363 }, 364 blur: () => { 365 editor?.chain().blur() 366 }, 367 getCursorPosition: () => { 368 const pos = editor?.state.selection.$anchor.pos 369 return pos ? editor?.view.coordsAtPos(pos) : undefined 370 }, 371 maybeClosePopup: () => autocompleteRef.current?.maybeClose() ?? false, 372 })) 373 374 const inputStyle = useMemo(() => { 375 const style = normalizeTextStyles( 376 [a.text_lg, a.leading_snug, t.atoms.text], 377 { 378 fontScale: fonts.scaleMultiplier, 379 fontFamily: fonts.family, 380 flags: {}, 381 }, 382 ) 383 /* 384 * TipTap component isn't a RN View and while it seems to convert 385 * `fontSize` to `px`, it doesn't convert `lineHeight`. 386 * 387 * `lineHeight` should always be defined here, this is defensive. 388 */ 389 style.lineHeight = style.lineHeight 390 ? ((style.lineHeight + 'px') as unknown as number) 391 : undefined 392 style.minHeight = webForceMinHeight ? 140 : undefined 393 return style 394 }, [t, fonts, webForceMinHeight]) 395 396 return ( 397 <> 398 <View style={[styles.container, hasRightPadding && styles.rightPadding]}> 399 {/* @ts-ignore inputStyle is fine */} 400 <EditorContent editor={editor} style={inputStyle} /> 401 </View> 402 403 {isDropping && ( 404 <Portal> 405 <Animated.View 406 style={styles.dropContainer} 407 entering={FadeIn.duration(80)} 408 exiting={FadeOut.duration(80)}> 409 <View 410 style={[ 411 t.atoms.bg, 412 t.atoms.border_contrast_low, 413 styles.dropModal, 414 ]}> 415 <Text 416 style={[ 417 a.text_lg, 418 a.font_semi_bold, 419 t.atoms.text_contrast_medium, 420 t.atoms.border_contrast_high, 421 styles.dropText, 422 ]}> 423 <Trans>Drop to add images</Trans> 424 </Text> 425 </View> 426 </Animated.View> 427 </Portal> 428 )} 429 </> 430 ) 431} 432 433function editorJsonToText( 434 json: JSONContent, 435 isLastDocumentChild: boolean = false, 436): string { 437 let text = '' 438 if (json.type === 'doc') { 439 if (json.content?.length) { 440 for (let i = 0; i < json.content.length; i++) { 441 const node = json.content[i] 442 const isLastNode = i === json.content.length - 1 443 text += editorJsonToText(node, isLastNode) 444 } 445 } 446 } else if (json.type === 'paragraph') { 447 if (json.content?.length) { 448 for (let i = 0; i < json.content.length; i++) { 449 const node = json.content[i] 450 text += editorJsonToText(node) 451 } 452 } 453 if (!isLastDocumentChild) { 454 text += '\n' 455 } 456 } else if (json.type === 'hardBreak') { 457 text += '\n' 458 } else if (json.type === 'text') { 459 text += json.text || '' 460 } else if (json.type === 'mention') { 461 text += `@${json.attrs?.id || ''}` 462 } 463 return text 464} 465 466const styles = StyleSheet.create({ 467 container: { 468 flex: 1, 469 alignSelf: 'flex-start', 470 padding: 5, 471 marginLeft: 8, 472 marginBottom: 10, 473 }, 474 rightPadding: { 475 paddingRight: 32, 476 }, 477 dropContainer: { 478 backgroundColor: '#0007', 479 pointerEvents: 'none', 480 alignItems: 'center', 481 justifyContent: 'center', 482 // @ts-ignore web only -prf 483 position: 'fixed', 484 padding: 16, 485 top: 0, 486 bottom: 0, 487 left: 0, 488 right: 0, 489 }, 490 dropModal: { 491 // @ts-ignore web only 492 boxShadow: 'rgba(0, 0, 0, 0.3) 0px 5px 20px', 493 padding: 8, 494 borderWidth: 1, 495 borderRadius: 16, 496 }, 497 dropText: { 498 paddingVertical: 44, 499 paddingHorizontal: 36, 500 borderStyle: 'dashed', 501 borderRadius: 8, 502 borderWidth: 2, 503 }, 504}) 505 506function textToHtml(text: string): string { 507 return text 508 .replace(/&/g, '&amp;') 509 .replace(/</g, '&lt;') 510 .replace(/>/g, '&gt;') 511 .replace(/\n/g, '<br>') 512} 513 514function getImageOrVideoFromUri( 515 items: DataTransferItemList, 516 callback: (uri: string) => void, 517) { 518 for (let index = 0; index < items.length; index++) { 519 const item = items[index] 520 const type = item.type 521 522 if (type === 'text/plain') { 523 item.getAsString(async itemString => { 524 if (isUriImage(itemString)) { 525 const response = await fetch(itemString) 526 const blob = await response.blob() 527 528 if (blob.type.startsWith('image/')) { 529 blobToDataUri(blob).then(callback, err => console.error(err)) 530 } 531 532 if (blob.type.startsWith('video/')) { 533 blobToDataUri(blob).then(callback, err => console.error(err)) 534 } 535 } 536 }) 537 } else if (type.startsWith('image/')) { 538 const file = item.getAsFile() 539 540 if (file) { 541 blobToDataUri(file).then(callback, err => console.error(err)) 542 } 543 } else if (type.startsWith('video/')) { 544 const file = item.getAsFile() 545 546 if (file) { 547 blobToDataUri(file).then(callback, err => console.error(err)) 548 } 549 } 550 } 551}