Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: change page reload and account switch logic #2975

Merged
merged 14 commits into from
Sep 25, 2024
Merged
73 changes: 38 additions & 35 deletions composables/idb/index.ts
Original file line number Diff line number Diff line change
@@ -1,72 +1,75 @@
import type { MaybeRefOrGetter, RemovableRef } from '@vueuse/core'
import type { Ref } from 'vue'
import type { UseIDBOptions } from '@vueuse/integrations/useIDBKeyval'
import { del, get, set, update } from '~/utils/elk-idb'

const isIDBSupported = !process.test && typeof indexedDB !== 'undefined'
export interface UseAsyncIDBKeyvalReturn<T> {
set: (value: T) => Promise<void>
readIDB: () => Promise<T | undefined>
}

export async function useAsyncIDBKeyval<T>(
key: IDBValidKey,
initialValue: MaybeRefOrGetter<T>,
options: UseIDBOptions = {},
source?: Ref<T>,
): Promise<RemovableRef<T>> {
source: RemovableRef<T>,
options: Omit<UseIDBOptions, 'shallow'> = {},
): Promise<UseAsyncIDBKeyvalReturn<T>> {
const {
flush = 'pre',
deep = true,
shallow,
writeDefaults = true,
onError = (e: unknown) => {
console.error(e)
},
} = options

const data = source ?? (shallow ? shallowRef : ref)(initialValue) as Ref<T>

const rawInit: T = toValue<T>(initialValue)

async function read() {
if (!isIDBSupported)
return
try {
const rawValue = await get<T>(key)
if (rawValue === undefined) {
if (rawInit !== undefined && rawInit !== null)
await set(key, rawInit)
}
else {
data.value = rawValue
try {
const rawValue = await get<T>(key)
if (rawValue === undefined) {
if (rawInit !== undefined && rawInit !== null && writeDefaults) {
await set(key, rawInit)
source.value = rawInit
}
}
catch (e) {
onError(e)
else {
source.value = rawValue
}
}
catch (e) {
onError(e)
}

await read()

async function write() {
if (!isIDBSupported)
return
async function write(data: T) {
try {
if (data.value == null) {
if (data == null) {
await del(key)
}
else {
// IndexedDB does not support saving proxies, convert from proxy before saving
if (Array.isArray(data.value))
await update(key, () => (JSON.parse(JSON.stringify(data.value))))
else if (typeof data.value === 'object')
await update(key, () => ({ ...data.value }))
else
await update(key, () => (data.value))
await update(key, () => toRaw(data))
}
}
catch (e) {
onError(e)
}
}

watch(data, () => write(), { flush, deep })
const {
pause: pauseWatch,
resume: resumeWatch,
} = watchPausable(source, data => write(data), { flush, deep })

async function setData(value: T): Promise<void> {
pauseWatch()
try {
await write(value)
source.value = value
}
finally {
resumeWatch()
}
}

return data as RemovableRef<T>
return { set: setData, readIDB: () => get<T>(key) }
}
62 changes: 17 additions & 45 deletions composables/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const mock = process.mock

const users: Ref<UserLogin[]> | RemovableRef<UserLogin[]> = import.meta.server ? ref<UserLogin[]>([]) : ref<UserLogin[]>([]) as RemovableRef<UserLogin[]>
const nodes = useLocalStorage<Record<string, any>>(STORAGE_KEY_NODES, {}, { deep: true })
const currentUserHandle = useLocalStorage<string>(STORAGE_KEY_CURRENT_USER_HANDLE, mock ? mock.user.account.id : '')
export const currentUserHandle = useLocalStorage<string>(STORAGE_KEY_CURRENT_USER_HANDLE, mock ? mock.user.account.id : '')
userquin marked this conversation as resolved.
Show resolved Hide resolved
export const instanceStorage = useLocalStorage<Record<string, mastodon.v1.Instance>>(STORAGE_KEY_SERVERS, mock ? mock.server : {}, { deep: true })

export type ElkInstance = Partial<mastodon.v1.Instance> & {
Expand All @@ -32,17 +32,24 @@ export function getInstanceCache(server: string): mastodon.v1.Instance | undefin
}

export const currentUser = computed<UserLogin | undefined>(() => {
if (currentUserHandle.value) {
const user = users.value.find(user => user.account?.acct === currentUserHandle.value)
const handle = currentUserHandle.value
const currentUsers = users.value
if (handle) {
const user = currentUsers.find(user => user.account?.acct === handle)
if (user)
return user
}
// Fallback to the first account
return users.value[0]
return currentUsers.length ? currentUsers[0] : undefined
})

const publicInstance = ref<ElkInstance | null>(null)
export const currentInstance = computed<null | ElkInstance>(() => currentUser.value ? instanceStorage.value[currentUser.value.server] ?? null : publicInstance.value)
export const currentInstance = computed<null | ElkInstance>(() => {
const user = currentUser.value
const storage = instanceStorage.value
const instance = publicInstance.value
return user ? storage[user.server] ?? null : instance
})

export function getInstanceDomain(instance: ElkInstance) {
return instance.accountDomain || withoutProtocol(instance.uri)
Expand All @@ -55,44 +62,6 @@ export const currentNodeInfo = computed<null | Record<string, any>>(() => nodes.
export const isGotoSocial = computed(() => currentNodeInfo.value?.software?.name === 'gotosocial')
export const isGlitchEdition = computed(() => currentInstance.value?.version?.includes('+glitch'))

// when multiple tabs: we need to reload window when sign in, switch account or sign out
if (import.meta.client) {
// fix #2972: now users loaded from idb, we need to wait for it
const initialLoad = ref(true)
watchOnce(users, () => {
initialLoad.value = false
}, { immediate: true, flush: 'sync' })

const windowReload = () => {
if (document.visibilityState === 'visible' && !initialLoad.value)
window.location.reload()
}
watch(currentUserHandle, async (handle, oldHandle) => {
// when sign in or switch account
if (handle) {
if (handle === currentUser.value?.account?.acct) {
// when sign in, the other tab will not have the user, idb is not reactive
const newUser = users.value.find(user => user.account?.acct === handle)
// if the user is there, then we are switching account
if (newUser) {
// check if the change is on current tab: if so, don't reload
if (document.hasFocus() || document.visibilityState === 'visible')
return
}
}

window.addEventListener('visibilitychange', windowReload, { capture: true })
}
// when sign out
else if (oldHandle) {
const oldUser = users.value.find(user => user.account?.acct === oldHandle)
// when sign out, the other tab will not have the user, idb is not reactive
if (oldUser)
window.addEventListener('visibilitychange', windowReload, { capture: true })
}
}, { immediate: true, flush: 'post' })
}

export function useUsers() {
return users
}
Expand All @@ -102,7 +71,10 @@ export function useSelfAccount(user: MaybeRefOrGetter<mastodon.v1.Account | unde

export const characterLimit = computed(() => currentInstance.value?.configuration?.statuses.maxCharacters ?? DEFAULT_POST_CHARS_LIMIT)

export async function loginTo(masto: ElkMasto, user: Overwrite<UserLogin, { account?: mastodon.v1.AccountCredentials }>) {
export async function loginTo(
masto: ElkMasto,
user: Overwrite<UserLogin, { account?: mastodon.v1.AccountCredentials }>,
) {
const { client } = masto
const instance = mastoLogin(masto, user)

Expand Down Expand Up @@ -303,7 +275,7 @@ export async function signOut() {
if (!currentUserHandle.value)
await useRouter().push('/')

loginTo(masto, currentUser.value || { server: publicServer.value })
await loginTo(masto, currentUser.value || { server: publicServer.value })
}

export function checkLogin() {
Expand Down
137 changes: 1 addition & 136 deletions pages/[[server]]/lists.vue
Original file line number Diff line number Diff line change
@@ -1,70 +1,9 @@
<script setup lang="ts">
import type { mastodon } from 'masto'

definePageMeta({
middleware: 'auth',
})

const { t } = useI18n()

const client = useMastoClient()

const paginator = client.v1.lists.list()

useHydratedHead({
title: () => t('nav.lists'),
})

const paginatorRef = ref()
const inputRef = ref<HTMLInputElement>()
const actionError = ref<string | undefined>(undefined)
const busy = ref<boolean>(false)
const createText = ref('')
const enableSubmit = computed(() => createText.value.length > 0)

async function createList() {
if (busy.value || !enableSubmit.value)
return

busy.value = true
actionError.value = undefined
await nextTick()
try {
const newEntry = await client.v1.lists.create({
title: createText.value,
})
paginatorRef.value?.createEntry(newEntry)
createText.value = ''
}
catch (err) {
console.error(err)
actionError.value = (err as Error).message
nextTick(() => {
inputRef.value?.focus()
})
}
finally {
busy.value = false
}
}

function clearError(focusBtn: boolean) {
actionError.value = undefined
if (focusBtn) {
nextTick(() => {
inputRef.value?.focus()
})
}
}

function updateEntry(list: mastodon.v1.List) {
paginatorRef.value?.updateEntry(list)
}
function removeEntry(id: string) {
paginatorRef.value?.removeEntry(id)
}

onDeactivated(() => clearError(false))
</script>

<template>
Expand All @@ -75,80 +14,6 @@ onDeactivated(() => clearError(false))
<span text-lg font-bold>{{ t('nav.lists') }}</span>
</NuxtLink>
</template>
<slot>
<CommonPaginator ref="paginatorRef" :paginator="paginator">
<template #default="{ item }">
<ListEntry
:model-value="item"
@update:model-value="updateEntry"
@list-removed="removeEntry"
/>
</template>
<template #done>
<form
border="t base"
p-4 w-full
flex="~ wrap" relative gap-3
:aria-describedby="actionError ? 'create-list-error' : undefined"
:class="actionError ? 'border border-base border-rounded rounded-be-is-0 rounded-be-ie-0 border-b-unset border-$c-danger-active' : null"
@submit.prevent="createList"
>
<div
bg-base border="~ base" flex-1 h10 ps-1 pe-4 rounded-2 w-full flex="~ row"
items-center relative focus-within:box-shadow-outline gap-3
>
<input
ref="inputRef"
v-model="createText"
bg-transparent
outline="focus:none"
px-4
pb="1px"
flex-1
placeholder-text-secondary
:placeholder="$t('list.list_title_placeholder')"
@keypress.enter="createList"
>
</div>
<div flex="~ col" gap-y-4 gap-x-2 sm="~ justify-between flex-row">
<button flex="~ row" gap-x-2 items-center btn-solid :disabled="!enableSubmit || busy">
<span v-if="busy" aria-hidden="true" block animate animate-spin preserve-3d class="rtl-flip">
<span block i-ri:loader-2-fill aria-hidden="true" />
</span>
<span v-else aria-hidden="true" block i-material-symbols:playlist-add-rounded class="rtl-flip" />
{{ $t('list.create') }}
</button>
</div>
</form>
<CommonErrorMessage
v-if="actionError"
id="create-list-error"
described-by="create-list-failed"
class="rounded-bs-is-0 rounded-bs-ie-0 border-t-dashed m-b-2"
>
<header id="create-list-failed" flex justify-between>
<div flex items-center gap-x-2 font-bold>
<div aria-hidden="true" i-ri:error-warning-fill />
<p>{{ $t('list.error') }}</p>
</div>
<CommonTooltip placement="bottom" :content="$t('list.clear_error')">
<button
flex rounded-4 p1 hover:bg-active cursor-pointer transition-100 :aria-label="$t('list.clear_error')"
@click="clearError(true)"
>
<span aria-hidden="true" w="1.75em" h="1.75em" i-ri:close-line />
</button>
</CommonTooltip>
</header>
<ol ps-2 sm:ps-1>
<li flex="~ col sm:row" gap-y-1 sm:gap-x-2>
<strong sr-only>{{ $t('list.error_prefix') }}</strong>
<span>{{ actionError }}</span>
</li>
</ol>
</CommonErrorMessage>
</template>
</CommonPaginator>
</slot>
<NuxtPage v-if="isHydrated" />
</MainContent>
</template>
Loading