elk/composables/status.ts

81 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-12-01 06:46:26 +00:00
import type { Status } from 'masto'
type Action = 'reblogged' | 'favourited' | 'bookmarked' | 'pinned'
type CountField = 'reblogsCount' | 'favouritesCount'
export interface StatusActionsProps {
status: Status
}
export function useStatusActions(props: StatusActionsProps) {
let status = $ref<Status>({ ...props.status })
watch(
() => props.status,
val => status = { ...val },
{ deep: true, immediate: true },
)
// Use different states to let the user press different actions right after the other
const isLoading = $ref({
reblogged: false,
favourited: false,
bookmarked: false,
pinned: false,
translation: false,
})
2022-12-02 02:18:57 +00:00
async function toggleStatusAction(action: Action, newStatus: () => Promise<Status>, countField?: CountField) {
// check login
if (!checkLogin())
return
// Optimistic update
2022-12-01 06:46:26 +00:00
status[action] = !status[action]
if (countField)
status[countField] += status[action] ? 1 : -1
try {
isLoading[action] = true
2022-12-02 02:18:57 +00:00
Object.assign(status, await newStatus())
2022-12-01 06:46:26 +00:00
}
finally {
isLoading[action] = false
}
}
const toggleReblog = () => toggleStatusAction(
'reblogged',
2022-12-02 02:18:57 +00:00
() => useMasto().statuses[status.reblogged ? 'unreblog' : 'reblog'](status.id).then((res) => {
2022-12-01 06:46:26 +00:00
if (status.reblogged)
// returns the original status
return res.reblog!
return res
}),
'reblogsCount',
)
const toggleFavourite = () => toggleStatusAction(
'favourited',
2022-12-02 02:18:57 +00:00
() => useMasto().statuses[status.favourited ? 'unfavourite' : 'favourite'](status.id),
2022-12-01 06:46:26 +00:00
'favouritesCount',
)
const toggleBookmark = () => toggleStatusAction(
'bookmarked',
2022-12-02 02:18:57 +00:00
() => useMasto().statuses[status.bookmarked ? 'unbookmark' : 'bookmark'](status.id),
2022-12-01 06:46:26 +00:00
)
const togglePin = async () => toggleStatusAction(
'pinned',
2022-12-02 02:18:57 +00:00
() => useMasto().statuses[status.pinned ? 'unpin' : 'pin'](status.id),
2022-12-01 06:46:26 +00:00
)
return {
status: $$(status),
isLoading: $$(isLoading),
toggleReblog,
toggleFavourite,
toggleBookmark,
togglePin,
}
}