akkoma-fe/src/components/post_status_form/post_status_form.js

412 lines
14 KiB
JavaScript
Raw Normal View History

2016-10-30 15:53:58 +00:00
import statusPoster from '../../services/status_poster/status_poster.service.js'
2016-11-06 18:30:35 +00:00
import MediaUpload from '../media_upload/media_upload.vue'
import ScopeSelector from '../scope_selector/scope_selector.vue'
2019-08-12 10:18:37 +00:00
import EmojiInput from '../emoji_input/emoji_input.vue'
2019-06-18 20:28:31 +00:00
import PollForm from '../poll/poll_form.vue'
import Attachment from '../attachment/attachment.vue'
2016-11-25 17:21:25 +00:00
import fileTypeService from '../../services/file_type/file_type.service.js'
import { findOffset } from '../../services/offset_finder/offset_finder.service.js'
2020-07-07 06:08:50 +00:00
import { reject, map, uniqBy } from 'lodash'
2019-08-12 10:18:37 +00:00
import suggestor from '../emoji_input/suggestor.js'
import { mapGetters } from 'vuex'
import Checkbox from '../checkbox/checkbox.vue'
2016-11-03 16:17:32 +00:00
2019-09-19 18:38:55 +00:00
const buildMentionsString = ({ user, attentions = [] }, currentUser) => {
2016-11-03 16:17:32 +00:00
let allAttentions = [...attentions]
allAttentions.unshift(user)
allAttentions = uniqBy(allAttentions, 'id')
2019-06-09 18:35:49 +00:00
allAttentions = reject(allAttentions, { id: currentUser.id })
2016-11-03 16:17:32 +00:00
let mentions = map(allAttentions, (attention) => {
return `@${attention.screen_name}`
})
return mentions.length > 0 ? mentions.join(' ') + ' ' : ''
2016-11-03 16:17:32 +00:00
}
2016-10-30 15:53:58 +00:00
const PostStatusForm = {
2016-11-03 15:59:27 +00:00
props: [
2016-11-03 16:17:32 +00:00
'replyTo',
'repliedUser',
2018-06-12 17:28:48 +00:00
'attentions',
2018-09-25 12:16:26 +00:00
'copyMessageScope',
2018-08-26 00:50:11 +00:00
'subject'
2016-11-03 15:59:27 +00:00
],
2016-11-06 18:30:35 +00:00
components: {
MediaUpload,
EmojiInput,
2019-06-18 20:28:31 +00:00
PollForm,
ScopeSelector,
Checkbox,
Attachment
2016-11-06 18:30:35 +00:00
},
2018-04-15 16:05:16 +00:00
mounted () {
this.resize(this.$refs.textarea)
const textLength = this.$refs.textarea.value.length
this.$refs.textarea.setSelectionRange(textLength, textLength)
2018-08-05 19:17:11 +00:00
if (this.replyTo) {
this.$refs.textarea.focus()
}
2018-04-15 16:05:16 +00:00
},
2016-11-03 15:59:27 +00:00
data () {
2018-04-29 14:44:08 +00:00
const preset = this.$route.query.message
let statusText = preset || ''
2016-11-03 16:17:32 +00:00
const { scopeCopy } = this.$store.getters.mergedConfig
2016-11-03 16:17:32 +00:00
if (this.replyTo) {
const currentUser = this.$store.state.users.currentUser
statusText = buildMentionsString({ user: this.repliedUser, attentions: this.attentions }, currentUser)
}
2019-06-09 18:35:49 +00:00
const scope = ((this.copyMessageScope && scopeCopy) || this.copyMessageScope === 'direct')
? this.copyMessageScope
: this.$store.state.users.currentUser.default_scope
2018-09-25 12:16:26 +00:00
const { postContentType: contentType } = this.$store.getters.mergedConfig
2019-02-21 16:16:11 +00:00
2016-10-30 15:53:58 +00:00
return {
dropFiles: [],
submitDisabled: false,
error: null,
posting: false,
highlighted: 0,
2016-11-03 16:17:32 +00:00
newStatus: {
spoilerText: this.subject || '',
2016-11-06 18:30:35 +00:00
status: statusText,
nsfw: false,
files: [],
2019-06-18 20:28:31 +00:00
poll: {},
2019-02-18 05:03:26 +00:00
mediaDescriptions: {},
2019-02-21 16:16:11 +00:00
visibility: scope,
contentType
},
2019-06-18 20:28:31 +00:00
caret: 0,
pollFormVisible: false,
2020-06-10 09:41:02 +00:00
showDropIcon: 'hide',
dropStopTimeout: null
2016-10-30 15:53:58 +00:00
}
},
computed: {
users () {
return this.$store.state.users.users
},
userDefaultScope () {
return this.$store.state.users.currentUser.default_scope
},
showAllScopes () {
2019-10-09 18:32:32 +00:00
return !this.mergedConfig.minimalScopesMode
},
emojiUserSuggestor () {
return suggestor({
emoji: [
...this.$store.state.instance.emoji,
...this.$store.state.instance.customEmoji
],
2019-07-18 03:40:02 +00:00
users: this.$store.state.users.users,
2020-05-13 14:48:31 +00:00
updateUsersList: (query) => this.$store.dispatch('searchUsers', { query })
})
},
emojiSuggestor () {
2019-06-09 18:35:49 +00:00
return suggestor({
emoji: [
...this.$store.state.instance.emoji,
...this.$store.state.instance.customEmoji
]
})
},
emoji () {
return this.$store.state.instance.emoji || []
},
customEmoji () {
return this.$store.state.instance.customEmoji || []
},
2018-02-09 14:51:04 +00:00
statusLength () {
return this.newStatus.status.length
},
spoilerTextLength () {
return this.newStatus.spoilerText.length
},
2018-02-09 14:51:04 +00:00
statusLengthLimit () {
2018-09-09 19:31:34 +00:00
return this.$store.state.instance.textlimit
2018-02-09 14:51:04 +00:00
},
hasStatusLengthLimit () {
return this.statusLengthLimit > 0
},
charactersLeft () {
return this.statusLengthLimit - (this.statusLength + this.spoilerTextLength)
},
isOverLengthLimit () {
return this.hasStatusLengthLimit && (this.charactersLeft < 0)
},
2019-03-30 10:41:42 +00:00
minimalScopesMode () {
return this.$store.state.instance.minimalScopesMode
},
alwaysShowSubject () {
return this.mergedConfig.alwaysShowSubjectInput
},
2019-03-07 04:13:04 +00:00
postFormats () {
return this.$store.state.instance.postFormats || []
},
2019-04-02 15:19:45 +00:00
safeDMEnabled () {
return this.$store.state.instance.safeDM
},
2019-06-18 20:28:31 +00:00
pollsAvailable () {
return this.$store.state.instance.pollsAvailable &&
this.$store.state.instance.pollLimits.max_options >= 2
},
hideScopeNotice () {
return this.$store.getters.mergedConfig.hideScopeNotice
2017-03-15 16:06:48 +00:00
},
2019-06-18 20:28:31 +00:00
pollContentError () {
return this.pollFormVisible &&
this.newStatus.poll &&
this.newStatus.poll.error
},
...mapGetters(['mergedConfig'])
},
2016-10-30 15:53:58 +00:00
methods: {
2020-07-07 06:07:20 +00:00
async postStatus (newStatus) {
if (this.posting) { return }
2018-01-31 17:48:09 +00:00
if (this.submitDisabled) { return }
if (this.newStatus.status === '') {
if (this.newStatus.files.length === 0) {
this.error = 'Cannot post an empty status with no files'
2017-08-24 13:25:26 +00:00
return
}
}
2019-06-18 20:28:31 +00:00
const poll = this.pollFormVisible ? this.newStatus.poll : {}
if (this.pollContentError) {
this.error = this.pollContentError
return
}
this.posting = true
2020-07-07 06:07:20 +00:00
await this.setAllMediaDescriptions()
const data = await statusPoster.postStatus({
2016-10-30 15:53:58 +00:00
status: newStatus.status,
2018-06-07 21:31:43 +00:00
spoilerText: newStatus.spoilerText || null,
2018-06-07 09:03:50 +00:00
visibility: newStatus.visibility,
sensitive: newStatus.nsfw,
2016-11-06 18:30:35 +00:00
media: newStatus.files,
2016-11-03 15:59:27 +00:00
store: this.$store,
inReplyToStatusId: this.replyTo,
2019-06-18 20:28:31 +00:00
contentType: newStatus.contentType,
poll
2016-10-30 15:53:58 +00:00
})
2020-07-07 06:07:20 +00:00
if (!data.error) {
this.newStatus = {
status: '',
spoilerText: '',
files: [],
visibility: newStatus.visibility,
contentType: newStatus.contentType,
poll: {}
}
this.pollFormVisible = false
this.$refs.mediaUpload.clearFile()
this.clearPollForm()
this.$emit('posted')
let el = this.$el.querySelector('textarea')
el.style.height = 'auto'
el.style.height = undefined
this.error = null
} else {
this.error = data.error
}
this.posting = false
2016-11-06 18:30:35 +00:00
},
addMediaFile (fileInfo) {
this.newStatus.files.push(fileInfo)
},
2016-11-26 02:00:06 +00:00
removeMediaFile (fileInfo) {
let index = this.newStatus.files.indexOf(fileInfo)
this.newStatus.files.splice(index, 1)
},
2018-12-08 21:36:54 +00:00
uploadFailed (errString, templateArgs) {
2018-12-08 21:39:58 +00:00
templateArgs = templateArgs || {}
this.error = this.$t('upload.error.base') + ' ' + this.$t('upload.error.' + errString, templateArgs)
2018-12-08 15:23:21 +00:00
},
disableSubmit () {
this.submitDisabled = true
},
enableSubmit () {
this.submitDisabled = false
2016-11-25 17:21:25 +00:00
},
type (fileInfo) {
return fileTypeService.fileType(fileInfo.mimetype)
},
2017-11-28 20:31:40 +00:00
paste (e) {
2019-09-23 21:06:53 +00:00
this.resize(e)
2017-11-28 20:31:40 +00:00
if (e.clipboardData.files.length > 0) {
// prevent pasting of file as text
e.preventDefault()
2017-11-28 20:31:40 +00:00
// Strangely, files property gets emptied after event propagation
// Trying to wrap it in array doesn't work. Plus I doubt it's possible
// to hold more than one file in clipboard.
this.dropFiles = [e.clipboardData.files[0]]
}
},
fileDrop (e) {
if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {
2019-06-09 18:35:49 +00:00
e.preventDefault() // allow dropping text like before
this.dropFiles = e.dataTransfer.files
clearTimeout(this.dropStopTimeout)
2020-06-10 09:41:02 +00:00
this.showDropIcon = 'hide'
}
},
fileDragStop (e) {
// The false-setting is done with delay because just using leave-events
// directly caused unwanted flickering, this is not perfect either but
// much less noticable.
clearTimeout(this.dropStopTimeout)
2020-06-10 09:41:02 +00:00
this.showDropIcon = 'fade'
this.dropStopTimeout = setTimeout(() => (this.showDropIcon = 'hide'), 500)
},
fileDrag (e) {
2017-02-22 21:33:28 +00:00
e.dataTransfer.dropEffect = 'copy'
if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {
clearTimeout(this.dropStopTimeout)
2020-06-10 09:41:02 +00:00
this.showDropIcon = 'show'
}
},
onEmojiInputInput (e) {
this.$nextTick(() => {
this.resize(this.$refs['textarea'])
})
},
resize (e) {
const target = e.target || e
if (!(target instanceof window.Element)) { return }
// Reset to default height for empty form, nothing else to do here.
if (target.value === '') {
target.style.height = null
this.$refs['emoji-input'].resize()
return
}
2019-10-22 20:53:23 +00:00
const formRef = this.$refs['form']
const bottomRef = this.$refs['bottom']
/* Scroller is either `window` (replies in TL), sidebar (main post form,
* replies in notifs) or mobile post form. Note that getting and setting
* scroll is different for `Window` and `Element`s
*/
2019-10-22 20:53:23 +00:00
const bottomBottomPaddingStr = window.getComputedStyle(bottomRef)['padding-bottom']
const bottomBottomPadding = Number(bottomBottomPaddingStr.substring(0, bottomBottomPaddingStr.length - 2))
const scrollerRef = this.$el.closest('.sidebar-scroller') ||
this.$el.closest('.post-form-modal-view') ||
window
// Getting info about padding we have to account for, removing 'px' part
const topPaddingStr = window.getComputedStyle(target)['padding-top']
const bottomPaddingStr = window.getComputedStyle(target)['padding-bottom']
const topPadding = Number(topPaddingStr.substring(0, topPaddingStr.length - 2))
const bottomPadding = Number(bottomPaddingStr.substring(0, bottomPaddingStr.length - 2))
const vertPadding = topPadding + bottomPadding
/* Explanation:
*
* https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight
* scrollHeight returns element's scrollable content height, i.e. visible
* element + overscrolled parts of it. We use it to determine when text
* inside the textarea exceeded its height, so we can set height to prevent
* overscroll, i.e. make textarea grow with the text. HOWEVER, since we
* explicitly set new height, scrollHeight won't go below that, so we can't
* SHRINK the textarea when there's extra space. To workaround that we set
* height to 'auto' which makes textarea tiny again, so that scrollHeight
* will match text height again. HOWEVER, shrinking textarea can screw with
2019-10-22 20:53:23 +00:00
* the scroll since there might be not enough padding around form-bottom to even
2019-09-25 16:32:30 +00:00
* warrant a scroll, so it will jump to 0 and refuse to move anywhere,
* so we check current scroll position before shrinking and then restore it
* with needed delta.
*/
// this part has to be BEFORE the content size update
const currentScroll = scrollerRef === window
? scrollerRef.scrollY
: scrollerRef.scrollTop
const scrollerHeight = scrollerRef === window
? scrollerRef.innerHeight
: scrollerRef.offsetHeight
const scrollerBottomBorder = currentScroll + scrollerHeight
// BEGIN content size update
target.style.height = 'auto'
const newHeight = target.scrollHeight - vertPadding
target.style.height = `${newHeight}px`
// END content size update
2019-10-22 20:53:23 +00:00
// We check where the bottom border of form-bottom element is, this uses findOffset
// to find offset relative to scrollable container (scroller)
2019-10-22 20:53:23 +00:00
const bottomBottomBorder = bottomRef.offsetHeight + findOffset(bottomRef, scrollerRef).top + bottomBottomPadding
2019-10-22 20:53:23 +00:00
const isBottomObstructed = scrollerBottomBorder < bottomBottomBorder
const isFormBiggerThanScroller = scrollerHeight < formRef.offsetHeight
const bottomChangeDelta = bottomBottomBorder - scrollerBottomBorder
// The intention is basically this;
2019-10-22 20:53:23 +00:00
// Keep form-bottom always visible so that submit button is in view EXCEPT
// if form element bigger than scroller and caret isn't at the end, so that
// if you scroll up and edit middle of text you won't get scrolled back to bottom
const shouldScrollToBottom = isBottomObstructed &&
2019-10-22 20:53:23 +00:00
!(isFormBiggerThanScroller &&
this.$refs.textarea.selectionStart !== this.$refs.textarea.value.length)
2019-10-22 20:53:23 +00:00
const totalDelta = shouldScrollToBottom ? bottomChangeDelta : 0
const targetScroll = currentScroll + totalDelta
if (scrollerRef === window) {
scrollerRef.scroll(0, targetScroll)
} else {
scrollerRef.scrollTop = targetScroll
}
this.$refs['emoji-input'].resize()
},
showEmojiPicker () {
this.$refs['textarea'].focus()
this.$refs['emoji-input'].triggerShowPicker()
},
clearError () {
this.error = null
2018-06-07 09:03:50 +00:00
},
changeVis (visibility) {
this.newStatus.visibility = visibility
},
2019-06-18 20:28:31 +00:00
togglePollForm () {
this.pollFormVisible = !this.pollFormVisible
},
setPoll (poll) {
this.newStatus.poll = poll
},
clearPollForm () {
if (this.$refs.pollForm) {
this.$refs.pollForm.clear()
}
},
dismissScopeNotice () {
this.$store.dispatch('setOption', { name: 'hideScopeNotice', value: true })
2020-07-07 06:07:20 +00:00
},
setMediaDescription (id) {
const description = this.newStatus.mediaDescriptions[id]
if (!description || description.trim() === '') return
return statusPoster.setMediaDescription({ store: this.$store, id, description })
},
setAllMediaDescriptions () {
const ids = this.newStatus.files.map(file => file.id)
return Promise.all(ids.map(id => this.setMediaDescription(id)))
2016-10-30 15:53:58 +00:00
}
}
}
export default PostStatusForm