Page MenuHomePhorge

No OneTemporary

Authored By
Unknown
Size
155 KB
Referenced Files
None
Subscribers
None
diff --git a/src/boot/after_store.js b/src/boot/after_store.js
index 2b2c75362e..32c1a65e23 100644
--- a/src/boot/after_store.js
+++ b/src/boot/after_store.js
@@ -1,626 +1,626 @@
/* global process */
import vClickOutside from 'click-outside-vue3'
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import VueVirtualScroller from 'vue-virtual-scroller'
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'
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 { config } from '@fortawesome/fontawesome-svg-core'
import {
FontAwesomeIcon,
FontAwesomeLayers,
} from '@fortawesome/vue-fontawesome'
config.autoAddCss = false
import App from '../App.vue'
import FaviconService from '../services/favicon_service/favicon_service.js'
import { applyStyleConfig } from '../services/style_setter/style_setter.js'
import { initServiceWorker, updateFocus } from '../services/sw/sw.js'
import {
windowHeight,
windowWidth,
} from '../services/window_utils/window_utils'
import routes from './routes'
import { useAuthFlowStore } from 'src/stores/auth_flow'
import { useEmojiStore } from 'src/stores/emoji.js'
import { useI18nStore } from 'src/stores/i18n'
import { useInstanceStore } from 'src/stores/instance.js'
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
import { useInterfaceStore } from 'src/stores/interface.js'
import { useLocalConfigStore } from 'src/stores/local_config.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useOAuthStore } from 'src/stores/oauth.js'
import { useStatusesStore } from 'src/stores/statuses.js'
import { useSyncConfigStore } from 'src/stores/sync_config.js'
import { useUserHighlightStore } from 'src/stores/user_highlight.js'
import { useUsersStore } from 'src/stores/users.js'
import VBodyScrollLock from 'src/directives/body_scroll_lock'
import {
INSTANCE_DEFAULT_CONFIG_DEFINITIONS,
INSTANCE_IDENTITY_DEFAULT_DEFINITIONS,
INSTANCE_IDENTIY_EXTERNAL,
} from 'src/modules/default_config_state.js'
let staticInitialResults = null
const parsedInitialResults = () => {
if (!document.getElementById('initial-results')) {
return null
}
if (!staticInitialResults) {
staticInitialResults = JSON.parse(
document.getElementById('initial-results').textContent,
)
}
return staticInitialResults
}
const decodeUTF8Base64 = (data) => {
const rawData = atob(data)
const array = Uint8Array.from([...rawData].map((char) => char.codePointAt(0)))
const text = new TextDecoder().decode(array)
return text
}
const preloadFetch = async (request) => {
const data = parsedInitialResults()
if (!data?.[request]) {
return window.fetch(request)
}
const decoded = decodeUTF8Base64(data[request])
const requestData = JSON.parse(decoded)
return {
ok: true,
json: () => requestData,
text: () => requestData,
}
}
const getInstanceConfig = async ({ store }) => {
try {
const res = await preloadFetch('/api/v1/instance')
if (res.ok) {
const data = await res.json()
const textLimit = data.max_toot_chars
const vapidPublicKey = data.pleroma.vapid_public_key
useInstanceCapabilitiesStore().set(
'pleromaExtensionsAvailable',
data.pleroma,
)
useInstanceStore().set({
path: 'limits.textLimit',
value: textLimit,
})
useInstanceStore().set({
path: 'accountApprovalRequired',
value: data.approval_required,
})
useInstanceStore().set({
path: 'birthdayRequired',
value: !!data.pleroma?.metadata.birthday_required,
})
useInstanceStore().set({
path: 'birthdayMinAge',
value: data.pleroma?.metadata.birthday_min_age || 0,
})
if (vapidPublicKey) {
useInstanceStore().set({
path: 'vapidPublicKey',
value: vapidPublicKey,
})
}
} else {
throw res
}
} catch (error) {
console.error('Could not load instance config, potentially fatal')
console.error(error)
}
// We should check for scrobbles support here but it requires userId
// so instead we check for it where it's fetched (statuses.js)
}
const getBackendProvidedConfig = async () => {
try {
const res = await window.fetch('/api/pleroma/frontend_configurations')
if (res.ok) {
const data = await res.json()
return data.pleroma_fe
} else {
throw res
}
} catch (error) {
console.error(
'Could not load backend-provided frontend config, potentially fatal',
)
console.error(error)
}
}
const getStaticConfig = async () => {
try {
const res = await window.fetch('/static/config.json')
if (res.ok) {
return res.json()
} else {
throw res
}
} catch (error) {
console.warn(
'Failed to load static/config.json, continuing without it.',
error,
)
return {}
}
}
const setSettings = async ({ apiConfig, staticConfig, store }) => {
const overrides = window.___pleromafe_dev_overrides || {}
const env = window.___pleromafe_mode.NODE_ENV
// This takes static config and overrides properties that are present in apiConfig
let config = {}
if (overrides.staticConfigPreference && env === 'development') {
console.warn('OVERRIDING API CONFIG WITH STATIC CONFIG')
config = { ...apiConfig, ...staticConfig }
} else {
config = { ...staticConfig, ...apiConfig }
}
Object.keys(INSTANCE_IDENTITY_DEFAULT_DEFINITIONS).forEach((source) => {
if (source === 'name') return
if (INSTANCE_IDENTIY_EXTERNAL.has(source)) return
useInstanceStore().set({
value:
config[source] ?? INSTANCE_IDENTITY_DEFAULT_DEFINITIONS[source].default,
path: `instanceIdentity.${source}`,
})
})
Object.keys(INSTANCE_DEFAULT_CONFIG_DEFINITIONS).forEach((source) =>
useInstanceStore().set({
value:
config[source] ?? INSTANCE_DEFAULT_CONFIG_DEFINITIONS[source].default,
path: `prefsStorage.${source}`,
}),
)
useAuthFlowStore().setInitialStrategy(config.loginMethod)
}
const getTOS = async ({ store }) => {
try {
const res = await window.fetch('/static/terms-of-service.html')
if (res.ok) {
const html = await res.text()
useInstanceStore().set({ path: 'instanceIdentity.tos', value: html })
} else {
throw res
}
} catch (e) {
console.warn("Can't load TOS\n", e)
}
}
const getInstancePanel = async ({ store }) => {
try {
const res = await preloadFetch('/instance/panel.html')
if (res.ok) {
const html = await res.text()
useInstanceStore().set({
path: 'instanceIdentity.instanceSpecificPanelContent',
value: html,
})
} else {
throw res
}
} catch (e) {
console.warn("Can't load instance panel\n", e)
}
}
const getStickers = async ({ store }) => {
try {
const res = await window.fetch('/static/stickers.json')
if (res.ok) {
const values = await res.json()
const stickers = (
await Promise.all(
Object.entries(values).map(async ([name, path]) => {
const resPack = await window.fetch(path + 'pack.json')
let meta = {}
if (resPack.ok) {
meta = await resPack.json()
}
return {
pack: name,
path,
meta,
}
}),
)
).sort((a, b) => {
return a.meta.title.localeCompare(b.meta.title)
})
useEmojiStore().setStickers(stickers)
} else {
throw res
}
} catch (e) {
console.warn("Can't load stickers\n", e)
}
}
const resolveStaffAccounts = ({ store, accounts }) => {
const nicknames = accounts.map((uri) => uri.split('/').pop())
useInstanceStore().set({
path: 'staffAccounts',
value: nicknames,
})
}
const getNodeInfo = async ({ store }) => {
try {
let res = await preloadFetch('/nodeinfo/2.1.json')
if (!res.ok) res = await preloadFetch('/nodeinfo/2.0.json')
if (res.ok) {
const data = await res.json()
const metadata = data.metadata
const features = metadata.features
useInstanceStore().set({
path: 'instanceIdentity.name',
value: metadata.nodeName,
})
useInstanceStore().set({
path: 'registrationOpen',
value: data.openRegistrations,
})
useInstanceCapabilitiesStore().set(
'mediaProxyAvailable',
features.includes('media_proxy'),
)
useInstanceCapabilitiesStore().set(
'safeDM',
features.includes('safe_dm_mentions'),
)
useInstanceCapabilitiesStore().set(
'shoutAvailable',
features.includes('chat'),
)
useInstanceCapabilitiesStore().set(
'pleromaChatMessagesAvailable',
features.includes('pleroma_chat_messages'),
)
useInstanceCapabilitiesStore().set(
'pleromaCustomEmojiReactionsAvailable',
features.includes('pleroma_custom_emoji_reactions') ||
features.includes('custom_emoji_reactions'),
)
useInstanceCapabilitiesStore().set(
'pleromaBookmarkFoldersAvailable',
features.includes('pleroma:bookmark_folders'),
)
useInstanceCapabilitiesStore().set(
'gopherAvailable',
features.includes('gopher'),
)
useInstanceCapabilitiesStore().set(
'pollsAvailable',
features.includes('polls'),
)
useInstanceCapabilitiesStore().set(
'editingAvailable',
features.includes('editing'),
)
useInstanceCapabilitiesStore().set(
'mailerEnabled',
metadata.mailerEnabled,
)
useInstanceCapabilitiesStore().set(
'quotingAvailable',
features.includes('quote_posting'),
)
useInstanceCapabilitiesStore().set(
'groupActorAvailable',
features.includes('pleroma:group_actors'),
)
useInstanceCapabilitiesStore().set(
'blockExpiration',
features.includes('pleroma:block_expiration'),
)
useInstanceStore().set({
path: 'localBubbleInstances',
value: metadata.localBubbleInstances ?? [],
})
useInstanceCapabilitiesStore().set(
'localBubble',
(metadata.localBubbleInstances ?? []).length > 0,
)
useInstanceStore().set({
path: 'limits.pollLimits',
value: metadata.pollLimits,
})
const uploadLimits = metadata.uploadLimits
useInstanceStore().set({
path: 'limits.uploadlimit',
value: Number.parseInt(uploadLimits.general),
})
useInstanceStore().set({
path: 'limits.avatarlimit',
value: Number.parseInt(uploadLimits.avatar),
})
useInstanceStore().set({
path: 'limits.backgroundlimit',
value: Number.parseInt(uploadLimits.background),
})
useInstanceStore().set({
path: 'limits.bannerlimit',
value: Number.parseInt(uploadLimits.banner),
})
useInstanceStore().set({
path: 'limits.fieldsLimits',
value: metadata.fieldsLimits,
})
useInstanceStore().set({
path: 'restrictedNicknames',
value: metadata.restrictedNicknames,
})
useInstanceCapabilitiesStore().set('postFormats', metadata.postFormats)
const suggestions = metadata.suggestions
useInstanceCapabilitiesStore().set(
'suggestionsEnabled',
suggestions.enabled,
)
// this is unused, why?
useInstanceCapabilitiesStore().set('suggestionsWeb', suggestions.web)
const software = data.software
useInstanceStore().set({
path: 'backendVersion',
value: software.version,
})
useInstanceStore().set({
path: 'backendRepository',
value: software.repository,
})
const priv = metadata.private
useInstanceStore().set({ path: 'privateMode', value: priv })
const frontendVersion = window.___pleromafe_commit_hash
useInstanceStore().set({
path: 'frontendVersion',
value: frontendVersion,
})
const federation = metadata.federation
useInstanceCapabilitiesStore().set(
'tagPolicyAvailable',
federation.mrf_policies === undefined
? false
: metadata.federation.mrf_policies.includes('TagPolicy'),
)
useInstanceStore().set({
path: 'federationPolicy',
value: federation,
})
useInstanceStore().set({
path: 'federating',
value: federation.enabled === undefined ? true : federation.enabled,
})
const accountActivationRequired = metadata.accountActivationRequired
useInstanceStore().set({
path: 'accountActivationRequired',
value: accountActivationRequired,
})
const accounts = metadata.staffAccounts
resolveStaffAccounts({ store, accounts })
} else {
throw res
}
} catch (e) {
console.warn('Could not load nodeinfo', e)
}
}
const setConfig = async ({ store }) => {
// apiConfig, staticConfig
const configInfos = await Promise.all([
getBackendProvidedConfig(),
getStaticConfig(),
])
const apiConfig = configInfos[0]
const staticConfig = configInfos[1]
await setSettings({ store, apiConfig, staticConfig })
}
const checkOAuthToken = async ({ store }) => {
const oauth = useOAuthStore()
if (oauth.userToken) {
return useUsersStore().loginUser(oauth.userToken)
}
return
}
const afterStoreSetup = async ({ pinia, store, storageError, i18n }) => {
const app = createApp(App)
// Must have app use pinia before we do anything that touches the store
// https://pinia.vuejs.org/core-concepts/plugins.html#Introduction
// "Plugins are only applied to stores created after the plugins themselves, and after pinia is passed to the app, otherwise they won't be applied."
app.use(pinia)
app.config.errorHandler = (error, instance, info) => {
console.error(
'Global Vue Error Handler caught an error:',
error,
instance,
info,
)
useInterfaceStore().setGlobalError({ error, instance, info })
}
const waitForAllStoresToLoad = async () => {
// the stores that do not persist technically do not need to be awaited here,
// but that involves either hard-coding the stores in some place (prone to errors)
// or writing another vite plugin to analyze which stores needs persisting (++load time)
const allStores = import.meta.glob('../stores/*.js', { eager: true })
if (process.env.NODE_ENV === 'development') {
// do some checks to avoid common errors
if (!Object.keys(allStores).length) {
throw new TypeError(
'No stores are available. Check the code in src/boot/after_store.js',
)
}
}
await Promise.all(
Object.entries(allStores).map(async ([name, mod]) => {
const isStoreName = (name) => name.startsWith('use')
if (process.env.NODE_ENV === 'development') {
if (Object.keys(mod).filter(isStoreName).length !== 1) {
throw new TypeError(
'Each store file must export exactly one store as a named export. Check your code in src/stores/',
)
}
}
const storeFuncName = Object.keys(mod).find(isStoreName)
if (storeFuncName && typeof mod[storeFuncName] === 'function') {
const p = mod[storeFuncName]().$persistLoaded
if (!(p instanceof Promise)) {
throw new TypeError(
`${name} store's $persistLoaded is not a Promise. The persist plugin is not applied.`,
)
}
await p
} else {
throw new TypeError(
`Store module ${name} does not export a 'use...' function`,
)
}
}),
)
}
let newStorageError
try {
await waitForAllStoresToLoad()
} catch (e) {
console.error('Cannot load stores:', e)
newStorageError = e
}
if (storageError || newStorageError) {
useInterfaceStore().pushGlobalNotice({
messageKey: 'errors.storage_unavailable',
level: 'error',
})
}
useInterfaceStore().setLayoutWidth(windowWidth())
useInterfaceStore().setLayoutHeight(windowHeight())
window.syncConfig = useSyncConfigStore()
window.mergedConfig = useMergedConfigStore()
window.localConfig = useLocalConfigStore()
window.highlightConfig = useUserHighlightStore()
FaviconService.initFaviconService()
- initServiceWorker(store)
+ initServiceWorker()
window.addEventListener('focus', () => updateFocus())
const overrides = window.___pleromafe_dev_overrides || {}
const server =
overrides.target !== undefined ? overrides.target : window.location.origin
useInstanceStore().set({ path: 'server', value: server })
await setConfig({ store })
try {
await useInterfaceStore()
.applyTheme()
.catch((e) => {
console.error('Error setting theme', e)
})
} catch (e) {
window.splashError(e)
throw e
}
applyStyleConfig(useMergedConfigStore().mergedConfig, i18n.global)
// Now we can try getting the server settings and logging in
// Most of these are preloaded into the index.html so blocking is minimized
await Promise.all([
checkOAuthToken({ store }),
getInstancePanel({ store }),
getNodeInfo({ store }),
getInstanceConfig({ store }),
])
getTOS({ store })
getStickers({ store })
const router = createRouter({
history: createWebHistory(),
routes: routes(store),
scrollBehavior: (to, _from, savedPosition) => {
if (to.matched.some((m) => m.meta.dontScroll)) {
return {}
}
return savedPosition || { left: 0, top: 0 }
},
})
useI18nStore().setI18n(i18n)
// Global WS handlers
useInterfaceStore().attachSocket()
useStatusesStore().attachSocket()
app.use(router)
app.use(store)
app.use(i18n)
// Little thing to get out of invalid theme state
window.resetThemes = () => {
useInterfaceStore().resetThemeV3()
useInterfaceStore().resetThemeV3Palette()
useInterfaceStore().resetThemeV2()
}
app.use(vClickOutside)
app.use(VBodyScrollLock)
app.use(VueVirtualScroller)
app.component('FAIcon', FontAwesomeIcon)
app.component('FALayers', FontAwesomeLayers)
app.component('Status', Status)
app.component('RichContent', RichContent)
app.component('StillImage', StillImage)
// remove after vue 3.3
app.config.unwrapInjectedRef = true
app.mount('#app')
return app
}
export default afterStoreSetup
diff --git a/src/components/chat_new/chat_new.js b/src/components/chat_new/chat_new.js
index 23193c1691..1e26d24fb8 100644
--- a/src/components/chat_new/chat_new.js
+++ b/src/components/chat_new/chat_new.js
@@ -1,83 +1,84 @@
import { mapState } from 'pinia'
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 { useUsersStore } from 'src/stores/users.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 { data } = await chats({
credentials: useOAuthStore().token,
})
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(useUsersStore, ['currentUser', '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' })
+ this.useSearchStore()
+ .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/domain_mute_card/domain_mute_card.js b/src/components/domain_mute_card/domain_mute_card.js
index a0442a7069..274679b8d8 100644
--- a/src/components/domain_mute_card/domain_mute_card.js
+++ b/src/components/domain_mute_card/domain_mute_card.js
@@ -1,28 +1,28 @@
import ProgressButton from 'src/components/progress_button/progress_button.vue'
import { useUsersStore } from 'src/stores/users.js'
const DomainMuteCard = {
props: ['domain'],
components: {
ProgressButton,
},
computed: {
user() {
return useUsersStore().currentUser
},
muted() {
return this.user.domainMutes.includes(this.domain)
},
},
methods: {
unmuteDomain() {
- return this.$store.dispatch('unmuteDomain', this.domain)
+ return useUsersStore().unmuteDomain(this.domain)
},
muteDomain() {
- return this.$store.dispatch('muteDomain', this.domain)
+ return useUsersStore().muteDomain(this.domain)
},
},
}
export default DomainMuteCard
diff --git a/src/components/emoji_input/suggestor.js b/src/components/emoji_input/suggestor.js
index c31cb6717b..6a7dbff9a8 100644
--- a/src/components/emoji_input/suggestor.js
+++ b/src/components/emoji_input/suggestor.js
@@ -1,149 +1,151 @@
+import { useSearchStore } from 'src/stores/search.js'
+
/**
* suggest - generates a suggestor function to be used by emoji-input
* data: object providing source information for specific types of suggestions:
* data.emoji - optional, an array of all emoji available i.e.
* (useEmojiStore().standardEmojiList + state.instance.customEmoji)
* data.users - optional, an array of all known users
* updateUsersList - optional, a function to search and append to users
*
* Depending on data present one or both (or none) can be present, so if field
* doesn't support user linking you can just provide only emoji.
*/
export default (data) => {
const emojiCurry = suggestEmoji(data.emoji)
const usersCurry = data.store && suggestUsers(data.store)
return (input, nameKeywordLocalizer) => {
const firstChar = input[0]
if (firstChar === ':' && data.emoji) {
return emojiCurry(input, nameKeywordLocalizer)
}
if (firstChar === '@' && usersCurry) {
return usersCurry(input)
}
return []
}
}
export const suggestEmoji = (emojis) => (input, nameKeywordLocalizer) => {
const noPrefix = input.toLowerCase().substring(1)
return emojis
.map((emoji) => ({ ...emoji, ...nameKeywordLocalizer(emoji) }))
.filter(
(emoji) =>
emoji.names
.concat(emoji.keywords)
.filter((kw) => kw.toLowerCase().includes(noPrefix)).length,
)
.map((k) => {
let score = 0
// An exact match always wins
score += Math.max(
...k.names.map((name) => (name.toLowerCase() === noPrefix ? 200 : 0)),
0,
)
// Prioritize custom emoji a lot
score += k.imageUrl ? 100 : 0
// Prioritize prefix matches somewhat
score += Math.max(
...k.names.map((kw) =>
kw.toLowerCase().startsWith(noPrefix) ? 10 : 0,
),
0,
)
// Sort by length
score -= k.displayText.length
k.score = score
return k
})
.sort((a, b) => {
// Break ties alphabetically
const alphabetically = a.displayText > b.displayText ? 0.5 : -0.5
return b.score - a.score + alphabetically
})
}
export const suggestUsers = ({ dispatch, state }) => {
// Keep some persistent values in closure, most importantly for the
// custom debounce to work. Lodash debounce does not return a promise.
let suggestions = []
let previousQuery = ''
let timeout = null
let cancelUserSearch = null
- const userSearch = (query) => dispatch('searchUsers', { query })
+ const userSearch = (query) => useSearchStore().searchUsers({ query })
const debounceUserSearch = (query) => {
cancelUserSearch?.()
return new Promise((resolve, reject) => {
timeout = setTimeout(() => {
userSearch(query).then(resolve).catch(reject)
}, 300)
cancelUserSearch = () => {
clearTimeout(timeout)
resolve([])
}
})
}
return async (input) => {
const noPrefix = input.toLowerCase().substr(1)
if (previousQuery === noPrefix) return suggestions
suggestions = []
previousQuery = noPrefix
// Fetch more and wait, don't fetch if there's the 2nd @ because
// the backend user search can't deal with it.
// Reference semantics make it so that we get the updated data after
// the await.
if (!noPrefix.includes('@')) {
await debounceUserSearch(noPrefix)
}
const newSuggestions = state.users.users
.filter(
(user) =>
user.screen_name &&
user.name &&
(user.screen_name.toLowerCase().startsWith(noPrefix) ||
user.name.toLowerCase().startsWith(noPrefix)),
)
.slice(0, 20)
.sort((a, b) => {
let aScore = 0
let bScore = 0
// Matches on screen name (i.e. user@instance) makes a priority
aScore += a.screen_name.toLowerCase().startsWith(noPrefix) ? 2 : 0
bScore += b.screen_name.toLowerCase().startsWith(noPrefix) ? 2 : 0
// Matches on name takes second priority
aScore += a.name.toLowerCase().startsWith(noPrefix) ? 1 : 0
bScore += b.name.toLowerCase().startsWith(noPrefix) ? 1 : 0
const diff = (bScore - aScore) * 10
// Then sort alphabetically
const activity = a.last_status_at < b.last_status_at ? 100 : -100
const nameAlphabetically = a.name > b.name ? 1 : -1
const screenNameAlphabetically = a.screen_name > b.screen_name ? 1 : -1
return diff + nameAlphabetically + screenNameAlphabetically + activity
})
.map((user) => ({
user,
displayText: user.screen_name_ui,
detailText: user.name,
imageUrl: user.profile_image_url_original,
replacement: '@' + user.screen_name + ' ',
}))
suggestions = newSuggestions || []
return suggestions
}
}
diff --git a/src/components/follow_request_card/follow_request_card.js b/src/components/follow_request_card/follow_request_card.js
index 02d3bec343..c4b43811a1 100644
--- a/src/components/follow_request_card/follow_request_card.js
+++ b/src/components/follow_request_card/follow_request_card.js
@@ -1,97 +1,99 @@
import { defineAsyncComponent } from 'vue'
import BasicUserCard from '../basic_user_card/basic_user_card.vue'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useNotificationsStore } from 'src/stores/notifications.js'
import { useOAuthStore } from 'src/stores/oauth.js'
import { approveUser, denyUser } from 'src/api/user.js'
const FollowRequestCard = {
props: ['user'],
components: {
BasicUserCard,
ConfirmModal: defineAsyncComponent(
() => import('src/components/confirm_modal/confirm_modal.vue'),
),
},
data() {
return {
showingApproveConfirmDialog: false,
showingDenyConfirmDialog: false,
}
},
methods: {
findFollowRequestNotificationId() {
const notif = useNotificationsStore().data.find(
(notif) =>
notif.from_profile.id === this.user.id &&
notif.type === 'follow_request',
)
return notif?.id
},
showApproveConfirmDialog() {
this.showingApproveConfirmDialog = true
},
hideApproveConfirmDialog() {
this.showingApproveConfirmDialog = false
},
showDenyConfirmDialog() {
this.showingDenyConfirmDialog = true
},
hideDenyConfirmDialog() {
this.showingDenyConfirmDialog = false
},
approveUser() {
if (this.shouldConfirmApprove) {
this.showApproveConfirmDialog()
} else {
this.doApprove()
}
},
doApprove() {
approveUser({
id: this.user.id,
credentials: useOAuthStore().token,
})
+ // TODO fix
this.$store.dispatch('removeFollowRequest', this.user)
const notifId = this.findFollowRequestNotificationId()
- this.$store.dispatch('markSingleNotificationAsSeen', { id: notifId })
+ useNotificationsStore().markSingleNotificationAsSeen(notifId)
this.hideApproveConfirmDialog()
},
denyUser() {
if (this.shouldConfirmDeny) {
this.showDenyConfirmDialog()
} else {
this.doDeny()
}
},
doDeny() {
const notifId = this.findFollowRequestNotificationId()
denyUser({
id: this.user.id,
credentials: useOAuthStore().token,
}).then(() => {
- this.$store.dispatch('dismissNotificationLocal', { id: notifId })
+ useNotificationsStore().dismissNotificationLocal(notifId)
+ // TODO fix
this.$store.dispatch('removeFollowRequest', this.user)
})
this.hideDenyConfirmDialog()
},
},
computed: {
mergedConfig() {
return useMergedConfigStore().mergedConfig
},
shouldConfirmApprove() {
return this.mergedConfig.modalOnApproveFollow
},
shouldConfirmDeny() {
return this.mergedConfig.modalOnDenyFollow
},
},
}
export default FollowRequestCard
diff --git a/src/components/lists_user_search/lists_user_search.js b/src/components/lists_user_search/lists_user_search.js
index aed3f1ce77..5ac6e679ab 100644
--- a/src/components/lists_user_search/lists_user_search.js
+++ b/src/components/lists_user_search/lists_user_search.js
@@ -1,56 +1,56 @@
import { debounce } from 'lodash'
import Checkbox from 'src/components/checkbox/checkbox.vue'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faChevronLeft, faSearch } from '@fortawesome/free-solid-svg-icons'
library.add(faSearch, faChevronLeft)
const ListsUserSearch = {
components: {
Checkbox,
},
emits: ['loading', 'loadingDone', 'results'],
data() {
return {
loading: false,
query: '',
followingOnly: true,
}
},
methods: {
onInput: debounce(function () {
this.search(this.query)
}, 2000),
search(query) {
if (!query) {
this.loading = false
return
}
this.loading = true
this.$emit('loading')
this.userIds = []
- this.$store
- .dispatch('search', {
+ this.useSearchStore()
+ .search({
q: query,
resolve: true,
type: 'accounts',
following: this.followingOnly,
})
.then((data) => {
this.$emit(
'results',
data.accounts.map((a) => a.id),
)
})
.finally(() => {
this.loading = false
this.$emit('loadingDone')
})
},
},
}
export default ListsUserSearch
diff --git a/src/components/mobile_nav/mobile_nav.js b/src/components/mobile_nav/mobile_nav.js
index 80cfc5326a..163c0e9aad 100644
--- a/src/components/mobile_nav/mobile_nav.js
+++ b/src/components/mobile_nav/mobile_nav.js
@@ -1,167 +1,168 @@
import { mapState } from 'pinia'
import { defineAsyncComponent } from 'vue'
import NavigationPins from 'src/components/navigation/navigation_pins.vue'
import GestureService from '../../services/gesture_service/gesture_service'
import {
countExtraNotifications,
unseenNotifications,
} 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 { useNotificationsStore } from 'src/stores/notifications.js'
import { useUsersStore } from 'src/stores/users.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 useUsersStore().currentUser
},
unseenNotifications() {
return unseenNotifications(
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'
},
shouldConfirmLogout() {
return useMergedConfigStore().mergedConfig.modalOnLogout
},
closingDrawerMarksAsSeen() {
return useMergedConfigStore().mergedConfig.closingDrawerMarksAsSeen
},
...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')
useUsersStore().logout()
this.hideConfirmLogout()
},
markNotificationsAsSeen() {
- this.$store.dispatch('markNotificationsAsSeen')
+ useNotificationsStore().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/notification/notification.js b/src/components/notification/notification.js
index 577a811427..a589c0cf69 100644
--- a/src/components/notification/notification.js
+++ b/src/components/notification/notification.js
@@ -1,238 +1,237 @@
import { mapState } from 'pinia'
import { defineAsyncComponent } from 'vue'
import Report from 'src/components/report/report.vue'
import StatusContent 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'
import UserLink from 'src/components/user_link/user_link.vue'
import UserPopover from 'src/components/user_popover/user_popover.vue'
import { isStatusNotification } from '../../services/notification_utils/notification_utils_sw.js'
import {
highlightClass,
highlightStyle,
} from '../../services/user_highlighter/user_highlighter.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
+import { useNotificationsStore } from 'src/stores/notifications.js'
import { useOAuthStore } from 'src/stores/oauth.js'
import { useStatusesStore } from 'src/stores/statuses.js'
import { useUserHighlightStore } from 'src/stores/user_highlight.js'
import { useUsersStore } from 'src/stores/users.js'
import { approveUser, denyUser } from 'src/api/user.js'
import generateProfileLink from 'src/services/user_profile_link_generator/user_profile_link_generator'
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faCheck,
faCompressAlt,
faExpandAlt,
faEyeSlash,
faRetweet,
faStar,
faSuitcaseRolling,
faTimes,
faUser,
faUserPlus,
} from '@fortawesome/free-solid-svg-icons'
library.add(
faCheck,
faTimes,
faStar,
faRetweet,
faUserPlus,
faUser,
faEyeSlash,
faSuitcaseRolling,
faExpandAlt,
faCompressAlt,
)
const Notification = {
data() {
return {
selecting: false,
statusExpanded: false,
unmuted: false,
showingApproveConfirmDialog: false,
showingDenyConfirmDialog: false,
}
},
props: ['notification'],
emits: ['interacted'],
components: {
StatusContent,
UserAvatar,
Timeago,
Report,
UserPopover,
UserLink,
ConfirmModal: defineAsyncComponent(
() => import('src/components/confirm_modal/confirm_modal.vue'),
),
},
mounted() {
document.addEventListener('selectionchange', this.onContentSelect)
},
unmounted() {
document.removeEventListener('selectionchange', this.onContentSelect)
},
methods: {
toggleStatusExpanded() {
if (!this.expandable) return
this.statusExpanded = !this.statusExpanded
},
onContentSelect() {
const { isCollapsed, anchorNode, offsetNode } = document.getSelection()
if (isCollapsed) {
this.selecting = false
return
}
const within =
this.$refs.root.contains(anchorNode) ||
this.$refs.root.contains(offsetNode)
if (within) {
this.selecting = true
} else {
this.selecting = false
}
},
onContentClick(e) {
if (
!this.selecting &&
!e.target.closest('a') &&
!e.target.closest('button')
) {
this.toggleStatusExpanded()
}
},
generateUserProfileLink(user) {
return generateProfileLink(
user.id,
user.screen_name,
useInstanceStore().restrictedNicknames,
)
},
getUser(notification) {
return this.$store.state.users.usersObject[notification.from_profile.id]
},
interacted() {
this.$emit('interacted')
},
toggleMute() {
this.unmuted = !this.unmuted
},
showApproveConfirmDialog() {
this.showingApproveConfirmDialog = true
},
hideApproveConfirmDialog() {
this.showingApproveConfirmDialog = false
},
showDenyConfirmDialog() {
this.showingDenyConfirmDialog = true
},
hideDenyConfirmDialog() {
this.showingDenyConfirmDialog = false
},
approveUser() {
if (this.shouldConfirmApprove) {
this.showApproveConfirmDialog()
} else {
this.doApprove()
}
},
doApprove() {
approveUser({
id: this.user.id,
credentials: useOAuthStore().token,
})
+ // TODO Fix this
this.$store.dispatch('removeFollowRequest', this.user)
- this.$store.dispatch('markSingleNotificationAsSeen', {
- id: this.notification.id,
- })
+ useNotificationsStore().markSingleNotificationAsSeen(this.notification.id)
this.hideApproveConfirmDialog()
},
denyUser() {
if (this.shouldConfirmDeny) {
this.showDenyConfirmDialog()
} else {
this.doDeny()
}
},
doDeny() {
denyUser({
id: this.user.id,
credentials: useOAuthStore().token,
}).then(() => {
- this.$store.dispatch('dismissNotificationLocal', {
- id: this.notification.id,
- })
+ useNotificationsStore().dismissNotificationLocal(this.notification.id)
+ // TODO Fix this
this.$store.dispatch('removeFollowRequest', this.user)
})
this.hideDenyConfirmDialog()
},
},
computed: {
status() {
// Used for StatusContent
if (this.notification.status) {
return useStatusesStore().allStatuses.get(this.notification.status.id)
}
},
userClass() {
return highlightClass(this.notification.from_profile)
},
userStyle() {
const user = this.notification.from_profile.screen_name
return highlightStyle(useUserHighlightStore().get(user))
},
expandable() {
return new Set(['like', 'pleroma:emoji_reaction', 'repeat', 'poll']).has(
this.notification.type,
)
},
user() {
return useUsersStore().findUser(this.notification.from_profile.id)
},
userProfileLink() {
return this.generateUserProfileLink(this.user)
},
targetUser() {
return useUsersStore().findUser(this.notification.target.id)
},
targetUserProfileLink() {
return this.generateUserProfileLink(this.targetUser)
},
needMute() {
return useUsersStore().relationship(this.user.id).muting
},
isStatusNotification() {
return isStatusNotification(this.notification.type)
},
mergedConfig() {
return useMergedConfigStore().mergedConfig
},
allowNonSquareEmoji() {
return this.mergedConfig.nonSquareEmoji
},
pauseMfm() {
return this.mergedConfig.pauseMfm
},
scaleMfm() {
return this.mergedConfig.scaleMfm
},
shouldConfirmApprove() {
return this.mergedConfig.modalOnApproveFollow
},
shouldConfirmDeny() {
return this.mergedConfig.modalOnDenyFollow
},
...mapState(useUsersStore, ['currentUser']),
},
}
export default Notification
diff --git a/src/components/notifications/notifications.js b/src/components/notifications/notifications.js
index 3f65cc65b8..e642fc5545 100644
--- a/src/components/notifications/notifications.js
+++ b/src/components/notifications/notifications.js
@@ -1,256 +1,255 @@
import { mapState } from 'pinia'
import { computed } from 'vue'
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,
filteredNotifications,
unseenNotifications,
} from '../../services/notification_utils/notification_utils.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 { useNotificationsStore } from 'src/stores/notifications.js'
-import { useUsersStore } from 'src/stores/users.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,
// 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 useNotificationsStore().data
},
error() {
return useNotificationsStore().error
},
unseenNotifications() {
return unseenNotifications(
useMergedConfigStore().mergedConfig.notificationVisibility,
useMergedConfigStore().mergedConfig.ignoreInactionableSeen,
)
},
filteredNotifications() {
if (this.unseenAtTop) {
return [
...filteredNotifications(
useMergedConfigStore().mergedConfig.notificationVisibility,
).filter((n) => this.shouldShowUnseen(n)),
...filteredNotifications(
useMergedConfigStore().mergedConfig.notificationVisibility,
).filter((n) => !this.shouldShowUnseen(n)),
]
} else {
return filteredNotifications(
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.unreadChatsCount +
this.unreadAnnouncementCount
)
},
loading() {
return useNotificationsStore().fetcher.loading.value
},
bottomedOut() {
return useNotificationsStore().fetcher.bottomedOut.value
},
noHeading() {
const { layoutType } = useInterfaceStore()
return this.minimalMode || layoutType === 'mobile'
},
teleportTarget() {
const map = {
wide: '#notifs-column',
mobile: '#mobile-notifications',
}
return map[this.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']),
...mapState(useChatsStore, ['unreadChatsCount']),
...mapState(useInterfaceStore, ['layoutType']),
},
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
useNotificationsStore().notificationClicked(id)
},
notificationInteracted(notification) {
const { id } = notification
useNotificationsStore().markSingleNotificationAsSeen(id)
},
markAsSeen() {
useNotificationsStore().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
}
useNotificationsStore().fetcher.fetchOlder()
},
},
}
export default Notifications
diff --git a/src/components/quote/quote_form.js b/src/components/quote/quote_form.js
index b350fb0e3c..61abf743b3 100644
--- a/src/components/quote/quote_form.js
+++ b/src/components/quote/quote_form.js
@@ -1,120 +1,120 @@
import { debounce } from 'lodash'
import Checkbox from 'src/components/checkbox/checkbox.vue'
import Quote from './quote.vue'
import { useInstanceStore } from 'src/stores/instance.js'
export default {
components: {
Quote,
Checkbox,
},
name: 'QuoteForm',
props: {
visible: {
type: Boolean,
},
url: {
type: String,
required: false,
default: '',
},
id: {
type: String,
required: false,
default: '',
},
},
data() {
return {
text: this.url,
loading: false,
error: false,
debounceSetQuote: debounce((value) => {
this.fetchStatus(value)
}, 1000),
}
},
created() {
if (this.url && !this.id) {
this.fetchStatus(this.url)
} else if (this.id) {
this.text =
window.location.protocol +
'//' +
this.instanceHost +
'/notice/' +
this.id
}
},
computed: {
instanceHost() {
return new URL(useInstanceStore().server).host
},
noticeRegex() {
return new RegExp(
`^([^/:]*:?//|)(${window.location.host}|${this.instanceHost})/notice/(.*)$`,
)
},
quoteVisible() {
return (!!this.id || this.loading) && !this.error
},
},
watch: {
text(value) {
this.debounceSetQuote(value)
this.$emit('update:url', value)
},
visible(value) {
if (value && this.url) {
this.fetchStatus(this.url)
}
},
},
methods: {
clear() {
this.text = this.url
this.loading = false
this.error = false
},
setLoading(value) {
this.loading = value
},
handleError(error) {
this.id = null
this.error = !!error
},
fetchStatus(value) {
this.error = false
const notice = this.noticeRegex.exec(value)
if (notice?.length === 4) {
this.$emit('update:id', notice[3])
} else if (value) {
this.loading = true
- this.$store
- .dispatch('search', {
+ this.useSearchStore()
+ .search({
q: value,
resolve: true,
offset: 0,
limit: 1,
type: 'statuses',
})
.then((data) => {
if (data?.statuses?.length === 1) {
this.$emit('update:id', data.statuses[0].id)
} else {
this.handleError(true)
}
})
.catch(this.handleError)
.finally(() => {
this.loading = false
})
} else {
this.$emit('update:id', null)
}
},
},
}
diff --git a/src/components/remove_follower_button/remove_follower_button.js b/src/components/remove_follower_button/remove_follower_button.js
index cbe92dce16..a0e7a0f133 100644
--- a/src/components/remove_follower_button/remove_follower_button.js
+++ b/src/components/remove_follower_button/remove_follower_button.js
@@ -1,54 +1,55 @@
import { defineAsyncComponent } from 'vue'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
+import { useUsersStore } from 'src/stores/users.js'
export default {
props: ['user', 'relationship'],
data() {
return {
inProgress: false,
showingConfirmRemoveFollower: false,
}
},
components: {
ConfirmModal: defineAsyncComponent(
() => import('src/components/confirm_modal/confirm_modal.vue'),
),
},
computed: {
label() {
if (this.inProgress) {
return this.$t('user_card.follow_progress')
} else {
return this.$t('user_card.remove_follower')
}
},
shouldConfirmRemoveUserFromFollowers() {
return useMergedConfigStore().mergedConfig.modalOnRemoveUserFromFollowers
},
},
methods: {
showConfirmRemoveUserFromFollowers() {
this.showingConfirmRemoveFollower = true
},
hideConfirmRemoveUserFromFollowers() {
this.showingConfirmRemoveFollower = false
},
onClick() {
if (!this.shouldConfirmRemoveUserFromFollowers) {
this.doRemoveUserFromFollowers()
} else {
this.showConfirmRemoveUserFromFollowers()
}
},
doRemoveUserFromFollowers() {
this.inProgress = true
- this.$store
- .dispatch('removeUserFromFollowers', this.relationship.id)
- .then(() => {
+ useUsersStore()
+ .removeUserFromFollowers(this.relationship.id)
+ .finally(() => {
this.inProgress = false
})
this.hideConfirmRemoveUserFromFollowers()
},
},
}
diff --git a/src/components/search/search.js b/src/components/search/search.js
index e4c2c56742..43a9b4f737 100644
--- a/src/components/search/search.js
+++ b/src/components/search/search.js
@@ -1,133 +1,134 @@
import { map, uniqBy } from 'lodash'
import Conversation from 'src/components/conversation/conversation.vue'
import FollowCard from 'src/components/follow_card/follow_card.vue'
import TabSwitcher from 'src/components/tab_switcher/tab_switcher.jsx'
+import { useSearchStore } from 'src/stores/search.js'
import { useStatusesStore } from 'src/stores/statuses.js'
import { useUsersStore } from 'src/stores/users.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faCircleNotch, faSearch } from '@fortawesome/free-solid-svg-icons'
library.add(faCircleNotch, faSearch)
const Search = {
components: {
FollowCard,
Conversation,
TabSwitcher,
},
props: ['query'],
data() {
return {
loaded: false,
loading: false,
searchTerm: this.query || '',
userIds: [],
statuses: [],
hashtags: [],
currenResultTab: 'statuses',
statusesOffset: 0,
lastStatusFetchCount: 0,
lastQuery: '',
}
},
computed: {
users() {
return this.userIds.map((userId) => useUsersStore().findUser(userId))
},
visibleStatuses() {
const allStatuses = useStatusesStore().allStatuses
return this.statuses.filter(
(status) =>
allStatuses.has(status.id) && !allStatuses.get(status.id).deleted,
)
},
},
mounted() {
this.search(this.query)
},
watch: {
query(newValue) {
this.searchTerm = newValue
this.search(newValue)
},
},
methods: {
newQuery(query) {
this.$router.push({ name: 'search', query: { query } })
this.$refs.searchInput.focus()
},
search(query, searchType = null) {
if (!query) {
this.loading = false
return
}
this.loading = true
this.$refs.searchInput.blur()
if (this.lastQuery !== query) {
this.userIds = []
this.hashtags = []
this.statuses = []
this.statusesOffset = 0
this.lastStatusFetchCount = 0
}
- this.$store
- .dispatch('search', {
+ useSearchStore()
+ .search({
q: query,
resolve: true,
offset: this.statusesOffset,
type: searchType,
})
.then((data) => {
this.loading = false
const oldLength = this.statuses.length
// Always append to old results. If new results are empty, this doesn't change anything
this.userIds = this.userIds.concat(map(data.accounts, 'id'))
this.statuses = uniqBy(this.statuses.concat(data.statuses), 'id')
this.hashtags = this.hashtags.concat(data.hashtags)
this.currenResultTab = this.getActiveTab()
this.loaded = true
// Offset from whatever we already have
this.statusesOffset = this.statuses.length
// Because the amount of new statuses can actually be zero, compare to old lenght instead
this.lastStatusFetchCount = this.statuses.length - oldLength
this.lastQuery = query
})
},
resultCount(tabName) {
const length = this[tabName].length
return length === 0 ? '' : ` (${length})`
},
onResultTabSwitch(key) {
this.currenResultTab = key
},
getActiveTab() {
if (this.visibleStatuses.length > 0) {
return 'statuses'
} else if (this.users.length > 0) {
return 'people'
} else if (this.hashtags.length > 0) {
return 'hashtags'
}
return 'statuses'
},
lastHistoryRecord(hashtag) {
return hashtag.history?.[0]
},
},
}
export default Search
diff --git a/src/components/settings_modal/tabs/composing_tab.js b/src/components/settings_modal/tabs/composing_tab.js
index dadb2498fc..3e734e6e90 100644
--- a/src/components/settings_modal/tabs/composing_tab.js
+++ b/src/components/settings_modal/tabs/composing_tab.js
@@ -1,192 +1,193 @@
import { mapState } from 'pinia'
import FontControl from 'src/components/font_control/font_control.vue'
import InterfaceLanguageSwitcher from 'src/components/interface_language_switcher/interface_language_switcher.vue'
import ScopeSelector from 'src/components/scope_selector/scope_selector.vue'
import Select from 'src/components/select/select.vue'
import BooleanSetting from '../helpers/boolean_setting.vue'
import ChoiceSetting from '../helpers/choice_setting.vue'
import FloatSetting from '../helpers/float_setting.vue'
import IntegerSetting from '../helpers/integer_setting.vue'
import SharedComputedObject from '../helpers/shared_computed_object.js'
import UnitSetting from '../helpers/unit_setting.vue'
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 { useOAuthStore } from 'src/stores/oauth.js'
import { useSyncConfigStore } from 'src/stores/sync_config.js'
import { useUsersStore } from 'src/stores/users.js'
import { updateProfile } from 'src/api/user.js'
import localeService from 'src/services/locale/locale.service.js'
import { cacheKey, clearCache, emojiCacheKey } from 'src/services/sw/sw.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faDatabase,
faGlobe,
faMessage,
faPenAlt,
faSliders,
} from '@fortawesome/free-solid-svg-icons'
library.add(faGlobe, faMessage, faPenAlt, faDatabase, faSliders)
const ComposingTab = {
data() {
return {
subjectLineOptions: ['email', 'noop', 'masto'].map((mode) => ({
key: mode,
value: mode,
label: this.$t(
`settings.subject_line_${mode === 'masto' ? 'mastodon' : mode}`,
),
})),
conversationDisplayOptions: ['tree', 'linear'].map((mode) => ({
key: mode,
value: mode,
label: this.$t(`settings.conversation_display_${mode}`),
})),
absoluteTime12hOptions: ['24h', '12h'].map((mode) => ({
key: mode,
value: mode,
label: this.$t(`settings.absolute_time_format_12h_${mode}`),
})),
conversationOtherRepliesButtonOptions: ['below', 'inside'].map(
(mode) => ({
key: mode,
value: mode,
label: this.$t(`settings.conversation_other_replies_button_${mode}`),
}),
),
mentionLinkDisplayOptions: ['short', 'full_for_remote', 'full'].map(
(mode) => ({
key: mode,
value: mode,
label: this.$t(`settings.mention_link_display_${mode}`),
}),
),
userPopoverAvatarActionOptions: ['close', 'zoom', 'open'].map((mode) => ({
key: mode,
value: mode,
label: this.$t(`settings.user_popover_avatar_action_${mode}`),
})),
unsavedPostActionOptions: ['save', 'discard', 'confirm'].map((mode) => ({
key: mode,
value: mode,
label: this.$t(`settings.unsaved_post_action_${mode}`),
})),
loopSilentAvailable:
// Firefox
Object.getOwnPropertyDescriptor(
HTMLVideoElement.prototype,
'mozHasAudio',
) ||
// Chrome-likes
Object.getOwnPropertyDescriptor(
HTMLMediaElement.prototype,
'webkitAudioDecodedByteCount',
) ||
// Future spec, still not supported in Nightly 63 as of 08/2018
Object.getOwnPropertyDescriptor(
HTMLMediaElement.prototype,
'audioTracks',
),
emailLanguage: useUsersStore().currentUser.language || [''],
}
},
components: {
BooleanSetting,
ChoiceSetting,
IntegerSetting,
FloatSetting,
UnitSetting,
InterfaceLanguageSwitcher,
ScopeSelector,
Select,
FontControl,
},
computed: {
postFormats() {
return useInstanceCapabilitiesStore().postFormats
},
postContentOptions() {
return this.postFormats.map((format) => ({
key: format,
value: format,
label: this.$t(`post_status.content_type["${format}"]`),
}))
},
language: {
get: function () {
return useMergedConfigStore().mergedConfig.interfaceLanguage
},
set: function (val) {
useSyncConfigStore().setSimplePrefAndSave({
path: 'interfaceLanguage',
value: val,
})
},
},
...SharedComputedObject(),
...mapState(useInstanceStore, ['blockExpiration']),
},
methods: {
changeDefaultScope(value) {
this.$store.dispatch('setProfileOption', { name: 'defaultScope', value })
},
clearCache(key) {
clearCache(key)
.then(() => {
- this.$store.dispatch('settingsSaved', { success: true })
+ useInterfaceStore().settingsSaved({ success: true })
})
.catch((error) => {
- this.$store.dispatch('settingsSaved', { error })
+ useInterfaceStore().settingsSaved({ error })
})
},
tooSmall() {
this.$emit('tooSmall')
},
tooBig() {
this.$emit('tooBig')
},
getNavMode() {
return this.$refs.tabSwitcher.getNavMode()
},
clearAssetCache() {
this.clearCache(cacheKey)
},
clearEmojiCache() {
this.clearCache(emojiCacheKey)
},
updateProfile() {
const params = {
language: localeService.internalToBackendLocaleMulti(
this.emailLanguage,
),
}
updateProfile({
params,
credentials: useOAuthStore().token,
}).then((result) => {
useUsersStore().addNewUsers(result)
})
},
updateFont(key, value) {
useSyncConfigStore().setSimplePrefAndSave({
path: 'theme3hacks',
value: {
...this.mergedConfig.theme3hacks,
fonts: {
...this.mergedConfig.theme3hacks.fonts,
[key]: value,
},
},
})
},
},
}
export default ComposingTab
diff --git a/src/components/settings_modal/tabs/developer_tab.js b/src/components/settings_modal/tabs/developer_tab.js
index 9a6258638a..9697233d58 100644
--- a/src/components/settings_modal/tabs/developer_tab.js
+++ b/src/components/settings_modal/tabs/developer_tab.js
@@ -1,47 +1,48 @@
import { mapState } from 'pinia'
import BooleanSetting from '../helpers/boolean_setting.vue'
import SharedComputedObject from '../helpers/shared_computed_object.js'
import { useInstanceStore } from 'src/stores/instance.js'
+import { useInterfaceStore } from 'src/stores/interface.js'
import { cacheKey, clearCache, emojiCacheKey } from 'src/services/sw/sw.js'
const pleromaFeCommitUrl =
'https://git.pleroma.social/pleroma/pleroma-fe/commit/'
const VersionTab = {
components: {
BooleanSetting,
},
computed: {
frontendVersionLink() {
return pleromaFeCommitUrl + this.frontendVersion
},
...mapState(useInstanceStore, [
'backendVersion',
'backendRepository',
'frontendVersion',
]),
...SharedComputedObject(),
},
methods: {
clearAssetCache() {
this.clearCache(cacheKey)
},
clearEmojiCache() {
this.clearCache(emojiCacheKey)
},
clearCache(key) {
clearCache(key)
.then(() => {
- this.$store.dispatch('settingsSaved', { success: true })
+ useInterfaceStore().settingsSaved({ success: true })
})
.catch((error) => {
- this.$store.dispatch('settingsSaved', { error })
+ useInterfaceStore().settingsSaved({ error })
})
},
},
}
export default VersionTab
diff --git a/src/components/settings_modal/tabs/mutes_and_blocks_tab.js b/src/components/settings_modal/tabs/mutes_and_blocks_tab.js
index e7884992ee..824ec6a2e9 100644
--- a/src/components/settings_modal/tabs/mutes_and_blocks_tab.js
+++ b/src/components/settings_modal/tabs/mutes_and_blocks_tab.js
@@ -1,141 +1,142 @@
import { get, map, reject } from 'lodash'
import Autosuggest from 'src/components/autosuggest/autosuggest.vue'
import BlockCard from 'src/components/block_card/block_card.vue'
import Checkbox from 'src/components/checkbox/checkbox.vue'
import DomainMuteCard from 'src/components/domain_mute_card/domain_mute_card.vue'
import List from 'src/components/list/list.vue'
import MuteCard from 'src/components/mute_card/mute_card.vue'
import ProgressButton from 'src/components/progress_button/progress_button.vue'
import TabSwitcher from 'src/components/tab_switcher/tab_switcher.jsx'
import { useInstanceStore } from 'src/stores/instance.js'
import { useOAuthStore } from 'src/stores/oauth.js'
import { useOAuthTokensStore } from 'src/stores/oauth_tokens.js'
+import { useSearchStore } from 'src/stores/search.js'
import { useUsersStore } from 'src/stores/users.js'
import { importBlocks, importFollows } from 'src/api/user.js'
const MutesAndBlocks = {
data() {
return {
activeTab: 'profile',
}
},
created() {
useOAuthTokensStore().fetchTokens()
useInstanceStore().getKnownDomains()
},
components: {
TabSwitcher,
DomainMuteCard,
BlockCard,
List,
MuteCard,
ProgressButton,
Autosuggest,
Checkbox,
},
computed: {
knownDomains() {
return useInstanceStore().knownDomains
},
user() {
return useUsersStore().currentUser
},
blocks() {
return get(this.user, 'blockIds', [])
},
mutes() {
return get(this.user, 'muteIds', [])
},
domains() {
return get(this.user, 'domainMutes', [])
},
},
methods: {
fetchItems(group) {
return () => useUsersStore()['fetch' + group](this.userId)
},
importFollows(file) {
return importFollows({
file,
credentials: useOAuthStore().token,
}).then(({ data: status }) => {
if (!status) {
throw new Error('failed')
}
})
},
importBlocks(file) {
return importBlocks({
file,
credentials: useOAuthStore().token,
}).then(({ data: status }) => {
if (!status) {
throw new Error('failed')
}
})
},
generateExportableUsersContent(users) {
// Get addresses
return users
.map((user) => {
// check is it's a local user
if (user?.is_local) {
// append the instance address
return user.screen_name + '@' + location.hostname
}
return user.screen_name
})
.join('\n')
},
activateTab(tabName) {
this.activeTab = tabName
},
filterUnblockedUsers(userIds) {
return reject(userIds, (userId) => {
const relationship = useUsersStore().relationship(this.userId)
return relationship.blocking || userId === this.user.id
})
},
filterUnMutedUsers(userIds) {
return reject(userIds, (userId) => {
const relationship = useUsersStore().relationship(this.userId)
return relationship.muting || userId === this.user.id
})
},
queryUserIds(query) {
- return this.$store
- .dispatch('searchUsers', { query })
+ return useSearchStore()
+ .searchUsers({ query })
.then((users) => map(users, 'id'))
},
blockUsers(ids) {
return useUsersStore().blockUsers(ids)
},
unblockUsers(ids) {
return useUsersStore().unblockUsers(ids)
},
muteUsers(ids) {
return useUsersStore().muteUsers(ids)
},
unmuteUsers(ids) {
return useUsersStore().unmuteUsers(ids)
},
filterUnMutedDomains(urls) {
return urls.filter((url) => !this.user.domainMutes.includes(url))
},
queryKnownDomains(query) {
return new Promise((resolve) => {
resolve(
this.knownDomains.filter((url) => url.toLowerCase().includes(query)),
)
})
},
unmuteDomains(domains) {
- return this.$store.dispatch('unmuteDomains', domains)
+ return useUsersStore().unmuteDomains(domains)
},
},
}
export default MutesAndBlocks
diff --git a/src/components/status/status.js b/src/components/status/status.js
index 7c8400bdce..d807b64fff 100644
--- a/src/components/status/status.js
+++ b/src/components/status/status.js
@@ -1,586 +1,586 @@
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 { useScrobblesStore } from 'src/stores/scrobbles.js'
import { useStatusesStore } from 'src/stores/statuses.js'
import { useSyncConfigStore } from 'src/stores/sync_config.js'
import { useUserHighlightStore } from 'src/stores/user_highlight.js'
import { useUsersStore } from 'src/stores/users.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: {
statusId: String,
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,
}
},
created() {
useScrobblesStore().getLatestScrobble(this.status.user.id)
},
computed: {
status() {
return this.statusoid ?? useStatusesStore().allStatuses.get(this.statusId)
},
repeater() {
return useUsersStore().findUser(this.status.user.id)
},
user() {
return useUsersStore().findUser(this.mainStatus.user.id)
},
showReasonMutedThread() {
return (
(this.mainStatus.thread_muted ||
this.smainSatus.reblog?.thread_muted) &&
!this.inConversation
)
},
allowNonSquareEmoji() {
return this.mergedConfig.nonSquareEmoji
},
pauseMfm() {
return this.mergedConfig.pauseMfm
},
scaleMfm() {
return this.mergedConfig.scaleMfm
},
repeaterClass() {
return highlightClass(this.repeater)
},
userClass() {
return highlightClass(this.user)
},
deleted() {
return this.status.deleted
},
repeaterStyle() {
return highlightStyle(
useUserHighlightStore().get(this.repeater.screen_name),
)
},
userStyle() {
if (this.noHeading) return
return highlightStyle(useUserHighlightStore().get(this.user.screen_name))
},
userProfileLink() {
return this.generateUserProfileLink(this.user.id, this.user.screen_name)
},
replyProfileLink() {
if (this.isReply) {
const user = useUsersStore().findUser(
this.mainStatus.in_reply_to_user_id,
)
// FIXME Why user not found sometimes???
return user ? user.statusnet_profile_url : 'NOT_FOUND'
}
},
retweet() {
return !!this.status.retweeted_status
},
repeaterName() {
return this.status.user.name || this.status.user.screen_name_ui
},
repeaterHtml() {
return this.status.user.name
},
repeaterProfileLink() {
return this.generateUserProfileLink(
this.repeater.id,
this.repeater.screen_name,
)
},
mainStatus() {
if (this.retweet) {
return this.status.retweeted_status
} else {
return this.status
}
},
loggedIn() {
return !!this.currentUser
},
muteFilterHits() {
return muteFilterHits(
Object.values(
useSyncConfigStore().prefsStorage.simple.muteFilters || {},
),
this.status,
)
},
botStatus() {
return this.status.user.actor_type === 'Service'
},
sensitiveStatus() {
return this.status.nsfw
},
mentionsLine() {
if (!this.headTailLinks) return []
const writtenSet = new Set(
this.headTailLinks.writtenMentions.map((_) => _.url),
)
return this.mainStatus.attentions
.filter((attn) => {
// no reply user
return (
attn.id !== this.mainStatus.in_reply_to_user_id &&
// no self-replies
attn.statusnet_profile_url !==
this.mainStatus.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.mainStatus.thread_muted ? 'thread' : null,
this.muteFilterHits.length > 0 ? 'filtered' : null,
this.muteBotStatuses && this.botStatus ? 'bot' : null,
this.muteSensitiveStatuses && this.sensitiveStatus ? 'nsfw' : null,
].filter(Boolean)
},
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.status.user.id === this.currentUser?.id) return false
return !this.unmuted && !this.shouldNotMute && this.muteReasons.length > 0
},
userIsMuted() {
if (this.status.user.id === this.currentUser?.id) return false
const { reblog } = this.status
const relationship = useUsersStore().relationship(this.status.user.id)
const relationshipReblog =
reblog && useUsersStore().relationship(reblog.user.id)
return (
(status.muted && !status.thread_muted) ||
// Reprööt of a muted post according to BE
(reblog?.muted && !reblog.thread_muted) ||
// Muted user
relationship.muting ||
// Muted user of a reprööt
relationshipReblog?.muting
)
},
shouldNotMute() {
if (this.ignoreMute) return true
if (this.focused) return true
const { reblog } = this.mainStatus
return (
((this.inProfile &&
// Don't mute user's posts on user timeline (except reblogs)
((!reblog && this.mainStatus.user.id === this.profileUserId) ||
// Same as above but also allow self-reblogs
reblog?.user.id === this.profileUserId)) ||
// Don't mute statuses in muted conversation when said conversation is opened
(this.inConversation && this.mainStatus.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.mainStatus.in_reply_to_status_id &&
this.mainStatus.in_reply_to_user_id
)
},
replyToName() {
if (this.mainStatus.in_reply_to_screen_name) {
return this.status.in_reply_to_screen_name
} else {
const user = useUsersStore().findUser(
this.mainStatus.in_reply_to_user_id,
)
return user?.screen_name_ui
}
},
combinedFavsAndRepeatsUsers() {
// Use the status from the global status repository since favs and repeats are saved in it
const combinedUsers = [].concat(
this.mainStatus.favoritedBy,
this.mainStatus.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.mainStatus.quotes_count)
)
},
muteBotStatuses() {
return this.mergedConfig.muteBotStatuses
},
muteSensitiveStatuses() {
return this.mergedConfig.muteSensitiveStatuses
},
hideBotIndication() {
return this.mergedConfig.hideBotIndication
},
currentUser() {
return useUsersStore().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.mainStatus.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(focused) {
if (this.$el.getBoundingClientRect == null) return
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)
},
'mainStatus.repeat_num': function (num) {
// refetch repeats when repeat_num is changed in any way
if (
this.focused &&
this.mainStatus.rebloggedBy &&
this.mainStatus.rebloggedBy.length !== num
) {
- this.$store.dispatch('fetchRepeats', this.status.id)
+ useStatusesStore().fetchRepeats(this.status.id)
}
},
'mainStatus.fave_num': function (num) {
// refetch favs when fave_num is changed in any way
if (
this.focused &&
this.mainStatus.favoritedBy &&
this.mainStatus.favoritedBy.length !== num
) {
- this.$store.dispatch('fetchFavs', this.status.id)
+ useStatusesStore().fetchFavs(this.status.id)
}
},
isSuspendable: function (suspend) {
this.$emit('suspendableStateChange', { id: this.status.id, suspend })
},
},
}
export default Status
diff --git a/src/components/status_action_buttons/action_button_container.js b/src/components/status_action_buttons/action_button_container.js
index cdb83c0b5e..fce80d9f0f 100644
--- a/src/components/status_action_buttons/action_button_container.js
+++ b/src/components/status_action_buttons/action_button_container.js
@@ -1,151 +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 { useStatusesStore } from 'src/stores/statuses.js'
import { useUsersStore } from 'src/stores/users.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', 'defaultButton', 'hideLabel'],
emits: ['emojiPickerShown'],
mounted() {
if (this.button.name === 'mute') {
- this.$store.dispatch('fetchDomainMutes')
+ useUsersStore().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 useUsersStore().relationship(this.user.id).muting
},
conversationIsMuted() {
return this.status.thread_muted
},
domain() {
return this.user.fqn.split('@')[1]
},
domainIsMuted() {
return new Set(useUsersStore().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 useUsersStore().unmuteUser(this.user.id)
},
unmuteConversation() {
return useStatusesStore().unmuteConversation(this.status.id)
},
unmuteDomain() {
return useUsersStore().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_bookmark_folder_menu/status_bookmark_folder_menu.js b/src/components/status_bookmark_folder_menu/status_bookmark_folder_menu.js
index c2f070b6d6..5e2c71b650 100644
--- a/src/components/status_bookmark_folder_menu/status_bookmark_folder_menu.js
+++ b/src/components/status_bookmark_folder_menu/status_bookmark_folder_menu.js
@@ -1,41 +1,42 @@
import { mapState } from 'pinia'
import Popover from 'src/components/popover/popover.vue'
import { useBookmarkFoldersStore } from 'src/stores/bookmark_folders.js'
+import { useStatusesStore } from 'src/stores/statuses.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faChevronRight, faFolder } from '@fortawesome/free-solid-svg-icons'
library.add(faChevronRight, faFolder)
const StatusBookmarkFolderMenu = {
props: ['status'],
emits: ['success', 'error', 'close'],
data() {
return {}
},
components: {
Popover,
},
computed: {
...mapState(useBookmarkFoldersStore, {
folders: (store) => store.allFolders,
}),
folderId() {
return this.status.bookmark_folder_id
},
},
methods: {
toggleFolder(id) {
const value = id === this.folderId ? null : id
- this.$store
- .dispatch('bookmark', { id: this.status.id, bookmark_folder_id: value })
+ useStatusesStore()
+ .bookmark(this.status.id, value)
.then(() => this.$emit('success'))
.catch((err) => this.$emit('error', err.error.error))
},
},
}
export default StatusBookmarkFolderMenu
diff --git a/src/components/user_list_menu/user_list_menu.js b/src/components/user_list_menu/user_list_menu.js
index b361752768..d04cdf6925 100644
--- a/src/components/user_list_menu/user_list_menu.js
+++ b/src/components/user_list_menu/user_list_menu.js
@@ -1,68 +1,69 @@
import { mapState } from 'pinia'
import Popover from 'src/components/popover/popover.vue'
import { useListsStore } from 'src/stores/lists.js'
+import { useUsersStore } from 'src/stores/users.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faChevronRight } from '@fortawesome/free-solid-svg-icons'
library.add(faChevronRight)
const UserListMenu = {
props: ['user'],
data() {
return {}
},
components: {
Popover,
},
created() {
- this.$store.dispatch('fetchUserInLists', this.user.id)
+ useUsersStore().fetchUserInLists(this.user.id)
},
computed: {
...mapState(useListsStore, {
allLists: (store) => store.allLists,
}),
inListsSet() {
return new Set(this.user.inLists.map((x) => x.id))
},
lists() {
if (!this.user.inLists) return []
return this.allLists.map((list) => ({
...list,
inList: this.inListsSet.has(list.id),
}))
},
triggerAttrs() {
return {
class: 'menu-item dropdown-item -has-submenu',
}
},
},
methods: {
toggleList(listId) {
if (this.inListsSet.has(listId)) {
useListsStore()
.removeListAccount({ accountId: this.user.id, listId })
.then((response) => {
if (!response.ok) {
return
}
- this.$store.dispatch('fetchUserInLists', this.user.id)
+ useUsersStore().fetchUserInLists(this.user.id)
})
} else {
useListsStore()
.addListAccount({ accountId: this.user.id, listId })
.then((response) => {
if (!response.ok) {
return
}
- this.$store.dispatch('fetchUserInLists', this.user.id)
+ useUsersStore().fetchUserInLists(this.user.id)
})
}
},
},
}
export default UserListMenu
diff --git a/src/components/user_note/user_note.js b/src/components/user_note/user_note.js
index bd246e9b3b..dab3ac9f6e 100644
--- a/src/components/user_note/user_note.js
+++ b/src/components/user_note/user_note.js
@@ -1,49 +1,48 @@
import PanelLoading from 'src/components/panel_loading/panel_loading.vue'
+import { useUsersStore } from 'src/stores/users.js'
+
const UserNote = {
props: {
user: Object,
relationship: Object,
editable: Boolean,
},
components: {
PanelLoading,
},
data() {
return {
localNote: this.relationship.note,
editing: false,
frozen: false,
}
},
watch: {
relationship() {
this.localNote = this.relationship.note
},
},
methods: {
startEditing() {
this.localNote = this.relationship.note
this.editing = true
},
finalizeEditing() {
this.frozen = true
- this.$store
- .dispatch('editUserNote', {
- id: this.user.id,
- comment: this.localNote,
- })
+ useUsersStore()
+ .editUserNote(this.user.id, this.localNote)
.then(() => {
this.frozen = false
this.editing = false
})
.catch(() => {
this.frozen = false
this.editing = false
})
},
},
}
export default UserNote
diff --git a/src/lib/push_notifications_plugin.js b/src/lib/push_notifications_plugin.js
index 4798068cf9..951eb2c4b7 100644
--- a/src/lib/push_notifications_plugin.js
+++ b/src/lib/push_notifications_plugin.js
@@ -1,90 +1,63 @@
import { useInstanceStore } from 'src/stores/instance.js'
import { useInterfaceStore } from 'src/stores/interface.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useUsersStore } from 'src/stores/users.js'
export const piniaPushNotificationsPlugin = ({ store }) => {
const validActions = {
sync_config: new Set(['setPreference']),
interface: new Set(['setNotificationPermission', 'setLoginStatus']),
}
if (!validActions[store.$id]) return // Not applicable to the store
store.$onAction(({ name: actionName, args }) => {
if (!validActions[store.$id].has(actionName)) return // Not applicable to action
// Initial state
let vapidPublicKey = useInstanceStore().vapidPublicKey
let enabled = useMergedConfigStore().mergedConfig.webPushNotifications
let permissionGranted =
useInterfaceStore().notificationPermission === 'granted'
let permissionPresent =
useInterfaceStore().notificationPermission !== undefined
let user = !!useUsersStore().currentUser
if (store.$id === 'instance') {
if (actionName === 'set' && args[0].path === 'vapidPublicKey') {
const { value } = args[0]
vapidPublicKey = value
}
}
if (!vapidPublicKey || !permissionPresent) {
return
}
if (store.$id === 'interface') {
if (actionName === 'setNotificationPermission') {
permissionGranted = args[0] === 'granted'
} else if (actionName === 'setLoginStatus') {
user = args[0]
} else {
return
}
} else if (store.$id === 'sync_config') {
if (
actionName === 'setPreference' &&
args[0].path === 'simple.webPushNotifications'
) {
const { value } = args[0]
enabled = value
} else {
return
}
}
if (permissionGranted && enabled && user) {
return useInterfaceStore().registerPushNotifications()
} else {
return useInterfaceStore().unregisterPushNotifications()
}
})
}
-
-// TODO make it work with pinia
-export const vuexPushNotificationsPlugin = (store) => {
- store.subscribe((mutation, state) => {
- // Initial state
- const vapidPublicKey = useInstanceStore().vapidPublicKey
- const enabled = useMergedConfigStore().mergedConfig.webPushNotifications
- const permissionGranted =
- useInterfaceStore().notificationPermission === 'granted'
- const permissionPresent =
- useInterfaceStore().notificationPermission !== undefined
- const user = state.users.currentUser
-
- if (!permissionPresent || !vapidPublicKey) return
-
- if (
- mutation.type === 'setCurrentUser' ||
- mutation.type === 'clearCurrentUser'
- ) {
- if (user && permissionGranted && enabled) {
- return store.dispatch('registerPushNotifications')
- } else {
- return store.dispatch('unregisterPushNotifications')
- }
- }
- })
-}
diff --git a/src/services/status_poster/status_poster.service.js b/src/services/status_poster/status_poster.service.js
index a25f601070..371632eceb 100644
--- a/src/services/status_poster/status_poster.service.js
+++ b/src/services/status_poster/status_poster.service.js
@@ -1,115 +1,119 @@
import { map } from 'lodash'
import { useStatusesStore } from 'src/stores/statuses.js'
+import { useTimelinesStore } from 'src/stores/timelines.js'
import { useUsersStore } from 'src/stores/users.js'
import {
editStatus as apiEditStatus,
postStatus as apiPostStatus,
setMediaDescription as apiSetMediaDescription,
uploadMedia as apiUploadMedia,
} from 'src/api/user.js'
const postStatus = ({
store,
status,
spoilerText,
visibility,
sensitive,
poll,
media = [],
inReplyToStatusId = undefined,
quoteId = undefined,
contentType = 'text/plain',
preview = false,
idempotencyKey = '',
}) => {
const mediaIds = map(media, 'id')
return apiPostStatus({
credentials: useUsersStore().currentUser.credentials,
status,
spoilerText,
visibility,
sensitive,
mediaIds,
inReplyToStatusId,
quoteId,
contentType,
poll,
preview,
idempotencyKey,
}).then(({ data, timestamp }) => {
if (!preview)
useStatusesStore().addNewStatuses({
timestamp,
statuses: [data],
timeline: 'friends',
showImmediately: true,
noIdUpdate: true, // To prevent missing notices on next pull.
})
return data
})
}
const editStatus = ({
store,
statusId,
status,
spoilerText,
sensitive,
poll,
media = [],
contentType = 'text/plain',
}) => {
const mediaIds = map(media, 'id')
return apiEditStatus({
id: statusId,
credentials: useUsersStore().currentUser.credentials,
status,
spoilerText,
sensitive,
poll,
mediaIds,
contentType,
})
- .then(({ data }) => {
- store.dispatch('addNewStatuses', {
+ .then(({ data, timestamp }) => {
+ useStatusesStore().addNewStatuses({
+ statuses: [data],
+ timestamp,
+ })
+ useTimelinesStore().addStatusesToTimeline('friends', undefined, {
statuses: [data],
- timeline: 'friends',
showImmediately: true,
noIdUpdate: true, // To prevent missing notices on next pull.
})
return data
})
.catch((err) => {
console.error('Error editing status', err)
return {
error: err.message,
}
})
}
const uploadMedia = ({ store, formData }) => {
const credentials = useUsersStore().currentUser.credentials
return apiUploadMedia({ credentials, formData }).then(({ data }) => data)
}
const setMediaDescription = ({ store, id, description }) => {
const credentials = useUsersStore().currentUser.credentials
return apiSetMediaDescription({ credentials, id, description }).then(
({ data }) => data,
)
}
const statusPosterService = {
postStatus,
editStatus,
uploadMedia,
setMediaDescription,
}
export default statusPosterService
diff --git a/src/services/sw/sw.js b/src/services/sw/sw.js
index ef8200a4d4..9040f0cf5a 100644
--- a/src/services/sw/sw.js
+++ b/src/services/sw/sw.js
@@ -1,187 +1,188 @@
+import { useNotificationsStore } from 'src/stores/notifications.js'
+
/* global process */
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
const base64 = (base64String + padding)
.replaceAll('-', '+')
.replaceAll('_', '/')
const rawData = window.atob(base64)
return Uint8Array.from([...rawData].map((char) => char.codePointAt(0)))
}
export function isSWSupported() {
return 'serviceWorker' in navigator
}
function isPushSupported() {
return 'PushManager' in window
}
function getOrCreateServiceWorker() {
if (!isSWSupported()) return
const swType = process.env.HAS_MODULE_SERVICE_WORKER ? 'module' : 'classic'
return navigator.serviceWorker
.register('/sw-pleroma.js', { type: swType })
.catch((err) =>
console.error('Unable to get or create a service worker.', err),
)
}
function subscribePush(registration, isEnabled, vapidPublicKey) {
if (!isEnabled) throw new Error('Web Push is disabled in config')
if (!vapidPublicKey) throw new Error('VAPID public key is not found')
const subscribeOptions = {
userVisibleOnly: false,
applicationServerKey: urlBase64ToUint8Array(vapidPublicKey),
}
return registration.pushManager.subscribe(subscribeOptions)
}
async function unsubscribePush(registration) {
return registration.pushManager.getSubscription().then((subscription) => {
if (subscription === null) {
return 'No subscription'
}
return subscription.unsubscribe()
})
}
function deleteSubscriptionFromBackEnd(token) {
return fetch('/api/v1/push/subscription/', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
}).then((response) => {
if (!response.ok) throw new Error('Bad status code from server.')
return response
})
}
function sendSubscriptionToBackEnd(
subscription,
token,
notificationVisibility,
) {
return window
.fetch('/api/v1/push/subscription/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
subscription,
data: {
alerts: {
follow: notificationVisibility.follows,
favourite: notificationVisibility.likes,
mention: notificationVisibility.mentions,
reblog: notificationVisibility.repeats,
move: notificationVisibility.moves,
},
},
}),
})
.then((response) => {
if (!response.ok) throw new Error('Bad status code from server.')
return response.json()
})
.then((responseData) => {
if (!responseData.id) throw new Error('Bad response from server.')
return responseData
})
}
-export async function initServiceWorker(store) {
+export async function initServiceWorker() {
if (!isSWSupported()) return
await getOrCreateServiceWorker()
navigator.serviceWorker.addEventListener('message', (event) => {
- const { dispatch } = store
const { type, ...rest } = event.data
switch (type) {
case 'notificationClicked':
- dispatch('notificationClicked', { id: rest.id })
+ useNotificationsStore().notificationClicked(rest.id)
}
})
}
export async function showDesktopNotification(content) {
if (!isSWSupported) return
const { active: sw } =
(await window.navigator.serviceWorker.getRegistration()) || {}
if (!sw) return console.error('No serviceworker found!')
sw.postMessage({ type: 'desktopNotification', content })
}
export async function closeDesktopNotification({ id }) {
if (!isSWSupported) return
const { active: sw } =
(await window.navigator.serviceWorker.getRegistration()) || {}
if (!sw) return console.error('No serviceworker found!')
if (id >= 0) {
sw.postMessage({ type: 'desktopNotificationClose', content: { id } })
} else {
sw.postMessage({ type: 'desktopNotificationClose', content: { all: true } })
}
}
export async function updateFocus() {
if (!isSWSupported) return
const { active: sw } =
(await window.navigator.serviceWorker.getRegistration()) || {}
if (!sw) return console.error('No serviceworker found!')
sw.postMessage({ type: 'updateFocus' })
}
export function registerPushNotifications(
isEnabled,
vapidPublicKey,
token,
notificationVisibility,
) {
if (isPushSupported()) {
getOrCreateServiceWorker()
.then((registration) =>
subscribePush(registration, isEnabled, vapidPublicKey),
)
.then((subscription) =>
sendSubscriptionToBackEnd(subscription, token, notificationVisibility),
)
.catch((e) =>
console.warn(`Failed to setup Web Push Notifications: ${e.message}`),
)
}
}
export function unregisterPushNotifications(token) {
if (isPushSupported()) {
getOrCreateServiceWorker()
.then((registration) => {
return unsubscribePush(registration).then((result) => [
registration,
result,
])
})
.then(([, unsubResult]) => {
if (unsubResult === 'No subscription') return
if (!unsubResult) {
console.warn("Push subscription cancellation wasn't successful")
}
return deleteSubscriptionFromBackEnd(token)
})
.catch((e) => {
console.warn(`Failed to disable Web Push Notifications: ${e.message}`)
})
}
}
export const shouldCache = process.env.NODE_ENV === 'production'
export const cacheKey = 'pleroma-fe'
export const emojiCacheKey = 'pleroma-fe-emoji'
export const clearCache = (key) => caches.delete(key)
export { getOrCreateServiceWorker }
diff --git a/test/fixtures/setup_test.js b/test/fixtures/setup_test.js
index d63e639d79..3da0231a47 100644
--- a/test/fixtures/setup_test.js
+++ b/test/fixtures/setup_test.js
@@ -1,144 +1,143 @@
-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),
VueVirtualScroller,
createRouter({
history: createMemoryHistory(),
routes: routes({
state: {
users: {
currentUser: {},
},
instance: {},
},
}),
}),
(Vue) => {
Vue.directive('body-scroll-lock', {})
},
],
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?.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 a7fab6210d..068bedabef 100644
--- a/test/unit/specs/boot/routes.spec.js
+++ b/test/unit/specs/boot/routes.spec.js
@@ -1,74 +1,73 @@
import { createTestingPinia } from '@pinia/testing'
createTestingPinia()
import { createMemoryHistory, createRouter } from 'vue-router'
-import { createStore } from 'vuex'
import routes from 'src/boot/routes'
describe('routes', () => {
const router = createRouter({
history: createMemoryHistory(),
routes: routes(),
})
it('root path', async () => {
await router.push('/main/all')
const matchedComponents = router.currentRoute.value.matched
expect(matchedComponents[0].components.default.__file).to.contain(
'/timeline.vue',
)
})
it("user's profile", async () => {
await router.push('/fake-user-name')
const matchedComponents = router.currentRoute.value.matched
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.__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.__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.__file).to.contain(
'/timeline.vue',
)
})
it('list edit', async () => {
await router.push('/lists/1/edit')
const matchedComponents = router.currentRoute.value.matched
expect(matchedComponents[0].components.default.__file).to.contain(
'/lists_edit.vue',
)
})
})
diff --git a/test/unit/specs/components/draft.spec.js b/test/unit/specs/components/draft.spec.js
index 6332eba7ea..40d63419bc 100644
--- a/test/unit/specs/components/draft.spec.js
+++ b/test/unit/specs/components/draft.spec.js
@@ -1,193 +1,193 @@
import { createTestingPinia } from '@pinia/testing'
import { flushPromises, mount } from '@vue/test-utils'
import { setActivePinia } from 'pinia'
import { nextTick } from 'vue'
-import { useUsersStore } from 'src/stores/users.js'
import PostStatusForm from 'src/components/post_status_form/post_status_form.vue'
import { $t, mountOpts, waitForEvent } from '../../../fixtures/setup_test'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
+import { useUsersStore } from 'src/stores/users.js'
const autoSaveOrNot = (caseFn, caseTitle, runFn) => {
caseFn(`${caseTitle} with auto-save`, function () {
return runFn.bind(this)(true)
})
caseFn(`${caseTitle} with no auto-save`, function () {
return runFn.bind(this)(false)
})
}
const saveManually = async (wrapper) => {
const morePostActions = wrapper.findByText(
'button',
$t('post_status.more_post_actions'),
)
await morePostActions.trigger('click')
const btn = wrapper.findByText(
'button',
$t('post_status.save_to_drafts_button'),
)
await btn.trigger('click')
}
const waitSaveTime = 4000
const currentUser = {
id: 'current-user',
default_scope: 'public',
locked: false,
}
describe('Draft saving', () => {
beforeEach(() => {
setActivePinia(createTestingPinia())
useUsersStore().currentUser = currentUser
})
afterEach(() => {
vi.useRealTimers()
})
autoSaveOrNot(
it,
'should save when the button is clicked',
async (autoSave) => {
const wrapper = mount(PostStatusForm, mountOpts())
const store = useMergedConfigStore()
store.mergedConfig = {
autoSaveDraft: autoSave,
}
expect(wrapper.vm.$store.getters.draftCount).to.equal(0)
const textarea = wrapper.get('textarea')
await textarea.setValue('mew mew')
await saveManually(wrapper)
expect(wrapper.vm.$store.getters.draftCount).to.equal(1)
expect(wrapper.vm.$store.getters.draftsArray[0].status).to.equal(
'mew mew',
)
},
)
it('should auto-save if it is enabled', async function () {
vi.useFakeTimers()
const wrapper = mount(PostStatusForm, mountOpts())
const store = useMergedConfigStore()
store.mergedConfig = {
autoSaveDraft: true,
}
expect(wrapper.vm.$store.getters.draftCount).to.equal(0)
const textarea = wrapper.get('textarea')
await textarea.setValue('mew mew')
expect(wrapper.vm.$store.getters.draftCount).to.equal(0)
await vi.advanceTimersByTimeAsync(waitSaveTime)
expect(wrapper.vm.$store.getters.draftCount).to.equal(1)
expect(wrapper.vm.$store.getters.draftsArray[0].status).to.equal('mew mew')
})
it('should auto-save when close if auto-save is on', async () => {
const wrapper = mount(
PostStatusForm,
mountOpts({
props: {
closeable: true,
},
}),
)
const store = useMergedConfigStore()
store.mergedConfig = {
autoSaveDraft: true,
}
expect(wrapper.vm.$store.getters.draftCount).to.equal(0)
const textarea = wrapper.get('textarea')
await textarea.setValue('mew mew')
wrapper.vm.requestClose()
expect(wrapper.vm.$store.getters.draftCount).to.equal(1)
await waitForEvent(wrapper, 'close-accepted')
})
it('should save when close if auto-save is off, and unsavedPostAction is save', async () => {
const wrapper = mount(
PostStatusForm,
mountOpts({
props: {
closeable: true,
},
}),
)
const store = useMergedConfigStore()
store.mergedConfig = {
autoSaveDraft: false,
unsavedPostAction: 'save',
}
expect(wrapper.vm.$store.getters.draftCount).to.equal(0)
const textarea = wrapper.get('textarea')
await textarea.setValue('mew mew')
wrapper.vm.requestClose()
expect(wrapper.vm.$store.getters.draftCount).to.equal(1)
await waitForEvent(wrapper, 'close-accepted')
})
it('should discard when close if auto-save is off, and unsavedPostAction is discard', async () => {
const wrapper = mount(
PostStatusForm,
mountOpts({
props: {
closeable: true,
},
}),
)
const store = useMergedConfigStore()
store.mergedConfig = {
autoSaveDraft: false,
unsavedPostAction: 'discard',
}
expect(wrapper.vm.$store.getters.draftCount).to.equal(0)
const textarea = wrapper.get('textarea')
await textarea.setValue('mew mew')
wrapper.vm.requestClose()
await waitForEvent(wrapper, 'close-accepted')
expect(wrapper.vm.$store.getters.draftCount).to.equal(0)
})
it('should confirm when close if auto-save is off, and unsavedPostAction is confirm', async () => {
const wrapper = mount(
PostStatusForm,
mountOpts({
props: {
closeable: true,
},
}),
)
const store = useMergedConfigStore(createTestingPinia())
store.mergedConfig = {
autoSaveDraft: false,
unsavedPostAction: 'confirm',
}
expect(wrapper.vm.$store.getters.draftCount).to.equal(0)
const textarea = wrapper.get('textarea')
await textarea.setValue('mew mew')
wrapper.vm.requestClose()
await nextTick()
await flushPromises()
const saveButton = await vi.waitFor(() => {
const button = wrapper.findByText(
'button',
$t('post_status.close_confirm_save_button'),
)
if (!button) throw new Error('Save button not present')
return button
})
expect(saveButton).to.be.ok
await saveButton.trigger('click')
console.info('clicked')
expect(wrapper.vm.$store.getters.draftCount).to.equal(1)
await flushPromises()
await waitForEvent(wrapper, 'close-accepted')
})
})
diff --git a/test/unit/specs/components/rich_content.spec.js b/test/unit/specs/components/rich_content.spec.js
index 9286d9d735..19bfdc0350 100644
--- a/test/unit/specs/components/rich_content.spec.js
+++ b/test/unit/specs/components/rich_content.spec.js
@@ -1,522 +1,570 @@
import { createTestingPinia } from '@pinia/testing'
-import { setActivePinia } from 'pinia'
import { mount, shallowMount } from '@vue/test-utils'
-import { mountOpts } from '../../../fixtures/setup_test'
+import { setActivePinia } from 'pinia'
import RichContent from 'src/components/rich_content/rich_content.jsx'
+import { mountOpts } from '../../../fixtures/setup_test'
const attentions = []
const makeMention = (who, noClass) => {
attentions.push({ statusnet_profile_url: `https://fake.tld/@${who}` })
return noClass
? `<span><a href="https://fake.tld/@${who}">@<span>${who}</span></a></span>`
: `<span class="h-card"><a class="u-url mention" href="https://fake.tld/@${who}">@<span>${who}</span></a></span>`
}
const p = (...data) => `<p>${data.join('')}</p>`
const compwrap = (...data) =>
`<span class="RichContent">${data.join('')}</span>`
const mentionsLine = (times) =>
[
'<mentions-line-stub mentions="',
new Array(times).fill('[object Object]').join(','),
'"></mentions-line-stub>',
].join('')
describe('RichContent', () => {
beforeEach(() => {
setActivePinia(createTestingPinia())
})
it('renders simple post without exploding', () => {
const html = p('Hello world!')
- const wrapper = shallowMount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: true,
- greentext: true,
- emoji: [],
- html,
- },
- }))
+ const wrapper = shallowMount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: true,
+ greentext: true,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(wrapper.html().replaceAll('\n', '')).to.eql(compwrap(html))
})
it('unescapes everything as needed', () => {
const html = [p('Testing &#39;em all'), 'Testing &#39;em all'].join('')
const expected = [p("Testing 'em all"), "Testing 'em all"].join('')
- const wrapper = shallowMount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: true,
- greentext: true,
- emoji: [],
- html,
- },
- }))
+ const wrapper = shallowMount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: true,
+ greentext: true,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(wrapper.html().replaceAll('\n', '')).to.eql(compwrap(expected))
})
it('replaces mention with mentionsline', () => {
const html = p(makeMention('John'), ' how are you doing today?')
- const wrapper = shallowMount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: true,
- greentext: true,
- emoji: [],
- html,
- },
- }))
+ const wrapper = shallowMount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: true,
+ greentext: true,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(wrapper.html().replaceAll('\n', '')).to.eql(
compwrap(p(mentionsLine(1), ' how are you doing today?')),
)
})
it('replaces mentions at the end of the hellpost', () => {
const html = [
p('How are you doing today, fine gentlemen?'),
p(makeMention('John'), makeMention('Josh'), makeMention('Jeremy')),
].join('')
const expected = [
p('How are you doing today, fine gentlemen?'),
// TODO fix this extra line somehow?
p(
'<mentions-line-stub mentions="',
'[object Object],',
'[object Object],',
'[object Object]',
'"></mentions-line-stub>',
),
].join('')
- const wrapper = shallowMount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: true,
- greentext: true,
- emoji: [],
- html,
- },
- }))
+ const wrapper = shallowMount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: true,
+ greentext: true,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(wrapper.html().replaceAll('\n', '')).to.eql(compwrap(expected))
})
it('Does not touch links if link handling is disabled', () => {
const html = [
[makeMention('Jack'), "let's meet up with ", makeMention('Janet')].join(
'',
),
[makeMention('John'), makeMention('Josh'), makeMention('Jeremy')].join(
'',
),
].join('\n')
const strippedHtml = [
[
makeMention('Jack', true),
"let's meet up with ",
makeMention('Janet', true),
].join(''),
[
makeMention('John', true),
makeMention('Josh', true),
makeMention('Jeremy', true),
].join(''),
].join('\n')
- const wrapper = shallowMount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: false,
- greentext: true,
- emoji: [],
- html,
- },
- }))
+ const wrapper = shallowMount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: false,
+ greentext: true,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(wrapper.html()).to.eql(compwrap(strippedHtml))
})
it('Adds greentext and cyantext to the post', () => {
const html = ['&gt;preordering videogames', '&gt;any year'].join('\n')
const expected = [
'<span class="greentext">&gt;preordering videogames</span>',
'<span class="greentext">&gt;any year</span>',
].join('\n')
- const wrapper = shallowMount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: false,
- greentext: true,
- emoji: [],
- html,
- },
- }))
+ const wrapper = shallowMount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: false,
+ greentext: true,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(wrapper.html()).to.eql(compwrap(expected))
})
it('Does not add greentext and cyantext if setting is set to false', () => {
const html = ['&gt;preordering videogames', '&gt;any year'].join('\n')
- const wrapper = shallowMount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: false,
- greentext: false,
- emoji: [],
- html,
- },
- }))
+ const wrapper = shallowMount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: false,
+ greentext: false,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(wrapper.html()).to.eql(compwrap(html))
})
it('Adds emoji to post', () => {
const html = p('Ebin :DDDD :spurdo:')
const expected = p(
'Ebin :DDDD ',
'<anonymous-stub shortcode="spurdo" islocal="true" class="emoji img" src="about:blank" title=":spurdo:" alt=":spurdo:"></anonymous-stub>',
)
- const wrapper = shallowMount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: false,
- greentext: false,
- emoji: [{ url: 'about:blank', shortcode: 'spurdo' }],
- html,
- },
- }))
+ const wrapper = shallowMount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: false,
+ greentext: false,
+ emoji: [{ url: 'about:blank', shortcode: 'spurdo' }],
+ html,
+ },
+ }),
+ )
expect(wrapper.html().replaceAll('\n', '')).to.eql(compwrap(expected))
})
it("Doesn't add nonexistent emoji to post", () => {
const html = p('Lol :lol:')
- const wrapper = shallowMount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: false,
- greentext: false,
- emoji: [],
- html,
- },
- }))
+ const wrapper = shallowMount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: false,
+ greentext: false,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(wrapper.html().replaceAll('\n', '')).to.eql(compwrap(html))
})
it('Greentext + last mentions', () => {
const html = [
'&gt;quote',
makeMention('lol'),
'&gt;quote',
'&gt;quote',
].join('\n')
const expected = [
'<span class="greentext">&gt;quote</span>',
mentionsLine(1),
'<span class="greentext">&gt;quote</span>',
'<span class="greentext">&gt;quote</span>',
].join('\n')
- const wrapper = shallowMount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: true,
- greentext: true,
- emoji: [],
- html,
- },
- }))
+ const wrapper = shallowMount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: true,
+ greentext: true,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(wrapper.html()).to.eql(compwrap(expected))
})
it('One buggy example', () => {
const html = [
'Bruh',
'Bruh',
[makeMention('foo'), makeMention('bar'), makeMention('baz')].join(''),
'Bruh',
].join('<br>')
const expected = ['Bruh', 'Bruh', mentionsLine(3), 'Bruh'].join('<br>')
- const wrapper = shallowMount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: true,
- greentext: true,
- emoji: [],
- html,
- },
- }))
+ const wrapper = shallowMount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: true,
+ greentext: true,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(wrapper.html().replaceAll('\n', '')).to.eql(compwrap(expected))
})
it('buggy example/hashtags', () => {
const html = [
'<p>',
'<a href="http://macrochan.org/images/N/H/NHCMDUXJPPZ6M3Z2CQ6D2EBRSWGE7MZY.jpg">',
'NHCMDUXJPPZ6M3Z2CQ6D2EBRSWGE7MZY.jpg</a>',
' <a class="hashtag" data-tag="nou" href="https://shitposter.club/tag/nou">',
'#nou</a>',
' <a class="hashtag" data-tag="screencap" href="https://shitposter.club/tag/screencap">',
'#screencap</a>',
' </p>',
].join('')
const expected = [
'<p>',
'<a href="http://macrochan.org/images/N/H/NHCMDUXJPPZ6M3Z2CQ6D2EBRSWGE7MZY.jpg" target="_blank">',
'NHCMDUXJPPZ6M3Z2CQ6D2EBRSWGE7MZY.jpg</a>',
' <hashtag-link-stub url="https://shitposter.club/tag/nou" content="#nou" tag="nou">',
'</hashtag-link-stub>',
' <hashtag-link-stub url="https://shitposter.club/tag/screencap" content="#screencap" tag="screencap">',
'</hashtag-link-stub>',
' </p>',
].join('')
- const wrapper = shallowMount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: true,
- greentext: true,
- emoji: [],
- html,
- },
- }))
+ const wrapper = shallowMount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: true,
+ greentext: true,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(wrapper.html().replaceAll('\n', '')).to.eql(compwrap(expected))
})
it('rich contents of a mention are handled properly', () => {
attentions.push({ statusnet_profile_url: 'lol' })
const html = [
p(
'<a href="lol" class="mention">',
'<span>',
'https://</span>',
'<span>',
'lol.tld/</span>',
'<span>',
'</span>',
'</a>',
),
p('Testing'),
].join('')
const expected = [
p(
'<span class="MentionsLine">',
'<span class="MentionLink mention-link">',
'<a href="lol" class="original" target="_blank">',
'<span>',
'https://</span>',
'<span>',
'lol.tld/</span>',
'<span>',
'</span>',
'</a>',
'</span>',
'</span>',
),
p('Testing'),
].join('')
- const wrapper = mount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: true,
- greentext: true,
- emoji: [],
- html,
- },
- }))
+ const wrapper = mount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: true,
+ greentext: true,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(
wrapper
.html()
.replaceAll('\n', '')
.replaceAll(/<!--.*?-->/g, ''),
).to.eql(compwrap(expected))
})
it('rich contents of nested mentions are handled properly', () => {
attentions.push({ statusnet_profile_url: 'lol' })
const html = [
'<span class="poast-style">',
'<a href="lol" class="mention">',
'<span>',
'https://</span>',
'<span>',
'lol.tld/</span>',
'<span>',
'</span>',
'</a>',
' ',
'<a href="lol" class="mention">',
'<span>',
'https://</span>',
'<span>',
'lol.tld/</span>',
'<span>',
'</span>',
'</a>',
' ',
'</span>',
'Testing',
].join('')
const expected = [
'<span>',
'<span class="MentionsLine">',
'<span class="MentionLink mention-link">',
'<a href="lol" class="original" target="_blank">',
'<span>',
'https://</span>',
'<span>',
'lol.tld/</span>',
'<span>',
'</span>',
'</a>',
'</span>',
'<span class="MentionLink mention-link">',
'<a href="lol" class="original" target="_blank">',
'<span>',
'https://</span>',
'<span>',
'lol.tld/</span>',
'<span>',
'</span>',
'</a>',
'</span>',
'</span>',
' ',
'</span>',
'Testing',
].join('')
- const wrapper = mount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: true,
- greentext: true,
- emoji: [],
- html,
- },
- }))
+ const wrapper = mount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: true,
+ greentext: true,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(
wrapper
.html()
.replaceAll('\n', '')
.replaceAll(/<!--.*?-->/g, ''),
).to.eql(compwrap(expected))
})
it('rich contents of a link are handled properly', () => {
const html = [
'<p>',
'Freenode is dead.</p>',
'<p>',
'<a href="https://isfreenodedeadyet.com/">',
'<span>',
'https://</span>',
'<span>',
'isfreenodedeadyet.com/</span>',
'<span>',
'</span>',
'</a>',
'</p>',
].join('')
const expected = [
'<p>',
'Freenode is dead.</p>',
'<p>',
'<a href="https://isfreenodedeadyet.com/" target="_blank">',
'<span>',
'https://</span>',
'<span>',
'isfreenodedeadyet.com/</span>',
'<span>',
'</span>',
'</a>',
'</p>',
].join('')
- const wrapper = shallowMount(RichContent, mountOpts({
- props: {
- attentions,
- handleLinks: true,
- greentext: true,
- emoji: [],
- html,
- },
- }))
+ const wrapper = shallowMount(
+ RichContent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks: true,
+ greentext: true,
+ emoji: [],
+ html,
+ },
+ }),
+ )
expect(wrapper.html().replaceAll('\n', '')).to.eql(compwrap(expected))
})
it.skip('[INFORMATIVE] Performance testing, 10 000 simple posts', () => {
const amount = 20
const onePost = p(
makeMention('Lain'),
makeMention('Lain'),
makeMention('Lain'),
makeMention('Lain'),
makeMention('Lain'),
makeMention('Lain'),
makeMention('Lain'),
makeMention('Lain'),
makeMention('Lain'),
makeMention('Lain'),
' i just landed in l a where are you',
)
const TestComponent = {
template: `
<div v-if="!vhtml">
${new Array(amount).fill(`<RichContent html="${onePost}" :greentext="true" :handleLinks="handeLinks" :emoji="[]" :attentions="attentions"/>`)}
</div>
<div v-else="vhtml">
${new Array(amount).fill(`<div v-html="${onePost}"/>`)}
</div>
`,
props: ['handleLinks', 'attentions', 'vhtml'],
}
const ptest = (handleLinks, vhtml) => {
const t0 = performance.now()
- const wrapper = mount(TestComponent, mountOpts({
- props: {
- attentions,
- handleLinks,
- vhtml,
- },
- }))
+ const wrapper = mount(
+ TestComponent,
+ mountOpts({
+ props: {
+ attentions,
+ handleLinks,
+ vhtml,
+ },
+ }),
+ )
const t1 = performance.now()
wrapper.destroy()
const t2 = performance.now()
return `Mount: ${t1 - t0}ms, destroy: ${t2 - t1}ms, avg ${(t1 - t0) / amount}ms - ${(t2 - t1) / amount}ms per item`
}
console.debug(`${amount} items with links handling:`)
console.debug(ptest(true))
console.debug(`${amount} items without links handling:`)
console.debug(ptest(false))
console.debug(`${amount} items plain v-html:`)
console.debug(ptest(false, true))
})
})
diff --git a/test/unit/specs/services/notification_utils/notification_utils.spec.js b/test/unit/specs/services/notification_utils/notification_utils.spec.js
index f610fae7f3..09d39f7044 100644
--- a/test/unit/specs/services/notification_utils/notification_utils.spec.js
+++ b/test/unit/specs/services/notification_utils/notification_utils.spec.js
@@ -1,94 +1,94 @@
-import { setActivePinia } from 'pinia'
import { createTestingPinia } from '@pinia/testing'
+import { setActivePinia } from 'pinia'
-import { useSyncConfigStore } from 'src/stores/sync_config.js'
import { useNotificationsStore } from 'src/stores/notifications.js'
+import { useSyncConfigStore } from 'src/stores/sync_config.js'
import * as NotificationUtils from 'src/services/notification_utils/notification_utils.js'
describe('NotificationUtils', () => {
beforeEach(() => {
setActivePinia(createTestingPinia())
useSyncConfigStore().mergedConfig = {
notificationVisibility: {
likes: true,
repeats: true,
mentions: false,
},
}
})
describe('filteredNotifications', () => {
it('should return sorted notifications with configured types', () => {
useNotificationsStore().data = [
{
id: 1,
action: { id: '1' },
type: 'like',
},
{
id: 2,
action: { id: '2' },
type: 'mention',
},
{
id: 3,
action: { id: '3' },
type: 'repeat',
},
]
const expected = [
{
action: { id: '3' },
id: 3,
type: 'repeat',
},
{
action: { id: '1' },
id: 1,
type: 'like',
},
]
expect(
NotificationUtils.filteredNotifications({
mentions: false,
likes: true,
repeats: true,
}),
).to.eql(expected)
})
})
describe('unseenNotifications', () => {
it('should return only notifications not marked as seen', () => {
useNotificationsStore().data = [
{
action: { id: '1' },
type: 'like',
seen: false,
},
{
action: { id: '2' },
type: 'mention',
seen: true,
},
]
const expected = [
{
action: { id: '1' },
type: 'like',
seen: false,
},
]
expect(
NotificationUtils.unseenNotifications({
likes: true,
repeats: true,
mentions: false,
}),
).to.eql(expected)
})
})
})
diff --git a/test/unit/specs/stores/notifications.spec.js b/test/unit/specs/stores/notifications.spec.js
index 653999cdbe..ad8b6bf44e 100644
--- a/test/unit/specs/stores/notifications.spec.js
+++ b/test/unit/specs/stores/notifications.spec.js
@@ -1,400 +1,390 @@
import { createTestingPinia } from '@pinia/testing'
import { setActivePinia } from 'pinia'
import { useI18nStore } from 'src/stores/i18n.js'
import { useNotificationsStore } from 'src/stores/notifications.js'
import { useReportsStore } from 'src/stores/reports.js'
import { useStatusesStore } from 'src/stores/statuses.js'
import { useStreamingStore } from 'src/stores/streaming.js'
import { useUsersStore } from 'src/stores/users.js'
import * as USER_API from 'src/api/user.js'
const userId = '1'
const userScreenName = 'user'
const userName = 'Guy'
const userUrl = 'http://localhost/user'
const mockMastoAPIUser = ({
screen_name = userScreenName,
name = userName,
url = userUrl,
id = userId,
} = {}) => ({
id,
acct: screen_name,
display_name: name,
fields: [],
avatar: '',
url,
pleroma: {
emoji_reactions: [],
},
})
const mockUser = ({
screen_name = userScreenName,
id = userId,
name = userName,
url = userUrl,
} = {}) => ({
_original: mockMastoAPIUser({
screen_name,
id,
name,
url,
}),
id,
name,
screen_name,
url,
relationship: undefined,
})
const mockStatus = ({
id = '1',
text,
summary,
type = 'status',
statusUser = mockUser(),
} = {}) => ({
id,
user: statusUser,
summary: summary ?? `Summary number ${id}`,
name: 'status',
text: text ?? `Text number ${id}`,
uri: '',
type,
attentions: [],
statusnet_conversation_id: 'c1',
emoji_reactions: [],
})
const mockStatusNotification = ({
id = '1',
type = 'like',
status = mockStatus({ id }),
seen = false,
user = mockUser(),
} = {}) => ({
type,
id,
status,
seen,
user,
from_profile: user,
})
-const DEFAULT_OPTIONS = (method = 'POST') => ({
- method,
- credentials: 'same-origin',
- headers: {
- Accept: 'application/json',
- },
-})
-
describe('Notifications store', () => {
beforeEach(() => {
vi.useFakeTimers()
setActivePinia(createTestingPinia({ stubActions: false }))
useI18nStore().i18n = {
t: () => {
/* no-op */
},
}
})
afterEach(() => {
vi.useRealTimers()
})
it('activate', () => {
const store = useNotificationsStore()
const sub = vi.fn()
useStreamingStore().addSubscriber = sub
store.activate()
expect(sub).to.have.been.called
expect(store.fetcher).to.not.be.null
expect(store.socket).to.not.be.null
store.deactivate()
})
it('deactivate', () => {
const store = useNotificationsStore()
const unsub = vi.fn()
useStreamingStore().removeSubscriber = unsub
store.activate()
// Checking so that they were set properly before
// since reset changes them to ''
store.maxId = '2'
store.minId = '1'
store.idStore = new Map()
store.idStore.set('1', {})
store.idStore.set('2', {})
store.deactivate()
expect(unsub).to.have.been.called
expect(store.fetcher).to.be.null
expect(store.socket).to.be.null
expect(store.idStore).to.have.length(0)
expect(store).to.have.property('maxId', '')
expect(store).to.have.property('minId', '')
})
it('updateExtremes should update min and max ids', () => {
const store = useNotificationsStore()
store.maxId = '10'
store.minId = '05'
store.updateExtremes('04')
store.updateExtremes('11')
expect(store).to.have.property('maxId', '11')
expect(store).to.have.property('minId', '04')
})
describe('addNewNotifications', () => {
it('adds notifications to the list', () => {
const store = useNotificationsStore()
store.addNewNotifications({
timestamp: 1,
data: [
mockStatusNotification({ id: 'a' }),
mockStatusNotification({ id: 'b' }),
],
})
// must be ordered
expect(store.data.map(({ id }) => id)).to.eql(['a', 'b'])
expect(store.idStore).to.have.keys(['a', 'b'])
expect(store).to.have.property('maxId', 'b')
expect(store).to.have.property('minId', 'a')
})
it('ignores duplicates', () => {
const store = useNotificationsStore()
store.addNewNotifications({
timestamp: 1,
data: [
mockStatusNotification({ id: '2' }),
mockStatusNotification({ id: '1' }),
],
})
store.addNewNotifications({
timestamp: 1,
data: [
mockStatusNotification({ id: '3' }),
mockStatusNotification({ id: '2' }),
],
})
// must be ordered
expect(store.data.map(({ id }) => id)).to.eql(['3', '2', '1'])
expect(store.idStore).to.have.keys(['1', '2', '3'])
expect(store).to.have.property('maxId', '3')
expect(store).to.have.property('minId', '1')
})
it('appends notifications if fetching older', () => {
const store = useNotificationsStore()
store.addNewNotifications({
timestamp: 1,
data: [
mockStatusNotification({ id: '4' }),
mockStatusNotification({ id: '3' }),
],
})
store.addNewNotifications(
{
timestamp: 1,
data: [
mockStatusNotification({ id: '2' }),
mockStatusNotification({ id: '1' }),
],
},
true,
)
// must be ordered
expect(store.data.map(({ id }) => id)).to.eql(['4', '3', '2', '1'])
expect(store.idStore).to.have.keys(['1', '2', '3', '4'])
expect(store).to.have.property('maxId', '4')
expect(store).to.have.property('minId', '1')
})
it('should update usersStore', () => {
const store = useNotificationsStore()
const mock = vi.spyOn(useUsersStore(), 'addNewUsers')
const mockedNotification = mockStatusNotification({ type: 'follow' })
store.addNewNotifications({
timestamp: 1337,
data: [mockedNotification],
})
expect(mock).to.have.been.called
expect(mock.mock.calls[0][0]).to.have.property('timestamp', 1337)
expect(mock.mock.calls[0][0].data[0]).to.eql(
mockedNotification.from_profile,
)
})
it('should update reportsStore', (notificationType) => {
const store = useNotificationsStore()
const mock = vi.spyOn(useReportsStore(), 'addReport')
const mockedNotification = mockStatusNotification({
type: 'pleroma:report',
})
mockedNotification.report = { data: '123' }
store.addNewNotifications({
timestamp: 1337,
data: [mockedNotification],
})
expect(mock).to.have.been.calledWith({ data: '123' })
})
it.each([
'like',
'mention',
'status',
'repeat',
'pleroma:emoji_reaction',
'poll',
])('should update statusesStore on %s notification', (notificationType) => {
const store = useNotificationsStore()
const mock = vi.fn()
useStatusesStore().addNewStatuses = mock
const mockedNotification = mockStatusNotification({
type: notificationType,
})
store.addNewNotifications({
timestamp: 1337,
data: [mockedNotification],
})
expect(mock).to.have.been.called
expect(mock.mock.calls[0][0]).to.have.property('timestamp', 1337)
expect(mock.mock.calls[0][0].statuses[0]).to.eql(
mockedNotification.status,
)
})
})
describe('wipeStatuses', () => {
it('clears all statuses', () => {
const store = useNotificationsStore()
store.addNewNotifications({
timestamp: 1,
data: [
mockStatusNotification({
id: 'n2',
status: mockStatus({ id: 's2' }),
}),
mockStatusNotification({
id: 'n1',
status: mockStatus({ id: 's1' }),
}),
],
})
store.wipeStatuses(['s2'])
expect(store.idStore).to.not.have.members('n2')
expect(store.data.map(({ id }) => id)).to.eql(['n1'])
})
})
describe('read/dismiss', () => {
it('read single', () => {
const mockFetch = vi.fn()
mockFetch.mockResolvedValueOnce(
new Response(JSON.stringify({ ok: 'ok' }), {
headers: { 'Content-Type': 'application/json' },
}),
)
vi.stubGlobal('fetch', mockFetch)
const store = useNotificationsStore()
- const mockedNotification = mockStatusNotification()
store.addNewNotifications({
timestamp: 1337,
data: [
mockStatusNotification({ id: 'n3' }),
mockStatusNotification({ id: 'n2' }),
mockStatusNotification({ id: 'n1' }),
],
})
expect(store.data[1]).to.have.property('seen', false)
store.markSingleNotificationAsSeen('n2')
expect(store.data[0]).to.have.property('seen', false)
expect(store.data[1]).to.have.property('seen', true)
expect(store.data[0]).to.have.property('seen', false)
const calls = mockFetch.mock.calls
expect(calls).to.have.length(1)
const callOne = calls[0]
expect(callOne[0]).to.eql(USER_API.NOTIFICATION_READ_URL)
const formData = Object.fromEntries(callOne[1].body.entries())
expect(formData).to.eql({ id: 'n2' })
})
it('read all', () => {
const mockFetch = vi.fn()
mockFetch.mockResolvedValueOnce(
new Response(JSON.stringify({ ok: 'ok' }), {
headers: { 'Content-Type': 'application/json' },
}),
)
vi.stubGlobal('fetch', mockFetch)
const store = useNotificationsStore()
- const mockedNotification = mockStatusNotification()
// FormData is weird to test
store.addNewNotifications({
timestamp: 1337,
data: [
mockStatusNotification({ id: 'n3' }),
mockStatusNotification({ id: 'n2' }),
mockStatusNotification({ id: 'n1' }),
],
})
expect(store.data[0]).to.have.property('seen', false)
expect(store.data[1]).to.have.property('seen', false)
expect(store.data[2]).to.have.property('seen', false)
store.markNotificationsAsSeen()
expect(store.data[0]).to.have.property('seen', true)
expect(store.data[1]).to.have.property('seen', true)
expect(store.data[2]).to.have.property('seen', true)
// FormData is weird to test
const calls = mockFetch.mock.calls
expect(calls).to.have.length(1)
const callOne = calls[0]
expect(callOne[0]).to.eql(USER_API.NOTIFICATION_READ_URL)
const formData = Object.fromEntries(callOne[1].body.entries())
expect(formData).to.eql({ max_id: 'n3' })
})
})
})

File Metadata

Mime Type
text/x-diff
Expires
Fri, Oct 30, 1:11 AM (1 d, 9 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1799069
Default Alt Text
(155 KB)

Event Timeline