forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 馃挮
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} 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 {splitGraphemes} from 'unicode-segmenter/grapheme'
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 = [...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(richTextToHTML(richtext), 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 setRichText(newRt)
269
270 const nextDetectedUris = new Map<string, LinkFacetMatch>()
271 if (newRt.facets) {
272 for (const facet of newRt.facets) {
273 for (const feature of facet.features) {
274 if (AppBskyRichtextFacet.isLink(feature)) {
275 nextDetectedUris.set(feature.uri, {facet, rt: newRt})
276 }
277 }
278 }
279 }
280
281 const suggestedUri = suggestLinkCardUri(
282 isPaste,
283 nextDetectedUris,
284 prevDetectedUris.current,
285 pastSuggestedUris.current,
286 )
287 prevDetectedUris.current = nextDetectedUris
288 if (suggestedUri) {
289 onNewLink(suggestedUri)
290 }
291 },
292 },
293 [modeClass],
294 )
295
296 const onEmojiInserted = useCallback(
297 (emoji: Emoji) => {
298 editor?.chain().focus().insertContent(emoji.native).run()
299 },
300 [editor],
301 )
302 useEffect(() => {
303 if (!isActive) {
304 return
305 }
306 textInputWebEmitter.addListener('emoji-inserted', onEmojiInserted)
307 return () => {
308 textInputWebEmitter.removeListener('emoji-inserted', onEmojiInserted)
309 }
310 }, [onEmojiInserted, isActive])
311
312 useImperativeHandle(ref, () => ({
313 focus: () => {
314 editor?.chain().focus()
315 },
316 blur: () => {
317 editor?.chain().blur()
318 },
319 getCursorPosition: () => {
320 const pos = editor?.state.selection.$anchor.pos
321 return pos ? editor?.view.coordsAtPos(pos) : undefined
322 },
323 maybeClosePopup: () => autocompleteRef.current?.maybeClose() ?? false,
324 }))
325
326 const inputStyle = useMemo(() => {
327 const style = normalizeTextStyles(
328 [a.text_lg, a.leading_snug, t.atoms.text],
329 {
330 fontScale: fonts.scaleMultiplier,
331 fontFamily: fonts.family,
332 flags: {},
333 },
334 )
335 /*
336 * TipTap component isn't a RN View and while it seems to convert
337 * `fontSize` to `px`, it doesn't convert `lineHeight`.
338 *
339 * `lineHeight` should always be defined here, this is defensive.
340 */
341 style.lineHeight = style.lineHeight
342 ? ((style.lineHeight + 'px') as unknown as number)
343 : undefined
344 style.minHeight = webForceMinHeight ? 140 : undefined
345 return style
346 }, [t, fonts, webForceMinHeight])
347
348 return (
349 <>
350 <View style={[styles.container, hasRightPadding && styles.rightPadding]}>
351 {/* @ts-ignore inputStyle is fine */}
352 <EditorContent editor={editor} style={inputStyle} />
353 </View>
354
355 {isDropping && (
356 <Portal>
357 <Animated.View
358 style={styles.dropContainer}
359 entering={FadeIn.duration(80)}
360 exiting={FadeOut.duration(80)}>
361 <View
362 style={[
363 t.atoms.bg,
364 t.atoms.border_contrast_low,
365 styles.dropModal,
366 ]}>
367 <Text
368 style={[
369 a.text_lg,
370 a.font_semi_bold,
371 t.atoms.text_contrast_medium,
372 t.atoms.border_contrast_high,
373 styles.dropText,
374 ]}>
375 <Trans>Drop to add images</Trans>
376 </Text>
377 </View>
378 </Animated.View>
379 </Portal>
380 )}
381 </>
382 )
383}
384
385/**
386 * Helper function to initialise the editor with RichText, which expects HTML
387 *
388 * All the extensions are able to initialise themselves from plain text, *except*
389 * for the Mention extension - we need to manually convert it into a `<span>` element
390 *
391 * It also escapes HTML characters
392 */
393function richTextToHTML(richtext: RichText): string {
394 let html = ''
395
396 for (const segment of richtext.segments()) {
397 if (segment.mention) {
398 html += `<span data-type="mention" data-id="${escapeHTML(segment.mention.did)}"></span>`
399 } else {
400 html += escapeHTML(segment.text)
401 }
402 }
403
404 return html
405}
406
407function escapeHTML(str: string): string {
408 return str
409 .replace(/&/g, '&')
410 .replace(/</g, '<')
411 .replace(/>/g, '>')
412 .replace(/"/g, '"')
413}
414
415function editorJsonToText(
416 json: JSONContent,
417 isLastDocumentChild: boolean = false,
418): string {
419 let text = ''
420 if (json.type === 'doc') {
421 if (json.content?.length) {
422 for (let i = 0; i < json.content.length; i++) {
423 const node = json.content[i]
424 const isLastNode = i === json.content.length - 1
425 text += editorJsonToText(node, isLastNode)
426 }
427 }
428 } else if (json.type === 'paragraph') {
429 if (json.content?.length) {
430 for (let i = 0; i < json.content.length; i++) {
431 const node = json.content[i]
432 text += editorJsonToText(node)
433 }
434 }
435 if (!isLastDocumentChild) {
436 text += '\n'
437 }
438 } else if (json.type === 'hardBreak') {
439 text += '\n'
440 } else if (json.type === 'text') {
441 text += json.text || ''
442 } else if (json.type === 'mention') {
443 text += `@${json.attrs?.id || ''}`
444 }
445 return text
446}
447
448const styles = StyleSheet.create({
449 container: {
450 flex: 1,
451 alignSelf: 'flex-start',
452 padding: 5,
453 marginLeft: 8,
454 marginBottom: 10,
455 },
456 rightPadding: {
457 paddingRight: 32,
458 },
459 dropContainer: {
460 backgroundColor: '#0007',
461 pointerEvents: 'none',
462 alignItems: 'center',
463 justifyContent: 'center',
464 // @ts-ignore web only -prf
465 position: 'fixed',
466 padding: 16,
467 top: 0,
468 bottom: 0,
469 left: 0,
470 right: 0,
471 },
472 dropModal: {
473 // @ts-ignore web only
474 boxShadow: 'rgba(0, 0, 0, 0.3) 0px 5px 20px',
475 padding: 8,
476 borderWidth: 1,
477 borderRadius: 16,
478 },
479 dropText: {
480 paddingVertical: 44,
481 paddingHorizontal: 36,
482 borderStyle: 'dashed',
483 borderRadius: 8,
484 borderWidth: 2,
485 },
486})
487
488function getImageOrVideoFromUri(
489 items: DataTransferItemList,
490 callback: (uri: string) => void,
491) {
492 for (let index = 0; index < items.length; index++) {
493 const item = items[index]
494 const type = item.type
495
496 if (type === 'text/plain') {
497 item.getAsString(async itemString => {
498 if (isUriImage(itemString)) {
499 const response = await fetch(itemString)
500 const blob = await response.blob()
501
502 if (blob.type.startsWith('image/')) {
503 blobToDataUri(blob).then(callback, err => console.error(err))
504 }
505
506 if (blob.type.startsWith('video/')) {
507 blobToDataUri(blob).then(callback, err => console.error(err))
508 }
509 }
510 })
511 } else if (type.startsWith('image/')) {
512 const file = item.getAsFile()
513
514 if (file) {
515 blobToDataUri(file).then(callback, err => console.error(err))
516 }
517 } else if (type.startsWith('video/')) {
518 const file = item.getAsFile()
519
520 if (file) {
521 blobToDataUri(file).then(callback, err => console.error(err))
522 }
523 }
524 }
525}