Page MenuHomePhorge

No OneTemporary

Size
674 KB
Referenced Files
None
Subscribers
None
This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/changelog.d/chat_vew.add b/changelog.d/chat_vew.add
new file mode 100644
index 0000000000..7e649d454f
--- /dev/null
+++ b/changelog.d/chat_vew.add
@@ -0,0 +1 @@
+Chat view for threads
diff --git a/src/App.js b/src/App.js
index 934b967131..4ce6f1abcc 100644
--- a/src/App.js
+++ b/src/App.js
@@ -1,306 +1,310 @@
import { throttle } from 'lodash'
import { mapState } from 'pinia'
import { defineAsyncComponent } from 'vue'
import DesktopNav from 'src/components/desktop_nav/desktop_nav.vue'
import FeaturesPanel from 'src/components/features_panel/features_panel.vue'
import GlobalError from 'src/components/global_error/global_error.vue'
import GlobalNoticeList from 'src/components/global_notice_list/global_notice_list.vue'
import InstanceSpecificPanel from 'src/components/instance_specific_panel/instance_specific_panel.vue'
import MobileNav from 'src/components/mobile_nav/mobile_nav.vue'
import MobilePostStatusButton from 'src/components/mobile_post_status_button/mobile_post_status_button.vue'
import NavPanel from 'src/components/nav_panel/nav_panel.vue'
import UserPanel from 'src/components/user_panel/user_panel.vue'
import { getOrCreateServiceWorker } from './services/sw/sw'
import { windowHeight, windowWidth } from './services/window_utils/window_utils'
import { useEmojiStore } from 'src/stores/emoji.js'
import { useI18nStore } from 'src/stores/i18n.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
import { useInterfaceStore } from 'src/stores/interface.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useShoutStore } from 'src/stores/shout.js'
// Helper to unwrap reactive proxies
window.toValue = (x) => JSON.parse(JSON.stringify(x))
export default {
name: 'app',
components: {
UserPanel,
NavPanel,
Notifications: defineAsyncComponent(
() => import('src/components/notifications/notifications.vue'),
),
InstanceSpecificPanel,
FeaturesPanel,
WhoToFollowPanel: defineAsyncComponent(
() =>
import('src/components/who_to_follow_panel/who_to_follow_panel.vue'),
),
ShoutPanel: defineAsyncComponent(
() => import('src/components/shout_panel/shout_panel.vue'),
),
MediaModal: defineAsyncComponent(
() => import('src/components/media_modal/media_modal.vue'),
),
MobilePostStatusButton,
MobileNav,
DesktopNav,
SettingsModal: defineAsyncComponent(
() => import('src/components/settings_modal/settings_modal.vue'),
),
UpdateNotification: defineAsyncComponent(
() =>
import('src/components/update_notification/update_notification.vue'),
),
PostStatusModal: defineAsyncComponent(
() => import('src/components/post_status_modal/post_status_modal.vue'),
),
UserReportingModal: defineAsyncComponent(
() =>
import('src/components/user_reporting_modal/user_reporting_modal.vue'),
),
EditStatusModal: defineAsyncComponent(
() => import('src/components/edit_status_modal/edit_status_modal.vue'),
),
StatusHistoryModal: defineAsyncComponent(
() =>
import('src/components/status_history_modal/status_history_modal.vue'),
),
GlobalError,
GlobalNoticeList,
},
data: () => ({
mobileActivePanel: 'timeline',
}),
provide() {
return {
allowNonSquareEmoji: useMergedConfigStore().mergedConfig.nonSquareEmoji,
}
},
watch: {
themeApplied() {
this.removeSplash()
},
currentTheme() {
this.setThemeBodyClass()
},
layoutType() {
document.getElementById('modal').classList = ['-' + this.layoutType]
},
},
created() {
// Load the locale from the storage
const value = useMergedConfigStore().mergedConfig.interfaceLanguage
useI18nStore().setLanguage(value)
useEmojiStore().loadUnicodeEmojiData(value)
document.getElementById('modal').classList = ['-' + this.layoutType]
// Create bound handlers
this.updateScrollState = throttle(this.scrollHandler, 200)
this.updateMobileState = throttle(this.resizeHandler, 200)
},
mounted() {
window.addEventListener('resize', this.updateMobileState)
this.scrollParent.addEventListener('scroll', this.updateScrollState)
if (this.themeApplied) {
this.setThemeBodyClass()
this.removeSplash()
}
getOrCreateServiceWorker()
},
unmounted() {
window.removeEventListener('resize', this.updateMobileState)
this.scrollParent.removeEventListener('scroll', this.updateScrollState)
},
computed: {
currentTheme() {
if (this.styleDataUsed) {
const styleMeta = this.styleDataUsed.find(
(x) => x.component === '@meta',
)
if (styleMeta !== undefined) {
return styleMeta.directives.name.replaceAll(' ', '-').toLowerCase()
}
}
return 'stock'
},
layoutModalClass() {
return '-' + this.layoutType
},
classes() {
return [
{
'-reverse': this.reverseLayout,
'-no-sticky-headers': this.noSticky,
'-has-new-post-button': this.newPostButtonShown,
},
'-' + this.layoutType,
]
},
navClasses() {
const { navbarColumnStretch } = useMergedConfigStore().mergedConfig
return [
'-' + this.layoutType,
...(navbarColumnStretch ? ['-column-stretch'] : []),
]
},
currentUser() {
return this.$store.state.users.currentUser
},
userBackground() {
return this.currentUser.background_image
},
foreignProfileBackground() {
return (
useMergedConfigStore().mergedConfig.allowForeignUserBackground &&
useInterfaceStore().foreignProfileBackground
)
},
instanceBackground() {
return useMergedConfigStore().mergedConfig.hideInstanceWallpaper
? null
: this.instanceBackgroundUrl
},
background() {
return (
this.foreignProfileBackground ||
this.userBackground ||
this.instanceBackground
)
},
bgStyle() {
if (this.background) {
return {
'--body-background-image': `url(${this.background})`,
}
}
},
shoutJoined() {
return useShoutStore().joined
},
isChats() {
- return this.$route.name === 'chat' || this.$route.name === 'chats'
+ return (
+ this.$route.name === 'chat' ||
+ this.$route.name === 'chats' ||
+ this.$route.name === 'conversation2'
+ )
},
isListEdit() {
return this.$route.name === 'lists-edit'
},
newPostButtonShown() {
if (this.isChats) return false
if (this.isListEdit) return false
return (
useMergedConfigStore().mergedConfig.alwaysShowNewPostButton ||
this.layoutType === 'mobile'
)
},
shoutboxPosition() {
return (
useMergedConfigStore().mergedConfig.alwaysShowNewPostButton || false
)
},
hideShoutbox() {
- return useMergedConfigStore().mergedConfig.hideShoutbox
+ return this.isChats || useMergedConfigStore().mergedConfig.hideShoutbox
},
reverseLayout() {
const { thirdColumnMode, sidebarRight: reverseSetting } =
useMergedConfigStore().mergedConfig
if (this.layoutType !== 'wide') {
return reverseSetting
} else {
return thirdColumnMode === 'notifications'
? reverseSetting
: !reverseSetting
}
},
noSticky() {
return useMergedConfigStore().mergedConfig.disableStickyHeaders
},
showScrollbars() {
return useMergedConfigStore().mergedConfig.showScrollbars
},
scrollParent() {
return window /* this.$refs.appContentRef */
},
showInstanceSpecificPanel() {
return (
this.instanceSpecificPanelPresent &&
!useMergedConfigStore().mergedConfig.hideISP
)
},
...mapState(useMergedConfigStore, ['mergedConfig']),
...mapState(useInterfaceStore, [
'themeApplied',
'styleDataUsed',
'layoutType',
]),
...mapState(useInstanceStore, ['styleDataUsed']),
...mapState(useInstanceCapabilitiesStore, [
'suggestionsEnabled',
'editingAvailable',
]),
...mapState(useInstanceStore, {
instanceBackgroundUrl: (store) => store.instanceIdentity.background,
showFeaturesPanel: (store) => store.instanceIdentity.showFeaturesPanel,
instanceSpecificPanelPresent: (store) =>
store.instanceIdentity.showInstanceSpecificPanel &&
store.instanceIdentity.instanceSpecificPanelContent,
}),
},
methods: {
resizeHandler() {
useInterfaceStore().setLayoutWidth(windowWidth())
useInterfaceStore().setLayoutHeight(windowHeight())
},
scrollHandler() {
const scrollPosition =
this.scrollParent === window
? window.scrollY
: this.scrollParent.scrollTop
if (scrollPosition != 0) {
this.$refs.appContentRef.classList.add(['-scrolled'])
} else {
this.$refs.appContentRef.classList.remove(['-scrolled'])
}
},
setThemeBodyClass() {
const themeName = this.currentTheme
const classList = Array.from(document.body.classList)
const oldTheme = classList.filter((c) => c.startsWith('theme-'))
if (themeName !== null && themeName !== '') {
const newTheme = `theme-${themeName.toLowerCase()}`
// remove old theme reference if there are any
if (oldTheme.length) {
document.body.classList.replace(oldTheme[0], newTheme)
} else {
document.body.classList.add(newTheme)
}
} else {
// remove theme reference if non-V3 theme is used
document.body.classList.remove(...oldTheme)
}
},
removeSplash() {
document.querySelector('#status').textContent = this.$t(
'splash.fun_' + Math.ceil(Math.random() * 4),
)
const splashscreenRoot = document.querySelector('#splash')
splashscreenRoot.addEventListener('transitionend', () => {
splashscreenRoot.remove()
})
setTimeout(() => {
splashscreenRoot.remove() // forcibly remove it, should fix my plasma browser widget t. HJ
}, 600)
splashscreenRoot.classList.add('hidden')
document.querySelector('#app').classList.remove('hidden')
},
},
}
diff --git a/src/api/chats.js b/src/api/chats.js
index 114038e528..5d766dec40 100644
--- a/src/api/chats.js
+++ b/src/api/chats.js
@@ -1,87 +1,94 @@
import { paramsString, promisedRequest } from './helpers.js'
-import { parseChat } from 'src/services/entity_normalizer/entity_normalizer.service.js'
+import {
+ parseChat,
+ parseChatMessage,
+} from 'src/services/entity_normalizer/entity_normalizer.service.js'
const PLEROMA_CHATS_URL = '/api/v1/pleroma/chats'
const PLEROMA_CHAT_URL = (id) => `/api/v1/pleroma/chats/by-account-id/${id}`
const PLEROMA_CHAT_MESSAGES_URL = (id, { maxId, sinceId, limit } = {}) =>
`/api/v1/pleroma/chats/${id}/messages${paramsString({ maxId, sinceId, limit })}`
const PLEROMA_CHAT_READ_URL = (id) => `/api/v1/pleroma/chats/${id}/read`
const PLEROMA_DELETE_CHAT_MESSAGE_URL = (chatId, messageId) =>
`/api/v1/pleroma/chats/${chatId}/messages/${messageId}`
export const chats = ({ credentials }) =>
promisedRequest({
url: PLEROMA_CHATS_URL,
credentials,
}).then(({ data }) => ({
- chatList: data.map(parseChat).filter((c) => c),
+ data: data.map(parseChat).filter((c) => c),
}))
export const getOrCreateChat = ({ accountId, credentials }) =>
promisedRequest({
url: PLEROMA_CHAT_URL(accountId),
method: 'POST',
credentials,
- })
+ }).then(({ data }) => ({ data: parseChat(data) }))
export const chatMessages = ({
id,
credentials,
maxId,
sinceId,
limit = 20,
}) => {
return promisedRequest({
url: PLEROMA_CHAT_MESSAGES_URL(id, { maxId, sinceId, limit }),
method: 'GET',
credentials,
- })
+ }).then(({ data }) => ({
+ data: data.map(parseChatMessage).filter((c) => c),
+ }))
}
export const sendChatMessage = ({
id,
content,
mediaId = null,
idempotencyKey,
credentials,
}) => {
const payload = {
content,
}
if (mediaId) {
payload.media_id = mediaId
}
const headers = {}
if (idempotencyKey) {
headers['idempotency-key'] = idempotencyKey
}
return promisedRequest({
url: PLEROMA_CHAT_MESSAGES_URL(id),
method: 'POST',
payload,
credentials,
headers,
- })
+ }).then(({ data }) => ({
+ data: parseChatMessage(data),
+ }))
}
export const readChat = ({ id, lastReadId, credentials }) =>
promisedRequest({
url: PLEROMA_CHAT_READ_URL(id),
method: 'POST',
payload: {
last_read_id: lastReadId,
},
credentials,
})
export const deleteChatMessage = ({ chatId, messageId, credentials }) =>
promisedRequest({
url: PLEROMA_DELETE_CHAT_MESSAGE_URL(chatId, messageId),
method: 'DELETE',
credentials,
})
diff --git a/src/api/user.js b/src/api/user.js
index aa111e305b..b4b6fafa9f 100644
--- a/src/api/user.js
+++ b/src/api/user.js
@@ -1,921 +1,921 @@
import { concat, last } from 'lodash'
import { paramsString, promisedRequest } from './helpers.js'
import { fetchFriends, MASTODON_STATUS_URL } from './public.js'
import {
parseAttachment,
parseStatus,
parseUser,
} from 'src/services/entity_normalizer/entity_normalizer.service.js'
const MUTES_IMPORT_URL = '/api/pleroma/mutes_import'
const BLOCKS_IMPORT_URL = '/api/pleroma/blocks_import'
const FOLLOW_IMPORT_URL = '/api/pleroma/follow_import'
const DELETE_ACCOUNT_URL = '/api/pleroma/delete_account'
const CHANGE_EMAIL_URL = '/api/pleroma/change_email'
const CHANGE_PASSWORD_URL = '/api/pleroma/change_password'
const MOVE_ACCOUNT_URL = '/api/pleroma/move_account'
const ALIASES_URL = '/api/pleroma/aliases'
const NOTIFICATION_SETTINGS_URL = '/api/pleroma/notification_settings'
const NOTIFICATION_READ_URL = '/api/v1/pleroma/notifications/read'
const MFA_SETTINGS_URL = '/api/pleroma/accounts/mfa'
const MFA_BACKUP_CODES_URL = '/api/pleroma/accounts/mfa/backup_codes'
const MFA_SETUP_OTP_URL = '/api/pleroma/accounts/mfa/setup/totp'
const MFA_CONFIRM_OTP_URL = '/api/pleroma/accounts/mfa/confirm/totp'
const MFA_DISABLE_OTP_URL = '/api/pleroma/accounts/mfa/totp'
const MASTODON_DISMISS_NOTIFICATION_URL = (id) =>
`/api/v1/notifications/${id}/dismiss`
const MASTODON_FAVORITE_URL = (id) => `/api/v1/statuses/${id}/favourite`
const MASTODON_UNFAVORITE_URL = (id) => `/api/v1/statuses/${id}/unfavourite`
const MASTODON_RETWEET_URL = (id) => `/api/v1/statuses/${id}/reblog`
const MASTODON_UNRETWEET_URL = (id) => `/api/v1/statuses/${id}/unreblog`
const MASTODON_DELETE_URL = (id) => `/api/v1/statuses/${id}`
const MASTODON_FOLLOW_URL = (id) => `/api/v1/accounts/${id}/follow`
const MASTODON_UNFOLLOW_URL = (id) => `/api/v1/accounts/${id}/unfollow`
const MASTODON_FOLLOW_REQUESTS_URL = '/api/v1/follow_requests'
const MASTODON_APPROVE_USER_URL = (id) =>
`/api/v1/follow_requests/${id}/authorize`
const MASTODON_DENY_USER_URL = (id) => `/api/v1/follow_requests/${id}/reject`
const MASTODON_USER_RELATIONSHIPS_URL = ({ id, withSuspended }) =>
`/api/v1/accounts/relationships/${paramsString({ id, withSuspended })}`
const MASTODON_USER_IN_LISTS = (id) => `/api/v1/accounts/${id}/lists`
export const MASTODON_LIST_URL = (id = '') => `/api/v1/lists/${id}`
export const MASTODON_LIST_ACCOUNTS_URL = (id) => `/api/v1/lists/${id}/accounts`
const MASTODON_USER_BLOCKS_URL = ({
maxId,
sinceId,
limit,
withRelationships,
}) =>
`/api/v1/blocks/${paramsString({ maxId, sinceId, limit, withRelationships })}`
const MASTODON_USER_MUTES_URL = ({
maxId,
sinceId,
limit,
withRelationships,
}) =>
`/api/v1/mutes/${paramsString({ maxId, sinceId, limit, withRelationships })}`
const MASTODON_BLOCK_USER_URL = (id) => `/api/v1/accounts/${id}/block`
const MASTODON_UNBLOCK_USER_URL = (id) => `/api/v1/accounts/${id}/unblock`
const MASTODON_MUTE_USER_URL = (id) => `/api/v1/accounts/${id}/mute`
const MASTODON_UNMUTE_USER_URL = (id) => `/api/v1/accounts/${id}/unmute`
const MASTODON_REMOVE_USER_FROM_FOLLOWERS = (id) =>
`/api/v1/accounts/${id}/remove_from_followers`
const MASTODON_USER_NOTE_URL = (id) => `/api/v1/accounts/${id}/note`
const MASTODON_BOOKMARK_STATUS_URL = (id) => `/api/v1/statuses/${id}/bookmark`
const MASTODON_UNBOOKMARK_STATUS_URL = (id) =>
`/api/v1/statuses/${id}/unbookmark`
const MASTODON_POST_STATUS_URL = '/api/v1/statuses'
const MASTODON_MEDIA_UPLOAD_URL = '/api/v1/media'
const MASTODON_VOTE_URL = (id) => `/api/v1/polls/${id}/votes`
const MASTODON_PROFILE_UPDATE_URL = '/api/v1/accounts/update_credentials'
const MASTODON_REPORT_USER_URL = '/api/v1/reports'
const MASTODON_PIN_OWN_STATUS = (id) => `/api/v1/statuses/${id}/pin`
const MASTODON_UNPIN_OWN_STATUS = (id) => `/api/v1/statuses/${id}/unpin`
const MASTODON_MUTE_CONVERSATION = (id) => `/api/v1/statuses/${id}/mute`
const MASTODON_UNMUTE_CONVERSATION = (id) => `/api/v1/statuses/${id}/unmute`
const MASTODON_DOMAIN_BLOCKS_URL = '/api/v1/domain_blocks'
const MASTODON_ANNOUNCEMENTS_URL = '/api/v1/announcements'
const MASTODON_ANNOUNCEMENTS_DISMISS_URL = (id) =>
`/api/v1/announcements/${id}/dismiss`
const PLEROMA_EMOJI_REACT_URL = (id, emoji) =>
`/api/v1/pleroma/statuses/${id}/reactions/${emoji}`
const PLEROMA_EMOJI_UNREACT_URL = (id, emoji) =>
`/api/v1/pleroma/statuses/${id}/reactions/${emoji}`
const PLEROMA_BACKUP_URL = '/api/v1/pleroma/backups'
const PLEROMA_BOOKMARK_FOLDERS_URL = '/api/v1/pleroma/bookmark_folders'
const PLEROMA_BOOKMARK_FOLDER_URL = (id) =>
`/api/v1/pleroma/bookmark_folders/${id}`
// #Posts
export const favorite = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_FAVORITE_URL(id),
method: 'POST',
credentials,
}).then(({ data, ...rest }) => ({ ...rest, data: parseStatus(data) }))
export const unfavorite = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_UNFAVORITE_URL(id),
method: 'POST',
credentials,
}).then(({ data, ...rest }) => ({ ...rest, data: parseStatus(data) }))
export const retweet = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_RETWEET_URL(id),
method: 'POST',
credentials,
}).then(({ data, ...rest }) => ({ ...rest, data: parseStatus(data) }))
export const unretweet = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_UNRETWEET_URL(id),
method: 'POST',
credentials,
}).then(({ data, ...rest }) => ({ ...rest, data: parseStatus(data) }))
export const reactWithEmoji = ({ id, emoji, credentials }) =>
promisedRequest({
url: PLEROMA_EMOJI_REACT_URL(id, emoji),
method: 'PUT',
credentials,
}).then(({ data, ...rest }) => ({ ...rest, data: parseStatus(data) }))
export const unreactWithEmoji = ({ id, emoji, credentials }) =>
promisedRequest({
url: PLEROMA_EMOJI_UNREACT_URL(id, emoji),
method: 'DELETE',
credentials,
}).then(({ data, ...rest }) => ({ ...rest, data: parseStatus(data) }))
export const bookmarkStatus = ({ id, credentials, ...options }) =>
promisedRequest({
url: MASTODON_BOOKMARK_STATUS_URL(id),
credentials,
method: 'POST',
payload: {
folder_id: options.folder_id,
},
})
export const unbookmarkStatus = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_UNBOOKMARK_STATUS_URL(id),
credentials,
method: 'POST',
})
export const pinOwnStatus = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_PIN_OWN_STATUS(id),
credentials,
method: 'POST',
}).then(({ data, ...rest }) => ({ ...rest, data: parseStatus(data) }))
export const unpinOwnStatus = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_UNPIN_OWN_STATUS(id),
credentials,
method: 'POST',
}).then(({ data, ...rest }) => ({ ...rest, data: parseStatus(data) }))
export const muteConversation = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_MUTE_CONVERSATION(id),
credentials,
method: 'POST',
}).then(({ data, ...rest }) => ({ ...rest, data: parseStatus(data) }))
export const unmuteConversation = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_UNMUTE_CONVERSATION(id),
credentials,
method: 'POST',
}).then(({ data, ...rest }) => ({ ...rest, data: parseStatus(data) }))
export const vote = ({ pollId, choices, credentials }) => {
return promisedRequest({
url: MASTODON_VOTE_URL(encodeURIComponent(pollId)),
method: 'POST',
credentials,
payload: {
choices,
},
})
}
// #Posting
export const postStatus = ({
credentials,
status,
spoilerText,
visibility,
sensitive,
poll,
mediaIds = [],
inReplyToStatusId,
quoteId,
contentType,
preview,
idempotencyKey,
}) => {
const form = new FormData()
- const pollOptions = poll.options || []
+ const pollOptions = poll?.options || []
form.append('status', status)
form.append('source', 'Pleroma FE')
if (spoilerText) form.append('spoiler_text', spoilerText)
if (visibility) form.append('visibility', visibility)
if (sensitive) form.append('sensitive', sensitive)
if (contentType) form.append('content_type', contentType)
mediaIds.forEach((val) => {
form.append('media_ids[]', val)
})
if (pollOptions.some((option) => option !== '')) {
const normalizedPoll = {
expires_in: Number.parseInt(poll.expiresIn, 10),
multiple: poll.multiple,
}
Object.keys(normalizedPoll).forEach((key) => {
form.append(`poll[${key}]`, normalizedPoll[key])
})
pollOptions.forEach((option) => {
form.append('poll[options][]', option)
})
}
if (inReplyToStatusId) {
form.append('in_reply_to_id', inReplyToStatusId)
}
if (quoteId) {
form.append('quote_id', quoteId)
}
if (preview) {
form.append('preview', 'true')
}
const headers = {}
if (idempotencyKey) {
headers['idempotency-key'] = idempotencyKey
}
return promisedRequest({
url: MASTODON_POST_STATUS_URL,
formData: form,
method: 'POST',
credentials,
headers,
}).then(({ data, ...rest }) => ({ ...rest, data: parseStatus(data) }))
}
export const editStatus = ({
id,
credentials,
status,
spoilerText,
sensitive,
poll,
mediaIds = [],
contentType,
}) => {
const form = new FormData()
- const pollOptions = poll.options || []
+ const pollOptions = poll?.options || []
form.append('status', status)
if (spoilerText) form.append('spoiler_text', spoilerText)
if (sensitive) form.append('sensitive', sensitive)
if (contentType) form.append('content_type', contentType)
mediaIds.forEach((val) => {
form.append('media_ids[]', val)
})
if (pollOptions.some((option) => option !== '')) {
const normalizedPoll = {
expires_in: Number.parseInt(poll.expiresIn, 10),
multiple: poll.multiple,
}
Object.keys(normalizedPoll).forEach((key) => {
form.append(`poll[${key}]`, normalizedPoll[key])
})
pollOptions.forEach((option) => {
form.append('poll[options][]', option)
})
}
return promisedRequest({
url: MASTODON_STATUS_URL(id),
formData: form,
method: 'PUT',
credentials,
}).then(({ data, ...rest }) => ({ ...rest, data: parseStatus(data) }))
}
export const deleteStatus = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_DELETE_URL(id),
credentials,
method: 'DELETE',
})
export const uploadMedia = ({ formData, credentials }) =>
promisedRequest({
url: MASTODON_MEDIA_UPLOAD_URL,
formData,
method: 'POST',
credentials,
}).then(({ data, ...rest }) => ({ ...rest, data: parseAttachment(data) }))
export const setMediaDescription = ({ id, description, credentials }) =>
promisedRequest({
url: `${MASTODON_MEDIA_UPLOAD_URL}/${id}`,
method: 'PUT',
credentials,
payload: {
description,
},
}).then(({ data, ...rest }) => ({ ...rest, data: parseAttachment(data) }))
// #Notifications
export const dismissNotification = ({ credentials, id }) =>
promisedRequest({
url: MASTODON_DISMISS_NOTIFICATION_URL(id),
method: 'POST',
payload: { id },
credentials,
})
export const markNotificationsAsSeen = ({
id,
credentials,
single = false,
}) => {
const formData = new FormData()
if (single) {
formData.append('id', id)
} else {
formData.append('max_id', id)
}
return promisedRequest({
url: NOTIFICATION_READ_URL,
formData,
credentials,
method: 'POST',
})
}
// #Announcements
export const getAnnouncements = ({ credentials }) =>
promisedRequest({ url: MASTODON_ANNOUNCEMENTS_URL, credentials })
export const dismissAnnouncement = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_ANNOUNCEMENTS_DISMISS_URL(id),
credentials,
method: 'POST',
})
// #Imports
export const importMutes = ({ file, credentials }) => {
const formData = new FormData()
formData.append('list', file)
return promisedRequest({
url: MUTES_IMPORT_URL,
formData,
method: 'POST',
credentials,
}).then((response) => response.ok)
}
export const importBlocks = ({ file, credentials }) => {
const formData = new FormData()
formData.append('list', file)
return promisedRequest({
url: BLOCKS_IMPORT_URL,
formData,
method: 'POST',
credentials,
}).then((response) => response.ok)
}
export const importFollows = ({ file, credentials }) => {
const formData = new FormData()
formData.append('list', file)
return promisedRequest({
url: FOLLOW_IMPORT_URL,
formData,
method: 'POST',
credentials,
}).then((response) => response.ok)
}
export const exportFriends = ({ id, credentials }) => {
// biome-ignore lint/suspicious/noAsyncPromiseExecutor: TODO refactor this
return new Promise(async (resolve, reject) => {
try {
let friends = []
let more = true
while (more) {
const maxId = friends.length > 0 ? last(friends).id : undefined
const users = await fetchFriends({
id,
maxId,
credentials,
withRelationships: true,
})
friends = concat(friends, users)
if (users.length === 0) {
more = false
}
}
resolve(friends)
} catch (err) {
reject(err)
}
})
}
// #Profile settings
export const updateNotificationSettings = ({ credentials, settings }) => {
return promisedRequest({
url: NOTIFICATION_SETTINGS_URL,
credentials,
method: 'PUT',
payload: settings,
})
}
export const updateProfileImages = ({
credentials,
avatar = null,
avatarName = null,
banner = null,
background = null,
}) => {
const form = new FormData()
if (avatar !== null) {
if (avatarName !== null) {
form.append('avatar', avatar, avatarName)
} else {
form.append('avatar', avatar)
}
}
if (banner !== null) form.append('header', banner)
if (background !== null) form.append('pleroma_background_image', background)
return promisedRequest({
url: MASTODON_PROFILE_UPDATE_URL,
credentials,
method: 'PATCH',
formData: form,
}).then(({ data, ...rest }) => ({ ...rest, data: parseUser(data) }))
}
export const updateProfile = ({ credentials, params }) => {
const formData = new FormData()
for (const name in params) {
if (name === 'fields_attributes') {
params[name].forEach((param, i) => {
formData.append(name + `[${i}][name]`, param.name)
formData.append(name + `[${i}][value]`, param.value)
})
} else {
if (typeof params[name] === 'object') {
console.warn(
'Object detected in updateProfile API call. This will not work, use updateProfileJSON instead.',
)
console.warn('Object:\n' + JSON.stringify(params[name], null, 2))
}
formData.append(name, params[name])
}
}
return promisedRequest({
url: MASTODON_PROFILE_UPDATE_URL,
credentials,
method: 'PATCH',
formData,
}).then(({ data, ...rest }) => ({ ...rest, data: parseUser(data) }))
}
export const updateProfileJSON = ({ credentials, params }) =>
promisedRequest({
url: MASTODON_PROFILE_UPDATE_URL,
credentials,
payload: params,
method: 'PATCH',
}).then(({ data, ...rest }) => ({ ...rest, data: parseUser(data) }))
export const changeEmail = ({ credentials, email, password }) => {
const form = new FormData()
form.append('email', email)
form.append('password', password)
return promisedRequest({
url: CHANGE_EMAIL_URL,
formData: form,
method: 'POST',
credentials,
})
}
export const moveAccount = ({ credentials, password, targetAccount }) => {
const form = new FormData()
form.append('password', password)
form.append('target_account', targetAccount)
return promisedRequest({
url: MOVE_ACCOUNT_URL,
formData: form,
method: 'POST',
credentials,
})
}
export const changePassword = ({
credentials,
password,
newPassword,
newPasswordConfirmation,
}) => {
const form = new FormData()
form.append('password', password)
form.append('new_password', newPassword)
form.append('new_password_confirmation', newPasswordConfirmation)
return promisedRequest({
url: CHANGE_PASSWORD_URL,
formData: form,
method: 'POST',
credentials,
})
}
// #MFA
export const settingsMFA = ({ credentials }) =>
promisedRequest({
url: MFA_SETTINGS_URL,
credentials,
method: 'GET',
})
export const mfaDisableOTP = ({ credentials, password }) => {
const form = new FormData()
form.append('password', password)
return promisedRequest({
url: MFA_DISABLE_OTP_URL,
formData: form,
method: 'DELETE',
credentials,
})
}
export const mfaConfirmOTP = ({ credentials, password, token }) => {
const form = new FormData()
form.append('password', password)
form.append('code', token)
return promisedRequest({
url: MFA_CONFIRM_OTP_URL,
formData: form,
credentials,
method: 'POST',
})
}
export const mfaSetupOTP = ({ credentials }) =>
promisedRequest({
url: MFA_SETUP_OTP_URL,
credentials,
method: 'GET',
})
export const generateMfaBackupCodes = ({ credentials }) =>
promisedRequest({
url: MFA_BACKUP_CODES_URL,
credentials,
method: 'GET',
})
// #Aliases
export const addAlias = ({ credentials, alias }) =>
promisedRequest({
url: ALIASES_URL,
method: 'PUT',
credentials,
payload: { alias },
})
export const deleteAlias = ({ credentials, alias }) =>
promisedRequest({
url: ALIASES_URL,
method: 'DELETE',
credentials,
payload: { alias },
})
export const listAliases = ({ credentials }) =>
promisedRequest({
url: ALIASES_URL,
method: 'GET',
credentials,
params: {
_cacheBooster: Date().now(),
},
})
// User manipulation
export const fetchUserRelationship = ({ id, withSuspended, credentials }) =>
promisedRequest({
url: MASTODON_USER_RELATIONSHIPS_URL({ id, withSuspended }),
credentials,
})
export const followUser = ({ id, credentials, ...options }) => {
const payload = {}
if (options.reblogs !== undefined) {
payload.reblogs = options.reblogs
}
if (options.notify !== undefined) {
payload.notify = options.notify
}
return promisedRequest({
url: MASTODON_FOLLOW_URL(id),
payload,
credentials,
method: 'POST',
})
}
export const unfollowUser = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_UNFOLLOW_URL(id),
credentials,
method: 'POST',
})
export const fetchUserInLists = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_USER_IN_LISTS(id),
credentials,
})
export const removeUserFromFollowers = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_REMOVE_USER_FROM_FOLLOWERS(id),
credentials,
method: 'POST',
})
export const fetchFollowRequests = ({ credentials }) =>
promisedRequest({
url: MASTODON_FOLLOW_REQUESTS_URL,
credentials,
}).then(({ data, ...rest }) => ({ ...rest, data: data.map(parseUser) }))
export const approveUser = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_APPROVE_USER_URL(id),
credentials,
method: 'POST',
})
export const denyUser = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_DENY_USER_URL(id),
credentials,
method: 'POST',
})
export const editUserNote = ({ id, credentials, comment }) =>
promisedRequest({
url: MASTODON_USER_NOTE_URL(id),
credentials,
payload: {
comment,
},
method: 'POST',
})
export const fetchMutes = ({ maxId, credentials }) =>
promisedRequest({
url: MASTODON_USER_MUTES_URL({ maxId, withRelationships: true }),
credentials,
}).then(({ data, ...rest }) => ({ ...rest, data: data.map(parseUser) }))
export const muteUser = ({ id, expiresIn, credentials }) => {
const payload = {}
if (expiresIn) {
payload.expires_in = expiresIn
}
return promisedRequest({
url: MASTODON_MUTE_USER_URL(id),
credentials,
method: 'POST',
payload,
})
}
export const unmuteUser = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_UNMUTE_USER_URL(id),
credentials,
method: 'POST',
})
export const fetchBlocks = ({ maxId, credentials }) =>
promisedRequest({
url: MASTODON_USER_BLOCKS_URL({ maxId, withRelationships: true }),
credentials,
}).then(({ data, ...rest }) => ({ ...rest, data: data.map(parseUser) }))
export const blockUser = ({ id, expiresIn, credentials }) => {
const payload = {}
if (expiresIn) {
payload.duration = expiresIn
}
return promisedRequest({
url: MASTODON_BLOCK_USER_URL(id),
credentials,
method: 'POST',
payload,
})
}
export const unblockUser = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_UNBLOCK_USER_URL(id),
credentials,
method: 'POST',
})
export const reportUser = ({
credentials,
userId,
statusIds,
comment,
forward,
}) =>
promisedRequest({
url: MASTODON_REPORT_USER_URL,
method: 'POST',
payload: {
account_id: userId,
status_ids: statusIds,
comment,
forward,
},
credentials,
})
// #Domain mutes
export const fetchDomainMutes = ({ credentials }) =>
promisedRequest({ url: MASTODON_DOMAIN_BLOCKS_URL, credentials })
export const muteDomain = ({ domain, credentials }) =>
promisedRequest({
url: MASTODON_DOMAIN_BLOCKS_URL,
method: 'POST',
payload: { domain },
credentials,
})
export const unmuteDomain = ({ domain, credentials }) =>
promisedRequest({
url: MASTODON_DOMAIN_BLOCKS_URL,
method: 'DELETE',
payload: { domain },
credentials,
})
// #Backups
export const addBackup = ({ credentials }) =>
promisedRequest({
url: PLEROMA_BACKUP_URL,
method: 'POST',
credentials,
})
export const listBackups = ({ credentials }) =>
promisedRequest({
url: PLEROMA_BACKUP_URL,
method: 'GET',
credentials,
params: {
_cacheBooster: Date().now(),
},
})
// #OAuth
export const fetchOAuthTokens = ({ credentials }) =>
promisedRequest({
url: '/api/oauth_tokens.json',
credentials,
})
export const revokeOAuthToken = ({ id, credentials }) =>
promisedRequest({
url: `/api/oauth_tokens/${id}`,
credentials,
method: 'DELETE',
})
// #Lists
export const fetchLists = ({ credentials }) =>
promisedRequest({
url: MASTODON_LIST_URL(),
credentials,
})
export const createList = ({ title, credentials }) =>
promisedRequest({
url: MASTODON_LIST_URL(),
credentials,
method: 'POST',
payload: { title },
})
export const getList = ({ listId, credentials }) =>
promisedRequest({
url: MASTODON_LIST_URL(listId),
credentials,
})
export const updateList = ({ listId, title, credentials }) =>
promisedRequest({
url: MASTODON_LIST_URL(listId),
credentials,
method: 'PUT',
payload: { title },
})
export const getListAccounts = ({ listId, credentials }) =>
promisedRequest({
url: MASTODON_LIST_ACCOUNTS_URL(listId),
credentials,
}).then((data) => data.map(({ id }) => id))
export const addAccountsToList = ({ listId, accountIds, credentials }) =>
promisedRequest({
url: MASTODON_LIST_ACCOUNTS_URL(listId),
credentials,
method: 'POST',
payload: { account_ids: accountIds },
})
export const removeAccountsFromList = ({ listId, accountIds, credentials }) =>
promisedRequest({
url: MASTODON_LIST_ACCOUNTS_URL(listId),
credentials,
method: 'DELETE',
payload: { account_ids: accountIds },
})
export const deleteList = ({ listId, credentials }) =>
promisedRequest({
url: MASTODON_LIST_URL(listId),
method: 'DELETE',
credentials,
})
// #Bookmarks
export const fetchBookmarkFolders = ({ credentials }) =>
promisedRequest({
url: PLEROMA_BOOKMARK_FOLDERS_URL,
credentials,
})
export const createBookmarkFolder = ({ name, emoji, credentials }) =>
promisedRequest({
url: PLEROMA_BOOKMARK_FOLDERS_URL,
credentials,
method: 'POST',
payload: { name, emoji },
})
export const updateBookmarkFolder = ({ folderId, name, emoji, credentials }) =>
promisedRequest({
url: PLEROMA_BOOKMARK_FOLDER_URL(folderId),
credentials,
method: 'PATCH',
payload: { name, emoji },
})
export const deleteBookmarkFolder = ({ folderId, credentials }) =>
promisedRequest({
url: PLEROMA_BOOKMARK_FOLDER_URL(folderId),
method: 'DELETE',
credentials,
})
// #So long and thanks for all the fish
export const deleteAccount = ({ credentials, password }) => {
const formData = new FormData()
formData.append('password', password)
return promisedRequest({
url: DELETE_ACCOUNT_URL,
formData,
method: 'POST',
credentials,
})
}
diff --git a/src/boot/routes.js b/src/boot/routes.js
index d50baab04e..5897fad921 100644
--- a/src/boot/routes.js
+++ b/src/boot/routes.js
@@ -1,314 +1,271 @@
-import { defineAsyncComponent } from 'vue'
-
import AuthForm from 'src/components/auth_form/auth_form.js'
import BookmarkTimeline from 'src/components/bookmark_timeline/bookmark_timeline.vue'
import BubbleTimeline from 'src/components/bubble_timeline/bubble_timeline.vue'
import ConversationPage from 'src/components/conversation-page/conversation-page.vue'
import DMs from 'src/components/dm_timeline/dm_timeline.vue'
import FriendsTimeline from 'src/components/friends_timeline/friends_timeline.vue'
import NavPanel from 'src/components/nav_panel/nav_panel.vue'
import PublicAndExternalTimeline from 'src/components/public_and_external_timeline/public_and_external_timeline.vue'
import PublicTimeline from 'src/components/public_timeline/public_timeline.vue'
import QuotesTimeline from 'src/components/quotes_timeline/quotes_timeline.vue'
import RemoteUserResolver from 'src/components/remote_user_resolver/remote_user_resolver.vue'
import TagTimeline from 'src/components/tag_timeline/tag_timeline.vue'
import { useInstanceStore } from 'src/stores/instance.js'
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
export default (store) => {
const validateAuthenticatedRoute = (to, from, next) => {
if (store.state.users.currentUser) {
next()
} else {
next(
useInstanceStore().instanceIdentity.redirectRootNoLogin || '/main/all',
)
}
}
let routes = [
{
name: 'root',
path: '/',
redirect: () => {
return (
(store.state.users.currentUser
? useInstanceStore().instanceIdentity.redirectRootLogin
: useInstanceStore().instanceIdentity.redirectRootNoLogin) ||
'/main/all'
)
},
},
{
name: 'public-external-timeline',
path: '/main/all',
component: PublicAndExternalTimeline,
},
{
name: 'public-timeline',
path: '/main/public',
component: PublicTimeline,
},
{
name: 'friends',
path: '/main/friends',
component: FriendsTimeline,
beforeEnter: validateAuthenticatedRoute,
},
{ name: 'tag-timeline', path: '/tag/:tag', component: TagTimeline },
{ name: 'bookmarks', path: '/bookmarks', component: BookmarkTimeline },
{ name: 'bubble', path: '/bubble', component: BubbleTimeline },
{
name: 'conversation',
path: '/notice/:id',
component: ConversationPage,
meta: { dontScroll: true },
},
+ {
+ name: 'conversation2',
+ path: '/conversation/:statusId',
+ component: () => import('src/components/chat_view/chat_view.vue'),
+ props: true,
+ meta: { dontScroll: true },
+ beforeEnter: validateAuthenticatedRoute,
+ },
{ name: 'quotes', path: '/notice/:id/quotes', component: QuotesTimeline },
{
name: 'remote-user-profile-acct',
path: '/remote-users/:_(@)?:username([^/@]+)@:hostname([^/@]+)',
component: RemoteUserResolver,
beforeEnter: validateAuthenticatedRoute,
},
{
name: 'remote-user-profile',
path: '/remote-users/:hostname/:username',
component: RemoteUserResolver,
beforeEnter: validateAuthenticatedRoute,
},
{
name: 'external-user-profile',
path: '/users/$:id',
- component: defineAsyncComponent(
- () => import('src/components/user_profile/user_profile.vue'),
- ),
+ component: () => import('src/components/user_profile/user_profile.vue'),
},
{
name: 'user-profile-admin-view',
path: '/users/$:id/admin_view',
- component: defineAsyncComponent(
- () => import('src/components/user_profile/user_profile_admin_view.vue'),
- ),
+ component: () =>
+ import('src/components/user_profile/user_profile_admin_view.vue'),
},
{
name: 'interactions',
path: '/users/:username/interactions',
- component: defineAsyncComponent(
- () => import('src/components/interactions/interactions.vue'),
- ),
+ component: () => import('src/components/interactions/interactions.vue'),
beforeEnter: validateAuthenticatedRoute,
},
{
name: 'dms',
path: '/users/:username/dms',
component: DMs,
beforeEnter: validateAuthenticatedRoute,
},
{
name: 'registration',
path: '/registration',
- component: defineAsyncComponent(
- () => import('src/components/registration/registration.vue'),
- ),
+ component: () => import('src/components/registration/registration.vue'),
},
{
name: 'password-reset',
path: '/password-reset',
- component: defineAsyncComponent(
- () => import('src/components/password_reset/password_reset.vue'),
- ),
+ component: () =>
+ import('src/components/password_reset/password_reset.vue'),
props: true,
},
{
name: 'registration-token',
path: '/registration/:token',
- component: defineAsyncComponent(
- () => import('src/components/registration/registration.vue'),
- ),
+ component: () => import('src/components/registration/registration.vue'),
},
{
name: 'friend-requests',
path: '/friend-requests',
- component: defineAsyncComponent(
- () => import('src/components/follow_requests/follow_requests.vue'),
- ),
+ component: () =>
+ import('src/components/follow_requests/follow_requests.vue'),
beforeEnter: validateAuthenticatedRoute,
},
{
name: 'notifications',
path: '/:username/notifications',
- component: defineAsyncComponent(
- () => import('src/components/notifications/notifications.vue'),
- ),
+ component: () => import('src/components/notifications/notifications.vue'),
props: () => ({ disableTeleport: true }),
beforeEnter: validateAuthenticatedRoute,
},
{
name: 'login',
path: '/login',
component: AuthForm,
},
{
name: 'shout-panel',
path: '/shout-panel',
- component: defineAsyncComponent(
- () => import('src/components/shout_panel/shout_panel.vue'),
- ),
+ component: () => import('src/components/shout_panel/shout_panel.vue'),
props: () => ({ floating: false }),
},
{
name: 'oauth-callback',
path: '/oauth-callback',
- component: defineAsyncComponent(
- () => import('src/components/oauth_callback/oauth_callback.vue'),
- ),
+ component: () =>
+ import('src/components/oauth_callback/oauth_callback.vue'),
props: (route) => ({ code: route.query.code }),
},
{
name: 'search',
path: '/search',
- component: defineAsyncComponent(
- () => import('src/components/search/search.vue'),
- ),
+ component: () => import('src/components/search/search.vue'),
props: (route) => ({ query: route.query.query }),
},
{
name: 'who-to-follow',
path: '/who-to-follow',
- component: defineAsyncComponent(
- () => import('src/components/who_to_follow/who_to_follow.vue'),
- ),
+ component: () => import('src/components/who_to_follow/who_to_follow.vue'),
beforeEnter: validateAuthenticatedRoute,
},
{
name: 'about',
path: '/about',
- component: defineAsyncComponent(
- () => import('src/components/about/about.vue'),
- ),
+ component: () => import('src/components/about/about.vue'),
},
{
name: 'announcements',
path: '/announcements',
- component: defineAsyncComponent(
- () =>
- import('src/components/announcements_page/announcements_page.vue'),
- ),
+ component: () =>
+ import('src/components/announcements_page/announcements_page.vue'),
},
{
name: 'drafts',
path: '/drafts',
- component: defineAsyncComponent(
- () => import('src/components/drafts/drafts.vue'),
- ),
+ component: () => import('src/components/drafts/drafts.vue'),
},
{
name: 'user-profile',
path: '/users/:name',
- component: defineAsyncComponent(
- () => import('src/components/user_profile/user_profile.vue'),
- ),
+ component: () => import('src/components/user_profile/user_profile.vue'),
},
{
name: 'legacy-user-profile',
path: '/:name',
- component: defineAsyncComponent(
- () => import('src/components/user_profile/user_profile.vue'),
- ),
+ component: () => import('src/components/user_profile/user_profile.vue'),
},
{
name: 'lists',
path: '/lists',
- component: defineAsyncComponent(
- () => import('src/components/lists/lists.vue'),
- ),
+ component: () => import('src/components/lists/lists.vue'),
},
{
name: 'lists-timeline',
path: '/lists/:id',
- component: defineAsyncComponent(
- () => import('src/components/lists_timeline/lists_timeline.vue'),
- ),
+ component: () =>
+ import('src/components/lists_timeline/lists_timeline.vue'),
},
{
name: 'lists-edit',
path: '/lists/:id/edit',
- component: defineAsyncComponent(
- () => import('src/components/lists_edit/lists_edit.vue'),
- ),
+ component: () => import('src/components/lists_edit/lists_edit.vue'),
},
{
name: 'lists-new',
path: '/lists/new',
- component: defineAsyncComponent(
- () => import('src/components/lists_edit/lists_edit.vue'),
- ),
+ component: () => import('src/components/lists_edit/lists_edit.vue'),
},
{
name: 'edit-navigation',
path: '/nav-edit',
component: NavPanel,
props: () => ({ forceExpand: true, forceEditMode: true }),
beforeEnter: validateAuthenticatedRoute,
},
{
name: 'bookmark-folders',
path: '/bookmark_folders',
- component: defineAsyncComponent(
- () => import('src/components/bookmark_folders/bookmark_folders.vue'),
- ),
+ component: () =>
+ import('src/components/bookmark_folders/bookmark_folders.vue'),
},
{
name: 'bookmark-folder-new',
path: '/bookmarks/new-folder',
- component: defineAsyncComponent(
- () =>
- import(
- 'src/components/bookmark_folder_edit/bookmark_folder_edit.vue'
- ),
- ),
+ component: () =>
+ import('src/components/bookmark_folder_edit/bookmark_folder_edit.vue'),
},
{
name: 'bookmark-folder',
path: '/bookmarks/:id',
component: BookmarkTimeline,
},
{
name: 'bookmark-folder-edit',
path: '/bookmarks/:id/edit',
- component: defineAsyncComponent(
- () =>
- import(
- 'src/components/bookmark_folder_edit/bookmark_folder_edit.vue'
- ),
- ),
+ component: () =>
+ import('src/components/bookmark_folder_edit/bookmark_folder_edit.vue'),
},
]
if (useInstanceCapabilitiesStore().pleromaChatMessagesAvailable) {
routes = routes.concat([
{
name: 'chat',
- path: '/users/:username/chats/:recipient_id',
- component: defineAsyncComponent(
- () => import('src/components/chat/chat.vue'),
- ),
+ path: '/users/:username/chats/:chatUserId',
+ component: () => import('src/components/chat_view/chat_view.vue'),
meta: { dontScroll: false },
+ props: true,
beforeEnter: validateAuthenticatedRoute,
},
{
name: 'chats',
path: '/users/:username/chats',
- component: defineAsyncComponent(
- () => import('src/components/chat_list/chat_list.vue'),
- ),
+ component: () => import('src/components/chat_list/chat_list.vue'),
meta: { dontScroll: false },
beforeEnter: validateAuthenticatedRoute,
},
])
}
return routes
}
diff --git a/src/components/chat/chat.js b/src/components/chat/chat.js
deleted file mode 100644
index 6ac51902b7..0000000000
--- a/src/components/chat/chat.js
+++ /dev/null
@@ -1,433 +0,0 @@
-import { throttle } from 'lodash'
-import { mapState as mapPiniaState } from 'pinia'
-import { mapGetters, mapState } from 'vuex'
-
-import ChatMessage from 'src/components/chat_message/chat_message.vue'
-import ChatTitle from 'src/components/chat_title/chat_title.vue'
-import PostStatusForm from 'src/components/post_status_form/post_status_form.vue'
-import chatService from '../../services/chat_service/chat_service.js'
-import { buildFakeMessage } from '../../services/chat_utils/chat_utils.js'
-import { promiseInterval } from '../../services/promise_interval/promise_interval.js'
-import {
- getNewTopPosition,
- getScrollPosition,
- isBottomedOut,
- isScrollable,
-} from './chat_layout_utils.js'
-
-import { useInterfaceStore } from 'src/stores/interface.js'
-import { useMergedConfigStore } from 'src/stores/merged_config.js'
-import { useOAuthStore } from 'src/stores/oauth.js'
-
-import {
- chatMessages,
- getOrCreateChat,
- sendChatMessage,
-} from 'src/api/chats.js'
-import { WSConnectionStatus } from 'src/api/websocket.js'
-
-import { library } from '@fortawesome/fontawesome-svg-core'
-import { faChevronDown, faChevronLeft } from '@fortawesome/free-solid-svg-icons'
-
-library.add(faChevronDown, faChevronLeft)
-
-const BOTTOMED_OUT_OFFSET = 10
-const JUMP_TO_BOTTOM_BUTTON_VISIBILITY_OFFSET = 10
-const SAFE_RESIZE_TIME_OFFSET = 100
-const MARK_AS_READ_DELAY = 1500
-const MAX_RETRIES = 10
-
-const Chat = {
- components: {
- ChatMessage,
- ChatTitle,
- PostStatusForm,
- },
- data() {
- return {
- jumpToBottomButtonVisible: false,
- hoveredMessageChainId: undefined,
- lastScrollPosition: {},
- scrollableContainerHeight: '100%',
- errorLoadingChat: false,
- messageRetriers: {},
- }
- },
- created() {
- this.startFetching()
- window.addEventListener('resize', this.handleResize)
- },
- mounted() {
- window.addEventListener('scroll', this.handleScroll)
- if (document.hidden !== undefined) {
- document.addEventListener(
- 'visibilitychange',
- this.handleVisibilityChange,
- false,
- )
- }
-
- this.$nextTick(() => {
- this.handleResize()
- })
- },
- unmounted() {
- window.removeEventListener('scroll', this.handleScroll)
- window.removeEventListener('resize', this.handleResize)
- if (document.hidden !== undefined)
- document.removeEventListener(
- 'visibilitychange',
- this.handleVisibilityChange,
- false,
- )
- this.$store.dispatch('clearCurrentChat')
- },
- computed: {
- recipient() {
- return this.currentChat && this.currentChat.account
- },
- recipientId() {
- return this.$route.params.recipient_id
- },
- formPlaceholder() {
- if (this.recipient) {
- return this.$t('chats.message_user', {
- nickname: this.recipient.screen_name_ui,
- })
- } else {
- return ''
- }
- },
- chatViewItems() {
- return chatService.getView(this.currentChatMessageService)
- },
- newMessageCount() {
- return (
- this.currentChatMessageService &&
- this.currentChatMessageService.newMessageCount
- )
- },
- streamingEnabled() {
- return (
- this.mergedConfig.useStreamingApi &&
- this.mastoUserSocketStatus === WSConnectionStatus.JOINED
- )
- },
- ...mapGetters([
- 'currentChat',
- 'currentChatMessageService',
- 'findOpenedChatByRecipientId',
- ]),
- ...mapPiniaState(useMergedConfigStore, ['mergedConfig']),
- ...mapPiniaState(useInterfaceStore, {
- mobileLayout: (store) => store.layoutType === 'mobile',
- }),
- ...mapState({
- mastoUserSocketStatus: (state) => state.api.mastoUserSocketStatus,
- currentUser: (state) => state.users.currentUser,
- }),
- },
- watch: {
- chatViewItems() {
- // We don't want to scroll to the bottom on a new message when the user is viewing older messages.
- // Therefore we need to know whether the scroll position was at the bottom before the DOM update.
- const bottomedOutBeforeUpdate = this.bottomedOut(BOTTOMED_OUT_OFFSET)
- this.$nextTick(() => {
- if (bottomedOutBeforeUpdate) {
- this.scrollDown()
- }
- })
- },
- $route: function () {
- this.startFetching()
- },
- mastoUserSocketStatus(newValue) {
- if (newValue === WSConnectionStatus.JOINED) {
- this.fetchChat({ isFirstFetch: true })
- }
- },
- },
- methods: {
- // Used to animate the avatar near the first message of the message chain when any message belonging to the chain is hovered
- onMessageHover({ isHovered, messageChainId }) {
- this.hoveredMessageChainId = isHovered ? messageChainId : undefined
- },
- onFilesDropped() {
- this.$nextTick(() => {
- this.handleResize()
- })
- },
- handleVisibilityChange() {
- this.$nextTick(() => {
- if (!document.hidden && this.bottomedOut(BOTTOMED_OUT_OFFSET)) {
- this.scrollDown({ forceRead: true })
- }
- })
- },
- // "Sticks" scroll to bottom instead of top, helps with OSK resizing the viewport
- handleResize(opts = {}) {
- const { delayed = false } = opts
-
- if (delayed) {
- setTimeout(() => {
- this.handleResize({ ...opts, delayed: false })
- }, SAFE_RESIZE_TIME_OFFSET)
- return
- }
-
- this.$nextTick(() => {
- const { offsetHeight = undefined } = getScrollPosition()
- const diff = offsetHeight - this.lastScrollPosition.offsetHeight
- if (diff !== 0 && !this.bottomedOut()) {
- this.$nextTick(() => {
- window.scrollBy({ top: -Math.trunc(diff) })
- })
- }
- this.lastScrollPosition = getScrollPosition()
- })
- },
- scrollDown(options = {}) {
- const { behavior = 'auto', forceRead = false } = options
- this.$nextTick(() => {
- window.scrollTo({
- top: document.documentElement.scrollHeight,
- behavior,
- })
- })
- if (forceRead) {
- this.readChat()
- }
- },
- readChat() {
- if (
- !(
- this.currentChatMessageService && this.currentChatMessageService.maxId
- )
- ) {
- return
- }
- if (document.hidden) {
- return
- }
- const lastReadId = this.currentChatMessageService.maxId
- this.$store.dispatch('readChat', {
- id: this.currentChat.id,
- lastReadId,
- })
- },
- bottomedOut(offset) {
- return isBottomedOut(offset)
- },
- reachedTop() {
- return window.scrollY <= 0
- },
- cullOlderCheck() {
- window.setTimeout(() => {
- if (this.bottomedOut(JUMP_TO_BOTTOM_BUTTON_VISIBILITY_OFFSET)) {
- this.$store.dispatch(
- 'cullOlderMessages',
- this.currentChatMessageService.chatId,
- )
- }
- }, 5000)
- },
- handleScroll: throttle(function () {
- this.lastScrollPosition = getScrollPosition()
- if (!this.currentChat) {
- return
- }
-
- if (this.reachedTop()) {
- this.fetchChat({ maxId: this.currentChatMessageService.minId })
- } else if (this.bottomedOut(JUMP_TO_BOTTOM_BUTTON_VISIBILITY_OFFSET)) {
- this.jumpToBottomButtonVisible = false
- this.cullOlderCheck()
- if (this.newMessageCount > 0) {
- // Use a delay before marking as read to prevent situation where new messages
- // arrive just as you're leaving the view and messages that you didn't actually
- // get to see get marked as read.
- window.setTimeout(() => {
- // Don't mark as read if the element doesn't exist, user has left chat view
- if (this.$el) this.readChat()
- }, MARK_AS_READ_DELAY)
- }
- } else {
- this.jumpToBottomButtonVisible = true
- }
- }, 200),
- handleScrollUp(positionBeforeLoading) {
- const positionAfterLoading = getScrollPosition()
- window.scrollTo({
- top: getNewTopPosition(positionBeforeLoading, positionAfterLoading),
- })
- },
- fetchChat({ isFirstFetch = false, fetchLatest = false, maxId }) {
- const chatMessageService = this.currentChatMessageService
- if (!chatMessageService) {
- return
- }
- if (fetchLatest && this.streamingEnabled) {
- return
- }
-
- const chatId = chatMessageService.chatId
- const fetchOlderMessages = !!maxId
- const sinceId = fetchLatest && chatMessageService.maxId
-
- return chatMessages({
- id: chatId,
- maxId,
- sinceId,
- credentials: useOAuthStore().token,
- }).then(({ data: messages }) => {
- // Clear the current chat in case we're recovering from a ws connection loss.
- if (isFirstFetch) {
- chatService.clear(chatMessageService)
- }
-
- const positionBeforeUpdate = getScrollPosition()
- this.$store
- .dispatch('addChatMessages', { chatId, messages })
- .then(() => {
- this.$nextTick(() => {
- if (fetchOlderMessages) {
- this.handleScrollUp(positionBeforeUpdate)
- }
-
- // In vertical screens, the first batch of fetched messages may not always take the
- // full height of the scrollable container.
- // If this is the case, we want to fetch the messages until the scrollable container
- // is fully populated so that the user has the ability to scroll up and load the history.
- if (!isScrollable() && messages.length > 0) {
- this.fetchChat({
- maxId: this.currentChatMessageService.minId,
- })
- }
- })
- })
- })
- },
- async startFetching() {
- let chat = this.findOpenedChatByRecipientId(this.recipientId)
- if (!chat) {
- try {
- const { data } = await getOrCreateChat({
- accountId: this.recipientId,
- credentials: useOAuthStore().token,
- })
- chat = data
- } catch (e) {
- console.error('Error creating or getting a chat', e)
- this.errorLoadingChat = true
- }
- }
- if (chat) {
- this.$nextTick(() => {
- this.scrollDown({ forceRead: true })
- })
- this.$store.dispatch('addOpenedChat', { chat })
- this.doStartFetching()
- }
- },
- doStartFetching() {
- this.$store.dispatch('startFetchingCurrentChat', {
- fetcher: () =>
- promiseInterval(() => this.fetchChat({ fetchLatest: true }), 5000),
- })
- this.fetchChat({ isFirstFetch: true })
- },
- handleAttachmentPosting() {
- this.$nextTick(() => {
- this.handleResize()
- // When the posting form size changes because of a media attachment, we need an extra resize
- // to account for the potential delay in the DOM update.
- this.scrollDown({ forceRead: true })
- })
- },
- sendMessage({ status, media, idempotencyKey }) {
- const params = {
- id: this.currentChat.id,
- content: status,
- idempotencyKey,
- }
-
- if (media[0]) {
- params.mediaId = media[0].id
- }
-
- const fakeMessage = buildFakeMessage({
- attachments: media,
- chatId: this.currentChat.id,
- content: status,
- userId: this.currentUser.id,
- idempotencyKey,
- })
-
- this.$store
- .dispatch('addChatMessages', {
- chatId: this.currentChat.id,
- messages: [fakeMessage],
- })
- .then(() => {
- this.handleAttachmentPosting()
- })
-
- return this.doSendMessage({
- params,
- fakeMessage,
- retriesLeft: MAX_RETRIES,
- })
- },
- doSendMessage({ params, fakeMessage, retriesLeft = MAX_RETRIES }) {
- if (retriesLeft <= 0) return
-
- sendChatMessage({
- ...params,
- credentials: useOAuthStore().token,
- })
- .then(({ data }) => {
- this.$store.dispatch('addChatMessages', {
- chatId: this.currentChat.id,
- updateMaxId: false,
- messages: [{ ...data, fakeId: fakeMessage.id }],
- })
-
- return data
- })
- .catch((error) => {
- console.error('Error sending message', error)
- this.$store.dispatch('handleMessageError', {
- chatId: this.currentChat.id,
- fakeId: fakeMessage.id,
- isRetry: retriesLeft !== MAX_RETRIES,
- })
- if (
- (error.statusCode >= 500 && error.statusCode < 600) ||
- error.message === 'Failed to fetch'
- ) {
- this.messageRetriers[fakeMessage.id] = setTimeout(
- () => {
- this.doSendMessage({
- params,
- fakeMessage,
- retriesLeft: retriesLeft - 1,
- })
- },
- 1000 * 2 ** (MAX_RETRIES - retriesLeft),
- )
- }
- return {}
- })
-
- return Promise.resolve(fakeMessage)
- },
- goBack() {
- this.$router.push({
- name: 'chats',
- params: { username: this.currentUser.screen_name },
- })
- },
- },
-}
-
-export default Chat
diff --git a/src/components/chat/chat.vue b/src/components/chat/chat.vue
deleted file mode 100644
index cedbdce694..0000000000
--- a/src/components/chat/chat.vue
+++ /dev/null
@@ -1,99 +0,0 @@
-<template>
- <div class="chat-view">
- <div class="chat-view-inner">
- <div
- ref="inner"
- class="panel-default panel chat-view-body"
- >
- <div
- ref="header"
- class="panel-heading -sticky chat-view-heading"
- >
- <button
- class="button-unstyled go-back-button"
- @click="goBack"
- >
- <FAIcon
- size="lg"
- icon="chevron-left"
- />
- </button>
- <div class="title text-center">
- <ChatTitle
- :user="recipient"
- :with-avatar="true"
- />
- </div>
- </div>
- <div
- class="chat-message-list message-list"
- :style="{ height: scrollableContainerHeight }"
- >
- <template v-if="!errorLoadingChat">
- <ChatMessage
- v-for="chatViewItem in chatViewItems"
- :key="chatViewItem.id"
- :author="recipient"
- :chat-view-item="chatViewItem"
- :hovered-message-chain="chatViewItem.messageChainId === hoveredMessageChainId"
- @hover="onMessageHover"
- />
- </template>
- <div
- v-else
- class="chat-loading-error"
- >
- <div class="alert error">
- {{ $t('chats.error_loading_chat') }}
- </div>
- </div>
- </div>
- <div
- ref="footer"
- class="panel-body footer"
- >
- <div
- class="jump-to-bottom-button"
- :class="{ 'visible': jumpToBottomButtonVisible }"
- @click="scrollDown({ behavior: 'smooth' })"
- >
- <span>
- <FAIcon icon="chevron-down" />
- <div
- v-if="newMessageCount"
- class="badge -notification unread-chat-count unread-message-count"
- >
- {{ newMessageCount }}
- </div>
- </span>
- </div>
- <PostStatusForm
- :disable-subject="true"
- :disable-scope-selector="true"
- :disable-notice="true"
- :disable-lock-warning="true"
- :disable-polls="true"
- :disable-quotes="true"
- :disable-sensitivity-checkbox="true"
- :disable-submit="errorLoadingChat || !currentChat"
- :disable-preview="true"
- :disable-draft="true"
- :optimistic-posting="true"
- :post-handler="sendMessage"
- :submit-on-enter="!mobileLayout"
- :preserve-focus="!mobileLayout"
- :auto-focus="!mobileLayout"
- :placeholder="formPlaceholder"
- :file-limit="1"
- max-height="160"
- emoji-picker-placement="top"
- @resize="handleResize"
- />
- </div>
- </div>
- </div>
- </div>
-</template>
-
-<script src="./chat.js"></script>
-<style src="./chat.scss" lang="scss" />
diff --git a/src/components/chat_list/chat_list.js b/src/components/chat_list/chat_list.js
index 597fcc7093..446ccb70a5 100644
--- a/src/components/chat_list/chat_list.js
+++ b/src/components/chat_list/chat_list.js
@@ -1,38 +1,41 @@
-import { mapGetters, mapState } from 'vuex'
+import { mapState as mapPiniaState } from 'pinia'
+import { mapState } from 'vuex'
import ChatListItem from 'src/components/chat_list_item/chat_list_item.vue'
import ChatNew from 'src/components/chat_new/chat_new.vue'
import List from 'src/components/list/list.vue'
+import { useChatsStore } from 'src/stores/chats.js'
+
const ChatList = {
components: {
ChatListItem,
List,
ChatNew,
},
computed: {
...mapState({
currentUser: (state) => state.users.currentUser,
}),
- ...mapGetters(['sortedChatList']),
+ ...mapPiniaState(useChatsStore, ['sortedChatList']),
},
data() {
return {
isNew: false,
}
},
created() {
- this.$store.dispatch('fetchChats', { latest: true })
+ useChatsStore().fetchChats()
},
methods: {
cancelNewChat() {
this.isNew = false
- this.$store.dispatch('fetchChats', { latest: true })
+ useChatsStore().fetchChats()
},
newChat() {
this.isNew = true
},
},
}
export default ChatList
diff --git a/src/components/chat_list_item/chat_list_item.js b/src/components/chat_list_item/chat_list_item.js
index 3bbb93d609..c95895def2 100644
--- a/src/components/chat_list_item/chat_list_item.js
+++ b/src/components/chat_list_item/chat_list_item.js
@@ -1,71 +1,71 @@
import { mapState } from 'vuex'
import AvatarList from 'src/components/avatar_list/avatar_list.vue'
import ChatTitle from 'src/components/chat_title/chat_title.vue'
import StatusBody from 'src/components/status_content/status_content.vue'
import Timeago from 'src/components/timeago/timeago.vue'
import UserAvatar from 'src/components/user_avatar/user_avatar.vue'
const ChatListItem = {
name: 'ChatListItem',
props: ['chat'],
components: {
UserAvatar,
AvatarList,
Timeago,
ChatTitle,
StatusBody,
},
computed: {
...mapState({
currentUser: (state) => state.users.currentUser,
}),
attachmentInfo() {
if (this.chat.lastMessage.attachments.length === 0) {
return
}
const types = this.chat.lastMessage.attachments.map((file) => file.type)
if (types.includes('video')) {
return this.$t('file_type.video')
} else if (types.includes('audio')) {
return this.$t('file_type.audio')
} else if (types.includes('image')) {
return this.$t('file_type.image')
} else {
return this.$t('file_type.file')
}
},
messageForStatusContent() {
const message = this.chat.lastMessage
const messageEmojis = message ? message.emojis : []
const isYou = message && message.account_id === this.currentUser.id
const content = message ? this.attachmentInfo || message.content : ''
const messagePreview = isYou
? `<i>${this.$t('chats.you')}</i> ${content}`
: content
return {
summary: '',
emojis: messageEmojis,
raw_html: messagePreview,
text: messagePreview,
attachments: [],
}
},
},
methods: {
openChat() {
if (this.chat.id) {
this.$router.push({
name: 'chat',
params: {
username: this.currentUser.screen_name,
- recipient_id: this.chat.account.id,
+ chatUserId: this.chat.account.id,
},
})
}
},
},
}
export default ChatListItem
diff --git a/src/components/chat_message/chat_message.js b/src/components/chat_message/chat_message.js
index 2066a81942..78be870b47 100644
--- a/src/components/chat_message/chat_message.js
+++ b/src/components/chat_message/chat_message.js
@@ -1,116 +1,223 @@
import { mapState as mapPiniaState } from 'pinia'
+import { defineAsyncComponent } from 'vue'
import { mapState } from 'vuex'
import Attachment from 'src/components/attachment/attachment.vue'
import ChatMessageDate from 'src/components/chat_message_date/chat_message_date.vue'
+import EmojiReactions from 'src/components/emoji_reactions/emoji_reactions.vue'
import Gallery from 'src/components/gallery/gallery.vue'
import LinkPreview from 'src/components/link-preview/link-preview.vue'
+import MentionLink from 'src/components/mention_link/mention_link.vue'
import Popover from 'src/components/popover/popover.vue'
+import StatusActionButtons from 'src/components/status_action_buttons/status_action_buttons.vue'
+import StatusBody from 'src/components/status_body/status_body.vue'
import StatusContent from 'src/components/status_content/status_content.vue'
+import StatusPopover from 'src/components/status_popover/status_popover.vue'
+import Timeago from 'src/components/timeago/timeago.vue'
import UserAvatar from 'src/components/user_avatar/user_avatar.vue'
import UserPopover from 'src/components/user_popover/user_popover.vue'
import { useInstanceStore } from 'src/stores/instance.js'
import { useInterfaceStore } from 'src/stores/interface'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { library } from '@fortawesome/fontawesome-svg-core'
-import { faEllipsisH, faTimes } from '@fortawesome/free-solid-svg-icons'
+import {
+ faCircleNotch,
+ faEllipsisH,
+ faReply,
+ faRetweet,
+ faStar,
+ faTimes,
+} from '@fortawesome/free-solid-svg-icons'
-library.add(faTimes, faEllipsisH)
+library.add(faTimes, faEllipsisH, faCircleNotch, faReply, faStar, faRetweet)
const ChatMessage = {
name: 'ChatMessage',
props: [
- 'author',
'edited',
'noHeading',
- 'chatViewItem',
+ 'previousItem',
+ 'chatItem',
+ 'previousItem',
'hoveredMessageChain',
+ 'focused',
+ 'repliedTo',
],
- emits: ['hover'],
+ emits: ['hover', 'replyRequested'],
components: {
Popover,
Attachment,
StatusContent,
+ StatusBody,
+ StatusActionButtons,
UserAvatar,
Gallery,
LinkPreview,
ChatMessageDate,
+ EmojiReactions,
UserPopover,
+ StatusPopover,
+ MentionLink,
+ Quote: defineAsyncComponent(() => import('src/components/quote/quote.vue')),
+ Timeago,
},
computed: {
- // Returns HH:MM (hours and minutes) in local time.
- createdAt() {
- const time = this.chatViewItem.data.created_at
- return time.toLocaleTimeString('en', {
- hour: '2-digit',
- minute: '2-digit',
- hour12: false,
- })
+ isMessage() {
+ return this.chatItem.type === 'message'
+ },
+ message() {
+ if (!this.isMessage) return null
+ return this.chatItem.data.retweeted_status ?? this.chatItem.data
+ },
+ isStatus() {
+ // ChatMessage only has account_id while Status has full user data
+ return !!this.message.user
+ },
+ authorId() {
+ return this.isStatus ? this.message.user.id : this.message.account_id
+ },
+ author() {
+ return this.$store.getters.findUser(this.authorId)
},
isCurrentUser() {
- return this.message.account_id === this.currentUser.id
+ // mini-hack/optimizaiton:
+ // - current user would always be in memory so if user is missing it's obviously not us
+ // - if anon views page then "us" pretty much doesn't exist
+ if (!this.author || !this.currentUser) return false
+ return this.author.id === this.currentUser.id
},
- message() {
- return this.chatViewItem.data
+
+ // Reply stuff
+ isCustomReply() {
+ if (!this.previousItem) return false
+ if (!this.message.in_reply_to_status_id) return false
+ return this.previousItem.data.id !== this.message.in_reply_to_status_id
},
- isMessage() {
- return this.chatViewItem.type === 'message'
+ isBrokenReply() {
+ if (!this.previousItem) return false
+ return !this.message.in_reply_to_status_id
+ },
+ customReplyTo() {
+ return this.$store.state.statuses.allStatusesObject[
+ this.message.in_reply_to_status_id
+ ]
},
+ replyToName() {
+ if (this.message.in_reply_to_screen_name) {
+ return this.message.in_reply_to_screen_name
+ } else {
+ const user = this.$store.getters.findUser(
+ this.message.in_reply_to_user_id,
+ )
+ return user && user.screen_name_ui
+ }
+ },
+ replyProfileLink() {
+ if (this.isCustomReply) {
+ const user = this.$store.getters.findUser(
+ this.message.in_reply_to_user_id,
+ )
+ // FIXME Why user not found sometimes???
+ return user ? user.statusnet_profile_url : 'NOT_FOUND'
+ }
+ },
+
+ // Quote stuff
+ quoteId() {
+ return this.message.quote_id
+ },
+ quoteUrl() {
+ return this.message.quote_url
+ },
+ quoteVisible() {
+ return this.message.quote_visible
+ },
+
+ // Content
messageForStatusContent() {
return {
+ ...this.message,
summary: '',
emojis: this.message.emojis,
- raw_html: this.message.content || '',
+ raw_html: this.message.content || this.message.raw_html || '',
text: this.message.content || '',
- attachments: this.message.attachments,
}
},
hasAttachment() {
return this.message.attachments.length > 0
},
- ...mapPiniaState(useInterfaceStore, {
- betterShadow: (store) => store.browserSupport.cssFilter,
- }),
- ...mapState({
- currentUser: (state) => state.users.currentUser,
- restrictedNicknames: (state) => useInstanceStore().restrictedNicknames,
- }),
+
+ // Stylistic
+ classnames() {
+ return {
+ '-outgoing': this.isCurrentUser,
+ '-incoming': !this.isCurrentUser,
+ '-pending': this.message.pending,
+ '-focused': this.focused,
+ }
+ },
popoverMarginStyle() {
if (this.isCurrentUser) {
return {}
} else {
return { left: 50 }
}
},
- ...mapPiniaState(useMergedConfigStore, ['mergedConfig', 'findUser']),
+
+ // Global stuff
+ ...mapPiniaState(useInterfaceStore, {
+ betterShadow: (store) => store.browserSupport.cssFilter,
+ }),
+ ...mapState({
+ currentUser: (state) => state.users.currentUser,
+ restrictedNicknames: (state) => useInstanceStore().restrictedNicknames,
+ }),
+ ...mapPiniaState(useMergedConfigStore, ['mergedConfig']),
},
data() {
return {
hovered: false,
menuOpened: false,
}
},
methods: {
onHover(bool) {
this.$emit('hover', {
isHovered: bool,
- messageChainId: this.chatViewItem.messageChainId,
+ messageChainId: this.chatItem.messageChainId,
})
},
+ visibilityIcon(visibility) {
+ switch (visibility) {
+ case 'private':
+ return 'lock'
+ case 'unlisted':
+ return 'lock-open'
+ case 'direct':
+ return 'envelope'
+ case 'local':
+ return 'igloo'
+ default:
+ return 'globe'
+ }
+ },
+ visibilityLocalized() {
+ return this.$i18n.t('general.scope_in_timeline.' + this.status.visibility)
+ },
async deleteMessage() {
const confirmed = window.confirm(this.$t('chats.delete_confirm'))
if (confirmed) {
- await this.$store.dispatch('deleteChatMessage', {
- messageId: this.chatViewItem.data.id,
- chatId: this.chatViewItem.data.chat_id,
+ await this.$emit('delete', {
+ messageId: this.message.id,
+ chatId: this.message.chat_id,
})
}
this.hovered = false
this.menuOpened = false
},
},
}
export default ChatMessage
diff --git a/src/components/chat_message/chat_message.scss b/src/components/chat_message/chat_message.scss
index c058f8172e..e23ca3bd04 100644
--- a/src/components/chat_message/chat_message.scss
+++ b/src/components/chat_message/chat_message.scss
@@ -1,146 +1,218 @@
.chat-message-wrapper {
&.hovered-message-chain {
.animated.Avatar {
canvas {
display: none;
}
img {
visibility: visible;
}
}
}
- .chat-message-menu {
+ .attachments {
+ min-width: 10em;
+ }
+
+ .quoted-post {
+ margin-bottom: 1.5em;
+ }
+
+ .chat-message-toolbar {
transition: opacity 0.1s;
opacity: 0;
position: absolute;
top: -0.8em;
+ right: 0.4rem;
+ z-index: 1;
- button {
+ .quick-action-buttons {
+ justify-items: end;
+ grid-template-columns: auto auto auto;
+ }
+
+ .simple-button {
padding-top: 0.2em;
padding-bottom: 0.2em;
}
+
+ &.-visible {
+ opacity: 1;
+ }
}
.menu-icon {
cursor: pointer;
}
+ .reply-to-header {
+ display: flex;
+ gap: 0.5rem;
+ align-items: center;
+ padding: 0.125em 0;
+ width: 100%;
+ }
+
+ .avatar-spacer {
+ flex: 0 0 2.2rem;
+ width: 2.2rem;
+ }
+
.popover {
width: 12em;
}
.chat-message {
display: flex;
- padding-bottom: 0.5em;
.status-body:hover {
--_still-image-img-visibility: visible;
--_still-image-canvas-visibility: hidden;
--_still-image-label-visibility: hidden;
}
}
.avatar-wrapper {
- margin-right: 0.72em;
- width: 32px;
+ margin-right: 0.5em;
}
.link-preview,
.attachments {
margin-bottom: 1em;
}
.status {
background-color: var(--background);
color: var(--text);
border-radius: var(--roundness);
display: flex;
padding: 0.75em;
border: 1px solid var(--border);
}
.created-at {
position: relative;
float: right;
font-size: 0.8em;
margin: -1em 0 -0.5em;
font-style: italic;
- opacity: 0.8;
}
.without-attachment {
.message-content {
// TODO figure out how to do it properly
.RichContent::after {
margin-right: 5.4em;
content: " ";
display: inline-block;
}
}
}
.pending {
.status-content.media-body,
.created-at {
color: var(--faint);
}
}
.error {
.status-content.media-body,
.created-at {
color: var(--badgeNotification);
}
}
+ .message-bubble-wrapper {
+ display: flex;
+ }
+
.chat-message-inner {
display: flex;
flex-direction: column;
align-items: flex-start;
- max-width: 80%;
- min-width: 10em;
- width: 100%;
}
- .outgoing {
+ .end-spacer {
+ flex: 1 1 0;
+ min-width: calc(2.2rem + 0.5rem + 2rem);
+ }
+
+ .reply-indicator {
display: flex;
- flex-flow: row wrap;
- place-content: end flex-end;
+ place-items: center;
+ place-content: center;
+ padding: 0.25em;
+ width: 1em;
+ margin: var(--roundness) 0;
+ background: var(--border);
+ border-radius: var(--roundness);
+ border: 1px solid var(--border);
- .chat-message-inner {
- align-items: flex-end;
+ + .end-spacer {
+ // Compensate for reply indicator
+ min-width: calc(2.2rem + 0.5rem + 2rem - (1rem + (1px + 0.25rem) * 2));
}
+ }
- .chat-message-menu {
- right: 0.4rem;
+ &.-incoming {
+ .reply-indicator {
+ border-bottom-left-radius: 0;
+ border-top-left-radius: 0;
}
}
- .incoming {
- .chat-message-menu {
- left: 0.4rem;
+ .reply-to-popover {
+ white-space: nowrap;
+ }
+
+ .reply-label {
+ white-space: nowrap;
+ }
+
+ &.-outgoing {
+ &,
+ .message-bubble-wrapper,
+ .chat-message{
+ flex-direction: row-reverse;
+ }
+
+ .reply-to-header {
+ justify-content: end;
+ }
+
+ .reply-indicator {
+ border-bottom-right-radius: 0;
+ border-top-right-radius: 0;
+
+ .icon {
+ transform: scaleX(-1);
+ }
+ }
+
+ .chat-message-inner {
+ align-items: flex-end;
}
}
.chat-message-inner.with-media {
width: 100%;
.status {
width: 100%;
}
}
.visible {
opacity: 1;
}
}
.chat-message-date-separator {
text-align: center;
- margin: 1.4em 0;
font-size: 0.9em;
+ line-height: 2;
user-select: none;
color: var(--textFaint);
}
diff --git a/src/components/chat_message/chat_message.style.js b/src/components/chat_message/chat_message.style.js
index f7632bc6f9..67f0ae6c12 100644
--- a/src/components/chat_message/chat_message.style.js
+++ b/src/components/chat_message/chat_message.style.js
@@ -1,22 +1,31 @@
export default {
name: 'ChatMessage',
selector: '.chat-message',
variants: {
outgoing: '.outgoing',
},
+ states: {
+ focused: '.-focused',
+ },
validInnerComponents: ['Text', 'Icon', 'Border', 'PollGraph'],
defaultRules: [
{
directives: {
background: '--bg, 2',
backgroundNoCssColor: 'yes',
},
},
{
variant: 'outgoing',
directives: {
background: '--bg, 5',
},
},
+ {
+ state: ['focused'],
+ directives: {
+ background: '--inheritedBackground, 10',
+ },
+ },
],
}
diff --git a/src/components/chat_message/chat_message.vue b/src/components/chat_message/chat_message.vue
index 22e2e8eb86..b772a9b20c 100644
--- a/src/components/chat_message/chat_message.vue
+++ b/src/components/chat_message/chat_message.vue
@@ -1,102 +1,241 @@
<template>
<div
v-if="isMessage"
class="chat-message-wrapper"
- :class="{ 'hovered-message-chain': hoveredMessageChain }"
+ :class="[classnames, { 'hovered-message-chain': hoveredMessageChain }]"
+ :id="`chatmessage-${message.id}`"
@mouseover="onHover(true)"
@mouseleave="onHover(false)"
>
+ <i18n-t
+ v-if="isStatus && (isCustomReply || isBrokenReply)"
+ keypath="status.reply_to_with_arg"
+ scope="global"
+ tag="small"
+ class="reply-to-header faint"
+ >
+ <template #replyToWithIcon>
+ <div class="avatar-spacer" />
+ <StatusPopover
+ v-if="!isBrokenReply"
+ :status-id="customReplyTo?.id"
+ class="reply-to-popover"
+ :class="{ '-strikethrough': !message.parent_visible }"
+ >
+ <i18n-t
+ keypath="status.reply_to_with_icon"
+ scope="global"
+ >
+ <template #icon>
+ <FAIcon
+ class="fa-scale-110"
+ icon="reply"
+ flip="horizontal"
+ />
+ </template>
+ <template #replyTo>
+ <span class="reply-label">
+ {{ $t('status.reply_to') }}
+ </span>
+ </template>
+ </i18n-t>
+ </StatusPopover>
+ <span v-else class="reply-label">
+ {{ $t('status.broken_reply') }}
+ </span>
+ </template>
+ <template #user>
+ <MentionLink
+ class="reply-body"
+ :content="replyToName"
+ :url="replyProfileLink"
+ :user-id="message.in_reply_to_user_id"
+ :user-screen-name="message.in_reply_to_screen_name"
+ />
+ <!-- v-if is there because status might not be loaded yet -->
+ <template v-if="customReplyTo && customReplyTo.text.trim().length > 0">
+ :
+ <StatusBody
+ class="reply-body faint"
+ :status="customReplyTo"
+ collapse
+ single-line
+ ignore-subject
+ />
+ </template>
+ </template>
+ </i18n-t>
<div
class="chat-message"
- :class="[{ 'outgoing': isCurrentUser, 'incoming': !isCurrentUser }]"
+ :class="classnames"
>
<div
v-if="!isCurrentUser"
class="avatar-wrapper"
>
<UserPopover
- v-if="chatViewItem.isHead"
- :user-id="author.id"
+ v-if="chatItem.isHead"
+ :user-id="authorId"
>
<UserAvatar
+ v-if="author"
:compact="true"
:user="author"
/>
</UserPopover>
+ <div v-else class="avatar-spacer" />
</div>
<div class="chat-message-inner">
- <div
- class="status-body"
- :style="{ 'min-width': message.attachment ? '80%' : '' }"
- >
+ <div class="message-bubble-wrapper">
<div
- class="media status"
- :class="{ 'without-attachment': !hasAttachment, 'pending': chatViewItem.data.pending, 'error': chatViewItem.data.error }"
- style="position: relative;"
- @mouseenter="hovered = true"
- @mouseleave="hovered = false"
+ class="status-body"
+ :style="{ 'min-width': message.attachment ? '80%' : '' }"
>
<div
- class="chat-message-menu"
- :class="{ 'visible': hovered || menuOpened }"
+ class="media status"
+ :class="{ 'without-attachment': !hasAttachment, 'pending': chatItem.data.pending, 'error': chatItem.data.error }"
+ style="position: relative;"
+ @mouseenter="hovered = true"
+ @mouseleave="hovered = false"
>
- <Popover
- trigger="click"
- placement="top"
- bound-to-selector=".chat-view-inner"
- :bound-to="{ x: 'container' }"
- :margin="popoverMarginStyle"
- @show="menuOpened = true"
- @close="menuOpened = false"
+
+ <StatusActionButtons
+ v-if="isStatus"
+ class="chat-message-toolbar"
+ :class="{ '-visible': hovered || menuOpened }"
+ :status="message"
+ :pinned="new Set(['reply', 'emoji'])"
+ fixed-pinned
+ use-default-buttons
+ hide-labels
+ in-chat-view
+ @toggle-replying="$emit('replyRequested', message)"
+ />
+ <div
+ class="chat-message-toolbar"
+ :class="{ '-visible': hovered || menuOpened }"
+ v-else
>
- <template #content>
- <div class="dropdown-menu">
- <div class="menu-item dropdown-item -icon">
- <button
- class="main-button"
- @click="deleteMessage"
- >
- <FAIcon icon="times" /> {{ $t("chats.delete") }}
- </button>
+ <Popover
+ trigger="click"
+ :trigger-attrs="{ 'class': 'button-default menu-icon simple-button', title: $t('chats.more') }"
+ placement="top"
+ :margin="popoverMarginStyle"
+ @show="menuOpened = true"
+ @close="menuOpened = false"
+ >
+ <template #content>
+ <div class="dropdown-menu">
+ <div class="menu-item dropdown-item -icon">
+ <button
+ class="main-button"
+ @click="deleteMessage"
+ >
+ <FAIcon icon="times" /> {{ $t("chats.delete") }}
+ </button>
+ </div>
</div>
- </div>
- </template>
- <template #trigger>
- <button
- class="button-default menu-icon"
- :title="$t('chats.more')"
- >
+ </template>
+ <template #trigger>
<FAIcon icon="ellipsis-h" />
- </button>
+ </template>
+ </Popover>
+ </div>
+ <StatusContent
+ class="message-content"
+ :class="{ faint: message.pending }"
+ :status="messageForStatusContent"
+ :full-content="true"
+ >
+ <template #footer>
+ <EmojiReactions
+ v-if="isStatus"
+ :status="message"
+ />
+ <Quote
+ v-if="isStatus"
+ class="quoted-post"
+ :status-id="quoteId"
+ :status-url="quoteUrl"
+ :status-visible="quoteVisible"
+ initially-expanded
+ />
+ <span
+ class="created-at"
+ >
+ <span
+ v-if="message.favorited"
+ >
+ <FAIcon
+ class="fa-scale-110"
+ icon="star"
+ fixed-width
+ />
+ </span>
+ <span
+ v-if="message.repeated"
+ >
+ <FAIcon
+ class="fa-scale-110"
+ icon="retweet"
+ fixed-width
+ />
+ </span>
+ <span
+ v-if="message.visibility"
+ class="visibility-icon"
+ :title="visibilityLocalized"
+ >
+ <FAIcon
+ class="fa-scale-110"
+ :icon="visibilityIcon(message.visibility)"
+ fixed-width
+ />
+ </span>
+ <span
+ v-if="message.pending"
+ class="loading-spinner"
+ >
+ <FAIcon
+ class="fa-old-padding"
+ icon="circle-notch"
+ spin
+ />
+ </span>
+ {{ ' ' }}
+ <router-link
+ class="timeago faint"
+ :to="{ name: 'conversation2', params: { statusId: message.id } }"
+ >
+ <Timeago
+ :time="message.created_at"
+ :auto-update="60"
+ />
+ </router-link>
+ </span>
</template>
- </Popover>
+ </StatusContent>
</div>
- <StatusContent
- class="message-content"
- :status="messageForStatusContent"
- :full-content="true"
- >
- <template #footer>
- <span
- class="created-at"
- >
- {{ createdAt }}
- </span>
- </template>
- </StatusContent>
</div>
+ <div
+ v-if="isStatus && repliedTo"
+ class="reply-indicator"
+ >
+ <FAIcon class="icon" icon="reply" />
+ </div>
+ <div class="end-spacer" />
</div>
</div>
</div>
</div>
<div
v-else
class="chat-message-date-separator"
>
- <ChatMessageDate :date="chatViewItem.date" />
+ <ChatMessageDate :date="chatItem.date" :show-time="chatItem.isTime" />
</div>
</template>
<script src="./chat_message.js"></script>
<style src="./chat_message.scss" lang="scss" />
diff --git a/src/components/chat_message_date/chat_message_date.vue b/src/components/chat_message_date/chat_message_date.vue
index f0cadb6e75..6c1be505bc 100644
--- a/src/components/chat_message_date/chat_message_date.vue
+++ b/src/components/chat_message_date/chat_message_date.vue
@@ -1,29 +1,41 @@
<template>
<time>
{{ displayDate }}
</time>
</template>
<script>
+import { useMergedConfigStore } from 'src/stores/merged_config.js'
+
import localeService from 'src/services/locale/locale.service.js'
export default {
name: 'Timeago',
- props: ['date'],
+ props: ['date', 'showTime'],
computed: {
+ time12hFormat() {
+ return useMergedConfigStore().mergedConfig.absoluteTimeFormat12h === '12h'
+ },
displayDate() {
const today = new Date()
today.setHours(0, 0, 0, 0)
if (this.date.getTime() === today.getTime()) {
return this.$t('display_date.today')
} else {
- return this.date.toLocaleDateString(
- localeService.internalToBrowserLocale(this.$i18n.locale),
- { day: 'numeric', month: 'long' },
- )
+ if (this.showTime) {
+ return this.date.toLocaleTimeString(
+ localeService.internalToBrowserLocale(this.$i18n.locale),
+ { hour12: this.time12hFormat, hour: 'numeric', minute: 'numeric' },
+ )
+ } else {
+ return this.date.toLocaleDateString(
+ localeService.internalToBrowserLocale(this.$i18n.locale),
+ { day: 'numeric', month: 'long' },
+ )
+ }
}
},
},
}
</script>
diff --git a/src/components/chat_message_list/chat_message_list.js b/src/components/chat_message_list/chat_message_list.js
new file mode 100644
index 0000000000..a51e6a0e44
--- /dev/null
+++ b/src/components/chat_message_list/chat_message_list.js
@@ -0,0 +1,135 @@
+import { orderBy, uniqueId } from 'lodash'
+
+import ChatMessage from 'src/components/chat_message/chat_message.vue'
+
+const ChatMessageList = {
+ components: {
+ ChatMessage,
+ },
+ props: {
+ messages: Array,
+ pendingMessages: {
+ type: Array,
+ required: false,
+ default: [],
+ },
+ headerDate: Boolean,
+ focusedId: String,
+ repliedId: String,
+ },
+ data() {
+ return {
+ hoveredMessageChainId: undefined,
+ }
+ },
+ emits: ['messageDelete', 'replyRequested'],
+ computed: {
+ chatItems() {
+ const messages = [
+ ...orderBy(this.messages, ['pending', 'id'], ['asc', 'asc']),
+ ...this.pendingMessages.map((m) => ({ ...m, pending: true })),
+ ]
+ return messages
+ .reduceRight((acc, message, index) => {
+ const date = new Date(message.created_at)
+
+ const olderMessage = messages[index - 1]
+ const newerItem = acc[acc.length - 1]
+
+ const diff = olderMessage
+ ? message.created_at - olderMessage.created_at
+ : null
+
+ const MAX_DIFF = 1000 * 60 * 5 // 5 minutes
+
+ const dateDiffs = (() => {
+ if (olderMessage) {
+ const newerDate = new Date(message.created_at)
+ const olderDate = new Date(olderMessage.created_at)
+
+ newerDate.setHours(0, 0, 0, 0)
+ olderDate.setHours(0, 0, 0, 0)
+
+ return newerDate.toISOString() !== olderDate.toISOString()
+ } else {
+ return true
+ }
+ })()
+
+ const chatItem = {
+ type: 'message',
+ data: message,
+ date,
+ id: message.id,
+ isTail: true,
+ isHead: true,
+ }
+
+ if (newerItem == null) {
+ chatItem.messageChainId = uniqueId()
+ } else {
+ if (newerItem.type === 'date') {
+ chatItem.messageChainId = uniqueId()
+ } else if (newerItem.type === 'message') {
+ const newerUser =
+ newerItem.data.account_id || newerItem.data.user.id
+ const olderUser = message.account_id || message.user.id
+ if (newerUser !== olderUser) {
+ chatItem.messageChainId = uniqueId()
+ } else {
+ chatItem.messageChainId = newerItem.messageChainId
+ chatItem.isTail = false
+ newerItem.isHead = false
+ }
+ }
+ }
+
+ if (diff > MAX_DIFF || (!olderMessage && this.headerDate)) {
+ return [
+ ...acc,
+ chatItem,
+ {
+ type: 'date',
+ date,
+ isDate: dateDiffs,
+ isTime: diff > MAX_DIFF && !dateDiffs,
+ id: date.getTime().toString(),
+ },
+ ]
+ } else {
+ return [...acc, chatItem]
+ }
+ }, [])
+ .reverse()
+ },
+ },
+ methods: {
+ onMessageHover({ isHovered, messageChainId }) {
+ this.hoveredMessageChainId = isHovered ? messageChainId : undefined
+ },
+ onMessageDelete({ messageId, chatId }) {
+ this.$emit('messageDelete', { messageId, chatId })
+ },
+ onReplyRequested(message) {
+ this.$emit('replyRequested', message)
+ },
+ getPreviousItem(index) {
+ let result = null
+
+ this.chatItems
+ .slice(0, index)
+ .reverse()
+ .some((item) => {
+ const isMessage = item.type === 'message'
+ if (isMessage) {
+ result = item
+ }
+ return isMessage
+ })
+
+ return result
+ },
+ },
+}
+
+export default ChatMessageList
diff --git a/src/components/chat_message_list/chat_message_list.scss b/src/components/chat_message_list/chat_message_list.scss
new file mode 100644
index 0000000000..2bc604da7e
--- /dev/null
+++ b/src/components/chat_message_list/chat_message_list.scss
@@ -0,0 +1,7 @@
+.ChatMessageList {
+ padding: 0.5em;
+ display: flex;
+ gap: 0.5em;
+ flex-direction: column;
+ justify-content: end;
+}
diff --git a/src/components/chat/chat.style.js b/src/components/chat_message_list/chat_message_list.style.js
similarity index 76%
rename from src/components/chat/chat.style.js
rename to src/components/chat_message_list/chat_message_list.style.js
index 55cf657c2b..7424fa9c89 100644
--- a/src/components/chat/chat.style.js
+++ b/src/components/chat_message_list/chat_message_list.style.js
@@ -1,13 +1,14 @@
export default {
name: 'Chat',
- selector: '.chat-message-list',
+ selector: '.ChatMessageList',
validInnerComponents: ['Text', 'Link', 'Icon', 'Avatar', 'ChatMessage'],
defaultRules: [
{
directives: {
+ backgroundNoCssColor: 'yes',
background: '--bg',
blur: '5px',
},
},
],
}
diff --git a/src/components/chat_message_list/chat_message_list.vue b/src/components/chat_message_list/chat_message_list.vue
new file mode 100644
index 0000000000..5cdbf68719
--- /dev/null
+++ b/src/components/chat_message_list/chat_message_list.vue
@@ -0,0 +1,19 @@
+<template>
+ <div class="ChatMessageList">
+ <ChatMessage
+ v-for="(chatItem, index) in chatItems"
+ :key="chatItem.id"
+ :chat-item="chatItem"
+ :previous-item="getPreviousItem(index)"
+ :hovered-message-chain="chatItem.messageChainId === hoveredMessageChainId"
+ :focused="chatItem.id === focusedId"
+ :repliedTo="chatItem.id === repliedId"
+ @hover="onMessageHover"
+ @delete="onMessageDelete"
+ @reply-requested="onReplyRequested"
+ />
+ </div>
+</template>
+
+<script src="./chat_message_list.js"></script>
+<style src="./chat_message_list.scss" lang="scss" />
diff --git a/src/components/chat_new/chat_new.js b/src/components/chat_new/chat_new.js
index ccfe2df509..00826ce660 100644
--- a/src/components/chat_new/chat_new.js
+++ b/src/components/chat_new/chat_new.js
@@ -1,85 +1,85 @@
import { mapGetters, mapState } from 'vuex'
import BasicUserCard from 'src/components/basic_user_card/basic_user_card.vue'
import UserAvatar from 'src/components/user_avatar/user_avatar.vue'
import { useOAuthStore } from 'src/stores/oauth.js'
import { chats } from 'src/api/chats.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faChevronLeft, faSearch } from '@fortawesome/free-solid-svg-icons'
library.add(faSearch, faChevronLeft)
const chatNew = {
components: {
BasicUserCard,
UserAvatar,
},
data() {
return {
suggestions: [],
userIds: [],
loading: false,
query: '',
}
},
async created() {
- const { chatList } = await chats({
+ const { data } = await chats({
credentials: useOAuthStore().token,
})
- chatList.forEach((chat) => this.suggestions.push(chat.account))
+ data.forEach((chat) => this.suggestions.push(chat.account))
},
computed: {
users() {
return this.userIds.map((userId) => this.findUser(userId))
},
availableUsers() {
if (this.query.length !== 0) {
return this.users
} else {
return this.suggestions
}
},
...mapState({
currentUser: (state) => state.users.currentUser,
}),
...mapGetters(['findUser']),
},
methods: {
goBack() {
this.$emit('cancel')
},
goToChat(user) {
this.$router.push({ name: 'chat', params: { recipient_id: user.id } })
},
onInput() {
this.search(this.query)
},
addUser(user) {
this.selectedUserIds.push(user.id)
this.query = ''
},
removeUser(userId) {
this.selectedUserIds = this.selectedUserIds.filter((id) => id !== userId)
},
search(query) {
if (!query) {
this.loading = false
return
}
this.loading = true
this.userIds = []
this.$store
.dispatch('search', { q: query, resolve: true, type: 'accounts' })
.then((data) => {
this.loading = false
this.userIds = data.accounts.map((a) => a.id)
})
},
},
}
export default chatNew
diff --git a/src/components/chat/chat_layout_utils.js b/src/components/chat_view/chat_layout_utils.js
similarity index 100%
rename from src/components/chat/chat_layout_utils.js
rename to src/components/chat_view/chat_layout_utils.js
diff --git a/src/components/chat_view/chat_view.js b/src/components/chat_view/chat_view.js
new file mode 100644
index 0000000000..f48b75c653
--- /dev/null
+++ b/src/components/chat_view/chat_view.js
@@ -0,0 +1,647 @@
+import { get, maxBy, minBy, sortBy, throttle } from 'lodash'
+import { mapState as mapPiniaState } from 'pinia'
+import { nextTick } from 'vue'
+import { mapState } from 'vuex'
+
+import ChatMessageList from 'src/components/chat_message_list/chat_message_list.vue'
+import ChatTitle from 'src/components/chat_title/chat_title.vue'
+import PostStatusForm from 'src/components/post_status_form/post_status_form.vue'
+import { buildFakeMessage } from '../../services/chat_utils/chat_utils.js'
+import { promiseInterval } from '../../services/promise_interval/promise_interval.js'
+import {
+ getNewTopPosition,
+ getScrollPosition,
+ isBottomedOut,
+ isScrollable,
+} from './chat_layout_utils.js'
+
+import { useChatsStore } from 'src/stores/chats.js'
+import { useInterfaceStore } from 'src/stores/interface.js'
+import { useMergedConfigStore } from 'src/stores/merged_config.js'
+import { useOAuthStore } from 'src/stores/oauth.js'
+
+import {
+ chatMessages,
+ deleteChatMessage,
+ getOrCreateChat,
+ readChat,
+ sendChatMessage,
+} from 'src/api/chats.js'
+import { fetchConversation, fetchStatus } from 'src/api/public.js'
+import { WSConnectionStatus } from 'src/api/websocket.js'
+
+import { library } from '@fortawesome/fontawesome-svg-core'
+import { faChevronDown, faChevronLeft } from '@fortawesome/free-solid-svg-icons'
+
+library.add(faChevronDown, faChevronLeft)
+
+const BOTTOMED_OUT_OFFSET = 10
+const JUMP_TO_BOTTOM_BUTTON_VISIBILITY_OFFSET = 10
+const SAFE_RESIZE_TIME_OFFSET = 100
+const MARK_AS_READ_DELAY = 1500
+const MAX_RETRIES = 10
+
+const isConfirmation = (storage, message) => {
+ if (!message.idempotency_key) return
+ return storage.idempotencyKeyIndex[message.idempotency_key]
+}
+
+const Chat = {
+ components: {
+ ChatMessageList,
+ ChatTitle,
+ PostStatusForm,
+ },
+ props: {
+ statusId: {
+ type: String,
+ default: null,
+ },
+ chatUserId: {
+ type: String,
+ default: null,
+ },
+ testMode: Boolean,
+ },
+ data() {
+ return {
+ // Main info
+ chat: null,
+ messages: [],
+ messagesIndex: {},
+ pendingMessages: [],
+ pendingMessagesIndex: {},
+ minId: undefined,
+ maxId: undefined,
+
+ // Conversation stuff
+ explicitReplyStatus: null,
+
+ // Unread stuff
+ newMessageCount: 0,
+ lastReadMessageId: null,
+ lastScrollPosition: {},
+ jumpToBottomButtonVisible: false,
+
+ // Internal network stuff
+ fetcher: null,
+ errorLoadingChat: false,
+ messageRetriers: {},
+ idempotencyKeyIndex: {},
+ }
+ },
+ created() {
+ if (this.testMode) return
+ this.startFetching()
+ },
+ mounted() {
+ window.addEventListener('resize', this.handleResize)
+ window.addEventListener('scroll', this.handleScroll)
+ if (typeof document.hidden !== 'undefined') {
+ document.addEventListener(
+ 'visibilitychange',
+ this.handleVisibilityChange,
+ false,
+ )
+ }
+
+ this.$nextTick(() => {
+ this.handleResize()
+ })
+ },
+ unmounted() {
+ window.removeEventListener('scroll', this.handleScroll)
+ window.removeEventListener('resize', this.handleResize)
+ if (typeof document.hidden !== 'undefined')
+ document.removeEventListener(
+ 'visibilitychange',
+ this.handleVisibilityChange,
+ false,
+ )
+ },
+ computed: {
+ conversationId() {
+ const status = this.$store.state.statuses.allStatusesObject[this.statusId]
+ return get(
+ status,
+ 'retweeted_status.statusnet_conversation_id',
+ get(status, 'statusnet_conversation_id'),
+ )
+ },
+ isConversation() {
+ return this.statusId !== null
+ },
+ recipient() {
+ return this.chat?.account
+ },
+ formPlaceholder() {
+ if (this.recipient) {
+ return this.$t('chats.message_user', {
+ nickname: this.recipient.screen_name_ui,
+ })
+ } else {
+ return ''
+ }
+ },
+
+ // Conversation stuff
+ lastStatus() {
+ return this.messages[this.messages.length - 1]
+ },
+ replyStatus() {
+ return this.explicitReplyStatus ?? this.lastStatus
+ },
+
+ // Global Stuff
+ streamingEnabled() {
+ if (this.isConversation) return false // Unsupported
+ return (
+ this.mergedConfig.useStreamingApi &&
+ this.mastoUserSocketStatus === WSConnectionStatus.JOINED
+ )
+ },
+ ...mapPiniaState(useInterfaceStore, {
+ mobileLayout: (store) => store.layoutType === 'mobile',
+ }),
+ ...mapPiniaState(useMergedConfigStore, ['mergedConfig']),
+ ...mapState({
+ mastoUserSocketStatus: (state) => state.api.mastoUserSocketStatus,
+ currentUser: (state) => state.users.currentUser,
+ }),
+ },
+ watch: {
+ messages(old, neu) {
+ if (old.length === neu.length) return
+ // We don't want to scroll to the bottom on a new message when the user is viewing older messages.
+ // Therefore we need to know whether the scroll position was at the bottom before the DOM update.
+ const bottomedOutBeforeUpdate = isBottomedOut(BOTTOMED_OUT_OFFSET)
+ this.$nextTick(() => {
+ if (bottomedOutBeforeUpdate) {
+ this.scrollDown()
+ }
+ })
+ },
+ async replyStatus(newVal) {
+ await nextTick() // wait for changes to propagate to postStatusForm
+ if (this.testMode) return
+ this.$refs.postStatusForm.update()
+ },
+ $route: async function (newVal) {
+ if (this.messagesIndex[newVal.params.statusId]) {
+ const focused = document.getElementById(
+ `chatmessage-${this.$route.params.statusId}`,
+ )
+ if (focused?.getBoundingClientRect == null) return
+ const bottomBoundary =
+ window.innerHeight - this.$refs.footer.clientHeight
+ const topBoundary =
+ this.$refs.header.clientHeight +
+ document.getElementById('nav').clientHeight
+ const margin = Number(
+ window
+ .getComputedStyle(this.$refs.messageList.$el)
+ .gap.replace('px', ''),
+ )
+
+ const rect = focused.getBoundingClientRect()
+ const scrollAmount = (() => {
+ if (rect.top < topBoundary) {
+ // Post is above screen, match its top to screen top
+ return rect.top - topBoundary - margin
+ } else if (rect.height >= bottomBoundary) {
+ // Post we want to see is taller than screen so match its top to screen top
+ return rect.top - topBoundary - margin
+ } else if (rect.bottom > bottomBoundary) {
+ // Post is below screen, match its bottom to screen bottom
+ return rect.bottom - bottomBoundary + margin
+ } else {
+ return 0
+ }
+ })()
+
+ if (scrollAmount !== 0) {
+ window.scrollBy(0, scrollAmount)
+ }
+
+ return
+ }
+
+ this.clear()
+ this.startFetching()
+ },
+ mastoUserSocketStatus(newValue) {
+ if (newValue === WSConnectionStatus.JOINED) {
+ this.fetchChat({ isFirstFetch: true })
+ }
+ },
+ },
+ methods: {
+ // Actions
+ async readChat() {
+ if (this.conversationId) return // Unsupported
+ if (!this.maxId || document.hidden) {
+ return
+ }
+ const lastReadId = this.maxId
+ const isNewMessage = this.lastReadMessageId !== lastReadId
+
+ if (!isNewMessage) return
+
+ if (!this.testMode) {
+ await readChat({
+ id: this.chat.id,
+ lastReadId,
+ credentials: useOAuthStore().token,
+ })
+ }
+
+ useChatsStore().readChat(this.chat.id)
+ this.lastReadMessageId = this.maxId
+ this.newMessageCount = 0
+ },
+ scrollDown(options = {}) {
+ const { behavior = 'auto', forceRead = false } = options
+ this.$nextTick(() => {
+ window.scrollTo({
+ top: document.documentElement.scrollHeight,
+ behavior,
+ })
+ })
+ if (forceRead) {
+ this.readChat()
+ }
+ },
+ cullOlder() {
+ const maxIndex = this.messages.length
+ const minIndex = maxIndex - 50
+ if (maxIndex <= 50) return
+
+ this.messages = sortBy(this.messages, ['id'])
+ this.minId = this.messages[minIndex].id
+
+ for (const message of this.messages) {
+ if (message.id < this.minId) {
+ delete this.messagesIndex[message.id]
+ delete this.idempotencyKeyIndex[message.idempotency_key]
+ }
+ }
+
+ this.messages = this.messages.slice(minIndex, maxIndex)
+ },
+ clear() {
+ this.messages = this.messages.filter((m) => m.error)
+ this.messagesIndex = this.messages.reduce(
+ (acc, m) => ({
+ ...acc,
+ [m.id]: m,
+ }),
+ {},
+ )
+ this.newMessageCount = 0
+ this.lastReadMessageId = null
+ this.minId = undefined
+ this.maxId = undefined
+ },
+ async fetchChat({ isFirstFetch = false, fetchLatest = false, maxId }) {
+ if (fetchLatest && this.streamingEnabled) {
+ return
+ }
+
+ let messages
+ if (this.isConversation) {
+ const [
+ { data: status },
+ {
+ data: { ancestors, descendants },
+ },
+ ] = await Promise.all([
+ fetchStatus({
+ id: this.statusId,
+ credentials: useOAuthStore().token,
+ }),
+ fetchConversation({
+ id: this.statusId,
+ credentials: useOAuthStore().token,
+ }),
+ ])
+ messages = [...ancestors, status, ...descendants]
+ } else {
+ const { data } = await chatMessages({
+ id: this.chat.id,
+ maxId,
+ sinceId: fetchLatest ? this.maxId : null,
+ credentials: useOAuthStore().token,
+ })
+ messages = data
+ }
+
+ // Clear the current chat in case we're recovering from a ws connection loss.
+ if (isFirstFetch) {
+ this.clear()
+ }
+
+ const positionBeforeUpdate = getScrollPosition()
+ this.addMessages({ messages })
+
+ await nextTick()
+ if (isFirstFetch) {
+ this.scrollDown()
+ }
+
+ const fetchOlderMessages = !!maxId
+ if (fetchOlderMessages) {
+ this.handleScrollUp(positionBeforeUpdate)
+ }
+
+ // In vertical screens, the first batch of fetched messages may not always take the
+ // full height of the scrollable container.
+ // If this is the case, we want to fetch the messages until the scrollable container
+ // is fully populated so that the user has the ability to scroll up and load the history.
+ //
+ // Conversation fetching doesn't support pagination and spews out everything at once
+ // so we both can't and don't need to fetch previous posts
+ if (!this.isConversation && !isScrollable() && messages.length > 0) {
+ this.fetchChat({
+ maxId: this.minId,
+ })
+ }
+ },
+ async startFetching() {
+ if (!this.isConversation) {
+ try {
+ const { data } = await getOrCreateChat({
+ accountId: this.chatUserId,
+ credentials: useOAuthStore().token,
+ })
+ this.$store.commit('addNewUsers', [data.account])
+ data.account = this.$store.getters.findUser(data.account.id)
+ this.chat = data
+ } catch (e) {
+ console.error('Error creating or getting a chat', e)
+ this.errorLoadingChat = true
+ }
+ }
+
+ if (this.isConversation || this.chat) {
+ this.$nextTick(() => {
+ this.scrollDown({ forceRead: true })
+ })
+ this.doStartFetching()
+ }
+ },
+ doStartFetching() {
+ this.fetcher = promiseInterval(
+ () => this.fetchChat({ fetchLatest: true }),
+ 5000,
+ )
+ this.fetchChat({ isFirstFetch: true })
+ },
+ addMessages({ messages: newMessages }) {
+ for (let i = 0; i < newMessages.length; i++) {
+ const message = newMessages[i]
+
+ // Sanity check
+ if (!this.isConversation && message.chat_id !== this.chat.id) {
+ console.warn(
+ `Chat message doesn't belong to current chat (id: ${this.chat.id})!!`,
+ message,
+ )
+ return
+ }
+
+ // Clear any known pending messages
+ if (message.idempotency_key) {
+ if (this.pendingMessagesIndex[message.idempotencyKeyIndex]) {
+ delete this.pendingMessagesIndex[message.idempotencyKeyIndex]
+ this.pendingMessages = this.pendingMessages.filter(
+ ({ idempotency_key }) =>
+ idempotency_key !== message.idempotency_key,
+ )
+ }
+ }
+
+ if (!this.minId || (!message.pending && message.id < this.minId)) {
+ this.minId = message.id
+ }
+
+ if (!this.maxId || message.id > this.maxId) {
+ this.maxId = message.id
+ }
+
+ if (!this.messagesIndex[message.id] && !isConfirmation(this, message)) {
+ if (this.lastReadMessageId < message.id) {
+ this.newMessageCount++
+ }
+ this.messagesIndex[message.id] = message
+ this.messages.push(this.messagesIndex[message.id])
+ this.idempotencyKeyIndex[message.idempotency_key] = true
+ }
+ }
+ },
+ goBack() {
+ this.$router.back()
+ },
+
+ // Optimistic posting (chats only)
+ async sendMessage({ status, media, idempotencyKey }) {
+ const params = {
+ id: this.chat.id,
+ content: status,
+ idempotencyKey,
+ }
+
+ if (media[0]) {
+ params.mediaId = media[0].id
+ }
+
+ const fakeMessage = buildFakeMessage({
+ attachments: media,
+ chatId: this.chat.id,
+ content: status,
+ userId: this.currentUser.id,
+ idempotencyKey,
+ })
+
+ this.pendingMessages.push(fakeMessage)
+ this.pendingMessagesIndex[idempotencyKey] = fakeMessage
+
+ this.handleAttachmentPosting()
+
+ return this.doSendMessage({
+ params,
+ retriesLeft: MAX_RETRIES,
+ })
+ },
+ async doSendMessage({ params, retriesLeft = MAX_RETRIES }) {
+ if (retriesLeft <= 0) return
+
+ try {
+ const { data } = await sendChatMessage({
+ ...params,
+ credentials: useOAuthStore().token,
+ })
+
+ this.addMessages({
+ messages: [{ ...data }],
+ })
+ } catch (error) {
+ if (
+ error.name !== 'StatusCodeError' ||
+ error.message === 'Failed to fetch'
+ )
+ throw error
+ console.error('Error sending message', error)
+
+ this.handleMessageError({
+ chatId: this.chat.id,
+ idempotencyKey: params.idempotencyKey,
+ isRetry: retriesLeft !== MAX_RETRIES,
+ })
+
+ if (
+ (error.statusCode >= 500 && error.statusCode < 600) ||
+ error.message === 'Failed to fetch'
+ ) {
+ this.messageRetriers[params.idempotencyKey] = setTimeout(
+ () => {
+ this.doSendMessage({
+ params,
+ retriesLeft: retriesLeft - 1,
+ })
+ },
+ 1000 * 2 ** (MAX_RETRIES - retriesLeft),
+ )
+ }
+ }
+ },
+ handleMessageError(idempotencyKey, isRetry) {
+ const fakeMessage = this.pendingMessagesIndex[idempotencyKey]
+
+ if (fakeMessage) {
+ fakeMessage.error = true
+ fakeMessage.pending = false
+ }
+ },
+
+ // Checks
+ hasReachedTop() {
+ return window.scrollY <= 0
+ },
+ cullOlderCheck() {
+ if (this.conversationId) return
+ window.setTimeout(() => {
+ if (isBottomedOut(JUMP_TO_BOTTOM_BUTTON_VISIBILITY_OFFSET)) {
+ this.cullOlder()
+ }
+ }, 5000)
+ },
+
+ // Event handlers
+ onPosted(data) {
+ this.explicitReplyStatus = null
+ this.$router.push({
+ name: 'conversation2',
+ params: { statusId: data.id },
+ })
+ },
+ handleVisibilityChange() {
+ this.$nextTick(() => {
+ if (!document.hidden && isBottomedOut(BOTTOMED_OUT_OFFSET)) {
+ this.scrollDown({ forceRead: true })
+ }
+ })
+ },
+ onFilesDropped() {
+ this.$nextTick(() => {
+ this.handleResize()
+ })
+ },
+ handleResize(opts = {}) {
+ // "Sticks" scroll to bottom instead of top, helps with OSK resizing the viewport
+ const { delayed = false } = opts
+
+ if (delayed) {
+ setTimeout(() => {
+ this.handleResize({ ...opts, delayed: false })
+ }, SAFE_RESIZE_TIME_OFFSET)
+ return
+ }
+
+ this.$nextTick(() => {
+ const { offsetHeight = undefined } = getScrollPosition()
+ const diff = offsetHeight - this.lastScrollPosition.offsetHeight
+ if (diff !== 0 && !isBottomedOut()) {
+ this.$nextTick(() => {
+ window.scrollBy({ top: -Math.trunc(diff) })
+ })
+ }
+ this.lastScrollPosition = getScrollPosition()
+ })
+ },
+ handleScroll: throttle(function () {
+ if (!this.chat) {
+ return
+ }
+ this.lastScrollPosition = getScrollPosition()
+
+ if (this.hasReachedTop()) {
+ this.fetchChat({ maxId: this.minId })
+ } else if (isBottomedOut(JUMP_TO_BOTTOM_BUTTON_VISIBILITY_OFFSET)) {
+ this.jumpToBottomButtonVisible = false
+ this.cullOlderCheck()
+ if (this.newMessageCount > 0) {
+ // Use a delay before marking as read to prevent situation where new messages
+ // arrive just as you're leaving the view and messages that you didn't actually
+ // get to see get marked as read.
+ window.setTimeout(() => {
+ // Don't mark as read if the element doesn't exist, user has left chat view
+ if (this.$el) this.readChat()
+ }, MARK_AS_READ_DELAY)
+ }
+ } else {
+ this.jumpToBottomButtonVisible = true
+ }
+ }, 200),
+ handleScrollUp(positionBeforeLoading) {
+ const positionAfterLoading = getScrollPosition()
+
+ window.scrollTo({
+ top: getNewTopPosition(positionBeforeLoading, positionAfterLoading),
+ })
+ },
+ handleAttachmentPosting() {
+ this.$nextTick(() => {
+ this.handleResize()
+ // When the posting form size changes because of a media attachment, we need an extra resize
+ // to account for the potential delay in the DOM update.
+ this.scrollDown({ forceRead: true })
+ })
+ },
+
+ // Ugly
+ // TODO move to ChatMessage
+ async deleteChatMessage({ chatId, messageId }) {
+ if (!this.testMode)
+ await deleteChatMessage({
+ chatId,
+ messageId,
+ credentials: useOAuthStore().token,
+ })
+
+ this.messages = this.messages.filter((m) => m.id !== messageId)
+ delete this.messagesIndex[messageId]
+
+ if (this.maxId === messageId) {
+ const lastMessage = maxBy(this.messages, 'id')
+ this.maxId = lastMessage.id
+ }
+
+ if (this.minId === messageId) {
+ const firstMessage = minBy(this.messages, 'id')
+ this.minId = firstMessage.id
+ }
+ },
+ },
+}
+
+export default Chat
diff --git a/src/components/chat/chat.scss b/src/components/chat_view/chat_view.scss
similarity index 83%
rename from src/components/chat/chat.scss
rename to src/components/chat_view/chat_view.scss
index 8af710ae1f..87028c7c47 100644
--- a/src/components/chat/chat.scss
+++ b/src/components/chat_view/chat_view.scss
@@ -1,98 +1,119 @@
.chat-view {
display: flex;
- height: 100%;
+
+ .chat-list-wrapper {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ }
+
+ .top-spacer {
+ flex: 1 1 0;
+ min-height: 0;
+ }
.chat-view-inner {
height: auto;
width: 100%;
overflow: visible;
display: flex;
}
.chat-view-body {
box-sizing: border-box;
display: flex;
flex-direction: column;
width: 100%;
overflow: visible;
min-height: calc(100vh - var(--navbar-height));
margin: 0;
border-radius: var(--roundness);
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
&::after {
border-radius: 0;
}
}
.message-list {
padding: 0 0.8em;
height: 100%;
display: flex;
flex-direction: column;
justify-content: end;
}
.footer {
position: sticky;
+ display: flex;
+ align-items: stretch;
+ flex-direction: column;
+ padding: 0;
bottom: 0;
z-index: 1;
}
.chat-view-heading {
grid-template-columns: auto minmax(50%, 1fr);
}
.go-back-button {
text-align: center;
line-height: 1;
height: 100%;
align-self: start;
width: var(--__panel-heading-height-inner);
}
.jump-to-bottom-button {
width: 2.5em;
height: 2.5em;
border-radius: 100%;
position: absolute;
right: 1.3em;
top: -3.2em;
display: flex;
justify-content: center;
align-items: center;
box-shadow: 0 1px 1px rgb(0 0 0 / 30%), 0 2px 4px rgb(0 0 0 / 30%);
z-index: 10;
transition: 0.35s all;
transition-timing-function: cubic-bezier(0, 1, 0.5, 1);
opacity: 0;
visibility: hidden;
cursor: pointer;
&.visible {
opacity: 1;
visibility: visible;
}
.unread-message-count {
font-size: 0.8em;
left: 50%;
margin-top: -1rem;
padding: 0.1em;
border-radius: 50px;
position: absolute;
}
.chat-loading-error {
width: 100%;
display: flex;
align-items: flex-end;
height: 100%;
.error {
width: 100%;
}
}
}
+
+ .reply-to-text {
+ text-align: center;
+ line-height: 1.2;
+ padding-top: 0.5em;
+ margin-bottom: -0.5em;
+ }
}
diff --git a/src/components/chat_view/chat_view.vue b/src/components/chat_view/chat_view.vue
new file mode 100644
index 0000000000..e6bef0f84c
--- /dev/null
+++ b/src/components/chat_view/chat_view.vue
@@ -0,0 +1,124 @@
+<template>
+ <div class="chat-view">
+ <div class="chat-view-inner">
+ <div
+ ref="inner"
+ class="panel-default panel chat-view-body"
+ >
+ <div
+ ref="header"
+ class="panel-heading -sticky chat-view-heading"
+ >
+ <button
+ class="button-unstyled go-back-button"
+ @click="goBack"
+ >
+ <FAIcon
+ size="lg"
+ icon="chevron-left"
+ />
+ </button>
+ <div class="title">
+ <template v-if="isConversation">
+ <RichContent
+ v-if="messages[0]?.summary_raw_html"
+ :html="messages[0].summary_raw_html"
+ :emoji="messages[0].emojis"
+ />
+ <template v-else>
+ {{ $t('timeline.conversation') }}
+ </template>
+ </template>
+ <ChatTitle
+ v-else
+ :user="recipient"
+ :with-avatar="true"
+ />
+ </div>
+ </div>
+ <div class="chat-list-wrapper panel-body">
+ <div class="top-spacer" />
+ <ChatMessageList
+ ref="messageList"
+ header-date
+ :messages="messages"
+ :pending-messages="pendingMessages"
+ :replied-id="replyStatus?.id"
+ :focused-id="statusId"
+ @message-delete="deleteChatMessage"
+ @reply-requested="e => explicitReplyStatus = e"
+ />
+ </div>
+ <div
+ ref="footer"
+ class="panel-footer -flexible-height footer"
+ >
+ <div
+ class="jump-to-bottom-button"
+ :class="{ 'visible': jumpToBottomButtonVisible }"
+ @click="scrollDown({ behavior: 'smooth' })"
+ >
+ <span>
+ <FAIcon icon="chevron-down" />
+ <div
+ v-if="newMessageCount"
+ class="badge -notification unread-chat-count unread-message-count"
+ >
+ {{ newMessageCount }}
+ </div>
+ </span>
+ </div>
+ <div
+ v-if="isConversation"
+ class="auto-reply-to-section"
+ >
+ <div class="reply-to-text">
+ {{ explicitReplyStatus ? $t('status.reply_to_selected') : $t('status.reply_to_last') }}
+ <button
+ v-if="explicitReplyStatus"
+ class="button-default"
+ @click="explicitReplyStatus = null"
+ >
+ <FAIcon icon="times" />
+ {{ $t('general.cancel') }}
+ </button>
+ </div>
+ </div>
+ <PostStatusForm
+ ref="postStatusForm"
+ :replied-status="replyStatus"
+ :mentions-line="isConversation"
+ mentions-line-read-only
+
+ disable-quotes
+ disable-notice
+ disable-lock-warning
+ :disable-subject="!isConversation"
+ :disable-scope-selector="!isConversation"
+ :disable-polls="!isConversation"
+ :disable-sensitivity-checkbox="!isConversation"
+ :disable-preview="!isConversation"
+ :disable-draft="!isConversation"
+
+ :disable-submit="isConversation ? !replyStatus : (errorLoadingChat || !chat)"
+ :optimistic-posting="!isConversation"
+
+ chat-view
+ preserve-focus
+ :auto-focus="!mobileLayout"
+ :placeholder="formPlaceholder"
+ :file-limit="isConversation ? null : 1"
+ :max-height="160"
+ emoji-picker-placement="top"
+ :post-handler="isConversation ? null : sendMessage"
+ @resize="handleResize"
+ @posted="onPosted"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<script src="./chat_view.js"></script>
+<style src="./chat_view.scss" lang="scss" />
diff --git a/src/components/conversation/conversation.js b/src/components/conversation/conversation.js
index 00605657e2..0bbf01e6ab 100644
--- a/src/components/conversation/conversation.js
+++ b/src/components/conversation/conversation.js
@@ -1,617 +1,636 @@
import { clone, filter, findIndex, get, reduce } from 'lodash'
import { mapState as mapPiniaState } from 'pinia'
import { mapState } from 'vuex'
+import ChatMessageList from 'src/components/chat_message_list/chat_message_list.vue'
+import PostStatusForm from 'src/components/post_status_form/post_status_form.vue'
import QuickFilterSettings from 'src/components/quick_filter_settings/quick_filter_settings.vue'
import QuickViewSettings from 'src/components/quick_view_settings/quick_view_settings.vue'
+import RichContent from 'src/components/rich_content/rich_content.jsx'
import ThreadTree from 'src/components/thread_tree/thread_tree.vue'
import { useInterfaceStore } from 'src/stores/interface'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useOAuthStore } from 'src/stores/oauth.js'
import { fetchConversation, fetchStatus } from 'src/api/public.js'
import { WSConnectionStatus } from 'src/api/websocket.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faAngleDoubleDown,
faAngleDoubleLeft,
faChevronLeft,
+ faReply,
+ faTimes,
} from '@fortawesome/free-solid-svg-icons'
-library.add(faAngleDoubleDown, faAngleDoubleLeft, faChevronLeft)
+library.add(
+ faAngleDoubleDown,
+ faAngleDoubleLeft,
+ faChevronLeft,
+ faReply,
+ faTimes,
+)
const sortById = (a, b) => {
const idA = a.type === 'retweet' ? a.retweeted_status.id : a.id
const idB = b.type === 'retweet' ? b.retweeted_status.id : b.id
const seqA = Number(idA)
const seqB = Number(idB)
const isSeqA = !Number.isNaN(seqA)
const isSeqB = !Number.isNaN(seqB)
if (isSeqA && isSeqB) {
return seqA < seqB ? -1 : 1
} else if (isSeqA && !isSeqB) {
return -1
} else if (!isSeqA && isSeqB) {
return 1
} else {
return idA < idB ? -1 : 1
}
}
const sortAndFilterConversation = (conversation, statusoid) => {
if (statusoid.type === 'retweet') {
conversation = filter(
conversation,
(status) =>
status.type === 'retweet' ||
status.id !== statusoid.retweeted_status.id,
)
} else {
conversation = filter(conversation, (status) => status.type !== 'retweet')
}
return conversation.filter((_) => _).sort(sortById)
}
const conversation = {
props: {
statusId: {
// Main thing
type: String,
required: true,
},
collapsable: {
// Whether conversation can be collapsed
// i.e. when it's not a page
type: Boolean,
default: false,
},
isPage: {
// Whether conversation is rendered as a standalone page
// as opposed to embedded into a timeline
type: Boolean,
default: false,
},
pinnedStatusIdsObject: {
// Used for user profile, map of pinned statuses
type: Object,
default: null,
},
inProfile: {
// Whether conversation is rendered in a user profile
// used for overriding muted status
type: Boolean,
default: false,
},
profileUserId: {
// used with inProfile, user id of the profile
type: String,
default: null,
},
virtualHidden: {
// Whether conversation is suspended. Controls rendering of statuses
type: Boolean,
default: false,
},
},
data() {
return {
focused: null,
expanded: false,
threadDisplayStatusObject: {}, // id => 'showing' | 'hidden'
inlineDivePosition: null,
loadStatusError: null,
unsuspendibleIds: new Set(),
}
},
created() {
if (this.isPage) {
this.fetchConversation()
}
},
computed: {
maxDepthToShowByDefault() {
// maxDepthInThread = max number of depths that is *visible*
// since our depth starts with 0 and "showing" means "showing children"
// there is a -2 here
const maxDepth = this.mergedConfig.maxDepthInThread - 2
return maxDepth >= 1 ? maxDepth : 1
},
streamingEnabled() {
return (
this.mergedConfig.useStreamingApi &&
this.mastoUserSocketStatus === WSConnectionStatus.JOINED
)
},
displayStyle() {
return this.mergedConfig.conversationDisplay
},
- isTreeView() {
- return !this.isLinearView
- },
treeViewIsSimple() {
return !this.mergedConfig.conversationTreeAdvanced
},
+ isTreeView() {
+ return this.displayStyle === 'tree'
+ },
isLinearView() {
- return this.displayStyle === 'linear'
+ return this.displayStyle !== 'tree'
},
shouldFadeAncestors() {
return this.mergedConfig.conversationTreeFadeAncestors
},
otherRepliesButtonPosition() {
return this.mergedConfig.conversationOtherRepliesButton
},
showOtherRepliesButtonBelowStatus() {
return this.otherRepliesButtonPosition === 'below'
},
showOtherRepliesButtonInsideStatus() {
return this.otherRepliesButtonPosition === 'inside'
},
suspendable() {
return this.unsuspendibleIds.size > 0
},
hideStatus() {
return this.virtualHidden && this.suspendable
},
status() {
return this.$store.state.statuses.allStatusesObject[this.statusId]
},
originalStatusId() {
if (this.status.retweeted_status) {
return this.status.retweeted_status.id
} else {
return this.statusId
}
},
conversationId() {
return this.getConversationId(this.statusId)
},
conversation() {
if (!this.status) {
return []
}
if (!this.isExpanded) {
return [this.status]
}
const conversation = clone(
this.$store.state.statuses.conversationsObject[this.conversationId],
)
const statusIndex = findIndex(conversation, { id: this.originalStatusId })
if (statusIndex !== -1) {
conversation[statusIndex] = this.status
}
return sortAndFilterConversation(conversation, this.status)
},
statusMap() {
return this.conversation.reduce((res, s) => {
res[s.id] = s
return res
}, {})
},
threadTree() {
const reverseLookupTable = this.conversation.reduce(
(table, status, index) => {
table[status.id] = index
return table
},
{},
)
const threads = this.conversation.reduce(
(a, cur) => {
const id = cur.id
a.forest[id] = this.getReplies(id).map((s) => s.id)
return a
},
{
forest: {},
},
)
const walk = (forest, topLevel, depth = 0, processed = {}) =>
topLevel
.map((id) => {
if (processed[id]) {
return []
}
processed[id] = true
return [
{
status: this.conversation[reverseLookupTable[id]],
id,
depth,
},
walk(forest, forest[id], depth + 1, processed),
].reduce((a, b) => a.concat(b), [])
})
.reduce((a, b) => a.concat(b), [])
const linearized = walk(
threads.forest,
this.topLevel.map((k) => k.id),
)
return linearized
},
replyIds() {
return this.conversation
.map((k) => k.id)
.reduce((res, id) => {
res[id] = (this.replies[id] || []).map((k) => k.id)
return res
}, {})
},
totalReplyCount() {
const sizes = {}
const subTreeSizeFor = (id) => {
if (sizes[id]) {
return sizes[id]
}
sizes[id] =
1 +
this.replyIds[id]
.map((cid) => subTreeSizeFor(cid))
.reduce((a, b) => a + b, 0)
return sizes[id]
}
this.conversation.map((k) => k.id).map(subTreeSizeFor)
return Object.keys(sizes).reduce((res, id) => {
res[id] = sizes[id] - 1 // exclude itself
return res
}, {})
},
totalReplyDepth() {
const depths = {}
const subTreeDepthFor = (id) => {
if (depths[id]) {
return depths[id]
}
depths[id] =
1 +
this.replyIds[id]
.map((cid) => subTreeDepthFor(cid))
.reduce((a, b) => (a > b ? a : b), 0)
return depths[id]
}
this.conversation.map((k) => k.id).map(subTreeDepthFor)
return Object.keys(depths).reduce((res, id) => {
res[id] = depths[id] - 1 // exclude itself
return res
}, {})
},
depths() {
return this.threadTree.reduce((a, k) => {
a[k.id] = k.depth
return a
}, {})
},
topLevel() {
const topLevel = this.conversation.reduce(
(tl, cur) =>
tl.filter(
(k) =>
this.getReplies(cur.id)
.map((v) => v.id)
.indexOf(k.id) === -1,
),
this.conversation,
)
return topLevel
},
otherTopLevelCount() {
return this.topLevel.length - 1
},
showingTopLevel() {
if (this.canDive && this.diveRoot) {
return [this.statusMap[this.diveRoot]]
}
return this.topLevel
},
diveRoot() {
const statusId = this.inlineDivePosition || this.statusId
const isTopLevel = !this.parentOf(statusId)
return isTopLevel ? null : statusId
},
diveDepth() {
return this.canDive && this.diveRoot ? this.depths[this.diveRoot] : 0
},
diveMode() {
return this.canDive && !!this.diveRoot
},
shouldShowAllConversationButton() {
// The "show all conversation" button tells the user that there exist
// other toplevel statuses, so do not show it if there is only a single root
return (
this.isTreeView &&
this.isExpanded &&
this.diveMode &&
this.topLevel.length > 1
)
},
shouldShowAncestors() {
return (
this.isTreeView &&
this.isExpanded &&
this.ancestorsOf(this.diveRoot).length
)
},
replies() {
let i = 1
return reduce(
this.conversation,
(result, { id, in_reply_to_status_id: irid }) => {
if (irid) {
result[irid] = result[irid] || []
result[irid].push({
name: `#${i}`,
id,
})
}
i++
return result
},
{},
)
},
isExpanded() {
return !!(this.expanded || this.isPage)
},
hiddenStyle() {
const height = (this.status && this.status.virtualHeight) || '120px'
return this.virtualHidden ? { height } : {}
},
threadDisplayStatus() {
return this.conversation.reduce((a, k) => {
const id = k.id
const depth = this.depths[id]
const status = (() => {
if (this.threadDisplayStatusObject[id]) {
return this.threadDisplayStatusObject[id]
}
if (depth - this.diveDepth <= this.maxDepthToShowByDefault) {
return 'showing'
} else {
return 'hidden'
}
})()
a[id] = status
return a
}, {})
},
canDive() {
return this.isTreeView && this.isExpanded
},
maybeFocused() {
return this.isExpanded ? this.focused : null
},
...mapPiniaState(useMergedConfigStore, ['mergedConfig']),
...mapState({
mastoUserSocketStatus: (state) => state.api.mastoUserSocketStatus,
}),
...mapPiniaState(useInterfaceStore, {
mobileLayout: (store) => store.layoutType === 'mobile',
}),
},
components: {
ThreadTree,
QuickFilterSettings,
QuickViewSettings,
+ ChatMessageList,
+ PostStatusForm,
+ RichContent,
},
watch: {
statusId(newVal, oldVal) {
const newConversationId = this.getConversationId(newVal)
const oldConversationId = this.getConversationId(oldVal)
if (
newConversationId &&
oldConversationId &&
newConversationId === oldConversationId
) {
this.setFocused(this.originalStatusId)
} else {
this.fetchConversation()
}
},
expanded(value) {
if (value) {
this.fetchConversation()
} else {
this.resetDisplayState()
}
},
virtualHidden() {
this.$store.dispatch('setVirtualHeight', {
statusId: this.statusId,
height: `${this.$el.clientHeight}px`,
})
},
},
methods: {
fetchConversation() {
if (this.status) {
fetchConversation({
id: this.statusId,
credentials: useOAuthStore().token,
}).then(({ data: { ancestors, descendants } }) => {
this.$store.dispatch('addNewStatuses', { statuses: ancestors })
this.$store.dispatch('addNewStatuses', { statuses: descendants })
this.setFocused(this.originalStatusId)
})
} else {
this.loadStatusError = null
fetchStatus({
id: this.statusId,
credentials: useOAuthStore().token,
})
.then(({ data: status }) => {
this.$store.dispatch('addNewStatuses', { statuses: [status] })
this.fetchConversation()
})
.catch((error) => {
console.error(error)
this.loadStatusError = error
})
}
},
getReplies(id) {
return this.replies[id] || []
},
setFocused(id) {
if (!id) return
this.focused = id
if (!this.streamingEnabled) {
this.$store.dispatch('fetchStatus', id)
}
this.$store.dispatch('fetchFavsAndRepeats', id)
this.$store.dispatch('fetchEmojiReactionsBy', id)
},
toggleExpanded() {
this.expanded = !this.expanded
},
getConversationId(statusId) {
const status = this.$store.state.statuses.allStatusesObject[statusId]
return get(
status,
'retweeted_status.statusnet_conversation_id',
get(status, 'statusnet_conversation_id'),
)
},
setThreadDisplay(id, nextStatus) {
this.threadDisplayStatusObject = {
...this.threadDisplayStatusObject,
[id]: nextStatus,
}
},
toggleThreadDisplay(id) {
const curStatus = this.threadDisplayStatus[id]
const nextStatus = curStatus === 'showing' ? 'hidden' : 'showing'
this.setThreadDisplay(id, nextStatus)
},
setThreadDisplayRecursively(id, nextStatus) {
this.setThreadDisplay(id, nextStatus)
this.getReplies(id)
.map((k) => k.id)
.map((id) => this.setThreadDisplayRecursively(id, nextStatus))
},
showThreadRecursively(id) {
this.setThreadDisplayRecursively(id, 'showing')
},
leastVisibleAncestor(id) {
let cur = id
let parent = this.parentOf(cur)
while (cur) {
// if the parent is showing it means cur is visible
if (this.threadDisplayStatus[parent] === 'showing') {
return cur
}
parent = this.parentOf(parent)
cur = this.parentOf(cur)
}
// nothing found, fall back to toplevel
return this.topLevel[0] ? this.topLevel[0].id : undefined
},
diveIntoStatus(id) {
this.tryScrollTo(id)
},
diveToTopLevel() {
this.tryScrollTo(
this.topLevelAncestorOrSelfId(this.diveRoot) || this.topLevel[0].id,
)
},
// only used when we are not on a page
undive() {
this.inlineDivePosition = null
this.setFocused(this.statusId)
},
tryScrollTo(id) {
if (!id) {
return
}
if (this.isPage) {
// set statusId
this.$router.push({ name: 'conversation', params: { id } })
} else {
this.inlineDivePosition = id
}
// Because the conversation can be unmounted when out of sight
// and mounted again when it comes into sight,
// the `mounted` or `created` function in `status` should not
// contain scrolling calls, as we do not want the page to jump
// when we scroll with an expanded conversation.
//
// Now the method is to rely solely on the `focused` watcher
// in `status` components.
// In linear views, all statuses are rendered at all times, but
// in tree views, it is possible that a change in active status
// removes and adds status components (e.g. an originally child
// status becomes an ancestor status, and thus they will be
// different).
// Here, let the components be rendered first, in order to trigger
// the `focused` watcher.
this.$nextTick(() => {
this.setFocused(id)
})
},
goToCurrent() {
this.tryScrollTo(this.diveRoot || this.topLevel[0].id)
},
statusById(id) {
return this.statusMap[id]
},
parentOf(id) {
const status = this.statusById(id)
if (!status) {
return undefined
}
const { in_reply_to_status_id: parentId } = status
if (!this.statusMap[parentId]) {
return undefined
}
return parentId
},
parentOrSelf(id) {
return this.parentOf(id) || id
},
// Ancestors of some status, from top to bottom
ancestorsOf(id) {
const ancestors = []
let cur = this.parentOf(id)
while (cur) {
ancestors.unshift(this.statusMap[cur])
cur = this.parentOf(cur)
}
return ancestors
},
topLevelAncestorOrSelfId(id) {
let cur = id
let parent = this.parentOf(id)
while (parent) {
cur = this.parentOf(cur)
parent = this.parentOf(parent)
}
return cur
},
resetDisplayState() {
this.undive()
this.threadDisplayStatusObject = {}
},
onStatusSuspendStateChange({ id, suspend }) {
if (!suspend) {
this.unsuspendibleIds.add(id)
} else {
this.unsuspendibleIds.delete(id)
}
},
+ onPosted(data) {
+ if (this.isPage) {
+ this.$router.push({ name: 'conversation', params: { id: data.id } })
+ }
+ },
},
}
export default conversation
diff --git a/src/components/conversation/conversation.scss b/src/components/conversation/conversation.scss
new file mode 100644
index 0000000000..99ecb338a0
--- /dev/null
+++ b/src/components/conversation/conversation.scss
@@ -0,0 +1,95 @@
+.Conversation {
+ z-index: 1;
+
+ &.-hidden {
+ background: var(--__panel-background);
+ backdrop-filter: var(--__panel-backdrop-filter);
+ }
+
+ .conversation-dive-to-top-level-box {
+ padding: var(--status-margin);
+ border-bottom: 1px solid var(--border);
+ border-radius: 0;
+
+ /* Make the button stretch along the whole row */
+ display: flex;
+ align-items: stretch;
+ flex-direction: column;
+ }
+
+ .thread-ancestors {
+ margin-left: var(--status-margin);
+ border-left: 2px solid var(--border);
+ }
+
+ .thread-ancestor.-faded .RichContent {
+ /* stylelint-disable declaration-no-important */
+ --text: var(--textFaint) !important;
+ --link: var(--linkFaint) !important;
+ --funtextGreentext: var(--funtextGreentextFaint) !important;
+ --funtextCyantext: var(--funtextCyantextFaint) !important;
+ /* stylelint-enable declaration-no-important */
+ }
+
+ .thread-ancestor-dive-box {
+ padding-left: var(--status-margin);
+ border-bottom: 1px solid var(--border);
+ border-radius: 0;
+
+ /* Make the button stretch along the whole row */
+ &,
+ &-inner {
+ display: flex;
+ align-items: stretch;
+ flex-direction: column;
+ }
+ }
+
+ .thread-ancestor-dive-box-inner {
+ padding: var(--status-margin);
+ }
+
+ .conversation-status {
+ border-bottom: 1px solid var(--border);
+ border-radius: 0;
+ }
+
+ .thread-ancestor-has-other-replies .conversation-status,
+ &:last-child:not(.-expanded) .conversation-status,
+ &.-expanded .conversation-status:last-child,
+ .thread-ancestor:last-child .conversation-status,
+ .thread-ancestor:last-child .thread-ancestor-dive-box,
+ &.-expanded .thread-tree .conversation-status {
+ border-bottom: none;
+ }
+
+ .thread-ancestors + .thread-tree > .conversation-status {
+ border-top: 1px solid var(--border);
+ }
+
+ /* expanded conversation in timeline */
+ &.status-fadein.-expanded .thread-body {
+ border-left: 4px solid var(--cRed);
+ border-radius: var(--roundness);
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+ border-bottom: 1px solid var(--border);
+ }
+
+ &.-expanded.status-fadein {
+ --___margin: calc(var(--status-margin) / 2);
+
+ background: var(--background);
+ margin: var(--___margin);
+
+ &::before {
+ z-index: -1;
+ content: "";
+ display: block;
+ position: absolute;
+ inset: calc(var(--___margin) * -1);
+ background: var(--background);
+ backdrop-filter: var(--__panel-backdrop-filter);
+ }
+ }
+}
diff --git a/src/components/conversation/conversation.vue b/src/components/conversation/conversation.vue
index 684a5de924..170ab41d6f 100644
--- a/src/components/conversation/conversation.vue
+++ b/src/components/conversation/conversation.vue
@@ -1,306 +1,216 @@
<template>
<div
v-if="!hideStatus"
:style="hiddenStyle"
class="Conversation"
:class="{ '-expanded' : isExpanded, 'panel' : isExpanded }"
>
<div
v-if="isExpanded"
class="panel-heading conversation-heading -sticky"
>
<h1 class="title">
+ <RichContent
+ v-if="conversation[0]?.summary_raw_html"
+ :html="conversation[0].summary_raw_html"
+ :emoji="conversation[0].emojis"
+ />
+ <template v-else>
{{ $t('timeline.conversation') }}
+ </template>
</h1>
<button
v-if="collapsable"
class="button-unstyled -link"
@click.prevent="toggleExpanded"
>
{{ $t('timeline.collapse') }}
</button>
<QuickFilterSettings
v-if="!collapsable && mobileLayout"
:conversation="true"
class="rightside-button"
/>
<QuickViewSettings
v-if="!collapsable"
:conversation="true"
class="rightside-button"
/>
</div>
<div
v-if="isPage && !status"
class="conversation-body"
:class="{ 'panel-body': isExpanded }"
>
<p v-if="!loadStatusError">
<FAIcon
spin
icon="circle-notch"
/>
{{ $t('status.loading') }}
</p>
<p v-else>
{{ $t('status.load_error', { error: loadStatusError }) }}
</p>
</div>
<div
v-else
class="conversation-body"
:class="{ 'panel-body': isExpanded }"
>
<div
v-if="isTreeView"
class="thread-body"
>
<div
v-if="shouldShowAllConversationButton"
class="conversation-dive-to-top-level-box"
>
<i18n-t
keypath="status.show_all_conversation_with_icon"
tag="button"
class="button-unstyled -link"
scope="global"
@click.prevent="diveToTopLevel"
>
<template #icon>
<FAIcon
icon="angle-double-left"
/>
</template>
<template #text>
<span>
{{ $t('status.show_all_conversation', { numStatus: otherTopLevelCount }, otherTopLevelCount) }}
</span>
</template>
</i18n-t>
</div>
<div
v-if="shouldShowAncestors"
class="thread-ancestors"
>
<article
v-for="status in ancestorsOf(diveRoot)"
:key="status.id"
class="thread-ancestor"
:class="{'thread-ancestor-has-other-replies': getReplies(status.id).length > 1, '-faded': shouldFadeAncestors}"
>
<Status
ref="statusComponent"
class="conversation-status status-fadein panel-body"
:statusoid="status"
:replies="getReplies(status.id)"
:expandable="!isExpanded"
:focused="maybeFocused === status.id"
:inline-expanded="collapsable && isExpanded"
:show-pinned="pinnedStatusIdsObject && pinnedStatusIdsObject[status.id]"
:in-profile="inProfile"
:in-conversation="isExpanded"
:profile-user-id="profileUserId"
:simple-tree="treeViewIsSimple"
:show-other-replies-as-button="showOtherRepliesButtonInsideStatus"
can-dive
@goto="setFocused"
@dive="() => diveIntoStatus(status.id)"
@suspendable-state-change="onStatusSuspendStateChange"
/>
<div
v-if="showOtherRepliesButtonBelowStatus && getReplies(status.id).length > 1"
class="thread-ancestor-dive-box"
>
<div
class="thread-ancestor-dive-box-inner"
>
<i18n-t
tag="button"
scope="global"
keypath="status.ancestor_follow_with_icon"
class="button-unstyled -link thread-tree-show-replies-button"
@click.prevent="diveIntoStatus(status.id)"
>
<template #icon>
<FAIcon
icon="angle-double-right"
/>
</template>
<template #text>
<span>
{{ $t('status.ancestor_follow', { numReplies: getReplies(status.id, getReplies(status.id).length - 1).length - 1 }) }}
</span>
</template>
</i18n-t>
</div>
</div>
</article>
</div>
<ThreadTree
v-for="status in showingTopLevel"
:key="status.id"
ref="statusComponent"
:depth="0"
:status="status"
:in-profile="inProfile"
:conversation="conversation"
:collapsable="collapsable"
:is-expanded="isExpanded"
:pinned-status-ids-object="pinnedStatusIdsObject"
:profile-user-id="profileUserId"
:get-replies="getReplies"
:focused="maybeFocused"
:toggle-expanded="toggleExpanded"
:simple="treeViewIsSimple"
:thread-display-status="threadDisplayStatus"
:show-thread-recursively="showThreadRecursively"
:total-reply-count="totalReplyCount"
:total-reply-depth="totalReplyDepth"
:can-dive="canDive"
@goto="setFocused"
@dive="diveIntoStatus"
@suspendable-state-change="onStatusSuspendStateChange"
/>
</div>
<div
- v-if="isLinearView"
+ v-else-if="isLinearView"
class="thread-body"
>
<article>
<Status
v-for="status in conversation"
:key="status.id"
ref="statusComponent"
class="conversation-status status-fadein panel-body"
:statusoid="status"
:replies="getReplies(status.id)"
:expandable="!isExpanded"
:focused="maybeFocused === status.id || maybeFocused === status.retweeted_status?.id"
:inline-expanded="collapsable && isExpanded"
:show-pinned="pinnedStatusIdsObject && pinnedStatusIdsObject[status.id]"
:in-profile="inProfile"
:in-conversation="isExpanded"
:profile-user-id="profileUserId"
@goto="setFocused"
@toggle-expanded="toggleExpanded"
@suspendable-state-change="onStatusSuspendStateChange"
/>
</article>
</div>
</div>
</div>
<div
v-else
class="Conversation -hidden"
:style="hiddenStyle"
/>
</template>
<script src="./conversation.js"></script>
-
-<style lang="scss">
-.Conversation {
- z-index: 1;
-
- &.-hidden {
- background: var(--__panel-background);
- backdrop-filter: var(--__panel-backdrop-filter);
- }
-
- .conversation-dive-to-top-level-box {
- padding: var(--status-margin);
- border-bottom: 1px solid var(--border);
- border-radius: 0;
-
- /* Make the button stretch along the whole row */
- display: flex;
- align-items: stretch;
- flex-direction: column;
- }
-
- .thread-ancestors {
- margin-left: var(--status-margin);
- border-left: 2px solid var(--border);
- }
-
- .thread-ancestor.-faded .RichContent {
- /* stylelint-disable declaration-no-important */
- --text: var(--textFaint) !important;
- --link: var(--linkFaint) !important;
- --funtextGreentext: var(--funtextGreentextFaint) !important;
- --funtextCyantext: var(--funtextCyantextFaint) !important;
- /* stylelint-enable declaration-no-important */
- }
-
- .thread-ancestor-dive-box {
- padding-left: var(--status-margin);
- border-bottom: 1px solid var(--border);
- border-radius: 0;
-
- /* Make the button stretch along the whole row */
- &,
- &-inner {
- display: flex;
- align-items: stretch;
- flex-direction: column;
- }
- }
-
- .thread-ancestor-dive-box-inner {
- padding: var(--status-margin);
- }
-
- .conversation-status {
- border-bottom: 1px solid var(--border);
- border-radius: 0;
- }
-
- .thread-ancestor-has-other-replies .conversation-status,
- &:last-child:not(.-expanded) .conversation-status,
- &.-expanded .conversation-status:last-child,
- .thread-ancestor:last-child .conversation-status,
- .thread-ancestor:last-child .thread-ancestor-dive-box,
- &.-expanded .thread-tree .conversation-status {
- border-bottom: none;
- }
-
- .thread-ancestors + .thread-tree > .conversation-status {
- border-top: 1px solid var(--border);
- }
-
- /* expanded conversation in timeline */
- &.status-fadein.-expanded .thread-body {
- border-left: 4px solid var(--cRed);
- border-radius: var(--roundness);
- border-top-left-radius: 0;
- border-top-right-radius: 0;
- border-bottom: 1px solid var(--border);
- }
-
- &.-expanded.status-fadein {
- --___margin: calc(var(--status-margin) / 2);
-
- background: var(--background);
- margin: var(--___margin);
-
- &::before {
- z-index: -1;
- content: "";
- display: block;
- position: absolute;
- inset: calc(var(--___margin) * -1);
- background: var(--background);
- backdrop-filter: var(--__panel-backdrop-filter);
- }
- }
-}
-</style>
+<style src="./conversation.scss" />
diff --git a/src/components/draft/draft.js b/src/components/draft/draft.js
index fac5790aa1..49e186eae0 100644
--- a/src/components/draft/draft.js
+++ b/src/components/draft/draft.js
@@ -1,101 +1,103 @@
import { cloneDeep } from 'lodash'
import { defineAsyncComponent } from 'vue'
import Gallery from 'src/components/gallery/gallery.vue'
import PostStatusForm from 'src/components/post_status_form/post_status_form.vue'
import StatusContent from 'src/components/status_content/status_content.vue'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faPollH } from '@fortawesome/free-solid-svg-icons'
library.add(faPollH)
const Draft = {
components: {
PostStatusForm,
EditStatusForm: defineAsyncComponent(
() => import('src/components/edit_status_form/edit_status_form.vue'),
),
ConfirmModal: defineAsyncComponent(
() => import('src/components/confirm_modal/confirm_modal.vue'),
),
StatusContent,
Gallery,
},
props: {
draft: {
type: Object,
required: true,
},
},
data() {
return {
referenceDraft: cloneDeep(this.draft),
editing: false,
showingConfirmDialog: false,
}
},
computed: {
relAttrs() {
if (this.draft.type === 'edit') {
return { statusId: this.draft.refId }
} else if (this.draft.type === 'reply') {
- return { replyTo: this.draft.refId }
+ return {
+ repliedStatus: this.refStatus,
+ }
} else {
return {}
}
},
safeToSave() {
return (
this.draft.status ||
this.draft.files?.length ||
this.draft.hasPoll ||
this.draft.hasQuote
)
},
postStatusFormProps() {
return {
draftId: this.draft.id,
...this.relAttrs,
}
},
refStatus() {
return this.draft.refId
? this.$store.state.statuses.allStatusesObject[this.draft.refId]
: undefined
},
localCollapseSubjectDefault() {
return useMergedConfigStore().mergedConfig.collapseMessageWithSubject
},
},
watch: {
editing(newVal) {
if (newVal) return
if (this.safeToSave) {
this.$store.dispatch('addOrSaveDraft', { draft: this.draft })
} else {
this.$store.dispatch('addOrSaveDraft', { draft: this.referenceDraft })
}
},
},
methods: {
toggleEditing() {
this.editing = !this.editing
},
abandon() {
this.showingConfirmDialog = true
},
doAbandon() {
this.$store.dispatch('abandonDraft', { id: this.draft.id }).then(() => {
this.hideConfirmDialog()
})
},
hideConfirmDialog() {
this.showingConfirmDialog = false
},
},
}
export default Draft
diff --git a/src/components/draft/draft.vue b/src/components/draft/draft.vue
index c91675e35b..e610f627b9 100644
--- a/src/components/draft/draft.vue
+++ b/src/components/draft/draft.vue
@@ -1,168 +1,168 @@
<template>
<article class="Draft">
<div
v-if="!editing"
class="status-content"
>
<div>
<i18n-t
v-if="draft.type === 'reply' || draft.type === 'edit'"
tag="span"
:keypath="draft.type === 'reply' ? 'drafts.replying' : 'drafts.editing'"
>
<template #statusLink>
<router-link
class="faint-link"
:to="{ name: 'conversation', params: { id: draft.refId } }"
>
{{ refStatus ? refStatus.external_url : $t('drafts.unavailable') }}
</router-link>
</template>
</i18n-t>
<StatusContent
v-if="draft.refId && refStatus"
class="status-content"
:status="refStatus"
:compact="true"
/>
</div>
<div class="status-preview">
<span class="status_content">
<p v-if="draft.spoilerText">
<i>
{{ draft.spoilerText }}:
</i>
</p>
<p v-if="draft.status">{{ draft.status }}</p>
<p
v-else
class="faint"
>{{ $t('drafts.empty') }}</p>
</span>
<Gallery
v-if="draft.files?.length !== 0"
class="attachments media-body"
:compact="true"
:nsfw="nsfwClickthrough"
:attachments="draft.files"
:limit="1"
size="small"
@play="$emit('mediaplay', attachment.id)"
@pause="$emit('mediapause', attachment.id)"
/>
<div
- v-if="draft.poll.options"
+ v-if="draft.poll?.options"
class="poll-indicator-container"
:title="$t('drafts.poll_tooltip')"
>
<div class="poll-indicator">
<FAIcon
icon="poll-h"
size="3x"
/>
</div>
</div>
</div>
</div>
<div v-if="editing">
<PostStatusForm
v-if="draft.type !== 'edit'"
:hide-draft="true"
v-bind="postStatusFormProps"
/>
<EditStatusForm
v-else
:hide-draft="true"
:params="postStatusFormProps"
/>
</div>
<teleport to="#modal">
<ConfirmModal
v-if="showingConfirmDialog"
:title="$t('drafts.abandon_confirm_title')"
:confirm-text="$t('drafts.abandon_confirm_accept_button')"
:cancel-text="$t('drafts.abandon_confirm_cancel_button')"
@accepted="doAbandon"
@cancelled="hideConfirmDialog"
>
{{ $t('drafts.abandon_confirm') }}
</ConfirmModal>
</teleport>
<div class="actions">
<button
class="btn button-default"
:aria-expanded="editing"
@click.prevent.stop="toggleEditing"
>
{{ editing ? $t('drafts.save') : $t('drafts.continue') }}
</button>
<button
class="btn button-default"
@click.prevent.stop="abandon"
>
{{ $t('drafts.abandon') }}
</button>
</div>
</article>
</template>
<script src="./draft.js"></script>
<style lang="scss">
.Draft {
position: relative;
.status-content {
padding: 0.5em;
margin: 0.5em 0;
}
.status-preview {
display: grid;
grid-template-columns: 1fr;
grid-auto-columns: 10em;
grid-auto-flow: column;
grid-gap: 0.5em;
align-items: start;
max-width: 100%;
p {
white-space: normal;
overflow-x: hidden;
}
.poll-indicator-container {
border-radius: var(--roundness);
display: grid;
place-items: center center;
align-self: start;
height: 0;
padding-bottom: 62.5%;
position: relative;
}
.poll-indicator {
box-sizing: border-box;
border: 1px solid var(--border);
position: absolute;
inset: 0;
display: grid;
place-items: center center;
width: 100%;
height: 100%;
}
}
.actions {
display: flex;
flex-direction: row;
justify-content: space-evenly;
.btn {
flex: 1;
margin-left: 1em;
margin-right: 1em;
}
}
}
</style>
diff --git a/src/components/extra_notifications/extra_notifications.js b/src/components/extra_notifications/extra_notifications.js
index 31ca57aaa1..24ed074af9 100644
--- a/src/components/extra_notifications/extra_notifications.js
+++ b/src/components/extra_notifications/extra_notifications.js
@@ -1,75 +1,77 @@
-import { mapState as mapPiniaState } from 'pinia'
+import { mapState } from 'pinia'
import { mapGetters } from 'vuex'
import { useAnnouncementsStore } from 'src/stores/announcements.js'
+import { useChatsStore } from 'src/stores/chats.js'
import { useInterfaceStore } from 'src/stores/interface.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useSyncConfigStore } from 'src/stores/sync_config.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faBullhorn,
faComments,
faUserPlus,
} from '@fortawesome/free-solid-svg-icons'
library.add(faUserPlus, faComments, faBullhorn)
const ExtraNotifications = {
computed: {
shouldShowChats() {
return (
this.mergedConfig.showExtraNotifications &&
this.mergedConfig.showChatsInExtraNotifications &&
- this.unreadChatCount
+ this.unreadChatsCount
)
},
shouldShowAnnouncements() {
return (
this.mergedConfig.showExtraNotifications &&
this.mergedConfig.showAnnouncementsInExtraNotifications &&
this.unreadAnnouncementCount
)
},
shouldShowFollowRequests() {
return (
this.mergedConfig.showExtraNotifications &&
this.mergedConfig.showFollowRequestsInExtraNotifications &&
this.followRequestCount
)
},
hasAnythingToShow() {
return (
this.shouldShowChats ||
this.shouldShowAnnouncements ||
this.shouldShowFollowRequests
)
},
shouldShowCustomizationTip() {
return (
this.mergedConfig.showExtraNotificationsTip && this.hasAnythingToShow
)
},
currentUser() {
return this.$store.state.users.currentUser
},
- ...mapGetters(['unreadChatCount', 'followRequestCount']),
- ...mapPiniaState(useAnnouncementsStore, {
+ ...mapGetters(['followRequestCount']),
+ ...mapState(useAnnouncementsStore, {
unreadAnnouncementCount: 'unreadAnnouncementCount',
}),
- ...mapPiniaState(useMergedConfigStore, ['mergedConfig']),
+ ...mapState(useMergedConfigStore, ['mergedConfig']),
+ ...mapState(useChatsStore, ['unreadChatsCount']),
},
methods: {
openNotificationSettings() {
return useInterfaceStore().openSettingsModalTab('notifications')
},
dismissConfigurationTip() {
return useSyncConfigStore().setSimplePrefAndSave({
path: 'showExtraNotificationsTip',
value: false,
})
},
},
}
export default ExtraNotifications
diff --git a/src/components/extra_notifications/extra_notifications.vue b/src/components/extra_notifications/extra_notifications.vue
index fa64ce1fa7..3884359508 100644
--- a/src/components/extra_notifications/extra_notifications.vue
+++ b/src/components/extra_notifications/extra_notifications.vue
@@ -1,116 +1,116 @@
<template>
<div class="ExtraNotifications panel-body">
<div
v-if="shouldShowChats"
class="notification unseen"
>
<div class="notification-overlay" />
<router-link
class="button-unstyled -link extra-notification"
:to="{ name: 'chats', params: { username: currentUser.screen_name } }"
>
<FAIcon
fixed-width
class="fa-scale-110 icon"
icon="comments"
/>
- {{ $t('notifications.unread_chats', { num: unreadChatCount }, unreadChatCount) }}
+ {{ $t('notifications.unread_chats', { num: unreadChatsCount }, unreadChatsCount) }}
</router-link>
</div>
<div
v-if="shouldShowAnnouncements"
class="notification unseen"
>
<div class="notification-overlay" />
<router-link
class="button-unstyled -link extra-notification"
:to="{ name: 'announcements' }"
>
<FAIcon
fixed-width
class="fa-scale-110 icon"
icon="bullhorn"
/>
{{ $t('notifications.unread_announcements', { num: unreadAnnouncementCount }, unreadAnnouncementCount) }}
</router-link>
</div>
<div
v-if="shouldShowFollowRequests"
class="notification unseen"
>
<div class="notification-overlay" />
<router-link
class="button-unstyled -link extra-notification"
:to="{ name: 'friend-requests' }"
>
<FAIcon
fixed-width
class="fa-scale-110 icon"
icon="user-plus"
/>
{{ $t('notifications.unread_follow_requests', { num: followRequestCount }, followRequestCount) }}
</router-link>
</div>
<i18n-t
v-if="shouldShowCustomizationTip"
tag="span"
class="notification tip extra-notification"
keypath="notifications.configuration_tip"
scope="global"
>
<template #theSettings>
<button
class="button-unstyled -link"
@click="openNotificationSettings"
>
{{ $t('notifications.configuration_tip_settings') }}
</button>
</template>
<template #dismiss>
<button
class="button-unstyled -link"
@click="dismissConfigurationTip"
>
{{ $t('notifications.configuration_tip_dismiss') }}
</button>
</template>
</i18n-t>
</div>
</template>
<script src="./extra_notifications.js" />
<style lang="scss">
.ExtraNotifications {
width: 100%;
display: flex;
flex-direction: column;
align-items: stretch;
&.panel-body::before {
content: '';
padding: 0;
}
.notification {
width: 100%;
border-bottom: 1px solid;
border-color: var(--border);
display: flex;
flex-direction: column;
align-items: stretch;
}
.extra-notification {
padding: 1em;
}
.icon {
margin-right: 0.5em;
}
.tip {
display: inline;
}
}
</style>
diff --git a/src/components/mobile_nav/mobile_nav.js b/src/components/mobile_nav/mobile_nav.js
index b47376d53d..4eb956f64c 100644
--- a/src/components/mobile_nav/mobile_nav.js
+++ b/src/components/mobile_nav/mobile_nav.js
@@ -1,166 +1,167 @@
import { mapState } from 'pinia'
import { defineAsyncComponent } from 'vue'
-import { mapGetters } from 'vuex'
import NavigationPins from 'src/components/navigation/navigation_pins.vue'
import GestureService from '../../services/gesture_service/gesture_service'
import {
countExtraNotifications,
unseenNotificationsFromStore,
} from '../../services/notification_utils/notification_utils'
import { useAnnouncementsStore } from 'src/stores/announcements.js'
+import { useChatsStore } from 'src/stores/chats.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faArrowUp,
faBars,
faBell,
faCheckDouble,
faMinus,
faTimes,
} from '@fortawesome/free-solid-svg-icons'
library.add(faTimes, faBell, faBars, faArrowUp, faMinus, faCheckDouble)
const MobileNav = {
components: {
SideDrawer: defineAsyncComponent(
() => import('src/components/side_drawer/side_drawer.vue'),
),
Notifications: defineAsyncComponent(
() => import('src/components/notifications/notifications.vue'),
),
NavigationPins,
ConfirmModal: defineAsyncComponent(
() => import('src/components/confirm_modal/confirm_modal.vue'),
),
},
data: () => ({
notificationsCloseGesture: undefined,
notificationsOpen: false,
notificationsAtTop: true,
showingConfirmLogout: false,
}),
created() {
this.notificationsCloseGesture = GestureService.swipeGesture(
GestureService.DIRECTION_RIGHT,
() => this.closeMobileNotifications(true),
50,
)
},
computed: {
currentUser() {
return this.$store.state.users.currentUser
},
unseenNotifications() {
return unseenNotificationsFromStore(
this.$store,
useMergedConfigStore().mergedConfig.notificationVisibility,
useMergedConfigStore().mergedConfig.ignoreInactionableSeen,
)
},
unseenNotificationsCount() {
return (
this.unseenNotifications.length +
countExtraNotifications(
this.$store,
useMergedConfigStore().mergedConfig,
+ useChatsStore().unreadChatsCount,
useAnnouncementsStore().unreadAnnouncementCount,
)
)
},
unseenCount() {
return this.unseenNotifications.length
},
unseenCountBadgeText() {
return `${this.unseenCount ? this.unseenCount : ''}`
},
hideSitename() {
return useInstanceStore().hideSitename
},
sitename() {
return useInstanceStore().name
},
isChat() {
return this.$route.name === 'chat'
},
- ...mapState(useAnnouncementsStore, ['unreadAnnouncementCount']),
- ...mapState(useMergedConfigStore, {
- pinnedItems: (store) =>
- new Set(store.prefsStorage.collections.pinnedNavItems).has('chats'),
- }),
shouldConfirmLogout() {
return useMergedConfigStore().mergedConfig.modalOnLogout
},
closingDrawerMarksAsSeen() {
return useMergedConfigStore().mergedConfig.closingDrawerMarksAsSeen
},
- ...mapGetters(['unreadChatCount']),
+ ...mapState(useAnnouncementsStore, ['unreadAnnouncementCount']),
+ ...mapState(useMergedConfigStore, {
+ pinnedItems: (store) =>
+ new Set(store.prefsStorage.collections.pinnedNavItems).has('chats'),
+ }),
+ ...mapState(useChatsStore, ['unreadChatsCount']),
},
methods: {
toggleMobileSidebar() {
this.$refs.sideDrawer.toggleDrawer()
},
openMobileNotifications() {
this.notificationsOpen = true
},
closeMobileNotifications(markRead) {
if (this.notificationsOpen) {
// make sure to mark notifs seen only when the notifs were open and not
// from close-calls.
this.notificationsOpen = false
if (markRead && this.closingDrawerMarksAsSeen) {
this.markNotificationsAsSeen()
}
}
},
notificationsTouchStart(e) {
GestureService.beginSwipe(e, this.notificationsCloseGesture)
},
notificationsTouchMove(e) {
GestureService.updateSwipe(e, this.notificationsCloseGesture)
},
scrollToTop() {
window.scrollTo(0, 0)
},
scrollMobileNotificationsToTop() {
this.$refs.mobileNotifications.scrollTo(0, 0)
},
showConfirmLogout() {
this.showingConfirmLogout = true
},
hideConfirmLogout() {
this.showingConfirmLogout = false
},
logout() {
if (!this.shouldConfirmLogout) {
this.doLogout()
} else {
this.showConfirmLogout()
}
},
doLogout() {
this.$router.replace('/main/public')
this.$store.dispatch('logout')
this.hideConfirmLogout()
},
markNotificationsAsSeen() {
this.$store.dispatch('markNotificationsAsSeen')
},
onScroll({ target: { scrollTop, clientHeight, scrollHeight } }) {
this.notificationsAtTop = scrollTop > 0
},
},
watch: {
$route() {
// handles closing notificaitons when you press any router-link on the
// notifications.
this.closeMobileNotifications()
},
},
}
export default MobileNav
diff --git a/src/components/mobile_nav/mobile_nav.vue b/src/components/mobile_nav/mobile_nav.vue
index 743b7deb0b..8cdb70a1a9 100644
--- a/src/components/mobile_nav/mobile_nav.vue
+++ b/src/components/mobile_nav/mobile_nav.vue
@@ -1,260 +1,260 @@
<template>
<div
class="MobileNav"
>
<nav
id="nav"
class="mobile-nav"
@click="scrollToTop()"
>
<div class="item">
<button
class="button-unstyled mobile-nav-button"
:title="$t('nav.mobile_sidebar')"
:aria-expanaded="$refs.sideDrawer && !$refs.sideDrawer.closed"
@click.stop.prevent="toggleMobileSidebar()"
>
<FAIcon
class="fa-scale-110 fa-old-padding"
icon="bars"
/>
<div
- v-if="(unreadChatCount && !chatsPinned) || unreadAnnouncementCount"
+ v-if="(unreadChatsCount && !chatsPinned) || unreadAnnouncementCount"
class="badge -dot -notification"
/>
</button>
<NavigationPins class="pins" />
</div> <div class="item right">
<button
v-if="currentUser"
class="button-unstyled mobile-nav-button"
:title="unseenNotificationsCount ? $t('nav.mobile_notifications_unread_active') : $t('nav.mobile_notifications')"
@click.stop.prevent="openMobileNotifications()"
>
<FAIcon
class="fa-scale-110 fa-old-padding"
icon="bell"
/>
<div
v-if="unseenNotificationsCount"
class="badge -dot -notification"
/>
</button>
</div>
</nav>
<aside
v-if="currentUser"
class="mobile-notifications-drawer mobile-drawer"
:class="{ '-closed': !notificationsOpen }"
@touchstart.stop="notificationsTouchStart"
@touchmove.stop="notificationsTouchMove"
>
<div class="panel-heading mobile-notifications-header">
<h1 class="title">
{{ $t('notifications.notifications') }}
<span
v-if="unseenCountBadgeText"
class="badge -notification unseen-count"
>{{ unseenCountBadgeText }}</span>
</h1>
<span class="spacer" />
<button
v-if="notificationsAtTop"
class="button-unstyled mobile-nav-button"
:title="$t('general.scroll_to_top')"
@click.stop.prevent="scrollMobileNotificationsToTop"
>
<FALayers class="fa-scale-110 fa-old-padding-layer">
<FAIcon icon="arrow-up" />
<FAIcon
icon="minus"
transform="up-7"
/>
</FALayers>
</button>
<button
v-if="!closingDrawerMarksAsSeen"
class="button-unstyled mobile-nav-button"
:title="$t('nav.mobile_notifications_mark_as_seen')"
@click.stop.prevent="markNotificationsAsSeen()"
>
<FAIcon
class="fa-scale-110 fa-old-padding"
icon="check-double"
/>
</button>
<button
class="button-unstyled mobile-nav-button"
:title="$t('nav.mobile_notifications_close')"
@click.stop.prevent="closeMobileNotifications(true)"
>
<FAIcon
class="fa-scale-110 fa-old-padding"
icon="times"
/>
</button>
</div>
<!-- Notifications teleport target -->
<div
id="mobile-notifications"
ref="mobileNotifications"
class="mobile-notifications"
@scroll="onScroll"
/>
</aside>
<SideDrawer
ref="sideDrawer"
:logout="logout"
/>
<teleport to="#modal">
<ConfirmModal
v-if="showingConfirmLogout"
:title="$t('login.logout_confirm_title')"
:confirm-danger="true"
:confirm-text="$t('login.logout_confirm_accept_button')"
:cancel-text="$t('login.logout_confirm_cancel_button')"
@accepted="doLogout"
@cancelled="hideConfirmLogout"
>
{{ $t('login.logout_confirm') }}
</ConfirmModal>
</teleport>
</div>
</template>
<script src="./mobile_nav.js"></script>
<style lang="scss">
.MobileNav {
z-index: var(--ZI_navbar);
.mobile-nav {
display: grid;
line-height: var(--navbar-height);
grid-template-rows: var(--navbar-height);
grid-template-columns: 2fr auto;
width: 100%;
box-sizing: border-box;
a {
color: var(--link);
}
}
.mobile-inner-nav {
width: 100%;
display: flex;
align-items: center;
}
.mobile-nav-button {
display: inline-block;
text-align: center;
padding: 0 1em;
position: relative;
cursor: pointer;
}
.site-name {
padding: 0 0.3em;
display: inline-block;
}
.item {
/* moslty just to get rid of extra whitespaces */
display: flex;
}
.mobile-notifications-drawer {
width: 100%;
height: 100vh;
overflow-x: hidden;
position: fixed;
top: 0;
left: 0;
box-shadow: var(--shadow);
transition-property: transform;
transition-duration: 0.25s;
transform: translateX(0);
z-index: var(--ZI_navbar);
-webkit-overflow-scrolling: touch;
background: var(--background);
&.-closed {
transform: translateX(100%);
box-shadow: none;
}
}
.mobile-notifications-header {
display: flex;
align-items: center;
justify-content: space-between;
z-index: calc(var(--ZI_navbar) + 100);
width: 100%;
height: 3.5em;
line-height: 3.5em;
position: absolute;
box-shadow: var(--shadow);
.spacer {
flex: 1;
}
.title {
font-size: 1.3em;
margin-left: 0.6em;
white-space: nowrap;
overflow-x: hidden;
text-overflow: ellipsis;
}
}
.pins {
flex: 1;
.pinned-item {
flex-grow: 1;
}
}
.mobile-notifications {
margin-top: 3.5em;
width: 100vw;
height: calc(100vh - var(--navbar-height));
overflow: hidden scroll;
.notifications {
padding: 0;
border-radius: 0;
box-shadow: none;
.panel {
border-radius: 0;
margin: 0;
box-shadow: none;
}
.panel::after {
border-radius: 0;
}
.panel .panel-heading {
border-radius: 0;
box-shadow: none;
}
}
}
.confirm-modal.dark-overlay {
&::before {
z-index: 3000;
}
.dialog-modal.panel {
z-index: 3001;
}
}
}
</style>
diff --git a/src/components/nav_panel/nav_panel.js b/src/components/nav_panel/nav_panel.js
index ae6264217b..5a4a78ec48 100644
--- a/src/components/nav_panel/nav_panel.js
+++ b/src/components/nav_panel/nav_panel.js
@@ -1,169 +1,170 @@
import { mapState as mapPiniaState } from 'pinia'
-import { mapGetters, mapState } from 'vuex'
+import { mapState } from 'vuex'
import BookmarkFoldersMenuContent from 'src/components/bookmark_folders_menu/bookmark_folders_menu_content.vue'
import Checkbox from 'src/components/checkbox/checkbox.vue'
import ListsMenuContent from 'src/components/lists_menu/lists_menu_content.vue'
import { filterNavigation } from 'src/components/navigation/filter.js'
import { ROOT_ITEMS, TIMELINES } from 'src/components/navigation/navigation.js'
import NavigationEntry from 'src/components/navigation/navigation_entry.vue'
import NavigationPins from 'src/components/navigation/navigation_pins.vue'
import { useAnnouncementsStore } from 'src/stores/announcements'
+import { useChatsStore } from 'src/stores/chats.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
import { useSyncConfigStore } from 'src/stores/sync_config.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faBell,
faBookmark,
faBullhorn,
faChevronDown,
faChevronUp,
faCity,
faComments,
faEnvelope,
faFilePen,
faGlobe,
faInfoCircle,
faList,
faStream,
faUsers,
} from '@fortawesome/free-solid-svg-icons'
library.add(
faUsers,
faGlobe,
faCity,
faBookmark,
faEnvelope,
faChevronDown,
faChevronUp,
faComments,
faBell,
faInfoCircle,
faStream,
faList,
faBullhorn,
faFilePen,
)
const NavPanel = {
props: ['forceExpand', 'forceEditMode'],
components: {
BookmarkFoldersMenuContent,
ListsMenuContent,
NavigationEntry,
NavigationPins,
Checkbox,
},
data() {
return {
editMode: false,
showTimelines: false,
showLists: false,
showBookmarkFolders: false,
timelinesList: Object.entries(TIMELINES).map(([k, v]) => ({
...v,
name: k,
})),
rootList: Object.entries(ROOT_ITEMS).map(([k, v]) => ({ ...v, name: k })),
}
},
methods: {
toggleTimelines() {
this.showTimelines = !this.showTimelines
},
toggleLists() {
this.showLists = !this.showLists
},
toggleBookmarkFolders() {
this.showBookmarkFolders = !this.showBookmarkFolders
},
toggleEditMode() {
this.editMode = !this.editMode
},
toggleCollapse() {
useSyncConfigStore().setSimplePrefAndSave({
path: 'collapseNav',
value: !this.collapsed,
})
useSyncConfigStore().pushSyncConfig()
},
isPinned(item) {
return this.pinnedItems.has(item)
},
togglePin(item) {
if (this.isPinned(item)) {
useSyncConfigStore().removeCollectionPreference({
path: 'collections.pinnedNavItems',
value: item,
})
} else {
useSyncConfigStore().addCollectionPreference({
path: 'collections.pinnedNavItems',
value: item,
})
}
useSyncConfigStore().pushSyncConfig()
},
},
computed: {
...mapPiniaState(useAnnouncementsStore, {
unreadAnnouncementCount: 'unreadAnnouncementCount',
supportsAnnouncements: (store) => store.supportsAnnouncements,
}),
...mapPiniaState(useInstanceCapabilitiesStore, [
'pleromaChatMessagesAvailable',
'pleromaBookmarkFoldersAvailable',
'localBubble',
]),
...mapPiniaState(useInstanceStore, ['federating']),
...mapPiniaState(useInstanceStore, {
privateMode: (store) => store.private,
}),
...mapPiniaState(useSyncConfigStore, {
collapsed: (store) => store.prefsStorage.simple.collapseNav,
pinnedItems: (store) =>
new Set(store.prefsStorage.collections.pinnedNavItems),
}),
...mapState({
currentUser: (state) => state.users.currentUser,
followRequestCount: (state) => state.api.followRequests.length,
}),
+ ...mapPiniaState(useChatsStore, ['unreadChatsCount']),
timelinesItems() {
return filterNavigation(
Object.entries({ ...TIMELINES })
// do not show in timeliens list since it's in a better place now
.filter(([key]) => key !== 'bookmarks')
.map(([k, v]) => ({ ...v, name: k })),
{
hasChats: this.pleromaChatMessagesAvailable,
hasAnnouncements: this.supportsAnnouncements,
isFederating: this.federating,
isPrivate: this.privateMode,
currentUser: this.currentUser,
supportsBubbleTimeline: this.localBubble,
supportsBookmarkFolders: this.pleromaBookmarkFoldersAvailable,
},
)
},
rootItems() {
return filterNavigation(
Object.entries({ ...ROOT_ITEMS }).map(([k, v]) => ({ ...v, name: k })),
{
hasChats: this.pleromaChatMessagesAvailable,
hasAnnouncements: this.supportsAnnouncements,
isFederating: this.federating,
isPrivate: this.privateMode,
currentUser: this.currentUser,
supportsBubbleTimeline: this.localBubble,
supportsBookmarkFolders: this.pleromaBookmarkFoldersAvailable,
},
)
},
- ...mapGetters(['unreadChatCount']),
},
}
export default NavPanel
diff --git a/src/components/navigation/navigation.js b/src/components/navigation/navigation.js
index 66fb0d3473..39fa2c993c 100644
--- a/src/components/navigation/navigation.js
+++ b/src/components/navigation/navigation.js
@@ -1,132 +1,132 @@
// routes that take :username property
export const USERNAME_ROUTES = new Set([
'dms',
'interactions',
'notifications',
'chat',
'chats',
])
// routes that take :name property
export const NAME_ROUTES = new Set(['user-profile', 'legacy-user-profile'])
export const TIMELINES = {
home: {
route: 'friends',
icon: 'home',
label: 'nav.home_timeline',
criteria: ['!private'],
},
public: {
route: 'public-timeline',
anon: true,
icon: 'users',
label: 'nav.public_tl',
criteria: ['!private'],
},
bubble: {
route: 'bubble',
anon: true,
icon: 'city',
label: 'nav.bubble',
criteria: ['!private', 'federating', 'supportsBubbleTimeline'],
},
twkn: {
route: 'public-external-timeline',
anon: true,
icon: 'globe',
label: 'nav.twkn',
criteria: ['!private', 'federating'],
},
// bookmarks are still technically a timeline so we should show it in the dropdown
bookmarks: {
route: 'bookmarks',
icon: 'bookmark',
label: 'nav.bookmarks',
},
favorites: {
routeObject: { name: 'user-profile', query: { tab: 'favorites' } },
icon: 'star',
label: 'user_card.favorites',
},
dms: {
route: 'dms',
icon: 'envelope',
label: 'nav.dms',
},
}
export const ROOT_ITEMS = {
bookmarks: {
route: 'bookmarks',
icon: 'bookmark',
label: 'nav.bookmarks',
// shows bookmarks entry in a better suited location
// hides it when bookmark folders are supported since
// we show custom component instead of it
criteria: ['!supportsBookmarkFolders'],
},
interactions: {
route: 'interactions',
icon: 'bell',
label: 'nav.interactions',
},
chats: {
route: 'chats',
icon: 'comments',
label: 'nav.chats',
badgeStyle: 'notification',
- badgeGetter: 'unreadChatCount',
+ badgeGetter: 'unreadChatsCount',
criteria: ['chats'],
},
friendRequests: {
route: 'friend-requests',
icon: 'user-plus',
label: 'nav.friend_requests',
badgeStyle: 'notification',
criteria: ['lockedUser'],
badgeGetter: 'followRequestCount',
},
about: {
route: 'about',
anon: true,
icon: 'info-circle',
label: 'nav.about',
},
announcements: {
route: 'announcements',
icon: 'bullhorn',
label: 'nav.announcements',
store: 'announcements',
badgeStyle: 'notification',
badgeGetter: 'unreadAnnouncementCount',
criteria: ['announcements'],
},
drafts: {
route: 'drafts',
icon: 'file-pen',
label: 'nav.drafts',
badgeStyle: 'neutral',
badgeGetter: 'draftCount',
},
}
export function routeTo(item, currentUser) {
if (!item.route && !item.routeObject) return null
let route
if (item.routeObject) {
route = item.routeObject
} else {
route = { name: item.anon || currentUser ? item.route : item.anonRoute }
}
if (USERNAME_ROUTES.has(route.name)) {
route.params = { username: currentUser.screen_name }
} else if (NAME_ROUTES.has(route.name)) {
route.params = { name: currentUser.screen_name }
}
return route
}
diff --git a/src/components/notifications/notifications.js b/src/components/notifications/notifications.js
index 49349b1272..393aef639e 100644
--- a/src/components/notifications/notifications.js
+++ b/src/components/notifications/notifications.js
@@ -1,272 +1,273 @@
import { mapState } from 'pinia'
import { computed } from 'vue'
-import { mapGetters } from 'vuex'
import ExtraNotifications from 'src/components/extra_notifications/extra_notifications.vue'
import Notification from 'src/components/notification/notification.vue'
import FaviconService from '../../services/favicon_service/favicon_service.js'
import {
ACTIONABLE_NOTIFICATION_TYPES,
countExtraNotifications,
filteredNotificationsFromStore,
notificationsFromStore,
unseenNotificationsFromStore,
} from '../../services/notification_utils/notification_utils.js'
import notificationsFetcher from '../../services/notifications_fetcher/notifications_fetcher.service.js'
import NotificationFilters from './notification_filters.vue'
import { useAnnouncementsStore } from 'src/stores/announcements.js'
+import { useChatsStore } from 'src/stores/chats.js'
import { useInterfaceStore } from 'src/stores/interface.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faArrowUp,
faCircleNotch,
faMinus,
} from '@fortawesome/free-solid-svg-icons'
library.add(faCircleNotch, faArrowUp, faMinus)
const DEFAULT_SEEN_TO_DISPLAY_COUNT = 30
const Notifications = {
components: {
Notification,
NotificationFilters,
ExtraNotifications,
},
props: {
// Disables panel styles, unread mark, potentially other notification-related actions
// meant for "Interactions" timeline
minimalMode: Boolean,
// Custom filter mode, an array of strings, possible values 'mention', 'status', 'repeat', 'like', 'follow', used to override global filter for use in "Interactions" timeline
filterMode: Array,
// Do not show extra notifications
noExtra: {
type: Boolean,
default: false,
},
// Disable teleporting (i.e. for /users/user/notifications)
disableTeleport: Boolean,
},
data() {
return {
showScrollTop: false,
bottomedOut: false,
// How many seen notifications to display in the list. The more there are,
// the heavier the page becomes. This count is increased when loading
// older notifications, and cut back to default whenever hitting "Read!".
seenToDisplayCount: DEFAULT_SEEN_TO_DISPLAY_COUNT,
}
},
provide() {
return {
popoversZLayer: computed(() => this.popoversZLayer),
}
},
computed: {
mainClass() {
return this.minimalMode ? '' : 'panel panel-default'
},
notifications() {
return notificationsFromStore(this.$store)
},
error() {
return this.$store.state.notifications.error
},
unseenNotifications() {
return unseenNotificationsFromStore(
this.$store,
useMergedConfigStore().mergedConfig.notificationVisibility,
useMergedConfigStore().mergedConfig.ignoreInactionableSeen,
)
},
filteredNotifications() {
if (this.unseenAtTop) {
return [
...filteredNotificationsFromStore(
this.$store,
useMergedConfigStore().mergedConfig.notificationVisibility,
).filter((n) => this.shouldShowUnseen(n)),
...filteredNotificationsFromStore(
this.$store,
useMergedConfigStore().mergedConfig.notificationVisibility,
).filter((n) => !this.shouldShowUnseen(n)),
]
} else {
return filteredNotificationsFromStore(
this.$store,
useMergedConfigStore().mergedConfig.notificationVisibility,
this.filterMode,
)
}
},
unseenCountBadgeText() {
return `${this.unseenCount ? this.unseenCount : ''}${this.extraNotificationsCount ? '*' : ''}`
},
unseenCount() {
return this.unseenNotifications.length
},
ignoreInactionableSeen() {
return useMergedConfigStore().mergedConfig.ignoreInactionableSeen
},
extraNotificationsCount() {
return countExtraNotifications(
this.$store,
useMergedConfigStore().mergedConfig,
+ useChatsStore().unreadChatsCount,
useAnnouncementsStore().unreadAnnouncementCount,
)
},
unseenCountTitle() {
return (
this.unseenNotifications.length +
- this.unreadChatCount +
+ this.unreadChatsCount +
this.unreadAnnouncementCount
)
},
loading() {
return this.$store.state.notifications.loading
},
noHeading() {
const { layoutType } = useInterfaceStore()
return this.minimalMode || layoutType === 'mobile'
},
teleportTarget() {
const { layoutType } = useInterfaceStore()
const map = {
wide: '#notifs-column',
mobile: '#mobile-notifications',
}
return map[layoutType] || '#notifs-sidebar'
},
popoversZLayer() {
const { layoutType } = useInterfaceStore()
return layoutType === 'mobile' ? 'navbar' : null
},
notificationsToDisplay() {
return this.filteredNotifications.slice(
0,
this.unseenCount + this.seenToDisplayCount,
)
},
noSticky() {
return useMergedConfigStore().mergedConfig.disableStickyHeaders
},
unseenAtTop() {
return useMergedConfigStore().mergedConfig.unseenAtTop
},
showExtraNotifications() {
return !this.noExtra
},
...mapState(useAnnouncementsStore, ['unreadAnnouncementCount']),
- ...mapGetters(['unreadChatCount']),
+ ...mapState(useChatsStore, ['unreadChatsCount']),
},
mounted() {
this.scrollerRef = this.$refs.root.closest('.column.-scrollable')
if (!this.scrollerRef) {
this.scrollerRef = this.$refs.root.closest('.mobile-notifications')
}
if (!this.scrollerRef) {
this.scrollerRef = this.$refs.root.closest('.column.main')
}
this.scrollerRef.addEventListener('scroll', this.updateScrollPosition)
},
unmounted() {
if (!this.scrollerRef) return
this.scrollerRef.removeEventListener('scroll', this.updateScrollPosition)
},
watch: {
unseenCountTitle(count) {
if (count > 0) {
FaviconService.drawFaviconBadge()
useInterfaceStore().setPageTitle(`(${count})`)
} else {
FaviconService.clearFaviconBadge()
useInterfaceStore().setPageTitle('')
}
},
teleportTarget() {
// handle scroller change
this.$nextTick(() => {
this.scrollerRef.removeEventListener(
'scroll',
this.updateScrollPosition,
)
this.scrollerRef = this.$refs.root.closest('.column.-scrollable')
if (!this.scrollerRef) {
this.scrollerRef = this.$refs.root.closest('.mobile-notifications')
}
this.scrollerRef.addEventListener('scroll', this.updateScrollPosition)
this.updateScrollPosition()
})
},
},
methods: {
scrollToTop() {
const scrollable = this.scrollerRef
scrollable.scrollTo({ top: this.$refs.root.offsetTop })
},
updateScrollPosition() {
this.showScrollTop =
this.$refs.root.offsetTop < this.scrollerRef.scrollTop
},
shouldShowUnseen(notification) {
if (notification.seen) return false
const actionable = ACTIONABLE_NOTIFICATION_TYPES.has(notification.type)
return this.ignoreInactionableSeen ? actionable : true
},
/* "Interacted" really refers to "actionable" notifications that require user input,
* everything else (likes/repeats/reacts) cannot be acted and therefore we just clear
* the "seen" status upon any clicks on them
*/
notificationClicked(notification) {
const { id } = notification
this.$store.dispatch('notificationClicked', { id })
},
notificationInteracted(notification) {
const { id } = notification
this.$store.dispatch('markSingleNotificationAsSeen', { id })
},
markAsSeen() {
this.$store.dispatch('markNotificationsAsSeen')
this.seenToDisplayCount = DEFAULT_SEEN_TO_DISPLAY_COUNT
},
fetchOlderNotifications() {
if (this.loading) {
return
}
const seenCount = this.filteredNotifications.length - this.unseenCount
if (this.seenToDisplayCount < seenCount) {
this.seenToDisplayCount = Math.min(
this.seenToDisplayCount + 20,
seenCount,
)
return
} else if (this.seenToDisplayCount > seenCount) {
this.seenToDisplayCount = seenCount
}
const store = this.$store
const credentials = store.state.users.currentUser.credentials
store.commit('setNotificationsLoading', { value: true })
notificationsFetcher
.fetchAndUpdate({
store,
credentials,
older: true,
})
.then((notifs) => {
store.commit('setNotificationsLoading', { value: false })
if (notifs.length === 0) {
this.bottomedOut = true
}
this.seenToDisplayCount += notifs.length
})
},
},
}
export default Notifications
diff --git a/src/components/poll/poll_form.js b/src/components/poll/poll_form.js
index e89935c7e1..5d0334a635 100644
--- a/src/components/poll/poll_form.js
+++ b/src/components/poll/poll_form.js
@@ -1,141 +1,151 @@
import Select from 'src/components/select/select.vue'
import { useInstanceStore } from 'src/stores/instance.js'
import * as DateUtils from 'src/services/date_utils/date_utils.js'
import { pollFallback } from 'src/services/poll/poll.service.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faPlus, faTimes } from '@fortawesome/free-solid-svg-icons'
library.add(faTimes, faPlus)
export default {
components: {
Select,
},
name: 'PollForm',
props: {
- visible: {},
- params: {
+ visible: Boolean,
+ modelValue: {
type: Object,
- required: true,
+ required: false,
+ default: null,
},
},
+ emits: ['update:modelValue'],
computed: {
pollType: {
get() {
- return pollFallback(this.params, 'pollType')
+ return pollFallback(this.modelValue, 'pollType')
},
set(newVal) {
- this.params.pollType = newVal
+ this.$emit('update:modelValue', {
+ ...this.modelValue,
+ pollType: newVal,
+ })
},
},
- options() {
- const hasOptions = !!this.params.options
- if (!hasOptions) {
- this.params.options = pollFallback(this.params, 'options')
- }
- return this.params.options
+ options: {
+ get() {
+ return pollFallback(this.modelValue, 'options')
+ },
+ set(newVal) {
+ this.$emit('update:modelValue', { ...this.modelValue, options: newVal })
+ },
},
expiryAmount: {
get() {
- return pollFallback(this.params, 'expiryAmount')
+ return pollFallback(this.modelValue, 'expiryAmount')
},
set(newVal) {
- this.params.expiryAmount = newVal
+ this.$emit('update:modelValue', {
+ ...this.modelValue,
+ expiryAmount: newVal,
+ })
},
},
expiryUnit: {
get() {
- return pollFallback(this.params, 'expiryUnit')
+ return pollFallback(this.modelValue, 'expiryUnit')
},
set(newVal) {
- this.params.expiryUnit = newVal
+ this.$emit('update:modelValue', {
+ ...this.modelValue,
+ expiryUnit: newVal,
+ })
},
},
pollLimits() {
return useInstanceStore().limits.pollLimits
},
maxOptions() {
return this.pollLimits.max_options
},
maxLength() {
return this.pollLimits.max_option_chars
},
expiryUnits() {
const allUnits = ['minutes', 'hours', 'days']
const expiry = this.convertExpiryFromUnit
return allUnits.filter(
(unit) => this.pollLimits.max_expiration >= expiry(unit, 1),
)
},
minExpirationInCurrentUnit() {
return Math.ceil(
this.convertExpiryToUnit(
this.expiryUnit,
this.pollLimits.min_expiration,
),
)
},
maxExpirationInCurrentUnit() {
return Math.floor(
this.convertExpiryToUnit(
this.expiryUnit,
this.pollLimits.max_expiration,
),
)
},
},
methods: {
- clear() {
- this.pollType = 'single'
- this.options = ['', '']
- this.expiryAmount = 10
- this.expiryUnit = 'minutes'
- },
nextOption(index) {
const element = this.$el.querySelector(`#poll-${index + 1}`)
if (element) {
element.focus()
} else {
// Try adding an option and try focusing on it
const addedOption = this.addOption()
if (addedOption) {
this.$nextTick(function () {
this.nextOption(index)
})
}
}
},
addOption() {
if (this.options.length < this.maxOptions) {
- this.options.push('')
+ this.options = [...this.options, '']
return true
}
return false
},
deleteOption(index) {
if (this.options.length > 2) {
this.options.splice(index, 1)
+ this.options = this.options
}
},
+ updateOption(index, value) {
+ this.options = this.options
+ },
convertExpiryToUnit(unit, amount) {
// Note: we want seconds and not milliseconds
return DateUtils.secondsToUnit(unit, amount)
},
convertExpiryFromUnit(unit, amount) {
return DateUtils.unitToSeconds(unit, amount)
},
expiryAmountChange() {
this.expiryAmount = Math.max(
this.minExpirationInCurrentUnit,
this.expiryAmount,
)
this.expiryAmount = Math.min(
this.maxExpirationInCurrentUnit,
this.expiryAmount,
)
},
},
}
diff --git a/src/components/poll/poll_form.vue b/src/components/poll/poll_form.vue
index ea45fd17fe..cb8a6f91fc 100644
--- a/src/components/poll/poll_form.vue
+++ b/src/components/poll/poll_form.vue
@@ -1,155 +1,156 @@
<template>
<div
v-if="visible"
class="poll-form"
>
<div
v-for="(option, index) in options"
:key="index"
class="poll-option"
>
<div class="input-container">
<input
:id="`poll-${index}`"
v-model="options[index]"
size="1"
class="input poll-option-input"
type="text"
:placeholder="$t('polls.option')"
:maxlength="maxLength"
@keydown.enter.stop.prevent="nextOption(index)"
+ @change="updateOption"
>
</div>
<button
v-if="options.length > 2"
class="delete-option button-unstyled -hover-highlight"
@click="deleteOption(index)"
>
<FAIcon icon="times" />
</button>
</div>
<button
v-if="options.length < maxOptions"
class="add-option faint button-unstyled -hover-highlight"
@click="addOption"
>
<FAIcon
icon="plus"
size="sm"
/>
{{ $t("polls.add_option") }}
</button>
<div class="poll-type-expiry">
<div
class="poll-type"
:title="$t('polls.type')"
>
<Select
v-model="pollType"
class="poll-type-select"
unstyled="true"
>
<option value="single">
{{ $t('polls.single_choice') }}
</option>
<option value="multiple">
{{ $t('polls.multiple_choices') }}
</option>
</Select>
</div>
<div
class="poll-expiry"
:title="$t('polls.expiry')"
>
<input
v-model="expiryAmount"
type="number"
class="input expiry-amount hide-number-spinner"
:min="minExpirationInCurrentUnit"
:max="maxExpirationInCurrentUnit"
@change="expiryAmountChange"
>
{{ ' ' }}
<Select
v-model="expiryUnit"
unstyled="true"
class="expiry-unit"
@change="expiryAmountChange"
>
<option
v-for="unit in expiryUnits"
:key="unit"
:value="unit"
>
{{ $t(`time.unit.${unit}_short`, [''], expiryAmount) }}
</option>
</Select>
</div>
</div>
</div>
</template>
<script src="./poll_form.js"></script>
<style lang="scss">
.poll-form {
display: flex;
flex-direction: column;
padding: 0 0.5em 0.5em;
.add-option {
align-self: flex-start;
padding-top: 0.25em;
padding-left: 0.1em;
}
.poll-option {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-bottom: 0.25em;
}
.input-container {
width: 100%;
input {
// Hack: dodge the floating X icon
padding-right: 2.5em;
width: 100%;
}
}
.delete-option {
// Hack: Move the icon over the input box
width: 1.5em;
margin-left: -1.5em;
z-index: 1;
}
.poll-type-expiry {
margin-top: 0.5em;
display: flex;
width: 100%;
}
.poll-type {
margin-right: 0.75em;
flex: 1 1 60%;
.poll-type-select {
padding-right: 0.75em;
}
}
.poll-expiry {
display: flex;
.expiry-amount {
width: 3em;
text-align: right;
}
}
}
</style>
diff --git a/src/components/post_status_form/post_status_form.js b/src/components/post_status_form/post_status_form.js
index bd2b44e546..02a70e388a 100644
--- a/src/components/post_status_form/post_status_form.js
+++ b/src/components/post_status_form/post_status_form.js
@@ -1,997 +1,1099 @@
-import { debounce, map, reject, uniqBy } from 'lodash'
+import {
+ debounce,
+ isEqual,
+ unescape as ldUnescape,
+ reject,
+ uniqBy,
+} from 'lodash'
import { mapActions, mapState } from 'pinia'
import { defineAsyncComponent } from 'vue'
import Attachment from 'src/components/attachment/attachment.vue'
import Checkbox from 'src/components/checkbox/checkbox.vue'
import DraftCloser from 'src/components/draft_closer/draft_closer.vue'
import EmojiInput from 'src/components/emoji_input/emoji_input.vue'
import suggestor from 'src/components/emoji_input/suggestor.js'
import Gallery from 'src/components/gallery/gallery.vue'
import MediaUpload from 'src/components/media_upload/media_upload.vue'
import Popover from 'src/components/popover/popover.vue'
import ScopeSelector from 'src/components/scope_selector/scope_selector.vue'
import Select from 'src/components/select/select.vue'
import StatusContent from 'src/components/status_content/status_content.vue'
import { propsToNative } from '../../services/attributes_helper/attributes_helper.service.js'
import { findOffset } from '../../services/offset_finder/offset_finder.service.js'
import genRandomSeed from '../../services/random_seed/random_seed.service.js'
import statusPoster from '../../services/status_poster/status_poster.service.js'
import { useEmojiStore } from 'src/stores/emoji.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
import { useInterfaceStore } from 'src/stores/interface.js'
import { useMediaViewerStore } from 'src/stores/media_viewer.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useSyncConfigStore } from 'src/stores/sync_config.js'
import { pollFormToMasto } from 'src/services/poll/poll.service.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faBan,
faChevronDown,
faChevronLeft,
faChevronRight,
faCircleNotch,
faPollH,
faQuoteRight,
faSmileBeam,
faTimes,
faUpload,
} from '@fortawesome/free-solid-svg-icons'
library.add(
faSmileBeam,
faPollH,
faUpload,
faQuoteRight,
faBan,
faTimes,
faCircleNotch,
faChevronDown,
faChevronLeft,
faChevronRight,
)
-const buildMentionsString = ({ user, attentions = [] }, currentUser) => {
- let allAttentions = [...attentions]
-
- allAttentions.unshift(user)
-
- allAttentions = uniqBy(allAttentions, 'id')
- allAttentions = reject(allAttentions, { id: currentUser.id })
-
- const mentions = map(allAttentions, (attention) => {
- return `@${attention.screen_name}`
- })
-
- return mentions.length > 0 ? mentions.join(' ') + ' ' : ''
-}
-
// Converts a string with px to a number like '2px' -> 2
const pxStringToNumber = (str) => {
return Number(str.substring(0, str.length - 2))
}
-const typeAndRefId = ({ replyTo, profileMention, statusId }) => {
- if (replyTo) {
- return ['reply', replyTo]
- } else if (profileMention) {
- return ['mention', profileMention]
- } else if (statusId) {
- return ['edit', statusId]
- } else {
- return ['new', '']
- }
-}
-
const PostStatusForm = {
- props: [
- 'statusId',
- 'statusText',
- 'statusIsSensitive',
- 'statusPoll',
- 'statusFiles',
- 'statusMediaDescriptions',
- 'statusScope',
- 'statusContentType',
- 'replyTo',
- 'repliedUser',
- 'attentions',
- 'copyMessageScope',
- 'subject',
- 'disableSubject',
- 'disableScopeSelector',
- 'disableVisibilitySelector',
- 'disableNotice',
- 'disableLockWarning',
- 'disablePolls',
- 'disableQuotes',
- 'disableSensitivityCheckbox',
- 'disableSubmit',
- 'disablePreview',
- 'disableDraft',
- 'hideDraft',
- 'closeable',
- 'placeholder',
- 'maxHeight',
- 'postHandler',
- 'preserveFocus',
- 'autoFocus',
- 'fileLimit',
- 'submitOnEnter',
- 'emojiPickerPlacement',
- 'optimisticPosting',
- 'profileMention',
- 'draftId',
- ],
+ props: {
+ // Status editing stuff
+ statusId: String,
+ statusText: String,
+ statusSubject: String,
+ statusIsSensitive: {
+ type: Boolean,
+ required: false,
+ default: null, // Avoiding automatic conversion null -> false
+ },
+ statusPoll: Object,
+ statusQuote: Object,
+ statusFiles: Array,
+ statusMediaDescriptions: Object,
+ statusVisibility: String,
+ statusContentType: String,
+
+ // Replies/mentions
+ repliedStatus: Object, // Object of a status replying to
+ profileMention: Object, // Mentioned user (used in profile page -> mention)
+
+ // Draft stuff
+ hideDraft: Boolean, // Disable drafts functionality
+ closeable: Boolean, // Whether form can be closed (i.e. in replies)
+ draftId: String, // ID of the draft to be used
+
+ // Chats stuff
+ chatView: Boolean, // Used for the "submit on enter" user setting
+ maxHeight: Number,
+ placeholder: String,
+ postHandler: Function, // Used to override poster to use chats one instead of status one
+ preserveFocus: Boolean, // Keep focus on form after posting
+ autoFocus: Boolean, // Steal focus when form is opened
+ fileLimit: Number, // Chats only support 1 attachment :(
+ emojiPickerPlacement: String,
+ optimisticPosting: Boolean, // Don't wait for confirmation that post is done
+
+ // Feature toggles for special cases (mostly chats)
+ mentionsLine: Boolean, // Use separate field for specifying mentions
+ mentionsLineReadOnly: Boolean, // Make the said field read-only (for chat conversation view)
+ disableSubject: Boolean,
+ disableScopeSelector: Boolean,
+ disableVisibilitySelector: Boolean,
+ disableNotice: Boolean,
+ disableLockWarning: Boolean,
+ disablePolls: Boolean,
+ disableQuotes: Boolean,
+ disableSensitivityCheckbox: Boolean,
+ disableSubmit: Boolean,
+ disablePreview: Boolean,
+ disableDraft: Boolean,
+ },
emits: [
'posted',
'draft-done',
'resize',
'mediaplay',
'mediapause',
'close-accepted',
'update',
],
+ data() {
+ return {
+ initialized: false,
+ randomSeed: genRandomSeed(),
+ // Posting stuff
+ idempotencyKey: '',
+ /* Data is initialized first, but we have no access to .computed yet
+ * which we need for some defaults (i.e. user configration)
+ * so we pre-fill with stuff meant for status editing and later
+ * back-fill with defaults in .created()
+ */
+ newStatus: {
+ status: this.statusText ?? null,
+ mentions: this.statusMentionLine ?? null,
+ spoilerText: this.statusSubject ?? null,
+ quote: this.statusQuote ?? null,
+ files: this.statusFiles ?? null,
+ poll: this.statusPoll ?? null,
+ mediaDescriptions: this.statusMediaDescriptions ?? null,
+ nsfw: this.statusIsSensitive ?? null,
+ visibility: this.statusVisibility ?? null,
+ contentType: this.statusContentType ?? null,
+ },
+
+ // Attachments
+ dropFiles: [],
+ uploadingFiles: false,
+ showDropIcon: 'hide',
+ dropStopTimeout: null,
+
+ // Preview
+ preview: null,
+ previewLoading: false,
+
+ // Draft
+ saveInhibited: true,
+ saveable: false,
+
+ // Misc States
+ emojiInputShown: false,
+ error: null,
+ posting: false,
+ }
+ },
components: {
MediaUpload,
EmojiInput,
PollForm: defineAsyncComponent(
() => import('src/components/poll/poll_form.vue'),
),
QuoteForm: defineAsyncComponent(
() => import('src/components/quote/quote_form.vue'),
),
ScopeSelector,
Checkbox,
Select,
Attachment,
StatusContent,
Gallery,
DraftCloser,
Popover,
},
- mounted() {
+ created() {
this.updateIdempotencyKey()
+
+ // If we are starting a new post, do not associate it with old drafts
+ const draft =
+ !this.disableDraft && (this.draftId || this.statusType !== 'new')
+ ? this.getDraft(this.statusType, this.refId)
+ : null
+
+ if (draft) {
+ // Copying and overriding defaults from the draft for each field
+ Object.keys(this.newStatus).forEach((key) => {
+ this.newStatus[key] = draft[key] ?? this.newStatus[key]
+ })
+ } else {
+ Object.entries(this.defaultNewStatus).forEach(([key, value]) => {
+ this.newStatus[key] = this.newStatus[key] ?? value
+ })
+ }
+
+ this.initialized = true
+ },
+ mounted() {
this.resize(this.$refs.textarea)
- if (this.replyTo) {
+ if (this.repliedStatus) {
const textLength = this.$refs.textarea.value.length
this.$refs.textarea.setSelectionRange(textLength, textLength)
}
- if (this.replyTo || this.autoFocus) {
+ if (this.repliedStatus || this.autoFocus) {
this.$refs.textarea.focus()
}
},
- data() {
- const preset = this.$route.query.message
- let statusText = preset || ''
-
- const { scopeCopy } = useMergedConfigStore().mergedConfig
-
- const [statusType, refId] = typeAndRefId({
- replyTo: this.replyTo,
- profileMention: this.profileMention && this.repliedUser?.id,
- statusId: this.statusId,
- })
-
- // If we are starting a new post, do not associate it with old drafts
- let statusParams =
- !this.disableDraft && (this.draftId || statusType !== 'new')
- ? this.getDraft(statusType, refId)
- : null
+ computed: {
+ // Visibility / expansion state of subcomponents
+ pollFormVisible() {
+ return this.hasPoll
+ },
+ quoteFormVisible() {
+ return this.hasQuote && !this.newStatus.quote.thread
+ },
+ showPreview() {
+ return !this.disablePreview && (!!this.preview || this.previewLoading)
+ },
- if (!statusParams) {
- if (statusType === 'reply' || statusType === 'mention') {
- const currentUser = this.$store.state.users.currentUser
- statusText = buildMentionsString(
- { user: this.repliedUser, attentions: this.attentions },
- currentUser,
- )
+ // Composing stuff
+ statusType() {
+ if (this.repliedStatus) {
+ return 'reply'
+ } else if (this.profileMention) {
+ return 'mention'
+ } else if (this.statusId) {
+ return 'edit'
+ } else {
+ return 'new'
+ }
+ },
+ refId() {
+ if (this.repliedStatus) {
+ return this.repliedStatus.id
+ } else if (this.profileMention) {
+ return this.profileMention.id
+ } else if (this.statusId) {
+ return this.statusId
+ } else {
+ return null
}
+ },
+ mentionsString() {
+ if (this.statusType !== 'reply' && this.statusType !== 'mention')
+ return ''
+ let allAttentions = [...(this.repliedStatus?.attentions || [])]
+ const repliedUser = this.repliedStatus?.user || this.profileMention
- const scope =
- (this.copyMessageScope && scopeCopy) ||
- this.copyMessageScope === 'direct'
- ? this.copyMessageScope
- : this.$store.state.users.currentUser.default_scope
+ if (repliedUser) allAttentions.unshift(repliedUser)
- const { postContentType: contentType, sensitiveByDefault } =
- useMergedConfigStore().mergedConfig
+ allAttentions = uniqBy(allAttentions, 'id')
+ allAttentions = reject(allAttentions, { id: this.currentUser.id })
- statusParams = {
- type: statusType,
- refId,
- spoilerText: this.subject || '',
- status: statusText,
- nsfw: !!sensitiveByDefault,
+ const mentions = allAttentions.map(
+ (attention) => `@${attention.screen_name}`,
+ )
+
+ return mentions.length > 0 ? mentions.join(' ') + ' ' : ''
+ },
+ newStatusContent() {
+ return this.mentionsLine
+ ? this.mentionsString + this.newStatus.status
+ : this.newStatus.status
+ },
+ defaultNewStatus() {
+ const defaultNewStatus = {
files: [],
- poll: {},
- hasPoll: false,
- hasQuote: false,
- quote: {
- id: '',
- url: '',
- thread: false,
- },
+ poll: null,
+ quote: null,
mediaDescriptions: {},
- visibility: scope,
- contentType,
- quoting: false,
- }
-
- if (statusType === 'edit') {
- const statusContentType = this.statusContentType || contentType
- statusParams = {
- type: statusType,
- refId,
- spoilerText: this.subject || '',
- status: this.statusText || '',
- nsfw: this.statusIsSensitive || !!sensitiveByDefault,
- files: this.statusFiles || [],
- poll: this.statusPoll || {},
- hasPoll: false,
- hasQuote: false,
- quote: {
- id: '',
- url: '',
- thread: false,
- },
- mediaDescriptions: this.statusMediaDescriptions || {},
- visibility: this.statusScope || scope,
- contentType: statusContentType,
+ }
+
+ const scope = (() => {
+ if (this.repliedStatus) {
+ if (this.repliedStatus.visibility === 'direct') return 'direct'
+ if (this.userDefaultScopeCopy) return this.repliedStatus.visibility
}
+ return this.userDefaultScope
+ })()
+
+ const preset = this.$route.query.message
+ const statusText = preset ?? ''
+
+ if (this.mentionsLine) {
+ defaultNewStatus.status = statusText
+ } else {
+ defaultNewStatus.status = this.mentionsString + statusText
}
- }
- return {
- randomSeed: genRandomSeed(),
- dropFiles: [],
- uploadingFiles: false,
- error: null,
- posting: false,
- highlighted: 0,
- newStatus: statusParams,
- caret: 0,
- showDropIcon: 'hide',
- dropStopTimeout: null,
- preview: null,
- previewLoading: false,
- emojiInputShown: false,
- idempotencyKey: '',
- saveInhibited: true,
- saveable: false,
- }
- },
- computed: {
- users() {
- return this.$store.state.users.users
+ defaultNewStatus.mentions = this.mentionsString.trim()
+ defaultNewStatus.spoilerText = this.repliedSubjectString ?? ''
+ defaultNewStatus.nsfw = this.userDefaultSensitive
+ defaultNewStatus.visibility = scope
+ defaultNewStatus.contentType = this.userDefaultPostContentType
+
+ return defaultNewStatus
},
- userDefaultScope() {
- return this.$store.state.users.currentUser.default_scope
+ // -Edit
+ isEdit() {
+ return typeof this.statusId !== 'undefined' && this.statusId.trim() !== ''
},
- showAllScopes() {
- return !this.mergedConfig.minimalScopesMode
+ // -Reply
+ isReply() {
+ return this.statusType === 'reply'
},
- hideExtraActions() {
- return this.disableDraft || this.hideDraft
+ inReplyToStatusId() {
+ return !this.hasQuote ||
+ !this.newStatus.quote.thread ||
+ !this.newStatus.quote.id
+ ? this.repliedStatus?.id
+ : undefined
+ },
+ repliedSubjectString() {
+ if (!this.repliedStatus?.summary) return null
+ const decodedSummary = ldUnescape(this.repliedStatus.summary)
+ const behavior = this.mergedConfig.subjectLineBehavior
+ const startsWithRe = decodedSummary.match(/^re[: ]/i)
+ if ((behavior !== 'noop' && startsWithRe) || behavior === 'masto') {
+ return decodedSummary
+ } else if (behavior === 'email') {
+ return 're: '.concat(decodedSummary)
+ } else if (behavior === 'noop') {
+ return ''
+ }
+ },
+ // -Poll
+ hasPoll() {
+ return this.newStatus.poll != null
+ },
+ // -Quotes
+ hasQuote() {
+ return this.newStatus.quote !== null
+ },
+ quotable() {
+ if (!this.quotingAvailable || !this.isReply) {
+ return false
+ }
+
+ if (
+ this.repliedStatus.visibility === 'public' ||
+ this.repliedStatus.visibility === 'unlisted' ||
+ this.repliedStatus.visibility === 'local'
+ ) {
+ return true
+ } else if (this.repliedStatus.visibility === 'private') {
+ return this.repliedStatus.user.id === this.currentUser.id
+ }
+
+ return false
},
+ quoteId() {
+ return this.newStatus.quote?.id ?? null
+ },
+ // This is for "reply/quote" toggle
+ quoteThreadToggled: {
+ get() {
+ return this.newStatus.quote?.thread
+ },
+ set(value) {
+ if (value) {
+ this.newStatus.quote = {}
+ this.newStatus.quote.thread = value
+ this.newStatus.quote.id = value ? this.repliedStatus.id : ''
+ } else {
+ this.newStatus.quote = null
+ }
+ },
+ },
+ postingOptions() {
+ const poll = this.hasPoll ? pollFormToMasto(this.newStatus.poll) : null
+
+ return {
+ status: this.newStatusContent,
+ spoilerText: this.newStatus.spoilerText,
+ visibility: this.newStatus.visibility,
+ sensitive: this.newStatus.nsfw,
+ media: this.newStatus.files,
+ inReplyToStatusId: this.inReplyToStatusId,
+ quoteId: this.quoteId,
+ contentType: this.newStatus.contentType,
+ poll,
+ idempotencyKey: this.idempotencyKey,
+
+ store: this.$store,
+ }
+ },
+
+ // Emoji stuff
emojiUserSuggestor() {
return suggestor({
emoji: [
...useEmojiStore().standardEmojiList,
...useEmojiStore().customEmoji,
],
store: this.$store,
})
},
emojiSuggestor() {
return suggestor({
emoji: [
...useEmojiStore().standardEmojiList,
...useEmojiStore().customEmoji,
],
})
},
emoji() {
return useEmojiStore().standardEmojiList
},
customEmoji() {
return useEmojiStore().customEmoji
},
+
+ // Length & Limits
statusLength() {
- return this.newStatus.status.length
+ return this.newStatusContent.length
},
spoilerTextLength() {
return this.newStatus.spoilerText.length
},
statusLengthLimit() {
return useInstanceStore().limits.textLimit
},
hasStatusLengthLimit() {
return this.statusLengthLimit > 0
},
charactersLeft() {
return (
this.statusLengthLimit - (this.statusLength + this.spoilerTextLength)
)
},
isOverLengthLimit() {
return this.hasStatusLengthLimit && this.charactersLeft < 0
},
- minimalScopesMode() {
- return useInstanceStore().minimalScopesMode
+ isEmptyStatus() {
+ return (
+ this.newStatus.status.trim() === '' && this.newStatus.files.length === 0
+ )
},
- alwaysShowSubject() {
- return this.mergedConfig.alwaysShowSubjectInput
+ uploadFileLimitReached() {
+ return this.newStatus.files.length >= this.fileLimit
},
- postFormats() {
- return useInstanceCapabilitiesStore().postFormats || []
+
+ // Drafts
+ isDirty() {
+ return Object.entries(this.defaultNewStatus).some(
+ ([key, defaultValue]) => {
+ const actualValue = this.newStatus[key]
+ if (actualValue === null) return false
+ return !isEqual(actualValue, defaultValue)
+ },
+ )
},
- safeDMEnabled() {
- return useInstanceCapabilitiesStore().safeDM
+ shouldAutoSaveDraft() {
+ return useMergedConfigStore().mergedConfig.autoSaveDraft
},
- pollsAvailable() {
+ debouncedMaybeAutoSaveDraft() {
+ return debounce(this.maybeAutoSaveDraft, 3000)
+ },
+ autoSaveState() {
+ if (this.saveable) {
+ return this.$t('post_status.auto_save_saving')
+ } else if (this.newStatus.id) {
+ return this.$t('post_status.auto_save_saved')
+ } else {
+ return this.$t('post_status.auto_save_nothing_new')
+ }
+ },
+ safeToSaveDraft() {
return (
- useInstanceCapabilitiesStore().pollsAvailable &&
- useInstanceStore().limits.pollLimits.max_options >= 2 &&
- this.disablePolls !== true
+ (this.newStatus.status ||
+ this.newStatus.spoilerText ||
+ this.newStatus.files.length ||
+ this.hasPoll ||
+ this.hasQuote) &&
+ this.saveable
)
},
- hideScopeNotice() {
+ hasEmptyDraft() {
return (
- this.disableNotice ||
- useMergedConfigStore().mergedConfig.hideScopeNotice
+ this.newStatus.id &&
+ !(
+ this.newStatus.status ||
+ this.newStatus.spoilerText ||
+ this.newStatus.files.length ||
+ this.hasPoll ||
+ this.hasQuote
+ )
)
},
+
+ // Error handling
pollContentError() {
return (
this.pollFormVisible && this.newStatus.poll && this.newStatus.poll.error
)
},
- showPreview() {
- return !this.disablePreview && (!!this.preview || this.previewLoading)
+
+ // Featureset detection
+ postFormats() {
+ return useInstanceCapabilitiesStore().postFormats || []
+ },
+ safeDMEnabled() {
+ return useInstanceCapabilitiesStore().safeDM
},
- emptyStatus() {
+ pollsAvailable() {
return (
- this.newStatus.status.trim() === '' && this.newStatus.files.length === 0
+ useInstanceCapabilitiesStore().pollsAvailable &&
+ useInstanceStore().limits.pollLimits.max_options >= 2 &&
+ this.disablePolls !== true
)
},
- uploadFileLimitReached() {
- return this.newStatus.files.length >= this.fileLimit
- },
- isEdit() {
- return typeof this.statusId !== 'undefined' && this.statusId.trim() !== ''
+ hideExtraActions() {
+ return this.disableDraft || this.hideDraft
},
quotingAvailable() {
if (!useInstanceCapabilitiesStore().quotingAvailable) {
return false
}
return this.disableQuotes !== true
},
- isReply() {
- return this.newStatus.type === 'reply'
- },
- quotable() {
- return this.quotingAvailable && this.replyTo
- },
- quoteThreadToggled: {
- get() {
- return this.newStatus.hasQuote && this.newStatus.quote.thread
- },
- set(value) {
- this.newStatus.hasQuote = value
- this.newStatus.quote.thread = value
- this.newStatus.quote.id = value ? this.replyTo : ''
- },
- },
- defaultQuotable() {
- if (
- !this.quotingAvailable ||
- !this.isReply ||
- !useMergedConfigStore().mergedConfig.quoteReply
- ) {
- return false
- }
-
- const repliedStatus =
- this.$store.state.statuses.allStatusesObject[this.replyTo]
- if (!repliedStatus) {
- return false
- }
- if (
- repliedStatus.visibility === 'public' ||
- repliedStatus.visibility === 'unlisted' ||
- repliedStatus.visibility === 'local'
- ) {
- return true
- } else if (repliedStatus.visibility === 'private') {
- return repliedStatus.user.id === this.$store.state.users.currentUser.id
- }
-
- return false
- },
- inReplyStatusId() {
- return !this.newStatus.hasQuote ||
- !this.newStatus.quote.thread ||
- !this.newStatus.quote.id
- ? this.replyTo
- : undefined
+ // User configuration
+ userDefaultScope() {
+ return this.currentUser.default_scope
},
- quoteId() {
- return this.newStatus.hasQuote ? this.newStatus.quote.id : undefined
+ userDefaultPostContentType() {
+ return this.mergedConfig.postContentType
},
- debouncedMaybeAutoSaveDraft() {
- return debounce(this.maybeAutoSaveDraft, 3000)
+ userDefaultScopeCopy() {
+ return this.mergedConfig.scopeCopy
},
- pollFormVisible() {
- return this.newStatus.hasPoll
+ userDefaultSensitive() {
+ return this.mergedConfig.sensitiveByDefault
},
- quoteFormVisible() {
- return this.newStatus.hasQuote && !this.newStatus.quote.thread
+ showAllScopes() {
+ return !this.mergedConfig.minimalScopesMode
},
- shouldAutoSaveDraft() {
- return useMergedConfigStore().mergedConfig.autoSaveDraft
+ minimalScopesMode() {
+ return this.mergedConfig.minimalScopesMode
},
- autoSaveState() {
- if (this.saveable) {
- return this.$t('post_status.auto_save_saving')
- } else if (this.newStatus.id) {
- return this.$t('post_status.auto_save_saved')
- } else {
- return this.$t('post_status.auto_save_nothing_new')
- }
+ alwaysShowSubject() {
+ return this.mergedConfig.alwaysShowSubjectInput
},
- safeToSaveDraft() {
+ hideScopeNotice() {
return (
- (this.newStatus.status ||
- this.newStatus.spoilerText ||
- this.newStatus.files?.length ||
- this.newStatus.hasPoll ||
- this.newStatus.hasQuote) &&
- this.saveable
+ this.disableNotice ||
+ useMergedConfigStore().mergedConfig.hideScopeNotice
)
},
- hasEmptyDraft() {
- return (
- this.newStatus.id &&
- !(
- this.newStatus.status ||
- this.newStatus.spoilerText ||
- this.newStatus.files?.length ||
- this.newStatus.hasPoll ||
- this.newStatus.hasQuote
- )
- )
+ submitOnEnter() {
+ return this.chatView && this.mergedConfig.chatSubmitOnEnter
+ },
+
+ // Global stuff
+ currentUser() {
+ return this.$store.state.users.currentUser
},
...mapState(useMergedConfigStore, ['mergedConfig']),
...mapState(useInterfaceStore, {
mobileLayout: (store) => store.mobileLayout,
}),
},
watch: {
- newStatus: {
- deep: true,
- handler() {
- this.statusChanged()
- },
+ isDirty(newVal, oldVal) {
+ this.statusChanged()
},
saveable(val) {
// https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event#usage_notes
// MDN says we'd better add the beforeunload event listener only when needed, and remove it when it's no longer needed
if (val) {
this.addBeforeUnloadListener()
} else {
this.removeBeforeUnloadListener()
}
},
},
- beforeUnmount() {
- this.maybeAutoSaveDraft()
- this.removeBeforeUnloadListener()
- },
methods: {
- ...mapActions(useMediaViewerStore, ['increment']),
- statusChanged() {
- this.autoPreview()
- this.updateIdempotencyKey()
- this.debouncedMaybeAutoSaveDraft()
- this.saveable = true
- this.saveInhibited = false
+ // Composing
+ update() {
+ Object.entries(this.defaultNewStatus).forEach(([key, value]) => {
+ if (key === 'status') return
+ this.newStatus[key] = value
+ })
+ },
+ onMentionsLineUpdate(e) {
+ if (this.mentionsLineReadOnly) return
+ this.newStatus.mentions = e
+ },
+ changeVis(visibility) {
+ this.newStatus.visibility = visibility
},
clearStatus() {
- const newStatus = this.newStatus
this.saveInhibited = true
- this.newStatus = {
- status: '',
- spoilerText: '',
- files: [],
- visibility: newStatus.visibility,
- contentType: newStatus.contentType,
- poll: {},
- hasPoll: false,
- hasQuote: false,
- quote: {},
- mediaDescriptions: {},
- }
+ this.newStatus.status = ''
+ this.newStatus.mentions = ''
+ this.newStatus.spoilerText = ''
+ this.newStatus.files = []
+ this.newStatus.poll = null
+ this.newStatus.quote = null
+ this.newStatus.nsfw = this.defaultNewStatus.nsfw
+ this.newStatus.mediaDescriptions = {}
this.$refs.mediaUpload && this.$refs.mediaUpload.clearFile()
- this.clearPollForm()
- this.clearQuoteForm()
if (this.preserveFocus) {
this.$nextTick(() => {
this.$refs.textarea.focus()
})
}
const el = this.$el.querySelector('textarea')
el.style.height = 'auto'
el.style.height = undefined
this.error = null
if (this.preview) this.previewStatus()
this.saveable = false
},
- async postStatus(event, newStatus) {
+ async postStatus(event) {
if (this.posting && !this.optimisticPosting) {
return
}
if (this.disableSubmit) {
return
}
if (this.emojiInputShown) {
return
}
if (this.submitOnEnter) {
event.stopPropagation()
event.preventDefault()
}
if (
this.optimisticPosting &&
- (this.emptyStatus || this.isOverLengthLimit)
+ (this.isEmptyStatus || this.isOverLengthLimit)
) {
return
}
- if (this.emptyStatus) {
+ if (this.isEmptyStatus) {
this.error = this.$t('post_status.empty_status_error')
return
}
- const poll = newStatus.hasPoll ? pollFormToMasto(newStatus.poll) : {}
if (this.pollContentError) {
this.error = this.pollContentError
return
}
this.posting = true
try {
await this.setAllMediaDescriptions()
} catch {
this.error = this.$t('post_status.media_description_error')
this.posting = false
return
}
- const postingOptions = {
- status: newStatus.status,
- spoilerText: newStatus.spoilerText || null,
- visibility: newStatus.visibility,
- sensitive: newStatus.nsfw,
- media: newStatus.files,
- store: this.$store,
- inReplyToStatusId: this.inReplyStatusId,
- quoteId: this.quoteId,
- contentType: newStatus.contentType,
- poll,
- idempotencyKey: this.idempotencyKey,
- }
-
const postHandler = this.postHandler
? this.postHandler
: statusPoster.postStatus
- postHandler(postingOptions)
+ postHandler(this.postingOptions)
.then((data) => {
this.abandonDraft()
this.clearStatus()
+ this.updateIdempotencyKey()
this.$emit('posted', data)
})
.catch((error) => {
this.error = error
})
.finally(() => {
this.posting = false
})
},
+
+ // Preview
previewStatus() {
- if (this.emptyStatus && this.newStatus.spoilerText.trim() === '') {
+ if (this.isEmptyStatus && this.newStatus.spoilerText.trim() === '') {
this.preview = { error: this.$t('post_status.preview_empty') }
this.previewLoading = false
return
}
- const newStatus = this.newStatus
this.previewLoading = true
statusPoster
.postStatus({
- status: newStatus.status,
- spoilerText: newStatus.spoilerText || null,
- visibility: newStatus.visibility,
- sensitive: newStatus.nsfw,
+ ...this.postingOptions,
media: [],
- store: this.$store,
- inReplyToStatusId: this.inReplyStatusId,
- quoteId: this.quoteId,
- contentType: newStatus.contentType,
- poll: {},
+ poll: null,
preview: true,
})
.then((data) => {
// Don't apply preview if not loading, because it means
// user has closed the preview manually.
if (!this.previewLoading) return
this.preview = data
})
.catch((error) => {
this.preview = { error }
})
.finally(() => {
this.previewLoading = false
})
},
debouncePreviewStatus: debounce(function () {
this.previewStatus()
}, 500),
autoPreview() {
if (!this.preview) return
this.previewLoading = true
this.debouncePreviewStatus()
},
closePreview() {
this.preview = null
this.previewLoading = false
},
togglePreview() {
if (this.showPreview) {
this.closePreview()
} else {
this.previewStatus()
}
},
+
+ // Attachments
+ 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)))
+ },
addMediaFile(fileInfo) {
this.newStatus.files.push(fileInfo)
this.$emit('resize', { delayed: true })
},
removeMediaFile(fileInfo) {
const index = this.newStatus.files.indexOf(fileInfo)
this.newStatus.files.splice(index, 1)
this.$emit('resize')
},
editAttachment(fileInfo, newText) {
this.newStatus.mediaDescriptions[fileInfo.id] = newText
},
shiftUpMediaFile(fileInfo) {
const { files } = this.newStatus
const index = this.newStatus.files.indexOf(fileInfo)
+ if (index === 0) return
files.splice(index, 1)
files.splice(index - 1, 0, fileInfo)
},
shiftDnMediaFile(fileInfo) {
const { files } = this.newStatus
const index = this.newStatus.files.indexOf(fileInfo)
+ if (index === files.length - 1) return
files.splice(index, 1)
files.splice(index + 1, 0, fileInfo)
},
uploadFailed(errString, templateArgs) {
templateArgs = templateArgs || {}
this.error =
this.$t('upload.error.base') +
' ' +
this.$t('upload.error.' + errString, templateArgs)
},
startedUploadingFiles() {
this.uploadingFiles = true
},
finishedUploadingFiles() {
this.$emit('resize')
this.uploadingFiles = false
},
paste(e) {
this.autoPreview()
this.resize(e)
if (e.clipboardData.files.length > 0) {
// prevent pasting of file as text
e.preventDefault()
// 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')) {
e.preventDefault() // allow dropping text like before
this.dropFiles = e.dataTransfer.files
clearTimeout(this.dropStopTimeout)
this.showDropIcon = 'hide'
}
},
fileDragStop() {
// 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)
this.showDropIcon = 'fade'
this.dropStopTimeout = setTimeout(() => (this.showDropIcon = 'hide'), 500)
},
fileDrag(e) {
e.dataTransfer.dropEffect = this.uploadFileLimitReached ? 'none' : 'copy'
if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {
clearTimeout(this.dropStopTimeout)
this.showDropIcon = 'show'
}
},
+
+ // Auto-sizable input field
+ // TODO separate into its own component pls
onEmojiInputInput() {
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.$emit('resize')
return
}
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
*/
const bottomBottomPaddingStr =
window.getComputedStyle(bottomRef)['padding-bottom']
const bottomBottomPadding = pxStringToNumber(bottomBottomPaddingStr)
const scrollerRef =
this.$el.closest('.column.-scrollable') ||
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 = pxStringToNumber(topPaddingStr)
const bottomPadding = pxStringToNumber(bottomPaddingStr)
const vertPadding = topPadding + bottomPadding
const oldHeight = pxStringToNumber(target.style.height)
/* 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
* the scroll since there might be not enough padding around form-bottom to even
* 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 heightWithoutPadding = Math.floor(target.scrollHeight - vertPadding)
let newHeight = this.maxHeight
? Math.min(heightWithoutPadding, this.maxHeight)
: heightWithoutPadding
// This is a bit of a hack to combat target.scrollHeight being different on every other input
// on some browsers for whatever reason. Don't change the height if difference is 1px or less.
if (Math.abs(newHeight - oldHeight) <= 1) {
newHeight = oldHeight
}
target.style.height = `${newHeight}px`
this.$emit('resize', newHeight)
// END content size update
// We check where the bottom border of form-bottom element is, this uses findOffset
// to find offset relative to scrollable container (scroller)
const bottomBottomBorder =
bottomRef.offsetHeight +
findOffset(bottomRef, scrollerRef).top +
bottomBottomPadding
const isBottomObstructed = scrollerBottomBorder < bottomBottomBorder
const isFormBiggerThanScroller = scrollerHeight < formRef.offsetHeight
const bottomChangeDelta = bottomBottomBorder - scrollerBottomBorder
// The intention is basically this;
// 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 &&
!(
isFormBiggerThanScroller &&
this.$refs.textarea.selectionStart !==
this.$refs.textarea.value.length
)
const totalDelta = shouldScrollToBottom ? bottomChangeDelta : 0
const targetScroll = Math.round(currentScroll + totalDelta)
if (scrollerRef === window) {
scrollerRef.scroll(0, targetScroll)
} else {
scrollerRef.scrollTop = targetScroll
}
},
- clearError() {
- this.error = null
- },
- changeVis(visibility) {
- this.newStatus.visibility = visibility
- },
+
+ // Poll
togglePollForm() {
- this.newStatus.hasPoll = !this.newStatus.hasPoll
+ this.newStatus.poll = this.hasPoll ? null : {}
},
setPoll(poll) {
this.newStatus.poll = poll
},
- clearPollForm() {
- if (this.$refs.pollForm) {
- this.$refs.pollForm.clear()
- }
- },
- clearQuoteForm() {
- if (this.$refs.quoteForm) {
- this.$refs.quoteForm.clear()
+
+ // Quote
+ toggleQuoteForm() {
+ // This is for the "attach quote" button
+ if (!this.hasQuote) {
+ this.newStatus.quote = {}
+ this.newStatus.quote.thread = false
+ this.newStatus.quote.id = null
+ this.newStatus.quote.url = ''
+ } else {
+ this.newStatus.quote = null
}
},
- toggleQuoteForm() {
- this.newStatus.hasQuote = !this.newStatus.hasQuote
- this.newStatus.quote = {}
- this.newStatus.quote.thread = false
- this.newStatus.quote.id = null
- this.newStatus.quote.url = ''
- },
- dismissScopeNotice() {
- useSyncConfigStore().setSimplePrefAndSave({
- path: 'hideScopeNotice',
- value: true,
- })
- },
- 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)))
- },
- handleEmojiInputShow(value) {
- this.emojiInputShown = value
- },
- updateIdempotencyKey() {
- this.idempotencyKey = Date.now().toString()
- },
- openProfileTab() {
- useInterfaceStore().openSettingsModalTab('profile')
- },
- propsToNative(props) {
- return propsToNative(props)
+ // Drafts
+ statusChanged() {
+ this.autoPreview()
+ this.updateIdempotencyKey()
+ this.debouncedMaybeAutoSaveDraft()
+ this.saveable = true
+ this.saveInhibited = false
},
saveDraft() {
if (!this.disableDraft && !this.saveInhibited) {
if (this.safeToSaveDraft) {
return this.$store
- .dispatch('addOrSaveDraft', { draft: this.newStatus })
+ .dispatch('addOrSaveDraft', {
+ draft: {
+ type: this.statusType,
+ refId: this.refId,
+ ...this.newStatus,
+ },
+ })
.then((id) => {
if (this.newStatus.id !== id) {
this.newStatus.id = id
}
this.saveable = false
if (!this.shouldAutoSaveDraft) {
this.clearStatus()
+ this.updateIdempotencyKey()
this.$emit('draft-done')
}
})
} else if (this.hasEmptyDraft) {
// There is a draft, but there is nothing in it, clear it
return this.abandonDraft().then(() => {
this.saveable = false
if (!this.shouldAutoSaveDraft) {
this.clearStatus()
+ this.updateIdempotencyKey()
this.$emit('draft-done')
}
})
}
}
return Promise.resolve()
},
maybeAutoSaveDraft() {
if (this.shouldAutoSaveDraft) {
this.saveDraft(false)
}
},
abandonDraft() {
- return this.$store.dispatch('abandonDraft', { id: this.newStatus.id })
+ return this.$store.dispatch('abandonDraft', { id: this.draftId })
},
- getDraft(statusType, refId) {
+ getDraft() {
const maybeDraft = this.$store.state.drafts.drafts[this.draftId]
if (this.draftId && maybeDraft) {
return maybeDraft
} else {
const existingDrafts = this.$store.getters.draftsByTypeAndRefId(
- statusType,
- refId,
+ this.statusType,
+ this.refId,
)
if (existingDrafts.length) {
return existingDrafts[0]
}
}
// No draft available, fall back
},
requestClose() {
if (!this.saveable) {
this.$emit('close-accepted')
} else {
this.$refs.draftCloser.requestClose()
}
},
saveAndCloseDraft() {
this.saveDraft().then(() => {
this.$emit('close-accepted')
})
},
discardAndCloseDraft() {
this.abandonDraft().then(() => {
this.$emit('close-accepted')
})
},
addBeforeUnloadListener() {
this._beforeUnloadListener ||= () => {
this.saveDraft()
}
window.addEventListener('beforeunload', this._beforeUnloadListener)
},
removeBeforeUnloadListener() {
if (this._beforeUnloadListener) {
window.removeEventListener('beforeunload', this._beforeUnloadListener)
}
},
+
+ // Misc
+ propsToNative(props) {
+ return propsToNative(props)
+ },
+ handleEmojiInputShow(value) {
+ this.emojiInputShown = value
+ },
+ updateIdempotencyKey() {
+ this.idempotencyKey = Date.now().toString()
+ },
+ openProfileTab() {
+ useInterfaceStore().openSettingsModalTab('profile')
+ },
+ dismissScopeNotice() {
+ useSyncConfigStore().setSimplePrefAndSave({
+ path: 'hideScopeNotice',
+ value: true,
+ })
+ },
+ clearError() {
+ this.error = null
+ },
+ ...mapActions(useMediaViewerStore, ['increment']),
+ },
+ beforeUnmount() {
+ this.maybeAutoSaveDraft()
+ this.removeBeforeUnloadListener()
},
}
export default PostStatusForm
diff --git a/src/components/post_status_form/post_status_form.scss b/src/components/post_status_form/post_status_form.scss
index 3d78884fe5..2b00dd1f4e 100644
--- a/src/components/post_status_form/post_status_form.scss
+++ b/src/components/post_status_form/post_status_form.scss
@@ -1,281 +1,290 @@
.post-status-form {
position: relative;
+ form {
+ display: flex;
+ flex-direction: column;
+ padding: 0.5em;
+ position: relative;
+ gap: 0.25em;
+ }
+
+ .form-group {
+ display: flex;
+ flex-direction: column;
+ line-height: 1.85;
+ }
+
.attachments {
margin-bottom: 0.5em;
}
.more-post-actions {
height: 100%;
.btn {
height: 100%;
}
}
.form-bottom {
display: flex;
justify-content: space-between;
- padding: 0.5em;
height: 2.5em;
.post-button-group {
width: 10em;
display: flex;
.post-button {
flex: 1 0 auto;
}
.more-post-actions {
flex: 0 0 auto;
}
}
p {
margin: 0.35em;
padding: 0.35em;
display: flex;
}
}
.form-bottom-left {
display: flex;
gap: 1.5em;
- margin-right: 1em;
+ margin: 0 0.5em;
button {
- padding: 0.5em;
- margin: -0.5em;
+ padding: 0.25em;
+ margin: -0.25em;
}
}
.preview-heading {
display: flex;
flex-wrap: wrap;
margin: 0 0.5em;
}
.preview-toggle {
flex: 10 0 auto;
cursor: pointer;
user-select: none;
&:hover {
text-decoration: underline;
}
svg,
i {
margin-left: 0.2em;
font-size: 0.8em;
transform: rotate(90deg);
}
}
.preview-container {
margin-bottom: 1em;
}
.preview-error {
font-style: italic;
color: var(--textFaint);
}
.preview-status {
border: 1px solid var(--border);
border-radius: var(--roundness);
padding: 0.5em;
margin: 0;
}
.reply-or-quote-selector {
margin-bottom: 0.5em;
gap: 0 1em;
display: flex;
flex-wrap: wrap-reverse;
grid-template-columns: 1fr 1fr;
}
.text-format {
.only-format {
color: var(--textFaint);
}
}
.visibility-tray {
display: flex;
justify-content: space-between;
align-items: baseline;
}
.visibility-notice {
border: 1px solid var(--border);
border-radius: var(--roundness);
}
.visibility-notice.edit-warning {
> :first-child {
margin-top: 0;
}
> :last-child {
margin-bottom: 0;
}
}
// Order is not necessary but a good indicator
.media-upload-icon {
order: 1;
justify-content: left;
}
.emoji-icon {
order: 2;
justify-content: center;
}
.poll-icon {
order: 3;
justify-content: center;
}
.quote-icon {
order: 4;
justify-content: right;
}
.bottom-left-button {
font-size: 1.85em;
line-height: 1.1;
flex: 1;
padding: 0 0.1em;
display: flex;
align-items: center;
}
.error {
text-align: center;
}
.media-upload-wrapper {
margin-right: 0.2em;
margin-bottom: 0.5em;
width: 18em;
img,
video {
object-fit: contain;
max-height: 10em;
}
.video {
max-height: 10em;
}
input {
flex: 1;
width: 100%;
}
}
.status-input-wrapper {
display: flex;
position: relative;
width: 100%;
flex-direction: column;
}
.btn[disabled] {
cursor: not-allowed;
}
- form {
- display: flex;
- flex-direction: column;
- margin: 0.6em;
- position: relative;
- }
-
- .form-group {
+ .inputs-wrapper {
+ padding: 0;
display: flex;
flex-direction: column;
- padding: 0.25em 0.5em 0.5em;
- line-height: 1.85;
}
- .inputs-wrapper {
- padding: 0;
+ .keyboard-enter-hint {
+ text-align: right;
+ line-height: 1;
}
textarea.input.form-post-body {
// TODO: make a resizable textarea component?
box-sizing: content-box; // needed for easier computation of dynamic size
overflow: hidden;
transition: min-height 200ms 100ms;
// stock padding + 1 line of text (for counter)
padding-bottom: calc(var(--_padding) + var(--post-line-height) * 1em);
padding-right: 0.5em;
// two lines of text
height: calc(var(--post-line-height) * 1em);
min-height: calc(var(--post-line-height) * 1em);
resize: none;
background: transparent;
text-wrap: stable;
&.scrollable-form {
overflow-y: auto;
}
}
.main-input {
position: relative;
}
.subject-input {
border-bottom: 1px solid var(--border);
}
+ .mentions-input {
+ border-bottom: 1px solid var(--border);
+ }
+
.character-counter {
position: absolute;
bottom: 0;
right: 2.2em;
padding: 0;
margin: 0;
line-height: 2.2em;
height: 2.2em;
&.error {
color: var(--cRed);
}
}
@keyframes fade-in {
from { opacity: 0; }
to { opacity: 0.6; }
}
@keyframes fade-out {
from { opacity: 0.6; }
to { opacity: 0; }
}
.drop-indicator {
position: absolute;
- width: 100%;
- height: 100%;
+ inset: 0;
font-size: 5em;
display: flex;
align-items: center;
justify-content: center;
opacity: 0.6;
color: var(--text);
background-color: var(--bg);
border-radius: var(--roundness);
border: 2px dashed var(--text);
}
.auto-save-status {
align-self: center;
}
}
diff --git a/src/components/post_status_form/post_status_form.vue b/src/components/post_status_form/post_status_form.vue
index 6c82d4b48e..e387862066 100644
--- a/src/components/post_status_form/post_status_form.vue
+++ b/src/components/post_status_form/post_status_form.vue
@@ -1,434 +1,454 @@
<template>
<div
ref="form"
class="post-status-form"
+ v-if="initialized"
>
<form
autocomplete="off"
@submit.prevent
@dragover.prevent="fileDrag"
>
<div class="form-group">
<div
- v-if="!$store.state.users.currentUser.locked && newStatus.visibility == 'private' && !disableLockWarning"
+ v-if="!currentUser.locked && newStatus.visibility == 'private' && !disableLockWarning"
class="visibility-notice notice-dismissible"
>
<i18n-t
keypath="post_status.account_not_locked_warning"
tag="p"
class=""
scope="global"
>
<button
class="button-unstyled -link"
@click="openProfileTab"
>
{{ $t('post_status.account_not_locked_warning_link') }}
</button>
</i18n-t>
</div>
<p
v-if="!hideScopeNotice && newStatus.visibility === 'public'"
class="visibility-notice notice-dismissible"
>
<span>{{ $t('post_status.scope_notice.public') }}</span>
<a
class="fa-scale-110 fa-old-padding dismiss"
:title="$t('post_status.scope_notice_dismiss')"
role="button"
tabindex="0"
@click.prevent="dismissScopeNotice()"
>
<FAIcon icon="times" />
</a>
</p>
<p
v-else-if="!hideScopeNotice && newStatus.visibility === 'unlisted'"
class="visibility-notice notice-dismissible"
>
<span>{{ $t('post_status.scope_notice.unlisted') }}</span>
<a
class="fa-scale-110 fa-old-padding dismiss"
:title="$t('post_status.scope_notice_dismiss')"
role="button"
tabindex="0"
@click.prevent="dismissScopeNotice()"
>
<FAIcon icon="times" />
</a>
</p>
<p
- v-else-if="!hideScopeNotice && newStatus.visibility === 'private' && $store.state.users.currentUser.locked"
+ v-else-if="!hideScopeNotice && newStatus.visibility === 'private' && currentUser.locked"
class="visibility-notice notice-dismissible"
>
<span>{{ $t('post_status.scope_notice.private') }}</span>
<a
class="fa-scale-110 fa-old-padding dismiss"
:title="$t('post_status.scope_notice_dismiss')"
role="button"
tabindex="0"
@click.prevent="dismissScopeNotice()"
>
<FAIcon icon="times" />
</a>
</p>
<p
- v-else-if="newStatus.visibility === 'direct'"
+ v-else-if="!hideScopeNotice && newStatus.visibility === 'direct'"
class="visibility-notice notice-dismissible"
>
<span v-if="safeDMEnabled">{{ $t('post_status.direct_warning_to_first_only') }}</span>
<span v-else>{{ $t('post_status.direct_warning_to_all') }}</span>
</p>
<div
v-if="isEdit"
class="visibility-notice edit-warning"
>
<p>{{ $t('post_status.edit_remote_warning') }}</p>
<p>{{ $t('post_status.edit_unsupported_warning') }}</p>
</div>
<div
v-if="!disablePreview"
class="preview-heading"
>
<a
class="preview-toggle faint"
@click.stop.prevent="togglePreview"
>
{{ $t('post_status.preview') }}
<FAIcon :icon="showPreview ? 'chevron-left' : 'chevron-right'" />
</a>
<div
v-show="previewLoading"
class="preview-spinner"
>
<FAIcon
class="fa-old-padding"
spin
icon="circle-notch"
/>
</div>
<div
v-if="quotable"
role="radiogroup"
class="reply-or-quote-selector"
>
<Checkbox
v-model="quoteThreadToggled"
:radio="true"
:disabled="quoteFormVisible"
>
{{ $t('post_status.quote_option') }}
</Checkbox>
<Checkbox
role="radio"
:radio="true"
:model-value="!quoteThreadToggled"
:disabled="quoteFormVisible"
@update:model-value="e => quoteThreadToggled = !e"
>
{{ $t('post_status.reply_option') }}
</Checkbox>
</div>
</div>
<div
v-if="showPreview"
class="preview-container"
>
<div
v-if="!preview"
class="preview-status"
>
{{ $t('general.loading') }}
</div>
<div
v-else-if="preview.error"
class="preview-status preview-error"
>
{{ preview.error }}
</div>
<StatusContent
v-else
:status="preview"
class="preview-status"
/>
</div>
<div class="input inputs-wrapper">
<EmojiInput
v-if="!disableSubject && (newStatus.spoilerText || alwaysShowSubject)"
v-model="newStatus.spoilerText"
enable-emoji-picker
:suggest="emojiSuggestor"
class="input form-control subject-input unstyled"
>
<template #default="inputProps">
<input
v-model="newStatus.spoilerText"
type="text"
:placeholder="$t('post_status.content_warning')"
:disabled="posting && !optimisticPosting"
v-bind="propsToNative(inputProps)"
size="1"
class="input form-post-subject unstyled"
>
</template>
</EmojiInput>
+ <input
+ v-if="mentionsLine"
+ :value="mentionsLineReadOnly ? mentionsString : newStatus.mentionsLine"
+ @change="onMentionsLineUpdate"
+ type="text"
+ :placeholder="$t('post_status.mentions_line')"
+ :disabled="mentionsLineReadOnly || (posting && !optimisticPosting)"
+ size="1"
+ class="input mentions-input form-post-mentions unstyled"
+ >
<EmojiInput
ref="emoji-input"
v-model="newStatus.status"
:suggest="emojiUserSuggestor"
:placement="emojiPickerPlacement"
class="input form-control main-input unstyled"
enable-sticker-picker
enable-emoji-picker
:newline-on-ctrl-enter="submitOnEnter"
@input="onEmojiInputInput"
@sticker-uploaded="addMediaFile"
@sticker-upload-failed="uploadFailed"
@shown="handleEmojiInputShow"
>
<template #default="inputProps">
<textarea
ref="textarea"
v-model="newStatus.status"
:placeholder="placeholder || $t('post_status.default')"
rows="1"
cols="1"
:disabled="posting && !optimisticPosting"
class="input form-post-body"
:class="{ 'scrollable-form': !!maxHeight }"
v-bind="propsToNative(inputProps)"
- @keydown.exact.enter="submitOnEnter && postStatus($event, newStatus)"
+ @keydown.exact.enter="submitOnEnter && postStatus($event)"
@keydown.meta.enter="postStatus($event, newStatus)"
- @keydown.ctrl.enter="!submitOnEnter && postStatus($event, newStatus)"
+ @keydown.ctrl.enter="!submitOnEnter && postStatus($event)"
@input="resize"
@compositionupdate="resize"
@paste="paste"
/>
<p
v-if="hasStatusLengthLimit"
class="character-counter faint"
:class="{ error: isOverLengthLimit }"
>
{{ charactersLeft }}
</p>
</template>
</EmojiInput>
</div>
<div
v-if="!disableScopeSelector"
class="visibility-tray"
>
<scope-selector
v-if="!disableVisibilitySelector"
+ ref="scopeSelector"
:show-all="showAllScopes"
:user-default="userDefaultScope"
- :original-scope="copyMessageScope"
+ :original-scope="newStatus.visibility"
:initial-scope="newStatus.visibility"
- :on-scope-change="changeVis"
+ @change="changeVis"
/>
<div
v-if="postFormats.length > 1"
class="text-format"
>
<Select
v-model="newStatus.contentType"
class="input form-control unstyled"
:attrs="{ 'aria-label': $t('post_status.content_type_selection') }"
unstyled="true"
>
<option
v-for="postFormat in postFormats"
:key="postFormat"
:value="postFormat"
>
{{ $t(`post_status.content_type["${postFormat}"]`) }}
</option>
</Select>
</div>
<div
v-if="postFormats.length === 1 && postFormats[0] !== 'text/plain'"
class="text-format"
>
<span class="only-format">
{{ $t(`post_status.content_type["${postFormats[0]}"]`) }}
</span>
</div>
</div>
</div>
<PollForm
v-if="pollsAvailable"
ref="pollForm"
:visible="pollFormVisible"
- :params="newStatus.poll"
+ v-model="newStatus.poll"
/>
<QuoteForm
v-if="quotingAvailable"
- :id="newStatus.quote.id"
ref="quoteForm"
:visible="quoteFormVisible"
- :url="newStatus.quote.url"
+ :id="newStatus.quote?.id"
+ :url="newStatus.quote?.url"
@update:url="url => newStatus.quote.url = url"
@update:id="id => newStatus.quote.id = id"
/>
<span
v-if="!disableDraft && shouldAutoSaveDraft"
class="auto-save-status"
>
{{ autoSaveState }}
</span>
<div
ref="bottom"
class="form-bottom"
>
<div class="form-bottom-left">
<media-upload
ref="mediaUpload"
class="bottom-left-button media-upload-icon"
:drop-files="dropFiles"
:disabled="uploadFileLimitReached"
@uploading="startedUploadingFiles"
@uploaded="addMediaFile"
@upload-failed="uploadFailed"
@all-uploaded="finishedUploadingFiles"
/>
<button
v-if="pollsAvailable"
class="bottom-left-button poll-icon button-unstyled"
:class="{ toggled: pollFormVisible }"
:title="$t('polls.add_poll')"
@click="togglePollForm"
>
<FAIcon icon="poll-h" />
</button>
<button
v-if="quotingAvailable"
class="bottom-left-button quote-icon button-unstyled"
:disabled="quoteThreadToggled"
:class="{ toggled: quoteFormVisible }"
:title="$t('tool_tip.add_quote')"
@click="toggleQuoteForm"
>
<FAIcon icon="quote-right" />
</button>
</div>
<div class="btn-group post-button-group">
<button
class="btn button-default post-button"
:disabled="isOverLengthLimit || posting || uploadingFiles || disableSubmit"
- @click.stop.prevent="postStatus($event, newStatus)"
+ @click.stop.prevent="postStatus($event)"
>
<template v-if="posting">
{{ $t('post_status.posting') }}
</template>
<template v-else>
{{ $t('post_status.post') }}
</template>
</button>
<Popover
v-if="!hideExtraActions"
class="more-post-actions"
:normal-button="true"
trigger="click"
placement="bottom"
:offset="{ y: 5 }"
:trigger-attrs="{ 'aria-label': $t('post_status.more_post_actions') }"
>
<template #trigger>
<FAIcon
class="fa-scale-110 fa-old-padding"
icon="chevron-down"
/>
</template>
<template #content="{close}">
<div
class="dropdown-menu"
role="menu"
>
<div
class="menu-item dropdown-item"
:class="{ disabled: !safeToSaveDraft }"
>
<button
v-if="!hideDraft || !disableDraft"
class="main-button"
role="menu"
:disabled="!safeToSaveDraft"
@click.prevent="saveDraft"
@click="close"
>
<template v-if="closeable">
{{ $t('post_status.save_to_drafts_and_close_button') }}
</template>
<template v-else>
{{ $t('post_status.save_to_drafts_button') }}
</template>
</button>
</div>
</div>
</template>
</Popover>
</div>
</div>
+ <small class="keyboard-enter-hint faint">
+ <i v-if="submitOnEnter">
+ {{ $t('post_status.enter_submits') }}
+ </i>
+ <i v-else>
+ {{ $t('post_status.enter_newline') }}
+ </i>
+ </small>
<div
v-show="showDropIcon !== 'hide'"
:style="{ animation: showDropIcon === 'show' ? 'fade-in 0.25s' : 'fade-out 0.5s' }"
class="drop-indicator"
@dragleave="fileDragStop"
@drop.stop="fileDrop"
>
<FAIcon :icon="uploadFileLimitReached ? 'ban' : 'upload'" />
</div>
<div
v-if="error"
class="alert error -dismissible"
>
<span>
{{ error }}
</span>
<button
class="button-unstyled"
@click="clearError"
>
<FAIcon
class="fa-scale-110 fa-old-padding"
icon="times"
/>
</button>
</div>
<Gallery
v-if="newStatus.files && newStatus.files.length > 0"
class="attachments"
:grid="true"
:nsfw="false"
:attachments="newStatus.files"
:descriptions="newStatus.mediaDescriptions"
:set-media="() => setMedia()"
:editable="true"
:edit-attachment="editAttachment"
:remove-attachment="removeMediaFile"
:shift-up-attachment="newStatus.files.length > 1 && shiftUpMediaFile"
:shift-dn-attachment="newStatus.files.length > 1 && shiftDnMediaFile"
@play="$emit('mediaplay', 'newStatus')"
@pause="$emit('mediapause', 'newStatus')"
/>
<div
v-if="newStatus.files.length > 0 && !disableSensitivityCheckbox"
class="upload_settings"
>
<Checkbox v-model="newStatus.nsfw">
{{ $t('post_status.attachments_sensitive') }}
</Checkbox>
</div>
</form>
<DraftCloser
ref="draftCloser"
@save="saveAndCloseDraft"
@discard="discardAndCloseDraft"
/>
</div>
</template>
<script src="./post_status_form.js"></script>
<style src="./post_status_form.scss" lang="scss"></style>
diff --git a/src/components/rich_content/rich_content.jsx b/src/components/rich_content/rich_content.jsx
index 55f8179ffa..646df5bab8 100644
--- a/src/components/rich_content/rich_content.jsx
+++ b/src/components/rich_content/rich_content.jsx
@@ -1,565 +1,566 @@
import { flattenDeep, unescape as ldUnescape } from 'lodash'
import HashtagLink from 'src/components/hashtag_link/hashtag_link.vue'
import { MENTIONS_LIMIT } from 'src/components/mentions_line/mentions_line.js'
import MentionsLine from 'src/components/mentions_line/mentions_line.vue'
import StillImage from 'src/components/still-image/still-image.vue'
import StillImageEmojiPopover from 'src/components/still-image/still-image-emoji-popover.vue'
import { convertHtmlToLines } from 'src/services/html_converter/html_line_converter.service.js'
import { convertHtmlToTree } from 'src/services/html_converter/html_tree_converter.service.js'
import {
getAttrs,
getTagName,
processTextForEmoji,
} from 'src/services/html_converter/utility.service.js'
import './rich_content.scss'
const MAYBE_LINE_BREAKING_ELEMENTS = [
'blockquote',
'br',
'hr',
'ul',
'ol',
'li',
'p',
'table',
'tbody',
'td',
'th',
'thead',
'tr',
'h1',
'h2',
'h3',
'h4',
'h5',
]
/**
* RichContent, The Über-powered component for rendering Post HTML.
*
* This takes post HTML and does multiple things to it:
* - Groups all mentions into <MentionsLine>, this affects all mentions regardles
* of where they are (beginning/middle/end), even single mentions are converted
* to a <MentionsLine> containing single <MentionLink>.
* - Replaces emoji shortcodes with <StillImage>'d images.
*
* There are two problems with this component's architecture:
* 1. Parsing HTML and rendering are inseparable. Attempts to separate the two
* proven to be a massive overcomplication due to amount of things done here.
* 2. We need to output both render and some extra data, which seems to be imp-
* possible in vue. Current solution is to emit 'parseReady' event when parsing
* is done within render() function.
*
* Apart from that one small hiccup with emit in render this _should_ be vue3-ready
*/
export default {
name: 'RichContent',
components: {
MentionsLine,
HashtagLink,
},
props: {
// Original html content
html: {
required: true,
type: String,
},
attentions: {
required: false,
default: () => [],
},
// Emoji object, as in status.emojis, note the "s" at the end...
emoji: {
required: true,
type: Array,
},
// Whether to handle links or not (posts: yes, everything else: no)
handleLinks: {
required: false,
type: Boolean,
default: false,
},
// Meme arrows
greentext: {
required: false,
type: Boolean,
default: false,
},
// Faint style (for notifs)
faint: {
required: false,
type: Boolean,
default: false,
},
// Collapse newlines
collapse: {
required: false,
type: Boolean,
default: false,
},
/* Content comes from current instance
*
* This is used for emoji stealing popover.
* By default we assume it is, so that steal
* emoji button isn't shown where it probably
* should not be.
*/
isLocal: {
required: false,
type: Boolean,
default: true,
},
// Allow wide emoji (max 3:1 ratio)
allowNonSquareEmoji: {
required: false,
type: Boolean,
default: false,
},
pauseMfm: {
required: false,
type: Boolean,
default: false,
},
scaleMfm: {
required: false,
type: Boolean,
default: false,
},
},
// NEVER EVER TOUCH DATA INSIDE RENDER
render() {
// Pre-process HTML
const { newHtml: html } = preProcessPerLine(this.html, this.greentext)
let currentMentions = null // Current chain of mentions, we group all mentions together
// This is used to recover spacing removed when parsing mentions
let lastSpacing = ''
const lastTags = [] // Tags that appear at the end of post body
const writtenMentions = [] // All mentions that appear in post body
const invisibleMentions = [] // All mentions that go beyond the limiter (see MentionsLine)
// to collapse too many mentions in a row
const writtenTags = [] // All tags that appear in post body
// unique index for vue "tag" property
let mentionIndex = 0
let tagsIndex = 0
const renderImage = (tag) => {
return <StillImage {...getAttrs(tag)} class="img" />
}
const renderHashtag = (attrs, children, encounteredTextReverse) => {
const { index, ...linkData } = getLinkData(attrs, children, tagsIndex++)
writtenTags.push(linkData)
if (!encounteredTextReverse) {
lastTags.push(linkData)
}
const { url, tag, content } = linkData
return <HashtagLink url={url} tag={tag} content={content} />
}
const renderMention = (attrs, children) => {
const linkData = getLinkData(attrs, children, mentionIndex++)
linkData.notifying = this.attentions.some(
(a) => a.statusnet_profile_url === linkData.url,
)
writtenMentions.push(linkData)
if (currentMentions === null) {
currentMentions = []
}
currentMentions.push(linkData)
if (currentMentions.length > MENTIONS_LIMIT) {
invisibleMentions.push(linkData)
}
if (currentMentions.length === 1) {
return <MentionsLine mentions={currentMentions} />
} else {
return ''
}
}
// Processor to use with html_tree_converter
const processItem = (item, index, array, what) => {
// Handle text nodes - just add emoji
if (typeof item === 'string') {
const emptyText = item.trim() === ''
if (item.includes('\n')) {
currentMentions = null
}
if (emptyText) {
// don't include spaces when processing mentions - we'll include them
// in MentionsLine
lastSpacing = item
// Don't remove last space in a container (fixes poast mentions)
return index !== array.length - 1 && currentMentions !== null
? item.trim()
: item
}
currentMentions = null
if (item.includes(':')) {
item = [
'',
processTextForEmoji(item, this.emoji, ({ shortcode, url }) => {
return (
<StillImageEmojiPopover
class="emoji img"
src={url}
title={`:${shortcode}:`}
alt={`:${shortcode}:`}
shortcode={shortcode}
isLocal={this.isLocal}
/>
)
}),
]
}
return item
}
// Handle tag nodes
if (Array.isArray(item)) {
const [opener, children, closer] = item
let Tag = getTagName(opener)
if (Tag.toLowerCase() === 'script') Tag = 'js-exploit'
if (Tag.toLowerCase() === 'style') Tag = 'css-exploit'
const fullAttrs = getAttrs(opener, () => true)
const attrs = getAttrs(opener)
const previouslyMentions = currentMentions !== null
/* During grouping of mentions we trim all the empty text elements
* This padding is added to recover last space removed in case
* we have a tag right next to mentions
*/
const mentionsLinePadding =
// Padding is only needed if we just finished parsing mentions
previouslyMentions &&
// Don't add padding if content is string and has padding already
!(
children &&
typeof children[0] === 'string' &&
children[0].match(/^\s/)
)
? lastSpacing
: ''
if (MAYBE_LINE_BREAKING_ELEMENTS.includes(Tag)) {
// all the elements that can cause a line change
currentMentions = null
} else if (Tag === 'img') {
// replace images with StillImage
return ['', [mentionsLinePadding, renderImage(opener)], '']
} else if (Tag === 'a' && this.handleLinks) {
// replace mentions with MentionLink
if (fullAttrs.class && fullAttrs.class.includes('mention')) {
// Handling mentions here
return renderMention(attrs, children)
} else {
currentMentions = null
}
} else if (Tag === 'span') {
if (
this.handleLinks &&
fullAttrs.class &&
fullAttrs.class.includes('h-card')
) {
return ['', children.map(processItem), '']
}
}
if (children !== undefined) {
return [
'',
[mentionsLinePadding, [opener, children.map(processItem), closer]],
'',
]
} else {
return ['', [mentionsLinePadding, item], '']
}
}
}
// Processor for back direction (for finding "last" stuff, just easier this way)
let encounteredTextReverse = false
const processItemReverse = (item, index, array, what) => {
// Handle text nodes - just add emoji
if (typeof item === 'string') {
const emptyText = item.trim() === ''
if (emptyText) return item
if (!encounteredTextReverse) encounteredTextReverse = true
return ldUnescape(item)
} else if (Array.isArray(item)) {
// Handle tag nodes
const [opener, children] = item
const Tag = opener === '' ? '' : getTagName(opener)
switch (Tag) {
case 'a': {
// replace mentions with MentionLink
if (!this.handleLinks) break
const fullAttrs = getAttrs(opener, () => true)
const attrs = getAttrs(opener, () => true)
// should only be this
if (
(fullAttrs.class && fullAttrs.class.includes('hashtag')) || // Pleroma style
fullAttrs.rel === 'tag' // Mastodon style
) {
return renderHashtag(attrs, children, encounteredTextReverse)
} else {
attrs.target = '_blank'
const newChildren = [...children]
.reverse()
.map(processItemReverse)
.reverse()
return <a {...attrs}>{newChildren}</a>
}
}
case '':
return [...children].reverse().map(processItemReverse).reverse()
}
// Render tag as is
if (children !== undefined) {
const newChildren = Array.isArray(children)
? [...children].reverse().map(processItemReverse).reverse()
: children
const attrs = getAttrs(opener)
const newAttrs = { ...attrs }
const fullAttrs = getAttrs(opener, () => true)
const classname = fullAttrs['class']
const isMFM = classname?.startsWith('mfm-')
if (isMFM) {
const mfmOperator = /^mfm-(\w+)$/.exec(classname)?.[1]
newAttrs['class'] = [
'mfm',
this.pauseMfm ? '-pause' : '',
this.scaleMfm ? '-scale' : '',
]
.filter(Boolean)
.join(' ')
newAttrs['data-mfm-operator'] = mfmOperator
switch (mfmOperator) {
case 'position': {
const x = Number.parseFloat(fullAttrs['data-mfm-x']) || 0
const y = Number.parseFloat(fullAttrs['data-mfm-y']) || 0
newAttrs.style = [
'transform:',
`translate(calc(${x} * (var(--emoji-size) / 2)), `,
`calc(${y} * (var(--emoji-size) / 2)))`,
].join(' ')
break
}
case 'scale': {
const x = Number.parseFloat(fullAttrs['data-mfm-x']) || 1
const y = Number.parseFloat(fullAttrs['data-mfm-y']) || 1
newAttrs.style = ['transform:', `scale(${x}, ${y})`].join(' ')
break
}
case 'rotate': {
const deg = Number.parseFloat(fullAttrs['data-mfm-deg']) || 0
newAttrs.style = [
`transform: rotate(${deg}deg)`,
'transform-origin: center',
].join(';')
break
}
case 'bg': {
const color = fullAttrs['data-mfm-color'] || 0
newAttrs.style = [`background-color: #${color}`].join(' ')
break
}
case 'fg': {
const color = fullAttrs['data-mfm-color'] || 0
newAttrs.style = [`color: #${color}`].join(';')
break
}
case 'spin': {
const speed = fullAttrs['data-mfm-speed'] || '1s'
const delay = fullAttrs['data-mfm-delay'] || 0
const left = fullAttrs['data-mfm-left'] != null
const alternate = fullAttrs['data-mfm-alternate'] != null
const y = fullAttrs['data-mfm-y'] != null
const x = fullAttrs['data-mfm-x'] != null
const anim = [
x ? 'mfm-spinX' : null,
y ? 'mfm-spinY' : null,
'mfm-spin',
].filter((a) => a)[0]
const direction = [
alternate ? 'alternate' : null,
left ? 'reverse' : null,
'normal',
].filter((a) => a)[0]
newAttrs.style = [
`animation-name: ${anim}`,
`animation-duration: ${speed}`,
'animation-iteration-count: infinite',
`animation-delay: ${delay}`,
`animation-direction: ${direction}`,
'animation-fill-mode: none',
'animation-timing-function: linear',
].join(';')
break
}
case 'flip': {
newAttrs.style = 'transform: scaleX(-1)'
break
}
case 'border': {
const width = fullAttrs['data-mfm-width'] || '0'
const style = fullAttrs['data-mfm-style'] || 'solid'
const color = fullAttrs['data-mfm-color'] || 'transparent'
const radius = fullAttrs['data-mfm-radius'] || '0'
const noclip = fullAttrs['data-mfm-noclip'] || false
newAttrs.style = [
`border: ${width} ${style} ${color}`,
`border-radius: ${radius}`,
`overflow: ${noclip ? 'visible' : 'clip'}`,
].join(';')
break
}
case 'tada':
case 'jelly':
case 'twitch':
case 'shake':
case 'jump':
case 'bounce':
case 'rainbow': {
const speed = fullAttrs['data-mfm-speed'] || '1s'
const delay = fullAttrs['data-mfm-delay'] || 0
const rules = [
`animation-name: mfm-${mfmOperator}`,
`animation-duration: ${speed}`,
'animation-iteration-count: infinite',
`animation-delay: ${delay}`,
'animation-direction: normal',
'animation-fill-mode: none',
'animation-timing-function: linear',
].join(';')
newAttrs.style = rules
break
}
case 'sparkle':
case 'x2':
case 'x3':
case 'x4':
// handled by css
break
default:
console.warn('Unsupported MFM operator:', mfmOperator, opener)
break
}
}
return <Tag {...newAttrs}>{newChildren}</Tag>
} else {
return <Tag />
}
}
return item
}
const pass1 = convertHtmlToTree(html).map(processItem)
const pass2 = [...pass1].reverse().map(processItemReverse).reverse()
// DO NOT USE SLOTS they cause a re-render feedback loop here.
// slots updated -> rerender -> emit -> update up the tree -> rerender -> ...
// at least until vue3?
const result = (
<span
class={[
'RichContent',
this.faint ? '-faint' : '',
this.allowNonSquareEmoji ? '-allow-non-square-emoji' : '',
]}
>
{this.collapse
? pass2.map((x) => {
- if (!Array.isArray(x)) return x.replace(/\n/g, ' ')
+ if (typeof x === 'string') return x.replace(/\n/g, ' ')
+ if (!Array.isArray(x)) return x
return x.map((y) => (y.type === 'br' ? ' ' : y))
})
: pass2}
</span>
)
const event = {
lastTags,
writtenMentions,
writtenTags,
invisibleMentions,
}
// DO NOT MOVE TO UPDATE. BAD IDEA.
this.$emit('parseReady', event)
return result
},
}
const getLinkData = (attrs, children, index) => {
const stripTags = (item) => {
if (typeof item === 'string') {
return item
} else {
return item[1].map(stripTags).join('')
}
}
const textContent = children.map(stripTags).join('')
return {
index,
url: attrs.href,
tag: attrs['data-tag'],
content: flattenDeep(children).join(''),
textContent,
}
}
/** Pre-processing HTML
*
* Currently this does one thing:
* - add green/cyantexting
*
* @param {String} html - raw HTML to process
* @param {Boolean} greentext - whether to enable greentexting or not
*/
export const preProcessPerLine = (html, greentext) => {
const greentextHandle = new Set(['p', 'div'])
const lines = convertHtmlToLines(html)
const newHtml = lines
.reverse()
.map((item, index, array) => {
if (!item.text) return item
const string = item.text
// Greentext stuff
if (
// Only if greentext is engaged
greentext &&
// Only handle p's and divs. Don't want to affect blockquotes, code etc
item.level.every((l) => greentextHandle.has(l)) &&
// Only if line begins with '>' or '<'
(string.includes('&gt;') || string.includes('&lt;'))
) {
const cleanedString = string
.replace(/<[^>]+?>/gi, '') // remove all tags
.replace(/@\w+/gi, '') // remove mentions (even failed ones)
.trim()
if (cleanedString.startsWith('&gt;')) {
return `<span class='greentext'>${string}</span>`
} else if (cleanedString.startsWith('&lt;')) {
return `<span class='cyantext'>${string}</span>`
}
}
return string
})
.reverse()
.join('')
return { newHtml }
}
diff --git a/src/components/scope_selector/scope_selector.js b/src/components/scope_selector/scope_selector.js
index 9d3a3a7182..0df50031d6 100644
--- a/src/components/scope_selector/scope_selector.js
+++ b/src/components/scope_selector/scope_selector.js
@@ -1,92 +1,94 @@
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faEnvelope,
faGlobe,
faLock,
faLockOpen,
} from '@fortawesome/free-solid-svg-icons'
library.add(faEnvelope, faGlobe, faLock, faLockOpen)
const ScopeSelector = {
props: {
showAll: {
required: true,
type: Boolean,
},
userDefault: {
required: true,
type: String,
},
originalScope: {
required: false,
type: String,
},
initialScope: {
required: false,
type: String,
},
- onScopeChange: {
- required: true,
- type: Function,
- },
unstyled: {
required: false,
type: Boolean,
default: true,
},
},
+ emits: ['change'],
data() {
return {
currentScope: this.initialScope,
}
},
computed: {
showNothing() {
return (
!this.showPublic &&
!this.showUnlisted &&
!this.showPrivate &&
!this.showDirect
)
},
showPublic() {
return this.originalScope !== 'direct' && this.shouldShow('public')
},
showUnlisted() {
return this.originalScope !== 'direct' && this.shouldShow('unlisted')
},
showPrivate() {
return this.originalScope !== 'direct' && this.shouldShow('private')
},
showDirect() {
return this.shouldShow('direct')
},
css() {
const style = this.unstyled ? 'button-unstyled' : 'button-default'
return {
public: [style, { toggled: this.currentScope === 'public' }],
unlisted: [style, { toggled: this.currentScope === 'unlisted' }],
private: [style, { toggled: this.currentScope === 'private' }],
direct: [style, { toggled: this.currentScope === 'direct' }],
}
},
},
methods: {
shouldShow(scope) {
return (
this.showAll ||
this.currentScope === scope ||
this.originalScope === scope ||
this.userDefault === scope ||
scope === 'direct'
)
},
changeVis(scope) {
this.currentScope = scope
- this.onScopeChange && this.onScopeChange(scope)
+ this.$emit('change', scope)
+ },
+ },
+ watch: {
+ originalScope(newVal) {
+ this.currentScope = newVal
},
},
}
export default ScopeSelector
diff --git a/src/components/settings_modal/tabs/composing_tab.vue b/src/components/settings_modal/tabs/composing_tab.vue
index 755539096b..b8c156bd30 100644
--- a/src/components/settings_modal/tabs/composing_tab.vue
+++ b/src/components/settings_modal/tabs/composing_tab.vue
@@ -1,117 +1,124 @@
<template>
<div :label="$t('settings.posts')">
<div class="setting-section">
<h3>{{ $t('settings.general') }}</h3>
<ul class="setting-list">
<li>
<label
class="setting-item "
for="default-vis"
>
<ScopeSelector
class="scope-selector setting-control"
:show-all="true"
:user-default="$store.state.profileConfig.defaultScope"
:initial-scope="$store.state.profileConfig.defaultScope"
:on-scope-change="changeDefaultScope"
:unstyled="false"
/>
</label>
</li>
<li>
<!-- <BooleanSetting source="profile" path="defaultNSFW"> -->
<BooleanSetting path="sensitiveByDefault">
{{ $t('settings.sensitive_by_default') }}
</BooleanSetting>
</li>
<li v-if="postFormats.length > 0">
<ChoiceSetting
id="postContentType"
path="postContentType"
:options="postContentOptions"
:local="true"
>
{{ $t('settings.default_post_status_content_type') }}
</ChoiceSetting>
</li>
<li>
<BooleanSetting path="padEmoji">
{{ $t('settings.pad_emoji') }}
</BooleanSetting>
</li>
<li>
<BooleanSetting
path="autocompleteSelect"
expert="1"
>
{{ $t('settings.autocomplete_select_first') }}
</BooleanSetting>
</li>
<li>
<BooleanSetting
path="autoSaveDraft"
>
{{ $t('settings.auto_save_draft') }}
</BooleanSetting>
</li>
<li v-if="!mergedConfig.autoSaveDraft">
<ChoiceSetting
id="unsavedPostAction"
path="unsavedPostAction"
:options="unsavedPostActionOptions"
expert="1"
>
{{ $t('settings.unsaved_post_action') }}
</ChoiceSetting>
</li>
</ul>
<h3>{{ $t('settings.replies') }}</h3>
<ul class="setting-list">
<li>
<BooleanSetting
path="scopeCopy"
>
{{ $t('settings.scope_copy') }}
</BooleanSetting>
</li>
<li>
<ChoiceSetting
id="subjectLineBehavior"
path="subjectLineBehavior"
:options="subjectLineOptions"
>
{{ $t('settings.subject_line_behavior') }}
</ChoiceSetting>
</li>
+ <li>
+ <BooleanSetting
+ path="chatSubmitOnEnter"
+ >
+ {{ $t('settings.submit_on_enter_in_chats') }}
+ </BooleanSetting>
+ </li>
</ul>
<h3 v-if="expertLevel > 0">
{{ $t('settings.attachments') }}
</h3>
<ul class="setting-list">
<li>
<BooleanSetting
path="imageCompression"
:local="true"
expert="1"
>
{{ $t('settings.image_compression') }}
</BooleanSetting>
<ul class="setting-list suboptions">
<li>
<BooleanSetting
path="alwaysUseJpeg"
:local="true"
expert="1"
parent-path="imageCompression"
>
{{ $t('settings.always_use_jpeg') }}
</BooleanSetting>
</li>
</ul>
</li>
</ul>
</div>
</div>
</template>
<script src="./composing_tab.js"></script>
diff --git a/src/components/side_drawer/side_drawer.js b/src/components/side_drawer/side_drawer.js
index 27e9a5249e..369177c7ac 100644
--- a/src/components/side_drawer/side_drawer.js
+++ b/src/components/side_drawer/side_drawer.js
@@ -1,136 +1,138 @@
import { mapActions, mapState } from 'pinia'
import { mapGetters } from 'vuex'
import { USERNAME_ROUTES } from 'src/components/navigation/navigation.js'
import UserCard from 'src/components/user_card/user_card.vue'
import GestureService from '../../services/gesture_service/gesture_service'
import { unseenNotificationsFromStore } from '../../services/notification_utils/notification_utils'
import { useAnnouncementsStore } from 'src/stores/announcements'
+import { useChatsStore } from 'src/stores/chats.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
import { useInterfaceStore } from 'src/stores/interface'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useShoutStore } from 'src/stores/shout'
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faBell,
faBullhorn,
faCog,
faComments,
faCompass,
faFilePen,
faHome,
faInfoCircle,
faList,
faSearch,
faSignInAlt,
faSignOutAlt,
faTachometerAlt,
faUserPlus,
} from '@fortawesome/free-solid-svg-icons'
library.add(
faSignInAlt,
faSignOutAlt,
faHome,
faComments,
faBell,
faUserPlus,
faBullhorn,
faSearch,
faTachometerAlt,
faCog,
faInfoCircle,
faCompass,
faList,
faFilePen,
)
const SideDrawer = {
props: ['logout'],
data: () => ({
closed: true,
closeGesture: undefined,
}),
created() {
this.closeGesture = GestureService.swipeGesture(
GestureService.DIRECTION_LEFT,
this.toggleDrawer,
)
if (this.currentUser && this.currentUser.locked) {
this.$store.dispatch('startFetchingFollowRequests')
}
},
components: {
UserCard,
},
computed: {
currentUser() {
return this.$store.state.users.currentUser
},
shout() {
return useShoutStore().joined
},
unseenNotifications() {
return unseenNotificationsFromStore(
this.$store,
useMergedConfigStore().mergedConfig.notificationVisibility,
useMergedConfigStore().mergedConfig.ignoreInactionableSeen,
)
},
unseenNotificationsCount() {
return this.unseenNotifications.length
},
followRequestCount() {
return this.$store.state.api.followRequests.length
},
timelinesRoute() {
let name
if (useInterfaceStore().lastTimeline) {
name = useInterfaceStore().lastTimeline
}
name = this.currentUser ? 'friends' : 'public-timeline'
if (USERNAME_ROUTES.has(name)) {
return { name, params: { username: this.currentUser.screen_name } }
} else {
return { name }
}
},
...mapState(useAnnouncementsStore, [
'supportsAnnouncements',
'unreadAnnouncementCount',
]),
...mapState(useInstanceCapabilitiesStore, [
'pleromaChatMessagesAvailable',
'suggestionsEnabled',
]),
...mapState(useInstanceStore, ['privateMode', 'federating']),
...mapState(useInstanceStore, {
logo: (store) => store.instanceIdentity.logo,
sitename: (store) => store.instanceIdentity.name,
hideSitename: (store) => store.instanceIdentity.hideSitename,
}),
- ...mapGetters(['unreadChatCount', 'draftCount']),
+ ...mapState(useChatsStore, ['unreadChatsCount']),
+ ...mapGetters(['draftCount']),
},
methods: {
toggleDrawer() {
this.closed = !this.closed
},
doLogout() {
this.logout()
this.toggleDrawer()
},
touchStart(e) {
GestureService.beginSwipe(e, this.closeGesture)
},
touchMove(e) {
GestureService.updateSwipe(e, this.closeGesture)
},
...mapActions(useInterfaceStore, ['openSettingsModal']),
},
}
export default SideDrawer
diff --git a/src/components/side_drawer/side_drawer.vue b/src/components/side_drawer/side_drawer.vue
index c034edf910..e0b7331c6e 100644
--- a/src/components/side_drawer/side_drawer.vue
+++ b/src/components/side_drawer/side_drawer.vue
@@ -1,445 +1,445 @@
<template>
<div
class="side-drawer-container mobile-drawer"
:class="{ 'side-drawer-container-closed': closed, 'side-drawer-container-open': !closed }"
>
<div
class="side-drawer-darken"
:class="{ 'side-drawer-darken-closed': closed}"
/>
<div
class="side-drawer"
:class="{'side-drawer-closed': closed}"
@touchstart="touchStart"
@touchmove="touchMove"
>
<div
class="side-drawer-heading"
@click="toggleDrawer"
>
<UserCard
v-if="currentUser"
:user-id="currentUser.id"
:hide-bio="true"
/>
<div
v-else
class="side-drawer-logo-wrapper"
>
<img :src="logo">
<span v-if="!hideSitename">{{ sitename }}</span>
</div>
</div>
<ul>
<li
v-if="!currentUser"
@click="toggleDrawer"
>
<router-link
:to="{ name: 'login' }"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="sign-in-alt"
/> {{ $t("login.login") }}
</router-link>
</li>
<li
v-if="currentUser || !privateMode"
@click="toggleDrawer"
>
<router-link
:to="timelinesRoute"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="home"
/> {{ $t("nav.timelines") }}
</router-link>
</li>
<li
v-if="currentUser"
@click="toggleDrawer"
>
<router-link
:to="{ name: 'lists' }"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="list"
/> {{ $t("nav.lists") }}
</router-link>
</li>
<li
v-if="currentUser"
@click="toggleDrawer"
>
<router-link
:to="{ name: 'bookmarks' }"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="bookmark"
/> {{ $t("nav.bookmarks") }}
</router-link>
</li>
<li
v-if="currentUser && pleromaChatMessagesAvailable"
@click="toggleDrawer"
>
<router-link
:to="{ name: 'chats', params: { username: currentUser.screen_name } }"
style="position: relative;"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="comments"
/> {{ $t("nav.chats") }}
<span
- v-if="unreadChatCount"
+ v-if="unreadChatsCount"
class="badge -notification"
>
- {{ unreadChatCount }}
+ {{ unreadChatsCount }}
</span>
</router-link>
</li>
</ul>
<ul v-if="currentUser">
<li @click="toggleDrawer">
<router-link
:to="{ name: 'interactions', params: { username: currentUser.screen_name } }"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="bell"
/> {{ $t("nav.interactions") }}
</router-link>
</li>
<li
v-if="currentUser.locked"
@click="toggleDrawer"
>
<router-link
to="/friend-requests"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="user-plus"
/> {{ $t("nav.friend_requests") }}
<span
v-if="followRequestCount > 0"
class="badge -notification"
>
{{ followRequestCount }}
</span>
</router-link>
</li>
<li
v-if="shout"
@click="toggleDrawer"
>
<router-link
:to="{ name: 'shout-panel' }"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="bullhorn"
/> {{ $t("shoutbox.title") }}
</router-link>
</li>
</ul>
<ul>
<li
v-if="currentUser || !privateMode"
@click="toggleDrawer"
>
<router-link
:to="{ name: 'search' }"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="search"
/> {{ $t("nav.search") }}
</router-link>
</li>
<li
v-if="currentUser && suggestionsEnabled"
@click="toggleDrawer"
>
<router-link
:to="{ name: 'who-to-follow' }"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="user-plus"
/> {{ $t("nav.who_to_follow") }}
</router-link>
</li>
<li @click="toggleDrawer">
<button
class="menu-item"
@click="openSettingsModal('user')"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="cog"
/> {{ $t("settings.settings") }}
</button>
</li>
<li @click="toggleDrawer">
<router-link
:to="{ name: 'about'}"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="info-circle"
/> {{ $t("nav.about") }}
</router-link>
</li>
<li
v-if="currentUser && currentUser.role === 'admin'"
@click="toggleDrawer"
>
<button
class="menu-item"
@click.stop="openSettingsModal('admin')"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="tachometer-alt"
/> {{ $t("nav.administration") }}
</button>
</li>
<li
v-if="currentUser && supportsAnnouncements"
@click="toggleDrawer"
>
<router-link
:to="{ name: 'announcements' }"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="bullhorn"
/> {{ $t("nav.announcements") }}
<span
v-if="unreadAnnouncementCount"
class="badge -notification"
>
{{ unreadAnnouncementCount }}
</span>
</router-link>
</li>
<li
v-if="currentUser"
@click="toggleDrawer"
>
<router-link
:to="{ name: 'drafts' }"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="file-pen"
/> {{ $t('nav.drafts') }}
<span
v-if="draftCount"
class="badge -neutral"
>
{{ draftCount }}
</span>
</router-link>
</li>
<li
v-if="currentUser"
@click="toggleDrawer"
>
<router-link
:to="{ name: 'edit-navigation' }"
class="menu-item"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="compass"
/> {{ $t("nav.edit_nav_mobile") }}
</router-link>
</li>
<li
v-if="currentUser"
@click="toggleDrawer"
>
<button
class="menu-item"
@click="doLogout"
>
<FAIcon
fixed-width
class="fa-scale-110 fa-old-padding"
icon="sign-out-alt"
/> {{ $t("login.logout") }}
</button>
</li>
</ul>
</div>
<div
class="side-drawer-click-outside"
:class="{'side-drawer-click-outside-closed': closed}"
@click.stop.prevent="toggleDrawer"
/>
</div>
</template>
<script src="./side_drawer.js"></script>
<style lang="scss">
.side-drawer-container {
position: fixed;
z-index: var(--ZI_navbar);
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: stretch;
transition-duration: 0s;
transition-property: transform;
}
.side-drawer-container-open {
transform: translate(0%);
}
.side-drawer-container-closed {
transition-delay: 0.35s;
transform: translate(-100%);
}
.side-drawer-darken {
top: 0;
left: 0;
width: 100vw;
height: 100vh;
position: fixed;
z-index: -1;
transition: 0.35s;
transition-property: background-color;
background-color: rgb(0 0 0 / 50%);
}
.side-drawer-darken-closed {
background-color: rgb(0 0 0 / 0%);
}
.side-drawer-click-outside {
flex: 1 1 100%;
}
.side-drawer {
overflow-x: hidden;
transition: 0.35s;
transition-timing-function: cubic-bezier(0, 1, 0.5, 1);
transition-property: transform;
margin: 0 0 0 -100px;
padding: 0 0 1em 100px;
width: 80%;
max-width: 20em;
flex: 0 0 80%;
box-shadow: var(--shadow);
background-color: var(--background);
.badge {
margin-left: 10px;
}
}
.side-drawer-logo-wrapper {
display: flex;
align-items: center;
padding: 0.85em;
img {
flex: none;
height: 50px;
margin-right: 0.85em;
}
span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.side-drawer-click-outside-closed {
flex: 0 0 0;
}
.side-drawer-closed {
transform: translate(-100%);
}
.side-drawer-heading {
background: transparent;
flex-direction: column;
align-items: stretch;
display: flex;
padding: 0;
margin: 0;
.user-info {
margin: 1em;
}
}
.side-drawer ul {
list-style: none;
margin: 0;
padding: 0;
border-bottom: 1px solid;
border-color: var(--border);
}
.side-drawer ul:last-child {
border: 0;
}
.side-drawer li {
padding: 0;
a,
button {
box-sizing: border-box;
display: block;
height: 3em;
line-height: 3em;
padding: 0 0.7em;
}
}
</style>
diff --git a/src/components/status/status.js b/src/components/status/status.js
index 29493fb093..fb37a7faf6 100644
--- a/src/components/status/status.js
+++ b/src/components/status/status.js
@@ -1,604 +1,590 @@
-import { unescape as ldUnescape, uniqBy } from 'lodash'
+import { uniqBy } from 'lodash'
import { defineAsyncComponent } from 'vue'
import AvatarList from 'src/components/avatar_list/avatar_list.vue'
import EmojiReactions from 'src/components/emoji_reactions/emoji_reactions.vue'
import MentionLink from 'src/components/mention_link/mention_link.vue'
import MentionsLine from 'src/components/mentions_line/mentions_line.vue'
import PostStatusForm from 'src/components/post_status_form/post_status_form.vue'
import StatusActionButtons from 'src/components/status_action_buttons/status_action_buttons.vue'
import StatusContent from 'src/components/status_content/status_content.vue'
import StatusPopover from 'src/components/status_popover/status_popover.vue'
import Timeago from 'src/components/timeago/timeago.vue'
import UserAvatar from 'src/components/user_avatar/user_avatar.vue'
import UserLink from 'src/components/user_link/user_link.vue'
import UserListPopover from 'src/components/user_list_popover/user_list_popover.vue'
import UserPopover from 'src/components/user_popover/user_popover.vue'
import { muteFilterHits } from '../../services/status_parser/status_parser.js'
import {
highlightClass,
highlightStyle,
} from '../../services/user_highlighter/user_highlighter.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useSyncConfigStore } from 'src/stores/sync_config.js'
import { useUserHighlightStore } from 'src/stores/user_highlight.js'
import generateProfileLink from 'src/services/user_profile_link_generator/user_profile_link_generator'
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faAngleDoubleRight,
faChevronDown,
faChevronUp,
faEllipsisH,
faEnvelope,
faEye,
faEyeSlash,
faGlobe,
faIgloo,
faLock,
faLockOpen,
faPlay,
faPlusSquare,
faReply,
faRetweet,
faSmileBeam,
faStar,
faThumbtack,
faTimes,
} from '@fortawesome/free-solid-svg-icons'
library.add(
faEnvelope,
faGlobe,
faIgloo,
faLock,
faLockOpen,
faTimes,
faRetweet,
faReply,
faPlusSquare,
faStar,
faSmileBeam,
faEllipsisH,
faEyeSlash,
faEye,
faThumbtack,
faChevronUp,
faChevronDown,
faAngleDoubleRight,
faPlay,
)
const Status = {
name: 'Status',
components: {
PostStatusForm,
UserAvatar,
AvatarList,
Timeago,
StatusPopover,
UserListPopover,
EmojiReactions,
StatusContent,
MentionLink,
MentionsLine,
UserPopover,
UserLink,
Quote: defineAsyncComponent(() => import('src/components/quote/quote.vue')),
StatusActionButtons,
},
props: {
statusoid: Object,
replies: Array,
expandable: Boolean,
focused: Boolean,
compact: Boolean,
isPreview: Boolean,
noHeading: Boolean,
inlineExpanded: Boolean,
showPinned: Boolean,
inProfile: Boolean,
inConversation: Boolean,
inQuote: Boolean,
profileUserId: String,
simpleTree: Boolean,
showOtherRepliesAsButton: Boolean,
canDive: Boolean,
ignoreMute: Boolean,
threadDisplayStatus: String,
},
emits: ['goto', 'dive', 'toggleExpanded', 'suspendableStateChange'],
data() {
return {
replying: false,
unmuted: false,
userExpanded: false,
mediaPlaying: new Set(),
error: null,
headTailLinks: null,
}
},
computed: {
showReasonMutedThread() {
return (
(this.status.thread_muted ||
(this.status.reblog && this.status.reblog.thread_muted)) &&
!this.inConversation
)
},
allowNonSquareEmoji() {
return this.mergedConfig.nonSquareEmoji
},
pauseMfm() {
return this.mergedConfig.pauseMfm
},
scaleMfm() {
return this.mergedConfig.scaleMfm
},
repeaterClass() {
const user = this.statusoid.user
return highlightClass(user)
},
userClass() {
const user = this.retweet
? this.statusoid.retweeted_status.user
: this.statusoid.user
return highlightClass(user)
},
deleted() {
return this.statusoid.deleted
},
repeaterStyle() {
const user = this.statusoid.user
return highlightStyle(useUserHighlightStore().get(user.screen_name))
},
userStyle() {
if (this.noHeading) return
const user = this.retweet
? this.statusoid.retweeted_status.user
: this.statusoid.user
return highlightStyle(useUserHighlightStore().get(user.screen_name))
},
userProfileLink() {
return this.generateUserProfileLink(
this.status.user.id,
this.status.user.screen_name,
)
},
replyProfileLink() {
if (this.isReply) {
const user = this.$store.getters.findUser(
this.status.in_reply_to_user_id,
)
// FIXME Why user not found sometimes???
return user ? user.statusnet_profile_url : 'NOT_FOUND'
}
},
retweet() {
return !!this.statusoid.retweeted_status
},
retweeterUser() {
return this.statusoid.user
},
retweeter() {
return this.statusoid.user.name || this.statusoid.user.screen_name_ui
},
retweeterHtml() {
return this.statusoid.user.name
},
retweeterProfileLink() {
return this.generateUserProfileLink(
this.statusoid.user.id,
this.statusoid.user.screen_name,
)
},
status() {
if (this.retweet) {
return this.statusoid.retweeted_status
} else {
return this.statusoid
}
},
statusFromGlobalRepository() {
// NOTE: Consider to replace status with statusFromGlobalRepository
return this.$store.state.statuses.allStatusesObject[this.status.id]
},
loggedIn() {
return !!this.currentUser
},
muteFilterHits() {
return muteFilterHits(
Object.values(
useSyncConfigStore().prefsStorage.simple.muteFilters || {},
),
this.status,
)
},
botStatus() {
return this.status.user.actor_type === 'Service'
},
showActorTypeIndicator() {
return !this.hideBotIndication
},
sensitiveStatus() {
return this.status.nsfw
},
mentionsLine() {
if (!this.headTailLinks) return []
const writtenSet = new Set(
this.headTailLinks.writtenMentions.map((_) => _.url),
)
return this.status.attentions
.filter((attn) => {
// no reply user
return (
attn.id !== this.status.in_reply_to_user_id &&
// no self-replies
attn.statusnet_profile_url !==
this.status.user.statusnet_profile_url &&
// don't include if mentions is written
!writtenSet.has(attn.statusnet_profile_url)
)
})
.map((attn) => ({
url: attn.statusnet_profile_url,
content: attn.screen_name,
userId: attn.id,
}))
},
hasMentionsLine() {
return this.mentionsLine.length > 0
},
muteReasons() {
return [
this.userIsMuted ? 'user' : null,
this.status.thread_muted ? 'thread' : null,
this.muteFilterHits.length > 0 ? 'filtered' : null,
this.muteBotStatuses && this.botStatus ? 'bot' : null,
this.muteSensitiveStatuses && this.sensitiveStatus ? 'nsfw' : null,
].filter((_) => _)
},
muteLocalized() {
if (this.muteReasons.length === 0) return null
const mainReason = () => {
switch (this.muteReasons[0]) {
case 'user':
return this.$t('status.muted_user')
case 'thread':
return this.$t('status.thread_muted')
case 'filtered':
return this.$t(
'status.muted_filters',
{
name: this.muteFilterHits[0].name,
filterMore: this.muteFilterHits.length - 1,
},
this.muteFilterHits.length,
)
case 'bot':
return this.$t('status.bot_muted')
case 'nsfw':
return this.$t('status.sensitive_muted')
}
}
if (this.muteReasons.length > 1) {
return this.$t(
'status.multi_reason_mute',
{
main: mainReason(),
numReasonsMore: this.muteReasons.length - 1,
},
this.muteReasons.length - 1,
)
} else {
return mainReason()
}
},
muted() {
if (this.ignoreMute) return false
if (this.statusoid.user.id === this.currentUser.id) return false
return !this.unmuted && !this.shouldNotMute && this.muteReasons.length > 0
},
userIsMuted() {
if (this.statusoid.user.id === this.currentUser.id) return false
const { status } = this
const { reblog } = status
const relationship = this.$store.getters.relationship(status.user.id)
const relationshipReblog =
reblog && this.$store.getters.relationship(reblog.user.id)
return (
(status.muted && !status.thread_muted) ||
// Reprööt of a muted post according to BE
(reblog && reblog.muted && !reblog.thread_muted) ||
// Muted user
relationship.muting ||
// Muted user of a reprööt
(relationshipReblog && relationshipReblog.muting)
)
},
shouldNotMute() {
if (this.ignoreMute) return true
if (this.focused) return true
const { status } = this
const { reblog } = status
return (
((this.inProfile &&
// Don't mute user's posts on user timeline (except reblogs)
((!reblog && status.user.id === this.profileUserId) ||
// Same as above but also allow self-reblogs
(reblog && reblog.user.id === this.profileUserId))) ||
// Don't mute statuses in muted conversation when said conversation is opened
(this.inConversation && status.thread_muted)) &&
// No excuses if post has muted words
!this.muteFilterHits.length > 0
)
},
hideMutedUsers() {
return this.mergedConfig.hideMutedPosts
},
hideMutedThreads() {
return this.mergedConfig.hideMutedThreads
},
hideFilteredStatuses() {
return this.mergedConfig.hideFilteredStatuses
},
hideWordFilteredPosts() {
return this.mergedConfig.hideWordFilteredPosts
},
hideStatus() {
return (
!this.shouldNotMute &&
((this.muted && this.hideFilteredStatuses) ||
(this.userIsMuted && this.hideMutedUsers) ||
(this.status.thread_muted && this.hideMutedThreads) ||
(this.muteFilterHits.length > 0 && this.hideWordFilteredPosts) ||
this.muteFilterHits.some((x) => x.hide))
)
},
isReply() {
return !!(
this.status.in_reply_to_status_id && this.status.in_reply_to_user_id
)
},
replyToName() {
if (this.status.in_reply_to_screen_name) {
return this.status.in_reply_to_screen_name
} else {
const user = this.$store.getters.findUser(
this.status.in_reply_to_user_id,
)
return user && user.screen_name_ui
}
},
- replySubject() {
- if (!this.status.summary) return ''
- const decodedSummary = ldUnescape(this.status.summary)
- const behavior = this.mergedConfig.subjectLineBehavior
- const startsWithRe = decodedSummary.match(/^re[: ]/i)
- if ((behavior !== 'noop' && startsWithRe) || behavior === 'masto') {
- return decodedSummary
- } else if (behavior === 'email') {
- return 're: '.concat(decodedSummary)
- } else if (behavior === 'noop') {
- return ''
- }
- },
combinedFavsAndRepeatsUsers() {
// Use the status from the global status repository since favs and repeats are saved in it
const combinedUsers = [].concat(
this.statusFromGlobalRepository.favoritedBy,
this.statusFromGlobalRepository.rebloggedBy,
)
return uniqBy(combinedUsers, 'id')
},
tags() {
return this.status.tags
.filter((tagObj) => Object.hasOwn(tagObj, 'name'))
.map((tagObj) => tagObj.name)
.join(' ')
},
hidePostStats() {
return this.mergedConfig.hidePostStats
},
shouldDisplayFavsAndRepeats() {
return (
!this.hidePostStats &&
this.focused &&
(this.combinedFavsAndRepeatsUsers.length > 0 ||
this.statusFromGlobalRepository.quotes_count)
)
},
muteBotStatuses() {
return this.mergedConfig.muteBotStatuses
},
muteSensitiveStatuses() {
return this.mergedConfig.muteSensitiveStatuses
},
hideBotIndication() {
return this.mergedConfig.hideBotIndication
},
currentUser() {
return this.$store.state.users.currentUser
},
mergedConfig() {
return useMergedConfigStore().mergedConfig
},
isSuspendable() {
return !this.replying && this.mediaPlaying.size === 0
},
inThreadForest() {
return !!this.threadDisplayStatus
},
threadShowing() {
return this.threadDisplayStatus === 'showing'
},
visibilityLocalized() {
return this.$i18n.t('general.scope_in_timeline.' + this.status.visibility)
},
isEdited() {
return this.status.edited_at !== null
},
editingAvailable() {
return useInstanceCapabilitiesStore().editingAvailable
},
quoteId() {
return this.status.quote_id
},
quoteUrl() {
return this.status.quote_url
},
quoteVisible() {
return this.status.quote_visible
},
quoteExpanded() {
return !this.inQuote
},
scrobblePresent() {
if (this.mergedConfig.hideScrobbles) return false
if (!this.status.user?.latestScrobble) return false
const value = this.mergedConfig.hideScrobblesAfter.match(/\d+/gs)[0]
const unit = this.mergedConfig.hideScrobblesAfter.match(/\D+/gs)[0]
let multiplier = 60 * 1000 // minutes is smallest unit
switch (unit) {
case 'm':
break
case 'h':
multiplier *= 60 // hour
break
case 'd':
multiplier *= 60 // hour
multiplier *= 24 // day
break
}
const maxAge = Number(value) * multiplier
const createdAt = Date.parse(this.status.user.latestScrobble.created_at)
const age = Date.now() - createdAt
if (age > maxAge) return false
return this.status.user.latestScrobble.artist
},
scrobble() {
return this.status.user?.latestScrobble
},
},
methods: {
visibilityIcon(visibility) {
switch (visibility) {
case 'private':
return 'lock'
case 'unlisted':
return 'lock-open'
case 'direct':
return 'envelope'
case 'local':
return 'igloo'
default:
return 'globe'
}
},
showError(error) {
this.error = error
},
clearError() {
this.error = undefined
},
toggleReplyForm() {
if (this.replying) {
// This emits 'close-accepted' if successful
// which in turn callse closeReply()
this.$refs.postStatusForm.requestClose()
} else {
this.replying = true
}
},
closeReplyForm() {
this.replying = false
},
gotoOriginal(id) {
if (this.inConversation) {
this.$emit('goto', id)
}
},
toggleExpanded() {
this.$emit('toggleExpanded')
},
toggleMute() {
this.unmuted = !this.unmuted
},
toggleUserExpanded() {
this.userExpanded = !this.userExpanded
},
generateUserProfileLink(id, name) {
return generateProfileLink(
id,
name,
useInstanceStore().restrictedNicknames,
)
},
addMediaPlaying(id) {
this.mediaPlaying.add(id)
},
removeMediaPlaying(id) {
this.mediaPlaying.delete(id)
},
setHeadTailLinks(headTailLinks) {
this.headTailLinks = headTailLinks
},
toggleThreadDisplay() {
this.controlledToggleThreadDisplay()
},
- scrollIfFocused(focusedId) {
+ scrollIfFocused(focused) {
if (this.$el.getBoundingClientRect == null) return
- const id = focusedId
- if (this.status.id === id) {
+ if (focused) {
const rect = this.$el.getBoundingClientRect()
if (rect.top < 100) {
// Post is above screen, match its top to screen top
window.scrollBy(0, rect.top - 100)
} else if (rect.height >= window.innerHeight - 50) {
// Post we want to see is taller than screen so match its top to screen top
window.scrollBy(0, rect.top - 100)
} else if (rect.bottom > window.innerHeight - 50) {
// Post is below screen, match its bottom to screen bottom
window.scrollBy(0, rect.bottom - window.innerHeight + 50)
}
}
},
},
watch: {
focused: function (id) {
this.scrollIfFocused(id)
},
'status.repeat_num': function (num) {
// refetch repeats when repeat_num is changed in any way
if (
this.focused &&
this.statusFromGlobalRepository.rebloggedBy &&
this.statusFromGlobalRepository.rebloggedBy.length !== num
) {
this.$store.dispatch('fetchRepeats', this.status.id)
}
},
'status.fave_num': function (num) {
// refetch favs when fave_num is changed in any way
if (
this.focused &&
this.statusFromGlobalRepository.favoritedBy &&
this.statusFromGlobalRepository.favoritedBy.length !== num
) {
this.$store.dispatch('fetchFavs', this.status.id)
}
},
isSuspendable: function (suspend) {
this.$emit('suspendableStateChange', { id: this.statusoid.id, suspend })
},
},
}
export default Status
diff --git a/src/components/status/status.scss b/src/components/status/status.scss
index f710088d67..1214d8b12b 100644
--- a/src/components/status/status.scss
+++ b/src/components/status/status.scss
@@ -1,388 +1,392 @@
.Status {
min-width: 0;
white-space: normal;
overflow-wrap: break-word;
text-wrap: pretty;
&:hover {
--_still-image-img-visibility: visible;
--_still-image-canvas-visibility: hidden;
--_still-image-label-visibility: hidden;
}
.gravestone {
padding: var(--status-margin);
display: flex;
.deleted-text {
margin: 0.5em 0;
align-items: center;
}
}
.status-container {
display: flex;
padding: var(--status-margin);
gap: var(--status-margin);
> * {
min-width: 0;
}
}
.pin {
display: flex;
align-items: center;
justify-content: flex-end;
margin-right: 0.5em;
}
._misclick-prevention & {
pointer-events: none;
.attachments {
pointer-events: initial;
cursor: initial;
}
}
.left-side {
flex: 0 0 auto;
}
.right-side {
flex: 1 1 auto;
}
.usercard {
margin-bottom: var(--status-margin);
}
.status-username {
white-space: nowrap;
overflow: hidden;
max-width: 85%;
font-weight: bold;
flex-shrink: 1;
margin-right: 0.4em;
text-overflow: ellipsis;
--_still_image-label-scale: 0.25;
--emoji-size: 1em;
}
.status-favicon {
height: 1.2em;
width: 1.2em;
margin-right: 0.4em;
object-fit: contain;
}
.status-heading {
margin-bottom: 0.5em;
}
.heading-name-row {
display: flex;
justify-content: space-between;
line-height: 1.3;
a {
display: inline-block;
white-space: nowrap;
text-overflow: ellipsis;
overflow-x: hidden;
width: 100%
}
}
.account-name {
display: inline-block;
min-width: 1em;
margin-right: 0.4em;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex: 1 1 0;
&.unknown {
min-width: 8em;
}
}
.heading-left {
display: flex;
min-width: 0;
}
.heading-right {
display: flex;
flex-shrink: 0;
align-self: baseline;
.button-unstyled {
padding: 0.2em;
margin: -0.2em;
}
.svg-inline--fa {
margin-left: 0.25em;
}
}
.glued-label {
display: inline-flex;
white-space: nowrap;
}
.timeago {
margin-right: 0.2em;
}
& .heading-reply-row,
& .heading-edited-row {
position: relative;
align-content: baseline;
font-size: 0.85em;
margin-top: 0.2em;
line-height: 130%;
max-width: 100%;
align-items: stretch;
}
& .reply-to-popover,
& .reply-to-no-popover,
& .mentions {
min-width: 0;
margin-right: 0.4em;
flex-shrink: 0;
}
.reply-glued-label {
margin-right: 0.5em;
}
.reply-to-popover {
.reply-to:hover::before {
content: "";
display: block;
position: absolute;
bottom: 0;
width: 100%;
border-bottom: 1px solid var(--faint);
pointer-events: none;
}
.faint-link:hover {
// override default
text-decoration: none;
}
&.-strikethrough {
.reply-to::after {
content: "";
display: block;
position: absolute;
top: 50%;
width: 100%;
border-bottom: 1px solid var(--faint);
pointer-events: none;
}
}
}
& .mentions,
& .reply-to {
white-space: nowrap;
position: relative;
}
& .mentions-text,
& .reply-to-text {
color: var(--faint);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.mentions-line {
display: inline;
}
.replies {
margin-top: 0.25em;
line-height: 1.3;
font-size: 0.85em;
display: flex;
flex-wrap: wrap;
& > * {
margin-right: 0.4em;
}
}
.reply-link {
height: 17px;
}
.repeat-info {
display: flex;
align-items: center;
padding: 0.4em var(--status-margin);
.repeater-avatar {
flex: 0 0 1.5em;
border-radius: var(--roundness);
margin-left: 2em; // 3.5 (poster avatar size) - 1.5 (repeater avatar size)
width: 1.5em;
height: 1.5em;
}
.right-side {
display: flex;
flex: 1 1 auto;
overflow-x: hidden;
text-overflow: ellipsis;
margin-right: 0;
gap: 0.5em;
.repeater-name {
flex: 0 1 auto;
margin: 0;
}
.repeat-label {
white-space: nowrap;
flex: 0 0 auto;
.repeat-icon {
vertical-align: middle;
color: var(--cGreen);
}
}
.emoji {
width: 1em;
height: 1em;
vertical-align: middle;
object-fit: contain;
}
}
}
.status-fadein {
animation-duration: 0.4s;
animation-name: fadein;
}
@keyframes fadein {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.status-actions {
position: relative;
width: 100%;
display: grid;
grid-template-columns: 1fr;
grid-auto-columns: 1fr;
grid-auto-flow: column;
margin-top: var(--status-margin);
}
.muted {
padding: 0.25em 0.6em;
height: 1.2em;
line-height: 1.2em;
text-overflow: ellipsis;
overflow: hidden;
display: flex;
flex-wrap: nowrap;
gap: 1ex;
& .status-username,
& .mute-reason {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.status-username {
font-weight: normal;
flex: 0 1 auto;
margin-right: 0.2em;
font-size: smaller;
display: flex;
}
.unmute {
flex: 0 0 auto;
margin-left: auto;
display: block;
}
}
.reply-form {
padding-top: 0;
padding-bottom: 0;
}
.reply-body {
flex: 1;
}
.favs-repeated-users {
margin-top: var(--status-margin);
}
.stats {
width: 100%;
display: flex;
line-height: 1em;
}
.avatar-row {
flex: 1;
position: relative;
display: flex;
align-items: center;
overflow: hidden;
&::before {
content: "";
position: absolute;
height: 100%;
width: 1px;
left: 0;
background-color: var(--textFaint);
}
}
.stat-count {
margin-right: var(--status-margin);
user-select: none;
.stat-title {
color: var(--textFaint);
font-size: 0.85em;
text-transform: uppercase;
position: relative;
}
.stat-number {
font-weight: bolder;
font-size: 1.1em;
line-height: 1em;
color: var(--text);
}
&:hover .stat-title {
text-decoration: underline;
}
}
+
+ .status-action-buttons {
+ margin-top: var(--status-margin);
+ }
}
diff --git a/src/components/status/status.vue b/src/components/status/status.vue
index 491f28e329..da9fbe7abf 100644
--- a/src/components/status/status.vue
+++ b/src/components/status/status.vue
@@ -1,564 +1,561 @@
<template>
<div
v-if="!hideStatus"
ref="root"
class="Status"
:class="[{ '-focused': focused }, { '-conversation': inlineExpanded }]"
>
<div
v-if="error"
class="alert error"
>
{{ error }}
<button
class="fa-scale-110 fa-old-padding"
type="button"
@click="clearError"
>
<FAIcon icon="times" />
</button>
</div>
<template v-if="muted && !isPreview">
<div class="status-container muted">
<small class="status-username">
<FAIcon
v-if="muted && retweet"
class="fa-scale-110 fa-old-padding repeat-icon"
icon="retweet"
/>
<user-link
:user="status.user"
:at="false"
/>
</small>
<small class="mute-reason">
{{ muteLocalized }}
</small>
<button
class="unmute button-unstyled"
@click.prevent="toggleMute"
>
<FAIcon
icon="eye-slash"
class="fa-scale-110 fa-old-padding"
/>
</button>
</div>
</template>
<template v-else>
<div
v-if="retweet && !noHeading && !inConversation"
:class="[repeaterClass, { highlighted: repeaterStyle }]"
:style="[repeaterStyle]"
class="status-container repeat-info"
>
<UserAvatar
v-if="retweet"
class="left-side repeater-avatar"
:show-actor-type-indicator="showActorTypeIndicator"
:user="statusoid.user"
/>
<div class="right-side faint">
<bdi
class="status-username repeater-name"
:title="retweeter"
>
<router-link
v-if="retweeterHtml"
:to="retweeterProfileLink"
>
<RichContent
:html="retweeterHtml"
:emoji="retweeterUser.emoji"
:allow-non-square-emoji="allowNonSquareEmoji"
:pause-mfm="pauseMfm"
:scale-mfm="scaleMfm"
:is-local="retweeterUser.is_local"
/>
</router-link>
<router-link
v-else
:to="retweeterProfileLink"
>{{ retweeter }}</router-link>
</bdi>
<div class="repeat-label">
<FAIcon
icon="retweet"
class="repeat-icon"
:title="$t('tool_tip.repeat')"
/>
{{ $t('timeline.repeated') }}
</div>
</div>
</div>
<div
v-if="!deleted"
:class="[userClass, { highlighted: userStyle, '-repeat': retweet && !inConversation }]"
:style="[ userStyle ]"
class="status-container"
:data-tags="tags"
>
<div
v-if="!noHeading"
class="left-side"
>
<a
v-if="status.user?.name"
:href="$router.resolve(userProfileLink).href"
@click.prevent
>
<UserPopover
:user-id="status.user.id"
:overlay-centers="true"
>
<UserAvatar
class="post-avatar"
:show-actor-type-indicator="showActorTypeIndicator"
:compact="compact"
:user="status?.user"
/>
</UserPopover>
</a>
<UserAvatar
v-else
:user="status?.user"
class="post-avatar"
:compact="compact"
:title="$t('status.unknown_user_info')"
/>
</div>
<div class="right-side">
<div
v-if="!noHeading"
class="status-heading"
>
<div class="heading-name-row">
<div
v-if="status.user"
class="heading-left"
>
<h4
v-if="status.user.name_html"
class="status-username"
:title="status.user.name"
>
<RichContent
:html="status.user.name"
:emoji="status.user.emoji"
:allow-non-square-emoji="allowNonSquareEmoji"
:is-local="status.user.is_local"
/>
</h4>
<h4
v-else
class="status-username"
:title="status.user.name"
>
{{ status.user.name }}
</h4>
<user-link
class="account-name"
:title="status.user.screen_name_ui"
:user="status.user"
:at="false"
/>
<img
v-if="!!(status.user && status.user.favicon)"
class="status-favicon"
:src="status.user.favicon"
>
</div>
<span class="heading-right">
<span
v-if="showPinned"
class="pin"
>
<FAIcon
icon="thumbtack"
class="faint"
/>
<span class="faint">{{ $t('status.pinned') }}</span>
</span>
<router-link
class="timeago faint"
:to="{ name: 'conversation', params: { id: status.id } }"
>
<Timeago
:time="status.created_at"
:auto-update="60"
/>
</router-link>
<span
v-if="status.visibility"
class="visibility-icon"
:title="visibilityLocalized"
>
<FAIcon
fixed-width
class="fa-scale-110"
:icon="visibilityIcon(status.visibility)"
/>
</span>
<button
v-if="expandable && !isPreview"
class="button-unstyled"
:title="$t('status.expand')"
@click.prevent="toggleExpanded"
>
<FAIcon
fixed-width
class="fa-scale-110"
icon="plus-square"
/>
</button>
<button
v-if="unmuted"
class="button-unstyled"
@click.prevent="toggleMute"
>
<FAIcon
fixed-width
icon="eye-slash"
class="fa-scale-110"
/>
</button>
<button
v-if="inThreadForest && replies && replies.length && !simpleTree"
class="button-unstyled"
:title="threadShowing ? $t('status.thread_hide') : $t('status.thread_show')"
:aria-expanded="threadShowing ? 'true' : 'false'"
@click.prevent="toggleThreadDisplay"
>
<FAIcon
fixed-width
class="fa-scale-110"
:icon="threadShowing ? 'chevron-up' : 'chevron-down'"
/>
</button>
<button
v-if="canDive && !simpleTree"
class="button-unstyled"
:title="$t('status.show_only_conversation_under_this')"
@click.prevent="$emit('dive')"
>
<FAIcon
fixed-width
class="fa-scale-110"
:icon="'angle-double-right'"
/>
</button>
</span>
</div>
<div
v-if="scrobblePresent"
class="status-rich-presence"
>
<a
v-if="scrobble.externalLink"
:href="scrobble.externalLink"
target="_blank"
>
{{ scrobble.artist }} — {{ scrobble.title }}
<FAIcon
class="fa-scale-110 fa-old-padding"
icon="play"
/>
<span class="status-rich-presence-time">
<Timeago
template-key="time.in_past"
:time="scrobble.created_at"
:auto-update="60"
/>
</span>
</a>
<span v-if="!scrobble.externalLink">
<FAIcon
class="fa-scale-110 fa-old-padding"
icon="music"
/>
{{ scrobble.artist }} — {{ scrobble.title }}
<FAIcon
class="fa-scale-110 fa-old-padding"
icon="play"
/>
<span class="status-rich-presence-time">
<Timeago
template-key="time.in_past"
:time="scrobble.created_at"
:auto-update="60"
/>
</span>
</span>
</div>
<div
v-if="isReply || hasMentionsLine"
class="heading-reply-row"
>
<span
v-if="isReply"
class="glued-label reply-glued-label"
>
<i18n-t
keypath="status.reply_to_with_arg"
scope="global"
>
<template #replyToWithIcon>
<StatusPopover
v-if="!isPreview"
:status-id="status.parent_visible && status.in_reply_to_status_id"
class="reply-to-popover"
style="min-width: 0;"
:class="{ '-strikethrough': !status.parent_visible }"
>
<button
class="button-unstyled reply-to"
:aria-label="$t('tool_tip.reply')"
@click.prevent="gotoOriginal(status.in_reply_to_status_id)"
>
<i18n-t
keypath="status.reply_to_with_icon"
scope="global"
>
<template #icon>
<FAIcon
class="fa-scale-110 fa-old-padding"
icon="reply"
flip="horizontal"
/>
</template>
<template #replyTo>
<span
class="reply-to-text"
>
{{ $t('status.reply_to') }}
</span>
</template>
</i18n-t>
</button>
</StatusPopover>
<span
v-else
class="reply-to-no-popover"
>
<span class="reply-to-text">{{ $t('status.reply_to') }}</span>
</span>
</template>
<template #user>
<MentionLink
:content="replyToName"
:url="replyProfileLink"
:user-id="status.in_reply_to_user_id"
:user-screen-name="status.in_reply_to_screen_name"
/>
</template>
</i18n-t>
</span>
<!-- This little wrapper is made for sole purpose of "gluing" -->
<!-- "Mentions" label to the first mention -->
<span
v-if="hasMentionsLine"
class="glued-label"
>
<span
class="mentions"
:aria-label="$t('tool_tip.mentions')"
@click.prevent="gotoOriginal(status.in_reply_to_status_id)"
>
<span
class="mentions-text"
>
{{ $t('status.mentions') }}
</span>
</span>
<MentionsLine
v-if="hasMentionsLine"
:mentions="mentionsLine.slice(0, 1)"
class="mentions-line-first"
/>
</span>
{{ ' ' }}
<MentionsLine
v-if="hasMentionsLine"
:mentions="mentionsLine.slice(1)"
class="mentions-line"
/>
</div>
<div
v-if="isEdited && editingAvailable && !isPreview"
class="heading-edited-row"
>
<i18n-t
scope="global"
keypath="status.edited_at"
tag="span"
>
<template #time>
<Timeago
template-key="time.in_past"
:time="status.edited_at"
:auto-update="60"
:long-format="true"
/>
</template>
</i18n-t>
</div>
</div>
<StatusContent
ref="content"
:status="status"
:focused="focused"
:in-conversation="inConversation"
@mediaplay="addMediaPlaying($event)"
@mediapause="removeMediaPlaying($event)"
@parse-ready="setHeadTailLinks"
/>
<Quote
:status-id="quoteId"
:status-url="quoteUrl"
:status-visible="quoteVisible"
:initially-expanded="quoteExpanded"
/>
<div
v-if="inConversation && !isPreview && replies && replies.length"
class="replies"
>
<button
v-if="showOtherRepliesAsButton && replies.length > 1"
class="button-unstyled -link"
:title="$t('status.ancestor_follow', { numReplies: replies.length - 1 }, replies.length - 1)"
@click.prevent="$emit('dive')"
>
{{ $t('status.replies_list_with_others', { numReplies: replies.length - 1 }, replies.length - 1) }}
</button>
<span
v-else
class="faint"
>
{{ $t('status.replies_list') }}
</span>
<StatusPopover
v-for="reply in replies"
:key="reply.id"
:status-id="reply.id"
>
<button
class="button-unstyled -link reply-link"
@click.prevent="gotoOriginal(reply.id)"
>
{{ reply.name }}
</button>
</StatusPopover>
</div>
<transition name="fade">
<div
v-if="shouldDisplayFavsAndRepeats"
class="favs-repeated-users"
>
<div class="stats">
<UserListPopover
v-if="statusFromGlobalRepository.rebloggedBy && statusFromGlobalRepository.rebloggedBy.length > 0"
:users="statusFromGlobalRepository.rebloggedBy"
>
<div class="stat-count">
<a class="stat-title">{{ $t('status.repeats') }}</a>
<div class="stat-number">
{{ statusFromGlobalRepository.rebloggedBy.length }}
</div>
</div>
</UserListPopover>
<UserListPopover
v-if="statusFromGlobalRepository.favoritedBy && statusFromGlobalRepository.favoritedBy.length > 0"
:users="statusFromGlobalRepository.favoritedBy"
>
<div
class="stat-count"
>
<a class="stat-title">{{ $t('status.favorites') }}</a>
<div class="stat-number">
{{ statusFromGlobalRepository.favoritedBy.length }}
</div>
</div>
</UserListPopover>
<router-link
v-if="statusFromGlobalRepository.quotes_count > 0"
:to="{ name: 'quotes', params: { id: status.id } }"
>
<div
class="stat-count"
>
<a class="stat-title">{{ $t('status.quotes') }}</a>
<div class="stat-number">
{{ statusFromGlobalRepository.quotes_count }}
</div>
</div>
</router-link>
<div class="avatar-row">
<AvatarList :users="combinedFavsAndRepeatsUsers" />
</div>
</div>
</div>
</transition>
<EmojiReactions
v-if="(mergedConfig.emojiReactionsOnTimeline || focused) && (!noHeading && !isPreview)"
:status="status"
/>
<StatusActionButtons
v-if="!noHeading && !isPreview"
+ class="status-action-buttons"
:status="status"
:replying="replying"
@toggle-replying="toggleReplyForm"
/>
</div>
</div>
<div
v-else
class="gravestone"
>
<div class="left-side">
<UserAvatar
class="post-avatar"
:compact="compact"
:show-actor-type-indicator="showActorTypeIndicator"
/>
</div>
<div class="right-side">
<div class="deleted-text">
{{ $t('status.status_deleted') }}
</div>
</div>
</div>
<div
v-if="replying"
class="status-container reply-form"
>
<PostStatusForm
ref="postStatusForm"
class="reply-body"
:closeable="true"
- :reply-to="status.id"
- :attentions="status.attentions"
- :replied-user="status.user"
- :copy-message-scope="status.visibility"
- :subject="replySubject"
+ :replied-status="status"
@posted="closeReplyForm"
@draft-done="closeReplyForm"
@close-accepted="closeReplyForm"
/>
</div>
</template>
</div>
</template>
<script src="./status.js"></script>
<style src="./status.scss" lang="scss"></style>
diff --git a/src/components/status_action_buttons/action_button.js b/src/components/status_action_buttons/action_button.js
index f3dd13e43e..2434820db2 100644
--- a/src/components/status_action_buttons/action_button.js
+++ b/src/components/status_action_buttons/action_button.js
@@ -1,164 +1,175 @@
import Popover from 'src/components/popover/popover.vue'
import StatusBookmarkFolderMenu from 'src/components/status_bookmark_folder_menu/status_bookmark_folder_menu.vue'
import EmojiPicker from '../emoji_picker/emoji_picker.vue'
import { useInstanceStore } from 'src/stores/instance.js'
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faBookmark as faBookmarkRegular,
faFaceSmileBeam,
faStar as faStarRegular,
} from '@fortawesome/free-regular-svg-icons'
import {
faBookmark,
faCheck,
faChevronDown,
faChevronRight,
+ faComments,
faExternalLinkAlt,
faEye,
faEyeSlash,
faHistory,
+ faList,
faMinus,
+ faPencil,
faPlus,
faReply,
faRetweet,
faShareAlt,
faStar,
faThumbtack,
faTimes,
faWrench,
} from '@fortawesome/free-solid-svg-icons'
library.add(
faPlus,
faMinus,
faCheck,
faTimes,
faWrench,
faChevronRight,
faChevronDown,
faReply,
faRetweet,
faStar,
faStarRegular,
faFaceSmileBeam,
faBookmark,
faBookmarkRegular,
faEyeSlash,
faEye,
faThumbtack,
+ faPencil,
faShareAlt,
+ faComments,
+ faList,
faExternalLinkAlt,
faHistory,
)
export default {
props: [
'button',
'status',
'extra',
'status',
'funcArg',
'getClass',
'getComponent',
'doAction',
'outerClose',
+ 'defaultButtonStyle',
+ 'hideLabel',
],
components: {
StatusBookmarkFolderMenu,
EmojiPicker,
Popover,
},
data: () => ({
animationState: false,
}),
computed: {
buttonClass() {
return [
this.button.name + '-button',
{
'-with-extra': this.button.name === 'bookmark',
'-extra': this.extra,
'-quick': !this.extra,
},
]
},
userIsMuted() {
return this.$store.getters.relationship(this.status.user.id).muting
},
threadIsMuted() {
return this.status.thread_muted
},
hideCustomEmoji() {
return !useInstanceCapabilitiesStore()
.pleromaCustomEmojiReactionsAvailable
},
hidePostStats() {
return useMergedConfigStore().mergedConfig.hidePostStats
},
buttonInnerClass() {
+ const buttonStyleClass = this.defaultButtonStyle
+ ? 'button-default'
+ : 'button-unstyled'
return [
this.button.name + '-button',
{
'main-button': this.extra,
- 'button-unstyled': !this.extra,
+ [buttonStyleClass]: !this.extra,
'-active': this.button.active?.(this.funcArg),
disabled: this.button.interactive
? !this.button.interactive(this.funcArg)
: false,
},
]
},
remoteInteractionLink() {
return useInstanceStore().getRemoteInteractionLink({
statusId: this.status.id,
})
},
},
methods: {
addReaction(event) {
const emoji = event.insertion
const existingReaction = this.status.emoji_reactions.find(
(r) => r.name === emoji,
)
if (existingReaction && existingReaction.me) {
this.$store.dispatch('unreactWithEmoji', { id: this.status.id, emoji })
} else {
this.$store.dispatch('reactWithEmoji', { id: this.status.id, emoji })
}
},
onShowEmojiPicker() {
this.$emit('emojiPickerShown', true)
},
onHideEmojiPicker() {
this.$emit('emojiPickerShown', false)
},
doActionWrap(
button,
close = () => {
/* no-op */
},
) {
if (
this.button.interactive ? !this.button.interactive(this.funcArg) : false
)
return
if (button.name === 'emoji') {
this.$refs.picker.togglePicker()
} else {
this.animationState = true
this.getComponent(button) === 'button' && this.doAction(button)
setTimeout(() => {
this.animationState = false
}, 500)
close()
}
},
},
}
diff --git a/src/components/status_action_buttons/action_button.vue b/src/components/status_action_buttons/action_button.vue
index 043cd995d0..e309ecea68 100644
--- a/src/components/status_action_buttons/action_button.vue
+++ b/src/components/status_action_buttons/action_button.vue
@@ -1,111 +1,111 @@
<template>
<div
class="action-button"
:class="buttonClass"
>
<component
:is="getComponent(button)"
class="action-button-inner"
:class="buttonInnerClass"
role="menuitem"
type="button"
placement="bottom"
:title="$t(button.label(funcArg))"
target="_blank"
:tabindex="0"
:disabled="button.interactive ? !button.interactive(funcArg) : false"
:href="getComponent(button) == 'a' ? button.link?.(funcArg) || remoteInteractionLink : undefined"
@click="doActionWrap(button, outerClose)"
>
<FALayers>
<FAIcon
class="fa-scale-110"
:icon="button.icon(funcArg)"
:spin="!extra && getComponent(button) == 'button' && button.animated?.() && animationState"
:style="{ '--fa-animation-duration': '750ms' }"
fixed-width
/>
<template v-if="!buttonClass.disabled && (!button.interactive || button?.interactive(funcArg)) && button.toggleable?.(funcArg) && button.active">
<FAIcon
v-if="button.active(funcArg) && button.activeIndicator?.() !== null"
class="active-marker"
transform="shrink-6 up-9 left-12"
:icon="button.activeIndicator?.(funcArg) || 'check'"
/>
<FAIcon
v-if="!button.active(funcArg)"
class="focus-marker"
transform="shrink-6 up-9 left-12"
:icon="button.openIndicator?.(funcArg) || 'plus'"
/>
<FAIcon
v-else
class="focus-marker"
transform="shrink-6 up-9 left-12"
:icon="button.closeIndicator?.(funcArg) || 'minus'"
/>
</template>
</FALayers>
<span
v-if="extra"
class="action-label"
>
{{ $t(button.label(funcArg)) }}
</span>
<FAIcon
v-if="button.dropdown?.()"
class="chevron-icon"
:icon="extra ? 'chevron-right' : 'chevron-down'"
fixed-width
/>
</component>
<span
- v-if="!hidePostStats && button.counter?.(funcArg) > 0"
+ v-if="!hidePostStats && button.counter?.(funcArg) > 0 && !hideLabel"
class="action-counter"
>
{{ button.counter?.(funcArg) }}
</span>
<span
v-if="!extra && button.name === 'bookmark'"
class="separator"
/>
<Popover
v-if="button.name === 'bookmark'"
class="chevron-popover"
:trigger="extra ? 'hover' : 'click'"
:placement="extra ? 'right' : 'bottom'"
:offset="extra ? { x: 10 } : { y: 10 }"
:trigger-attrs="{ class: 'extra-button' }"
>
<template #trigger>
<FAIcon
class="chevron-icon"
:icon="extra ? 'chevron-right' : 'chevron-down'"
fixed-width
/>
</template>
<template #content="{close}">
<StatusBookmarkFolderMenu
v-if="button.name === 'bookmark'"
:status="status"
@close="() => { close(); outerClose?.() }"
/>
</template>
</Popover>
<EmojiPicker
v-if="button.name === 'emoji'"
ref="picker"
:enable-sticker-picker="false"
:hide-custom-emoji="hideCustomEmoji"
class="emoji-picker-panel"
@emoji="addReaction"
@show="onShowEmojiPicker"
@close="onHideEmojiPicker"
/>
</div>
</template>
<script src="./action_button.js" />
<style lang="scss" src="./action_button.scss" />
diff --git a/src/components/status_action_buttons/action_button_container.js b/src/components/status_action_buttons/action_button_container.js
index 1f4cfc3f64..d031bd6e94 100644
--- a/src/components/status_action_buttons/action_button_container.js
+++ b/src/components/status_action_buttons/action_button_container.js
@@ -1,144 +1,151 @@
import { defineAsyncComponent } from 'vue'
import Popover from 'src/components/popover/popover.vue'
import ActionButton from './action_button.vue'
import { useAdminSettingsStore } from 'src/stores/admin_settings.js'
+import genRandomSeed from 'src/services/random_seed/random_seed.service.js'
+
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faEnvelope,
faEye,
faEyeSlash,
faFolderTree,
faGlobe,
faLock,
faLockOpen,
faUser,
} from '@fortawesome/free-solid-svg-icons'
library.add(
faUser,
faGlobe,
faFolderTree,
faEye,
faEyeSlash,
faLock,
faLockOpen,
faEnvelope,
)
export default {
components: {
ActionButton,
Popover,
MuteConfirm: defineAsyncComponent(
() => import('src/components/confirm_modal/mute_confirm.vue'),
),
UserTimedFilterModal: defineAsyncComponent(
() =>
import(
'src/components/user_timed_filter_modal/user_timed_filter_modal.vue'
),
),
},
- props: ['button', 'status'],
+ props: ['button', 'status', 'defaultButton', 'hideLabel'],
emits: ['emojiPickerShown'],
mounted() {
if (this.button.name === 'mute') {
this.$store.dispatch('fetchDomainMutes')
}
},
+ data() {
+ return {
+ randomSeed: genRandomSeed(),
+ }
+ },
computed: {
buttonClass() {
return [
this.button.name + '-button',
{
'-with-extra': this.button.name === 'bookmark',
'-extra': this.extra,
'-quick': !this.extra,
},
]
},
user() {
return this.status.user
},
userIsMuted() {
return this.$store.getters.relationship(this.user.id).muting
},
conversationIsMuted() {
return this.status.thread_muted
},
domain() {
return this.user.fqn.split('@')[1]
},
domainIsMuted() {
return new Set(this.$store.state.users.currentUser.domainMutes).has(
this.domain,
)
},
availableScopes() {
return ['private', 'unlisted', 'direct', 'public'].filter((scope) => {
return scope !== this.status.visibility
})
},
},
methods: {
visibilityIcon(visibility) {
switch (visibility) {
case 'private':
return 'lock'
case 'unlisted':
return 'lock-open'
case 'direct':
return 'envelope'
case 'local':
return 'igloo'
default:
return 'globe'
}
},
unmuteUser() {
return this.$store.dispatch('unmuteUser', this.user.id)
},
unmuteConversation() {
return this.$store.dispatch('unmuteConversation', { id: this.status.id })
},
unmuteDomain() {
return this.$store.dispatch('unmuteDomain', this.domain)
},
toggleUserMute() {
if (this.userIsMuted) {
this.unmuteUser()
} else {
this.$refs.confirmUser.optionallyPrompt()
}
},
setScope(visibility) {
return useAdminSettingsStore().changeStatusScope({
id: this.status.id,
visibility,
})
},
setSensitive(sensitive) {
useAdminSettingsStore().changeStatusScope({
id: this.status.id,
sensitive,
})
},
toggleConversationMute() {
if (this.conversationIsMuted) {
this.unmuteConversation()
} else {
this.$refs.confirmConversation.optionallyPrompt()
}
},
toggleDomainMute() {
if (this.domainIsMuted) {
this.unmuteDomain()
} else {
this.$refs.confirmDomain.optionallyPrompt()
}
},
},
}
diff --git a/src/components/status_action_buttons/action_button_container.vue b/src/components/status_action_buttons/action_button_container.vue
index 24f9a3c3bf..72b0136dfb 100644
--- a/src/components/status_action_buttons/action_button_container.vue
+++ b/src/components/status_action_buttons/action_button_container.vue
@@ -1,159 +1,161 @@
<template>
<div>
<Popover
v-if="button.dropdown?.()"
:trigger="$attrs.extra ? 'hover' : 'click'"
:offset="{ y: 5 }"
:placement="$attrs.extra ? 'right' : 'bottom'"
>
<template #trigger>
<ActionButton
:button="button"
:status="status"
+ :hide-label="hideLabel"
v-bind.prop="$attrs"
/>
</template>
<template #content>
<div
v-if="button.name === 'changeScope'"
:id="`popup-menu-scope-${randomSeed}`"
class="dropdown-menu"
role="menu"
>
<div
v-for="visibility in availableScopes"
:key="visibility"
class="menu-item dropdown-item extra-action -icon"
>
<button
class="main-button"
@click="() => setScope(visibility)"
>
<FAIcon
:icon="visibilityIcon(visibility)"
fixed-width
/>
{{ $t('general.scope_in_timeline.' + visibility) }}
</button>
</div>
<div
v-if="status.nsfw"
class="menu-item dropdown-item extra-action -icon"
>
<button
class="main-button"
@click="() => setSensitive(false)"
>
<FAIcon
icon="eye"
fixed-width
/>
{{ $t('status.mark_as_non-sensitive') }}
</button>
</div>
<div
v-else
class="menu-item dropdown-item extra-action -icon"
>
<button
class="main-button"
@click="() => setSensitive(true)"
>
<FAIcon
icon="eye-slash"
fixed-width
/>
{{ $t('status.mark_as_sensitive') }}
</button>
</div>
</div>
<div
v-if="button.name === 'mute'"
:id="`popup-menu-${randomSeed}`"
class="dropdown-menu"
role="menu"
>
<div class="menu-item dropdown-item extra-action -icon">
<button
class="main-button"
@click="toggleUserMute"
>
<FAIcon
icon="user"
fixed-width
/>
<template v-if="userIsMuted">
{{ $t('status.unmute_user') }}
</template>
<template v-else>
{{ $t('status.mute_user') }}
</template>
</button>
</div>
<div class="menu-item dropdown-item extra-action -icon">
<button
class="main-button"
@click="toggleConversationMute"
>
<FAIcon
icon="folder-tree"
fixed-width
/>
<template v-if="conversationIsMuted">
{{ $t('status.unmute_conversation') }}
</template>
<template v-else>
{{ $t('status.mute_conversation') }}
</template>
</button>
</div>
<div class="menu-item dropdown-item extra-action -icon">
<button
class="main-button"
@click="toggleDomainMute"
>
<FAIcon
icon="globe"
fixed-width
/>
<template v-if="domainIsMuted">
{{ $t('status.unmute_domain') }}
</template>
<template v-else>
{{ $t('status.mute_domain') }}
</template>
</button>
</div>
</div>
</template>
</Popover>
<ActionButton
v-else
:button="button"
:status="status"
+ :hide-label="hideLabel"
v-bind="$attrs"
@emoji-picker-shown="e => $emit('emojiPickerShown', e)"
/>
<teleport to="#modal">
<MuteConfirm
ref="confirmConversation"
type="conversation"
:status="status"
:user="user"
/>
<MuteConfirm
ref="confirmDomain"
type="domain"
:status="status"
:user="user"
/>
<UserTimedFilterModal
ref="confirmUser"
:is-mute="true"
:user="user"
/>
</teleport>
</div>
</template>
<script src="./action_button_container.js" />
diff --git a/src/components/status_action_buttons/buttons_definitions.js b/src/components/status_action_buttons/buttons_definitions.js
index d8e4e3cd36..6c94b43a5f 100644
--- a/src/components/status_action_buttons/buttons_definitions.js
+++ b/src/components/status_action_buttons/buttons_definitions.js
@@ -1,317 +1,345 @@
import { useEditStatusStore } from 'src/stores/editStatus.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useReportsStore } from 'src/stores/reports.js'
import { useStatusHistoryStore } from 'src/stores/statusHistory.js'
const PRIVATE_SCOPES = new Set(['private', 'direct'])
const PUBLIC_SCOPES = new Set(['public', 'unlisted'])
export const BUTTONS = [
{
// =========
// REPLY
// =========
name: 'reply',
label: 'tool_tip.reply',
icon: 'reply',
active: ({ replying }) => replying,
counter: ({ status }) => status.replies_count,
anon: true,
anonLink: true,
toggleable: true,
closeIndicator: 'times',
activeIndicator: null,
action({ emit }) {
emit('toggleReplying')
return Promise.resolve()
},
},
{
// =========
// REPEAT
// =========
name: 'retweet',
label: ({ status }) =>
status.repeated ? 'tool_tip.unrepeat' : 'tool_tip.repeat',
icon({ status, currentUser }) {
if (
currentUser.id !== status.user.id &&
PRIVATE_SCOPES.has(status.visibility)
) {
return 'lock'
}
return 'retweet'
},
animated: true,
active: ({ status }) => status.repeated,
counter: ({ status }) => status.repeat_num,
anonLink: true,
interactive: ({ status, currentUser }) =>
!!currentUser &&
(currentUser.id === status.user.id ||
!PRIVATE_SCOPES.has(status.visibility)),
toggleable: true,
confirm: ({ status, getters }) =>
!status.repeated && useMergedConfigStore().mergedConfig.modalOnRepeat,
confirmStrings: {
title: 'status.repeat_confirm_title',
body: 'status.repeat_confirm',
confirm: 'status.repeat_confirm_accept_button',
cancel: 'status.repeat_confirm_cancel_button',
},
action({ status, dispatch }) {
if (!status.repeated) {
return dispatch('retweet', { id: status.id })
} else {
return dispatch('unretweet', { id: status.id })
}
},
},
{
// =========
// FAVORITE
// =========
name: 'favorite',
label: ({ status }) =>
status.favorited ? 'tool_tip.unfavorite' : 'tool_tip.favorite',
icon: ({ status }) =>
status.favorited ? ['fas', 'star'] : ['far', 'star'],
animated: true,
active: ({ status }) => status.favorited,
counter: ({ status }) => status.fave_num,
anonLink: true,
toggleable: true,
action({ status, dispatch }) {
if (!status.favorited) {
return dispatch('favorite', { id: status.id })
} else {
return dispatch('unfavorite', { id: status.id })
}
},
},
{
// =========
// EMOJI REACTIONS
// =========
name: 'emoji',
label: 'tool_tip.add_reaction',
icon: ['far', 'face-smile-beam'],
interactive: () => true,
active: ({ emojiPickerShown }) => emojiPickerShown,
toggleable: true,
anonLink: true,
},
{
// =========
// MUTE
// =========
name: 'mute',
icon: 'eye-slash',
label: 'status.mute_ellipsis',
if: ({ loggedIn }) => loggedIn,
toggleable: false,
dropdown: true,
action({ status, dispatch, emit }) {
/* prevent hiding */
},
},
{
// =========
// PIN STATUS
// =========
name: 'pin',
icon: 'thumbtack',
label: ({ status }) => (status.pinned ? 'status.unpin' : 'status.pin'),
if({ status, loggedIn, currentUser }) {
return (
loggedIn &&
status.user.id === currentUser.id &&
PUBLIC_SCOPES.has(status.visibility)
)
},
action({ status, dispatch }) {
if (status.pinned) {
return dispatch('unpinStatus', status.id)
} else {
return dispatch('pinStatus', status.id)
}
},
},
{
// =========
// BOOKMARK
// =========
name: 'bookmark',
icon: ({ status }) =>
status.bookmarked ? ['fas', 'bookmark'] : ['far', 'bookmark'],
toggleable: true,
active: ({ status }) => status.bookmarked,
label: ({ status }) =>
status.bookmarked ? 'status.unbookmark' : 'status.bookmark',
if: ({ loggedIn }) => loggedIn,
action({ status, dispatch }) {
if (status.bookmarked) {
return dispatch('unbookmark', { id: status.id })
} else {
return dispatch('bookmark', { id: status.id })
}
},
},
{
// =========
// EDIT HISTORY
// =========
name: 'editHistory',
icon: 'history',
label: 'status.status_history',
if({ status, state }) {
return (
useInstanceCapabilitiesStore().editingAvailable &&
status.edited_at !== null
)
},
action({ status }) {
const originalStatus = { ...status }
const stripFieldsList = [
'attachments',
'created_at',
'emojis',
'text',
'raw_html',
'nsfw',
'poll',
'summary',
'summary_raw_html',
]
stripFieldsList.forEach((p) => delete originalStatus[p])
useStatusHistoryStore().openStatusHistoryModal(originalStatus)
return Promise.resolve()
},
},
{
// =========
// EDIT
// =========
name: 'edit',
icon: 'pen',
label: 'status.edit',
if({ status, loggedIn, currentUser, state }) {
return (
loggedIn &&
useInstanceCapabilitiesStore().editingAvailable &&
status.user.id === currentUser.id
)
},
action({ dispatch, status }) {
return dispatch('fetchStatusSource', { id: status.id }).then((data) =>
useEditStatusStore().openEditStatusModal({
statusId: status.id,
- subject: data.spoiler_text,
+ statusSubject: data.spoiler_text,
statusText: data.text,
statusIsSensitive: status.nsfw,
statusPoll: status.poll,
statusFiles: [...status.attachments],
- visibility: status.visibility,
+ statusVisibility: status.visibility,
statusContentType: data.content_type,
}),
)
},
},
+ {
+ // =========
+ // OPEN IN CHAT VIEW
+ // =========
+ name: 'chat_view',
+ icon: 'comments',
+ label: 'status.open_in_chat_view',
+ if({ chatView }) {
+ return !chatView
+ },
+ action({ router, status }) {
+ router.push({ name: 'conversation2', params: { statusId: status.id } })
+ },
+ },
+ {
+ // =========
+ // OPEN IN THREAD VIEW
+ // =========
+ name: 'thread_view',
+ icon: 'list',
+ label: 'status.open_in_thread_view',
+ if({ chatView }) {
+ return chatView
+ },
+ action({ router, status }) {
+ router.push({ name: 'conversation', params: { id: status.id } })
+ },
+ },
{
// =========
// DELETE
// =========
name: 'delete',
icon: 'times',
label: 'status.delete',
if({ status, loggedIn, currentUser }) {
return (
loggedIn &&
(status.user.id === currentUser.id ||
currentUser.privileges.has('messages_delete'))
)
},
confirm: ({ getters }) => useMergedConfigStore().mergedConfig.modalOnDelete,
confirmStrings: {
title: 'status.delete_confirm_title',
body: 'status.delete_confirm',
confirm: 'status.delete_confirm_accept_button',
cancel: 'status.delete_confirm_cancel_button',
},
action({ dispatch, status }) {
return dispatch('deleteStatus', { id: status.id })
},
},
{
// =========
// CHANGE SCOPE
// =========
name: 'changeScope',
icon: 'eye',
label: 'status.admin_change_scope',
if({ status, loggedIn, currentUser }) {
return (
loggedIn &&
(status.user.id === currentUser.id ||
currentUser.privileges.has('messages_delete'))
)
},
toggleable: false,
dropdown: true,
action({ status, dispatch, emit }) {
/* prevent hiding */
},
},
{
// =========
// SHARE/COPY
// =========
name: 'share',
icon: 'share-alt',
label: 'status.copy_link',
action({ state, status, router }) {
navigator.clipboard.writeText(
[
useInstanceStore().server,
router.resolve({ name: 'conversation', params: { id: status.id } })
.href,
].join(''),
)
return Promise.resolve()
},
},
{
// =========
// EXTERNAL
// =========
name: 'external',
icon: 'external-link-alt',
label: 'status.external_source',
link: ({ status }) => status.external_url,
},
{
// =========
// REPORT
// =========
name: 'report',
icon: 'flag',
label: 'user_card.report',
if: ({ loggedIn }) => loggedIn,
action({ status }) {
useReportsStore().openUserReportingModal({
userId: status.user.id,
statusIds: [status.id],
})
return Promise.resolve()
},
},
].map((button) => {
return Object.fromEntries(
Object.entries(button).map(([k, v]) => [
k,
typeof v === 'function' || k === 'name' ? v : () => v,
]),
)
})
diff --git a/src/components/status_action_buttons/status_action_buttons.js b/src/components/status_action_buttons/status_action_buttons.js
index 2341d21c56..73ac6ff7ed 100644
--- a/src/components/status_action_buttons/status_action_buttons.js
+++ b/src/components/status_action_buttons/status_action_buttons.js
@@ -1,158 +1,193 @@
import { mapState } from 'pinia'
import { defineAsyncComponent } from 'vue'
import Popover from 'src/components/popover/popover.vue'
import ActionButtonContainer from './action_button_container.vue'
import { BUTTONS } from './buttons_definitions.js'
import { useSyncConfigStore } from 'src/stores/sync_config.js'
import genRandomSeed from 'src/services/random_seed/random_seed.service.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faEllipsisH } from '@fortawesome/free-solid-svg-icons'
library.add(faEllipsisH)
const StatusActionButtons = {
- props: ['status', 'replying'],
+ props: {
+ status: {
+ type: Object,
+ required: true,
+ },
+ replying: {
+ type: Boolean,
+ default: false,
+ },
+ fixedPinned: {
+ type: Boolean,
+ default: false,
+ },
+ pinned: {
+ type: Set,
+ },
+ useDefaultButtons: {
+ type: Boolean,
+ default: false,
+ },
+ hideLabels: {
+ type: Boolean,
+ default: false,
+ },
+ inChatView: {
+ type: Boolean,
+ default: false,
+ },
+ },
emits: ['toggleReplying', 'onSuccess', 'onError'],
data() {
return {
showPin: false,
showingConfirmDialog: false,
currentConfirmTitle: '',
currentConfirmOkText: '',
currentConfirmCancelText: '',
currentConfirmAction: () => {
/* no-op */
},
randomSeed: genRandomSeed(),
emojiPickerShown: false,
}
},
components: {
Popover,
ConfirmModal: defineAsyncComponent(
() => import('src/components/confirm_modal/confirm_modal.vue'),
),
-
ActionButtonContainer,
},
computed: {
...mapState(useSyncConfigStore, {
- pinnedItems: (store) =>
+ userPinnedItems: (store) =>
new Set(store.prefsStorage.collections.pinnedStatusActions),
}),
+ pinnedItems() {
+ if (this.fixedPinned) {
+ return this.pinned
+ } else {
+ return this.userPinnedItems
+ }
+ },
buttons() {
return BUTTONS.filter((x) => (x.if ? x.if(this.funcArg) : true))
},
quickButtons() {
return this.buttons.filter((x) => this.pinnedItems.has(x.name))
},
extraButtons() {
return this.buttons.filter((x) => !this.pinnedItems.has(x.name))
},
currentUser() {
return this.$store.state.users.currentUser
},
funcArg() {
return {
status: this.status,
replying: this.replying,
emojiPickerShown: this.emojiPickerShown,
emit: this.$emit,
dispatch: this.$store.dispatch,
state: this.$store.state,
getters: this.$store.getters,
router: this.$router,
currentUser: this.currentUser,
loggedIn: !!this.currentUser,
+ chatView: !!this.inChatView,
}
},
triggerAttrs() {
return {
title: this.$t('status.more_actions'),
'aria-controls': `popup-menu-${this.randomSeed}`,
'aria-haspopup': 'menu',
}
},
},
methods: {
doAction(button) {
if (button.confirm?.(this.funcArg)) {
// TODO move to action_button
this.currentConfirmTitle = this.$t(
button.confirmStrings(this.funcArg).title,
)
this.currentConfirmOkText = this.$t(
button.confirmStrings(this.funcArg).confirm,
)
this.currentConfirmCancelText = this.$t(
button.confirmStrings(this.funcArg).cancel,
)
this.currentConfirmBody = this.$t(
button.confirmStrings(this.funcArg).body,
)
this.currentConfirmAction = () => {
this.showingConfirmDialog = false
this.doActionReal(button)
}
this.showingConfirmDialog = true
} else {
this.doActionReal(button)
}
},
doActionReal(button) {
const promise = button.action?.(this.funcArg) ?? Promise.resolve()
promise
.then(() => this.$emit('onSuccess'))
.catch((err) => this.$emit('onError', err))
},
onExtraClose() {
this.showPin = false
},
onEmojiPickerShown(state) {
this.emojiPickerShown = state
},
isPinned(button) {
return this.pinnedItems.has(button.name)
},
unpin(button) {
useSyncConfigStore().removeCollectionPreference({
path: 'collections.pinnedStatusActions',
value: button.name,
})
useSyncConfigStore().pushSyncConfig()
},
pin(button) {
useSyncConfigStore().addCollectionPreference({
path: 'collections.pinnedStatusActions',
value: button.name,
})
useSyncConfigStore().pushSyncConfig()
},
getComponent(button) {
if (!this.$store.state.users.currentUser && button.anonLink) {
return 'a'
} else if (button.action == null && button.link != null) {
return 'a'
} else {
return 'button'
}
},
getClass(button) {
return {
[button.name + '-button']: true,
disabled: button.interactive
? !button.interactive(this.funcArg)
: false,
'-pin-edit': this.showPin,
'-dropdown': button.dropdown?.(),
'-active': button.active?.(this.funcArg),
}
},
},
}
export default StatusActionButtons
diff --git a/src/components/status_action_buttons/status_action_buttons.scss b/src/components/status_action_buttons/status_action_buttons.scss
index db149b4182..b373432032 100644
--- a/src/components/status_action_buttons/status_action_buttons.scss
+++ b/src/components/status_action_buttons/status_action_buttons.scss
@@ -1,29 +1,34 @@
@use "../../mixins";
.StatusActionButtons {
.quick-action-buttons {
display: grid;
margin-left: -0.5em;
grid-template-columns: repeat(auto-fill, minmax(3.75em, 10%));
grid-auto-flow: row dense;
grid-auto-rows: 1fr;
grid-gap: 0.5em 0.1em;
- margin-top: var(--status-margin);
}
.pin-action-button {
display: flex;
z-index: 1;
padding: 0.5em;
margin: 0;
}
+
+ .quick-action.popover-wrapper {
+ button {
+ padding: 0
+ }
+ }
}
// popover
.extra-action-buttons {
.extra-action {
margin: 0;
padding-top: 0;
padding-bottom: 0;
padding-right: 0;
}
}
diff --git a/src/components/status_action_buttons/status_action_buttons.vue b/src/components/status_action_buttons/status_action_buttons.vue
index e0432048a9..34e5e25ea8 100644
--- a/src/components/status_action_buttons/status_action_buttons.vue
+++ b/src/components/status_action_buttons/status_action_buttons.vue
@@ -1,135 +1,140 @@
<template>
<div class="StatusActionButtons">
<span
class="quick-action-buttons"
:class="{ '-pin': showPin }"
>
<span
v-for="button in quickButtons"
:key="button.name"
class="quick-action"
:class="{ '-pin': showPin, '-toggle': button.dropdown?.(), '-with-extra': button.name === 'bookmark' }"
>
<ActionButtonContainer
:class="{ '-pin': showPin }"
:button="button"
:status="status"
:extra="false"
:func-arg="funcArg"
:get-class="getClass"
:get-component="getComponent"
:close="() => { /* no-op */ }"
:do-action="doAction"
@emoji-picker-shown="onEmojiPickerShown"
+ :default-button-style="useDefaultButtons"
+ :hide-label="hideLabels"
/>
<button
v-if="showPin && currentUser"
type="button"
class="button-unstyled pin-action-button"
:title="$t('general.unpin')"
:aria-pressed="true"
@click.stop.prevent="unpin(button)"
>
<FAIcon
v-if="showPin && currentUser"
fixed-width
icon="thumbtack"
/>
</button>
</span>
<Popover
trigger="click"
:trigger-attrs="triggerAttrs"
+ :normal-button="useDefaultButtons"
class="quick-action"
:tabindex="0"
placement="bottom"
:offset="{ y: 5 }"
remove-padding
@close="onExtraClose"
>
<template #trigger>
<FAIcon
class="action-button-inner"
icon="ellipsis-h"
/>
</template>
<template #content="{close, resize}">
<div
:id="`popup-menu-${randomSeed}`"
class="dropdown-menu extra-action-buttons"
role="menu"
>
<div
v-for="button in extraButtons"
:key="button.name"
class="menu-item dropdown-item extra-action -icon"
:disabled="getClass(button).disabled"
:class="{ disabled: getClass(button).disabled }"
>
<ActionButtonContainer
:button="button"
:status="status"
:extra="true"
:func-arg="funcArg"
:get-class="getClass"
:get-component="getComponent"
:outer-close="close"
:do-action="doAction"
+ :default-button-style="useDefaultButtons"
+ :hide-label="hideLabels"
/>
<button
v-if="showPin && currentUser"
type="button"
class="button-unstyled pin-action-button extra-button"
:title="$t('general.pin')"
:aria-pressed="false"
@click.stop.prevent="pin(button)"
>
<FAIcon
v-if="showPin && currentUser"
fixed-width
class="fa-scale-110"
transform="rotate-45"
icon="thumbtack"
/>
</button>
</div>
<div
v-if="currentUser"
class="menu-item dropdown-item extra-action -icon"
>
<button
class="main-button"
role="menuitem"
:tabindex="0"
@click.stop="() => { resize(); showPin = !showPin }"
>
<FAIcon
class="fa-scale-110"
fixed-width
icon="wrench"
/><span>{{ $t('nav.edit_pinned') }}</span>
</button>
</div>
</div>
</template>
</Popover>
</span>
<teleport to="#modal">
<ConfirmModal
v-if="showingConfirmDialog"
:title="currentConfirmTitle"
:confirm-text="currentConfirmOkText"
:cancel-text="currentConfirmCancelText"
@accepted="currentConfirmAction"
@cancelled="showingConfirmDialog = false"
>
{{ currentConfirmBody }}
</ConfirmModal>
</teleport>
</div>
</template>
<script src="./status_action_buttons.js"></script>
<style lang="scss" src="./status_action_buttons.scss"></style>
diff --git a/src/components/status_body/status_body.js b/src/components/status_body/status_body.js
index e6752cb1af..c76e04b9c0 100644
--- a/src/components/status_body/status_body.js
+++ b/src/components/status_body/status_body.js
@@ -1,190 +1,200 @@
import { mapState } from 'pinia'
+import RichContent from 'src/components/rich_content/rich_content.jsx'
+
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faFile,
faImage,
faLink,
faMusic,
faPollH,
} from '@fortawesome/free-solid-svg-icons'
library.add(faFile, faMusic, faImage, faLink, faPollH)
const StatusBody = {
name: 'StatusBody',
+ components: {
+ RichContent,
+ },
props: {
status: {
// Main thing
type: Object,
required: true,
},
compact: {
// Resizes emoji and minimizes vertical space used
// Primarily used for showing status in react notifications
type: Boolean,
default: false,
},
collapse: {
// replaces newlines with spaces
type: Boolean,
default: false,
},
singleLine: {
// Show entire thing (subject and content) in a single line
// Primarily used in chats
type: Boolean,
default: false,
},
inConversation: {
// Is status rendered within open conversation?
// Used to automatically expand subjects (if collapsed)
type: Boolean,
default: false,
},
+ ignoreSubject: {
+ // Pretend subject line doesn't exist. Useful for chat messages
+ // to indicate what post reply belongs to
+ type: Boolean,
+ default: false,
+ },
},
data() {
return {
postLength: this.status.text.length,
parseReadyDone: false,
showingTall: false,
showingLongSubject: false,
expandingSubject: null,
}
},
emits: ['parseReady'],
computed: {
allowNonSquareEmoji() {
return this.mergedConfig.nonSquareEmoji
},
pauseMfm() {
return this.mergedConfig.pauseMfm
},
scaleMfm() {
return this.mergedConfig.scaleMfm
},
// This is a bit hacky, but we want to approximate post height before rendering
// so we count newlines (masto uses <p> for paragraphs, GS uses <br> between them)
// as well as approximate line count by counting characters and approximating ~80
// per line.
//
// Using max-height + overflow: auto for status components resulted in false positives
// very often with japanese characters, and it was very annoying.
hasLongSubject() {
return this.status.summary.length > 240
},
hasSubject() {
- return !!this.status.summary
+ return !!this.status.summary && !this.ignoreSubject
},
// When a status has a subject and is also tall, we should only have one show more/less
// button. If the default is to collapse statuses with subjects, we just treat it like
// a status with a subject; otherwise, we just treat it like a tall status.
mightHideBecauseSubject() {
return (
!this.inConversation &&
this.hasSubject &&
this.mergedConfig.collapseMessageWithSubject
)
},
mightHideBecauseTall() {
if (this.singleLine || this.compact) return false
const lengthScore =
this.status.raw_html.split(/<p|<br/).length + this.postLength / 80
return lengthScore > 20
},
hideSubjectStatus() {
return this.mightHideBecauseSubject && !this.expandingSubject
},
hideTallStatus() {
return this.mightHideBecauseTall && !this.showingTall
},
shouldShowExpandToggle() {
return this.mightHideBecauseSubject || this.mightHideBecauseTall
},
toggleButtonClasses() {
return {
'cw-status-hider': !this.showingMore && this.mightHideBecauseSubject,
'tall-status-hider': !this.showingMore && this.mightHideBecauseTall,
'status-unhider': this.showingMore,
}
},
toggleText() {
if (this.showingMore) {
return this.mightHideBecauseSubject
? this.$t('status.hide_content')
: this.$t('general.show_less')
} else {
return this.mightHideBecauseSubject
? this.$t('status.show_content')
: this.$t('general.show_more')
}
},
shouldHide() {
return (
!this.showingMore && this.mightHideBecauseSubject && this.hasSubject
)
},
showingMore() {
return (
(this.mightHideBecauseTall && this.showingTall) ||
(this.mightHideBecauseSubject && this.expandingSubject)
)
},
attachmentTypes() {
return this.status.attachments.map((file) => file.type)
},
collapsedStatus() {
return this.status.raw_html.replace(/(\n|<br\s?\/?>)/g, ' ')
},
...mapState(useMergedConfigStore, ['mergedConfig']),
},
- components: {},
mounted() {
this.status.attentions &&
this.status.attentions.forEach((attn) => {
const { id } = attn
this.$store.dispatch('fetchUserIfMissing', id)
})
},
methods: {
onParseReady(event) {
if (this.parseReadyDone) return
this.parseReadyDone = true
this.$emit('parseReady', event)
const { writtenMentions, invisibleMentions } = event
writtenMentions
.filter((mention) => !mention.notifying)
.forEach((mention) => {
const { content, url } = mention
const cleanedString = content.replace(/<[^>]+?>/gi, '') // remove all tags
if (!cleanedString.startsWith('@')) return
const handle = cleanedString.slice(1)
const host = url.replace(/^https?:\/\//, '').replace(/\/.+?$/, '')
this.$store.dispatch('fetchUserIfMissing', `${handle}@${host}`)
})
/* This is a bit of a hack to make current tall status detector work
* with rich mentions. Invisible mentions are detected at RichContent level
* and also we generate plaintext version of mentions by stripping tags
* so here we subtract from post length by each mention that became invisible
* via MentionsLine
*/
this.postLength = invisibleMentions.reduce((acc, mention) => {
return acc - mention.textContent.length - 1
}, this.postLength)
},
toggleShowMore() {
if (this.mightHideBecauseTall) {
this.showingTall = !this.showingTall
} else if (this.mightHideBecauseSubject) {
this.expandingSubject = !this.expandingSubject
}
},
generateTagLink(tag) {
return `/tag/${tag}`
},
},
}
export default StatusBody
diff --git a/src/components/status_body/status_body.scss b/src/components/status_body/status_body.scss
index 9954663e78..46299533a0 100644
--- a/src/components/status_body/status_body.scss
+++ b/src/components/status_body/status_body.scss
@@ -1,196 +1,213 @@
.StatusBody {
display: flex;
flex-direction: column;
.emoji {
--_still_image-label-scale: 0.5;
}
.attachments {
margin-top: 0.5em;
}
& .text,
& .summary {
white-space: pre-wrap;
overflow-wrap: break-word;
text-wrap: pretty;
line-height: var(--post-line-height);
}
.summary {
display: block;
font-style: italic;
padding-bottom: 0.5em;
}
.text {
&.-single-line {
- white-space: nowrap;
+ white-space-collapse: collapse;
text-overflow: ellipsis;
overflow: hidden;
height: 1.4em;
}
}
.summary-wrapper {
margin-bottom: 0.5em;
border-style: solid;
border-width: 0 0 1px;
border-color: var(--border);
flex-grow: 0;
&.-tall {
position: relative;
.summary {
max-height: 2em;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
}
.text-wrapper {
position: relative;
text-overflow: ellipsis;
overflow-wrap: break-word;
overflow: hidden;
display: flex;
flex-flow: column nowrap;
&.-tall-status {
z-index: 1;
&:not(.-hidden) {
height: 16em;
}
.media-body {
min-height: 0;
mask:
linear-gradient(to top, white, transparent) bottom/100% 8em no-repeat,
linear-gradient(to top, white, white);
/* Autoprefixed seem to ignore this one, and also syntax is different */
/* stylelint-disable mask-composite */
/* stylelint-disable declaration-property-value-no-unknown */
/* stylelint-disable scss/declaration-property-value-no-unknown */
/* TODO check if this is still needed */
mask-composite: xor;
/* stylelint-enable scss/declaration-property-value-no-unknown */
/* stylelint-enable declaration-property-value-no-unknown */
/* stylelint-enable mask-composite */
mask-composite: exclude;
}
}
&.-expanded {
overflow: visible;
}
}
+ &.-single-line {
+ .summary-wrapper {
+ display: inline-block;
+ margin: 0;
+ padding: 0;
+ border: none;
+
+ .summary {
+ padding: 0;
+ }
+ }
+
+ .text-wrapper {
+ display: inline-flex;
+ }
+ }
+
& .tall-status-hider,
& .tall-subject-hider,
& .status-unhider,
& .cw-status-hider {
display: inline-block;
overflow-wrap: break-word;
text-wrap: pretty;
width: 100%;
text-align: center;
margin: 0.1em 0;
}
.status-unhider {
margin-top: auto;
position: sticky;
bottom: 0;
padding-bottom: 1em;
}
.tall-subject-hider {
// position: absolute;
padding-bottom: 0.5em;
&:not(.cw-status-hider) {
position: absolute;
margin-top: 10em;
height: 5em;
line-height: 8em;
z-index: 2;
}
}
& .status-unhider,
& .cw-status-hider {
overflow-wrap: break-word;
text-wrap: pretty;
svg {
color: inherit;
}
}
.toggle-button {
padding: 0.5em;
}
&.-compact {
align-items: start;
flex-direction: row;
& .body,
& .attachments {
max-height: 3.25em;
}
.body {
overflow: hidden;
white-space: normal;
min-width: 5em;
flex: 5 1 auto;
mask-size: auto 3.5em, auto auto;
mask-position: 0 0, 0 0;
mask-repeat: repeat-x, repeat;
mask-image: linear-gradient(to bottom, white 2em, transparent 3em);
/* Autoprefixed seem to ignore this one, and also syntax is different */
/* stylelint-disable mask-composite */
/* stylelint-disable declaration-property-value-no-unknown */
/* stylelint-disable scss/declaration-property-value-no-unknown */
/* TODO check if this is still needed */
mask-composite: xor;
/* stylelint-enable scss/declaration-property-value-no-unknown */
/* stylelint-enable declaration-property-value-no-unknown */
/* stylelint-enable mask-composite */
mask-composite: exclude;
}
.attachments {
margin-top: 0;
flex: 1 1 0;
min-width: 5em;
height: 100%;
margin-left: 0.5em;
}
.summary-wrapper {
.summary::after {
content: ": ";
}
line-height: inherit;
margin: 0;
border: none;
}
.text-wrapper {
display: inline-block;
width: 100%;
}
}
}
diff --git a/src/components/status_body/status_body.vue b/src/components/status_body/status_body.vue
index e8994180aa..c662a0aa75 100644
--- a/src/components/status_body/status_body.vue
+++ b/src/components/status_body/status_body.vue
@@ -1,76 +1,76 @@
<template>
<div
class="StatusBody"
- :class="{ '-compact': compact }"
+ :class="{ '-compact': compact, '-single-line': singleLine }"
>
<div class="body">
<div
v-if="hasSubject"
class="summary-wrapper"
:class="{ '-tall': (hasLongSubject && !showingLongSubject) }"
>
<RichContent
class="media-body summary"
:faint="compact"
:html="status.summary_raw_html"
:emoji="status.emojis"
:is-local="status.isLocal"
:allow-non-square-emoji="allowNonSquareEmoji"
:pause-mfm="pauseMfm"
:scale-mfm="scaleMfm"
/>
<button
v-show="hasLongSubject && showingLongSubject"
class="button-unstyled -link tall-subject-hider"
@click.prevent="toggleShowingLongSubject"
>
{{ $t("status.hide_full_subject") }}
</button>
<button
v-show="hasLongSubject && !showingLongSubject"
class="button-unstyled -link tall-subject-hider"
@click.prevent="toggleShowingLongSubject"
>
{{ $t("status.show_full_subject") }}
</button>
</div>
<div
class="text-wrapper"
- :class="{'-tall-status': hideTallStatus, '-hidden': shouldHide, '-expanded': showingMore}"
+ :class="{'-tall-status': hideTallStatus, '-hidden': shouldHide, '-expanded': showingMore }"
>
<RichContent
v-if="!(singleLine && hasSubject) && !shouldHide"
:class="{ '-single-line': singleLine }"
class="text media-body"
:html="status.raw_html"
:collapse="collapse"
:emoji="status.emojis"
:handle-links="true"
:faint="compact"
:greentext="mergedConfig.greentext"
:attentions="status.attentions"
:is-local="status.is_local"
:allow-non-square-emoji="allowNonSquareEmoji"
:pause-mfm="pauseMfm"
:scale-mfm="scaleMfm"
@parse-ready="onParseReady"
/>
<div
v-show="shouldShowExpandToggle"
:class="toggleButtonClasses"
>
<button
class="btn button-default toggle-button"
:aria-expanded="showingMore"
@click.prevent="toggleShowMore"
>
{{ toggleText }}
</button>
</div>
</div>
</div>
<slot v-if="!hideSubjectStatus" />
</div>
</template>
<script src="./status_body.js"></script>
<style lang="scss" src="./status_body.scss" />
diff --git a/src/components/user_card/user_card.js b/src/components/user_card/user_card.js
index 7c5b2a454d..9f6488b34d 100644
--- a/src/components/user_card/user_card.js
+++ b/src/components/user_card/user_card.js
@@ -1,626 +1,625 @@
import {
isEqual,
escape as ldEscape,
unescape as ldUnescape,
merge,
} from 'lodash'
import { mapState } from 'pinia'
import { defineAsyncComponent } from 'vue'
import Checkbox from 'src/components/checkbox/checkbox.vue'
import ColorInput from 'src/components/color_input/color_input.vue'
import EmojiInput from 'src/components/emoji_input/emoji_input.vue'
import suggestor from 'src/components/emoji_input/suggestor.js'
import FollowButton from 'src/components/follow_button/follow_button.vue'
import ProgressButton from 'src/components/progress_button/progress_button.vue'
import Select from 'src/components/select/select.vue'
import UserAvatar from 'src/components/user_avatar/user_avatar.vue'
import UserLink from 'src/components/user_link/user_link.vue'
import { useEmojiStore } from 'src/stores/emoji.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
import { useInterfaceStore } from 'src/stores/interface'
import { useMediaViewerStore } from 'src/stores/media_viewer'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { usePostStatusStore } from 'src/stores/post_status'
import { useUserHighlightStore } from 'src/stores/user_highlight.js'
import { updateProfile } from 'src/api/user.js'
import { propsToNative } from 'src/services/attributes_helper/attributes_helper.service.js'
import localeService from 'src/services/locale/locale.service.js'
import generateProfileLink from 'src/services/user_profile_link_generator/user_profile_link_generator'
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faBell,
faBirthdayCake,
faClockRotateLeft,
faEdit,
faExpandAlt,
faExternalLinkAlt,
faRss,
faSave,
faSearchPlus,
faTimes,
} from '@fortawesome/free-solid-svg-icons'
library.add(
faSave,
faRss,
faBell,
faSearchPlus,
faExternalLinkAlt,
faEdit,
faTimes,
faExpandAlt,
faBirthdayCake,
faClockRotateLeft,
)
const KNOWN_TAGS = new Set([
'mrf_tag:media-force-nsfw',
'mrf_tag:media-strip',
'mrf_tag:force-unlisted',
'mrf_tag:sandbox',
'mrf_tag:disable-remote-subscription',
'mrf_tag:disable-any-subscription',
])
export default {
props: {
// Enables all the options for profile editing, used in settings -> profile tab
editable: {
required: false,
default: false,
type: Boolean,
},
// ID of user to show data of
userId: {
required: true,
type: String,
},
// Use a compact layout that hides bio, stats etc.
hideBio: {
required: false,
default: false,
type: Boolean,
},
// Hide action buttons
hideButtons: {
required: false,
default: false,
type: Boolean,
},
// default - open profile, 'zoom' - zoom, function - call function
avatarAction: {
required: false,
type: String,
default: 'default',
},
// Show note editor if supported
hasNoteEditor: {
required: false,
type: Boolean,
default: false,
},
// Show close icon (for popovers)
showClose: {
required: false,
type: Boolean,
default: false,
},
// Show close icon (for popovers)
showExpand: {
required: false,
type: Boolean,
default: false,
},
// Disable forced 3:1 aspect ratio
compact: {
required: false,
type: Boolean,
default: false,
},
},
components: {
DialogModal: defineAsyncComponent(
() => import('src/components/dialog_modal/dialog_modal.vue'),
),
UserAvatar,
Checkbox,
RemoteFollow: defineAsyncComponent(
() => import('src/components/remote_follow/remote_follow.vue'),
),
ModerationTools: defineAsyncComponent(
() => import('src/components/moderation_tools/moderation_tools.vue'),
),
AccountActions: defineAsyncComponent(
() => import('src/components/account_actions/account_actions.vue'),
),
ProgressButton,
FollowButton,
Select,
UserLink,
UserNote: defineAsyncComponent(
() => import('src/components/user_note/user_note.vue'),
),
UserTimedFilterModal: defineAsyncComponent(
() =>
import(
'src/components/user_timed_filter_modal/user_timed_filter_modal.vue'
),
),
ColorInput,
EmojiInput,
ImageCropper: defineAsyncComponent(
() => import('src/components/image_cropper/image_cropper.vue'),
),
},
data() {
const user = this.$store.getters.findUser(this.userId)
return {
followRequestInProgress: false,
// Editable stuff
editImage: false,
newName: user.name_unescaped,
editingName: false,
newBio: ldUnescape(user.description),
editingBio: false,
newAvatar: null,
newAvatarFile: null,
newBanner: null,
newBannerFile: null,
newActorType: user.actor_type,
newBirthday: user.birthday,
newShowBirthday: user.show_birthday,
newShowRole: user.show_role,
newFields: user.fields?.map((field) => ({
name: field.name,
value: field.value,
})),
editingFields: false,
}
},
created() {
this.$store.dispatch('fetchUserRelationship', this.user.id)
},
computed: {
escapedNewBio() {
return ldEscape(this.newBio).replace(/\n/g, '<br>')
},
somethingToSave() {
if (this.newName !== this.user.name_unescaped) return true
if (this.newBio !== ldUnescape(this.user.description)) return true
if (this.newAvatar !== null) return true
if (this.newBanner !== null) return true
if (this.newActorType !== this.user.actor_type) return true
if (this.newBirthday !== this.user.birthday) return true
if (this.newShowBirthday !== this.user.show_birthday) return true
if (this.newShowRole !== this.user.show_role) return true
if (
!isEqual(
this.newFields,
this.user.fields?.map((field) => ({
name: field.name,
value: field.value,
})),
)
)
return true
return false
},
groupActorAvailable() {
return useInstanceCapabilitiesStore().groupActorAvailable
},
availableActorTypes() {
return this.groupActorAvailable
? ['Person', 'Service', 'Group']
: ['Person', 'Service']
},
user() {
return this.$store.getters.findUser(this.userId)
},
role() {
return this.user.role
},
relationship() {
return this.$store.getters.relationship(this.userId)
},
isOtherUser() {
return this.user.id !== this.$store.state.users.currentUser.id
},
subscribeUrl() {
const serverUrl = new URL(this.user.statusnet_profile_url)
return `${serverUrl.protocol}//${serverUrl.host}/main/ostatus`
},
loggedIn() {
return this.$store.state.users.currentUser
},
dailyAvg() {
const days = Math.ceil(
(new Date() - new Date(this.user.created_at)) / (60 * 60 * 24 * 1000),
)
return Math.round(this.user.statuses_count / days)
},
emoji() {
return useEmojiStore().customEmoji.map((e) => ({
shortcode: e.displayText,
static_url: e.imageUrl,
url: e.imageUrl,
}))
},
userHighlightType: {
get() {
return useUserHighlightStore().get(this.user.screen_name).type
},
set(type) {
if (type !== 'disabled') {
useUserHighlightStore().setAndSave({
user: this.user.screen_name,
value: { type },
})
} else {
useUserHighlightStore().unsetAndSave({ user: this.user.screen_name })
}
},
},
userHighlightColor: {
get() {
return useUserHighlightStore().get(this.user.screen_name).color
},
set(color) {
useUserHighlightStore().setAndSave({
user: this.user.screen_name,
value: { color },
})
},
},
visibleRole() {
if (!this.user.show_role && !this.user.adminData) {
return
}
const rights = this.user.rights
if (!rights) {
return
}
const validRole = rights.admin || rights.moderator
const roleTitle = rights.admin ? 'admin' : 'moderator'
return validRole && roleTitle
},
hideFollowsCount() {
return this.isOtherUser && this.user.hide_follows_count
},
hideFollowersCount() {
return this.isOtherUser && this.user.hide_followers_count
},
showModerationMenu() {
const privileges = this.loggedIn.privileges
return (
this.loggedIn.role === 'admin' ||
privileges.has('users_manage_activation_state') ||
privileges.has('users_delete') ||
privileges.has('users_manage_tags')
)
},
hasNote() {
return this.relationship.note
},
supportsNote() {
return 'note' in this.relationship
},
muteExpiryAvailable() {
return Object.hasOwn(this.user, 'mute_expires_at')
},
muteExpiry() {
return this.user.mute_expires_at === false
? this.$t('user_card.mute_expires_forever')
: this.$t('user_card.mute_expires_at', [
new Date(this.user.mute_expires_at).toLocaleString(),
])
},
blockExpiryAvailable() {
return Object.hasOwn(this.user, 'block_expires_at')
},
blockExpiry() {
return this.user.block_expires_at == null
? this.$t('user_card.block_expires_forever')
: this.$t('user_card.block_expires_at', [
new Date(this.user.mute_expires_at).toLocaleString(),
])
},
formattedBirthday() {
const browserLocale = localeService.internalToBrowserLocale(
this.$i18n.locale,
)
return (
this.user.birthday &&
new Date(Date.parse(this.user.birthday)).toLocaleDateString(
browserLocale,
{ timeZone: 'UTC', day: 'numeric', month: 'long', year: 'numeric' },
)
)
},
formattedJoinDate() {
const browserLocale = localeService.internalToBrowserLocale(
this.$i18n.locale,
)
return (
this.user.created_at &&
new Date(Date.parse(this.user.created_at)).toLocaleDateString(
browserLocale,
{ timeZone: 'UTC', day: 'numeric', month: 'long', year: 'numeric' },
)
)
},
// Editable stuff
avatarImgSrc() {
const currentUrl =
this.user.profile_image_url_original || this.defaultAvatar
if (!this.editable) return currentUrl
const newUrl =
this.newAvatar === null ? this.defaultAvatar : this.newAvatar
return this.newAvatar === null ? currentUrl : newUrl
},
bannerImgSrc() {
const currentUrl = this.user.cover_photo || this.defaultBanner
if (!this.editable) return currentUrl
const newUrl =
this.newBanner === null ? this.defaultBanner : this.newBanner
return this.newBanner === null ? currentUrl : newUrl
},
defaultAvatar() {
return (
useInstanceStore().server +
useInstanceStore().instanceIdentity.defaultAvatar
)
},
defaultBanner() {
return (
useInstanceStore().server +
useInstanceStore().instanceIdentity.defaultBanner
)
},
isDefaultAvatar() {
const baseAvatar = useInstanceStore().instanceIdenitity.defaultAvatar
return (
!this.$store.state.users.currentUser.profile_image_url ||
this.$store.state.users.currentUser.profile_image_url.includes(
baseAvatar,
)
)
},
isDefaultBanner() {
const baseBanner = useInstanceStore().instanceIdentity.defaultBanner
return (
!this.$store.state.users.currentUser.cover_photo ||
this.$store.state.users.currentUser.cover_photo.includes(baseBanner)
)
},
fieldsLimits() {
return useInstanceStore().limits.fieldsLimits
},
maxFields() {
return this.fieldsLimits ? this.fieldsLimits.maxFields : 0
},
emojiUserSuggestor() {
return suggestor({
emoji: [
...useEmojiStore().standardEmojiList,
...useEmojiStore().customEmoji,
],
store: this.$store,
})
},
emojiSuggestor() {
return suggestor({
emoji: [
...useEmojiStore().standardEmojiList,
...useEmojiStore().customEmoji,
],
})
},
allowNonSquareEmoji() {
return this.mergedConfig.nonSquareEmoji
},
pauseMfm() {
return this.mergedConfig.pauseMfm
},
scaleMfm() {
return this.mergedConfig.scaleMfm
},
hideUserStats() {
return this.mergedConfig.hideUserStats
},
hideRemarks() {
return this.mergedConfig.userCardHidePersonalMarks
},
...mapState(useMergedConfigStore, ['mergedConfig']),
},
methods: {
isKnownTag(tag) {
return KNOWN_TAGS.has(tag)
},
muteUser() {
this.$refs.timedMuteDialog.optionallyPrompt()
},
unmuteUser() {
this.$store.dispatch('unmuteUser', this.user.id)
},
subscribeUser() {
return this.$store.dispatch('subscribeUser', this.user.id)
},
unsubscribeUser() {
return this.$store.dispatch('unsubscribeUser', this.user.id)
},
linkClicked({ target }) {
if (target.tagName === 'SPAN') {
target = target.parentNode
}
if (target.tagName === 'A') {
window.open(target.href, '_blank')
}
},
userProfileLink(user) {
return generateProfileLink(
user.id,
user.screen_name,
useInstanceStore().restrictedNicknames,
)
},
openProfileTab() {
useInterfaceStore().openSettingsModalTab('profile')
},
zoomAvatar() {
const attachment = {
url: this.user.profile_image_url_original,
type: 'image',
}
useMediaViewerStore().setMedia([attachment])
useMediaViewerStore().setCurrentMedia(attachment)
},
mentionUser() {
usePostStatusStore().openPostStatusModal({
- profileMention: true,
- repliedUser: this.user,
+ profileMention: this.user,
})
},
onAvatarClickHandler(e) {
if (this.onAvatarClick) {
e.preventDefault()
this.onAvatarClick()
}
},
// Editable stuff
changeAvatar() {
this.editImage = 'avatar'
},
changeBanner() {
this.editImage = 'banner'
},
submitImage({ canvas, file }) {
if (canvas) {
return canvas.toBlob((data) =>
this.submitImage({ canvas: null, file: data }),
)
}
const reader = new window.FileReader()
reader.onload = (e) => {
const dataUrl = e.target.result
if (this.editImage === 'avatar') {
this.newAvatar = dataUrl
this.newAvatarFile = file
} else {
this.newBanner = dataUrl
this.newBannerFile = file
}
this.editImage = false
}
reader.readAsDataURL(file)
},
resetImage() {
if (this.editImage === 'avatar') {
this.newAvatar = null
this.newAvatarFile = null
} else {
this.newBanner = null
this.newBannerFile = null
}
this.editImage = false
},
addField() {
if (this.newFields.length < this.maxFields) {
this.newFields.push({ name: '', value: '' })
}
},
deleteField(index) {
this.newFields.splice(index, 1)
},
propsToNative(props) {
return propsToNative(props)
},
cancelImageText() {
return
},
resetState() {
const user = this.$store.state.users.currentUser
this.newName = user.name_unescaped
this.newBio = ldUnescape(user.description)
this.newAvatar = null
this.newAvatarFile = null
this.newBanner = null
this.newBannerFile = null
this.newActorType = user.actor_type
this.newBirthday = user.birthday
this.newShowBirthday = user.show_birthday
this.newShowRole = user.show_role
this.newFields = user.fields.map((field) => ({
name: field.name,
value: field.value,
}))
},
updateProfile() {
const params = {
note: this.newBio,
// Backend notation.
display_name: this.newName,
fields_attributes: this.newFields.filter((el) => el != null),
show_role: !!this.newShowRole,
birthday: this.newBirthday || '',
show_birthday: !!this.newShowBirthday,
}
if (this.newActorType) {
params.actor_type = this.newActorType
}
if (this.newAvatarFile !== null) {
params.avatar = this.newAvatarFile
}
if (this.newBannerFile !== null) {
params.header = this.newBannerFile
}
updateProfile({ params })
.then(({ data: user }) => {
this.newFields.splice(this.newFields.length)
merge(this.newFields, user.fields)
this.$store.commit('addNewUsers', [user])
this.$store.commit('setCurrentUser', user)
this.resetState()
})
.catch((error) => {
this.displayUploadError(error)
})
},
displayUploadError(error) {
useInterfaceStore().pushGlobalNotice({
messageKey: 'upload.error.message',
messageArgs: [error.message],
level: 'error',
})
},
},
}
diff --git a/src/components/user_panel/user_panel.vue b/src/components/user_panel/user_panel.vue
index b0479321c2..0f9260c4a9 100644
--- a/src/components/user_panel/user_panel.vue
+++ b/src/components/user_panel/user_panel.vue
@@ -1,51 +1,49 @@
<template>
<aside class="user-panel">
<div
v-if="signedIn"
key="user-panel-signed"
class="panel panel-default signed-in"
>
<UserCard
:user-id="user.id"
:hide-bio="true"
/>
<PostStatusForm />
</div>
<AuthForm
v-else
key="user-panel"
/>
</aside>
</template>
<script src="./user_panel.js"></script>
<style lang="scss">
.user-panel {
.panel {
background: var(--background);
backdrop-filter: var(--backdrop-filter);
}
.user-info {
margin: 0.6em 0.6em 0;
.Avatar {
width: 5em;
width: calc(min(5em, 20cqw));
height: 5em;
height: calc(min(5em, 20cqw));
}
}
.post-status-form {
- form {
- margin-top: 0;
- }
+ margin: 0.5em;
}
.signed-in {
z-index: 10;
}
}
</style>
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 644e082a10..60fcaf1dd4 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -1,2075 +1,2084 @@
{
"about": {
"mrf": {
"federation": "Federation",
"keyword": {
"keyword_policies": "Keyword policies",
"ftl_removal": "Removal from \"The Whole Known Network\" Timeline",
"reject": "Reject",
"replace": "Replace",
"is_replaced_by": "→"
},
"mrf_policies": "Enabled MRF policies",
"mrf_policies_desc": "MRF policies manipulate the federation behaviour of the instance. The following policies are enabled:",
"simple": {
"simple_policies": "Instance-specific policies",
"instance": "Instance",
"reason": "Reason",
"not_applicable": "N/A",
"accept": "Accept",
"accept_desc": "This instance only accepts messages from the following instances:",
"reject": "Reject",
"reject_desc": "This instance will not accept messages from the following instances:",
"quarantine": "Quarantine",
"quarantine_desc": "This instance will send only public posts to the following instances:",
"ftl_removal": "Removal from \"Known Network\" Timeline",
"ftl_removal_desc": "This instance removes these instances from \"Known Network\" timeline:",
"media_removal": "Media Removal",
"media_removal_desc": "This instance removes media from posts on the following instances:",
"media_nsfw": "Media force-set as sensitive",
"media_nsfw_desc": "This instance forces media to be set sensitive in posts on the following instances:"
}
},
"staff": "Staff",
"terms": "Terms of Service"
},
"announcements": {
"page_header": "Announcements",
"title": "Announcement",
"mark_as_read_action": "Mark as read",
"post_form_header": "Post announcement",
"post_placeholder": "Type your announcement content here...",
"post_action": "Post",
"post_error": "Error: {error}",
"close_error": "Close",
"delete_action": "Delete",
"start_time_prompt": "Start time: ",
"end_time_prompt": "End time: ",
"all_day_prompt": "This is an all-day event",
"published_time_display": "Published at {time}",
"start_time_display": "Starts at {time}",
"end_time_display": "Ends at {time}",
"edit_action": "Edit",
"submit_edit_action": "Submit",
"cancel_edit_action": "Cancel",
"inactive_message": "This announcement is inactive"
},
"shoutbox": {
"title": "Shoutbox"
},
"domain_mute_card": {
"mute": "Mute",
"mute_progress": "Muting…",
"unmute": "Unmute",
"unmute_progress": "Unmuting…"
},
"exporter": {
"export": "Export",
"processing": "Processing, you'll soon be asked to download your file"
},
"features_panel": {
"shout": "Shoutbox",
"pleroma_chat_messages": "Pleroma Chat",
"gopher": "Gopher",
"media_proxy": "Media proxy",
"scope_options": "Scope options",
"text_limit": "Text limit",
"title": "Features",
"who_to_follow": "Who to follow",
"upload_limit": "Upload limit"
},
"finder": {
"error_fetching_user": "Error fetching user",
"find_user": "Find user"
},
"general": {
"apply": "Apply",
"submit": "Submit",
"more": "More",
"no_more": "No more items",
"loading": "Loading…",
"generic_error": "An error occured",
"generic_error_message": "An error occured: {0}",
"generic_error_details": "Technical info:",
"error_retry": "Please try again",
"refresh_required": "Refresh required",
"refresh_required_content": "Failed to load UI code. Most likely frontend was updated on server, you'll need to refresh the page.",
"refresh_required_refresh": "Refresh page",
"retry": "Try again",
"optional": "optional",
"show_more": "Show more",
"show_less": "Show less",
"never_show_again": "Never show again",
"dismiss": "Dismiss",
"cancel": "Cancel",
"disable": "Disable",
"enable": "Enable",
"confirm": "Confirm",
"verify": "Verify",
"close": "Close",
"undo": "Undo",
"yes": "Yes",
"no": "No",
"none": "None",
"not_applicable": "N/A",
"not_available": "N/A",
"peek": "Peek",
"scroll_to_top": "Scroll to top",
"role": {
"admin": "Admin",
"moderator": "Moderator"
},
"unpin": "Unpin item",
"pin": "Pin item",
"flash_content": "Click to show Flash content using Ruffle (Experimental, may not work).",
"flash_security": "Note that this can be potentially dangerous since Flash content is still arbitrary code.",
"flash_fail": "Failed to load flash content, see console for details.",
"scope_in_timeline": {
"local": "Non-federated",
"direct": "Direct",
"private": "Followers-only",
"public": "Public",
"unlisted": "Unlisted"
}
},
"image_cropper": {
"crop_picture": "Crop picture",
"save": "Save",
"save_without_cropping": "Save without cropping",
"cancel": "Cancel"
},
"importer": {
"submit": "Submit",
"import": "Import",
"success": "Imported successfully.",
"error": "An error occured while importing this file."
},
"login": {
"login": "Log in",
"description": "Log in with OAuth",
"logout": "Log out",
"logout_confirm_title": "Logout confirmation",
"logout_confirm": "Do you really want to logout?",
"logout_confirm_accept_button": "Logout",
"logout_confirm_cancel_button": "Do not logout",
"password": "Password",
"placeholder": "e.g. lain",
"register": "Register",
"username": "Username",
"hint": "Log in to join the discussion",
"authentication_code": "Authentication code",
"enter_recovery_code": "Enter a recovery code",
"enter_two_factor_code": "Enter a two-factor code",
"recovery_code": "Recovery code",
"heading": {
"totp": "Two-factor authentication",
"recovery": "Two-factor recovery"
}
},
"media_modal": {
"previous": "Previous",
"next": "Next",
"counter": "{current} / {total}",
"hide": "Close media viewer"
},
"nav": {
"about": "About",
"administration": "Administration",
"back": "Back",
"friend_requests": "Follow requests",
"mentions": "Mentions",
"interactions": "Interactions",
"dms": "Direct messages",
"public_tl": "Public timeline",
"bubble": "Bubble timeline",
"timeline": "Timeline",
"home_timeline": "Home timeline",
"twkn": "Known Network",
"bookmarks": "Bookmarks",
"all_bookmarks": "All bookmarks",
"bookmark_folders": "Bookmark folders",
"user_search": "User Search",
"search": "Search",
"search_close": "Close search bar",
"who_to_follow": "Who to follow",
"preferences": "Preferences",
"timelines": "Timelines",
"chats": "Chats",
"lists": "Lists",
"edit_nav_mobile": "Customize navigation bar",
"edit_pinned": "Edit pinned items",
"edit_finish": "Done editing",
"mobile_sidebar": "Toggle mobile sidebar",
"mobile_notifications": "Open notifications (there are unread ones)",
"mobile_notifications_close": "Close notifications",
"mobile_notifications_mark_as_seen": "Mark all as seen",
"announcements": "Announcements",
"quotes": "Quotes",
"drafts": "Drafts"
},
"notifications": {
"broken_favorite": "Unknown status, searching for it…",
"error": "Error fetching notifications: {0}",
"favorited_you": "favorited your status",
"followed_you": "followed you",
"follow_request": "wants to follow you",
"load_older": "Load older notifications",
"notifications": "Notifications",
"read": "Read!",
"repeated_you": "repeated your status",
"no_more_notifications": "No more notifications",
"migrated_to": "migrated to",
"reacted_with": "reacted with {0}",
"submitted_report": "submitted a report",
"poll_ended": "poll has ended",
"unread_announcements": "{num} unread announcement | {num} unread announcements",
"unread_chats": "{num} unread chat | {num} unread chats",
"unread_follow_requests": "{num} new follow request | {num} new follow requests",
"configuration_tip": "You can customize what to display here in {theSettings}. {dismiss}",
"configuration_tip_settings": "the settings",
"configuration_tip_dismiss": "Do not show again",
"subscribed_status": "posted"
},
"polls": {
"add_poll": "Add poll",
"add_option": "Add option",
"option": "Option",
"votes": "votes",
"people_voted_count": "{count} person voted | {count} people voted",
"votes_count": "{count} vote | {count} votes",
"vote": "Vote",
"type": "Poll type",
"single_choice": "Single choice",
"multiple_choices": "Multiple choices",
"expiry": "Poll age",
"expires_at": "Poll ends {0}",
"expires_in": "Poll ends in {0}",
"expired": "Poll ended {0} ago",
"expired_at": "Poll ended {0}",
"not_enough_options": "Too few unique options in poll",
"non_anonymous": "Public poll",
"non_anonymous_title": "Other instances may display the options you voted for"
},
"emoji": {
"stickers": "Stickers",
"emoji": "Emoji",
"keep_open": "Keep picker open",
"search_emoji": "Search for an emoji",
"add_emoji": "Insert emoji",
"custom": "Custom emoji",
"hide_custom_emoji": "Hide custom emojis",
"unpacked": "Unpacked emoji",
"unicode": "Unicode emoji",
"unicode_groups": {
"activities": "Activities",
"animals-and-nature": "Animals & Nature",
"flags": "Flags",
"food-and-drink": "Food & Drink",
"objects": "Objects",
"people-and-body": "People & Body",
"smileys-and-emotion": "Smileys & Emotion",
"symbols": "Symbols",
"travel-and-places": "Travel & Places"
},
"load_all_hint": "Loaded first {saneAmount} emoji, loading all emoji may cause performance issues.",
"load_all": "Loading all {emojiAmount} emoji",
"regional_indicator": "Regional indicator {letter}"
},
"errors": {
"storage_unavailable": "Pleroma could not access browser storage. Your login or your local settings won't be saved and you might encounter unexpected issues. Try enabling cookies."
},
"interactions": {
"favs_repeats": "Repeats and favorites",
"follows": "New follows",
"emoji_reactions": "Emoji Reactions",
"reports": "Reports",
"moves": "User migrates",
"load_older": "Load older interactions",
"statuses": "Subscriptions"
},
"post_status": {
"edit_status": "Edit status",
"new_status": "Post new status",
"reply_option": "Reply to this status",
"quote_option": "Quote this status",
"quote_url": "Link to quoted post",
"account_not_locked_warning": "Your account is not {0}. Anyone can follow you to view your follower-only posts.",
"account_not_locked_warning_link": "locked",
"attachments_sensitive": "Mark attachments as sensitive",
"media_description": "Media description",
"content_type": {
"text/plain": "Plain text",
"text/html": "HTML",
"text/markdown": "Markdown",
"text/bbcode": "BBCode",
"text/x.misskeymarkdown": "MFM"
},
"content_type_selection": "Post format",
"content_warning": "Subject (optional)",
+ "mentions_line": "Mentioned users",
+ "enter_submits": "Enter key sends the post",
+ "enter_newline": "Enter key adds a newline",
"default": "Just landed in L.A.",
"direct_warning_to_all": "This post will be visible to all the mentioned users.",
"direct_warning_to_first_only": "This post will only be visible to the mentioned users at the beginning of the message.",
"edit_remote_warning": "Other remote instances may not support editing and unable to receive the latest version of your post.",
"edit_unsupported_warning": "Pleroma does not support editing mentions or polls.",
"posting": "Posting",
"post": "Post",
"preview": "Preview",
"preview_empty": "Empty",
"empty_status_error": "Can't post an empty status with no files",
"media_description_error": "Failed to update media, try again",
"scope_notice": {
"public": "This post will be visible to everyone",
"private": "This post will be visible to your followers only",
"unlisted": "This post will not be visible in Public Timeline and The Whole Known Network"
},
"scope_notice_dismiss": "Close this notice",
"scope": {
"direct": "Direct - post to mentioned users only",
"private": "Followers-only - post to followers only",
"public": "Public - post to public timelines",
"unlisted": "Unlisted - do not post to public timelines"
},
"close_confirm_title": "Closing post form",
"close_confirm": "What do you want to do with your current writing?",
"close_confirm_save_button": "Save",
"close_confirm_discard_button": "Discard",
"close_confirm_continue_composing_button": "Continue composing",
"auto_save_nothing_new": "Nothing new to save.",
"auto_save_saved": "Saved.",
"auto_save_saving": "Saving...",
"save_to_drafts_button": "Save to drafts",
"save_to_drafts_and_close_button": "Save to drafts and close",
"more_post_actions": "More post actions..."
},
"registration": {
"bio_optional": "Bio (optional)",
"email": "Email",
"email_optional": "Email (optional)",
"fullname": "Display name",
"password_confirm": "Password confirmation",
"registration": "Registration",
"token": "Invite token",
"captcha": "CAPTCHA",
"new_captcha": "Click the image to get a new captcha",
"username_placeholder": "e.g. lain",
"fullname_placeholder": "e.g. Lain Iwakura",
"bio_placeholder": "e.g.\nHi, I'm Lain.\nI’m an anime girl living in suburban Japan. You may know me from the Wired.",
"reason": "Reason to register",
"reason_placeholder": "This instance approves registrations manually.\nLet the administration know why you want to register.",
"register": "Register",
"validations": {
"username_required": "cannot be left blank",
"fullname_required": "cannot be left blank",
"email_required": "cannot be left blank",
"password_required": "cannot be left blank",
"password_confirmation_required": "cannot be left blank",
"password_confirmation_match": "should be the same as password",
"birthday_required": "cannot be left blank",
"birthday_min_age": "must be on or before {date}"
},
"email_language": "In which language do you want to receive emails from the server?",
"birthday": "Birthday:",
"birthday_optional": "Birthday (optional):"
},
"remote_user_resolver": {
"remote_user_resolver": "Remote user resolver",
"searching_for": "Searching for",
"error": "Not found."
},
"report": {
"reporter": "Reporter:",
"reported_user": "Reported user:",
"reported_statuses": "Reported statuses:",
"notes": "Notes:",
"state": "State:",
"state_open": "Open",
"state_closed": "Closed",
"state_resolved": "Resolved"
},
"selectable_list": {
"select_all": "Select all"
},
"settings": {
"invalid_settings_imported": "Error importing settings",
"add_language": "Add fallback language",
"remove_language": "Remove",
"primary_language": "Primary language:",
"fallback_language": "Fallback language {index}:",
"actor_type": "This account is:",
"actor_type_description": "Marking your account as a group will make it automatically repeat statuses that mention it.",
"actor_type_Person": "a normal user",
"actor_type_person_proper": "a person",
"actor_type_Service": "a bot",
"actor_type_Group": "a group",
"mobile_center_dialog": "Vertically center dialogs on mobile",
"app_name": "App name",
"expert_mode": "Show advanced",
"save": "Save changes",
"reset": "Reset changes",
"security": "Security",
"toggle_edit": "Edit",
"change_banner": "Change banner",
"change_avatar": "Change avatar",
"setting_changed": "Setting is different from default",
"setting_server_side": "This setting is tied to your profile and affects all sessions and clients",
"setting_local_side": "This setting is tied to current session and doesn't affects other devices and browsers",
"enter_current_password_to_confirm": "Enter your current password to confirm your identity",
"post_look_feel": "Posts Look & Feel",
"posts": "Posts",
"developer": "Developer",
"debug": "Debug",
"mention_links": "Mention Links",
"appearance": "Appearance",
"confirm_new_setting": "Confirm new setting?",
"confirm_new_question": "Does this look ok? Setting will be reverted in 10 seconds.",
"confirm_new_question_countdown": "Does this look ok? Setting will be reverted in 1 second. | Does this look ok? Setting will be reverted in {count} seconds.",
"revert": "Revert",
"confirm": "Confirm",
"text_size": "Text and interface size",
"text_size_tip": "Use {0} for absolute values, {1} will scale with browser default text size.",
"text_size_tip2": "Values other than {0} might break some things and themes",
"emoji_size": "Emoji size",
"navbar_size": "Top bar size",
"panel_header_size": "Panel header size",
"visual_tweaks": "Minor visual tweaks",
"theme_debug": "Show what background theme engine assumes when dealing with transparancy",
"scale_and_layout": "Interface scale and layout",
"timelines": "Timelines",
"format_and_language": "Format and Language",
"confirmations": "Confirmations",
"layout": "Layout",
"enabled": "Enabled",
"clutter": "Clutter",
"filter": {
"clutter": "Remove clutter",
"mute_filter": "Mute Filters",
"type": "Filter type",
"regexp": "RegExp",
"plain": "Simple",
"user": "User (Simple)",
"user_regexp": "User (RegExp)",
"case_sensitive": "Case-sensitive",
"hide": "Hide completely",
"name": "Name",
"value": "Value",
"expires": "Expires",
"expired": "Expired",
"copy": "Duplicate",
"save": "Save",
"delete": "Remove",
"new": "Create new",
"import": "Import",
"export": "Export",
"regexp_error": "Invalid Regular Expression",
"never_expires": "Never",
"total_count": "Total {count} custom filter|Total {count} custom filters",
"expired_count": "{count} expired filter|{count} expired filters",
"custom_filters": "Custom filters",
"purge_expired": "Remove expired filters",
"import_failure": "The selected file is not a supported Pleroma filter.",
"help": {
"word": "Simple and RegExp filters test against post's content and subject.",
"user": "User filter matches full user handle (user{'@'}domain) in the following: author, reply-to and mentions",
"regexp": "Regex variants are more advanced and use {link} to match instead of simple substring search.",
"regexp_link": "Regular Expressions",
"regexp_url": "https://en.wikipedia.org/wiki/Regular_expression"
}
},
"mfa": {
"otp": "OTP",
"setup_otp": "Setup OTP",
"wait_pre_setup_otp": "presetting OTP",
"confirm_and_enable": "Confirm & enable OTP",
"title": "Two-factor Authentication",
"generate_new_recovery_codes": "Generate new recovery codes",
"warning_of_generate_new_codes": "When you generate new recovery codes, your old codes won’t work anymore.",
"recovery_codes": "Recovery codes.",
"waiting_a_recovery_codes": "Receiving backup codes…",
"recovery_codes_warning": "Write the codes down or save them somewhere secure - otherwise you won't see them again. If you lose access to your 2FA app and recovery codes you'll be locked out of your account.",
"authentication_methods": "Authentication methods",
"scan": {
"title": "Scan",
"desc": "Using your two-factor app, scan this QR code or enter text key:",
"secret_code": "Key"
},
"verify": {
"desc": "To enable two-factor authentication, enter the code from your two-factor app:"
}
},
"units": {
"time": {
"m": "minutes",
"s": "seconds",
"h": "hours",
"d": "days"
}
},
"lists_navigation": "Show lists in navigation",
"allow_following_move": "Allow auto-follow when following account moves",
"attachmentRadius": "Attachments",
"attachments": "Attachments",
"image_compression": "Compress images before uploading",
"always_use_jpeg": "Always convert images to JPEG format",
"avatar": "Avatar",
"avatarAltRadius": "Avatars (notifications)",
"avatarRadius": "Avatars",
"background": "Background",
"bio": "Bio",
"profile_other": "Other",
"email_language": "Language for receiving emails from the server",
"block_export": "Block export",
"block_export_button": "Export your blocks to a csv file",
"block_import": "Block import",
"block_import_error": "Error importing blocks",
"blocks_imported": "Blocks imported! Processing them will take a while.",
"mute_export": "Mute export",
"mute_export_button": "Export your mutes to a csv file",
"mute_import": "Mute import",
"mute_import_error": "Error importing mutes",
"mutes_imported": "Mutes imported! Processing them will take a while.",
"import_mutes_from_a_csv_file": "Import mutes from a csv file",
"account_backup": "Account backup",
"account_backup_description": "This allows you to download an archive of your account information and your posts, but they cannot yet be imported into a Pleroma account.",
"account_backup_table_head": "Backup",
"download_backup": "Download",
"backup_not_ready": "This backup is not ready yet.",
"backup_running": "This backup is in progress, processed {number} record. | This backup is in progress, processed {number} records.",
"backup_failed": "This backup has failed.",
"remove_backup": "Remove",
"list_backups_error": "Error fetching backup list: {error}",
"add_backup": "Create a new backup",
"added_backup": "Added a new backup.",
"add_backup_error": "Error adding a new backup: {error}",
"blocks_tab": "Blocks",
"btnRadius": "Buttons",
"cBlue": "Blue (Reply, follow)",
"cGreen": "Green (Retweet)",
"cOrange": "Orange (Favorite)",
"cRed": "Red (Cancel)",
"change_email": "Change email",
"change_email_error": "There was an issue changing your email.",
"changed_email": "Email changed successfully!",
"change_password": "Change password",
"change_password_error": "There was an issue changing your password.",
"changed_password": "Password changed successfully!",
"chatMessageRadius": "Chat message",
"collapse_subject": "Collapse posts with subjects",
"composing": "Composing",
"replies": "Replying",
"confirm_new_password": "Confirm new password",
"current_password": "Current password",
"confirm_dialogs": "Ask for confirmation when",
"confirm_dialogs_repeat": "repeating a status",
"confirm_dialogs_unfollow": "unfollowing a user",
"confirm_dialogs_block": "blocking a user",
"confirm_dialogs_mute": "muting a user",
"confirm_dialogs_mute_domain": "muting domains",
"confirm_dialogs_mute_conversation": "muting conversations",
"confirm_dialogs_delete": "deleting a status",
"confirm_dialogs_logout": "logging out",
"confirm_dialogs_approve_follow": "approving a follower",
"confirm_dialogs_deny_follow": "denying a follower",
"confirm_dialogs_remove_follower": "removing a follower",
"mutes_and_blocks": "Mutes and Blocks",
"data_import_export_tab": "Data import / export",
"default_vis": "Default visibility scope",
"delete_account": "Delete account",
"delete_account_description": "Permanently delete your data and deactivate your account.",
"delete_account_error": "There was an issue deleting your account. If this persists please contact your instance administrator.",
"delete_account_instructions": "Type your password in the input below to confirm account deletion.",
"account_alias": "Account aliases",
"account_alias_table_head": "Alias",
"list_aliases_error": "Error fetching aliases: {error}",
"hide_list_aliases_error_action": "Close",
"remove_alias": "Remove this alias",
"new_alias_target": "Add a new alias (e.g. {example})",
"added_alias": "Alias is added.",
"add_alias_error": "Error adding alias: {error}",
"move_account": "Move account",
"move_account_notes": "If you want to move the account somewhere else, you must go to your target account and add an alias pointing here.",
"move_account_target": "Target account (e.g. {example})",
"moved_account": "Account is moved.",
"move_account_error": "Error moving account: {error}",
"discoverable": "Allow discovery of this account in search results and other services",
"domain_mutes": "Domains",
"domain_mutes2": "Excluded domains",
"user_mutes2": "Muted users",
"user_blocks": "Blocked users",
"avatar_size_instruction": "The recommended minimum size for avatar images is 150x150 pixels. Recommended aspect ratio is 1:1",
"banner_size_instruction": "The recommended minimum size for banner images is 450x150 pixels. Recommended aspect ratio is 3:1",
"pad_emoji": "Pad emoji with spaces when adding from picker",
"autocomplete_select_first": "Automatically select the first candidate when autocomplete results are available",
"unsaved_post_action": "When you try to close an unsaved posting form",
"unsaved_post_action_save": "Save it to drafts",
"unsaved_post_action_discard": "Discard it",
"unsaved_post_action_confirm": "Ask every time",
"auto_save_draft": "Save drafts as you compose",
"emoji_reactions_on_timeline": "Show emoji reactions on timeline",
"emoji_reactions_scale": "Reactions scale factor",
"absolute_time_format": "Use absolute time format",
"absolute_time_format_min_age": "Only use for time older than this amount of time",
"absolute_time_format_12h": "Time format",
"absolute_time_format_12h_12h": "12 hour format (i.e. 10:00 PM)",
"absolute_time_format_12h_24h": "24 hour format (i.e. 22:00)",
"export_theme": "Save preset",
"filtering": "Filtering",
"wordfilter": "Wordfilter",
"filtering_explanation": "All statuses containing these words will be muted, one per line",
"word_filter_and_more": "Word filter and more...",
"follow_export": "Follow export",
"follow_export_button": "Export your follows to a csv file",
"follow_import": "Follow import",
"follow_import_error": "Error importing followers",
"import_export": {
"title": "Import / Export",
"follows": "List of users you follow",
"blocks": "List of users you block",
"mutes": "List of users you mute"
},
"follows_imported": "Follows imported! Processing them will take a while.",
"accent": "Accent",
"foreground": "Foreground",
"general": "General",
"hide_attachments_in_convo": "Hide attachments in conversations",
"hide_attachments_in_tl": "Hide attachments in timeline",
"hide_media_previews": "Hide media previews",
"hide_muted_posts": "Hide posts of muted users",
"mute_bot_posts": "Mute bot posts",
"hide_actor_type_indication": "Hide actor type (bots, groups, etc.) indication in posts",
"hide_scrobbles": "Hide scrobbles",
"hide_scrobbles_after": "Hide scrobbles older than",
"mute_sensitive_posts": "Mute sensitive posts",
"hide_all_muted_posts": "Hide muted posts",
"max_thumbnails": "Maximum amount of thumbnails per post (empty = no limit)",
"hide_isp": "Hide instance-specific panel",
"hide_shoutbox": "Hide instance shoutbox",
"right_sidebar": "Reverse order of columns",
"navbar_column_stretch": "Stretch navbar to columns width",
"always_show_post_button": "Always show floating New Post button",
"hide_wallpaper": "Hide instance wallpaper",
"foreign_user_background": "Allow other user's profiles to override wallpaper",
"preload_images": "Preload images",
"use_one_click_nsfw": "Open NSFW attachments with just one click",
"hide_post_stats": "Hide post statistics (e.g. the number of favorites)",
"hide_user_stats": "Hide user statistics (e.g. the number of followers)",
"hide_filtered_statuses": "Hide all filtered posts",
"hide_muted_statuses": "Completely hide all muted posts",
"hide_wordfiltered_statuses": "Hide word-filtered statuses",
"hide_muted_threads": "Hide muted threads",
"import_blocks_from_a_csv_file": "Import blocks from a csv file",
"import_followers_from_a_csv_file": "Import follows from a csv file",
"import_theme": "Load preset",
"inputRadius": "Input fields",
"checkboxRadius": "Checkboxes",
"instance_default": "(default: {value})",
"instance_default_simple": "(default)",
"interface": "Interface",
"interfaceLanguage": "Interface language",
"invalid_theme_imported": "The selected file is not a supported Pleroma theme. No changes to your theme were made.",
"limited_availability": "Unavailable in your browser",
"links": "Links",
"lock_account_description": "Restrict your account to approved followers only",
"loop_video": "Loop videos",
"loop_video_silent_only": "Loop only videos without sound (i.e. Mastodon's \"gifs\")",
"mutes_tab": "Mutes",
"play_videos_in_modal": "Play videos in a popup frame",
"url": "URL",
"preview": "Preview",
"file_export_import": {
"backup_restore": "Settings backup",
"backup_settings": "Backup settings to file",
"backup_settings_theme": "Backup settings and theme to file",
"restore_settings": "Restore settings from file",
"errors": {
"invalid_file": "The selected file is not a supported Pleroma settings backup. No changes were made.",
"file_too_new": "Incompatile major version: {fileMajor}, this PleromaFE (settings ver {feMajor}) is too old to handle it",
"file_too_old": "Incompatile major version: {fileMajor}, file version is too old and not supported (min. set. ver. {feMajor})",
"file_slightly_new": "File minor version is different, some settings might not load"
}
},
"profile_fields": {
"label": "Profile metadata",
"add_field": "Add field",
"name": "Label",
"value": "Content"
},
"birthday": {
"label": "Birthday",
"show_birthday": "Show my birthday"
},
"account_profile_edit": "Edit Profile",
"account_privacy": "Privacy",
"use_contain_fit": "Don't crop the attachment in thumbnails",
"name": "Name",
"name_bio": "Name & bio",
"new_email": "New email",
"new_password": "New password",
"user_profiles": "User Profiles",
"notification_visibility": "Types of notifications to show",
"notification_visibility_in_column": "Show in notifications column/drawer",
"notification_visibility_native_notifications": "Show a native notification",
"notification_visibility_follows": "Follows",
"notification_visibility_follow_requests": "Follow requests",
"notification_visibility_likes": "Favorites",
"notification_visibility_mentions": "Mentions",
"notification_visibility_repeats": "Repeats",
"notification_visibility_reports": "Reports",
"notification_visibility_moves": "User Migrates",
"notification_visibility_emoji_reactions": "Reactions",
"notification_visibility_polls": "Ends of polls you voted in",
"notification_visibility_statuses": "Subscriptions",
"notification_show_extra": "Show extra notifications in the notifications column",
"notification_extra_chats": "Show unread chats",
"notification_extra_announcements": "Show unread announcements",
"notification_extra_follow_requests": "Show new follow requests",
"notification_extra_tip": "Show the customization tip for extra notifications",
"no_rich_text_description": "Strip rich text formatting from all posts",
"no_blocks": "No blocks",
"no_mutes": "No mutes",
"hide_favorites_description": "Don't show list of my favorites (people still get notified)",
"hide_follows_description": "Don't show who I'm following",
"hide_followers_description": "Don't show who's following me",
"hide_follows_count_description": "Don't show follow count",
"hide_followers_count_description": "Don't show follower count",
"show_admin_badge": "Show \"Admin\" badge in my profile",
"show_moderator_badge": "Show \"Moderator\" badge in my profile",
"nsfw_clickthrough": "Hide sensitive/NSFW media",
"oauth_tokens": "OAuth tokens",
"token": "Token",
"refresh_token": "Refresh token",
"valid_until": "Valid until",
"revoke_token": "Revoke",
"panelRadius": "Panels",
"pause_on_unfocused": "Pause when tab is not focused",
"presets": "Presets",
"profile_background": "Profile background",
"profile_banner": "Profile banner",
"profile_tab": "Profile",
"radii_help": "Set up interface edge rounding (in pixels)",
"replies_in_timeline": "Replies in timeline",
"reply_visibility_all": "Show all replies",
"reply_visibility_following": "Only show replies directed at me or users I'm following",
"reply_visibility_self": "Only show replies directed at me",
"reply_visibility_following_short": "Show replies to my follows",
"reply_visibility_self_short": "Show replies to self only",
"autohide_floating_post_button": "Automatically hide New Post button (mobile)",
"saving_err": "Error saving settings",
"saving_ok": "Settings saved",
"search_user_to_block": "Search whom you want to block",
"search_user_to_mute": "Search whom you want to mute",
"security_tab": "Security",
"scope_copy": "Copy scope when replying (DMs are always copied)",
"minimal_scopes_mode": "Minimize post scope selection options",
"set_new_avatar": "Set new avatar",
"set_new_profile_background": "Set new profile background",
"set_new_background": "Set new background",
"set_new_profile_banner": "Set new profile banner",
"reset_avatar": "Reset avatar",
"reset_banner": "Reset banner",
"reset_profile_background": "Reset profile background",
"reset_profile_banner": "Reset profile banner",
"reset_avatar_confirm": "Do you really want to reset the avatar?",
"reset_banner_confirm": "Do you really want to reset the banner?",
"reset_background_confirm": "Do you really want to reset the background?",
"settings": "Settings",
"subject_input_always_show": "Always show subject field",
"subject_line_behavior": "Copy subject when replying",
"subject_line_email": "Like email: \"re: subject\"",
"subject_line_mastodon": "Like mastodon: copy as is",
"subject_line_noop": "Do not copy",
+ "submit_on_enter_in_chats": "Send message on Enter in chats",
"force_theme_recompilation_debug": "Disable theme cahe, force recompile on each boot",
"conversation_display": "Conversation display style",
"conversation_display_tree": "Tree-style",
"conversation_display_tree_quick": "Tree view",
"disable_sticky_headers": "Don't stick column headers to top of the screen",
"show_scrollbars": "Show side column's scrollbars",
"third_column_mode": "When there's enough space, show third column containing",
"third_column_mode_none": "Don't show third column at all",
"third_column_mode_notifications": "Notifications column",
"third_column_mode_postform": "Main post form and navigation",
"columns": "Columns",
"column_sizes": "Column sizes",
"column_sizes_sidebar": "Sidebar",
"column_sizes_content": "Content",
"column_sizes_notifs": "Notifications",
"scale_and_font": "Scale and Font",
"theme_editor_min_width": "Minimum width of theme editor (0 for \"fit-content\")",
"tree_advanced": "Allow more flexible navigation in tree view",
"tree_fade_ancestors": "Display ancestors of the current status in faint text",
"conversation_display_linear": "Linear-style",
"conversation_display_linear_quick": "Linear view",
"conversation_other_replies_button": "Show the \"other replies\" button",
"conversation_other_replies_button_below": "Below statuses",
"conversation_other_replies_button_inside": "Inside statuses",
"max_depth_in_thread": "Maximum number of levels in thread to display by default",
"post_status_content_type": "Post status content type",
"default_post_status_content_type": "Default post status content type",
"sensitive_by_default": "Mark posts as sensitive by default",
"stop_gifs": "Pause animated images until you hover on them",
"non_square_emoji": "Allow non-square emoji",
"pause_mfm": "Pause MFM animations until you hover on them",
"scale_mfm": "Scale MFM animations with emoji size",
"streaming": "Automatically show new posts when scrolled to the top",
"auto_update": "Show new posts automatically",
"user_mutes": "Users",
"useStreamingApi": "Receive posts and notifications real-time",
"use_websockets": "Use websockets (Realtime updates)",
"text": "Text",
"theme": "Theme",
"theme_old": "Theme editor (old)",
"theme_help": "Use hex color codes (#rrggbb) to customize your color theme.",
"theme_help_v2_1": "You can also override certain component's colors and opacity by toggling the checkbox, use \"Clear all\" button to clear all overrides.",
"theme_help_v2_2": "Icons underneath some entries are background/text contrast indicators, hover over for detailed info. Please keep in mind that when using transparency contrast indicators show the worst possible case.",
"tooltipRadius": "Tooltips/alerts",
"type_domains_to_mute": "Search domains to mute",
"upload_a_photo": "Upload a photo",
"upload_picture": "Upload picture",
"select_picture": "Select picture",
"user_settings": "User Settings",
"values": {
"false": "no",
"true": "yes"
},
"virtual_scrolling": "Optimize timeline rendering",
"use_at_icon": "Display {'@'} symbol as an icon instead of text",
"mention_link_display": "Display mention links",
"mention_link_display_short": "always as short names (e.g. {'@'}foo)",
"mention_link_display_full_for_remote": "as full names only for remote users (e.g. {'@'}foo{'@'}example.org)",
"mention_link_display_full": "always as full names (e.g. {'@'}foo{'@'}example.org)",
"mention_link_use_tooltip": "Show user card when clicking mention links",
"mention_link_show_avatar": "Show user avatar beside the link",
"mention_link_show_avatar_quick": "Show user avatar next to mentions",
"mention_link_fade_domain": "Fade domains (e.g. {'@'}example.org in {'@'}foo{'@'}example.org)",
"mention_link_bolden_you": "Highlight mention of you when you are mentioned",
"user_popover_avatar_action": "Popover avatar click action",
"user_popover_avatar_action_zoom": "Zoom the avatar",
"user_popover_avatar_action_close": "Close the popover",
"user_popover_avatar_action_open": "Open profile",
"user_popover_avatar_overlay": "Show user popover over user avatar",
"user_card_left_justify": "Justify user bio to the left",
"user_card_hide_personal_marks": "Hide personal marks (highlight/note) in user profiles",
"posts_appearance": "Posts Appearance",
"fun": "Fun",
"greentext": "Meme arrows",
"plaintext_quotes": "Highlight plaintext {0}",
"greentext_quotes": ">quotes",
"show_yous": "Show (You)s",
"notifications": "Notifications",
"notification_setting_annoyance": "Annoyance",
"notification_setting_drawer_marks_as_seen": "Closing drawer (mobile) marks all notifications as read",
"notification_setting_ignore_inactionable_seen": "Ignore read state of inactionable notifications (likes, repeats etc)",
"notification_setting_ignore_inactionable_seen_tip": "This will not actually mark those notifications as read, and you'll still get desktop notifications about them if you chose so",
"notification_setting_unseen_at_top": "Show unread notifications above others",
"notification_setting_filters": "Filters",
"notification_setting_filters_chrome_push": "On some browsers (chrome) it might be impossible to completely filter out notifications by type when they arrive by Push",
"notification_setting_block_from_strangers": "Block notifications from users who you do not follow",
"notification_setting_privacy": "Privacy",
"notification_setting_hide_notification_contents": "Hide the sender and contents of push notifications",
"notification_mutes": "To stop receiving notifications from a specific user, use a mute.",
"notification_blocks": "Blocking a user stops all notifications as well as unsubscribes them.",
"enable_web_push_notifications": "Enable web push notifications",
"enable_web_push_always_show": "Always show web push notifications",
"enable_web_push_always_show_tip": "Some browsers (Chromium, Chrome) require that push messages always result in a notification, otherwise generic 'Website was updated in background' is shown, enable this to prevent this notification from showing, as Chrome seem to hide push notifications if tab is in focus. Can result in showing duplicate notifications on other browsers.",
"more_settings": "More settings",
"style": {
"style_section": "Style",
"custom_theme_used": "(Custom theme)",
"custom_style_used": "(Custom style)",
"stock_theme_used": "(Stock theme)",
"themes2_outdated": "Editor for Themes V2 is being phased out and will eventually be replaced with a new one that takes advantage of new Themes V3 engine. It should still work but experience might be degraded and inconsistent.",
"appearance_tab_note": "Changes on this tab do not affect the theme used, so exported theme will be different from what seen in the UI",
"visual_tweaks_section_note": "Changes in this section do not affect the theme used, exported theme will be different from what seen in the UI",
"update_preview": "Update preview",
"themes3": {
"define": "Override",
"palette": {
"label": "Color schemes",
"name_label": "Color scheme name",
"import": "Import palette",
"export": "Export palette",
"apply": "Apply palette",
"bg": "Panel background",
"fg": "Buttons etc.",
"text": "Text",
"link": "Links",
"accent": "Accent color",
"cRed": "Red color",
"cBlue": "Blue color",
"cGreen": "Green color",
"cOrange": "Orange color",
"wallpaper": "Wallpaper",
"v2_unsupported": "Older v2 themes don't support palettes. Switch to v3 theme to make use of palettes",
"bundled": "Bundled palettes",
"style": "Palettes provided by selected style",
"user": "Custom palette",
"imported": "Imported"
},
"editor": {
"title": "Style editor",
"reset_style": "Reset",
"load_style": "Open from file",
"save_style": "Save",
"style_name": "Stylesheet name",
"style_author": "Made by",
"style_license": "License",
"style_website": "Website",
"component_selector": "Component",
"variant_selector": "Variant",
"states_selector": "States",
"main_tab": "Main",
"shadows_tab": "Shadows",
"background": "Background color",
"text_color": "Text color",
"icon_color": "Icon color",
"link_color": "Link color",
"contrast": "Text contrast",
"roundness": "Roundness",
"opacity": "Opacity",
"border_color": "Border color",
"include_in_rule": "Add to rule",
"test_string": "TEST",
"invalid": "Invalid",
"refresh_preview": "Refresh preview",
"apply_preview": "Apply",
"text_auto": {
"label": "Auto-contrast",
"no-preserve": "Black or White",
"preserve": "Keep color",
"no-auto": "Disabled"
},
"component_tab": "Components style",
"palette_tab": "Color schemes",
"variables_tab": "Variables (Advanced)",
"variables": {
"label": "Variables",
"name_label": "Name:",
"type_label": "Type:",
"type_shadow": "Shadow",
"type_color": "Color",
"type_generic": "Generic",
"virtual_color": "Variable color value"
}
},
"hacks": {
"underlay_overrides": "Change underlay",
"underlay_override_mode_none": "Theme default",
"underlay_override_mode_opaque": "Replace with solid color",
"underlay_override_mode_transparent": "Remove entirely (might break some themes)",
"force_interface_roundness": "Override interface roundness/sharpness",
"forced_roundness_mode_disabled": "Use theme defaults",
"forced_roundness_mode_sharp": "Force sharp edges",
"forced_roundness_mode_nonsharp": "Force not-so-sharp (1px roundness) edges",
"forced_roundness_mode_round": "Force round edges"
},
"font": {
"group-builtin": "Browser default fonts",
"builtin": {
"serif": "Serif",
"sans-serif": "Sans-serif",
"monospace": "Monospace",
"inherit": "Unchanged"
},
"group-local": "Locally installed fonts",
"local-unavailable1": "List of locally installed fonts unavailable",
"local-unavailable2": "Use manual entry to specify custom font",
"font_list_unavailable": "Couldn't get locally installed fonts: {error}",
"lookup_local_fonts": "Load list of fonts installed on this computer",
"enter_manually": "Enter font name family manually",
"entry": "Enter {fontFamily}",
"select": "Select font",
"label": "{label} font"
}
},
"interface_font_user_override": "Override theme/browser font used",
"switcher": {
"keep_color": "Keep colors",
"keep_shadows": "Keep shadows",
"keep_opacity": "Keep opacity",
"keep_roundness": "Keep roundness",
"keep_fonts": "Keep fonts",
"save_load_hint": "\"Keep\" options preserve currently set options when selecting or loading themes, it also stores said options when exporting a theme. When all checkboxes unset, exporting theme will save everything.",
"reset": "Reset",
"clear_all": "Clear all",
"clear_opacity": "Clear opacity",
"load_theme": "Load theme",
"keep_as_is": "Keep as is",
"use_snapshot": "Old version",
"use_source": "New version",
"help": {
"upgraded_from_v2": "PleromaFE has been upgraded, theme could look a little bit different than you remember.",
"v2_imported": "File you imported was made for older FE. We try to maximize compatibility but there still could be inconsistencies.",
"future_version_imported": "File you imported was made in newer version of FE.",
"older_version_imported": "File you imported was made in older version of FE.",
"snapshot_present": "Theme snapshot is loaded, so all values are overriden. You can load theme's actual data instead.",
"snapshot_missing": "No theme snapshot was in the file so it could look different than originally envisioned.",
"fe_upgraded": "PleromaFE's theme engine upgraded after version update.",
"fe_downgraded": "PleromaFE's version rolled back.",
"migration_snapshot_ok": "Just to be safe, theme snapshot loaded. You can try loading theme data.",
"migration_napshot_gone": "For whatever reason snapshot was missing, some stuff could look different than you remember.",
"snapshot_source_mismatch": "Versions conflict: most likely FE was rolled back and updated again, if you changed theme using older version of FE you most likely want to use old version, otherwise use new version."
}
},
"common": {
"color": "Color",
"opacity": "Opacity",
"contrast": {
"hint": "Contrast ratio is {ratio}, it {level} {context}",
"level": {
"aa": "meets Level AA guideline (minimal)",
"aaa": "meets Level AAA guideline (recommended)",
"bad": "doesn't meet any accessibility guidelines"
},
"context": {
"18pt": "for large (18pt+) text",
"text": "for text"
}
}
},
"common_colors": {
"_tab_label": "Common",
"main": "Common colors",
"foreground_hint": "See \"Advanced\" tab for more detailed control",
"rgbo": "Icons, accents, badges"
},
"advanced_colors": {
"_tab_label": "Advanced",
"alert": "Alert background",
"alert_error": "Error",
"alert_warning": "Warning",
"alert_neutral": "Neutral",
"post": "Posts/User bios",
"badge": "Badge background",
"popover": "Tooltips, menus, popovers",
"badge_notification": "Notification",
"panel_header": "Panel header",
"top_bar": "Top bar",
"borders": "Borders",
"buttons": "Buttons",
"inputs": "Input fields",
"faint_text": "Faded text",
"underlay": "Underlay",
"wallpaper": "Wallpaper",
"poll": "Poll graph",
"icons": "Icons",
"highlight": "Highlighted elements",
"pressed": "Pressed",
"selectedPost": "Selected post",
"selectedMenu": "Selected menu item",
"disabled": "Disabled",
"toggled": "Toggled",
"tabs": "Tabs",
"chat": {
"incoming": "Incoming",
"outgoing": "Outgoing",
"border": "Border"
}
},
"radii": {
"_tab_label": "Roundness"
},
"shadows": {
"_tab_label": "Shadow and lighting",
"component": "Component",
"override": "Override",
"shadow_id": "Shadow #{value}",
"offset": "Shadow offset",
"zoom": "Zoom",
"offset-x": "x:",
"offset-y": "y:",
"light_grid": "Use light checkerboard",
"color_override": "Use different color",
"name": "Name",
"blur": "Blur",
"spread": "Spread",
"inset": "Inset",
"raw": "Plain shadow",
"expression": "Expression (advanced)",
"empty_expression": "Empty expression",
"hintV3": "For shadows you can also use the {0} notation to use other color slot.",
"filter_hint": {
"always_drop_shadow": "Warning, this shadow always uses {0} when browser supports it.",
"drop_shadow_syntax": "{0} does not support {1} parameter and {2} keyword.",
"avatar_inset_short": "Separate inset shadow",
"avatar_inset": "Please note that combining both inset and non-inset shadows on avatars might give unexpected results with transparent avatars.",
"spread_zero": "Shadows with spread > 0 will appear as if it was set to zero",
"inset_classic": "Inset shadows will be using {0}"
},
"components": {
"panel": "Panel",
"panelHeader": "Panel header",
"topBar": "Top bar",
"avatar": "User avatar (in profile view)",
"avatarStatus": "User avatar (in post display)",
"popup": "Popups and tooltips",
"button": "Button",
"buttonHover": "Button (hover)",
"buttonPressed": "Button (pressed)",
"buttonPressedHover": "Button (pressed+hover)",
"input": "Input field"
}
},
"fonts": {
"_tab_label": "Fonts",
"help": "Select font to use for elements of UI. For \"custom\" you have to enter exact font name as it appears in system.",
"components": {
"interface": "Interface",
"input": "Input fields",
"post": "Post text",
"monospace": "Monospaced text"
},
"components_inline": {
"interface": "interface",
"input": "input fields",
"post": "post text",
"monospace": "monospaced text"
},
"override": "Override {0} font",
"family": "Font name",
"size": "Size (in px)",
"weight": "Weight (boldness)",
"custom": "Custom"
},
"preview": {
"header": "Preview",
"content": "Content",
"error": "Example error",
"button": "Button",
"text": "A bunch of more {0} and {1}",
"mono": "content",
"input": "Just landed in L.A.",
"faint_link": "helpful manual",
"fine_print": "Read our {0} to learn nothing useful!",
"header_faint": "This is fine",
"checkbox": "I have skimmed over terms and conditions",
"link": "a nice lil' link"
}
},
"version": {
"title": "Version",
"backend_version": "Backend version",
"frontend_version": "Frontend version"
},
"commit_value": "Save",
"commit_value_tooltip": "Value is not saved, press this button to commit your changes",
"reset_value": "Reset",
"reset_value_tooltip": "Reset draft",
"hard_reset_value": "Hard reset",
"hard_reset_value_tooltip": "Remove setting from storage, forcing use of default value",
"cache": "Cache",
"clear_asset_cache": "Clear asset cache",
"clear_emoji_cache": "Clear emoji cache",
"compact_profiles": "Reduce profile height on user pages"
},
"admin_dash": {
"window_title": "Administration",
"wip_notice": "This admin dashboard is experimental and WIP, {adminFeLink}.",
"old_ui_link": "old admin UI available here",
"reset_all": "Reset all",
"commit_all": "Save all",
"tabs": {
"nodb": "No DB Config",
"instance": "Instance",
"users": "Users",
"limits": "Limits",
"frontends": "Front-ends",
"mailer": "EMails",
"media_proxy": "Media Proxy",
"emoji": "Emoji",
"uploads": "Uploads",
"monitoring": "Monitoring",
"registrations": "Registrations",
"links": "Links",
"job_queues": "Job Queues",
"auth": "Auth",
"posts": "Posts",
"rate_limit": "Rate Limits",
"http": "HTTP",
"federation": "Federation",
"other": "Other"
},
"posts": {
"global": "Global settings",
"local": "Local posts",
"remote": "Remote posts"
},
"other": {
"uncategorized": "Uncategorized",
"user_backup": "User Backup",
"reports": "Reports",
"privileges": "Privileges"
},
"monitoring": {
"builtins": "Built-in Tools",
"prometheus": "Prometheus Exporter"
},
"federation": {
"global": "Global settings",
"restrictions": "Restrictions",
"activitypub": "ActivityPub"
},
"auth": {
"MFA": "Multi-factor Authentication",
"LDAP": "LDAP Settings",
"OAuth": "Oauth2 settings",
"TOTP": "One-time Passwords (TOTP)",
"backup_codes": "Backup codes"
},
"job_queues": {
"Gun": {
"title": "Gun queues",
"connections_pools": "Gun connections pool",
"pools": {
"title": "Gun worker pools",
"default": "Default pool",
"federation": "Federation pool",
"media": "Media pool",
"rich_media": "Rich media pool",
"upload": "Upload pool"
}
},
"Hackney": {
"title": "Hackney pools",
"federation": "Federation",
"media": "Media",
"rich_media": "Rich media",
"upload": "Upload"
},
"queues": "Queues"
},
"rate_limit": {
"rate_limit": "Rate Limit",
"amount": "Amount",
"unauthenticated": "Unauthenticated",
"authenticated": "Authenticated",
"period": "Time period",
"separate": "Separate rate limits for authenticated/unauthenticated users"
},
"nodb": {
"heading": "Database config is disabled",
"text": "You need to change backend config files so that {property} is set to {value}, see more in {documentation}.",
"documentation": "documentation",
"text2": "Most configuration options will be unavailable."
},
"captcha": {
"native": "Native",
"kocaptcha": "KoCaptcha"
},
"http": {
"outbound": "Outgoing connections",
"incoming": "Incoming connections",
"security": "HTTP Security",
"web_push": "Web Push",
"web_push_description": "Web Push VAPID settings. You can use the mix task web_push.gen.keypair to generate it."
},
"registrations": {
"welcome": {
"title": "Welcome message",
"description": "Send new users a message when they sign up",
"direct_message": "Via direct message",
"chat_message": "Via chat",
"email_message": "Via email"
},
"restrictions": "Restrictions",
"autofollow": "Autofollow"
},
"links": {
"no_scheme": "No scheme",
"link_previews": "Link previews",
"link_formatter": "Link formatter"
},
"uploads": {
"attachments": "Attachments settings",
"upload": "Upload",
"local_uploader": "Local files",
"filenames": "Filenames, Titles and Descriptions",
"uploader_settings": "Uploader settings"
},
"media_proxy": {
"basic": "Basic Settings",
"invalidation": "Cache Invalidation",
"limits": "Limits",
"thumbnails": "Thumbnail Generation",
"invalidation_settings": "Cache Invalidation"
},
"mailer": {
"styling": "Styling",
"assets": "Assets",
"colors": "Color palette",
"adapter": "Mailing Adapter",
"auth": "Authentication"
},
"users": {
"title": "Users",
"local_id": "Local ID",
"no_users_found": "No users found",
"labels": {
"query": "Search",
"nickname": "{'@'}handle",
"name": "Display Name",
"name_colon": "Name:",
"email": "Email",
"email_colon": "Email:",
"handle_colon": "Handle:",
"origin": "Origin",
"activity": "Activity",
"privileges": "Privileges"
},
"tags": {
"add_new": "Add New Tag",
"new_title": "Enter New Tag And Confirm",
"yes": "Add",
"no": "Abort"
},
"options": {
"all": "All",
"only_local": "Only Local",
"only_external": "Only External",
"only_active": "Only Active",
"only_deactivated": "Only Deactivated",
"only_admins": "Only Admins",
"only_privileged": "Only Privileged",
"only_moderators": "Only Moderators",
"only_unapproved": "Exclude Approved",
"only_unconfirmed": "Exclude Confirmed"
},
"filters": {
"show_direct": "Show Direct Messages",
"show_reblogs": "Show Reblogs"
},
"indicator": {
"admin": "Admin",
"moderator": "Moderator",
"active": "Active",
"deactivated": "Deactivated",
"confirmed": "Confirmed",
"unconfirmed": "Pending confirmation",
"approved": "Approved",
"suggested": "Suggested",
"unapproved": "Pending approval"
}
},
"limits": {
"arbitrary_limits": "Arbitrary limits",
"posts": "Post limits",
"other": "Misc. limits",
"uploads": "Attachments limits",
"users": "User profile limits",
"profile_fields": "Profile fields limits",
"user_uploads": "Profile media limits"
},
"frontend": {
"title": "Frontend management",
"repository": "Repository link",
"versions": "Available versions",
"build_url": "Build URL",
"reinstall": "Reinstall",
"is_default": "(Default)",
"is_default_custom": "(Default, version: {version})",
"install": "Install",
"install_version": "Install version {version}",
"more_install_options": "More install options",
"more_default_options": "More default setting options",
"set_default": "Set default",
"set_default_version": "Set version {version} as default",
"wip_notice": "Please note that this section is a WIP and lacks certain features as backend implementation of front-end management is incomplete.",
"default_frontend": "Default frontend",
"default_frontend_tip": "Default frontend will be shown to all users. Currently there's no way to for a user to select personal frontend. If you switch away from PleromaFE you'll most likely have to use old and buggy AdminFE to do instance configuration until we replace it.",
"default_frontend_unavail": "Default frontend settings are not available, as this requires configuration in the database",
"available_frontends": "Available for install",
"failure_installing_frontend": "Failed to install frontend {version}: {reason}",
"success_installing_frontend": "Frontend {version} successfully installed"
},
"emoji": {
"global_actions": "Global actions",
"reload": "Reload emoji",
"reload_short": "Refresh",
"advanced": "Advanced",
"importFS": "Import emoji from filesystem",
"import_pack": "Upload emoji pack",
"import_pack_short": "Import",
"error": "Error: {0}",
"create_pack": "Create pack",
"delete_pack": "Delete pack",
"new_pack_name": "New pack name",
"create": "Create",
"emoji_packs": "Emoji packs",
"remote_packs": "Remote packs",
"remote_packs_short": "Remote",
"do_list": "List",
"remote_pack_instance": "Remote pack instance",
"emoji_pack": "Emoji pack",
"edit_pack": "Edit pack",
"metadata": "Metadata",
"description": "Description",
"homepage": "Homepage",
"fallback_src": "Fallback source",
"fallback_sha256": "Fallback SHA256",
"share": "Share",
"save": "Save",
"save_meta": "Save metadata",
"revert_meta": "Revert metadata",
"delete": "Delete",
"revert": "Revert",
"add_file": "Add file",
"adding_new": "Adding new emoji",
"shortcode": "Shortcode",
"filename": "Filename",
"emoji_source": "Emoji file source",
"upload_url": "Upload from URL",
"new_shortcode": "Shortcode, leave blank to infer",
"new_filename": "Filename, leave blank to infer",
"delete_confirm": "Are you sure you want to delete {0}?",
"download_pack": "Download pack",
"downloading_pack": "Downloading {0}",
"download": "Download",
"download_as_name": "New name",
"download_as_name_full": "New name, leave blank to reuse",
"files": "Files",
"editing": "Editing {0}",
"copying": "Copying {0}",
"copy_to": "Copy to",
"copy_to_pack": "Copy to local pack",
"delete_title": "Delete?",
"metadata_changed": "Metadata different from saved",
"emoji_changed": "Unsaved emoji file changes, check highlighted emoji",
"replace_warning": "This will REPLACE the local pack of the same name",
"copied_successfully": "Successfully copied emoji \"{0}\" to pack \"{1}\""
},
"generic_enforcement": {
"if_available": "If available",
"always": "Always",
"never": "Never"
},
"instance": {
"instance": "Instance information",
"registrations": "User sign-ups",
"captcha_header": "CAPTCHA",
"kocaptcha": "KoCaptcha settings",
"pwa": {
"manifest": "PWA Manifest",
"optional": "(optional)",
"no_icons": "No icons defined",
"icon": {
"purpose": "Icon purpose",
"any": "Any",
"monochrome": "Monochrome",
"maskable": "Maskable"
}
},
"misc_brand": "Miscellaneous elements",
"branding": "Branding",
"access": "Instance access",
"rich_metadata": "Metadata",
"restrict": {
"header": "Restrict access for anonymous visitors",
"description": "Detailed setting for allowing/disallowing access to certain aspects of API. By default (indeterminate state) it will disallow if instance is not public, ticked checkbox means disallow access even if instance is public, unticked means allow access even if instance is private. Please note that unexpected behavior might happen if some settings are set, i.e. if profile access is disabled posts will show without profile information.",
"timelines": "Timelines access",
"profiles": "User profiles access",
"activities": "Statuses/activities access"
},
":unauthenticated": "Unauthenticated",
":all": "Everyone"
},
"temp_overrides": {
":pleroma": {
":connections_pool": {
":max_idle_time": {
"label": "Maximum idle time",
"description": "Maximum idle time before CONFIRM"
},
":retry": {
"label": "Retry",
"description": "Number of retries for making a connection CONFIRM"
}
},
":hackney_pools": {
":rich_media": {
"label": "Rich media",
"description": "idk",
":max_connections": {
"label": "Max connections",
"description": "Number workers in the pool."
},
":timeout": {
"label": "Timeout",
"description": "Timeout while `hackney` will wait for response."
}
}
},
":pools": {
":rich_media": {
"label": "Rich media",
"description": "idk",
":size": {
"label": "Size",
"description": "Maximum number of concurrent requests in the pool."
},
":max_waiting": {
"label": "Max waiting",
"description": "Maximum number of requests waiting for other requests to finish. After this number is reached, the pool will start returning errors when a new request is made"
},
":recv_timeout": {
"label": "Recv timeout",
"description": "Timeout for the pool while gun will wait for response"
}
}
},
":rate_limit": {
":oauth_app_creation": {
"label": "OAuth app creation",
"description": "For registering new OAuth App ID"
},
":ap_routes": {
"label": "ActivityPub",
"description": "Federation endpoints"
},
":account_confirmation_resend": {
"label": "Account confirmation resend",
"description": "How often user can resend confirmation mail"
}
},
"Pleroma_DOT_Formatter": {
":attribute_toggle": {
"label": "Set {attr} attribute"
},
":truncate_toggle": {
"label": "Truncate"
},
":class": {
"label": "Value"
},
":rel": {
"label": "Value"
}
},
"Pleroma_DOT_Uploaders_DOT_Uploader": {
":timeout": {
"label": "Timeout",
"description": "Amount of milliseconds before dropping connection"
}
},
"Pleroma_DOT_Upload": {
":default_description": {
"label": "Default description",
"description": "Default description to give to a file. Setting it to ':filename' will use file's filename as description."
}
},
":instance": {
":public": {
"label": "Instance is public",
"description": "Disabling this will make all API accessible only for logged-in users, this will make Public and Federated timelines inaccessible to anonymous visitors."
},
":limit_to_local_content": {
"label": "Limit search to local content",
"description": "Disables global network search for unauthenticated (default), all users or none"
},
":description_limit": {
"label": "Limit",
"description": "Character limit for attachment descriptions"
},
":background_image": {
"label": "Background image",
"description": "Background image (primarily used by PleromaFE)"
}
},
":http_security": {
":allow_unsafe_eval": {
"label": "Allow unsafe-eval",
"description": "Allow unsafe evaluation of scripts (required for Flash support)"
},
":report_url": {
"label": "Report URL",
"description": "URL to report security violations to"
}
}
}
}
},
"time": {
"unit": {
"days": "{0} day | {0} days",
"days_short": "{0}d",
"days_suffix": "day(s)",
"hours": "{0} hour | {0} hours",
"hours_short": "{0}h",
"hours_suffix": "hour(s)",
"minutes": "{0} minute | {0} minutes",
"minutes_short": "{0}min",
"minutes_suffix": "minute(s)",
"months": "{0} month | {0} months",
"months_short": "{0}mo",
"months_suffix": "month(s)",
"seconds": "{0} second | {0} seconds",
"seconds_short": "{0}s",
"seconds_suffix": "second(s)",
"weeks": "{0} week | {0} weeks",
"weeks_short": "{0}w",
"weeks_suffix": "week(s)",
"years": "{0} year | {0} years",
"years_short": "{0}y",
"years_suffix": "year(s)"
},
"in_future": "in {0}",
"in_past": "{0} ago",
"now": "just now",
"now_short": "now"
},
"timeline": {
"collapse": "Collapse",
"conversation": "Conversation",
"error": "Error fetching timeline: {0}",
"load_older": "Load older statuses",
"no_retweet_hint": "Post is marked as followers-only or direct and cannot be repeated",
"repeated": "repeated",
"show_new": "Show new",
"reload": "Reload",
"up_to_date": "Up-to-date",
"no_more_statuses": "No more statuses",
"no_statuses": "No statuses",
"socket_reconnected": "Realtime connection established",
"socket_broke": "Realtime connection lost: CloseEvent code {0}",
"quick_view_settings": "Quick view settings",
"quick_filter_settings": "Quick filter settings",
"filter_settings": "Filter"
},
"status": {
"favorites": "Favorites",
"repeats": "Repeats",
"quotes": "Quotes",
"repeat_confirm": "Do you really want to repeat this status?",
"repeat_confirm_title": "Repeat confirmation",
"repeat_confirm_accept_button": "Repeat",
"repeat_confirm_cancel_button": "Do not repeat",
"delete": "Delete status",
"delete_error": "Error deleting status: {0}",
"edit": "Edit status",
"edited_at": "(last edited {time})",
+ "open_in_chat_view": "Open in chat view",
+ "open_in_thread_view": "Open in thread view",
"pin": "Pin on profile",
"unpin": "Unpin from profile",
"pinned": "Pinned",
"bookmark": "Bookmark",
"unbookmark": "Unbookmark",
"delete_confirm": "Do you really want to delete this status?",
"delete_confirm_title": "Delete confirmation",
"delete_confirm_accept_button": "Delete",
"delete_confirm_cancel_button": "Keep",
"reply_to": "Reply to",
+ "reply_to_selected": "Replying to selected message",
+ "reply_to_last": "Replying to last message",
"reply_to_with_icon": "{icon} {replyTo}",
+ "broken_reply": "Message belongs to the thread but is not a reply",
"reply_to_with_arg": "{replyToWithIcon} {user}",
"mentions": "Mentions",
"replies_list": "Replies:",
"replies_list_with_others": "Replies (+{numReplies} other): | Replies (+{numReplies} others):",
"mute_ellipsis": "Mute…",
"mute_user": "Mute user",
"unmute_user": "Unmute user",
"mute_domain": "Mute domain",
"unmute_domain": "Unmute domain",
"mute_conversation": "Mute conversation",
"unmute_conversation": "Unmute conversation",
"status_unavailable": "Status unavailable",
"copy_link": "Copy link to status",
"external_source": "External source",
"muted_words": "Wordfiltered: {word} | Wordfiltered: {word} and {numWordsMore} more words",
"muted_filters": "Filtered: {name} | Wordfiltered: {name} and {filtersMore} more words",
"multi_reason_mute": "{main} + one more reason | {main} + {numReasonsMore} more reasons",
"muted_user": "User muted",
"thread_muted": "Thread muted",
"thread_muted_and_words": ", has words:",
"sensitive_muted": "Muting sensitive content",
"bot_muted": "Muting bot content",
"show_full_subject": "Show full subject",
"hide_full_subject": "Hide full subject",
"show_content": "Show content",
"hide_content": "Hide content",
"status_deleted": "This post was deleted",
"unknown_user": "unknown user",
"unknown_user_info": "Unable to fetch information about this user",
"nsfw": "NSFW",
"expand": "Expand",
"you": "(You)",
"plus_more": "+{number} more",
"many_attachments": "Post has {number} attachment(s)",
"collapse_attachments": "Collapse attachments",
"show_all_attachments": "Show all attachments",
"show_attachment_in_modal": "Show in media modal",
"show_attachment_description": "Preview description (open attachment for full description)",
"attachment_description": "Attachment description",
"hide_attachment": "Hide attachment",
"remove_attachment": "Remove attachment",
"attachment_stop_flash": "Stop Flash player",
"move_up": "Shift attachment left",
"move_down": "Shift attachment right",
"open_gallery": "Open gallery",
"thread_hide": "Hide this thread",
"thread_show": "Show this thread",
"thread_show_full": "Show everything under this thread ({numStatus} status in total, max depth {depth}) | Show everything under this thread ({numStatus} statuses in total, max depth {depth})",
"thread_show_full_with_icon": "{icon} {text}",
"thread_follow": "See the remaining part of this thread ({numStatus} status in total) | See the remaining part of this thread ({numStatus} statuses in total)",
"thread_follow_with_icon": "{icon} {text}",
"ancestor_follow": "See {numReplies} other reply under this status | See {numReplies} other replies under this status",
"ancestor_follow_with_icon": "{icon} {text}",
"show_all_conversation_with_icon": "{icon} {text}",
"show_all_conversation": "Show full conversation ({numStatus} other status) | Show full conversation ({numStatus} other statuses)",
"show_only_conversation_under_this": "Only show replies to this status",
"status_history": "Status history",
"reaction_count_label": "{num} person reacted | {num} people reacted",
"hide_quote": "Hide the quoted status",
"display_quote": "Display the quoted status",
"invisible_quote": "Quoted status unavailable: {link}",
"more_actions": "More actions on this status",
"loading": "Loading...",
"load_error": "Unable to load status: {error}",
"admin_change_scope": "Change visibility",
"mark_as_sensitive": "Sensitive",
"mark_as_non-sensitive": "Non-sensitive"
},
"user_card": {
"approve": "Approve",
"approve_confirm_title": "Approve confirmation",
"approve_confirm_accept_button": "Approve",
"approve_confirm_cancel_button": "Do not approve",
"approve_confirm": "Do you want to approve {user}'s follow request?",
"block": "Block",
"blocked": "Blocked!",
"block_confirm_title": "Block confirmation",
"block_confirm": "Do you really want to block {user}?",
"block_confirm_accept_button": "Block",
"block_confirm_cancel_button": "Do not block",
"deactivated": "Deactivated",
"deny": "Deny",
"deny_confirm_title": "Deny confirmation",
"deny_confirm_accept_button": "Deny",
"deny_confirm_cancel_button": "Do not deny",
"deny_confirm": "Do you want to deny {user}'s follow request?",
"edit_profile": "Edit profile",
"favorites": "Favorites",
"follow": "Follow",
"follow_cancel": "Cancel request",
"follow_sent": "Request sent!",
"follow_progress": "Requesting…",
"follow_unfollow": "Unfollow",
"unfollow_confirm_title": "Unfollow confirmation",
"unfollow_confirm": "Do you really want to unfollow {user}?",
"unfollow_confirm_accept_button": "Unfollow",
"unfollow_confirm_cancel_button": "Do not unfollow",
"followees": "Following",
"followers": "Followers",
"following": "Following!",
"follows_you": "Follows you!",
"hidden": "Hidden",
"its_you": "It's you!",
"media": "Media",
"mention": "Mention",
"message": "Message",
"mute": "Mute",
"muted": "Muted",
"mute_confirm_title": "Mute confirmation",
"mute_confirm": "Do you really want to mute {user}?",
"mute_domain_confirm": "Do you really want to mute entire {domain}?",
"mute_confirm_accept_button": "Mute",
"mute_confirm_cancel_button": "Do not mute",
"mute_or": "or",
"expire_in": "Expire in",
"expire_mute_message": "Are you sure you want to mute {0}?",
"expire_block_message": "Are you sure you want to block {0}?",
"dont_ask_again_mute": "Always mute users this way",
"dont_ask_again_block": "Always block users this way",
"mute_block_temporarily": "Temporarily",
"mute_block_forever": "Forever",
"mute_block_never": "Never",
"mute_block_ask": "Ask",
"default_mute_expiration": "Always mute users",
"default_block_expiration": "Always block users",
"default_expiration_time": "Expire in",
"mute_expires_forever": "Muted forever",
"mute_expires_at": "Muted until {0}",
"block_expires_forever": "Blocked forever",
"block_expires_at": "Blocked until {0}",
"mute_duration_prompt": "Mute this user for (0 for indefinite time):",
"statuses_per_day": "Statuses per day",
"remote_follow": "Remote follow",
"remove_follower": "Remove follower",
"remove_follower_confirm_title": "Remove follower confirmation",
"remove_follower_confirm_accept_button": "Remove",
"remove_follower_confirm_cancel_button": "Keep",
"remove_follower_confirm": "Do you really want to remove {user} from your followers?",
"report": "Report",
"statuses": "Statuses",
"subscribe": "Subscribe",
"unsubscribe": "Unsubscribe",
"unblock": "Unblock",
"unblock_progress": "Unblocking…",
"block_progress": "Blocking…",
"unmute": "Unmute",
"unmute_progress": "Unmuting…",
"mute_progress": "Muting…",
"hide_repeats": "Hide repeats",
"show_repeats": "Show repeats",
"bot": "Bot",
"group": "Group",
"birthday": "Born {birthday}",
"joined": "Joined",
"admin_data": {
"data": "Administrative info",
"registration_reason": "Registration reason",
"tags": "Tags"
},
"admin_menu": {
"moderation": "Moderation",
"grant_admin": "Grant Admin",
"revoke_admin": "Revoke Admin",
"grant_moderator": "Grant Moderator",
"revoke_moderator": "Revoke Moderator",
"activate_account": "Activate",
"deactivate_account": "Deactivate",
"delete_account": "Delete",
"suggest_account": "Add to suggested",
"remove_suggested_account": "Remove from suggested",
"approve_account": "Approve",
"confirm_account": "Confirm",
"show_statuses": "Show all posts",
"disable_mfa": "Disable MFA",
"force_nsfw": "Mark all posts as NSFW",
"strip_media": "Remove media from posts",
"force_unlisted": "Force posts to be unlisted",
"sandbox": "Force posts to be followers-only",
"disable_remote_subscription": "Disallow following user from remote instances",
"disable_any_subscription": "Disallow following user at all",
"quarantine": "Disallow user posts from federating",
"require_password_change": "Require Password Change",
"resend_confirmation": "Resend Confirmation Email",
"confirm_modal": {
"delete_title": "User deletion",
"delete_content": "Delete user {user}? | Delete {count} users?",
"delete_content_2": "This will permanently delete the data from this accounts and deactivate it. Are you absolutely sure?",
"activate_title": "User activation",
"activate_content": "Activate user {user}? | Activate {count} users?",
"deactivate_content": "Dectivate user {user}? | Dectivate {count} users?",
"approval_title": "Approve users",
"approval_content": "Approve user {user}? | Approve {count} users?",
"confirm_title": "Confirm users",
"confirm_content": "Approve user {user}? | Approve {count} users?",
"suggest_title": "Suggest users",
"add_suggest_content": "Add user {user} to suggested users list? | Add {count} users to suggested users list?",
"remove_suggest_content": "Remove user {user} from suggested users list? | Add {count} users to suggested users list?",
"rights_title": "Promote users",
"grant_rights_content": "Grant user {user} {name} role? | Grant {count} users {name} role?",
"revoke_rights_content": "Revoke {name} role from user {user}? | Revoke {name} from {count} users?",
"tag_title": "Assign user policy",
"assign_tag_content": "Assign {user} a {name} policy? | Assign {name} policy to {count} users?",
"unassign_tag_content": "Unassign policy {name} from {user}? | Unassign policy {name} from {count} users?",
"resend_confirmation_title": "Email confirmation resend",
"resend_confirmation_content": "Resend confirmation email to {count} users?",
"disable_mfa_title": "Disable MFA",
"disable_mfa_content": "Disable Mult-Factor Authentication for {count} users?",
"require_password_change_title": "Force password change",
"require_password_change_content": "Force {count} users to change password on next login?",
"add": "Add",
"remove": "Remove",
"delete": "Delete",
"activate": "Activate",
"deactivate": "Deactivate",
"grant": "Grant",
"revoke": "Revoke",
"approve": "Approve",
"confirm": "Confirm",
"assign": "Assign",
"unassign": "Unassign",
"send": "Send"
}
},
"highlight_new": {
"disabled": "Don't highlight",
"solid": "Solid background",
"striped": "Striped background",
"side": "Side stripe"
},
"personal_note": "Personal note",
"note_blank_click": "Click to add note",
"highlight_header": "Highlight user's posts and mentions",
"tags": {
"mrf_tag:media-force-nsfw": "Mark as sensitive",
"mrf_tag:media-strip": "Remove attachments",
"mrf_tag:force-unlisted": "Force unlisted",
"mrf_tag:sandbox": "Remove from public timelines",
"mrf_tag:disable-remote-subscription": "Reject non-local follow requests",
"mrf_tag:disable-any-subscription": "Reject any follow requests"
}
},
"user_profile": {
"timeline_title": "User timeline",
"profile_does_not_exist": "Sorry, this profile does not exist.",
"profile_loading_error": "Sorry, there was an error loading this profile."
},
"user_reporting": {
"title": "Reporting {0}",
"add_comment_description": "The report will be sent to your instance moderators. You can provide an explanation of why you are reporting this account below:",
"additional_comments": "Additional comments",
"forward_description": "The account is from another server. Send a copy of the report there as well?",
"forward_to": "Forward to {0}",
"submit": "Submit",
"generic_error": "An error occurred while processing your request."
},
"who_to_follow": {
"more": "More",
"who_to_follow": "Who to follow"
},
"tool_tip": {
"media_upload": "Upload media",
"mentions": "Mentions",
"repeat": "Repeat",
"unrepeat": "Unrepeat",
"reply": "Reply",
"favorite": "Favorite",
"unfavorite": "Unfavorite",
"add_reaction": "Add Reaction",
"add_quote": "Add quote",
"user_settings": "User Settings",
"accept_follow_request": "Accept follow request",
"reject_follow_request": "Reject follow request",
"bookmark": "Bookmark",
"toggle_expand": "Expand or collapse notification to show post in full",
"toggle_mute": "Expand or collapse notification to reveal muted content",
"autocomplete_available": "{number} result is available. Use up and down keys to navigate through them. | {number} results are available. Use up and down keys to navigate through them."
},
"upload": {
"error": {
"base": "Upload failed.",
"message": "Upload failed: {0}",
"file_too_big": "File too big [{filesize}{filesizeunit} / {allowedsize}{allowedsizeunit}]",
"default": "Try again later"
},
"file_size_units": {
"B": "B",
"KiB": "KiB",
"MiB": "MiB",
"GiB": "GiB",
"TiB": "TiB"
}
},
"search": {
"people": "People",
"hashtags": "Hashtags",
"person_talking": "{count} person talking",
"people_talking": "{count} people talking",
"no_results": "No results",
"no_more_results": "No more results",
"load_more": "Load more results"
},
"password_reset": {
"forgot_password": "Forgot password?",
"password_reset": "Password reset",
"instruction": "Enter your email address or username. We will send you a link to reset your password.",
"placeholder": "Your email or username",
"check_email": "Check your email for a link to reset your password.",
"return_home": "Return to the home page",
"too_many_requests": "You have reached the limit of attempts, try again later.",
"password_reset_disabled": "Password reset is disabled. Please contact your instance administrator.",
"password_reset_required": "You must reset your password to log in.",
"password_reset_required_but_mailer_is_disabled": "You must reset your password, but password reset is disabled. Please contact your instance administrator."
},
"chats": {
"you": "You:",
"message_user": "Message {nickname}",
"delete": "Delete",
"chats": "Chats",
"new": "New Chat",
"empty_message_error": "Cannot post empty message",
"more": "More",
"delete_confirm": "Do you really want to delete this message?",
"error_loading_chat": "Something went wrong when loading the chat.",
"error_sending_message": "Something went wrong when sending the message.",
"empty_chat_list_placeholder": "You don't have any chats yet. Start a new chat!"
},
"bookmarks": {
"manage_bookmark_folders": "Manage bookmark folders"
},
"lists": {
"lists": "Lists",
"new": "New List",
"title": "List title",
"search": "Search users",
"create": "Create",
"save": "Save changes",
"delete": "Delete list",
"following_only": "Limit to Following",
"manage_lists": "Manage lists",
"manage_members": "Manage list members",
"add_members": "Search for more users",
"remove_from_list": "Remove from list",
"add_to_list": "Add to list",
"is_in_list": "Already in list",
"editing_list": "Editing list {listTitle}",
"creating_list": "Creating new list",
"update_title": "Save Title",
"really_delete": "Really delete list?",
"error": "Error manipulating lists: {0}"
},
"file_type": {
"audio": "Audio",
"video": "Video",
"image": "Image",
"file": "File"
},
"display_date": {
"today": "Today"
},
"update": {
"big_update_title": "Please bear with us",
"big_update_content": "We haven't had a release in a while, so things might look and feel different than what you're used to.",
"big_update_content2": "We implemented synchronized settings! This means (nearly) all your settings are now properly synchronized between devices and sessions. We try to migrate settings from old config but migration is performed only once, so some settings might be incorrect.",
"update_bugs": "Please report any issues and bugs on {pleromaForgejo}, as we have changed a lot, and although we test thoroughly and use development versions ourselves, we may have missed some things. We welcome your feedback and suggestions on issues you might encounter, or how to improve Pleroma and Pleroma-FE.",
"update_bugs2": "Let us know if you don't want certain setting synchronized on {pleromaForgejo}.",
"update_bugs_gitlab": "Pleroma GitLab",
"update_bugs_forgejo": "Pleroma Forgejo",
"update_changelog": "For more details on what's changed, see {theFullChangelog}.",
"update_changelog_here": "the full changelog",
"art_by": "Art by {linkToArtist}"
},
"unicode_domain_indicator": {
"tooltip": "This domain contains non-ascii characters."
},
"drafts": {
"drafts": "Drafts",
"no_drafts": "You have no drafts",
"clean_drafts": "Remove all drafts",
"empty": "(No content)",
"poll_tooltip": "Draft contains a poll",
"continue": "Continue composing",
"save": "Save without posting",
"abandon": "Abandon draft",
"abandon_confirm_title": "Abandon confirmation",
"abandon_confirm": "Do you really want to abandon this draft?",
"abandon_confirm_accept_button": "Abandon",
"abandon_confirm_cancel_button": "Keep",
"abandon_all_confirm": "Do you really want to abandon all drafts?",
"replying": "Replying to {statusLink}",
"editing": "Editing {statusLink}",
"unavailable": "(unavailable)"
},
"splash": {
"loading": "Loading...",
"theme": "Applying theme, please wait warmly...",
"fun_1": "Drink more water",
"fun_2": "Take it easy!",
"fun_3": "Suya...",
"fun_4": "My Pleroma machine is full power!",
"error": "Something went wrong"
},
"bookmark_folders": {
"select_folder": "Select bookmark folder",
"creating_folder": "Creating bookmark folder",
"editing_folder": "Editing folder {folderName}",
"emoji": "Emoji",
"name": "Folder name",
"new": "New Folder",
"create": "Create folder",
"delete": "Delete folder",
"update_folder": "Save changes",
"really_delete": "Do you really want to delete the folder?",
"error": "Error manipulating bookmark folders: {0}"
}
}
diff --git a/src/modules/api.js b/src/modules/api.js
index 232d1776d2..e26336c055 100644
--- a/src/modules/api.js
+++ b/src/modules/api.js
@@ -1,344 +1,345 @@
import { Socket } from 'phoenix'
import { maybeShowChatNotification } from '../services/chat_utils/chat_utils.js'
+import { useChatsStore } from 'src/stores/chats.js'
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
import { useInterfaceStore } from 'src/stores/interface.js'
import { useOAuthStore } from 'src/stores/oauth.js'
import { useShoutStore } from 'src/stores/shout.js'
import { fetchTimeline } from 'src/api/timelines.js'
import {
getMastodonSocketURI,
ProcessedWS,
WSConnectionStatus,
} from 'src/api/websocket.js'
import followRequestFetcher from 'src/services/follow_request_fetcher/follow_request_fetcher.service'
import notificationsFetcher from 'src/services/notifications_fetcher/notifications_fetcher.service.js'
import timelineFetcher from 'src/services/timeline_fetcher/timeline_fetcher.service.js'
const retryTimeout = (multiplier) => 1000 * multiplier
const api = {
state: {
retryMultiplier: 1,
fetchers: {},
socket: null,
mastoUserSocket: null,
mastoUserSocketStatus: null,
followRequests: [],
},
getters: {
followRequestCount: (state) => state.followRequests.length,
},
mutations: {
addFetcher(state, { fetcherName, fetcher }) {
state.fetchers[fetcherName] = fetcher
},
removeFetcher(state, { fetcherName }) {
state.fetchers[fetcherName].stop()
delete state.fetchers[fetcherName]
},
setWsToken(state, token) {
state.wsToken = token
},
setSocket(state, socket) {
state.socket = socket
},
setFollowRequests(state, value) {
state.followRequests = value
},
setMastoUserSocketStatus(state, value) {
state.mastoUserSocketStatus = value
},
incrementRetryMultiplier(state) {
state.retryMultiplier = Math.max(++state.retryMultiplier, 3)
},
resetRetryMultiplier(state) {
state.retryMultiplier = 1
},
},
actions: {
/**
* Global MastoAPI socket control, in future should disable ALL sockets/(re)start relevant sockets
*
* @param {Boolean} [initial] - whether this enabling happened at boot time or not
*/
enableMastoSockets(store, initial) {
const { state, dispatch, commit } = store
// Do not initialize unless nonexistent or closed
if (
state.mastoUserSocket &&
![WebSocket.CLOSED, WebSocket.CLOSING].includes(
state.mastoUserSocket.getState(),
)
) {
return
}
if (initial) {
commit('setMastoUserSocketStatus', WSConnectionStatus.STARTING_INITIAL)
} else {
commit('setMastoUserSocketStatus', WSConnectionStatus.STARTING)
}
return dispatch('startMastoUserSocket')
},
disableMastoSockets(store) {
const { state, dispatch, commit } = store
if (!state.mastoUserSocket) return
commit('setMastoUserSocketStatus', WSConnectionStatus.DISABLED)
return dispatch('stopMastoUserSocket')
},
// MastoAPI 'User' sockets
startMastoUserSocket(store) {
return new Promise((resolve, reject) => {
try {
const { state, commit, dispatch, rootState } = store
const timelineData = rootState.statuses.timelines.friends
const credentials = useOAuthStore().token
const url = getMastodonSocketURI({ credentials })
state.mastoUserSocket = ProcessedWS({
url,
id: 'Unified',
credentials,
})
state.mastoUserSocket.addEventListener(
'pleroma:authenticated',
() => {
state.mastoUserSocket.subscribe('user')
},
)
state.mastoUserSocket.addEventListener(
'message',
({ detail: message }) => {
if (!message) return // pings
if (message.event === 'notification') {
dispatch('addNewNotifications', {
notifications: [message.notification],
older: false,
})
} else if (message.event === 'update') {
dispatch('addNewStatuses', {
statuses: [message.status],
userId: false,
showImmediately: timelineData.visibleStatuses.length === 0,
timeline: 'friends',
})
} else if (message.event === 'status.update') {
dispatch('addNewStatuses', {
statuses: [message.status],
userId: false,
showImmediately:
message.status.id in timelineData.visibleStatusesObject,
timeline: 'friends',
})
} else if (message.event === 'delete') {
dispatch('deleteStatusById', message.id)
} else if (message.event === 'pleroma:chat_update') {
// The setTimeout wrapper is a temporary band-aid to avoid duplicates for the user's own messages when doing optimistic sending.
// The cause of the duplicates is the WS event arriving earlier than the HTTP response.
// This setTimeout wrapper can be removed once the commit `8e41baff` is in the stable Pleroma release.
// (`8e41baff` adds the idempotency key to the chat message entity, which PleromaFE uses when it's available, and it makes this artificial delay unnecessary).
setTimeout(() => {
dispatch('addChatMessages', {
chatId: message.chatUpdate.id,
messages: [message.chatUpdate.lastMessage],
})
dispatch('updateChat', { chat: message.chatUpdate })
maybeShowChatNotification(store, message.chatUpdate)
}, 100)
}
},
)
state.mastoUserSocket.addEventListener('open', () => {
// Do not show notification when we just opened up the page
if (
state.mastoUserSocketStatus !==
WSConnectionStatus.STARTING_INITIAL
) {
useInterfaceStore().pushGlobalNotice({
level: 'success',
messageKey: 'timeline.socket_reconnected',
timeout: 5000,
})
}
// Stop polling if we were errored or disabled
if (
new Set([
WSConnectionStatus.ERROR,
WSConnectionStatus.DISABLED,
]).has(state.mastoUserSocketStatus)
) {
dispatch('stopFetchingTimeline', { timeline: 'friends' })
dispatch('stopFetchingNotifications')
- dispatch('stopFetchingChats')
+ useChatsStore().stopFetchingChats()
}
commit('resetRetryMultiplier')
commit('setMastoUserSocketStatus', WSConnectionStatus.JOINED)
})
state.mastoUserSocket.addEventListener(
'error',
({ detail: error }) => {
console.error('Error in MastoAPI websocket:', error)
// TODO is this needed?
dispatch('clearOpenedChats')
},
)
state.mastoUserSocket.addEventListener(
'close',
({ detail: closeEvent }) => {
const ignoreCodes = new Set([
1000, // Normal (intended) closure
1001, // Going away
])
const { code } = closeEvent
if (ignoreCodes.has(code)) {
console.debug(
`Not restarting socket becasue of closure code ${code} is in ignore list`,
)
commit('setMastoUserSocketStatus', WSConnectionStatus.CLOSED)
} else {
console.warn(
`MastoAPI websocket disconnected, restarting. CloseEvent code: ${code}`,
)
setTimeout(() => {
dispatch('startMastoUserSocket')
}, retryTimeout(state.retryMultiplier))
commit('incrementRetryMultiplier')
if (state.mastoUserSocketStatus !== WSConnectionStatus.ERROR) {
dispatch('startFetchingTimeline', { timeline: 'friends' })
dispatch('startFetchingNotifications')
dispatch('startFetchingChats')
useInterfaceStore().pushGlobalNotice({
level: 'error',
messageKey: 'timeline.socket_broke',
messageArgs: [code],
timeout: 5000,
})
}
commit('setMastoUserSocketStatus', WSConnectionStatus.ERROR)
}
dispatch('clearOpenedChats')
},
)
resolve()
} catch (e) {
reject(e)
}
})
},
stopMastoUserSocket({ state, dispatch }) {
dispatch('startFetchingTimeline', { timeline: 'friends' })
dispatch('startFetchingNotifications')
dispatch('startFetchingChats')
state.mastoUserSocket.close()
},
// Timelines
startFetchingTimeline(
store,
{
timeline = 'friends',
tag = false,
userId = false,
listId = false,
statusId = false,
bookmarkFolderId = false,
},
) {
if (
timeline === 'favourites' &&
!useInstanceCapabilitiesStore().pleromaPublicFavouritesAvailable
)
return
if (store.state.fetchers[timeline]) return
const fetcher = timelineFetcher.startFetching({
timeline,
store,
userId,
listId,
statusId,
bookmarkFolderId,
tag,
credentials: useOAuthStore().token,
})
store.commit('addFetcher', { fetcherName: timeline, fetcher })
},
stopFetchingTimeline(store, timeline) {
const fetcher = store.state.fetchers[timeline]
if (!fetcher) return
store.commit('removeFetcher', { fetcherName: timeline, fetcher })
},
fetchTimeline(store, { timeline, ...rest }) {
fetchTimeline({
store,
timeline,
...rest,
credentials: useOAuthStore().token,
})
},
// Notifications
startFetchingNotifications(store) {
if (store.state.fetchers.notifications) return
const fetcher = notificationsFetcher.startFetching({
store,
credentials: useOAuthStore().token,
})
store.commit('addFetcher', { fetcherName: 'notifications', fetcher })
},
stopFetchingNotifications(store) {
const fetcher = store.state.fetchers.notifications
if (!fetcher) return
store.commit('removeFetcher', { fetcherName: 'notifications', fetcher })
},
// Follow requests
startFetchingFollowRequests(store) {
if (store.state.fetchers.followRequests) return
const fetcher = followRequestFetcher.startFetching({
store,
credentials: useOAuthStore().token,
})
store.commit('addFetcher', { fetcherName: 'followRequests', fetcher })
},
stopFetchingFollowRequests(store) {
const fetcher = store.state.fetchers.followRequests
if (!fetcher) return
store.commit('removeFetcher', { fetcherName: 'followRequests', fetcher })
},
// Pleroma websocket
setWsToken(store, token) {
store.commit('setWsToken', token)
},
initializeSocket({ commit, state, rootState }) {
// Set up websocket connection
const token = state.wsToken
if (
useInstanceCapabilitiesStore().shoutAvailable &&
typeof token !== 'undefined' &&
state.socket === null
) {
const socket = new Socket('/socket', { params: { token } })
socket.connect()
commit('setSocket', socket)
useShoutStore().initializeShout(socket)
}
},
disconnectFromSocket({ commit, state }) {
state.socket && state.socket.disconnect()
commit('setSocket', null)
},
},
}
export default api
diff --git a/src/modules/chats.js b/src/modules/chats.js
deleted file mode 100644
index abc035f092..0000000000
--- a/src/modules/chats.js
+++ /dev/null
@@ -1,277 +0,0 @@
-import { find, omitBy, orderBy, sumBy } from 'lodash'
-import { reactive } from 'vue'
-
-import chatService from '../services/chat_service/chat_service.js'
-import { maybeShowChatNotification } from '../services/chat_utils/chat_utils.js'
-import {
- parseChat,
- parseChatMessage,
-} from '../services/entity_normalizer/entity_normalizer.service.js'
-import { promiseInterval } from '../services/promise_interval/promise_interval.js'
-
-import { useOAuthStore } from 'src/stores/oauth.js'
-
-import { chats, deleteChatMessage, readChat } from 'src/api/chats.js'
-
-const emptyChatList = () => ({
- data: [],
- idStore: {},
-})
-
-const defaultState = {
- chatList: emptyChatList(),
- chatListFetcher: null,
- openedChats: reactive({}),
- openedChatMessageServices: reactive({}),
- fetcher: undefined,
- currentChatId: null,
- lastReadMessageId: null,
-}
-
-const getChatById = (state, id) => {
- return find(state.chatList.data, { id })
-}
-
-const sortedChatList = (state) => {
- return orderBy(state.chatList.data, ['updated_at'], ['desc'])
-}
-
-const unreadChatCount = (state) => {
- return sumBy(state.chatList.data, 'unread')
-}
-
-const chatsModule = {
- state: { ...defaultState },
- getters: {
- currentChat: (state) => state.openedChats[state.currentChatId],
- currentChatMessageService: (state) =>
- state.openedChatMessageServices[state.currentChatId],
- findOpenedChatByRecipientId: (state) => (recipientId) =>
- find(state.openedChats, (c) => c.account.id === recipientId),
- sortedChatList,
- unreadChatCount,
- },
- actions: {
- // Chat list
- startFetchingChats({ dispatch, commit }) {
- const fetcher = () => dispatch('fetchChats', { latest: true })
- commit('setChatListFetcher', {
- fetcher: () => promiseInterval(fetcher, 5000),
- })
- },
- stopFetchingChats({ commit }) {
- commit('setChatListFetcher', { fetcher: undefined })
- },
- fetchChats({ dispatch, rootState }) {
- return chats({
- credentials: useOAuthStore().token,
- }).then(({ chatList }) => {
- dispatch('addNewChats', { chats: chatList })
- return chats
- })
- },
- addNewChats(store, { chats }) {
- const { commit, dispatch, rootGetters } = store
- const newChatMessageSideEffects = (chat) => {
- maybeShowChatNotification(store, chat)
- }
- commit(
- 'addNewUsers',
- chats.map((k) => k.account).filter((k) => k),
- )
- commit('addNewChats', {
- dispatch,
- chats,
- rootGetters,
- newChatMessageSideEffects,
- })
- },
- updateChat({ commit }, { chat }) {
- commit('updateChat', { chat })
- },
-
- // Opened Chats
- startFetchingCurrentChat({ dispatch }, { fetcher }) {
- dispatch('setCurrentChatFetcher', { fetcher })
- },
- setCurrentChatFetcher({ commit }, { fetcher }) {
- commit('setCurrentChatFetcher', { fetcher })
- },
- addOpenedChat({ commit, dispatch }, { chat }) {
- commit('addOpenedChat', { dispatch, chat: parseChat(chat) })
- dispatch('addNewUsers', [chat.account])
- },
- addChatMessages({ commit }, value) {
- commit('addChatMessages', { commit, ...value })
- },
- resetChatNewMessageCount({ commit }, value) {
- commit('resetChatNewMessageCount', value)
- },
- clearCurrentChat({ commit }) {
- commit('setCurrentChatId', { chatId: undefined })
- commit('setCurrentChatFetcher', { fetcher: undefined })
- },
- readChat({ rootState, commit, dispatch }, { id, lastReadId }) {
- const isNewMessage = rootState.chats.lastReadMessageId !== lastReadId
-
- dispatch('resetChatNewMessageCount')
- commit('readChat', { id, lastReadId })
-
- if (isNewMessage) {
- readChat({
- id,
- lastReadId,
- credentials: useOAuthStore().token,
- })
- }
- },
- deleteChatMessage({ rootState, commit }, value) {
- deleteChatMessage({
- ...value,
- credentials: useOAuthStore().token,
- })
- commit('deleteChatMessage', { commit, ...value })
- },
- resetChats({ commit, dispatch }) {
- dispatch('clearCurrentChat')
- commit('resetChats', { commit })
- },
- clearOpenedChats({ commit }) {
- commit('clearOpenedChats', { commit })
- },
- handleMessageError({ commit }, value) {
- commit('handleMessageError', { commit, ...value })
- },
- cullOlderMessages({ commit }, chatId) {
- commit('cullOlderMessages', chatId)
- },
- },
- mutations: {
- setChatListFetcher(state, { fetcher }) {
- const prevFetcher = state.chatListFetcher
- if (prevFetcher) {
- prevFetcher.stop()
- }
- state.chatListFetcher = fetcher && fetcher()
- },
- setCurrentChatFetcher(state, { fetcher }) {
- const prevFetcher = state.fetcher
- if (prevFetcher) {
- prevFetcher.stop()
- }
- state.fetcher = fetcher && fetcher()
- },
- addOpenedChat(state, { chat }) {
- state.currentChatId = chat.id
- state.openedChats[chat.id] = chat
-
- if (!state.openedChatMessageServices[chat.id]) {
- state.openedChatMessageServices[chat.id] = chatService.empty(chat.id)
- }
- },
- setCurrentChatId(state, { chatId }) {
- state.currentChatId = chatId
- },
- addNewChats(state, { chats, newChatMessageSideEffects }) {
- chats.forEach((updatedChat) => {
- const chat = getChatById(state, updatedChat.id)
-
- if (chat) {
- const isNewMessage =
- (chat.lastMessage && chat.lastMessage.id) !==
- (updatedChat.lastMessage && updatedChat.lastMessage.id)
- chat.lastMessage = updatedChat.lastMessage
- chat.unread = updatedChat.unread
- chat.updated_at = updatedChat.updated_at
- if (isNewMessage && chat.unread) {
- newChatMessageSideEffects(updatedChat)
- }
- } else {
- state.chatList.data.push(updatedChat)
- state.chatList.idStore[updatedChat.id] = updatedChat
- }
- })
- },
- updateChat(state, { chat: updatedChat }) {
- const chat = getChatById(state, updatedChat.id)
- if (chat) {
- chat.lastMessage = updatedChat.lastMessage
- chat.unread = updatedChat.unread
- chat.updated_at = updatedChat.updated_at
- }
- if (!chat) {
- state.chatList.data.unshift(updatedChat)
- }
- state.chatList.idStore[updatedChat.id] = updatedChat
- },
- deleteChat(state, { id }) {
- state.chats.data = state.chats.data.filter(
- (conversation) => conversation.last_status.id !== id,
- )
- state.chats.idStore = omitBy(
- state.chats.idStore,
- (conversation) => conversation.last_status.id === id,
- )
- },
- resetChats(state, { commit }) {
- state.chatList = emptyChatList()
- state.currentChatId = null
- commit('setChatListFetcher', { fetcher: undefined })
- for (const chatId in state.openedChats) {
- chatService.clear(state.openedChatMessageServices[chatId])
- delete state.openedChats[chatId]
- delete state.openedChatMessageServices[chatId]
- }
- },
- setChatsLoading(state, { value }) {
- state.chats.loading = value
- },
- addChatMessages(state, { chatId, messages, updateMaxId }) {
- const chatMessageService = state.openedChatMessageServices[chatId]
- if (chatMessageService) {
- chatService.add(chatMessageService, {
- messages: messages.map(parseChatMessage),
- updateMaxId,
- })
- }
- },
- deleteChatMessage(state, { chatId, messageId }) {
- const chatMessageService = state.openedChatMessageServices[chatId]
- if (chatMessageService) {
- chatService.deleteMessage(chatMessageService, messageId)
- }
- },
- resetChatNewMessageCount(state) {
- const chatMessageService =
- state.openedChatMessageServices[state.currentChatId]
- chatService.resetNewMessageCount(chatMessageService)
- },
- // Used when a connection loss occurs
- clearOpenedChats(state) {
- const currentChatId = state.currentChatId
- for (const chatId in state.openedChats) {
- if (currentChatId !== chatId) {
- chatService.clear(state.openedChatMessageServices[chatId])
- delete state.openedChats[chatId]
- delete state.openedChatMessageServices[chatId]
- }
- }
- },
- readChat(state, { id, lastReadId }) {
- state.lastReadMessageId = lastReadId
- const chat = getChatById(state, id)
- if (chat) {
- chat.unread = 0
- }
- },
- handleMessageError(state, { chatId, fakeId, isRetry }) {
- const chatMessageService = state.openedChatMessageServices[chatId]
- chatService.handleMessageError(chatMessageService, fakeId, isRetry)
- },
- cullOlderMessages(state, chatId) {
- chatService.cullOlderMessages(state.openedChatMessageServices[chatId])
- },
- },
-}
-
-export default chatsModule
diff --git a/src/modules/default_config_state.js b/src/modules/default_config_state.js
index d9a2ba2479..9935e88ce4 100644
--- a/src/modules/default_config_state.js
+++ b/src/modules/default_config_state.js
@@ -1,835 +1,840 @@
import { get } from 'lodash'
const browserLocale = (navigator.language || 'en').split('-')[0]
export const convertDefinitions = (definitions) =>
Object.fromEntries(
Object.entries(definitions).map(([k, v]) => {
const defaultValue = v.default ?? null
return [k, defaultValue]
}),
)
/// Instance config entries provided by static config or pleroma api
/// Put settings here only if it does not make sense for a normal user
/// to override it.
export const INSTANCE_IDENTITY_DEFAULT_DEFINITIONS = {
style: {
description: 'Instance default style name',
type: 'string',
required: false,
},
palette: {
description: 'Instance default palette name',
type: 'string',
required: false,
},
theme: {
description: 'Instance default theme name',
type: 'string',
required: false,
},
defaultAvatar: {
description: "Default avatar image to use when user doesn't have one set",
type: 'string',
default: '/images/avi.png',
},
defaultBanner: {
description: "Default banner image to use when user doesn't have one set",
type: 'string',
default: '/images/banner.png',
},
background: {
description: 'Instance background/wallpaper',
type: 'string',
default: '/static/aurora_borealis.jpg',
},
embeddedToS: {
description: 'Whether to show Terms of Service title bar',
type: 'boolean',
default: true,
},
logo: {
description: 'Instance logo',
type: 'string',
default: '/static/logo.svg',
},
logoMargin: {
description: 'Margin for logo (spacing above/below)',
type: 'string',
default: '.2em',
},
logoMask: {
description:
'Use logo as a mask (works well for monochrome/transparent logos)',
type: 'boolean',
default: true,
},
logoLeft: {
description: 'Show logo on the left side of navbar',
type: 'boolean',
default: false,
},
redirectRootLogin: {
description: 'Where to redirect user after login',
type: 'string',
default: '/main/friends',
},
redirectRootNoLogin: {
description: 'Where to redirect anonymous visitors',
type: 'string',
default: '/main/all',
},
hideSitename: {
description: 'Hide the instance name in navbar',
type: 'boolean',
default: false,
},
nsfwCensorImage: {
description: 'Default NSFW censor image',
type: 'string',
required: false,
},
showFeaturesPanel: {
description: 'Show features panel to anonymous visitors',
type: 'boolean',
default: true,
},
showInstanceSpecificPanel: {
description: 'Show instance-specific panel',
type: 'boolean',
default: false,
},
// Html stuff
instanceSpecificPanelContent: {
description: 'HTML of Instance-specific panel',
type: 'string',
required: false,
},
tos: {
description: 'HTML of Terms of Service panel',
type: 'string',
required: false,
},
name: {
description: 'Instance Name',
type: 'string',
required: false,
},
}
export const INSTANCE_IDENTITY_DEFAULT = convertDefinitions(
INSTANCE_IDENTITY_DEFAULT_DEFINITIONS,
)
export const INSTANCE_IDENTIY_EXTERNAL = new Set([
'tos',
'instanceSpecificPanelContent',
])
/// This object contains setting entries that makes sense
/// at the user level. The defaults can also be overriden by
/// instance admins in the frontend_configuration endpoint or static config.
export const INSTANCE_DEFAULT_CONFIG_DEFINITIONS = {
expertLevel: {
description:
'Used to track which settings to show and hide in settings modal',
type: 'number', // not a boolean so we could potentially make multiple levels of expert-ness
default: 0,
},
hideISP: {
description: 'Hide Instance-specific panel',
default: false,
},
allowForeignUserBackground: {
description: "Allow other user's profiles to override wallpaper",
default: true,
},
hideInstanceWallpaper: {
description: 'Hide Instance default background',
default: false,
},
hideShoutbox: {
description: 'Hide shoutbox if present',
default: false,
},
hideMutedPosts: {
// bad name
description: 'Hide posts of muted users entirely',
default: false,
},
hideMutedThreads: {
description: 'Hide muted threads entirely',
default: true,
},
hideWordFilteredPosts: {
description: 'Hide wordfiltered posts entirely',
default: false,
},
muteBotStatuses: {
description: 'Mute posts made by bots',
default: false,
},
muteSensitiveStatuses: {
description: 'Mute posts marked as NSFW',
default: false,
},
collapseMessageWithSubject: {
description: 'Collapse posts with subject',
default: false,
},
padEmoji: {
description: 'Pad emoji with spaces when using emoji picker',
default: true,
},
hideAttachmentsInConv: {
description: 'Hide attachments',
default: false,
},
hideScrobbles: {
description: 'Hide scrobbles',
default: false,
},
hideScrobblesAfter: {
description: 'Hide scrobbles older than',
default: '2d',
},
maxThumbnails: {
description: 'Maximum attachments to show',
default: 16,
},
loopVideo: {
description: 'Loop videos',
default: true,
},
loopVideoSilentOnly: {
description: 'Loop only videos without sound',
default: true,
},
/// This is not the streaming API configuration, but rather an option
/// for automatically loading new posts into the timeline without
/// the user clicking the Show New button.
streaming: {
description: 'Automatically show new posts',
default: false,
},
pauseOnUnfocused: {
description: 'Pause showing new posts when tab is unfocused',
default: true,
},
emojiReactionsOnTimeline: {
description: 'Show emoji reactions on timeline',
default: true,
},
alwaysShowNewPostButton: {
description: 'Always show mobile "new post" button, even in desktop mode',
default: false,
},
autohideFloatingPostButton: {
description:
'Automatically hide mobile "new post" button when scrolling down',
default: false,
},
stopGifs: {
description: 'Play animated gifs on hover only',
default: true,
},
nonSquareEmoji: {
description: 'Allow emoji to be non-square (max 3:1 aspect)',
default: true,
},
pauseMfm: {
description: 'Pause MFM animations',
default: true,
},
scaleMfm: {
description: 'Scale MFM animation with emoji size',
default: false,
},
replyVisibility: {
description: 'Type of replies to show',
default: 'all',
},
thirdColumnMode: {
description: 'What to display in third column',
default: 'notifications',
},
notificationVisibility: {
description: 'What types of notifications to show',
default: {
follows: true,
mentions: true,
statuses: true,
likes: true,
repeats: true,
moves: true,
emojiReactions: true,
followRequest: true,
reports: true,
chatMention: true,
polls: true,
},
},
notificationNative: {
description: 'What type of notifications to show desktop notification for',
default: {
follows: true,
mentions: true,
statuses: true,
likes: false,
repeats: false,
moves: false,
emojiReactions: false,
followRequest: true,
reports: true,
chatMention: true,
polls: true,
},
},
webPushNotifications: {
description: 'Use WebPush',
default: false,
},
webPushAlwaysShowNotifications: {
description: 'Ignore filter when using WebPush',
default: false,
},
interfaceLanguage: {
description: 'UI language',
default: [browserLocale],
},
hideScopeNotice: {
description: 'Hide scope notification',
default: false,
},
scopeCopy: {
description: 'Copy scope like mastodon does',
default: true,
},
subjectLineBehavior: {
description: 'How to treat subject line',
default: 'email',
},
alwaysShowSubjectInput: {
description: 'Always show subject line field',
default: true,
},
minimalScopesMode: {
description: 'Minimize amount of options shown in scope selector',
default: false,
},
// This hides statuses filtered via a word filter
hideFilteredStatuses: {
description: 'Hide wordfiltered entirely',
default: false,
},
// Confirmations
modalOnRepeat: {
description: 'Show confirmation modal for repeat',
default: false,
},
modalOnUnfollow: {
description: 'Show confirmation modal for unfollow',
default: false,
},
modalOnBlock: {
description: 'Show confirmation modal for block',
default: true,
},
modalOnMute: {
description: 'Show confirmation modal for mute',
default: false,
},
modalOnMuteConversation: {
description: 'Show confirmation modal for mute conversation',
default: false,
},
modalOnMuteDomain: {
description: 'Show confirmation modal for mute domain',
default: true,
},
modalOnDelete: {
description: 'Show confirmation modal for delete',
default: true,
},
modalOnLogout: {
description: 'Show confirmation modal for logout',
default: true,
},
modalOnApproveFollow: {
description: 'Show confirmation modal for approve follow',
default: false,
},
modalOnDenyFollow: {
description: 'Show confirmation modal for deny follow',
default: false,
},
modalOnRemoveUserFromFollowers: {
description: 'Show confirmation modal for follower removal',
default: false,
},
// Expiry confirmations/default actions
onMuteDefaultAction: {
description: 'Default action when muting user',
default: 'ask',
},
onBlockDefaultAction: {
description: 'Default action when blocking user',
default: 'ask',
},
modalMobileCenter: {
description: 'Center mobile dialogs vertically',
default: false,
},
playVideosInModal: {
description: 'Play videos in gallery view',
default: false,
},
useContainFit: {
description: 'Use object-fit: contain for attachments',
default: true,
},
disableStickyHeaders: {
description: 'Disable sticky headers',
default: false,
},
showScrollbars: {
description: 'Always show scrollbars',
default: false,
},
userPopoverAvatarAction: {
description: 'What to do when clicking popover avatar',
default: 'open',
},
userPopoverOverlay: {
description: 'Overlay user popover with centering on avatar',
default: false,
},
userCardLeftJustify: {
description: 'Justify user bio to the left',
default: false,
},
userCardHidePersonalMarks: {
description: 'Hide highlight/personal note in user view',
default: false,
},
forcedRoundness: {
description: 'Force roundness of the theme',
default: -1,
},
greentext: {
description: 'Highlight plaintext >quotes',
default: false,
},
mentionLinkShowTooltip: {
description: 'Show tooltips for mention links',
default: true,
},
mentionLinkShowAvatar: {
description: 'Show avatar next to mention link',
default: false,
},
mentionLinkFadeDomain: {
description:
'Mute (fade) domain name in mention links if configured to show it',
default: true,
},
mentionLinkShowYous: {
description: 'Show (you)s when you are mentioned',
default: false,
},
mentionLinkBoldenYou: {
description: 'Boldern mentionlink of you',
default: true,
},
hidePostStats: {
description: 'Hide post stats (rt, favs)',
default: false,
},
hideBotIndication: {
description: 'Hide bot indicator',
default: false,
},
hideUserStats: {
description: 'Hide user stats (followers etc)',
default: false,
},
virtualScrolling: {
description: 'Timeline virtual scrolling',
default: true,
},
sensitiveByDefault: {
description: 'Assume attachments are NSFW by default',
default: false,
},
conversationDisplay: {
description: 'Style of conversation display',
default: 'linear',
},
conversationTreeAdvanced: {
description: 'Advanced features of tree view conversation',
default: false,
},
conversationOtherRepliesButton: {
description: 'Where to show "other replies" in tree conversation view',
default: 'below',
},
conversationTreeFadeAncestors: {
description: 'Fade ancestors in tree conversation view',
default: false,
},
showExtraNotifications: {
description:
'Show extra notifications (chats, announcements etc) in notification panel',
default: true,
},
showExtraNotificationsTip: {
description: 'Show tip for extra notifications (that user can remove them)',
default: true,
},
showChatsInExtraNotifications: {
description: 'Show chat messages in notifications',
default: true,
},
showAnnouncementsInExtraNotifications: {
description: 'Show announcements in notifications',
default: true,
},
showFollowRequestsInExtraNotifications: {
description: 'Show follow requests in notifications',
default: true,
},
maxDepthInThread: {
description: 'Maximum depth in tree conversation view',
default: 6,
},
autocompleteSelect: {
description: '',
default: false,
},
closingDrawerMarksAsSeen: {
description: 'Closing mobile notification pane marks everything as seen',
default: true,
},
unseenAtTop: {
description: 'Show unseen notifications above others',
default: false,
},
ignoreInactionableSeen: {
description: 'Treat inactionable (fav, rt etc) notifications as "seen"',
default: false,
},
unsavedPostAction: {
description: 'What to do if post is aborted',
default: 'confirm',
},
autoSaveDraft: {
description: 'Save drafts automatically',
default: false,
},
useAbsoluteTimeFormat: {
description: 'Use absolute time format',
default: false,
},
absoluteTimeFormatMinAge: {
description: 'Show absolute time format only after this post age',
default: '0d',
},
absoluteTime12h: {
description: 'Use 24h time format',
default: '24h',
},
themeChecksum: {
description: 'Checksum of theme used',
type: 'string',
required: false,
},
highlights: {
description: 'User highlights',
type: 'object',
required: false,
default: {},
},
underlay: {
description: 'Underlay override',
required: true,
default: 'none',
},
compactProfiles: {
description: 'Reduce profile height on user pages',
default: false,
},
}
export const INSTANCE_DEFAULT_CONFIG = convertDefinitions(
INSTANCE_DEFAULT_CONFIG_DEFINITIONS,
)
export const LOCAL_DEFAULT_CONFIG_DEFINITIONS = {
// TODO these two used to be separate but since separation feature got broken it doesn't matter
hideAttachments: {
description: 'Hide attachments in timeline',
default: false,
},
hideAttachmentsInConv: {
description: 'Hide attachments in coversation',
default: false,
},
hideNsfw: {
description: 'Hide nsfw posts',
default: true,
},
useOneClickNsfw: {
description: 'Open NSFW images directly in media modal',
default: false,
},
preloadImage: {
description: 'Preload images for NSFW',
default: true,
},
postContentType: {
description: 'Default post content type',
default: 'text/plain',
},
sidebarRight: {
description: 'Reverse order of columns',
default: false,
},
sidebarColumnWidth: {
description: 'Sidebar column width',
default: '25rem',
},
contentColumnWidth: {
description: 'Middle column width',
default: '45rem',
},
notifsColumnWidth: {
description: 'Notifications column width',
default: '25rem',
},
themeEditorMinWidth: {
description: 'Hack for theme editor on mobile',
default: '0rem',
},
emojiReactionsScale: {
description: 'Emoji reactions scale factor',
default: 0.5,
},
textSize: {
description: 'Font size',
default: '1rem',
},
emojiSize: {
description: 'Emoji size',
default: '2.2rem',
},
navbarSize: {
description: 'Navbar size',
default: '3.5rem',
},
panelHeaderSize: {
description: 'Panel header size',
default: '3.2rem',
},
navbarColumnStretch: {
description: 'Stretch navbar to match columns width',
default: false,
},
mentionLinkDisplay: {
description: 'How to display mention links',
default: 'short',
},
imageCompression: {
description: 'Image compression (WebP/JPEG)',
default: true,
},
alwaysUseJpeg: {
description: 'Compress images using JPEG only',
default: false,
},
useStreamingApi: {
description: 'Streaming API (WebSocket)',
default: false,
},
fontInterface: {
description: 'Interface font override',
type: 'string',
default: null,
},
fontInput: {
description: 'Input font override',
type: 'string',
default: null,
},
fontPosts: {
description: 'Post font override',
type: 'string',
default: null,
},
fontMonospace: {
description: 'Monospace font override',
type: 'string',
default: null,
},
+ chatSubmitOnEnter: {
+ description: 'Post status on enter key in chats and chat view',
+ type: 'boolean',
+ default: false,
+ },
themeDebug: {
description:
'Debug mode that uses computed backgrounds instead of real ones to debug contrast functions',
default: false,
},
forceThemeRecompilation: {
description: 'Flag that forces recompilation on boot even if cache exists',
default: false,
},
}
export const LOCAL_DEFAULT_CONFIG = convertDefinitions(
LOCAL_DEFAULT_CONFIG_DEFINITIONS,
)
export const LOCAL_ONLY_KEYS = new Set(Object.keys(LOCAL_DEFAULT_CONFIG))
export const SYNC_DEFAULT_CONFIG_DEFINITIONS = {
dontShowUpdateNotifs: {
description: 'Never show update notification (pleroma-tan)',
default: false,
},
collapseNav: {
description: 'Collapse navigation panel to header only',
default: false,
},
muteFilters: {
description: 'Object containing mute filters',
type: 'object',
default: {},
},
}
export const SYNC_DEFAULT_CONFIG = convertDefinitions(
SYNC_DEFAULT_CONFIG_DEFINITIONS,
)
export const SYNC_ONLY_KEYS = new Set(Object.keys(SYNC_DEFAULT_CONFIG))
export const THEME_CONFIG_DEFINITIONS = {
theme: {
description: 'Very old theme store, stores preset name, still in use',
default: null,
},
colors: {
description:
'VERY old theme store, just colors of V1, probably not even used anymore',
default: {},
},
// V2
customTheme: {
description:
'"Snapshot", previously was used as actual theme store for V2 so it\'s still used in case of PleromaFE downgrade event.',
default: null,
},
customThemeSource: {
description: '"Source", stores original theme data',
default: null,
},
// V3
style: {
description: 'Style name for builtins',
default: null,
},
styleCustomData: {
description: 'Custom style data (i.e. not builtin)',
default: null,
},
palette: {
description: 'Palette name for builtins',
default: null,
},
paletteCustomData: {
description: 'Custom palette data (i.e. not builtin)',
default: null,
},
}
export const THEME_CONFIG = convertDefinitions(THEME_CONFIG_DEFINITIONS)
export const makeUndefined = (c) =>
Object.fromEntries(Object.keys(c).map((key) => [key, undefined]))
/// For properties with special processing or properties that does not
/// make sense to be overriden on a instance-wide level.
export const ROOT_CONFIG = {
// Set these to undefined so it does not interfere with default settings check
...INSTANCE_DEFAULT_CONFIG,
...LOCAL_DEFAULT_CONFIG,
...SYNC_DEFAULT_CONFIG,
...THEME_CONFIG,
}
export const ROOT_CONFIG_DEFINITIONS = {
...INSTANCE_DEFAULT_CONFIG_DEFINITIONS,
...LOCAL_DEFAULT_CONFIG_DEFINITIONS,
...SYNC_DEFAULT_CONFIG_DEFINITIONS,
...THEME_CONFIG_DEFINITIONS,
}
export const validateSetting = ({
value,
path: fullPath,
definition,
throwError,
defaultState,
validateObjects = true,
}) => {
if (value === undefined) return undefined // only null is allowed as missing value
if (definition === undefined) return undefined // invalid definition
const path = fullPath.replace(/^simple./, '')
const depth = path.split('.')
if (
validateObjects &&
definition.type === 'object' &&
path.split('.').length <= 1
) {
console.error(
`attempt to set object ${fullPath} instead of its children. ignoring.`,
)
return undefined
}
if (get(defaultState, path.split('.')[0]) === undefined) {
const string = `Unknown option ${fullPath}, value: ${value}`
if (throwError) {
throw new Error(string)
} else {
console.error(string)
return undefined
}
}
let { required, type, default: defaultValue } = definition
if (type == null && defaultValue != null) {
type = typeof defaultValue
}
if (required && value == null) {
const string = `Value required for setting ${path} but was provided nullish; defaulting`
if (throwError) {
throw new Error(string)
} else {
console.error(string)
return defaultValue
}
}
if (depth > 2 && value !== null && type != null && typeof value !== type) {
const string = `Invalid type for setting ${path}: expected type ${type}, got ${typeof value}, value ${value}; defaulting`
if (throwError) {
throw new Error(string)
} else {
console.error(string)
return defaultValue
}
}
return value
}
diff --git a/src/modules/index.js b/src/modules/index.js
index e42260c06f..c8f3dce39c 100644
--- a/src/modules/index.js
+++ b/src/modules/index.js
@@ -1,17 +1,15 @@
import api from './api.js'
-import chats from './chats.js'
import drafts from './drafts.js'
import notifications from './notifications.js'
import profileConfig from './profileConfig.js'
import statuses from './statuses.js'
import users from './users.js'
export default {
statuses,
notifications,
users,
api,
profileConfig,
drafts,
- chats,
}
diff --git a/src/modules/users.js b/src/modules/users.js
index 38eb6032ce..8777f18da0 100644
--- a/src/modules/users.js
+++ b/src/modules/users.js
@@ -1,878 +1,879 @@
import Cookies from 'js-cookie'
import {
compact,
concat,
each,
isArray,
last,
map,
mergeWith,
uniq,
} from 'lodash'
import {
registerPushNotifications,
unregisterPushNotifications,
} from '../services/sw/sw.js'
import {
windowHeight,
windowWidth,
} from '../services/window_utils/window_utils'
import { useAnnouncementsStore } from 'src/stores/announcements.js'
import { useBookmarkFoldersStore } from 'src/stores/bookmark_folders.js'
+import { useChatsStore } from 'src/stores/chats.js'
import { useEmojiStore } from 'src/stores/emoji.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
import { useInterfaceStore } from 'src/stores/interface.js'
import { useListsStore } from 'src/stores/lists.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useOAuthStore } from 'src/stores/oauth.js'
import { useSyncConfigStore } from 'src/stores/sync_config.js'
import { useUserHighlightStore } from 'src/stores/user_highlight.js'
import { revokeToken } from 'src/api/oauth.js'
import {
fetchFollowers,
fetchFriends,
fetchUser,
fetchUserByName,
getCaptcha,
register,
searchUsers,
verifyCredentials,
} from 'src/api/public.js'
import {
blockUser as apiBlockUser,
editUserNote as apiEditUserNote,
muteUser as apiMuteUser,
unblockUser as apiUnblockUser,
unmuteUser as apiUnmuteUser,
fetchBlocks,
fetchDomainMutes,
fetchMutes,
fetchUserInLists,
fetchUserRelationship,
followUser,
} from 'src/api/user.js'
// TODO: Unify with mergeOrAdd in statuses.js
export const mergeOrAdd = (arr, obj, item) => {
if (!item) {
return false
}
const oldItem = obj[item.id]
if (oldItem) {
// We already have this, so only merge the new info.
mergeWith(oldItem, item, mergeArrayLength)
return { item: oldItem, new: false }
} else {
// This is a new item, prepare it
arr.push(item)
obj[item.id] = item
return { item, new: true }
}
}
const mergeArrayLength = (oldValue, newValue) => {
if (isArray(oldValue) && isArray(newValue)) {
oldValue.length = newValue.length
return mergeWith(oldValue, newValue, mergeArrayLength)
}
}
const getNotificationPermission = () => {
const Notification = window.Notification
if (!Notification) return Promise.resolve(null)
if (Notification.permission === 'default')
return Notification.requestPermission()
return Promise.resolve(Notification.permission)
}
const blockUser = (store, args) => {
const id = args.id
const expiresIn = typeof args === 'object' ? args.expiresIn : 0
const predictedRelationship = store.state.relationships[id] || { id }
store.commit('updateUserRelationship', [predictedRelationship])
store.commit('addBlockId', id)
return apiBlockUser({ id, expiresIn }).then(({ data: relationship }) => {
store.commit('updateUserRelationship', [relationship])
store.commit('addBlockId', id)
store.commit('removeStatus', { timeline: 'friends', userId: id })
store.commit('removeStatus', { timeline: 'public', userId: id })
store.commit('removeStatus', {
timeline: 'publicAndExternal',
userId: id,
})
})
}
const unblockUser = (store, id) => {
return apiUnblockUser({ id }).then(({ data: relationship }) =>
store.commit('updateUserRelationship', [relationship]),
)
}
const removeUserFromFollowers = (store, id) => {
return removeUserFromFollowers({ id }).then((relationship) =>
store.commit('updateUserRelationship', [relationship]),
)
}
const editUserNote = (store, { id, comment }) => {
return apiEditUserNote({ id, comment }).then((relationship) =>
store.commit('updateUserRelationship', [relationship]),
)
}
const muteUser = (store, args) => {
const id = typeof args === 'object' ? args.id : args
const expiresIn = typeof args === 'object' ? args.expiresIn : 0
const predictedRelationship = store.state.relationships[id] || { id }
store.commit('updateUserRelationship', [predictedRelationship])
store.commit('addMuteId', id)
return apiMuteUser({
id,
expiresIn,
credentials: useOAuthStore().token,
}).then(({ data: relationship }) => {
store.commit('updateUserRelationship', [relationship])
store.commit('addMuteId', id)
})
}
const unmuteUser = (store, id) => {
const predictedRelationship = store.state.relationships[id] || { id }
predictedRelationship.muting = false
store.commit('updateUserRelationship', [predictedRelationship])
return apiUnmuteUser({ id }).then(({ data: relationship }) =>
store.commit('updateUserRelationship', [relationship]),
)
}
const hideReblogs = (store, userId) => {
return followUser({
id: userId,
reblogs: false,
credentials: useOAuthStore().token,
}).then(({ data: relationship }) =>
store.commit('updateUserRelationship', [relationship]),
)
}
const showReblogs = (store, userId) => {
return followUser({
id: userId,
reblogs: true,
credentials: useOAuthStore().token,
}).then(({ data: relationship }) =>
store.commit('updateUserRelationship', [relationship]),
)
}
const muteDomain = (store, domain) => {
return muteDomain({
domain,
credentials: useOAuthStore().token,
}).then(() => store.commit('addDomainMute', domain))
}
const unmuteDomain = (store, domain) => {
return unmuteDomain({
domain,
credentials: useOAuthStore().token,
}).then(() => store.commit('removeDomainMute', domain))
}
export const mutations = {
tagUser(state, { user: { id }, tag }) {
const user = state.usersObject[id]
user.tags.add(tag)
},
untagUser(state, { user: { id }, tag }) {
const user = state.usersObject[id]
user.tags.delete(tag)
},
updateRight(state, { user: { id }, right, value }) {
const user = state.usersObject[id]
const newRights = user.rights
newRights[right] = value
user.rights = newRights
},
updateUserAdminData(state, { user }) {
const { id } = user
const localUser = state.usersObject[id]
localUser.adminData = user
localUser.deactivated = !user.is_active
localUser.tags = new Set(user.tags)
},
setCurrentUser(state, user) {
state.lastLoginName = user.screen_name
state.currentUser = mergeWith(
state.currentUser || {},
user,
mergeArrayLength,
)
},
clearCurrentUser(state) {
state.currentUser = false
state.lastLoginName = false
},
beginLogin(state) {
state.loggingIn = true
},
endLogin(state) {
state.loggingIn = false
},
saveFriendIds(state, { id, friendIds }) {
const user = state.usersObject[id]
user.friendIds = uniq(concat(user.friendIds || [], friendIds))
},
saveFollowerIds(state, { id, followerIds }) {
const user = state.usersObject[id]
user.followerIds = uniq(concat(user.followerIds || [], followerIds))
},
// Because frontend doesn't have a reason to keep these stuff in memory
// outside of viewing someones user profile.
clearFriends(state, userId) {
const user = state.usersObject[userId]
if (user) {
user.friendIds = []
}
},
clearFollowers(state, userId) {
const user = state.usersObject[userId]
if (user) {
user.followerIds = []
}
},
addNewUsers(state, users) {
each(users, (user) => {
if (user.relationship) {
state.relationships[user.relationship.id] = user.relationship
}
const res = mergeOrAdd(state.users, state.usersObject, user)
const item = res.item
if (res.new && item.screen_name && !item.screen_name.includes('@')) {
state.usersByNameObject[item.screen_name.toLowerCase()] = item
}
})
},
updateUserRelationship(state, relationships) {
relationships.forEach((relationship) => {
state.relationships[relationship.id] = relationship
})
},
updateUserInLists(state, { id, inLists }) {
state.usersObject[id].inLists = inLists
},
saveBlockIds(state, blockIds) {
state.currentUser.blockIds = blockIds
},
addBlockId(state, blockId) {
if (state.currentUser.blockIds.indexOf(blockId) === -1) {
state.currentUser.blockIds.push(blockId)
}
},
setBlockIdsMaxId(state, blockIdsMaxId) {
state.currentUser.blockIdsMaxId = blockIdsMaxId
},
saveMuteIds(state, muteIds) {
state.currentUser.muteIds = muteIds
},
setMuteIdsMaxId(state, muteIdsMaxId) {
state.currentUser.muteIdsMaxId = muteIdsMaxId
},
addMuteId(state, muteId) {
if (state.currentUser.muteIds.indexOf(muteId) === -1) {
state.currentUser.muteIds.push(muteId)
}
},
saveDomainMutes(state, domainMutes) {
state.currentUser.domainMutes = domainMutes
},
addDomainMute(state, domain) {
if (state.currentUser.domainMutes.indexOf(domain) === -1) {
state.currentUser.domainMutes.push(domain)
}
},
removeDomainMute(state, domain) {
const index = state.currentUser.domainMutes.indexOf(domain)
if (index !== -1) {
state.currentUser.domainMutes.splice(index, 1)
}
},
setPinnedToUser(state, status) {
const user = state.usersObject[status.user.id]
user.pinnedStatusIds = user.pinnedStatusIds || []
const index = user.pinnedStatusIds.indexOf(status.id)
if (status.pinned && index === -1) {
user.pinnedStatusIds.push(status.id)
} else if (!status.pinned && index !== -1) {
user.pinnedStatusIds.splice(index, 1)
}
},
setUserForStatus(state, status) {
status.user = state.usersObject[status.user.id]
},
setUserForNotification(state, notification) {
if (notification.type !== 'follow') {
notification.action.user = state.usersObject[notification.action.user.id]
}
notification.from_profile = state.usersObject[notification.from_profile.id]
},
setColor(state, { user: { id }, highlighted }) {
const user = state.usersObject[id]
user.highlight = highlighted
},
signUpPending(state) {
state.signUpPending = true
state.signUpErrors = []
state.signUpNotice = {}
},
signUpSuccess(state) {
state.signUpPending = false
},
signUpFailure(state, errors) {
state.signUpPending = false
state.signUpErrors = errors
state.signUpNotice = {}
},
signUpNotice(state, notice) {
state.signUpPending = false
state.signUpErrors = []
state.signUpNotice = notice
},
}
export const getters = {
findUser: (state) => (query) => {
return state.usersObject[query]
},
findUserByName: (state) => (query) => {
return state.usersByNameObject[query.toLowerCase()]
},
findUserByUrl: (state) => (query) => {
return state.users.find(
(u) =>
u.statusnet_profile_url &&
u.statusnet_profile_url.toLowerCase() === query.toLowerCase(),
)
},
relationship: (state) => (id) => {
const rel = id && state.relationships[id]
return rel || { id, loading: true }
},
}
export const defaultState = {
loggingIn: false,
lastLoginName: false,
currentUser: false,
users: [],
usersObject: {},
usersByNameObject: {},
signUpPending: false,
signUpErrors: [],
signUpNotice: {},
relationships: {},
}
const users = {
state: defaultState,
mutations,
getters,
actions: {
fetchUserIfMissing(store, id) {
const user = store.getters.findUser(id)
if (!user) {
return store.dispatch('fetchUser', id)
} else {
return Promise.resolve(user)
}
},
updateUserAdminData(store, { userAdminData }) {
return store
.dispatch('fetchUserIfMissing', userAdminData.id)
.then((user) => {
user.adminData = userAdminData
store.commit('addNewUsers', [user])
return user
})
},
fetchUser(store, id) {
return fetchUser({
id,
credentials: useOAuthStore().token,
})
.then(({ data: user }) => {
store.commit('addNewUsers', [user])
return user
})
.catch((error) => {
if (error.statusCode === 404) {
console.warn(`User ${id} not found`)
} else {
throw error
}
})
},
fetchUserByName(store, name) {
return fetchUserByName({
name,
credentials: useOAuthStore().token,
}).then(({ data: user }) => {
store.commit('addNewUsers', [user])
return user
})
},
fetchUserRelationship(store, id) {
if (store.state.currentUser) {
fetchUserRelationship({
id,
credentials: useOAuthStore().token,
}).then(({ data: relationships }) =>
store.commit('updateUserRelationship', relationships),
)
}
},
fetchUserInLists(store, id) {
if (store.state.currentUser) {
fetchUserInLists({
id,
credentials: useOAuthStore().token,
}).then(({ data: inLists }) =>
store.commit('updateUserInLists', { id, inLists }),
)
}
},
fetchBlocks(store, args) {
const { reset } = args || {}
const maxId = store.state.currentUser.blockIdsMaxId
return fetchBlocks({
maxId,
credentials: useOAuthStore().token,
}).then(({ data: blocks }) => {
if (reset) {
store.commit('saveBlockIds', map(blocks, 'id'))
} else {
map(blocks, 'id').map((id) => store.commit('addBlockId', id))
}
if (blocks.length) {
store.commit('setBlockIdsMaxId', last(blocks).id)
}
store.commit('addNewUsers', blocks)
return blocks
})
},
blockUser(store, data) {
return blockUser(store, data)
},
unblockUser(store, data) {
return unblockUser(store, data)
},
removeUserFromFollowers(store, id) {
return removeUserFromFollowers(store, id)
},
blockUsers(store, data = []) {
return Promise.all(data.map((d) => blockUser(store, d)))
},
unblockUsers(store, data = []) {
return Promise.all(data.map((d) => unblockUser(store, d)))
},
editUserNote(store, args) {
return editUserNote(store, args)
},
fetchMutes(store, args) {
const { reset } = args || {}
const maxId = store.state.currentUser.muteIdsMaxId
return fetchMutes({
maxId,
credentials: useOAuthStore().token,
}).then(({ data: mutes }) => {
if (reset) {
store.commit('saveMuteIds', map(mutes, 'id'))
} else {
map(mutes, 'id').map((id) => store.commit('addMuteId', id))
}
if (mutes.length) {
store.commit('setMuteIdsMaxId', last(mutes).id)
}
store.commit('addNewUsers', mutes)
return mutes
})
},
muteUser(store, data) {
return muteUser(store, data)
},
unmuteUser(store, id) {
return unmuteUser(store, id)
},
hideReblogs(store, id) {
return hideReblogs(store, id)
},
showReblogs(store, id) {
return showReblogs(store, id)
},
muteUsers(store, data = []) {
return Promise.all(data.map((d) => muteUser(store, d)))
},
unmuteUsers(store, ids = []) {
return Promise.all(ids.map((d) => unmuteUser(store, d)))
},
fetchDomainMutes(store) {
return fetchDomainMutes({
credentials: useOAuthStore().token,
}).then(({ data: domainMutes }) => {
store.commit('saveDomainMutes', domainMutes)
return domainMutes
})
},
muteDomain(store, domain) {
return muteDomain(store, domain)
},
unmuteDomain(store, domain) {
return unmuteDomain(store, domain)
},
muteDomains(store, domains = []) {
return Promise.all(domains.map((domain) => muteDomain(store, domain)))
},
unmuteDomains(store, domain = []) {
return Promise.all(domain.map((domain) => unmuteDomain(store, domain)))
},
fetchFriends({ rootState, commit }, id) {
const user = rootState.users.usersObject[id]
const maxId = last(user.friendIds)
return fetchFriends({
id,
maxId,
credentials: useOAuthStore().token,
}).then(({ data: friends }) => {
commit('addNewUsers', friends)
commit('saveFriendIds', { id, friendIds: map(friends, 'id') })
return friends
})
},
fetchFollowers({ rootState, commit }, id) {
const user = rootState.users.usersObject[id]
const maxId = last(user.followerIds)
return fetchFollowers({
id,
maxId,
credentials: useOAuthStore().token,
}).then(({ data: followers }) => {
commit('addNewUsers', followers)
commit('saveFollowerIds', { id, followerIds: map(followers, 'id') })
return followers
})
},
clearFriends({ commit }, userId) {
commit('clearFriends', userId)
},
clearFollowers({ commit }, userId) {
commit('clearFollowers', userId)
},
subscribeUser({ rootState, commit }, id) {
return followUser({
id,
notify: true,
credentials: useOAuthStore().token,
}).then(({ data: relationship }) =>
commit('updateUserRelationship', [relationship]),
)
},
unsubscribeUser({ rootState, commit }, id) {
return followUser({
id,
notify: false,
credentials: useOAuthStore().token,
}).then(({ data: relationship }) =>
commit('updateUserRelationship', [relationship]),
)
},
registerPushNotifications(store) {
const token = store.state.currentUser.credentials
const vapidPublicKey = useInstanceStore().vapidPublicKey
const isEnabled = useMergedConfigStore().mergedConfig.webPushNotifications
const notificationVisibility =
useMergedConfigStore().mergedConfig.notificationVisibility
registerPushNotifications(
isEnabled,
vapidPublicKey,
token,
notificationVisibility,
)
},
unregisterPushNotifications(store) {
const token = store.state.currentUser.credentials
unregisterPushNotifications(token)
},
addNewUsers({ commit }, users) {
commit('addNewUsers', users)
},
addNewStatuses(store, { statuses }) {
const users = map(statuses, 'user')
const retweetedUsers = compact(map(statuses, 'retweeted_status.user'))
store.commit('addNewUsers', users)
store.commit('addNewUsers', retweetedUsers)
each(statuses, (status) => {
// Reconnect users to statuses
store.commit('setUserForStatus', status)
// Set pinned statuses to user
store.commit('setPinnedToUser', status)
})
each(compact(map(statuses, 'retweeted_status')), (status) => {
// Reconnect users to retweets
store.commit('setUserForStatus', status)
// Set pinned retweets to user
store.commit('setPinnedToUser', status)
})
},
addNewNotifications(store, { notifications }) {
const users = map(notifications, 'from_profile')
const targetUsers = map(notifications, 'target').filter((_) => _)
const notificationIds = notifications.map((_) => _.id)
store.commit('addNewUsers', users)
store.commit('addNewUsers', targetUsers)
const notificationsObject = store.rootState.notifications.idStore
const relevantNotifications = Object.entries(notificationsObject)
.filter(([k]) => notificationIds.includes(k))
.map(([, val]) => val)
// Reconnect users to notifications
each(relevantNotifications, (notification) => {
store.commit('setUserForNotification', notification)
})
},
searchUsers({ rootState, commit }, { query }) {
return searchUsers({
query,
credentials: useOAuthStore().token,
}).then(({ data: users }) => {
commit('addNewUsers', users)
return users
})
},
async signUp(store, userInfo) {
const oauthStore = useOAuthStore()
store.commit('signUpPending')
try {
const token = await oauthStore.ensureAppToken()
const { data } = await register({
credentials: token,
params: { ...userInfo },
})
if (data.access_token) {
store.commit('signUpSuccess')
oauthStore.setToken(data.access_token)
await store.dispatch('loginUser', data.access_token)
return 'ok'
} else {
// Request succeeded, but user cannot login yet.
store.commit('signUpNotice', data)
return 'request_sent'
}
} catch (e) {
const errors = e.message
store.commit('signUpFailure', errors)
throw e
}
},
getCaptcha(store) {
return getCaptcha({
credentials: useOAuthStore().token,
}).then(({ data }) => data)
},
logout(store) {
const oauth = useOAuthStore()
// NOTE: No need to verify the app still exists, because if it doesn't,
// the token will be invalid too
return oauth
.ensureApp()
.then((app) => {
const params = {
app,
instance: useInstanceStore().server,
token: oauth.userToken,
}
return revokeToken(params)
})
.then(() => {
store.commit('clearCurrentUser')
store.dispatch('disconnectFromSocket')
store.dispatch('stopFetchingTimeline', 'friends')
store.dispatch('stopFetchingNotifications')
useListsStore().stopFetching()
useBookmarkFoldersStore().stopFetching()
store.dispatch('stopFetchingFollowRequests')
store.commit('clearNotifications')
store.commit('resetStatuses')
- store.dispatch('resetChats')
+ useChatsStore().resetChats()
oauth.clearToken()
Cookies.remove('__Host-pleroma_key', { path: '/' })
useInterfaceStore().setLastTimeline('public-timeline')
useInterfaceStore().setLayoutWidth(windowWidth())
useInterfaceStore().setLayoutHeight(windowHeight())
})
},
loginUser(store, accessToken) {
return new Promise((resolve, reject) => {
const commit = store.commit
const dispatch = store.dispatch
commit('beginLogin')
verifyCredentials({
credentials: useOAuthStore().token,
})
.then(({ data: user }) => {
// user.credentials = userCredentials
user.credentials = accessToken
user.blockIds = []
user.muteIds = []
user.domainMutes = []
commit('setCurrentUser', user)
useSyncConfigStore()
.initSyncConfig(user)
.then(() => {
useInterfaceStore()
.applyTheme()
.catch((e) => {
console.error('Error setting theme', e)
})
})
useUserHighlightStore().initUserHighlight(user)
commit('addNewUsers', [user])
useEmojiStore().fetchEmoji()
getNotificationPermission().then((permission) =>
useInterfaceStore().setNotificationPermission(permission),
)
// Do server-side storage migrations
// Debug snippet to clean up storage and reset migrations
/*
// Reset wordfilter
Object.keys(
useSyncConfigStore().prefsStorage.simple.muteFilters
).forEach(key => {
useSyncConfigStore().unsetSimplePrefAndSave({ path: 'muteFilters.' + key, value: null })
})
// Reset flag to 0 to re-run migrations
useSyncConfigStore().setFlag({ flag: 'configMigration', value: 0 })
/**/
if (user.token) {
dispatch('setWsToken', user.token)
// Initialize the shout socket.
dispatch('initializeSocket')
}
const startPolling = () => {
// Start getting fresh posts.
dispatch('startFetchingTimeline', { timeline: 'friends' })
// Start fetching notifications
dispatch('startFetchingNotifications')
if (useInstanceCapabilitiesStore().pleromaChatMessagesAvailable) {
// Start fetching chats
dispatch('startFetchingChats')
}
}
useListsStore().startFetching()
useBookmarkFoldersStore().startFetching()
if (user.locked) {
dispatch('startFetchingFollowRequests')
}
if (useMergedConfigStore().mergedConfig.useStreamingApi) {
dispatch('fetchTimeline', {
timeline: 'friends',
sinceId: null,
})
dispatch('fetchNotifications', { sinceId: null })
dispatch('enableMastoSockets', true)
.catch((error) => {
console.error(
'Failed initializing MastoAPI Streaming socket',
error,
)
})
.then(() => {
dispatch('fetchChats', { latest: true })
setTimeout(
() => dispatch('setNotificationsSilence', false),
10000,
)
})
} else {
startPolling()
}
// Start fetching things that don't need to block the UI
useAnnouncementsStore().startFetchingAnnouncements()
dispatch('fetchMutes')
dispatch('loadDrafts')
useInterfaceStore().setLayoutWidth(windowWidth())
useInterfaceStore().setLayoutHeight(windowHeight())
// Fetch our friends
fetchFriends({ id: user.id }).then(({ data: friends }) =>
commit('addNewUsers', friends),
)
commit('endLogin')
resolve()
})
.catch((error) => {
console.error(error)
// Authentication failed
commit('endLogin')
// remove authentication token on client/authentication errors
if ([400, 401, 403, 422].includes(error.statusCode)) {
useOAuthStore().clearToken()
}
commit('endLogin')
if (error.tatusCode === 401) {
throw new Error('Wrong username or password', error)
} else {
throw new Error('An error occurred, please try again', error)
}
})
})
},
},
}
export default users
diff --git a/src/services/chat_service/chat_service.js b/src/services/chat_service/chat_service.js
deleted file mode 100644
index eec267dde7..0000000000
--- a/src/services/chat_service/chat_service.js
+++ /dev/null
@@ -1,251 +0,0 @@
-import { maxBy, minBy, orderBy, sortBy, uniqueId } from 'lodash'
-
-const empty = (chatId) => {
- return {
- idIndex: {},
- idempotencyKeyIndex: {},
- messages: [],
- newMessageCount: 0,
- lastSeenMessageId: '0',
- chatId,
- minId: undefined,
- maxId: undefined,
- }
-}
-
-const clear = (storage) => {
- const failedMessageIds = []
-
- for (const message of storage.messages) {
- if (message.error) {
- failedMessageIds.push(message.id)
- } else {
- delete storage.idIndex[message.id]
- delete storage.idempotencyKeyIndex[message.idempotency_key]
- }
- }
-
- storage.messages = storage.messages.filter((m) =>
- failedMessageIds.includes(m.id),
- )
- storage.newMessageCount = 0
- storage.lastSeenMessageId = '0'
- storage.minId = undefined
- storage.maxId = undefined
-}
-
-const deleteMessage = (storage, messageId) => {
- if (!storage) {
- return
- }
- storage.messages = storage.messages.filter((m) => m.id !== messageId)
- delete storage.idIndex[messageId]
-
- if (storage.maxId === messageId) {
- const lastMessage = maxBy(storage.messages, 'id')
- storage.maxId = lastMessage.id
- }
-
- if (storage.minId === messageId) {
- const firstMessage = minBy(storage.messages, 'id')
- storage.minId = firstMessage.id
- }
-}
-
-const cullOlderMessages = (storage) => {
- const maxIndex = storage.messages.length
- const minIndex = maxIndex - 50
- if (maxIndex <= 50) return
-
- storage.messages = sortBy(storage.messages, ['id'])
- storage.minId = storage.messages[minIndex].id
- for (const message of storage.messages) {
- if (message.id < storage.minId) {
- delete storage.idIndex[message.id]
- delete storage.idempotencyKeyIndex[message.idempotency_key]
- }
- }
- storage.messages = storage.messages.slice(minIndex, maxIndex)
-}
-
-const handleMessageError = (storage, fakeId, isRetry) => {
- if (!storage) {
- return
- }
- const fakeMessage = storage.idIndex[fakeId]
- if (fakeMessage) {
- fakeMessage.error = true
- fakeMessage.pending = false
- if (!isRetry) {
- // Ensure the failed message doesn't stay at the bottom of the list.
- const lastPersistedMessage = orderBy(
- storage.messages,
- ['pending', 'id'],
- ['asc', 'desc'],
- )[0]
- if (lastPersistedMessage) {
- const oldId = fakeMessage.id
- fakeMessage.id = `${lastPersistedMessage.id}-${new Date().getTime()}`
- storage.idIndex[fakeMessage.id] = fakeMessage
- delete storage.idIndex[oldId]
- }
- }
- }
-}
-
-const add = (storage, { messages: newMessages, updateMaxId = true }) => {
- if (!storage) {
- return
- }
- for (let i = 0; i < newMessages.length; i++) {
- const message = newMessages[i]
-
- // sanity check
- if (message.chat_id !== storage.chatId) {
- return
- }
-
- if (message.fakeId) {
- const fakeMessage = storage.idIndex[message.fakeId]
- if (fakeMessage) {
- // In case the same id exists (chat update before POST response)
- // make sure to remove the older duplicate message.
- if (storage.idIndex[message.id]) {
- delete storage.idIndex[message.id]
- storage.messages = storage.messages.filter(
- (msg) => msg.id !== message.id,
- )
- }
- Object.assign(fakeMessage, message, { error: false })
- delete fakeMessage.fakeId
- storage.idIndex[fakeMessage.id] = fakeMessage
- delete storage.idIndex[message.fakeId]
-
- return
- }
- }
-
- if (!storage.minId || (!message.pending && message.id < storage.minId)) {
- storage.minId = message.id
- }
-
- if (!storage.maxId || message.id > storage.maxId) {
- if (updateMaxId) {
- storage.maxId = message.id
- }
- }
-
- if (!storage.idIndex[message.id] && !isConfirmation(storage, message)) {
- if (storage.lastSeenMessageId < message.id) {
- storage.newMessageCount++
- }
- storage.idIndex[message.id] = message
- storage.messages.push(storage.idIndex[message.id])
- storage.idempotencyKeyIndex[message.idempotency_key] = true
- }
- }
-}
-
-const isConfirmation = (storage, message) => {
- if (!message.idempotency_key) return
- return storage.idempotencyKeyIndex[message.idempotency_key]
-}
-
-const resetNewMessageCount = (storage) => {
- if (!storage) {
- return
- }
- storage.newMessageCount = 0
- storage.lastSeenMessageId = storage.maxId
-}
-
-// Inserts date separators and marks the head and tail if it's the chain of messages made by the same user
-const getView = (storage) => {
- if (!storage) {
- return []
- }
-
- const result = []
- const messages = orderBy(storage.messages, ['pending', 'id'], ['asc', 'asc'])
- const firstMessage = messages[0]
- let previousMessage = messages[messages.length - 1]
- let currentMessageChainId
-
- if (firstMessage) {
- const date = new Date(firstMessage.created_at)
- date.setHours(0, 0, 0, 0)
- result.push({
- type: 'date',
- date,
- id: date.getTime().toString(),
- })
- }
-
- let afterDate = false
-
- for (let i = 0; i < messages.length; i++) {
- const message = messages[i]
- const nextMessage = messages[i + 1]
-
- const date = new Date(message.created_at)
- date.setHours(0, 0, 0, 0)
-
- // insert date separator and start a new message chain
- if (previousMessage && previousMessage.date < date) {
- result.push({
- type: 'date',
- date,
- id: date.getTime().toString(),
- })
-
- previousMessage.isTail = true
- currentMessageChainId = undefined
- afterDate = true
- }
-
- const object = {
- type: 'message',
- data: message,
- date,
- id: message.id,
- messageChainId: currentMessageChainId,
- }
-
- // end a message chian
- if ((nextMessage && nextMessage.account_id) !== message.account_id) {
- object.isTail = true
- currentMessageChainId = undefined
- }
-
- // start a new message chain
- if (
- (previousMessage &&
- previousMessage.data &&
- previousMessage.data.account_id) !== message.account_id ||
- afterDate
- ) {
- currentMessageChainId = uniqueId()
- object.isHead = true
- object.messageChainId = currentMessageChainId
- }
-
- result.push(object)
- previousMessage = object
- afterDate = false
- }
-
- return result
-}
-
-const ChatService = {
- add,
- empty,
- getView,
- deleteMessage,
- cullOlderMessages,
- resetNewMessageCount,
- clear,
- handleMessageError,
-}
-
-export default ChatService
diff --git a/src/services/chat_utils/chat_utils.js b/src/services/chat_utils/chat_utils.js
index 6d3181dd15..ccf91e85c5 100644
--- a/src/services/chat_utils/chat_utils.js
+++ b/src/services/chat_utils/chat_utils.js
@@ -1,52 +1,50 @@
import { showDesktopNotification } from '../desktop_notification_utils/desktop_notification_utils.js'
-export const maybeShowChatNotification = (store, chat) => {
+export const maybeShowChatNotification = (chat) => {
if (!chat.lastMessage) return
- if (store.rootState.chats.currentChatId === chat.id && !document.hidden)
- return
- if (store.rootState.users.currentUser.id === chat.lastMessage.account_id)
+ if (window.vuex.state.users.currentUser.id === chat.lastMessage.account_id)
return
const opts = {
tag: chat.lastMessage.id,
title: chat.account.name,
icon: chat.account.profile_image_url,
body: chat.lastMessage.content,
}
if (
chat.lastMessage.attachment &&
chat.lastMessage.attachment.type === 'image'
) {
opts.image = chat.lastMessage.attachment.preview_url
}
- showDesktopNotification(store.rootState, opts)
+ showDesktopNotification(window.vuex.state, opts)
}
export const buildFakeMessage = ({
content,
chatId,
attachments,
userId,
idempotencyKey,
}) => {
const fakeMessage = {
content,
chat_id: chatId,
created_at: new Date(),
id: `${new Date().getTime()}`,
attachments,
account_id: userId,
idempotency_key: idempotencyKey,
emojis: [],
pending: true,
isNormalized: true,
}
if (attachments[0]) {
fakeMessage.attachment = attachments[0]
}
return fakeMessage
}
diff --git a/src/services/notification_utils/notification_utils.js b/src/services/notification_utils/notification_utils.js
index 37e5e95ade..6cb3dbc191 100644
--- a/src/services/notification_utils/notification_utils.js
+++ b/src/services/notification_utils/notification_utils.js
@@ -1,213 +1,212 @@
import { showDesktopNotification } from '../desktop_notification_utils/desktop_notification_utils.js'
import { muteFilterHits } from '../status_parser/status_parser.js'
import FaviconService from 'src/services/favicon_service/favicon_service.js'
export const ACTIONABLE_NOTIFICATION_TYPES = new Set([
'mention',
'pleroma:report',
'follow_request',
])
let cachedBadgeUrl = null
export const notificationsFromStore = (store) => store.state.notifications.data
const visibleTypes = (notificationVisibility) => {
return [
notificationVisibility.likes && 'like',
notificationVisibility.mentions && 'mention',
notificationVisibility.statuses && 'status',
notificationVisibility.repeats && 'repeat',
notificationVisibility.follows && 'follow',
notificationVisibility.followRequest && 'follow_request',
notificationVisibility.moves && 'move',
notificationVisibility.emojiReactions && 'pleroma:emoji_reaction',
notificationVisibility.reports && 'pleroma:report',
notificationVisibility.polls && 'poll',
].filter((_) => _)
}
const statusNotifications = new Set([
'like',
'mention',
'status',
'repeat',
'pleroma:emoji_reaction',
'poll',
])
export const isStatusNotification = (type) => statusNotifications.has(type)
export const isValidNotification = (notification) => {
if (isStatusNotification(notification.type) && !notification.status) {
return false
}
return true
}
const sortById = (a, b) => {
const seqA = Number(a.id)
const seqB = Number(b.id)
const isSeqA = !Number.isNaN(seqA)
const isSeqB = !Number.isNaN(seqB)
if (isSeqA && isSeqB) {
return seqA > seqB ? -1 : 1
} else if (isSeqA && !isSeqB) {
return 1
} else if (!isSeqA && isSeqB) {
return -1
} else {
return a.id > b.id ? -1 : 1
}
}
const isMutedNotification = (muteFilters, notification) => {
if (!notification.status) return false
if (notification.status.muted) return true
return muteFilterHits(muteFilters, notification.status).length > 0
}
export const maybeShowNotification = (
store,
notificationVisibility,
muteFilters,
notification,
i18n,
) => {
const rootState = store.rootState || store.state
if (notification.seen) return
if (!visibleTypes(notificationVisibility).includes(notification.type)) return
if (
notification.type === 'mention' &&
isMutedNotification(muteFilters, notification)
)
return
const notificationObject = prepareNotificationObject(notification, i18n)
showDesktopNotification(rootState, notificationObject)
}
export const filteredNotificationsFromStore = (
store,
notificationVisibility,
types,
) => {
// map is just to clone the array since sort mutates it and it causes some issues
const sortedNotifications = notificationsFromStore(store)
.map((_) => _)
.sort(sortById)
// TODO implement sorting elsewhere and make it optional
return sortedNotifications.filter((notification) =>
(types || visibleTypes(notificationVisibility)).includes(notification.type),
)
}
export const unseenNotificationsFromStore = (
store,
notificationVisibility,
ignoreInactionableSeen,
) => {
return filteredNotificationsFromStore(store, notificationVisibility).filter(
({ seen, type }) => {
if (!ignoreInactionableSeen) return !seen
if (seen) return false
return ACTIONABLE_NOTIFICATION_TYPES.has(type)
},
)
}
export const prepareNotificationObject = (notification, i18n) => {
if (cachedBadgeUrl === null) {
const favicons = FaviconService.getOriginalFavicons()
const favicon = favicons[favicons.length - 1]
if (!favicon) {
cachedBadgeUrl = 'about:blank'
} else {
cachedBadgeUrl = favicon.favimg.src
}
}
const notifObj = {
tag: notification.id,
type: notification.type,
badge: cachedBadgeUrl,
}
const status = notification.status
const title = notification.from_profile.name
notifObj.title = title
notifObj.icon = notification.from_profile.profile_image_url
let i18nString
switch (notification.type) {
case 'like':
i18nString = 'favorited_you'
break
case 'status':
i18nString = 'subscribed_status'
break
case 'repeat':
i18nString = 'repeated_you'
break
case 'follow':
i18nString = 'followed_you'
break
case 'move':
i18nString = 'migrated_to'
break
case 'follow_request':
i18nString = 'follow_request'
break
case 'pleroma:report':
i18nString = 'submitted_report'
break
case 'poll':
i18nString = 'poll_ended'
break
}
if (notification.type === 'pleroma:emoji_reaction') {
notifObj.body = i18n.t('notifications.reacted_with', [notification.emoji])
} else if (i18nString) {
notifObj.body = i18n.t('notifications.' + i18nString)
} else if (isStatusNotification(notification.type)) {
notifObj.body = notification.status.text
}
// Shows first attached non-nsfw image, if any. Should add configuration for this somehow...
if (
status &&
status.attachments &&
status.attachments.length > 0 &&
!status.nsfw &&
status.attachments[0].mimetype.startsWith('image/')
) {
notifObj.image = status.attachments[0].url
}
return notifObj
}
export const countExtraNotifications = (
store,
mergedConfig,
+ unreadChatsCount,
unreadAnnouncementCount,
) => {
const rootGetters = store.rootGetters || store.getters
if (!mergedConfig.showExtraNotifications) {
return 0
}
return [
- mergedConfig.showChatsInExtraNotifications
- ? rootGetters.unreadChatCount
- : 0,
+ mergedConfig.showChatsInExtraNotifications ? unreadChatsCount : 0,
mergedConfig.showAnnouncementsInExtraNotifications
? unreadAnnouncementCount
: 0,
mergedConfig.showFollowRequestsInExtraNotifications
? rootGetters.followRequestCount
: 0,
].reduce((a, c) => a + c, 0)
}
diff --git a/src/services/poll/poll.service.js b/src/services/poll/poll.service.js
index b6b5f35e63..468fc6ff9b 100644
--- a/src/services/poll/poll.service.js
+++ b/src/services/poll/poll.service.js
@@ -1,36 +1,34 @@
import { uniq } from 'lodash'
import * as DateUtils from 'src/services/date_utils/date_utils.js'
const pollFallbackValues = {
pollType: 'single',
options: ['', ''],
expiryAmount: 10,
expiryUnit: 'minutes',
}
-const pollFallback = (object, attr) => {
+export const pollFallback = (object, attr) => {
return object[attr] !== undefined ? object[attr] : pollFallbackValues[attr]
}
-const pollFormToMasto = (poll) => {
+export const pollFormToMasto = (poll) => {
const expiresIn = DateUtils.unitToSeconds(
pollFallback(poll, 'expiryUnit'),
pollFallback(poll, 'expiryAmount'),
)
const options = uniq(
pollFallback(poll, 'options').filter((option) => option !== ''),
)
if (options.length < 2) {
return { errorKey: 'polls.not_enough_options' }
}
return {
options,
multiple: pollFallback(poll, 'pollType') === 'multiple',
expiresIn,
}
}
-
-export { pollFallback, pollFormToMasto }
diff --git a/src/stores/chats.js b/src/stores/chats.js
new file mode 100644
index 0000000000..bc5b7f101e
--- /dev/null
+++ b/src/stores/chats.js
@@ -0,0 +1,114 @@
+import { find, omitBy, orderBy, sumBy } from 'lodash'
+import { defineStore } from 'pinia'
+
+import { maybeShowChatNotification } from '../services/chat_utils/chat_utils.js'
+import { promiseInterval } from '../services/promise_interval/promise_interval.js'
+
+import { useOAuthStore } from 'src/stores/oauth.js'
+
+import { chats } from 'src/api/chats.js'
+
+const emptyChatList = () => ({
+ data: [],
+ idStore: {},
+})
+
+const defaultState = {
+ chatList: emptyChatList(),
+ chatListFetcher: null,
+}
+
+const getChatById = (state, id) => {
+ return find(state.chatList.data, { id })
+}
+
+export const useChatsStore = defineStore('chats', {
+ state: () => ({ ...defaultState }),
+ getters: {
+ sortedChatList(state) {
+ return orderBy(state.chatList.data, ['updated_at'], ['desc'])
+ },
+ unreadChatsCount(state) {
+ return sumBy(state.chatList.data, 'unread')
+ },
+ },
+ actions: {
+ startFetchingChats() {
+ const fetcher = () => this.fetchChats()
+ this.setChatListFetcher(() => promiseInterval(fetcher, 5000))
+ },
+ stopFetchingChats() {
+ this.setChatListFetcher(null)
+ },
+ async fetchChats() {
+ const { data } = await chats({
+ credentials: useOAuthStore().token,
+ })
+
+ this.addNewChats(data)
+ },
+ setChatListFetcher(fetcher) {
+ const prevFetcher = this.chatListFetcher
+ if (prevFetcher) {
+ prevFetcher.stop()
+ }
+ this.chatListFetcher = fetcher?.()
+ },
+ resetChats() {
+ this.chatList = emptyChatList()
+ this.setChatListFetcher(null)
+ },
+ addNewChats(chats) {
+ window.vuex.commit(
+ 'addNewUsers',
+ chats.map((k) => k.account).filter((k) => k),
+ )
+
+ chats.forEach((updatedChat) => {
+ const chat = getChatById(this, updatedChat.id)
+
+ if (chat) {
+ const isNewMessage =
+ (chat.lastMessage && chat.lastMessage.id) !==
+ (updatedChat.lastMessage && updatedChat.lastMessage.id)
+ chat.lastMessage = updatedChat.lastMessage
+ chat.unread = updatedChat.unread
+ chat.updated_at = updatedChat.updated_at
+ if (isNewMessage && chat.unread) {
+ maybeShowChatNotification(chat)
+ }
+ } else {
+ this.chatList.data.push(updatedChat)
+ this.chatList.idStore[updatedChat.id] = updatedChat
+ }
+ })
+ },
+ readChat(id) {
+ const chat = getChatById(this, id)
+ if (chat) {
+ chat.unread = 0
+ }
+ },
+ updateChat({ chat: updatedChat }) {
+ const chat = getChatById(this, updatedChat.id)
+ if (chat) {
+ chat.lastMessage = updatedChat.lastMessage
+ chat.unread = updatedChat.unread
+ chat.updated_at = updatedChat.updated_at
+ }
+ if (!chat) {
+ this.chatList.data.unshift(updatedChat)
+ }
+ this.chatList.idStore[updatedChat.id] = updatedChat
+ },
+ deleteChat(id) {
+ this.chats.data = this.chats.data.filter(
+ (conversation) => conversation.last_status.id !== id,
+ )
+ this.chats.idStore = omitBy(
+ this.chats.idStore,
+ (conversation) => conversation.last_status.id === id,
+ )
+ },
+ },
+})
diff --git a/src/stores/interface.js b/src/stores/interface.js
index 8c101b9f4c..654cc55fdc 100644
--- a/src/stores/interface.js
+++ b/src/stores/interface.js
@@ -1,805 +1,803 @@
import { defineStore } from 'pinia'
import {
applyTheme,
getResourcesIndex,
tryLoadCache,
} from '../services/style_setter/style_setter.js'
import { deserialize } from '../services/theme_data/iss_deserializer.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useSyncConfigStore } from 'src/stores/sync_config.js'
import {
CURRENT_VERSION,
generatePreset,
} from 'src/services/theme_data/theme_data.service.js'
import { convertTheme2To3 } from 'src/services/theme_data/theme2_to_theme3.js'
const GENERIC_FONT_NAMES = new Set([
'serif',
'sans-serif',
'system-ui',
'cursive',
'fantasy',
'math',
'monospace',
])
export const useInterfaceStore = defineStore('interface', {
state: () => ({
localFonts: null,
themeApplied: false,
themeChangeInProgress: false,
themeVersion: 'v3',
styleNameUsed: null,
styleDataUsed: null,
useStylePalette: false, // hack for applying styles from appearance tab
paletteNameUsed: null,
paletteDataUsed: null,
themeNameUsed: null,
themeDataUsed: null,
temporaryChangesTimeoutId: null,
temporaryChangesCountdown: -1, // used for temporary options that revert after a timeout
temporaryChangesConfirm: () => {
/* no-op */
}, // used for applying temporary options
temporaryChangesRevert: () => {
/* no-op */
}, // used for reverting temporary options
settingsModalState: 'hidden',
settingsModalLoadedUser: false,
settingsModalLoadedAdmin: false,
settingsModalTargetTab: null,
settingsModalMode: 'user',
settings: {
currentSaveStateNotice: null,
noticeClearTimeout: null,
notificationPermission: null,
},
browserSupport: {
cssFilter:
window.CSS &&
window.CSS.supports &&
(window.CSS.supports('filter', 'drop-shadow(0 0)') ||
window.CSS.supports('-webkit-filter', 'drop-shadow(0 0)')),
localFonts: typeof window.queryLocalFonts === 'function',
},
layoutType: 'normal',
globalNotices: [],
globalError: null,
layoutHeight: 0,
lastTimeline: null,
foreignProfileBackground: null,
}),
actions: {
setTemporaryChanges({ confirm, revert }) {
this.temporaryChangesCountdown = 10
this.temporaryChangesConfirm = confirm
this.temporaryChangesRevert = revert
const countdownFunc = () => {
if (this.temporaryChangesCountdown <= 1) {
this.temporaryChangesRevert()
this.clearTemporaryChanges()
} else {
this.temporaryChangesCountdown--
this.temporaryChangesTimeoutId = setTimeout(countdownFunc, 1000)
}
}
this.temporaryChangesTimeoutId = setTimeout(countdownFunc, 1000)
},
clearTemporaryChanges() {
this.temporaryChangesTimeoutId ??
clearTimeout(this.temporaryChangesTimeoutId)
this.temporaryChangesTimeoutId = null
this.temporaryChangesCountdown = -1
this.temporaryChangesConfirm = () => {
/* no-op */
}
this.temporaryChangesRevert = () => {
/* no-op */
}
},
setPageTitle(option = '') {
try {
document.title = `${option} ${useInstanceStore().instanceIdentity.name}`
} catch (error) {
console.error(`${error}`)
}
},
setForeignProfileBackground(url) {
this.foreignProfileBackground = url
},
settingsSaved({ success, error }) {
if (success) {
if (this.noticeClearTimeout) {
clearTimeout(this.noticeClearTimeout)
}
this.settings.currentSaveStateNotice = { error: false, data: success }
this.settings.noticeClearTimeout = setTimeout(
() => delete this.settings.currentSaveStateNotice,
2000,
)
} else {
this.settings.currentSaveStateNotice = { error: true, errorData: error }
}
},
setNotificationPermission(permission) {
this.notificationPermission = permission
},
closeSettingsModal() {
this.settingsModalState = 'hidden'
},
openSettingsModal(value) {
this.settingsModalMode = value
this.settingsModalState = 'visible'
if (value === 'user') {
if (!this.settingsModalLoadedUser) {
this.settingsModalLoadedUser = true
}
} else if (value === 'admin') {
if (!this.settingsModalLoadedAdmin) {
this.settingsModalLoadedAdmin = true
}
}
},
setSettingsModalState(newState) {
const oldState = this.settingsModalState
const legal = (() => {
switch (oldState) {
case 'minimized':
return true
case 'visible':
return true
case 'hidden':
return newState === 'visible'
}
})()
if (legal) {
this.settingsModalState = newState
}
},
toggleMinimizeSettingsModal() {
switch (this.settingsModalState) {
case 'minimized':
this.settingsModalState = 'visible'
return
case 'visible':
this.settingsModalState = 'minimized'
return
case 'hidden':
return
default:
throw new Error(
`Illegal minimization state of settings modal: ${this.settingsModalState}`,
)
}
},
clearSettingsModalTargetTab() {
this.settingsModalTargetTab = null
},
openSettingsModalTab(value, mode = 'user') {
this.settingsModalTargetTab = value
this.openSettingsModal(mode)
},
removeGlobalNotice(notice) {
this.globalNotices = this.globalNotices.filter((n) => n !== notice)
},
setGlobalError({ error, instance, info }) {
- console.log(info)
switch (info) {
case 'https://vuejs.org/error-reference/#runtime-13': {
this.globalError = {
title: 'general.refresh_required',
content: 'general.refresh_required_content',
// `true` disables cache on Firefox (non-standard)
recover: () => window.location.reload(true),
recoverText: 'general.refresh_required_refresh',
error,
}
break
}
default: {
this.globalError = { error }
break
}
}
- console.log(this.globalError)
},
clearGlobalError() {
this.globalError = null
},
pushGlobalNotice({
messageKey,
messageArgs = {},
level = 'error',
timeout = 5000,
}) {
const notice = {
messageKey,
messageArgs,
level,
}
this.globalNotices.push(notice)
// Adding a new element to array wraps it in a Proxy, which breaks the comparison
// TODO: Generate UUID or something instead or relying on !== operator?
const newNotice = this.globalNotices[this.globalNotices.length - 1]
if (timeout > 0) {
setTimeout(() => this.removeGlobalNotice(newNotice), timeout)
}
return newNotice
},
setLayoutHeight(value) {
this.layoutHeight = value
},
setLayoutWidth(value) {
let width = value
if (value !== undefined) {
this.layoutWidth = value
} else {
width = this.layoutWidth
}
const mobileLayout = width <= 800
const normalOrMobile = mobileLayout ? 'mobile' : 'normal'
const { thirdColumnMode } = useMergedConfigStore().mergedConfig
if (thirdColumnMode === 'none' || !window.vuex.state.users.currentUser) {
this.layoutType = normalOrMobile
} else {
const wideLayout = width >= 1300
this.layoutType = wideLayout ? 'wide' : normalOrMobile
}
},
setFontsList(value) {
this.localFonts = [...new Set(value.map(({ family }) => family)).values()]
},
queryLocalFonts() {
if (this.localFonts !== null) return
this.setFontsList([])
if (!this.browserSupport.localFonts) {
return
}
window
.queryLocalFonts()
.then((fonts) => {
this.setFontsList(fonts)
})
.catch((e) => {
this.pushGlobalNotice({
messageKey: 'settings.style.themes3.font.font_list_unavailable',
messageArgs: {
error: e,
},
level: 'error',
})
})
},
setLastTimeline(value) {
this.lastTimeline = value
},
async fetchPalettesIndex() {
try {
const value = await getResourcesIndex('/static/palettes/index.json')
useInstanceStore().set({
path: 'palettesIndex',
value,
})
return value
} catch (e) {
console.error('Could not fetch palettes index', e)
useInstanceStore().set({
path: 'palettesIndex',
value: { _error: e },
})
return Promise.resolve({})
}
},
setPalette(value) {
this.resetThemeV3Palette()
this.resetThemeV2()
useSyncConfigStore().setPreference({ path: 'simple.palette', value })
useSyncConfigStore().pushSyncConfig()
this.applyTheme({ recompile: true })
},
setPaletteCustom(value) {
this.resetThemeV3Palette()
this.resetThemeV2()
useSyncConfigStore().setPreference({
path: 'simple.paletteCustomData',
value,
})
useSyncConfigStore().pushSyncConfig()
this.applyTheme({ recompile: true })
},
async fetchStylesIndex() {
try {
const value = await getResourcesIndex(
'/static/styles/index.json',
deserialize,
)
useInstanceStore().set({ path: 'stylesIndex', value })
return value
} catch (e) {
console.error('Could not fetch styles index', e)
useInstanceStore().set({
path: 'simple.stylesIndex',
value: { _error: e },
})
return Promise.resolve({})
}
},
setStyle(value) {
this.resetThemeV3()
this.resetThemeV2()
this.resetThemeV3Palette()
useSyncConfigStore().setPreference({ path: 'simple.style', value })
useSyncConfigStore().pushSyncConfig()
this.useStylePalette = true
this.applyTheme({ recompile: true }).then(() => {
this.useStylePalette = false
})
},
setStyleCustom(value) {
this.resetThemeV3()
this.resetThemeV2()
this.resetThemeV3Palette()
useSyncConfigStore().setPreference({
path: 'simple.styleCustomData',
value,
})
useSyncConfigStore().pushSyncConfig()
this.useStylePalette = true
this.applyTheme({ recompile: true }).then(() => {
this.useStylePalette = false
})
},
async fetchThemesIndex() {
try {
const value = await getResourcesIndex('/static/styles.json')
useInstanceStore().set({ path: 'themesIndex', value })
return value
} catch (e) {
console.error('Could not fetch themes index', e)
useInstanceStore().set({
path: 'themesIndex',
value: { _error: e },
})
return Promise.resolve({})
}
},
setTheme(value) {
this.resetThemeV3()
this.resetThemeV3Palette()
this.resetThemeV2()
useSyncConfigStore().setPreference({ path: 'simple.theme', value })
useSyncConfigStore().pushSyncConfig()
this.applyTheme({ recompile: true })
},
setThemeCustom(value) {
this.resetThemeV3()
this.resetThemeV3Palette()
this.resetThemeV2()
useSyncConfigStore().setPreference({ path: 'simple.customTheme', value })
useSyncConfigStore().setPreference({
path: 'simple.customThemeSource',
value,
})
useSyncConfigStore().pushSyncConfig()
this.applyTheme({ recompile: true })
},
resetThemeV3() {
useSyncConfigStore().setPreference({ path: 'simple.style', value: null })
useSyncConfigStore().setPreference({
path: 'simple.styleCustomData',
value: null,
})
},
resetThemeV3Palette() {
useSyncConfigStore().setPreference({
path: 'simple.palette',
value: null,
})
useSyncConfigStore().setPreference({
path: 'simple.paletteCustomData',
value: null,
})
},
resetThemeV2() {
useSyncConfigStore().setPreference({ path: 'simple.theme', value: null })
useSyncConfigStore().setPreference({
path: 'simple.customTheme',
value: null,
})
useSyncConfigStore().setPreference({
path: 'simple.customThemeSource',
value: null,
})
},
async getThemeData() {
const getData = async (resource, index, customData, name) => {
const capitalizedResource =
resource[0].toUpperCase() + resource.slice(1)
const result = {}
if (customData) {
result.nameUsed = 'custom' // custom data overrides name
result.dataUsed = customData
} else {
result.nameUsed = name
if (result.nameUsed == null) {
result.dataUsed = null
return result
}
let fetchFunc = index[result.nameUsed]
// Fallbacks
if (!fetchFunc) {
if (resource === 'style' || resource === 'palette') {
return result
}
const newName = Object.keys(index)[0]
fetchFunc = index[newName]
console.warn(
`${capitalizedResource} with id '${this.styleNameUsed}' not found, trying back to '${newName}'`,
)
if (!fetchFunc) {
console.warn(
`${capitalizedResource} doesn't have a fallback, defaulting to stock.`,
)
fetchFunc = () => Promise.resolve(null)
}
}
result.dataUsed = await fetchFunc()
}
return result
}
let {
theme: instanceThemeName,
style: instanceStyleName,
palette: instancePaletteName,
} = useInstanceStore().instanceIdentity
let { themesIndex, stylesIndex, palettesIndex } = useInstanceStore()
const {
style: userStyleName,
styleCustomData: userStyleCustomData,
palette: userPaletteName,
paletteCustomData: userPaletteCustomData,
} = useMergedConfigStore().mergedConfig
let {
theme: userThemeV2Name,
customTheme: userThemeV2Snapshot,
customThemeSource: userThemeV2Source,
} = useMergedConfigStore().mergedConfig
let majorVersionUsed
console.debug(
`User V3 palette: ${userPaletteName}, style: ${userStyleName} , custom: ${!!userStyleCustomData}`,
)
console.debug(
`User V2 name: ${userThemeV2Name}, source: ${!!userThemeV2Source}, snapshot: ${!!userThemeV2Snapshot}`,
)
console.debug(
`Instance V3 palette: ${instancePaletteName}, style: ${instanceStyleName}`,
)
console.debug('Instance V2 theme: ' + instanceThemeName)
if (
userPaletteName ||
userPaletteCustomData ||
userStyleName ||
userStyleCustomData ||
// User V2 overrides instance V3
((instancePaletteName || instanceStyleName) &&
instanceThemeName == null &&
userThemeV2Name == null)
) {
// Palette and/or style overrides V2 themes
instanceThemeName = null
userThemeV2Name = null
userThemeV2Source = null
userThemeV2Snapshot = null
majorVersionUsed = 'v3'
} else if (
userThemeV2Name ||
userThemeV2Snapshot ||
userThemeV2Source ||
instanceThemeName
) {
majorVersionUsed = 'v2'
} else {
// if all fails fallback to v3
majorVersionUsed = 'v3'
}
if (majorVersionUsed === 'v3') {
const result = await Promise.all([
this.fetchPalettesIndex(),
this.fetchStylesIndex(),
])
palettesIndex = result[0]
stylesIndex = result[1]
} else {
// Promise.all just to be uniform with v3
const result = await Promise.all([this.fetchThemesIndex()])
themesIndex = result[0]
}
this.themeVersion = majorVersionUsed
console.debug('Version used', majorVersionUsed)
if (majorVersionUsed === 'v3') {
this.themeDataUsed = null
this.themeNameUsed = null
const style = await getData(
'style',
stylesIndex,
userStyleCustomData,
userStyleName || instanceStyleName,
)
this.styleNameUsed = style.nameUsed
this.styleDataUsed = style.dataUsed
let firstStylePaletteName = null
style.dataUsed
?.filter((x) => x.component === '@palette')
.map((x) => {
const cleanDirectives = Object.fromEntries(
Object.entries(x.directives).filter(([k]) => k),
)
return { name: x.variant, ...cleanDirectives }
})
.forEach((palette) => {
const key = 'style.' + palette.name.toLowerCase().replace(/ /g, '_')
if (!firstStylePaletteName) firstStylePaletteName = key
palettesIndex[key] = () => Promise.resolve(palette)
})
const palette = await getData(
'palette',
palettesIndex,
userPaletteCustomData,
this.useStylePalette
? firstStylePaletteName
: userPaletteName || instancePaletteName,
)
if (this.useStylePalette) {
useSyncConfigStore().setPreference({
path: 'simple.palette',
value: firstStylePaletteName,
})
useSyncConfigStore().pushSyncConfig()
}
this.paletteNameUsed = palette.nameUsed
this.paletteDataUsed = palette.dataUsed
if (this.paletteDataUsed) {
this.paletteDataUsed.link =
this.paletteDataUsed.link || this.paletteDataUsed.accent
this.paletteDataUsed.accent =
this.paletteDataUsed.accent || this.paletteDataUsed.link
}
if (Array.isArray(this.paletteDataUsed)) {
const [
name,
bg,
fg,
text,
link,
cRed = '#FF0000',
cGreen = '#00FF00',
cBlue = '#0000FF',
cOrange = '#E3FF00',
] = palette.dataUsed
this.paletteDataUsed = {
name,
bg,
fg,
text,
link,
accent: link,
cRed,
cBlue,
cGreen,
cOrange,
}
}
console.debug('Palette data used', palette.dataUsed)
} else {
this.styleNameUsed = null
this.styleDataUsed = null
this.paletteNameUsed = null
this.paletteDataUsed = null
const theme = await getData(
'theme',
themesIndex,
userThemeV2Source || userThemeV2Snapshot,
userThemeV2Name || instanceThemeName,
)
this.themeNameUsed = theme.nameUsed
this.themeDataUsed = theme.dataUsed
}
},
async setThemeApplied() {
this.themeApplied = true
},
async applyTheme({ recompile = false } = {}) {
const { mergedConfig } = useMergedConfigStore()
const { forceThemeRecompilation, themeDebug } = mergedConfig
this.themeChangeInProgress = true
// If we're not forced to recompile try using
// cache (tryLoadCache return true if load successful)
const forceRecompile = forceThemeRecompilation || recompile
await this.getThemeData()
if (!forceRecompile && !themeDebug && (await tryLoadCache())) {
this.themeChangeInProgress = false
return this.setThemeApplied()
}
window.splashUpdate('splash.theme')
try {
const paletteIss = (() => {
if (!this.paletteDataUsed) return null
const result = {
component: 'Root',
directives: {},
}
Object.entries(this.paletteDataUsed)
.filter(([k]) => k !== 'name')
.forEach(([k, v]) => {
let issRootDirectiveName
switch (k) {
case 'background':
issRootDirectiveName = 'bg'
break
case 'foreground':
issRootDirectiveName = 'fg'
break
default:
issRootDirectiveName = k
}
result.directives['--' + issRootDirectiveName] = 'color | ' + v
})
return result
})()
const theme2ruleset =
this.themeDataUsed &&
convertTheme2To3(normalizeThemeData(this.themeDataUsed))
const hacks = []
const fontMap = {
Interface: 'Root',
Input: 'Input',
Posts: 'Post',
Monospace: 'Root',
}
Object.entries(fontMap).forEach(([font, component]) => {
const family = mergedConfig[`font${font}`]
const variable = font === 'Monospace' ? '--monoFont' : '--font'
if (typeof family === 'string') {
const familyString = GENERIC_FONT_NAMES.has(family)
? family
: `"${family}"`
hacks.push({
component,
directives: {
[variable]: `generic | ${familyString}`,
},
})
}
})
if (mergedConfig.underlay !== 'none') {
const newRule = {
component: 'Underlay',
directives: {},
}
if (mergedConfig.underlay === 'opaque') {
newRule.directives.opacity = 1
newRule.directives.background = '--wallpaper'
}
if (mergedConfig.underlay === 'transparent') {
newRule.directives.opacity = 0
}
hacks.push(newRule)
}
const rulesetArray = [
theme2ruleset,
this.styleDataUsed,
paletteIss,
hacks,
].filter(Boolean)
return applyTheme(
rulesetArray.flat(),
() => this.setThemeApplied(),
() => {
this.themeChangeInProgress = false
},
themeDebug,
)
} catch (e) {
console.error(e)
window.splashError(e)
}
},
},
})
export const normalizeThemeData = (input) => {
let themeData, themeSource
if (input.themeFileVerison === 1) {
// this might not be even used at all, some leftover of unimplemented code in V2 editor
return generatePreset(input).theme
} else if (
Object.hasOwn(input, '_pleroma_theme_version') ||
Object.hasOwn(input, 'source') ||
Object.hasOwn(input, 'theme')
) {
// We got passed a full theme file
themeData = input.theme
themeSource = input.source
} else if (
Object.hasOwn(input, 'themeEngineVersion') ||
Object.hasOwn(input, 'colors')
) {
// We got passed a source/snapshot
themeData = input
themeSource = input
}
// New theme presets don't have 'theme' property, they use 'source'
let out // shout, shout let it all out
if (themeSource && themeSource.themeEngineVersion === CURRENT_VERSION) {
// There are some themes in wild that have completely broken source
out = { ...(themeData || {}), ...themeSource }
} else {
out = themeData
}
// generatePreset here basically creates/updates "snapshot",
// while also fixing the 2.2 -> 2.3 colors/shadows/etc
return generatePreset(out).theme
}
diff --git a/test/fixtures/setup_test.js b/test/fixtures/setup_test.js
index 85a062cc76..1a04b9549c 100644
--- a/test/fixtures/setup_test.js
+++ b/test/fixtures/setup_test.js
@@ -1,145 +1,145 @@
import { createTestingPinia } from '@pinia/testing'
import { config } from '@vue/test-utils'
import { createMemoryHistory, createRouter } from 'vue-router'
import VueVirtualScroller from 'vue-virtual-scroller'
import RichContent from 'src/components/rich_content/rich_content.jsx'
import Status from 'src/components/status/status.vue'
import StillImage from 'src/components/still-image/still-image.vue'
import makeMockStore from './mock_store'
import routes from 'src/boot/routes'
export const $t = (msg) => msg
const $i18n = { t: (msg) => msg }
const applyAfterStore = (store, afterStore) => {
afterStore(store)
return store
}
const getDefaultOpts = ({
afterStore = () => {
/* no-op */
},
} = {}) => ({
global: {
plugins: [
applyAfterStore(makeMockStore(), afterStore),
+ createTestingPinia(),
VueVirtualScroller,
createRouter({
history: createMemoryHistory(),
routes: routes({
state: {
users: {
currentUser: {},
},
instance: {},
},
}),
}),
(Vue) => {
Vue.directive('body-scroll-lock', {})
},
- createTestingPinia(),
],
components: {
RichContent,
Status,
StillImage,
},
stubs: {
I18nT: true,
teleport: true,
FAIcon: true,
FALayers: true,
},
mocks: {
$t,
$i18n,
},
},
})
// https://github.com/vuejs/vue-test-utils/issues/960
const customBehaviors = () => {
const filterByText = (keyword) => {
const match =
keyword instanceof RegExp
? (target) => target && keyword.test(target)
: (target) => keyword === target
return (wrapper) =>
match(wrapper.text()) ||
match(wrapper.attributes('aria-label')) ||
match(wrapper.attributes('title'))
}
return {
findComponentByText(searchedComponent, text) {
return this.findAllComponents(searchedComponent)
.filter(filterByText(text))
.at(0)
},
findByText(searchedElement, text) {
return this.findAll(searchedElement).filter(filterByText(text)).at(0)
},
}
}
config.plugins.VueWrapper.install(customBehaviors)
export const mountOpts = (allOpts = {}) => {
const { afterStore, ...opts } = allOpts
const defaultOpts = getDefaultOpts({ afterStore })
const mergedOpts = {
...opts,
global: {
...defaultOpts.global,
},
}
if (opts.global) {
mergedOpts.global.plugins = mergedOpts.global.plugins.concat(
opts.global.plugins || [],
)
Object.entries(opts.global).forEach(([k, v]) => {
if (k === 'plugins') {
return
}
if (defaultOpts.global[k]) {
mergedOpts.global[k] = {
...defaultOpts.global[k],
...v,
}
} else {
mergedOpts.global[k] = v
}
})
}
return mergedOpts
}
// https://stackoverflow.com/questions/78033718/how-can-i-wait-for-an-emitted-event-of-a-mounted-component-in-vue-test-utils
export const waitForEvent = (
wrapper,
event,
{ timeout = 1000, timesEmitted = 1 } = {},
) => {
const tick = 10
return vi.waitFor(
() => {
const e = wrapper.emitted(event)
if (e && e.length >= timesEmitted) {
return
}
throw new Error('event is not emitted')
},
{
timeout,
interval: tick,
},
)
}
diff --git a/test/unit/specs/boot/routes.spec.js b/test/unit/specs/boot/routes.spec.js
index 6df0ab80df..98bb9a61dd 100644
--- a/test/unit/specs/boot/routes.spec.js
+++ b/test/unit/specs/boot/routes.spec.js
@@ -1,84 +1,83 @@
import { createTestingPinia } from '@pinia/testing'
createTestingPinia()
import { createMemoryHistory, createRouter } from 'vue-router'
import { createStore } from 'vuex'
import routes from 'src/boot/routes'
const store = createStore({
state: {
instance: {},
},
})
describe('routes', () => {
const router = createRouter({
history: createMemoryHistory(),
routes: routes(store),
})
it('root path', async () => {
await router.push('/main/all')
const matchedComponents = router.currentRoute.value.matched
expect(
Object.hasOwn(
matchedComponents[0].components.default.components,
'Timeline',
),
).to.eql(true)
})
it("user's profile", async () => {
await router.push('/fake-user-name')
const matchedComponents = router.currentRoute.value.matched
- expect(matchedComponents[0].components.default.name).to.eql(
- 'AsyncComponentWrapper',
+ expect(matchedComponents[0].components.default.__file).to.contain(
+ 'user_profile.vue',
)
})
it("user's profile at /users", async () => {
await router.push('/users/fake-user-name')
const matchedComponents = router.currentRoute.value.matched
- expect(matchedComponents[0].components.default.name).to.eql(
- 'AsyncComponentWrapper',
+ expect(matchedComponents[0].components.default.__file).to.contain(
+ 'user_profile.vue',
)
})
it('list view', async () => {
await router.push('/lists')
const matchedComponents = router.currentRoute.value.matched
-
- expect(matchedComponents[0].components.default.name).to.eql(
- 'AsyncComponentWrapper',
+ expect(matchedComponents[0].components.default.__file).to.contain(
+ 'lists.vue',
)
})
it('list timeline', async () => {
await router.push('/lists/1')
const matchedComponents = router.currentRoute.value.matched
- expect(matchedComponents[0].components.default.name).to.eql(
- 'AsyncComponentWrapper',
+ expect(matchedComponents[0].components.default.__file).to.contain(
+ 'lists_timeline.vue',
)
})
it('list edit', async () => {
await router.push('/lists/1/edit')
const matchedComponents = router.currentRoute.value.matched
- expect(matchedComponents[0].components.default.name).to.eql(
- 'AsyncComponentWrapper',
+ expect(matchedComponents[0].components.default.__file).to.contain(
+ 'lists_edit.vue',
)
})
})
diff --git a/test/unit/specs/components/chat_message_list.spec.js b/test/unit/specs/components/chat_message_list.spec.js
new file mode 100644
index 0000000000..126332b958
--- /dev/null
+++ b/test/unit/specs/components/chat_message_list.spec.js
@@ -0,0 +1,244 @@
+import { shallowMount } from '@vue/test-utils'
+
+import ChatMessageList from 'src/components/chat_message_list/chat_message_list.vue'
+
+describe('ChatMessageList', () => {
+ describe('computed.chatItems', () => {
+ it('Inserts date separators', () => {
+ const component = shallowMount(ChatMessageList, {
+ props: {
+ messages: [
+ {
+ id: '0',
+ account_id: 'Alice',
+ created_at: new Date('2020-06-22T20:00:00.000Z'),
+ },
+ {
+ id: '1',
+ account_id: 'Alice',
+ created_at: new Date('2020-06-22T20:01:00.000Z'),
+ },
+ {
+ id: '2',
+ account_id: 'Alice',
+ created_at: new Date('2020-06-23T20:00:00.000Z'),
+ },
+ ],
+ },
+ })
+
+ expect(component.vm.chatItems.map((i) => i.type)).to.eql([
+ 'message',
+ 'message',
+ 'date',
+ 'message',
+ ])
+ })
+
+ it('Inserts date header if needed', () => {
+ const component = shallowMount(ChatMessageList, {
+ props: {
+ headerDate: true,
+ messages: [
+ {
+ id: '0',
+ account_id: 'Alice',
+ created_at: new Date('2020-06-23T20:00:00.000Z'),
+ },
+ ],
+ },
+ })
+
+ expect(component.vm.chatItems.map((i) => i.type)).to.eql([
+ 'date',
+ 'message',
+ ])
+ })
+
+ it('Inserts time separators if messages were sent with considerable delay (5 minutes)', () => {
+ const component = shallowMount(ChatMessageList, {
+ props: {
+ messages: [
+ {
+ id: '0',
+ account_id: 'Alice',
+ created_at: new Date('2020-06-22T20:00:00.000Z'),
+ },
+ {
+ id: '1',
+ account_id: 'Alice',
+ created_at: new Date('2020-06-22T20:06:00.000Z'),
+ },
+ {
+ id: '2',
+ account_id: 'Alice',
+ created_at: new Date('2020-06-23T20:00:00.000Z'),
+ },
+ ],
+ },
+ })
+
+ expect(component.vm.chatItems.map((i) => i.type)).to.eql([
+ 'message',
+ 'date',
+ 'message',
+ 'date',
+ 'message',
+ ])
+ expect(component.vm.chatItems.map((i) => i.isTime)).to.eql([
+ undefined,
+ true,
+ undefined,
+ false,
+ undefined,
+ ])
+ })
+
+ it('Groups message chains by time and author', () => {
+ const component = shallowMount(ChatMessageList, {
+ props: {
+ messages: [
+ {
+ id: '0',
+ account_id: 'Alice',
+ created_at: new Date('2020-06-22T20:00:00.000Z'),
+ },
+ {
+ id: '1',
+ account_id: 'Alice',
+ created_at: new Date('2020-06-22T20:06:00.000Z'),
+ },
+ {
+ id: '2',
+ account_id: 'Alice',
+ created_at: new Date('2020-06-23T20:00:00.000Z'),
+ },
+ {
+ id: '3',
+ account_id: 'Bob',
+ created_at: new Date('2020-06-23T20:01:00.000Z'),
+ },
+ {
+ id: '4',
+ account_id: 'Bob',
+ created_at: new Date('2020-06-23T20:02:00.000Z'),
+ },
+ {
+ id: '5',
+ account_id: 'Bob',
+ created_at: new Date('2020-06-23T20:03:00.000Z'),
+ },
+ {
+ id: '6',
+ account_id: 'Eve',
+ created_at: new Date('2020-06-23T20:04:00.000Z'),
+ },
+ ],
+ },
+ })
+
+ // Type check
+ expect(component.vm.chatItems.map((i) => i.type)).to.eql([
+ 'message',
+ 'date',
+ 'message',
+ 'date',
+ 'message',
+ 'message',
+ 'message',
+ 'message',
+ 'message',
+ ])
+
+ // Chain head/Tail checks
+ expect(component.vm.chatItems.map((i) => [i.isHead, i.isTail])).to.eql([
+ [true, true],
+ [undefined, undefined],
+ [true, true],
+ [undefined, undefined],
+ [true, true],
+ [true, false],
+ [false, false],
+ [false, true],
+ [true, true],
+ ])
+
+ // Unique ID is randomly generated so we have to compare data against itself
+ // Two messages from Bob next to each other
+ expect(component.vm.chatItems[5].messageChainId).to.eql(
+ component.vm.chatItems[6].messageChainId,
+ )
+
+ // Message from Even right after Bob
+ expect(component.vm.chatItems[7].messageChainId).to.not.eql(
+ component.vm.chatItems[8].messageChainId,
+ )
+ })
+ })
+ describe('methods.getPreviousItem', () => {
+ describe('Finds correct previous meaningful (non-separator) message in the chatlist', () => {
+ let component
+
+ beforeEach(() => {
+ component = shallowMount(ChatMessageList, {
+ props: {
+ messages: [
+ {
+ id: '0',
+ account_id: 'Alice',
+ created_at: new Date('2020-06-22T20:00:00.000Z'),
+ },
+ {
+ // Separator
+ id: '1', // 2
+ account_id: 'Alice',
+ created_at: new Date('2020-06-22T20:06:00.000Z'),
+ },
+ {
+ // Separator
+ id: '2', // 4
+ account_id: 'Alice',
+ created_at: new Date('2020-06-23T20:00:00.000Z'),
+ },
+ {
+ id: '3', // 5
+ account_id: 'Bob',
+ created_at: new Date('2020-06-23T20:01:00.000Z'),
+ },
+ {
+ id: '4', // 6
+ account_id: 'Bob',
+ created_at: new Date('2020-06-23T20:02:00.000Z'),
+ },
+ {
+ id: '5', // 7
+ account_id: 'Bob',
+ created_at: new Date('2020-06-23T20:03:00.000Z'),
+ },
+ {
+ id: '6', // 8
+ account_id: 'Eve',
+ created_at: new Date('2020-06-23T20:04:00.000Z'),
+ },
+ ],
+ },
+ })
+ })
+
+ it('Directly next to each other', () => {
+ const correct = component.vm.chatItems[6]
+ expect(component.vm.getPreviousItem(7)).to.eql(correct)
+ })
+
+ it('Across separator', () => {
+ const correct = component.vm.chatItems[2]
+ expect(component.vm.getPreviousItem(4)).to.eql(correct)
+ })
+
+ it('Returns null if no previous item exist', () => {
+ const correct = null
+ expect(component.vm.getPreviousItem(0)).to.eql(correct)
+ })
+ })
+ })
+})
diff --git a/test/unit/specs/components/chat_view.spec.js b/test/unit/specs/components/chat_view.spec.js
new file mode 100644
index 0000000000..c308e4fbc3
--- /dev/null
+++ b/test/unit/specs/components/chat_view.spec.js
@@ -0,0 +1,137 @@
+import { createTestingPinia } from '@pinia/testing'
+import { shallowMount } from '@vue/test-utils'
+import { setActivePinia } from 'pinia'
+
+import ChatView from 'src/components/chat_view/chat_view.vue'
+
+const message1 = {
+ id: '1',
+ chat_id: 2,
+ idempotency_key: '1',
+ created_at: new Date('2020-06-22T18:45:53.000Z'),
+}
+
+const message2 = {
+ id: '2',
+ chat_id: 2,
+ idempotency_key: '2',
+ account_id: '9vmRb29zLQReckr5ay',
+ created_at: new Date('2020-06-22T18:45:56.000Z'),
+}
+
+const message3 = {
+ id: '3',
+ chat_id: 2,
+ idempotency_key: '3',
+ account_id: '9vmRb29zLQReckr5ay',
+ created_at: new Date('2020-07-22T18:45:59.000Z'),
+}
+
+const global = {
+ mocks: {
+ $store: {
+ state: {
+ api: {},
+ users: {},
+ statuses: {
+ allStatusesObject: {},
+ },
+ },
+ },
+ $route: {
+ params: {
+ recipient_id: 2,
+ },
+ },
+ $router: {
+ push: () => {
+ /* noop */
+ },
+ },
+ },
+ stubs: {
+ FAIcon: true,
+ },
+}
+
+describe('ChatView methods', () => {
+ let component
+ beforeEach(() => {
+ setActivePinia(createTestingPinia())
+ component = shallowMount(ChatView, { global, props: { testMode: true } })
+ component.vm.chat = { id: 2 }
+ })
+
+ describe('addMessages', () => {
+ it("Doesn't add duplicates", () => {
+ component.vm.addMessages({ messages: [message1] })
+ component.vm.addMessages({ messages: [message1] })
+ expect(component.vm.messages.length).to.eql(1)
+
+ component.vm.addMessages({ messages: [message2] })
+ expect(component.vm.messages.length).to.eql(2)
+ })
+
+ it('Updates minId and lastMessage and newMessageCount', async () => {
+ component.vm.addMessages({ messages: [message1] })
+ expect(component.vm.maxId).to.eql(message1.id)
+ expect(component.vm.minId).to.eql(message1.id)
+ expect(component.vm.newMessageCount).to.eql(1)
+
+ component.vm.addMessages({ messages: [message2] })
+ expect(component.vm.maxId).to.eql(message2.id)
+ expect(component.vm.minId).to.eql(message1.id)
+ expect(component.vm.newMessageCount).to.eql(2)
+
+ await component.vm.readChat()
+ expect(component.vm.newMessageCount).to.eql(0)
+ expect(component.vm.lastReadMessageId).to.eql(message2.id)
+
+ // Add message with higher id
+ component.vm.addMessages({ messages: [message3] })
+ expect(component.vm.newMessageCount).to.eql(1)
+ })
+ })
+
+ describe('deleteChatMessage', () => {
+ it('Updates minId and lastMessage', () => {
+ component.vm.addMessages({ messages: [message1] })
+ component.vm.addMessages({ messages: [message2] })
+ component.vm.addMessages({ messages: [message3] })
+
+ expect(component.vm.maxId).to.eql(message3.id)
+ expect(component.vm.minId).to.eql(message1.id)
+
+ component.vm.deleteChatMessage({ messageId: message3.id })
+ expect(component.vm.maxId).to.eql(message2.id)
+ expect(component.vm.minId).to.eql(message1.id)
+
+ component.vm.deleteChatMessage({ messageId: message1.id })
+ expect(component.vm.maxId).to.eql(message2.id)
+ expect(component.vm.minId).to.eql(message2.id)
+ })
+ })
+
+ describe('cullOlder', () => {
+ it('keeps 50 newest messages and messagesIndex matches', () => {
+ for (let i = 100; i > 0; i--) {
+ // Use decimal values with toFixed to hack together constant length predictable strings
+ component.vm.addMessages({
+ messages: [
+ {
+ ...message1,
+ id: 'a' + (i / 1000).toFixed(3),
+ idempotency_key: i,
+ },
+ ],
+ })
+ }
+ component.vm.cullOlder()
+ expect(component.vm.messages.length).to.eql(50)
+ expect(component.vm.messages[0].id).to.eql('a0.051')
+ expect(component.vm.minId).to.eql('a0.051')
+ expect(component.vm.messages[49].id).to.eql('a0.100')
+ expect(Object.keys(component.vm.messagesIndex).length).to.eql(50)
+ })
+ })
+})
diff --git a/test/unit/specs/components/post_status_form.spec.js b/test/unit/specs/components/post_status_form.spec.js
index 8f3d6d80ff..03c0ec8b91 100644
--- a/test/unit/specs/components/post_status_form.spec.js
+++ b/test/unit/specs/components/post_status_form.spec.js
@@ -1,61 +1,322 @@
-import { createTestingPinia } from '@pinia/testing'
import { mount } from '@vue/test-utils'
-import { setActivePinia } from 'pinia'
+import { vi } from 'vitest'
import PostStatusForm from 'src/components/post_status_form/post_status_form.vue'
import { mountOpts } from '../../../fixtures/setup_test'
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
+import { useMergedConfigStore } from 'src/stores/merged_config.js'
const currentUser = {
id: 'current-user',
default_scope: 'public',
locked: false,
}
const repliedUser = {
id: 'replied-user',
screen_name: 'replied',
}
const repliedStatus = {
id: 'status-1',
visibility: 'public',
user: repliedUser,
}
-const replyMountOpts = () =>
+const repliedStatus2 = {
+ id: 'status-2',
+ visibility: 'private',
+ summary: 'subject',
+ user: repliedUser,
+}
+
+const replyMountOpts = (props) =>
mountOpts({
- props: {
- replyTo: repliedStatus.id,
- repliedUser,
- attentions: [],
- copyMessageScope: repliedStatus.visibility,
- disableDraft: true,
- },
+ props,
afterStore(store) {
store.state.users.currentUser = currentUser
store.state.statuses.allStatusesObject = {
[repliedStatus.id]: repliedStatus,
}
},
})
describe('PostStatusForm', () => {
beforeEach(() => {
- setActivePinia(createTestingPinia())
+ vi.useFakeTimers()
})
- it('initializes a reply form when quoteReply is unset', () => {
- useInstanceCapabilitiesStore().quotingAvailable = true
+ it('Clean empty initial state', () => {
+ const wrapper = mount(PostStatusForm, replyMountOpts())
+
+ expect(wrapper.vm.statusType).to.equal('new')
+ expect(wrapper.vm.newStatus.spoilerText).to.eql('')
+ expect(wrapper.vm.newStatus.mentions).to.eql('')
+ expect(wrapper.vm.newStatus.status).to.eql('')
+ })
+ it('Reset cleans form to pristine state equal to state form was when created', () => {
const wrapper = mount(PostStatusForm, replyMountOpts())
- expect(wrapper.vm.newStatus.type).to.equal('reply')
+ const initial = { ...wrapper.vm.newStatus }
+ wrapper.vm.clearStatus()
+
+ expect(wrapper.vm.newStatus).to.eql(initial)
+ })
+
+ it('Initializes a reply form', () => {
+ const wrapper = mount(
+ PostStatusForm,
+ replyMountOpts({
+ repliedStatus: repliedStatus,
+ }),
+ )
+
+ useInstanceCapabilitiesStore().quotingAvailable = true
+
+ expect(wrapper.vm.statusType).to.equal('reply')
+ expect(wrapper.vm.isReply).to.equal(true)
+ expect(wrapper.vm.refId).to.equal('status-1')
+ expect(wrapper.vm.quotable).to.equal(true)
+ expect(wrapper.vm.inReplyToStatusId).to.equal('status-1')
+ expect(wrapper.vm.newStatus.quote).to.eql(null)
+ expect(wrapper.vm.newStatus.poll).to.eql(null)
+ expect(wrapper.vm.newStatus.spoilerText).to.eql('')
+ expect(wrapper.vm.newStatus.mentions).to.eql('@replied')
+ expect(wrapper.vm.newStatus.status).to.eql('@replied ')
+ expect(wrapper.vm.newStatus.visibility).to.eql('public')
+ })
+
+ it('Copies scope and subject line, disables quoting for locked posts', () => {
+ const wrapper = mount(
+ PostStatusForm,
+ replyMountOpts({
+ repliedStatus: repliedStatus2,
+ }),
+ )
+
+ useInstanceCapabilitiesStore().quotingAvailable = true
+
+ expect(wrapper.vm.statusType).to.equal('reply')
+ expect(wrapper.vm.isReply).to.equal(true)
+ expect(wrapper.vm.quotable).to.equal(false)
+ expect(wrapper.vm.newStatus.quote).to.eql(null)
+ expect(wrapper.vm.newStatus.poll).to.eql(null)
+ expect(wrapper.vm.newStatus.spoilerText).to.eql('re: subject')
+ expect(wrapper.vm.newStatus.mentions).to.eql('@replied')
+ expect(wrapper.vm.newStatus.status).to.eql('@replied ')
+ expect(wrapper.vm.newStatus.visibility).to.eql('private')
+
+ expect(wrapper.vm.postingOptions.status).to.eql('@replied ')
+ expect(wrapper.vm.postingOptions.spoilerText).to.eql('re: subject')
+ expect(wrapper.vm.postingOptions.visibility).to.eql('private')
+ expect(wrapper.vm.postingOptions.sensitive).to.eql(false)
+ expect(wrapper.vm.postingOptions.media).to.eql([])
+ expect(wrapper.vm.postingOptions.inReplyToStatusId).to.eql('status-2')
+ expect(wrapper.vm.postingOptions.quoteId).to.eql(null)
+ expect(wrapper.vm.postingOptions.contentType).to.eql('text/plain')
+ expect(wrapper.vm.postingOptions.poll).to.eql(null)
+ })
+
+ it('Forces direct mode when replying to a DM, mastodon style subject handling', () => {
+ // We need to initialize pinia first which is happening here...
+ const options = replyMountOpts({
+ repliedStatus: { ...repliedStatus2, visibility: 'direct' },
+ })
+
+ // ...set our settings...
+ useMergedConfigStore().mergedConfig = {
+ ...useMergedConfigStore().mergedConfig,
+ subjectLineBehavior: 'masto',
+ }
+
+ // ...and only then mount our component
+ const wrapper = mount(PostStatusForm, options)
+
+ // Otherwise we get multiple instances of pinia that don't talk to each other
+
+ expect(wrapper.vm.statusType).to.equal('reply')
+ expect(wrapper.vm.isReply).to.equal(true)
+ expect(wrapper.vm.quotable).to.equal(false)
+ expect(wrapper.vm.newStatus.quote).to.eql(null)
+ expect(wrapper.vm.newStatus.poll).to.eql(null)
+ expect(wrapper.vm.newStatus.spoilerText).to.eql('subject')
+ expect(wrapper.vm.newStatus.mentions).to.eql('@replied')
+ expect(wrapper.vm.newStatus.status).to.eql('@replied ')
+ expect(wrapper.vm.newStatus.visibility).to.eql('direct')
+ })
+
+ it('Sets status to statusText without mentions if mentions line is enabled', () => {
+ const wrapper = mount(
+ PostStatusForm,
+ replyMountOpts({
+ repliedStatus: repliedStatus2,
+ statusText: 'testing',
+ mentionsLine: true,
+ }),
+ )
+
+ expect(wrapper.vm.statusType).to.equal('reply')
+ expect(wrapper.vm.isReply).to.equal(true)
+ expect(wrapper.vm.newStatus.mentions).to.eql('@replied')
+ expect(wrapper.vm.newStatus.status).to.eql('testing')
+ })
+
+ it('Sets mention when asked for it', () => {
+ const wrapper = mount(
+ PostStatusForm,
+ replyMountOpts({
+ profileMention: repliedUser,
+ }),
+ )
+
+ expect(wrapper.vm.statusType).to.equal('mention')
+ expect(wrapper.vm.isReply).to.equal(false)
+ expect(wrapper.vm.newStatus.mentions).to.eql('@replied')
+ expect(wrapper.vm.newStatus.status).to.eql('@replied ')
+ })
+
+ it('Initializes quote when reply/quote toggled to quote', () => {
+ const wrapper = mount(
+ PostStatusForm,
+ replyMountOpts({
+ repliedStatus: repliedStatus2,
+ }),
+ )
+
+ expect(wrapper.vm.statusType).to.equal('reply')
+ expect(wrapper.vm.isReply).to.equal(true)
+
+ wrapper.vm.quoteThreadToggled = true
+
+ expect(wrapper.vm.newStatus.quote).to.eql({ thread: true, id: 'status-2' })
+ })
+
+ it('Resets quote when reply/quote toggled to reply', () => {
+ const wrapper = mount(
+ PostStatusForm,
+ replyMountOpts({
+ repliedStatus: repliedStatus2,
+ }),
+ )
+
+ expect(wrapper.vm.statusType).to.equal('reply')
+ expect(wrapper.vm.isReply).to.equal(true)
+
+ wrapper.vm.quoteThreadToggled = true
+ wrapper.vm.quoteThreadToggled = false
+
+ expect(wrapper.vm.newStatus.quote).to.eql(null)
+ })
+
+ it('Initializes and reset quote when toggling quote attachment', () => {
+ const wrapper = mount(
+ PostStatusForm,
+ replyMountOpts({
+ repliedStatus: repliedStatus2,
+ }),
+ )
+
+ expect(wrapper.vm.statusType).to.equal('reply')
+ expect(wrapper.vm.isReply).to.equal(true)
+
+ wrapper.vm.toggleQuoteForm()
expect(wrapper.vm.newStatus.quote).to.eql({
- id: '',
- url: '',
thread: false,
+ id: null,
+ url: '',
})
+ wrapper.vm.toggleQuoteForm()
+ expect(wrapper.vm.newStatus.quote).to.eql(null)
+ })
+
+ it('Status editing', () => {
+ const wrapper = mount(
+ PostStatusForm,
+ replyMountOpts({
+ statusId: 'edited',
+ statusText: 'text',
+ statusSubject: 'heading',
+ statusIsSensitive: true,
+ statusPoll: {},
+ statusQuote: {},
+ statusFiles: [],
+ statusMediaDescriptions: {},
+ statusVisibility: 'unlisted',
+ statusContentType: 'text/markdown',
+ }),
+ )
+
+ expect(wrapper.vm.statusType).to.equal('edit')
+ expect(wrapper.vm.isReply).to.equal(false) // edits don't support changing reply-to so it's pretty much ignored
+ expect(wrapper.vm.isEdit).to.equal(true)
+ expect(wrapper.vm.newStatus.quote).to.eql({})
+ expect(wrapper.vm.newStatus.poll).to.eql({})
+ expect(wrapper.vm.newStatus.spoilerText).to.eql('heading')
+ expect(wrapper.vm.newStatus.mentions).to.eql('')
+ expect(wrapper.vm.newStatus.status).to.eql('text')
+ expect(wrapper.vm.newStatus.visibility).to.eql('unlisted')
+ expect(wrapper.vm.newStatus.contentType).to.eql('text/markdown')
+ expect(wrapper.vm.newStatus.nsfw).to.equal(true)
+ expect(wrapper.vm.newStatus.files).to.eql([])
+ })
+
+ it('Posting should reset idempotency key', async () => {
+ vi.setSystemTime(new Date(2027, 1, 1, 13))
+ const wrapper = mount(PostStatusForm, replyMountOpts())
+ const oldIdempotency = wrapper.vm.idempotencyKey
+
+ vi.setSystemTime(new Date(2028, 1, 1, 13))
+
+ wrapper.vm.newStatus.status = 'Testing'
+ await wrapper.vm.postStatus()
+
+ expect(wrapper.vm.idempotencyKey).to.not.eql(oldIdempotency)
+ })
+
+ // TODO Probably better to separate attachment upload/manipulation into its own component?
+ // we need to upload-on-submit for compression setting anyway
+ it('Attachments manipulations (moving, adding, removing)', () => {
+ const wrapper = mount(PostStatusForm, replyMountOpts())
+
+ const i1 = { id: '1', url: 'a' }
+ const i2 = { id: '2', url: 'b' }
+ const i3 = { id: '3', url: 'c' }
+ const i4 = { id: '4', url: 'd' }
+ const iX = { id: 'x', url: 'x' }
+
+ wrapper.vm.newStatus.files = [i3, i1, iX, i2]
+
+ wrapper.vm.removeMediaFile(iX)
+ expect(wrapper.vm.newStatus.files).to.eql([i3, i1, i2])
+
+ wrapper.vm.shiftUpMediaFile(i1)
+ expect(wrapper.vm.newStatus.files).to.eql([i1, i3, i2])
+
+ wrapper.vm.shiftUpMediaFile(i1) // should ignore
+ expect(wrapper.vm.newStatus.files).to.eql([i1, i3, i2])
+
+ wrapper.vm.shiftDnMediaFile(i3)
+ expect(wrapper.vm.newStatus.files).to.eql([i1, i2, i3])
+
+ wrapper.vm.shiftDnMediaFile(i3) // should ignore
+ expect(wrapper.vm.newStatus.files).to.eql([i1, i2, i3])
+
+ wrapper.vm.addMediaFile(i4)
+ expect(wrapper.vm.newStatus.files).to.eql([i1, i2, i3, i4])
+ })
+
+ it('Attachment descriptions', () => {
+ const wrapper = mount(PostStatusForm, replyMountOpts())
+
+ const i1 = { id: '1', url: 'a' }
+
+ wrapper.vm.addMediaFile(i1)
+ expect(wrapper.vm.newStatus.files).to.eql([i1])
+
+ wrapper.vm.editAttachment(i1, 'description')
+ expect(wrapper.vm.newStatus.mediaDescriptions['1']).to.eql('description')
})
+ // TODO: Drafts (needs vuex to pinia migration)
})
diff --git a/test/unit/specs/services/chat_service/chat_service.spec.js b/test/unit/specs/services/chat_service/chat_service.spec.js
deleted file mode 100644
index 1cf5aa780b..0000000000
--- a/test/unit/specs/services/chat_service/chat_service.spec.js
+++ /dev/null
@@ -1,122 +0,0 @@
-import chatService from '../../../../../src/services/chat_service/chat_service.js'
-
-const message1 = {
- id: '9wLkdcmQXD21Oy8lEX',
- idempotency_key: '1',
- created_at: new Date('2020-06-22T18:45:53.000Z'),
-}
-
-const message2 = {
- id: '9wLkdp6ihaOVdNj8Wu',
- idempotency_key: '2',
- account_id: '9vmRb29zLQReckr5ay',
- created_at: new Date('2020-06-22T18:45:56.000Z'),
-}
-
-const message3 = {
- id: '9wLke9zL4Dy4OZR2RM',
- idempotency_key: '3',
- account_id: '9vmRb29zLQReckr5ay',
- created_at: new Date('2020-07-22T18:45:59.000Z'),
-}
-
-describe('chatService', () => {
- describe('.add', () => {
- it("Doesn't add duplicates", () => {
- const chat = chatService.empty()
- chatService.add(chat, { messages: [message1] })
- chatService.add(chat, { messages: [message1] })
- expect(chat.messages.length).to.eql(1)
-
- chatService.add(chat, { messages: [message2] })
- expect(chat.messages.length).to.eql(2)
- })
-
- it('Updates minId and lastMessage and newMessageCount', () => {
- const chat = chatService.empty()
-
- chatService.add(chat, { messages: [message1] })
- expect(chat.maxId).to.eql(message1.id)
- expect(chat.minId).to.eql(message1.id)
- expect(chat.newMessageCount).to.eql(1)
-
- chatService.add(chat, { messages: [message2] })
- expect(chat.maxId).to.eql(message2.id)
- expect(chat.minId).to.eql(message1.id)
- expect(chat.newMessageCount).to.eql(2)
-
- chatService.resetNewMessageCount(chat)
- expect(chat.newMessageCount).to.eql(0)
- expect(chat.lastSeenMessageId).to.eql(message2.id)
-
- // Add message with higher id
- chatService.add(chat, { messages: [message3] })
- expect(chat.newMessageCount).to.eql(1)
- })
- })
-
- describe('.delete', () => {
- it('Updates minId and lastMessage', () => {
- const chat = chatService.empty()
-
- chatService.add(chat, { messages: [message1] })
- chatService.add(chat, { messages: [message2] })
- chatService.add(chat, { messages: [message3] })
-
- expect(chat.maxId).to.eql(message3.id)
- expect(chat.minId).to.eql(message1.id)
-
- chatService.deleteMessage(chat, message3.id)
- expect(chat.maxId).to.eql(message2.id)
- expect(chat.minId).to.eql(message1.id)
-
- chatService.deleteMessage(chat, message1.id)
- expect(chat.maxId).to.eql(message2.id)
- expect(chat.minId).to.eql(message2.id)
- })
- })
-
- describe('.getView', () => {
- it('Inserts date separators', () => {
- const chat = chatService.empty()
-
- chatService.add(chat, { messages: [message1] })
- chatService.add(chat, { messages: [message2] })
- chatService.add(chat, { messages: [message3] })
-
- const view = chatService.getView(chat)
- expect(view.map((i) => i.type)).to.eql([
- 'date',
- 'message',
- 'message',
- 'date',
- 'message',
- ])
- })
- })
-
- describe('.cullOlderMessages', () => {
- it('keeps 50 newest messages and idIndex matches', () => {
- const chat = chatService.empty()
-
- for (let i = 100; i > 0; i--) {
- // Use decimal values with toFixed to hack together constant length predictable strings
- chatService.add(chat, {
- messages: [
- {
- ...message1,
- id: 'a' + (i / 1000).toFixed(3),
- idempotency_key: i,
- },
- ],
- })
- }
- chatService.cullOlderMessages(chat)
- expect(chat.messages.length).to.eql(50)
- expect(chat.messages[0].id).to.eql('a0.051')
- expect(chat.minId).to.eql('a0.051')
- expect(chat.messages[49].id).to.eql('a0.100')
- expect(Object.keys(chat.idIndex).length).to.eql(50)
- })
- })
-})

File Metadata

Mime Type
text/x-diff
Expires
Sat, Aug 8, 4:09 PM (1 d, 21 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1723689
Default Alt Text
(674 KB)

Event Timeline