@wordpress/block-library
Version:
Block library for the WordPress editor.
67 lines (66 loc) • 1.58 kB
JavaScript
// packages/block-library/src/gallery/order-images.js
function getSortKey(block, media, orderby) {
const { id } = block.attributes;
if (id === void 0) {
return void 0;
}
const record = media.find((item) => item.id === id);
if (!record) {
return void 0;
}
if (orderby === "title") {
return record.title?.raw ?? record.title?.rendered ?? "";
}
return record.date ?? "";
}
function hasSortableImages(blocks, media) {
const mediaIds = new Set(media.map((item) => item.id));
let sortableCount = 0;
for (const block of blocks) {
if (!mediaIds.has(block.attributes.id)) {
continue;
}
sortableCount++;
if (sortableCount > 1) {
return true;
}
}
return false;
}
function compareKeys(a, b, orderby) {
if (orderby === "title") {
return a.localeCompare(b, void 0, {
numeric: true,
sensitivity: "base"
});
}
if (a === b) {
return 0;
}
return a < b ? -1 : 1;
}
function sortImageBlocks(blocks, media, { orderby, order }) {
const direction = order === "desc" ? -1 : 1;
const keys = new Map(
blocks.map((block) => [
block,
getSortKey(block, media, orderby)
])
);
return [...blocks].sort((a, b) => {
const keyA = keys.get(a);
const keyB = keys.get(b);
if (keyA === void 0 || keyB === void 0) {
if (keyA === keyB) {
return 0;
}
return keyA === void 0 ? 1 : -1;
}
return compareKeys(keyA, keyB, orderby) * direction;
});
}
export {
hasSortableImages,
sortImageBlocks
};
//# sourceMappingURL=order-images.mjs.map