@awsui/components-react
Version:
On July 19th, 2022, we launched [Cloudscape Design System](https://cloudscape.design). Cloudscape is an evolution of AWS-UI. It consists of user interface guidelines, front-end components, design resources, and development tools for building intuitive, en
71 lines • 2.41 kB
JavaScript
import { isItemGroup } from './utils';
export default function createItemsTree(items) {
const itemToIndex = new Map();
const indexToItem = new Map();
const flatIndices = [];
traverseItems(items, (item, index) => {
const indexKey = stringifyIndex(index);
itemToIndex.set(item, indexKey);
indexToItem.set(indexKey, item);
flatIndices.push(indexKey);
});
return {
getItem: (index) => {
const indexKey = stringifyIndex(index);
return indexToItem.get(indexKey) || null;
},
getItemIndex: (item) => {
const indexKey = itemToIndex.get(item);
if (!indexKey) {
throw new Error('Invariant violation: item is not found.');
}
return parseIndex(indexKey);
},
getSequentialIndex: (index, direction, loop = false) => {
const indexKey = stringifyIndex(index);
const position = flatIndices.indexOf(indexKey);
let nextIndex = position + direction;
if (loop) {
if (nextIndex < 0) {
nextIndex = flatIndices.length - 1;
}
else if (nextIndex >= flatIndices.length) {
nextIndex = 0;
}
}
const nextIndexKey = flatIndices[nextIndex];
if (!nextIndexKey) {
return null;
}
return parseIndex(nextIndexKey);
},
getParentIndex: (item) => {
const indexKey = itemToIndex.get(item);
if (!indexKey) {
throw new Error('Invariant violation: item is not found.');
}
const index = parseIndex(indexKey);
// No parent
if (index.length === 1) {
return null;
}
return index.slice(0, index.length - 1);
},
};
}
export function traverseItems(items, act, parentIndex = []) {
items.forEach((item, index) => {
const itemIndex = [...parentIndex, index];
act(item, itemIndex);
if (isItemGroup(item)) {
traverseItems(item.items, act, itemIndex);
}
});
}
function stringifyIndex(index) {
return index.join('-');
}
function parseIndex(index) {
return index.split('-').map(it => parseInt(it));
}
//# sourceMappingURL=create-items-tree.js.map