tooot/src/screens/Shared/Compose/updateText.ts

51 lines
1.1 KiB
TypeScript
Raw Normal View History

2020-12-04 01:17:10 +01:00
import { Dispatch } from 'react'
import { PostAction, PostState } from '../Compose'
import formatText from './formatText'
2020-11-15 20:29:43 +01:00
const updateText = ({
2020-12-06 23:51:13 +01:00
origin,
2020-11-15 20:29:43 +01:00
postState,
2020-12-04 01:17:10 +01:00
postDispatch,
newText,
type
2020-11-15 20:29:43 +01:00
}: {
2020-12-06 23:51:13 +01:00
origin: 'text' | 'spoiler'
2020-11-15 20:29:43 +01:00
postState: PostState
2020-12-04 01:17:10 +01:00
postDispatch: Dispatch<PostAction>
2020-11-15 20:29:43 +01:00
newText: string
2020-12-04 01:17:10 +01:00
type: 'emoji' | 'suggestion'
2020-11-15 20:29:43 +01:00
}) => {
2020-12-06 23:51:13 +01:00
if (postState[origin].raw.length) {
const contentFront = postState[origin].raw.slice(
0,
postState[origin].selection.start
)
const contentRear = postState[origin].raw.slice(
postState[origin].selection.end
)
2020-12-03 22:03:06 +01:00
const whiteSpaceFront = /\s/g.test(contentFront.slice(-1))
const whiteSpaceRear = /\s/g.test(contentRear.slice(-1))
2020-12-04 01:17:10 +01:00
const newTextWithSpace = `${
whiteSpaceFront || type === 'suggestion' ? '' : ' '
}${newText}${whiteSpaceRear ? '' : ' '}`
2020-12-03 22:03:06 +01:00
2020-12-04 01:17:10 +01:00
formatText({
2020-12-06 23:51:13 +01:00
origin,
2020-12-04 01:17:10 +01:00
postDispatch,
2020-12-03 22:03:06 +01:00
content: [contentFront, newTextWithSpace, contentRear].join(''),
disableDebounce: true
})
} else {
2020-12-04 01:17:10 +01:00
formatText({
2020-12-06 23:51:13 +01:00
origin,
2020-12-04 01:17:10 +01:00
postDispatch,
2020-12-03 22:03:06 +01:00
content: `${newText} `,
disableDebounce: true
})
}
2020-11-15 20:29:43 +01:00
}
export default updateText