Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/plugins/helper/list_categories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -33,6 +34,7 @@ function listCategoriesHelper(this: LocalsType, categories?: Query<CategorySchem
const depth = options.depth ? parseInt(String(options.depth), 10) : 0;
const orderby = options.orderby || 'name';
const order = options.order || 1;
const collator = orderby === 'name' && options.locale ? new Intl.Collator(options.locale) : undefined;
const showCurrent = options.show_current || false;
const childrenIndicator = Object.prototype.hasOwnProperty.call(options, 'children_indicator') ? options.children_indicator : false;

Expand All @@ -45,7 +47,14 @@ function listCategoriesHelper(this: LocalsType, categories?: Query<CategorySchem
query.parent = {$exists: false};
}

return (categories as Query<CategorySchema>).find(query).sort(orderby, order);
const result = (categories as Query<CategorySchema>).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) => {
Expand Down
31 changes: 31 additions & 0 deletions test/scripts/helpers/list_categories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,4 +316,35 @@ describe('list_categories', () => {
'</ul>'
].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}});
}
});
});
Loading