import { ColorPalette } from '../tokens'; import { DesignToken } from 'style-dictionary'; export function select(path: string): any { return ({ colors }: { colors?: ColorPalette }) => { if (!colors) { throw new Error( '@lendi-ui/theme: Theme not found. Please ensure your components are wrapped in the Theme component e.g. ' ); } const pathWithDesignToken = `${path}.value`; let obj: any = colors; let startIndex = -1; let finishIndex = -1; do { // check if there is a key that matches the remainder of the path const restOfPath = pathWithDesignToken.substr(startIndex + 1); if (Object.prototype.hasOwnProperty.call(obj, restOfPath)) { return obj[restOfPath]; } // check if there is a key that matches the next part of the path finishIndex = pathWithDesignToken.indexOf('.', startIndex + 1); const nextPartOfPath = pathWithDesignToken.substr(startIndex + 1, finishIndex - startIndex - 1); if (finishIndex === -1 || !Object.prototype.hasOwnProperty.call(obj, nextPartOfPath)) { // console.warn(`@lendi-ui/commons: getColour(${path}) Could not find a matching color.`); return undefined; } obj = obj[nextPartOfPath]; startIndex = finishIndex; } while (true); // eslint-disable-line no-constant-condition }; }