feat: open reply dialog on timeline

closes #125
zio/stable
三咲智子 2022-11-28 18:23:33 +08:00
parent c2f3526e88
commit 9fca8eee30
No known key found for this signature in database
GPG Key ID: 69992F2250DFD93E
6 changed files with 85 additions and 53 deletions

View File

@ -3,32 +3,33 @@ import type { CreateStatusParams, StatusVisibility } from 'masto'
import { fileOpen } from 'browser-fs-access' import { fileOpen } from 'browser-fs-access'
import { useDropZone } from '@vueuse/core' import { useDropZone } from '@vueuse/core'
import { EditorContent } from '@tiptap/vue-3' import { EditorContent } from '@tiptap/vue-3'
import type { Draft } from '~/composables/statusDrafts'
const { const {
draftKey, draftKey,
placeholder = 'What is on your mind?', initial = getDefaultDraft() as never /* Bug of vue-core */,
inReplyToId,
inReplyToVisibility = 'public',
expanded: _expanded = false, expanded: _expanded = false,
} = defineProps<{ } = defineProps<{
draftKey: string draftKey: string
initial?: () => Draft
placeholder?: string placeholder?: string
inReplyToId?: string inReplyToId?: string
inReplyToVisibility?: StatusVisibility inReplyToVisibility?: StatusVisibility
expanded?: boolean expanded?: boolean
}>() }>()
// eslint-disable-next-line prefer-const
let { draft, isEmpty } = $(useDraft(draftKey, initial))
let isSending = $ref(false) let isSending = $ref(false)
let { draft } = $(useDraft(draftKey, inReplyToId, inReplyToVisibility)) let isExpanded = $ref(!isEmpty || _expanded)
const isExistDraft = $computed(() => !!draft.params.status && draft.params.status !== '<p></p>')
let isExpanded = $ref(isExistDraft || _expanded)
const { editor } = useTiptap({ const { editor } = useTiptap({
content: computed({ content: computed({
get: () => draft.params.status, get: () => draft.params.status,
set: newVal => draft.params.status = newVal, set: newVal => draft.params.status = newVal,
}), }),
placeholder, placeholder: draft.placeholder,
autofocus: isExpanded, autofocus: isExpanded,
onSubmit: publish, onSubmit: publish,
onFocus() { isExpanded = true }, onFocus() { isExpanded = true },
@ -108,6 +109,7 @@ async function publish() {
raw: draft.params.status, raw: draft.params.status,
...payload, ...payload,
}) })
// eslint-disable-next-line no-alert
const result = confirm('[DEV] Payload logged to console, do you want to publish it?') const result = confirm('[DEV] Payload logged to console, do you want to publish it?')
if (!result) if (!result)
return return
@ -121,7 +123,7 @@ async function publish() {
else else
await useMasto().statuses.update(draft.editingStatus.id, payload) await useMasto().statuses.update(draft.editingStatus.id, payload)
draft = getDefaultDraft({ inReplyToId, visibility: inReplyToVisibility }) draft = initial()
isPublishDialogOpen.value = false isPublishDialogOpen.value = false
} }
finally { finally {
@ -137,15 +139,6 @@ async function onDrop(files: File[] | null) {
} }
const { isOverDropZone } = useDropZone(dropZoneRef, onDrop) const { isOverDropZone } = useDropZone(dropZoneRef, onDrop)
onUnmounted(() => {
// Remove draft if it's empty
if (!draft.attachments.length && !draft.params.status) {
nextTick(() => {
delete currentUserDrafts.value[draftKey]
})
}
})
</script> </script>
<template> <template>
@ -261,7 +254,7 @@ onUnmounted(() => {
<button <button
btn-solid rounded-full text-sm btn-solid rounded-full text-sm
:disabled="!isExistDraft || isUploading || (draft.attachments.length === 0 && !draft.params.status)" :disabled="isEmpty || isUploading || (draft.attachments.length === 0 && !draft.params.status)"
@click="publish" @click="publish"
> >
{{ !draft.editingStatus ? 'Publish!' : 'Save changes' }} {{ !draft.editingStatus ? 'Publish!' : 'Save changes' }}

View File

@ -1,8 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
import type { Status } from 'masto' import type { Status } from 'masto'
const { status: _status } = defineProps<{ const { status: _status, details } = defineProps<{
status: Status status: Status
details?: boolean
}>() }>()
let status = $ref<Status>({ ..._status }) let status = $ref<Status>({ ..._status })
@ -80,6 +81,7 @@ const copyLink = async () => {
const deleteStatus = async () => { const deleteStatus = async () => {
// TODO confirm to delete // TODO confirm to delete
if (process.dev) { if (process.dev) {
// eslint-disable-next-line no-alert
const result = confirm('[DEV] Are you sure you want to delete this post?') const result = confirm('[DEV] Are you sure you want to delete this post?')
if (!result) if (!result)
return return
@ -97,22 +99,23 @@ const deleteAndRedraft = async () => {
// TODO confirm to delete // TODO confirm to delete
const { text } = await useMasto().statuses.remove(status.id) const { text } = await useMasto().statuses.remove(status.id)
openPublishDialog('dialog', getDraftFromStatus(status, text), true)
}
if (!dialogDraft.isEmpty) { const reply = () => {
// TODO confirm to overwrite if (details) {
// TODO focus to editor
}
else {
const { key, draft } = getReplyDraft(status)
openPublishDialog(key, draft())
} }
openPublishDialog('dialog', {
params: { ...getParamsFromStatus(status), status: text! },
attachments: [],
})
} }
function editStatus() { function editStatus() {
openPublishDialog(`edit-${status.id}`, { openPublishDialog(`edit-${status.id}`, {
...getDraftFromStatus(status),
editingStatus: status, editingStatus: status,
params: getParamsFromStatus(status),
attachments: [],
}) })
} }
</script> </script>
@ -122,11 +125,10 @@ function editStatus() {
<div flex-1> <div flex-1>
<StatusActionButton <StatusActionButton
content="Reply" content="Reply"
as="router-link"
:to="getStatusPath(status)"
:text="status.repliesCount" :text="status.repliesCount"
color="text-blue" hover="text-blue" group-hover="bg-blue/10" color="text-blue" hover="text-blue" group-hover="bg-blue/10"
icon="i-ri:chat-3-line" icon="i-ri:chat-3-line"
@click="reply"
/> />
</div> </div>

View File

@ -52,6 +52,6 @@ const visibility = $computed(() => STATUS_VISIBILITIES.find(v => v.value === sta
· {{ status.application?.name }} · {{ status.application?.name }}
</div> </div>
</div> </div>
<StatusActions :status="status" border="t base" pt-2 /> <StatusActions :status="status" details border="t base" pt-2 />
</div> </div>
</template> </template>

View File

@ -19,9 +19,12 @@ export function openSigninDialog() {
isSigninDialogOpen.value = true isSigninDialogOpen.value = true
} }
export function openPublishDialog(draftKey = 'dialog', draft?: Draft) { export function openPublishDialog(draftKey = 'dialog', draft?: Draft, overwrite = false): void {
dialogDraftKey.value = draftKey dialogDraftKey.value = draftKey
if (draft) if (overwrite) {
// TODO overwrite warning
}
if (draft && (overwrite || !currentUserDrafts.value[draftKey]))
currentUserDrafts.value[draftKey] = draft currentUserDrafts.value[draftKey] = draft
isPublishDialogOpen.value = true isPublishDialogOpen.value = true
} }

View File

@ -1,4 +1,4 @@
import type { Account, Attachment, CreateStatusParams, Status, StatusVisibility } from 'masto' import type { Account, Attachment, CreateStatusParams, Status } from 'masto'
import { STORAGE_KEY_DRAFTS } from '~/constants' import { STORAGE_KEY_DRAFTS } from '~/constants'
import type { Mutable } from '~/types/utils' import type { Mutable } from '~/types/utils'
@ -8,6 +8,7 @@ export interface Draft {
status?: Exclude<CreateStatusParams['status'], null> status?: Exclude<CreateStatusParams['status'], null>
} }
attachments: Attachment[] attachments: Attachment[]
placeholder: string
} }
export type DraftMap = Record<string, Draft> export type DraftMap = Record<string, Draft>
@ -26,30 +27,56 @@ export function getDefaultDraft({
status = '', status = '',
inReplyToId, inReplyToId,
visibility = 'public', visibility = 'public',
}: Partial<Draft['params']> = {}): Draft { placeholder = 'What is on your mind?',
attachments = [],
}: Partial<Draft['params'] & Omit<Draft, 'params'>> = {}): Draft {
return { return {
params: { params: {
status, status,
inReplyToId, inReplyToId,
visibility, visibility,
}, },
attachments: [], attachments,
placeholder,
} }
} }
export function getParamsFromStatus(status: Status): Draft['params'] { export function getDraftFromStatus(status: Status, text?: null | string): Draft {
return { return getDefaultDraft({
status: status.content, status: text || status.content,
mediaIds: status.mediaAttachments.map(att => att.id), mediaIds: status.mediaAttachments.map(att => att.id),
visibility: status.visibility, visibility: status.visibility,
attachments: status.mediaAttachments,
})
}
export function getReplyDraft(status: Status) {
return {
key: `reply-${status.id}`,
draft: () => getDefaultDraft({
inReplyToId: status!.id,
placeholder: `Reply to ${status?.account ? getDisplayName(status.account) : 'this thread'}`,
visibility: status.visibility,
}),
} }
} }
export function useDraft(draftKey: string, inReplyToId?: string, inReplyToVisibility?: StatusVisibility) { export const isEmptyDraft = (draft: Draft) => {
const { params, attachments } = draft
const status = params.status || ''
return (status.length === 0 || status === '<p></p>')
&& attachments.length === 0
&& (params.spoilerText || '').length === 0
}
export function useDraft(
draftKey: string,
initial: () => Draft = () => getDefaultDraft(),
) {
const draft = computed({ const draft = computed({
get() { get() {
if (!currentUserDrafts.value[draftKey]) if (!currentUserDrafts.value[draftKey])
currentUserDrafts.value[draftKey] = getDefaultDraft({ inReplyToId, visibility: inReplyToVisibility }) currentUserDrafts.value[draftKey] = initial()
return currentUserDrafts.value[draftKey] return currentUserDrafts.value[draftKey]
}, },
set(val) { set(val) {
@ -57,27 +84,30 @@ export function useDraft(draftKey: string, inReplyToId?: string, inReplyToVisibi
}, },
}) })
const isEmpty = computed(() => { const isEmpty = computed(() => isEmptyDraft(draft.value))
return (draft.value.params.status ?? '').trim().length === 0
&& draft.value.attachments.length === 0 onUnmounted(async () => {
// Remove draft if it's empty
if (isEmpty.value) {
await nextTick()
delete currentUserDrafts.value[draftKey]
}
}) })
return { draft, isEmpty } return { draft, isEmpty }
} }
export const dialogDraft = useDraft('dialog')
export function mentionUser(account: Account) { export function mentionUser(account: Account) {
openPublishDialog('dialog', getDefaultDraft({ openPublishDialog('dialog', getDefaultDraft({
status: `@${account.acct} `, status: `@${account.acct} `,
})) }), true)
} }
export function directMessageUser(account: Account) { export function directMessageUser(account: Account) {
openPublishDialog('dialog', getDefaultDraft({ openPublishDialog('dialog', getDefaultDraft({
status: `@${account.acct} `, status: `@${account.acct} `,
visibility: 'direct', visibility: 'direct',
})) }), true)
} }
export function clearUserDrafts(account?: Account) { export function clearUserDrafts(account?: Account) {

View File

@ -1,4 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import type { Status } from 'masto'
import type { ComponentPublicInstance } from 'vue' import type { ComponentPublicInstance } from 'vue'
const route = useRoute() const route = useRoute()
@ -6,9 +7,14 @@ const id = $(computedEager(() => route.params.status as string))
const main = ref<ComponentPublicInstance | null>(null) const main = ref<ComponentPublicInstance | null>(null)
let bottomSpace = $ref(0) let bottomSpace = $ref(0)
const { data: status, refresh: refreshStatus } = useAsyncData(async () => window.history.state?.status ?? await fetchStatus(id)) const { data: status, refresh: refreshStatus } = useAsyncData(async () => (
window.history.state?.status as Status | undefined)
?? await fetchStatus(id),
)
const { data: context, pending, refresh: refreshContext } = useAsyncData(`context:${id}`, () => useMasto().statuses.fetchContext(id)) const { data: context, pending, refresh: refreshContext } = useAsyncData(`context:${id}`, () => useMasto().statuses.fetchContext(id))
const replyDraft = $computed(() => status.value ? getReplyDraft(status.value) : null)
function scrollTo() { function scrollTo() {
const statusElement = unrefElement(main) const statusElement = unrefElement(main)
if (!statusElement) if (!statusElement)
@ -53,11 +59,9 @@ onReactivated(() => {
/> />
<PublishWidget <PublishWidget
v-if="currentUser" v-if="currentUser"
:draft-key="replyDraft!.key"
:initial="replyDraft!.draft"
border="t base" border="t base"
:draft-key="`reply-${id}`"
:placeholder="`Reply to ${status?.account ? getDisplayName(status.account) : 'this thread'}`"
:in-reply-to-id="id"
:in-reply-to-visibility="status.visibility"
/> />
<template v-if="context"> <template v-if="context">