budibase/packages/builder/src/components/userInterface/pagesParsing/searchComponents.js

47 lines
1.4 KiB
JavaScript
Raw Normal View History

import { find, isUndefined, filter, some, includes } from "lodash/fp"
2020-05-07 11:53:34 +02:00
import { pipe } from "components/common/core"
2019-07-28 09:03:11 +02:00
const normalString = s => (s || "").trim().toLowerCase()
2019-07-28 09:03:11 +02:00
export const isRootComponent = c =>
isComponent(c) && isUndefined(c.props._component)
2019-09-03 13:12:24 +02:00
export const isComponent = c => {
const hasProp = n => !isUndefined(c[n])
return hasProp("name") && hasProp("props")
2019-09-03 13:12:24 +02:00
}
2019-07-28 09:03:11 +02:00
export const searchAllComponents = (components, phrase) => {
const hasPhrase = (...vals) =>
pipe(vals, [some(v => includes(normalString(phrase))(normalString(v)))])
2019-07-28 09:03:11 +02:00
const componentMatches = c => {
if (hasPhrase(c.name, ...(c.tags || []))) return true
2019-07-28 09:03:11 +02:00
if (isRootComponent(c)) return false
2019-08-04 23:21:16 +02:00
const parent = getExactComponent(components, c.props._component)
2019-07-28 09:03:11 +02:00
return componentMatches(parent)
}
2019-07-28 09:03:11 +02:00
return filter(componentMatches)(components)
}
2019-07-28 09:03:11 +02:00
export const getExactComponent = (components, name) => {
const stringEquals = (s1, s2) => normalString(s1) === normalString(s2)
2019-07-28 09:03:11 +02:00
return pipe(components, [find(c => stringEquals(c.name, name))])
}
2019-07-28 09:03:11 +02:00
export const getAncestorProps = (components, name, found = []) => {
const thisComponent = getExactComponent(components, name)
2019-07-28 09:03:11 +02:00
if (isRootComponent(thisComponent)) return [thisComponent.props, ...found]
2019-07-28 09:03:11 +02:00
return getAncestorProps(components, thisComponent.props._component, [
{ ...thisComponent.props },
...found,
])
2019-08-14 23:11:59 +02:00
}