Update sort filter to take multiple keys into account in order of priority, default to order, then title

And use `order` on Page
This commit is contained in:
Lea Verou
2024-12-19 12:26:11 -05:00
parent f99f32d054
commit 5d13583da7
2 changed files with 48 additions and 5 deletions

View File

@@ -83,11 +83,53 @@ export function deepValue(obj, key) {
return key.reduce((subObj, property) => subObj?.[property], obj);
}
export function sort(arr, key = 'data.title') {
key = key.split('.');
function isNumeric(value) {
return typeof value === 'number' || (typeof value === 'string' && !isNaN(value));
}
function isEmpty(value) {
return value === null || value === undefined || value === '';
}
function compare(a, b) {
let isEmptyA = isEmpty(a);
let isEmptyB = isEmpty(b);
if (isEmptyA) {
if (isEmptyB) {
return 0;
} else {
return 1;
}
} else if (isEmptyB) {
return -1;
}
// Both strings, and at least one non-numeric
if (isNumeric(a) || isNumeric(b)) {
return a - b;
}
return (a + '').localeCompare(b);
}
/** Sort an array of objects */
export function sort(arr, keys = ['data.order', 'data.title']) {
keys = toArray(keys);
return arr.sort((a, b) => {
let aVal = deepValue(a, key);
let bVal = deepValue(b, key);
return aVal.localeCompare(bVal);
let aValues = keys.map(key => deepValue(a, key));
let bValues = keys.map(key => deepValue(b, key));
for (let i = 0; i < aValues.length; i++) {
let aVal = aValues[i];
let bVal = bValues[i];
let result = compare(aVal, bVal);
// They are not equal in terms of comparison OR we're at the last key
if (result !== 0 || i === aValues.length - 1) {
return result;
}
}
});
}

View File

@@ -3,6 +3,7 @@ title: Page
description: Pages offer an easy way to scaffold entire page layouts using minimal markup.
tags: component
isPro: true
order: 1
---
The page component is designed to power full webpages. It is flexible enough to handle most modern designs and includes a simple mechanism for handling desktop and mobile navigation.