@kobalte/core
Version:
Unstyled components and primitives for building accessible web apps and design systems with SolidJS.
116 lines (112 loc) • 3.27 kB
JavaScript
import { access, isString, isNumber } from '@kobalte/utils';
import { createMemo } from 'solid-js';
// src/primitives/create-collection/create-collection.ts
function buildNodes(params) {
let index = params.startIndex ?? 0;
const level = params.startLevel ?? 0;
const nodes = [];
const getKey = (data) => {
if (data == null) {
return "";
}
const _getKey = params.getKey ?? "key";
const dataKey = isString(_getKey) ? data[_getKey] : _getKey(data);
return dataKey != null ? String(dataKey) : "";
};
const getTextValue = (data) => {
if (data == null) {
return "";
}
const _getTextValue = params.getTextValue ?? "textValue";
const dataTextValue = isString(_getTextValue) ? data[_getTextValue] : _getTextValue(data);
return dataTextValue != null ? String(dataTextValue) : "";
};
const getDisabled = (data) => {
if (data == null) {
return false;
}
const _getDisabled = params.getDisabled ?? "disabled";
return (isString(_getDisabled) ? data[_getDisabled] : _getDisabled(data)) ?? false;
};
const getSectionChildren = (data) => {
if (data == null) {
return void 0;
}
if (isString(params.getSectionChildren)) {
return data[params.getSectionChildren];
}
return params.getSectionChildren?.(data);
};
for (const data of params.dataSource) {
if (isString(data) || isNumber(data)) {
nodes.push({
type: "item",
rawValue: data,
key: String(data),
textValue: String(data),
disabled: getDisabled(data),
level,
index
});
index++;
continue;
}
if (getSectionChildren(data) != null) {
nodes.push({
type: "section",
rawValue: data,
key: "",
// not applicable here
textValue: "",
// not applicable here
disabled: false,
// not applicable here
level,
index
});
index++;
const sectionChildren = getSectionChildren(data) ?? [];
if (sectionChildren.length > 0) {
const childNodes = buildNodes({
dataSource: sectionChildren,
getKey: params.getKey,
getTextValue: params.getTextValue,
getDisabled: params.getDisabled,
getSectionChildren: params.getSectionChildren,
startIndex: index,
startLevel: level + 1
});
nodes.push(...childNodes);
index += childNodes.length;
}
} else {
nodes.push({
type: "item",
rawValue: data,
key: getKey(data),
textValue: getTextValue(data),
disabled: getDisabled(data),
level,
index
});
index++;
}
}
return nodes;
}
// src/primitives/create-collection/create-collection.ts
function createCollection(props, deps = []) {
return createMemo(() => {
const nodes = buildNodes({
dataSource: access(props.dataSource),
getKey: access(props.getKey),
getTextValue: access(props.getTextValue),
getDisabled: access(props.getDisabled),
getSectionChildren: access(props.getSectionChildren)
});
for (let i = 0; i < deps.length; i++)
deps[i]();
return props.factory(nodes);
});
}
export { createCollection };