@chayns-components/core
Version:
A set of beautiful React components for developing your own applications with chayns.
92 lines (91 loc) • 2.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sortSearchBoxItems = exports.searchList = exports.getCurrentGroupName = void 0;
const surroundWithBTag = (text, startIndex, length) => {
const before = text.substring(0, startIndex);
const highlighted = text.substring(startIndex, startIndex + length);
const after = text.substring(startIndex + length);
return `${before}<b>${highlighted}</b>${after}`;
};
const getCurrentGroupName = element => {
let hasChildrenFound = false;
let currentGroupName = '';
const {
top: parentTop
} = element.getBoundingClientRect();
const {
children
} = element;
Array.from(children).forEach(child => {
if (hasChildrenFound) {
return;
}
const {
y: childrenY,
height: childrenHeight
} = child.getBoundingClientRect();
const {
id
} = child;
const sum = childrenY + childrenHeight - parentTop;
if (sum >= 0) {
hasChildrenFound = true;
let currentGroup = id;
if (id.startsWith('search-box-item__')) {
const nummer = id.split('__')[1];
currentGroup = (nummer === null || nummer === void 0 ? void 0 : nummer.split('_').pop()) ?? '';
}
currentGroupName = currentGroup;
}
});
return currentGroupName;
};
exports.getCurrentGroupName = getCurrentGroupName;
const sortSearchBoxItems = ({
searchString,
items
}) => {
const lowercaseSearchString = searchString.toLowerCase();
return [...items].sort((a, b) => {
const aStartsWithSearchString = a.text.toLowerCase().startsWith(lowercaseSearchString);
const bStartsWithSearchString = b.text.toLowerCase().startsWith(lowercaseSearchString);
if (aStartsWithSearchString && !bStartsWithSearchString) {
return -1;
}
if (!aStartsWithSearchString && bStartsWithSearchString) {
return 1;
}
return a.text.localeCompare(b.text);
});
};
exports.sortSearchBoxItems = sortSearchBoxItems;
const searchList = ({
searchString,
items
}) => {
const matchingItems = [];
const lowercaseSearchString = searchString.toLowerCase();
items.forEach(item => {
const lowercaseText = item.text.toLowerCase();
if (lowercaseText.includes(lowercaseSearchString)) {
if (searchString === '') {
matchingItems.push(item);
} else {
const startIndex = lowercaseText.indexOf(lowercaseSearchString);
const highlightedText = surroundWithBTag(item.text, startIndex, searchString.length);
matchingItems.push({
...item,
text: highlightedText
});
}
}
});
return sortSearchBoxItems({
items: matchingItems,
searchString
});
};
exports.searchList = searchList;
//# sourceMappingURL=searchBox.js.map