iceshrimp/packages/client/src/components/MkPagination.vue

364 lines
10 KiB
Vue
Raw Normal View History

<template>
2023-01-19 07:54:59 +09:00
<transition :name="$store.state.animation ? 'fade' : ''" mode="out-in">
<MkLoading v-if="fetching" />
<MkError v-else-if="error" @retry="init()" />
<div v-else-if="empty" key="_empty_" class="empty">
<slot name="empty">
<div class="_fullinfo">
<img src="/static-assets/badges/info.png" class="_ghost" alt="Error" />
<div>{{ i18n.ts.nothing }}</div>
</div>
</slot>
</div>
2023-01-19 07:54:59 +09:00
<div v-else ref="rootEl">
<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">
{{ i18n.ts.loadMore }}
</MkButton>
<MkLoading v-else class="loading" />
</div>
<slot :items="items"></slot>
<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">
{{ i18n.ts.loadMore }}
</MkButton>
<MkLoading v-else class="loading" />
2021-12-23 16:10:13 +09:00
</div>
</div>
2023-01-19 07:54:59 +09:00
</transition>
</template>
<script lang="ts" setup>
import { computed, ComputedRef, isRef, markRaw, onActivated, onDeactivated, Ref, ref, watch } from 'vue';
2023-01-15 10:24:56 +09:00
import * as calckey from 'calckey-js';
import * as os from '@/os';
import { onScrollTop, isTopVisible, getScrollPosition, getScrollContainer } from '@/scripts/scroll';
import MkButton from '@/components/MkButton.vue';
2022-07-20 22:24:26 +09:00
import { i18n } from '@/i18n';
2023-01-15 10:24:56 +09:00
export type Paging<E extends keyof calckey.Endpoints = keyof calckey.Endpoints> = {
endpoint: E;
limit: number;
2023-01-15 10:24:56 +09:00
params?: calckey.Endpoints[E]['req'] | ComputedRef<calckey.Endpoints[E]['req']>;
/**
* When using non-pageable endpoints, such as the search API
* (though it is somewhat inconsistent to use such an API with this function)
*/
noPaging?: boolean;
/**
* array items in reverse order (newest first)
*/
reversed?: boolean;
offsetMode?: boolean;
};
2022-08-23 12:16:56 +09:00
const SECOND_FETCH_LIMIT = 30;
const props = withDefaults(defineProps<{
pagination: Paging;
disableAutoLoad?: boolean;
displayLimit?: number;
externalItemArray?: Ref<Array<any>>;
}>(), {
displayLimit: 30,
});
const emit = defineEmits<{
(ev: 'queue', count: number): void;
}>();
2023-01-19 07:54:59 +09:00
type Item = { id: string;[another: string]: unknown; };
const rootEl = ref<HTMLElement>();
const items = ref<Item[]>([]);
const queue = ref<Item[]>([]);
const offset = ref(0);
const fetching = ref(true);
const moreFetching = ref(false);
const more = ref(false);
const backed = ref(false); // 遡り中か否か
const isBackTop = ref(false);
const empty = computed(() => items.value.length === 0);
const error = ref(false);
const init = async (): Promise<void> => {
queue.value = [];
fetching.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 as object),
limit: props.pagination.noPaging ? (props.pagination.limit || 10) : (props.pagination.limit || 10) + 1,
}).then(res => {
for (let i = 0; i < res.length; i++) {
const item = res[i];
if (props.pagination.reversed) {
if (i === res.length - 2) item._shouldInsertAd_ = true;
} else {
if (i === 3) item._shouldInsertAd_ = true;
}
}
if (!props.pagination.noPaging && (res.length > (props.pagination.limit || 10))) {
res.pop();
2023-01-13 06:04:56 +09:00
items.value = props.pagination.reversed ? [...res].reverse() : res;
more.value = true;
} else {
2023-01-13 06:04:56 +09:00
items.value = props.pagination.reversed ? [...res].reverse() : res;
more.value = false;
}
offset.value = res.length;
error.value = false;
fetching.value = false;
}, err => {
error.value = true;
fetching.value = false;
});
};
const reload = (): void => {
items.value = [];
init();
};
const refresh = async (): Promise<void> => {
2022-12-29 19:00:30 +09:00
const params = props.pagination.params ? isRef(props.pagination.params) ? props.pagination.params.value : props.pagination.params : {};
await os.api(props.pagination.endpoint, {
...(params as object),
2022-12-29 19:00:30 +09:00
limit: items.value.length + 1,
offset: 0,
}).then(res => {
let ids = items.value.reduce((a, b) => {
a[b.id] = true;
return a;
}, {} as { [id: string]: boolean; });
for (let i = 0; i < res.length; i++) {
const item = res[i];
if (!updateItem(item.id, old => item)) {
append(item);
}
delete ids[item.id];
}
for (const id in ids) {
removeItem(i => i.id === id);
}
}, err => {
error.value = true;
fetching.value = false;
});
};
const fetchMore = async (): Promise<void> => {
if (!more.value || fetching.value || moreFetching.value || items.value.length === 0) return;
moreFetching.value = true;
backed.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 as object),
limit: SECOND_FETCH_LIMIT + 1,
...(props.pagination.offsetMode ? {
offset: offset.value,
} : props.pagination.reversed ? {
sinceId: items.value[0].id,
} : {
untilId: items.value[items.value.length - 1].id,
}),
}).then(res => {
for (let i = 0; i < res.length; i++) {
const item = res[i];
if (props.pagination.reversed) {
if (i === res.length - 9) item._shouldInsertAd_ = true;
} else {
if (i === 10) item._shouldInsertAd_ = true;
}
}
if (res.length > SECOND_FETCH_LIMIT) {
res.pop();
2023-01-13 06:04:56 +09:00
items.value = props.pagination.reversed ? [...res].reverse().concat(items.value) : items.value.concat(res);
more.value = true;
} else {
2023-01-13 06:04:56 +09:00
items.value = props.pagination.reversed ? [...res].reverse().concat(items.value) : items.value.concat(res);
more.value = false;
}
offset.value += res.length;
moreFetching.value = false;
}, err => {
moreFetching.value = 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 as object),
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();
2023-01-19 07:58:16 +09:00
items.value = props.pagination.reversed ? [...res].reverse().concat(items.value) : items.value.concat(res);
more.value = true;
} else {
2023-01-19 07:58:16 +09:00
items.value = props.pagination.reversed ? [...res].reverse().concat(items.value) : items.value.concat(res);
more.value = false;
}
offset.value += res.length;
moreFetching.value = false;
}, err => {
moreFetching.value = false;
});
};
const prepend = (item: Item): void => {
if (props.pagination.reversed) {
if (rootEl.value) {
const container = getScrollContainer(rootEl.value);
if (container == null) {
// TODO?
} else {
const pos = getScrollPosition(rootEl.value);
const viewHeight = container.clientHeight;
const height = container.scrollHeight;
const isBottom = (pos + viewHeight > height - 32);
if (isBottom) {
// オーバーフローしたら古いアイテムは捨てる
if (items.value.length >= props.displayLimit) {
// このやり方だとVue 3.2以降アニメーションが動かなくなる
//items.value = items.value.slice(-props.displayLimit);
while (items.value.length >= props.displayLimit) {
items.value.shift();
}
more.value = true;
}
}
}
}
items.value.push(item);
// TODO
} else {
// 初回表示時はunshiftだけでOK
if (!rootEl.value) {
items.value.unshift(item);
return;
}
const isTop = isBackTop.value || (document.body.contains(rootEl.value) && isTopVisible(rootEl.value));
if (isTop) {
// Prepend the item
items.value.unshift(item);
// オーバーフローしたら古いアイテムは捨てる
if (items.value.length >= props.displayLimit) {
// このやり方だとVue 3.2以降アニメーションが動かなくなる
//this.items = items.value.slice(0, props.displayLimit);
while (items.value.length >= props.displayLimit) {
items.value.pop();
}
more.value = true;
}
} else {
queue.value.push(item);
onScrollTop(rootEl.value, () => {
2022-08-23 12:16:56 +09:00
for (const queueItem of queue.value) {
prepend(queueItem);
}
queue.value = [];
});
}
}
};
const append = (item: Item): void => {
items.value.push(item);
};
2022-12-29 19:00:30 +09:00
const removeItem = (finder: (item: Item) => boolean): boolean => {
const i = items.value.findIndex(finder);
2023-01-19 07:48:05 +09:00
const j = props.externalItemArray?.findIndex(finder);
2022-12-29 19:00:30 +09:00
return false;
}
items.value.splice(i, 1);
2022-12-29 19:00:30 +09:00
return true;
};
2022-12-29 19:00:30 +09:00
const updateItem = (id: Item['id'], replacer: (old: Item) => Item): boolean => {
const i = items.value.findIndex(item => item.id === id);
2023-01-19 07:48:05 +09:00
const j = props.externalItemArray?.findIndex(item => item.id === id);
if (i === -1 && j === -1) {
2022-12-29 19:00:30 +09:00
return false;
}
items.value[i] = replacer(items.value[i]);
2022-12-29 19:00:30 +09:00
return true;
};
if (props.pagination.params && isRef(props.pagination.params)) {
watch(props.pagination.params, init, { deep: true });
}
watch(queue, (a, b) => {
if (a.length === 0 && b.length === 0) return;
emit('queue', queue.value.length);
}, { deep: true });
init();
onActivated(() => {
isBackTop.value = false;
});
onDeactivated(() => {
isBackTop.value = window.scrollY === 0;
});
defineExpose({
2022-01-10 20:17:38 +09:00
items,
feat: Improve Push Notification (#7667) * clean up * ev => data * refactor * clean up * add type * antenna * channel * fix * add Packed type * add PackedRef * fix lint * add emoji schema * add reversiGame * add reversiMatching * remove signin schema (use Signin entity) * add schemas refs, fix Packed type * wip PackedHoge => Packed<'Hoge'> * add Packed type * note-reaction * user * user-group * user-list * note * app, messaging-message * notification * drive-file * drive-folder * following * muting * blocking * hashtag * page * app (with modifying schema) * import user? * channel * antenna * clip * gallery-post * emoji * Packed * reversi-matching * update stream.ts * https://github.com/misskey-dev/misskey/pull/7769#issuecomment-917542339 * fix lint * clean up? * add app * fix * nanka iroiro * wip * wip * fix lint * fix loginId * fix * refactor * refactor * remove follow action * clean up * Revert "remove follow action" This reverts commit defbb416480905af2150d1c92f10d8e1d1288c0a. * Revert "clean up" This reverts commit f94919cb9cff41e274044fc69c56ad36a33974f2. * remove fetch specification * renoteの条件追加 * apiFetch => cli * bypass fetch? * fix * refactor: use path alias * temp: add submodule * remove submodule * enhane: unison-reloadに指定したパスに移動できるように * null * null * feat: ログインするアカウントのIDをクエリ文字列で指定する機能 * null * await? * rename * rename * Update read.ts * merge * get-note-summary * fix * swパッケージに * add missing packages * fix getNoteSummary * add webpack-cli * :v: * remove plugins * sw-inject分離したがテストしてない * fix notification.vue * remove a blank line * disconnect intersection observer * disconnect2 * fix notification.vue * remove a blank line * disconnect intersection observer * disconnect2 * fix * :v: * clean up config * typesを戻した * Update packages/client/src/components/notification.vue Co-authored-by: Acid Chicken (硫酸鶏) <root@acid-chicken.com> * disconnect * oops * Failed to load the script unexpectedly回避 sw.jsとlib.tsを分離してみた * truncate notification * Update packages/client/src/ui/_common_/common.vue Co-authored-by: syuilo <Syuilotan@yahoo.co.jp> * clean up * clean up * キャッシュ対策 * Truncate push notification message * クライアントがあったらストリームに接続しているということなので通知しない判定の位置を修正 * components/drive-file-thumbnail.vue * components/drive-select-dialog.vue * components/drive-window.vue * merge * fix * Service Workerのビルドにesbuildを使うようにする * return createEmptyNotification() * fix * i18n.ts * update * :v: * remove ts-loader * fix * fix * enhance: Service Workerを常に登録するように * pollEnded * URLをsw.jsに戻す * clean up Co-authored-by: Acid Chicken (硫酸鶏) <root@acid-chicken.com> Co-authored-by: syuilo <Syuilotan@yahoo.co.jp>
2022-04-30 21:52:07 +09:00
queue,
backed,
reload,
2022-12-29 19:00:30 +09:00
refresh,
prepend,
append,
removeItem,
updateItem,
});
</script>
<style lang="scss" scoped>
.fade-enter-active,
.fade-leave-active {
2023-01-15 10:24:56 +09:00
transition: opacity 0.15s ease;
}
2023-01-19 07:54:59 +09:00
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
.cxiknjgy {
2023-01-19 07:54:59 +09:00
>.button {
2020-02-12 02:52:37 +09:00
margin-left: auto;
margin-right: auto;
}
}
</style>