client: refactor pagination.vue #216

Manually merged
Johann150 merged 2 commits from refactor-pagination.vue into main 2022-10-29 21:10:51 +00:00

View file

@ -15,14 +15,14 @@
<div v-else ref="rootEl"> <div v-else ref="rootEl">
<div v-show="pagination.reversed && more" key="_more_" class="cxiknjgy _gap"> <div v-show="pagination.reversed && more" key="_more_" class="cxiknjgy _gap">
<MkButton v-if="!moreFetching" class="button" :disabled="moreFetching" :style="{ cursor: moreFetching ? 'wait' : 'pointer' }" primary @click="fetchMoreAhead"> <MkButton v-if="!moreFetching" class="button" :disabled="moreFetching" :style="{ cursor: moreFetching ? 'wait' : 'pointer' }" primary @click="fetchMore(true)">
{{ i18n.ts.loadMore }} {{ i18n.ts.loadMore }}
</MkButton> </MkButton>
<MkLoading v-else class="loading"/> <MkLoading v-else class="loading"/>
</div> </div>
<slot :items="items"></slot> <slot :items="items"></slot>
<div v-show="!pagination.reversed && more" key="_more_" class="cxiknjgy _gap"> <div v-show="!pagination.reversed && more" key="_more_" class="cxiknjgy _gap">
<MkButton v-if="!moreFetching" v-appear="($store.state.enableInfiniteScroll && !disableAutoLoad) ? fetchMore : null" class="button" :disabled="moreFetching" :style="{ cursor: moreFetching ? 'wait' : 'pointer' }" primary @click="fetchMore"> <MkButton v-if="!moreFetching" v-appear="($store.state.enableInfiniteScroll && !disableAutoLoad) ? fetchMore : null" class="button" :disabled="moreFetching" :style="{ cursor: moreFetching ? 'wait' : 'pointer' }" primary @click="fetchMore()">
{{ i18n.ts.loadMore }} {{ i18n.ts.loadMore }}
</MkButton> </MkButton>
<MkLoading v-else class="loading"/> <MkLoading v-else class="loading"/>
@ -32,7 +32,7 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { computed, ComputedRef, isRef, onActivated, onDeactivated, ref, watch } from 'vue'; import { ComputedRef, isRef, onActivated, onDeactivated, watch } from 'vue';
import * as foundkey from 'foundkey-js'; import * as foundkey from 'foundkey-js';
import * as os from '@/os'; import * as os from '@/os';
import { onScrollTop, isTopVisible, getScrollPosition, getScrollContainer } from '@/scripts/scroll'; import { onScrollTop, isTopVisible, getScrollPosition, getScrollContainer } from '@/scripts/scroll';
@ -45,13 +45,13 @@ export type Paging<E extends keyof foundkey.Endpoints = keyof foundkey.Endpoints
params?: foundkey.Endpoints[E]['req'] | ComputedRef<foundkey.Endpoints[E]['req']>; params?: foundkey.Endpoints[E]['req'] | ComputedRef<foundkey.Endpoints[E]['req']>;
/** /**
* 検索APIのようなページング不可なエンドポイントを利用する場合 * When using non-pageable endpoints, such as the search API.
* (そのようなAPIをこの関数で使うのは若干矛盾してるけど) * (though it is slightly inconsistent to use such an API with this function)
*/ */
noPaging?: boolean; noPaging?: boolean;
/** /**
* items 配列の中身を逆順にする(新しい方が最後) * items Array contents in reverse order (newest first, last)
*/ */
reversed?: boolean; reversed?: boolean;
@ -76,202 +76,175 @@ const emit = defineEmits<{
type Item = { id: string; [another: string]: unknown; }; type Item = { id: string; [another: string]: unknown; };
const rootEl = ref<HTMLElement>(); let rootEl: HTMLElement | null = $ref(null);
const items = ref<Item[]>([]); let items: Item[] = $ref([]);
const queue = ref<Item[]>([]); let queue: Item[] = $ref([]);
const offset = ref(0); let offset: number = $ref(0);
const fetching = ref(true); let fetching: boolean = $ref(true);
const moreFetching = ref(false); let moreFetching: boolean = $ref(false);
const more = ref(false); let more: boolean = $ref(false);
const backed = ref(false); // let backed: boolean = $ref(false); //
const isBackTop = ref(false); let isBackTop: boolean = $ref(false);
const empty = computed(() => items.value.length === 0); const empty = $computed(() => items.length === 0);
const error = ref(false); let error: boolean = $ref(false);
const init = async (): Promise<void> => { const init = async (): Promise<void> => {
queue.value = []; queue = [];
fetching.value = true; fetching = true;
const params = props.pagination.params ? isRef(props.pagination.params) ? props.pagination.params.value : props.pagination.params : {}; const params = props.pagination.params
? isRef(props.pagination.params)
? props.pagination.params.value as Record<string, any>
: props.pagination.params
: {};
await os.api(props.pagination.endpoint, { await os.api(props.pagination.endpoint, {
...params, ...params,
limit: props.pagination.noPaging ? (props.pagination.limit || 10) : (props.pagination.limit || 10) + 1, limit: props.pagination.noPaging ? (props.pagination.limit || 10) : (props.pagination.limit || 10) + 1,
}).then(res => { }).then((res: Item[]) => {
if (!props.pagination.noPaging && (res.length > (props.pagination.limit || 10))) { if (!props.pagination.noPaging && (res.length > (props.pagination.limit || 10))) {
res.pop(); res.pop();
items.value = props.pagination.reversed ? [...res].reverse() : res; more = true;
more.value = true;
} else { } else {
items.value = props.pagination.reversed ? [...res].reverse() : res; more = false;
more.value = false;
} }
offset.value = res.length; items = props.pagination.reversed ? [...res].reverse() : res;
error.value = false; offset = res.length;
fetching.value = false; error = false;
fetching = false;
emit('loaded'); emit('loaded');
}, () => { }).catch(() => {
error.value = true; error = true;
fetching.value = false; fetching = false;
emit('error'); emit('error');
}); });
}; };
const reload = (): void => { const reload = (): void => {
items.value = []; items = [];
init(); init();
}; };
const fetchMore = async (): Promise<void> => { const fetchMore = async (ahead?: boolean): Promise<void> => {
if (!more.value || fetching.value || moreFetching.value || items.value.length === 0) return; if (!more || fetching || moreFetching || items.length === 0) return;
moreFetching.value = true; moreFetching = true;
backed.value = true; if (!ahead) {
const params = props.pagination.params ? isRef(props.pagination.params) ? props.pagination.params.value : props.pagination.params : {}; backed = true;
}
const params = props.pagination.params ? isRef(props.pagination.params) ? props.pagination.params : props.pagination.params : {};
await os.api(props.pagination.endpoint, { await os.api(props.pagination.endpoint, {
...params, ...params,
limit: SECOND_FETCH_LIMIT + 1, limit: SECOND_FETCH_LIMIT + 1,
...(props.pagination.offsetMode ? { ...(props.pagination.offsetMode ? {
offset: offset.value, offset,
} : props.pagination.reversed ? { } : ahead ? (
sinceId: items.value[0].id, props.pagination.reversed ? {
untilId: items[0].id,
} : { } : {
untilId: items.value[items.value.length - 1].id, sinceId: items[items.length - 1].id,
}), }
) : (
props.pagination.reversed ? {
sinceId: items[0].id,
} : {
untilId: items[items.length - 1].id,
}
)),
}).then(res => { }).then(res => {
if (res.length > SECOND_FETCH_LIMIT) { if (res.length > SECOND_FETCH_LIMIT) {
res.pop(); res.pop();
items.value = props.pagination.reversed ? [...res].reverse().concat(items.value) : items.value.concat(res); more = true;
more.value = true;
} else { } else {
items.value = props.pagination.reversed ? [...res].reverse().concat(items.value) : items.value.concat(res); more = false;
more.value = false;
} }
offset.value += res.length; items = props.pagination.reversed ? [...res].reverse().concat(items) : items.concat(res);
moreFetching.value = false; offset += res.length;
moreFetching = false;
}, () => { }, () => {
moreFetching.value = false; moreFetching = false;
});
};
const fetchMoreAhead = async (): Promise<void> => {
if (!more.value || fetching.value || moreFetching.value || items.value.length === 0) return;
moreFetching.value = true;
const params = props.pagination.params ? isRef(props.pagination.params) ? props.pagination.params.value : props.pagination.params : {};
await os.api(props.pagination.endpoint, {
...params,
limit: SECOND_FETCH_LIMIT + 1,
...(props.pagination.offsetMode ? {
offset: offset.value,
} : props.pagination.reversed ? {
untilId: items.value[0].id,
} : {
sinceId: items.value[items.value.length - 1].id,
}),
}).then(res => {
if (res.length > SECOND_FETCH_LIMIT) {
res.pop();
items.value = props.pagination.reversed ? [...res].reverse().concat(items.value) : items.value.concat(res);
more.value = true;
} else {
items.value = props.pagination.reversed ? [...res].reverse().concat(items.value) : items.value.concat(res);
more.value = false;
}
offset.value += res.length;
moreFetching.value = false;
}, () => {
moreFetching.value = false;
}); });
}; };
const prepend = (item: Item): void => { const prepend = (item: Item): void => {
if (props.pagination.reversed) { if (props.pagination.reversed) {
if (rootEl.value) { if (rootEl) {
const container = getScrollContainer(rootEl.value); const container = getScrollContainer(rootEl);
if (container == null) { if (container == null) {
// TODO? // TODO?
} else { } else {
const pos = getScrollPosition(rootEl.value); const pos = getScrollPosition(rootEl);
const viewHeight = container.clientHeight; const viewHeight = container.clientHeight;
const height = container.scrollHeight; const height = container.scrollHeight;
const isBottom = (pos + viewHeight > height - 32); const isBottom = (pos + viewHeight > height - 32);
// Discard old items if they overflow.
if (isBottom) { if (isBottom) {
// while (items.length >= props.displayLimit) {
if (items.value.length >= props.displayLimit) { items.shift();
// Vue 3.2
//items.value = items.value.slice(-props.displayLimit);
while (items.value.length >= props.displayLimit) {
items.value.shift();
} }
more.value = true; more = true;
} }
} }
} }
} items.push(item);
items.value.push(item);
// TODO // TODO
} else { } else {
// unshiftOK // Only unshift is required for initial display.
if (!rootEl.value) { if (!rootEl) {
items.value.unshift(item); items.unshift(item);
return; return;
} }
const isTop = isBackTop.value || (document.body.contains(rootEl.value) && isTopVisible(rootEl.value)); const isTop = isBackTop || (document.body.contains(rootEl) && isTopVisible(rootEl));
if (isTop) { if (isTop) {
// Prepend the item // Prepend the item
items.value.unshift(item); items.unshift(item);
// // Discard old items if they overflow.
if (items.value.length >= props.displayLimit) { while (items.length >= props.displayLimit) {
// Vue 3.2 items.pop();
//this.items = items.value.slice(0, props.displayLimit);
while (items.value.length >= props.displayLimit) {
items.value.pop();
}
more.value = true;
} }
more = true;
} else { } else {
queue.value.push(item); queue.push(item);
onScrollTop(rootEl.value, () => { onScrollTop(rootEl, () => {
for (const queueItem of queue.value) { for (const queueItem of queue) {
prepend(queueItem); prepend(queueItem);
} }
queue.value = []; queue = [];
}); });
} }
} }
}; };
const append = (item: Item): void => { const append = (item: Item): void => {
items.value.push(item); items.push(item);
}; };
const removeItem = (finder: (item: Item) => boolean): void => { const removeItem = (finder: (item: Item) => boolean): void => {
const i = items.value.findIndex(finder); const i = items.findIndex(finder);
items.value.splice(i, 1); items.splice(i, 1);
}; };
const updateItem = (id: Item['id'], replacer: (old: Item) => Item): void => { const updateItem = (id: Item['id'], replacer: (old: Item) => Item): void => {
const i = items.value.findIndex(item => item.id === id); const i = items.findIndex(item => item.id === id);
items.value[i] = replacer(items.value[i]); items[i] = replacer(items[i]);
}; };
if (props.pagination.params && isRef(props.pagination.params)) { if (props.pagination.params && isRef(props.pagination.params)) {
watch(props.pagination.params, init, { deep: true }); watch(props.pagination.params, init, { deep: true });
} }
watch(queue, (a, b) => { watch($$(queue), (a, b) => {
if (a.length === 0 && b.length === 0) return; if (a.length !== 0 || b.length !== 0) emit('queue', queue.length);
emit('queue', queue.value.length);
}, { deep: true }); }, { deep: true });
init(); init();
onActivated(() => { onActivated(() => {
isBackTop.value = false; isBackTop = false;
}); });
onDeactivated(() => { onDeactivated(() => {
isBackTop.value = window.scrollY === 0; isBackTop = window.scrollY === 0;
}); });
defineExpose({ defineExpose({