Files
MySpace/frontend/src/BlogImagePicker.vue
T

58 lines
2.5 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import { ref, watch } from "vue";
import { api, assetContentPath } from "./api";
interface ImageAsset { id: string; name: string }
defineProps<{ title: string }>();
const emit = defineEmits<{ select: [image: ImageAsset]; close: [] }>();
const query = ref("");
const offset = ref(0);
const images = ref<ImageAsset[]>([]);
const loading = ref(false);
const error = ref("");
const pageSize = 100;
watch([query, offset], async ([q, start], _, onCleanup) => {
const request = new AbortController();
onCleanup(() => request.abort());
loading.value = true;
error.value = "";
try {
const params = new URLSearchParams({ type: "image", q, offset: String(start) });
const result = await api<ImageAsset[]>(`/assets?${params}`, { signal: request.signal });
if (!request.signal.aborted) images.value = result;
} catch (e) {
if (!request.signal.aborted) error.value = (e as Error).message;
} finally {
if (!request.signal.aborted) loading.value = false;
}
}, { immediate: true });
</script>
<template>
<section class="blog-image-picker" aria-label="图床图片选择器">
<div class="flex between">
<strong>{{ title }}</strong>
<button type="button" class="linkbtn" @click="emit('close')">关闭选择器</button>
</div>
<input class="field" v-model="query" aria-label="搜索图床图片" placeholder="按文件名搜索图片"
@input="offset = 0" @keydown.enter.prevent />
<p v-if="loading" role="status">正在加载图片…</p>
<p v-else-if="error" role="alert">{{ error }}</p>
<p v-else-if="!images.length" class="muted">
{{ query ? "没有匹配的图片。" : offset ? "没有更多图片了。" : "图床中还没有图片,请先到「图床 / 文件」上传。" }}
</p>
<div v-else class="blog-image-grid">
<button v-for="image in images" :key="image.id" type="button" class="blog-image-choice"
:title="image.name" @click="emit('select', image)">
<img :src="assetContentPath(image.id)" alt="" loading="lazy" />
<span class="ellipsis">{{ image.name }}</span>
</button>
</div>
<div v-if="offset > 0 || images.length === pageSize" class="flex between">
<button type="button" class="btn" :disabled="loading || offset === 0" @click="offset -= pageSize">上一页</button>
<span class="small muted">第 {{ offset / pageSize + 1 }} 页</span>
<button type="button" class="btn" :disabled="loading || !!error || images.length < pageSize" @click="offset += pageSize">下一页</button>
</div>
</section>
</template>