budibase/packages/builder/src/builderStore/getNewComponentName.js

49 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-08-07 13:01:16 +02:00
import { walkProps } from "./storeUtils"
import { get_capitalised_name } from "../helpers"
import { get } from "svelte/store"
import { allScreens } from "builderStore"
import { FrontendTypes } from "../constants"
import { currentAsset } from "."
2020-08-07 13:01:16 +02:00
export default function(component, state) {
const capitalised = get_capitalised_name(
component.name || component._component
)
2020-08-07 13:01:16 +02:00
const matchingComponents = []
const findMatches = props => {
walkProps(props, c => {
2020-10-07 23:30:00 +02:00
const thisInstanceName = get_capitalised_name(c._instanceName)
if ((thisInstanceName || "").startsWith(capitalised)) {
matchingComponents.push(thisInstanceName)
2020-08-07 13:01:16 +02:00
}
})
}
// check layouts first
for (let layout of state.layouts) {
findMatches(layout.props)
}
2020-08-07 13:01:16 +02:00
// if viewing screen, check current screen for duplicate
if (state.currentFrontEndType === FrontendTypes.SCREEN) {
findMatches(get(currentAsset).props)
} else {
// viewing a layout - need to find against all screens
for (let screen of get(allScreens)) {
findMatches(screen.props)
2020-08-07 13:01:16 +02:00
}
}
2020-08-07 13:01:16 +02:00
2020-08-07 13:09:48 +02:00
let index = 1
2020-08-07 13:01:16 +02:00
let name
while (!name) {
const tryName = `${capitalised || "Copy"} ${index}`
2020-08-07 13:01:16 +02:00
if (!matchingComponents.includes(tryName)) name = tryName
index++
}
return name
}