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(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 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
385function editorJsonToText(
386 json: JSONContent,
387 isLastDocumentChild: boolean = false,
388): string {
389 let text = ''
390 if (json.type === 'doc') {
391 if (json.content?.length) {
392 for (let i = 0; i < json.content.length; i++) {
393 const node = json.content[i]
394 const isLastNode = i === json.content.length - 1
395 text += editorJsonToText(node, isLastNode)
396 }
397 }
398 } else if (json.type === 'paragraph') {
399 if (json.content?.length) {
400 for (let i = 0; i < json.content.length; i++) {
401 const node = json.content[i]
402 text += editorJsonToText(node)
403 }
404 }
405 if (!isLastDocumentChild) {
406 text += '\n'
407 }
408 } else if (json.type === 'hardBreak') {
409 text += '\n'
410 } else if (json.type === 'text') {
411 text += json.text || ''
412 } else if (json.type === 'mention') {
413 text += `@${json.attrs?.id || ''}`
414 }
415 return text
416}
417
418const styles = StyleSheet.create({
419 container: {
420 flex: 1,
421 alignSelf: 'flex-start',
422 padding: 5,
423 marginLeft: 8,
424 marginBottom: 10,
425 },
426 rightPadding: {
427 paddingRight: 32,
428 },
429 dropContainer: {
430 backgroundColor: '#0007',
431 pointerEvents: 'none',
432 alignItems: 'center',
433 justifyContent: 'center',
434 // @ts-ignore web only -prf
435 position: 'fixed',
436 padding: 16,
437 top: 0,
438 bottom: 0,
439 left: 0,
440 right: 0,
441 },
442 dropModal: {
443 // @ts-ignore web only
444 boxShadow: 'rgba(0, 0, 0, 0.3) 0px 5px 20px',
445 padding: 8,
446 borderWidth: 1,
447 borderRadius: 16,
448 },
449 dropText: {
450 paddingVertical: 44,
451 paddingHorizontal: 36,
452 borderStyle: 'dashed',
453 borderRadius: 8,
454 borderWidth: 2,
455 },
456})
457
458function getImageOrVideoFromUri(
459 items: DataTransferItemList,
460 callback: (uri: string) => void,
461) {
462 for (let index = 0; index < items.length; index++) {
463 const item = items[index]
464 const type = item.type
465
466 if (type === 'text/plain') {
467 item.getAsString(async itemString => {
468 if (isUriImage(itemString)) {
469 const response = await fetch(itemString)
470 const blob = await response.blob()
471
472 if (blob.type.startsWith('image/')) {
473 blobToDataUri(blob).then(callback, err => console.error(err))
474 }
475
476 if (blob.type.startsWith('video/')) {
477 blobToDataUri(blob).then(callback, err => console.error(err))
478 }
479 }
480 })
481 } else if (type.startsWith('image/')) {
482 const file = item.getAsFile()
483
484 if (file) {
485 blobToDataUri(file).then(callback, err => console.error(err))
486 }
487 } else if (type.startsWith('video/')) {
488 const file = item.getAsFile()
489
490 if (file) {
491 blobToDataUri(file).then(callback, err => console.error(err))
492 }
493 }
494 }
495}