Merge pull request #712 from Budibase/feat/linked-records-data-source

Linked records as data source
This commit is contained in:
Andrew Kingston 2020-10-13 10:13:38 +01:00 committed by GitHub
commit 459544f3b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 305 additions and 136 deletions

View File

@ -73,36 +73,42 @@ const componentInstanceToBindable = walkResult => i => {
const contextToBindables = (models, walkResult) => context => {
const contextParentPath = getParentPath(walkResult, context)
const isModel = context.model?.isModel || typeof context.model === "string"
const modelId =
typeof context.model === "string" ? context.model : context.model.modelId
const modelId = context.model?.modelId ?? context.model
const model = models.find(model => model._id === modelId)
let schema =
context.model?.type === "view"
? model?.views?.[context.model.name]?.schema
: model?.schema
// Avoid crashing whenever no data source has been selected
if (model == null) {
if (!schema) {
return []
}
const newBindable = key => ({
type: "context",
instance: context.instance,
// how the binding expression persists, and is used in the app at runtime
runtimeBinding: `${contextParentPath}data.${key}`,
// how the binding exressions looks to the user of the builder
readableBinding: `${context.instance._instanceName}.${model.name}.${key}`,
// model / view info
model: context.model,
})
// see ModelViewSelect.svelte for the format of context.model
// ... this allows us to bind to Model schemas, or View schemas
const schema = isModel ? model.schema : model.views[context.model.name].schema
const newBindable = ([key, fieldSchema]) => {
// Replace link bindings with a new property representing the count
let runtimeBoundKey = key
if (fieldSchema.type === "link") {
runtimeBoundKey = `${key}_count`
}
return {
type: "context",
fieldSchema,
instance: context.instance,
// how the binding expression persists, and is used in the app at runtime
runtimeBinding: `${contextParentPath}data.${runtimeBoundKey}`,
// how the binding expressions looks to the user of the builder
readableBinding: `${context.instance._instanceName}.${model.name}.${key}`,
// model / view info
model: context.model,
}
}
return (
Object.keys(schema)
Object.entries(schema)
.map(newBindable)
// add _id and _rev fields - not part of schema, but always valid
.concat([newBindable("_id"), newBindable("_rev")])
.concat([newBindable(["_id", "string"]), newBindable(["_rev", "string"])])
)
}

View File

@ -292,6 +292,11 @@ const addChildComponent = store => (componentToAdd, presetProps = {}) => {
? state.currentComponentInfo
: getParent(state.currentPreviewItem.props, state.currentComponentInfo)
// Don't continue if there's no parent
if (!targetParent) {
return state
}
targetParent._children = targetParent._children.concat(newComponent.props)
state.currentFrontEndType === "page"

View File

@ -1,11 +1,13 @@
<script>
export let data
export let currentPage
export let currentPage = 0
export let pageItemCount
export let ITEMS_PER_PAGE
let numPages = 0
$: numPages = Math.ceil((data?.length ?? 0) / ITEMS_PER_PAGE)
$: displayAllPages = numPages <= 10
$: pagesAroundCurrent = getPagesAroundCurrent(currentPage, numPages)
const next = () => {
if (currentPage + 1 === numPages) return
@ -20,18 +22,52 @@
const selectPage = page => {
currentPage = page
}
function getPagesAroundCurrent(current, max) {
const start = Math.max(current - 2, 1)
const end = Math.min(current + 2, max - 2)
let pages = []
for (let i = start; i <= end; i++) {
pages.push(i)
}
return pages
}
</script>
<div class="pagination">
<div class="pagination__buttons">
<button on:click={previous} disabled={currentPage === 0}>&lt;</button>
{#each Array(numPages) as _, idx}
<button
class:selected={idx === currentPage}
on:click={() => selectPage(idx)}>
{idx + 1}
{#if displayAllPages}
{#each Array(numPages) as _, idx}
<button
class:selected={idx === currentPage}
on:click={() => selectPage(idx)}>
{idx + 1}
</button>
{/each}
{:else}
<button class:selected={currentPage === 0} on:click={() => selectPage(0)}>
1
</button>
{/each}
{#if currentPage > 3}
<button disabled>...</button>
{/if}
{#each pagesAroundCurrent as idx}
<button
class:selected={idx === currentPage}
on:click={() => selectPage(idx)}>
{idx + 1}
</button>
{/each}
{#if currentPage < numPages - 4}
<button disabled>...</button>
{/if}
<button
class:selected={currentPage === numPages - 1}
on:click={() => selectPage(numPages - 1)}>
{numPages}
</button>
{/if}
<button
on:click={next}
disabled={currentPage === numPages - 1 || numPages === 0}>
@ -65,7 +101,8 @@
.pagination__buttons button {
display: inline-block;
padding: var(--spacing-s) var(--spacing-m);
padding: var(--spacing-s) 0;
text-align: center;
margin: 0;
background: #fff;
border: none;
@ -74,6 +111,9 @@
text-transform: capitalize;
min-width: 20px;
transition: 0.3s background-color;
font-family: var(--font-sans);
color: var(--grey-6);
width: 40px;
}
.pagination__buttons button:last-child {
border-right: none;
@ -83,11 +123,13 @@
background-color: var(--grey-1);
}
.pagination__buttons button.selected {
background: var(--grey-2);
background: var(--blue);
color: white;
}
p {
font-size: var(--font-size-s);
margin: var(--spacing-xl) 0;
color: var(--grey-6);
}
</style>

View File

@ -12,7 +12,6 @@
const dispatch = createEventDispatcher()
export let bindableProperties
console.log("Bindable Props: ", bindableProperties)
export let value = ""
export let close

View File

@ -1,15 +1,10 @@
<script>
import { goto } from "@sveltech/routify"
import { store } from "builderStore"
import { getComponentDefinition } from "builderStore/storeUtils"
import ConfirmDialog from "components/common/ConfirmDialog.svelte"
import { last, cloneDeep } from "lodash/fp"
import {
selectComponent,
getParent,
walkProps,
saveCurrentPreviewItem,
regenerateCssForCurrentScreen,
} from "builderStore/storeUtils"
import { getParent, saveCurrentPreviewItem } from "builderStore/storeUtils"
import { uuid } from "builderStore/uuid"
import { DropdownMenu } from "@budibase/bbui"
@ -29,6 +24,12 @@
dropdown.hide()
}
const selectComponent = component => {
store.selectComponent(component)
const path = store.getPathToComponent(component)
$goto(`./:page/:screen/${path}`)
}
const moveUpComponent = () => {
store.update(s => {
const parent = getParent(s.currentPreviewItem.props, component)
@ -78,10 +79,10 @@
if (parent) {
parent._children = parent._children.filter(c => c !== component)
selectComponent(parent)
}
saveCurrentPreviewItem(state)
return state
})
}

View File

@ -127,6 +127,9 @@
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
margin-left: -20px;
margin-right: -20px;
padding: 0 20px;
}
.instance-name {

View File

@ -49,7 +49,7 @@
{/each}
{:else}
<div class="no-design">
<span>This component does not have any design properties</span>
This component does not have any design properties.
</div>
{/if}
</div>
@ -78,9 +78,12 @@
flex: 1;
overflow-y: auto;
min-height: 0;
margin: 0 -20px;
padding: 0 20px;
}
.no-design {
text-align: center;
font-size: var(--font-size-s);
color: var(--grey-6);
}
</style>

View File

@ -1,13 +1,8 @@
<script>
import { fly } from "svelte/transition"
export let item
</script>
<div
data-cy={item.name}
class="item-item"
in:fly={{ y: 100, duration: 1000 }}
on:click>
<div data-cy={item.name} class="item-item" on:click>
<div class="item-icon">
<i class={item.icon} />
</div>

View File

@ -5,9 +5,22 @@
export let value
</script>
<Select thin secondary wide on:change {value}>
<option value="" />
{#each $backendUiStore.models as model}
<option value={model._id}>{model.name}</option>
{/each}
</Select>
<div>
<Select thin secondary wide on:change {value}>
<option value="">Choose a table</option>
{#each $backendUiStore.models as model}
<option value={model._id}>{model.name}</option>
{/each}
</Select>
</div>
<style>
div {
flex: 1 1 auto;
display: flex;
flex-direction: row;
}
div :global(> *) {
flex: 1 1 auto;
}
</style>

View File

@ -15,10 +15,12 @@
? models.find(m => m._id === componentInstance.datasource.modelId)
: null
$: type = componentInstance.datasource.type
$: if (model) {
options = componentInstance.datasource.isModel
? Object.keys(model.schema)
: Object.keys(model.views[componentInstance.datasource.name].schema)
options =
type === "model" || type === "link"
? Object.keys(model.schema)
: Object.keys(model.views[componentInstance.datasource.name].schema)
}
</script>

View File

@ -1,7 +1,8 @@
<script>
import { Button, Icon, DropdownMenu, Spacer, Heading } from "@budibase/bbui"
import { createEventDispatcher } from "svelte"
import { backendUiStore } from "builderStore"
import { store, backendUiStore } from "builderStore"
import fetchBindableProperties from "../../builderStore/fetchBindableProperties"
const dispatch = createEventDispatcher()
let anchorRight, dropdownRight
@ -13,28 +14,47 @@
dropdownRight.hide()
}
const models = $backendUiStore.models.map(m => ({
$: models = $backendUiStore.models.map(m => ({
label: m.name,
name: `all_${m._id}`,
modelId: m._id,
isModel: true,
type: "model",
}))
const views = $backendUiStore.models.reduce((acc, cur) => {
$: views = $backendUiStore.models.reduce((acc, cur) => {
let viewsArr = Object.entries(cur.views).map(([key, value]) => ({
label: key,
name: key,
...value,
type: "view",
}))
return [...acc, ...viewsArr]
}, [])
$: bindableProperties = fetchBindableProperties({
componentInstanceId: $store.currentComponentInfo._id,
components: $store.components,
screen: $store.currentPreviewItem,
models: $backendUiStore.models,
})
$: links = bindableProperties
.filter(x => x.fieldSchema.type === "link")
.map(property => ({
label: property.readableBinding,
fieldName: property.fieldSchema.name,
name: `all_${property.fieldSchema.modelId}`,
modelId: property.fieldSchema.modelId,
type: "link",
}))
</script>
<div class="dropdownbutton" bind:this={anchorRight}>
<Button secondary wide on:click={dropdownRight.show}>
<span>{value.label ? value.label : 'Model / View'}</span>
<Icon name="arrowdown" />
</Button>
<div
class="dropdownbutton"
bind:this={anchorRight}
on:click={dropdownRight.show}>
<span>{value.label ? value.label : 'Model / View'}</span>
<Icon name="arrowdown" />
</div>
<DropdownMenu bind:this={dropdownRight} anchor={anchorRight}>
<div class="dropdown">
@ -63,13 +83,51 @@
</li>
{/each}
</ul>
<hr />
<div class="title">
<Heading extraSmall>Relationships</Heading>
</div>
<ul>
{#each links as link}
<li
class:selected={value === link}
on:click={() => handleSelected(link)}>
{link.label}
</li>
{/each}
</ul>
</div>
</DropdownMenu>
<style>
.dropdownbutton {
width: 100%;
background-color: var(--grey-2);
border: var(--border-transparent);
padding: var(--spacing-m);
border-radius: var(--border-radius-m);
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
overflow: hidden;
flex: 1 1 auto;
}
.dropdownbutton:hover {
cursor: pointer;
background-color: var(--grey-3);
}
.dropdownbutton span {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
flex: 1 1 auto;
text-align: left;
font-size: var(--font-size-xs);
}
.dropdownbutton :global(svg) {
margin: -4px 0;
}
.dropdown {
padding: var(--spacing-m) 0;
z-index: 99999999;

View File

@ -1,4 +1,5 @@
<script>
import { goto } from "@sveltech/routify"
import { store, backendUiStore } from "builderStore"
import { Input, Button, Spacer, Select, ModalContent } from "@budibase/bbui"
import getTemplates from "builderStore/store/screenTemplates"
@ -71,14 +72,7 @@
})
}
finished()
}
const finished = () => {
templateIndex = 0
name = ""
route = ""
baseComponent = CONTAINER
$goto(`./:page/${name}`)
}
const routeNameExists = route => {

View File

@ -164,10 +164,10 @@
.bb-select-container {
outline: none;
width: 160px;
height: 36px;
cursor: pointer;
font-size: 14px;
overflow: hidden;
}
.bb-select-anchor {
@ -237,6 +237,7 @@
padding: 5px 0px;
cursor: pointer;
padding-left: 10px;
font-size: var(--font-size-s);
}
li:hover {

View File

@ -118,8 +118,7 @@
position: relative;
display: flex;
flex-flow: row;
min-width: 260px;
margin: 8px 0px;
margin: 8px 0;
align-items: center;
}
@ -128,7 +127,7 @@
align-items: center;
font-size: 12px;
font-weight: 400;
width: 100px;
flex: 0 0 100px;
text-align: left;
color: var(--ink);
margin-right: auto;
@ -139,7 +138,7 @@
flex: 1;
display: flex;
padding-left: 2px;
max-width: 164px;
overflow: hidden;
}
button {
position: absolute;

View File

@ -1,4 +1,5 @@
<script>
import { goto } from "@sveltech/routify"
import { store } from "builderStore"
import ConfirmDialog from "components/common/ConfirmDialog.svelte"
import api from "builderStore/api"
@ -16,19 +17,27 @@
}
const deleteScreen = () => {
store.update(s => {
const screens = s.screens.filter(c => c.name !== screen.name)
s.screens = screens
if (s.currentPreviewItem.name === screen.name) {
s.currentPreviewItem = s.pages[s.currentPageName]
s.currentFrontEndType = "page"
store.update(state => {
// Remove screen from screens
const screens = state.screens.filter(c => c.name !== screen.name)
state.screens = screens
// Remove screen from current page as well
const pageScreens = state.pages[state.currentPageName]._screens.filter(
scr => scr.name !== screen.name
)
state.pages[state.currentPageName]._screens = pageScreens
if (state.currentPreviewItem.name === screen.name) {
store.setCurrentPage($store.currentPageName)
$goto(`./:page/page-layout`)
}
api.delete(
`/_builder/api/pages/${s.currentPageName}/screens/${screen.name}`
`/_builder/api/pages/${state.currentPageName}/screens/${screen.name}`
)
return s
return state
})
}
</script>

View File

@ -67,9 +67,22 @@
}
</script>
<DataList editable secondary on:blur={handleBlur} on:change bind:value>
<option value="" />
{#each urls as url}
<option value={url.url}>{url.name}</option>
{/each}
</DataList>
<div>
<DataList editable secondary thin on:blur={handleBlur} on:change bind:value>
<option value="" />
{#each urls as url}
<option value={url.url}>{url.name}</option>
{/each}
</DataList>
</div>
<style>
div {
flex: 1 1 auto;
display: flex;
flex-direction: row;
}
div :global(> div) {
flex: 1 1 auto;
}
</style>

View File

@ -117,21 +117,21 @@
control={definition.control}
label={definition.label}
key={definition.key}
value={componentInstance[definition.key] || componentInstance[definition.key].defaultValue}
value={componentInstance[definition.key] || componentInstance[definition.key]?.defaultValue}
{componentInstance}
{onChange}
props={{ ...excludeProps(definition, ['control', 'label']) }} />
{/if}
{/each}
{:else}
<div>
<span>This component does not have any settings.</span>
</div>
<div>This component does not have any settings.</div>
{/if}
<style>
div {
text-align: center;
font-size: var(--font-size-s);
margin-top: var(--spacing-m);
color: var(--grey-6);
}
.duplicate-name {

View File

@ -305,7 +305,7 @@ export default {
design: { ...all },
settings: [
{
label: "Table",
label: "Data",
key: "datasource",
control: ModelViewSelect,
},
@ -587,7 +587,7 @@ export default {
design: { ...all },
settings: [
{
label: "Table",
label: "Data",
key: "datasource",
control: ModelViewSelect,
},
@ -659,7 +659,7 @@ export default {
properties: {
settings: [
{
label: "Table",
label: "Data",
key: "datasource",
control: ModelViewSelect,
},
@ -753,7 +753,7 @@ export default {
properties: {
settings: [
{
label: "Table",
label: "Data",
key: "datasource",
control: ModelViewSelect,
},
@ -867,7 +867,7 @@ export default {
properties: {
settings: [
{
label: "Table",
label: "Data",
key: "datasource",
control: ModelViewSelect,
},
@ -970,7 +970,7 @@ export default {
properties: {
settings: [
{
label: "Table",
label: "Data",
key: "datasource",
control: ModelViewSelect,
},

View File

@ -11,7 +11,7 @@ const entityMap = {
mustache.escape = text =>
String(text).replace(/[&<>"'`=/]/g, function fromEntityMap(s) {
return entityMap[s]
return entityMap[s] || s
})
export default mustache.render

View File

@ -17,8 +17,8 @@
export let _bb
export let datasource = {}
export let editable
export let theme = 'alpine'
export let height;
export let theme = "alpine"
export let height
export let pagination
let dataLoaded = false
@ -35,8 +35,9 @@
rowSelection: editable ? "multiple" : false,
suppressRowClickSelection: !editable,
paginationAutoPageSize: true,
pagination
pagination,
}
let store = _bb.store
onMount(async () => {
if (datasource.modelId) {
@ -44,7 +45,7 @@
model = await jsonModel.json()
const { schema } = model
if (!isEmpty(datasource)) {
data = await fetchData(datasource)
data = await fetchData(datasource, $store)
columnDefs = Object.keys(schema).map((key, i) => {
return {
headerCheckboxSelection: i === 0 && editable,
@ -68,8 +69,8 @@
type !== "boolean" &&
type !== "options" &&
// type !== "datetime" &&
type !== "link" &&
type !== "attachment"
type !== "link" &&
type !== "attachment"
const shouldHideField = name => {
if (name.startsWith("_")) return true

View File

@ -110,7 +110,7 @@ function linkedRecordRenderer(constraints, editable) {
container.style.placeItems = "center"
container.style.height = "100%"
container.innerText = params.value.length || 0
container.innerText = params.value ? params.value.length : 0
return container
}

View File

@ -20,6 +20,7 @@
let sort = {}
let sorted = []
let schema = {}
let store = _bb.store
$: cssVariables = {
backgroundColor,
@ -39,7 +40,7 @@
onMount(async () => {
if (!isEmpty(datasource)) {
data = await fetchData(datasource)
data = await fetchData(datasource, $store)
if (data && data.length) {
await fetchModel(data[0].modelId)
headers = Object.keys(schema).filter(shouldDisplayField)
@ -99,9 +100,9 @@
{#if schema[header].type === 'attachment'}
<AttachmentList files={row[header]} />
{:else if schema[header].type === 'link'}
<td>{row[header]} related row(s)</td>
{:else if row[header]}
<td>{row[header]}</td>
<td>{row[header] ? row[header].length : 0} related row(s)</td>
{:else}
<td>{row[header] == null ? '' : row[header]}</td>
{/if}
{/if}
{/each}

View File

@ -1,6 +1,5 @@
<script>
import { onMount } from "svelte"
import { Select, Label, Multiselect } from "@budibase/bbui"
import { Label, Multiselect } from "@budibase/bbui"
import api from "./api"
import { capitalise } from "./helpers"
@ -10,10 +9,11 @@
export let secondary
let linkedModel
let allRecords = []
$: label = capitalise(schema.name)
$: linkedModelId = schema.modelId
$: recordsPromise = fetchRecords(linkedModelId)
$: fetchRecords(linkedModelId)
$: fetchModel(linkedModelId)
async function fetchModel() {
@ -31,7 +31,7 @@
}
const FETCH_RECORDS_URL = `/api/${linkedModelId}/records`
const response = await api.get(FETCH_RECORDS_URL)
return await response.json()
allRecords = await response.json()
}
function getPrettyName(record) {
@ -50,16 +50,14 @@
table.
</Label>
{:else}
{#await recordsPromise then records}
<Multiselect
{secondary}
bind:value={linkedRecords}
label={showLabel ? label : null}
placeholder="Choose some options">
{#each records as record}
<option value={record._id}>{getPrettyName(record)}</option>
{/each}
</Multiselect>
{/await}
<Multiselect
{secondary}
bind:value={linkedRecords}
label={showLabel ? label : null}
placeholder="Choose some options">
{#each allRecords as record}
<option value={record._id}>{getPrettyName(record)}</option>
{/each}
</Multiselect>
{/if}
{/if}

View File

@ -7,10 +7,11 @@
export let datasource = []
let target
let store = _bb.store
onMount(async () => {
if (!isEmpty(datasource)) {
const data = await fetchData(datasource)
const data = await fetchData(datasource, $store)
_bb.attachChildren(target, {
hydrate: false,
context: data,

View File

@ -27,6 +27,10 @@
async function fetchData() {
const pathParts = window.location.pathname.split("/")
if (!model) {
return
}
let record
// if srcdoc, then we assume this is the builder preview
if (pathParts.length === 0 || pathParts[0] === "srcdoc") {
@ -48,7 +52,9 @@
const modelObj = await fetchModel(record.modelId)
for (let key of Object.keys(modelObj.schema)) {
if (modelObj.schema[key].type === "link") {
record[key] = Array.isArray(record[key]) ? record[key].length : 0
record[`${key}_count`] = Array.isArray(record[key])
? record[key].length
: 0
}
}

View File

@ -1,10 +1,17 @@
import api from "./api"
export default async function fetchData(datasource) {
const { isModel, name } = datasource
export default async function fetchData(datasource, store) {
const { type, name } = datasource
if (name) {
const records = isModel ? await fetchModelData() : await fetchViewData()
let records = []
if (type === "model") {
records = await fetchModelData()
} else if (type === "view") {
records = await fetchViewData()
} else if (type === "link") {
records = await fetchLinkedRecordsData()
}
// Fetch model schema so we can check for linked records
if (records && records.length) {
@ -13,7 +20,9 @@ export default async function fetchData(datasource) {
records.forEach(record => {
for (let key of keys) {
if (model.schema[key].type === "link") {
record[key] = Array.isArray(record[key]) ? record[key].length : 0
record[`${key}_count`] = Array.isArray(record[key])
? record[key].length
: 0
}
}
})
@ -53,4 +62,14 @@ export default async function fetchData(datasource) {
const response = await api.get(QUERY_VIEW_URL)
return await response.json()
}
async function fetchLinkedRecordsData() {
if (!store || !store.data || !store.data._id) {
return []
}
const QUERY_URL = `/api/${store.data.modelId}/${store.data._id}/enrich`
const response = await api.get(QUERY_URL)
const record = await response.json()
return record[datasource.fieldName]
}
}