Compare commits

...

20 Commits

Author SHA1 Message Date
Tim
81dfddf6e1 feat: highlight post author in comments 2025-09-25 13:34:25 +08:00
Tim
8b93aa95cf Merge pull request #1027 from nagisa77/feature/avatar_count
fix: 移动端头像显示问题 #1023
2025-09-24 16:58:29 +08:00
tim
425fc7d2b1 fix: 移动端头像显示问题 #1023 2025-09-24 16:57:42 +08:00
Tim
0fff73b682 Merge pull request #1025 from nagisa77/codex/add-pagination-support-for-tags-qfn36n
feat: paginate tags across backend and ui
2025-09-24 16:18:09 +08:00
Tim
e1171212d7 Merge pull request #1026 from nagisa77/codex/fix-dropdown-to-scroll-after-loading-more
fix: keep dropdown at bottom after loading more
2025-09-24 16:15:14 +08:00
Tim
e96db5d0d6 fix: keep dropdown at bottom after loading more 2025-09-24 16:14:45 +08:00
tim
1083c4241a fix: 修复语法问题 2025-09-24 16:06:17 +08:00
Tim
1eeabab41a feat: paginate tags across backend and ui 2025-09-24 15:58:24 +08:00
Tim
2b5f6f2208 Merge pull request #1022 from nagisa77/feature/user_list_and_avatar
Feature/user list and avatar
2025-09-24 01:51:51 +08:00
tim
bda377336d fix: 优化一些头像属性 2025-09-24 01:51:02 +08:00
tim
77507f7b18 Revert "style: enhance BaseUserAvatar presentation"
This reverts commit 229439aa05.
2025-09-24 01:38:41 +08:00
Tim
a39f2f7c00 Merge pull request #1021 from nagisa77/codex/improve-baseuseravatar-styling-ok22do
style: enhance BaseUserAvatar presentation
2025-09-24 01:31:46 +08:00
Tim
229439aa05 style: enhance BaseUserAvatar presentation 2025-09-24 01:31:31 +08:00
tim
612881f1b1 Revert "refine BaseUserAvatar styling"
This reverts commit c68c5985f6.
2025-09-24 01:31:05 +08:00
Tim
05c7bc18d7 Merge pull request #1020 from nagisa77/codex/improve-baseuseravatar-styling-z7f617
Enhance BaseUserAvatar aesthetics
2025-09-24 01:23:25 +08:00
tim
7d44791011 Revert "feat: refresh base user avatar styling"
This reverts commit 4b8229b0a1.
2025-09-24 01:22:50 +08:00
Tim
15b992b949 Merge pull request #1019 from nagisa77/codex/improve-baseuseravatar-styling
feat: refresh base user avatar styling
2025-09-24 01:21:29 +08:00
Tim
4b8229b0a1 feat: refresh base user avatar styling 2025-09-24 01:21:12 +08:00
Tim
dc13b2941f Merge pull request #1016 from nagisa77/feature/vditor_layout
fix: 移动端--频道--表情无法显示完全 #994
2025-09-23 23:48:59 +08:00
tim
13c250d392 fix: 移动端--频道--表情无法显示完全 #994 2025-09-23 23:48:31 +08:00
10 changed files with 342 additions and 277 deletions

View File

@@ -100,18 +100,32 @@ public class TagController {
)
public List<TagDto> list(
@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "pageSize", required = false) Integer pageSize,
@RequestParam(value = "limit", required = false) Integer limit
) {
List<Tag> tags = tagService.searchTags(keyword);
List<Long> tagIds = tags.stream().map(Tag::getId).toList();
Map<Long, Long> postCntByTagIds = postService.countPostsByTagIds(tagIds);
if (postCntByTagIds == null) {
postCntByTagIds = java.util.Collections.emptyMap();
}
Map<Long, Long> finalPostCntByTagIds = postCntByTagIds;
List<TagDto> dtos = tags
.stream()
.map(t -> tagMapper.toDto(t, postCntByTagIds.getOrDefault(t.getId(), 0L)))
.map(t -> tagMapper.toDto(t, finalPostCntByTagIds.getOrDefault(t.getId(), 0L)))
.sorted((a, b) -> Long.compare(b.getCount(), a.getCount()))
.collect(Collectors.toList());
if (page != null && pageSize != null && page >= 0 && pageSize > 0) {
int fromIndex = page * pageSize;
if (fromIndex >= dtos.size()) {
return java.util.Collections.emptyList();
}
int toIndex = Math.min(fromIndex + pageSize, dtos.size());
return new java.util.ArrayList<>(dtos.subList(fromIndex, toIndex));
}
if (limit != null && limit > 0 && dtos.size() > limit) {
return dtos.subList(0, limit);
return new java.util.ArrayList<>(dtos.subList(0, limit));
}
return dtos;
}

View File

@@ -82,6 +82,7 @@ class TagControllerTest {
t.setIcon("i2");
t.setSmallIcon("s2");
Mockito.when(tagService.searchTags(null)).thenReturn(List.of(t));
Mockito.when(postService.countPostsByTagIds(List.of(2L))).thenReturn(java.util.Map.of());
mockMvc
.perform(get("/api/tags"))
@@ -93,6 +94,31 @@ class TagControllerTest {
.andExpect(jsonPath("$[0].smallIcon").value("s2"));
}
@Test
void listTagsWithPagination() throws Exception {
Tag t1 = new Tag();
t1.setId(1L);
t1.setName("java");
Tag t2 = new Tag();
t2.setId(2L);
t2.setName("spring");
Mockito.when(tagService.searchTags(null)).thenReturn(List.of(t1, t2));
Mockito.when(postService.countPostsByTagIds(List.of(1L, 2L))).thenReturn(
java.util.Map.of(1L, 1L, 2L, 5L)
);
mockMvc
.perform(get("/api/tags").param("page", "1").param("pageSize", "1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", org.hamcrest.Matchers.hasSize(1)))
.andExpect(jsonPath("$[0].id").value(1));
mockMvc
.perform(get("/api/tags").param("page", "2").param("pageSize", "1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", org.hamcrest.Matchers.hasSize(0)));
}
@Test
void updateTag() throws Exception {
Tag t = new Tag();

View File

@@ -108,7 +108,6 @@ body {
.vditor-toolbar--pin {
top: calc(var(--header-height) + 1px) !important;
z-index: 20;
}
.vditor-panel {
@@ -134,26 +133,6 @@ body {
animation: spin 1s linear infinite;
}
/* .vditor {
--textarea-background-color: transparent;
border: none !important;
box-shadow: none !important;
}
.vditor-reset {
color: var(--text-color);
}
.vditor-toolbar {
background: transparent !important;
border: none !important;
box-shadow: none !important;
} */
/* .vditor-toolbar {
position: relative !important;
} */
/*************************
* Markdown 渲染样式
*************************/
@@ -333,10 +312,6 @@ body {
min-height: 100px;
}
.vditor-toolbar {
overflow-x: auto;
}
.about-content h1,
.info-content-text h1 {
font-size: 20px;
@@ -354,8 +329,8 @@ body {
margin-bottom: 3px;
}
.vditor-toolbar--pin {
top: 0 !important;
.vditor-panel {
min-width: 330px;
}
.about-content li,
@@ -367,11 +342,6 @@ body {
line-height: 1.5;
}
.vditor-panel {
position: relative;
min-width: 0;
}
.d2h-file-name {
font-size: 14px !important;
}

View File

@@ -6,8 +6,7 @@
:style="wrapperStyle"
v-bind="wrapperAttrs"
>
<BaseImage :src="currentSrc" :alt="altText" :class="imageClass" @error="onError" />
<span v-if="showInitial" class="base-user-avatar-initial">{{ userInitial }}</span>
<BaseImage :src="currentSrc" :alt="altText" class="base-user-avatar-img" @error="onError" />
</NuxtLink>
</template>
@@ -70,121 +69,19 @@ const resolvedLink = computed(() => {
const altText = computed(() => props.alt || '用户头像')
const identifier = computed(() => {
if (props.userId !== null && props.userId !== undefined && props.userId !== '') {
return String(props.userId)
}
if (props.alt && props.alt.trim()) {
return props.alt.trim()
}
return altText.value
})
const initialSource = computed(() => {
if (props.alt && props.alt.trim() && props.alt.trim() !== '用户头像') {
return props.alt.trim()
}
if (attrs.title && typeof attrs.title === 'string' && attrs.title.trim()) {
return attrs.title.trim()
}
if (props.userId !== null && props.userId !== undefined && props.userId !== '') {
return String(props.userId)
}
return ''
})
const isDefaultAvatar = computed(() => currentSrc.value === DEFAULT_AVATAR)
function parseCssSize(value) {
if (typeof value === 'number' && Number.isFinite(value)) {
return { numeric: value, unit: 'px' }
}
if (typeof value !== 'string') return null
const trimmed = value.trim()
if (!trimmed) return null
const directNumber = Number(trimmed)
if (!Number.isNaN(directNumber)) {
return { numeric: directNumber, unit: 'px' }
}
const match = trimmed.match(/^(-?\d*\.?\d+)([a-z%]+)$/i)
if (!match) return null
return { numeric: Number(match[1]), unit: match[2] }
}
const sizeStyle = computed(() => {
if (!props.width && props.width !== 0) return null
const value = typeof props.width === 'number' ? `${props.width}px` : props.width
if (!value) return null
const parsed = parseCssSize(value)
const style = { width: value, height: value, '--avatar-size': value }
if (parsed && Number.isFinite(parsed.numeric)) {
const computedFont = (parsed.numeric * 0.42).toFixed(2)
const normalized = computedFont.replace(/\.00$/, '')
style['--avatar-font-size'] = `${normalized}${parsed.unit}`
}
return style
})
function stringToColorSeed(value) {
if (!value) return 0
let hash = 0
for (let i = 0; i < value.length; i += 1) {
hash = (hash << 5) - hash + value.charCodeAt(i)
hash |= 0
}
return Math.abs(hash)
}
const accentStyle = computed(() => {
if (!isDefaultAvatar.value) return null
const seed = stringToColorSeed(identifier.value)
const hue = seed % 360
const altHue = (hue + 37) % 360
const saturation = 72
const lightness = 78
const start = `hsl(${hue}, ${saturation}%, ${Math.min(lightness + 8, 95)}%)`
const end = `hsl(${altHue}, ${Math.max(saturation - 12, 45)}%, ${Math.max(lightness - 12, 48)}%)`
return {
'--avatar-background': `linear-gradient(135deg, ${start}, ${end})`,
'--avatar-border-color': `hsla(${hue}, ${Math.max(saturation - 24, 32)}%, ${Math.max(
lightness - 35,
28,
)}%, 0.55)`,
'--avatar-text-color': '#ffffff',
}
return { width: value, height: value }
})
const wrapperStyle = computed(() => {
const attrStyle = attrs.style
return [
{ '--avatar-font-size': 'clamp(0.75rem, 0.6rem + 0.4vw, 1.75rem)' },
sizeStyle.value,
accentStyle.value,
attrStyle,
]
return [sizeStyle.value, attrStyle]
})
const wrapperClass = computed(() => [
attrs.class,
{
'is-rounded': props.rounded,
'has-default': isDefaultAvatar.value,
'is-interactive': !props.disableLink && Boolean(resolvedLink.value),
},
])
const imageClass = computed(() => ['base-user-avatar-img', { 'is-default': isDefaultAvatar.value }])
const userInitial = computed(() => {
const source = initialSource.value || ''
const trimmed = source.trim()
if (!trimmed) return ''
const match = trimmed.match(/[\p{L}\p{N}]/u)
if (match && match[0]) return match[0].toUpperCase()
return trimmed.charAt(0).toUpperCase()
})
const showInitial = computed(() => isDefaultAvatar.value && Boolean(userInitial.value))
const wrapperClass = computed(() => [attrs.class, { 'is-rounded': props.rounded }])
const wrapperAttrs = computed(() => {
const { class: _class, style: _style, ...rest } = attrs
@@ -200,28 +97,24 @@ function onError() {
<style scoped>
.base-user-avatar {
--avatar-background: var(--avatar-placeholder-color, #f0f0f0);
--avatar-border-color: rgba(15, 23, 42, 0.08);
--avatar-text-color: rgba(255, 255, 255, 0.86);
--avatar-shadow: 0 6px 18px rgba(15, 23, 42, 0.12);
--avatar-shadow-hover: 0 10px 24px rgba(15, 23, 42, 0.16);
--avatar-size: 3rem;
display: inline-flex;
align-items: center;
justify-content: center;
overflow: hidden;
position: relative;
background: var(--avatar-background);
border: 1px solid var(--avatar-border-color);
border-radius: var(--avatar-border-radius, 16px);
box-shadow: var(--avatar-shadow);
color: var(--avatar-text-color);
transition:
transform 0.28s ease,
box-shadow 0.32s ease,
border-color 0.32s ease,
filter 0.28s ease;
isolation: isolate;
background-color: var(--avatar-placeholder-color, #f0f0f0);
/* 先用box-sizing: border-box保证加border后宽高不变圆形不变形 */
box-sizing: border-box;
border: 1.5px solid var(--normal-border-color);
transition: all 0.6s ease;
}
.base-user-avatar:hover {
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
transform: scale(1.05);
}
.base-user-avatar:active {
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
}
.base-user-avatar.is-rounded {
@@ -229,35 +122,7 @@ function onError() {
}
.base-user-avatar:not(.is-rounded) {
border-radius: var(--avatar-border-radius, 16px);
}
.base-user-avatar.is-interactive {
cursor: pointer;
}
.base-user-avatar.is-interactive:hover,
.base-user-avatar.is-interactive:focus-visible {
transform: translateY(-1px) scale(1.01);
box-shadow: var(--avatar-shadow-hover);
border-color: rgba(59, 130, 246, 0.4);
}
.base-user-avatar.has-default::after {
content: '';
position: absolute;
inset: 1px;
border-radius: inherit;
background: rgba(15, 23, 42, 0.12);
mix-blend-mode: soft-light;
opacity: 0.25;
pointer-events: none;
transition: opacity 0.28s ease;
}
.base-user-avatar.has-default:hover::after,
.base-user-avatar.has-default:focus-visible::after {
opacity: 0.18;
border-radius: 0;
}
.base-user-avatar-img {
@@ -265,42 +130,5 @@ function onError() {
height: 100%;
object-fit: cover;
display: block;
filter: saturate(108%);
transition:
opacity 0.35s ease,
transform 0.35s ease,
filter 0.35s ease;
}
.base-user-avatar-img.is-default {
opacity: 0.32;
filter: saturate(90%) brightness(1.05);
mix-blend-mode: multiply;
}
.base-user-avatar-initial {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
font-weight: 600;
font-size: var(--avatar-font-size, calc(var(--avatar-size) * 0.42));
text-transform: uppercase;
letter-spacing: 0.04em;
pointer-events: none;
user-select: none;
color: inherit;
text-shadow: 0 1px 4px rgba(15, 23, 42, 0.4);
}
@media (prefers-reduced-motion: reduce) {
.base-user-avatar {
transition: none;
}
.base-user-avatar-img {
transition: none;
}
}
</style>

View File

@@ -15,6 +15,7 @@
<div class="common-info-content-header">
<div class="info-content-header-left">
<span class="user-name">{{ comment.userName }}</span>
<span v-if="isCommentFromPostAuthor" class="op-badge" title="楼主">OP</span>
<medal-one class="medal-icon" />
<NuxtLink
v-if="comment.medal"
@@ -157,6 +158,12 @@ const lightboxImgs = ref([])
const loggedIn = computed(() => authState.loggedIn)
const countReplies = (list) => list.reduce((sum, r) => sum + 1 + countReplies(r.reply || []), 0)
const replyCount = computed(() => countReplies(props.comment.reply || []))
const isCommentFromPostAuthor = computed(() => {
if (props.comment.userId == null || props.postAuthorId == null) {
return false
}
return String(props.comment.userId) === String(props.postAuthorId)
})
const toggleReplies = () => {
showReplies.value = !showReplies.value
@@ -426,6 +433,21 @@ const handleContentClick = (e) => {
color: var(--text-color);
}
.op-badge {
display: inline-flex;
align-items: center;
justify-content: center;
margin-left: 6px;
padding: 0 6px;
height: 18px;
border-radius: 9px;
background-color: rgba(242, 100, 25, 0.12);
color: #f26419;
font-size: 12px;
font-weight: 600;
line-height: 1;
}
.medal-icon {
font-size: 12px;
opacity: 0.6;

View File

@@ -52,6 +52,7 @@
v-if="open && !isMobile && (loading || filteredOptions.length > 0 || showSearch)"
:class="['dropdown-menu', menuClass]"
v-click-outside="close"
ref="menuRef"
>
<div v-if="showSearch" class="dropdown-search">
<search-icon class="search-icon" />
@@ -80,6 +81,7 @@
<span>{{ o.name }}</span>
</slot>
</div>
<slot name="footer" :close="close" :loading="loading" />
</template>
</div>
<Teleport to="body">
@@ -88,7 +90,7 @@
<next class="back-icon" @click="close" />
<span class="mobile-title">{{ placeholder }}</span>
</div>
<div class="dropdown-mobile-menu">
<div class="dropdown-mobile-menu" ref="mobileMenuRef">
<div v-if="showSearch" class="dropdown-search">
<search-icon class="search-icon" />
<input type="text" v-model="search" placeholder="搜索" />
@@ -116,6 +118,7 @@
<span>{{ o.name }}</span>
</slot>
</div>
<slot name="footer" :close="close" :loading="loading" />
</template>
</div>
</div>
@@ -151,6 +154,8 @@ export default {
const loaded = ref(false)
const loading = ref(false)
const wrapper = ref(null)
const menuRef = ref(null)
const mobileMenuRef = ref(null)
const isMobile = useIsMobile()
const toggle = () => {
@@ -200,6 +205,17 @@ export default {
}
}
const scrollToBottom = () => {
const el = isMobile.value ? mobileMenuRef.value : menuRef.value
if (el) {
el.scrollTop = el.scrollHeight
}
}
const reload = async () => {
await loadOptions(props.remote ? search.value : undefined)
}
watch(
() => props.initialOptions,
(val) => {
@@ -249,7 +265,7 @@ export default {
return /^https?:\/\//.test(icon) || icon.startsWith('/')
}
expose({ toggle, close })
expose({ toggle, close, reload, scrollToBottom })
return {
open,
@@ -259,6 +275,8 @@ export default {
search,
filteredOptions,
wrapper,
menuRef,
mobileMenuRef,
selectedLabels,
isSelected,
loading,

View File

@@ -116,30 +116,42 @@
<div v-if="isLoadingTag" class="menu-loading-container">
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
</div>
<div
v-else
v-for="t in tagData"
:key="t.id"
class="section-item"
:class="{ selected: isTagSelected(t.id) }"
<template v-else>
<div
v-for="t in tagData"
:key="t.id"
class="section-item"
:class="{ selected: isTagSelected(t.id) }"
@click="gotoTag(t)"
>
<BaseImage
v-if="isImageIcon(t.smallIcon || t.icon)"
:src="t.smallIcon || t.icon"
class="section-item-icon"
:alt="t.name"
/>
<component
v-else-if="t.smallIcon || t.icon"
:is="t.smallIcon || t.icon"
class="section-item-icon"
/>
<tag-one v-else class="section-item-icon" />
<span class="section-item-text"
>{{ t.name }} <span class="section-item-text-count">x {{ t.count }}</span></span
>
</div>
<BaseImage
v-if="isImageIcon(t.smallIcon || t.icon)"
:src="t.smallIcon || t.icon"
class="section-item-icon"
:alt="t.name"
/>
<component
v-else-if="t.smallIcon || t.icon"
:is="t.smallIcon || t.icon"
class="section-item-icon"
/>
<tag-one v-else class="section-item-icon" />
<span class="section-item-text"
>{{ t.name }} <span class="section-item-text-count">x {{ t.count }}</span></span
>
</div>
<div v-if="hasMoreTags || isLoadingMoreTags" class="section-item more-item">
<a
v-if="hasMoreTags && !isLoadingMoreTags"
href="#"
class="more-link"
@click.prevent="loadMoreTags"
>
查看更多
</a>
<span v-else class="more-loading">加载中...</span>
</div>
</template>
</div>
</div>
</div>
@@ -207,16 +219,88 @@ const {
},
)
const TAG_PAGE_SIZE = 10
const tagPage = ref(0)
const hasMoreTags = ref(true)
const isLoadingMoreTags = ref(false)
const buildTagUrl = (page = 0) => {
const base = API_BASE_URL || (import.meta.client ? window.location.origin : '')
const url = new URL('/api/tags', base)
url.searchParams.set('page', String(page))
url.searchParams.set('pageSize', String(TAG_PAGE_SIZE))
return url.toString()
}
const fetchTagPage = async (page = 0) => {
try {
return await $fetch(buildTagUrl(page))
} catch (e) {
console.error('Failed to fetch tags', e)
return []
}
}
const {
data: tagData,
pending: isLoadingTag,
error: tagError,
} = await useAsyncData('menu:tags', () => $fetch(`${API_BASE_URL}/api/tags?limit=10`), {
} = await useAsyncData('menu:tags', () => fetchTagPage(0), {
server: true,
default: () => [],
staleTime: 5 * 60 * 1000,
})
const dedupeTags = (list) => Array.from(new Map(list.map((tag) => [tag.id, tag])).values())
const initializeTagState = (val) => {
const initial = Array.isArray(val) ? val : []
if (!Array.isArray(val)) {
tagData.value = []
}
tagPage.value = 0
hasMoreTags.value = initial.length === TAG_PAGE_SIZE
}
initializeTagState(tagData.value)
watch(
tagData,
(val, oldVal) => {
const next = Array.isArray(val) ? val : []
if (!Array.isArray(val)) {
tagData.value = []
}
const shouldReset =
!Array.isArray(oldVal) || oldVal.length > next.length || next.length <= TAG_PAGE_SIZE
if (shouldReset) {
tagPage.value = 0
hasMoreTags.value = next.length === TAG_PAGE_SIZE
}
},
{ deep: false },
)
const loadMoreTags = async () => {
if (isLoadingMoreTags.value || !hasMoreTags.value) return
isLoadingMoreTags.value = true
const nextPage = tagPage.value + 1
try {
const result = await fetchTagPage(nextPage)
const data = Array.isArray(result) ? result : []
const existing = Array.isArray(tagData.value) ? tagData.value : []
tagData.value = dedupeTags([...existing, ...data])
tagPage.value = nextPage
if (data.length < TAG_PAGE_SIZE) {
hasMoreTags.value = false
}
} catch (e) {
console.error('Failed to load more tags', e)
} finally {
isLoadingMoreTags.value = false
}
}
/** 其余逻辑保持不变 */
const iconClass = computed(() => {
switch (themeState.mode) {
@@ -433,6 +517,27 @@ const gotoTag = (t) => {
transition: background-color 0.5s ease;
}
.more-item {
justify-content: center;
}
.more-link {
color: var(--primary-color);
text-decoration: none;
font-size: 14px;
cursor: pointer;
}
.more-link:hover {
text-decoration: underline;
}
.more-loading {
font-size: 13px;
color: var(--menu-text-color);
opacity: 0.7;
}
.section-item:hover {
background-color: var(--menu-selected-background-color-hover);
}
@@ -441,7 +546,6 @@ const gotoTag = (t) => {
background-color: var(--menu-selected-background-color);
}
.section-item-text-count {
font-size: 12px;
color: var(--menu-text-color);

View File

@@ -159,12 +159,6 @@ export default {
border: 1px solid var(--border-color);
border-radius: 8px;
}
.vditor {
min-height: 50px;
max-height: 150px;
}
.message-bottom-container {
display: flex;
flex-direction: row;

View File

@@ -1,5 +1,6 @@
<template>
<Dropdown
ref="dropdownRef"
v-model="selected"
:fetch-options="fetchTags"
multiple
@@ -25,11 +26,23 @@
<div v-if="option.description" class="option-desc">{{ option.description }}</div>
</div>
</template>
<template #footer>
<div v-if="hasMoreRemoteTags" class="dropdown-footer">
<a
href="#"
class="dropdown-more"
:class="{ disabled: loadMoreRequested }"
@click.prevent="loadMoreRemoteTags"
>
{{ loadMoreRequested ? '加载中...' : '查看更多' }}
</a>
</div>
</template>
</Dropdown>
</template>
<script setup>
import { computed, ref, watch } from 'vue'
import { computed, reactive, ref, watch, nextTick } from 'vue'
import { toast } from '~/main'
import Dropdown from '~/components/Dropdown.vue'
const config = useRuntimeConfig()
@@ -42,9 +55,19 @@ const props = defineProps({
options: { type: Array, default: () => [] },
})
const dropdownRef = ref(null)
const localTags = ref([])
const providedTags = ref(Array.isArray(props.options) ? [...props.options] : [])
const TAG_PAGE_SIZE = 10
const remoteState = reactive({
keyword: '',
nextPage: 0,
hasMore: true,
options: [],
})
const loadMoreRequested = ref(false)
watch(
() => props.options,
(val) => {
@@ -53,7 +76,7 @@ watch(
)
const mergedOptions = computed(() => {
const arr = [...providedTags.value, ...localTags.value]
const arr = [...providedTags.value, ...localTags.value, ...remoteState.options]
return arr.filter((v, i, a) => a.findIndex((t) => t.id === v.id) === i)
})
@@ -62,44 +85,93 @@ const isImageIcon = (icon) => {
return /^https?:\/\//.test(icon) || icon.startsWith('/')
}
const buildTagsUrl = (kw = '') => {
const buildTagsUrl = (kw = '', page = 0) => {
const base = API_BASE_URL || (import.meta.client ? window.location.origin : '')
const url = new URL('/api/tags', base)
if (kw) url.searchParams.set('keyword', kw)
url.searchParams.set('limit', '10')
url.searchParams.set('page', String(page))
url.searchParams.set('pageSize', String(TAG_PAGE_SIZE))
return url.toString()
}
const fetchRemoteTags = async (kw = '', page = 0) => {
const url = buildTagsUrl(kw, page)
try {
const res = await fetch(url)
if (res.ok) {
const data = await res.json()
return Array.isArray(data) ? data : []
}
throw new Error('failed to fetch tags')
} catch (e) {
console.error('Failed to fetch tags', e)
toast.error('获取标签失败')
throw e
}
}
const combineOptions = (remoteOptions = []) => {
const options = [...providedTags.value, ...localTags.value, ...remoteOptions]
return Array.from(new Map(options.map((t) => [t.id, t])).values())
}
const fetchTags = async (kw = '') => {
const defaultOption = { id: 0, name: '无标签' }
// 1) 先拼 URL自动兜底到 window.location.origin
const url = buildTagsUrl(kw)
// 2) 拉数据
let data = []
try {
const res = await fetch(url)
if (res.ok) data = await res.json()
} catch {
toast.error('获取标签失败')
if (kw !== remoteState.keyword) {
remoteState.keyword = kw
remoteState.nextPage = 0
remoteState.options = []
remoteState.hasMore = true
}
// 3) 合并、去重、可创建
let options = [...data, ...localTags.value]
const shouldFetch = remoteState.options.length === 0 || loadMoreRequested.value
if (shouldFetch) {
const pageToFetch = loadMoreRequested.value ? remoteState.nextPage : 0
try {
const data = await fetchRemoteTags(remoteState.keyword, pageToFetch)
if (pageToFetch === 0) {
remoteState.options = data
} else {
const existing = Array.isArray(remoteState.options) ? remoteState.options : []
const merged = [...existing, ...data]
remoteState.options = Array.from(new Map(merged.map((t) => [t.id, t])).values())
}
remoteState.hasMore = data.length === TAG_PAGE_SIZE
remoteState.nextPage = pageToFetch + 1
} catch (e) {
return [defaultOption, ...combineOptions(remoteState.options)]
} finally {
loadMoreRequested.value = false
}
}
let options = combineOptions(remoteState.options)
if (props.creatable && kw && !options.some((t) => t.name.toLowerCase() === kw.toLowerCase())) {
options.push({ id: `__create__:${kw}`, name: `创建"${kw}"` })
}
options = Array.from(new Map(options.map((t) => [t.id, t])).values())
// 4) 最终结果
return [defaultOption, ...options]
}
const hasMoreRemoteTags = computed(() => remoteState.hasMore)
const loadMoreRemoteTags = async () => {
if (!remoteState.hasMore || loadMoreRequested.value) return
loadMoreRequested.value = true
try {
await dropdownRef.value?.reload()
await nextTick()
dropdownRef.value?.scrollToBottom?.()
} catch (e) {
console.error('Failed to load more tags', e)
loadMoreRequested.value = false
}
}
const selected = computed({
get: () => props.modelValue,
set: (v) => {
@@ -151,4 +223,21 @@ const selected = computed({
font-weight: bold;
opacity: 0.4;
}
.dropdown-footer {
padding: 8px 20px;
text-align: center;
border-top: 1px solid var(--normal-border-color);
}
.dropdown-more {
color: var(--primary-color);
text-decoration: none;
cursor: pointer;
}
.dropdown-more.disabled {
pointer-events: none;
opacity: 0.6;
}
</style>

View File

@@ -85,7 +85,7 @@
</div>
<div class="article-member-avatars-container">
<div v-for="member in article.members">
<div v-for="member in article.members" class="article-member-avatar-item">
<BaseUserAvatar
class="article-member-avatar-item-img"
:src="member.avatar"