From cb4d027d0d243f532bb22e023c86f77fa7f53936 Mon Sep 17 00:00:00 2001 From: Mimi <1119186082@qq.com> Date: Thu, 13 Aug 2026 02:17:30 +0800 Subject: [PATCH] feat(helper): support locale-aware category sorting --- lib/plugins/helper/list_categories.ts | 11 ++++++++- test/scripts/helpers/list_categories.ts | 31 +++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/lib/plugins/helper/list_categories.ts b/lib/plugins/helper/list_categories.ts index 650ded230..0b6208dda 100644 --- a/lib/plugins/helper/list_categories.ts +++ b/lib/plugins/helper/list_categories.ts @@ -9,6 +9,7 @@ interface Options { depth?: number | string; orderby?: string; order?: number; + locale?: string; show_count?: boolean; show_current?: boolean; transform?: (name: string) => string; @@ -33,6 +34,7 @@ function listCategoriesHelper(this: LocalsType, categories?: Query).find(query).sort(orderby, order); + const result = (categories as Query).find(query); + + if (collator) { + const direction = order === -1 || String(order) === 'desc' ? -1 : 1; + return result.toArray().sort((a, b) => collator.compare(a.name, b.name) * direction); + } + + return result.sort(orderby, order); }; const hierarchicalList = (level: number, parent?: any) => { diff --git a/test/scripts/helpers/list_categories.ts b/test/scripts/helpers/list_categories.ts index eccb59df7..384ba511d 100644 --- a/test/scripts/helpers/list_categories.ts +++ b/test/scripts/helpers/list_categories.ts @@ -316,4 +316,35 @@ describe('list_categories', () => { '' ].join('')); }); + + it('locale', async () => { + const names = ['生活', '技术', '编程', '随笔', '测试']; + await Category.insert(names.map(name => ({name}))); + + try { + const categories = Category.find({name: {$in: names}}); + const renderedNames: string[] = []; + const options = { + style: false as const, + show_count: false, + transform(name: string) { + renderedNames.push(name); + return name; + } + }; + + listCategories(categories, options); + renderedNames.should.eql(['技术', '测试', '生活', '编程', '随笔']); + + renderedNames.length = 0; + listCategories(categories, {...options, locale: 'zh-CN'}); + renderedNames.should.eql(['编程', '测试', '技术', '生活', '随笔']); + + renderedNames.length = 0; + listCategories(categories, {...options, locale: 'zh-CN', order: -1}); + renderedNames.should.eql(['随笔', '生活', '技术', '测试', '编程']); + } finally { + await Category.remove({name: {$in: names}}); + } + }); });