From 0dc515647f7fdb3f3e1332075eaf13ac065d3a8a Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Thu, 24 Nov 2022 14:54:54 +0800 Subject: [PATCH] feat: rework status cache --- components/publish/PublishWidget.vue | 37 ++++++++++++++++------------ composables/statusDrafts.ts | 18 ++++++++++++++ 2 files changed, 39 insertions(+), 16 deletions(-) create mode 100644 composables/statusDrafts.ts diff --git a/components/publish/PublishWidget.vue b/components/publish/PublishWidget.vue index 07d2a1a0..dbd984d0 100644 --- a/components/publish/PublishWidget.vue +++ b/components/publish/PublishWidget.vue @@ -12,19 +12,26 @@ const { }>() let isSending = $ref(false) -const storageKey = `elk-draft-${draftKey}` function getDefaultStatus(): CreateStatusParamsWithStatus { return { status: '', inReplyToId, } } -let draft = $(useLocalStorage(storageKey, getDefaultStatus())) -let attachments = $(useLocalStorage(`${storageKey}-attachments`, [])) +const draft = $computed(() => { + if (!currentUserDrafts.value[draftKey]) { + currentUserDrafts.value[draftKey] = { + params: getDefaultStatus(), + attachments: [], + } + } + return currentUserDrafts.value[draftKey] +}) + const status = $computed(() => { return { - ...draft, - mediaIds: attachments.map(a => a.id), + ...draft.params, + mediaIds: draft.attachments.map(a => a.id), } as CreateStatusParams }) @@ -65,21 +72,21 @@ async function uploadAttachments(files: File[]) { const attachment = await masto.mediaAttachments.create({ file, }) - attachments.push(attachment) + draft.attachments.push(attachment) } isUploading = false } function removeAttachment(index: number) { - attachments.splice(index, 1) + draft.attachments.splice(index, 1) } async function publish() { try { isSending = true await masto.statuses.create(status) - draft = getDefaultStatus() - attachments = [] + draft.params = getDefaultStatus() + draft.attachments = [] } finally { isSending = false @@ -87,11 +94,9 @@ async function publish() { } onUnmounted(() => { - if (!draft.status) { - // @ts-expect-error draft cannot be undefined - draft = undefined + if (!draft.attachments.length && !draft.params.status) { nextTick(() => { - localStorage.removeItem(storageKey) + delete currentUserDrafts.value[draftKey] }) } }) @@ -103,7 +108,7 @@ onUnmounted(() => { :class="isSending ? 'pointer-events-none' : ''" >