Merge pull request #5272 from Budibase/cheeks-lab-day-devtools

DevTools
This commit is contained in:
Andrew Kingston 2022-04-14 12:57:01 +01:00 committed by GitHub
commit f6eef900ad
34 changed files with 896 additions and 150 deletions

View File

@ -16,6 +16,7 @@ exports.Headers = {
API_VER: "x-budibase-api-version",
APP_ID: "x-budibase-app-id",
TYPE: "x-budibase-type",
PREVIEW_ROLE: "x-budibase-role",
TENANT_ID: "x-budibase-tenant-id",
TOKEN: "x-budibase-token",
CSRF_TOKEN: "x-csrf-token",

View File

@ -36,6 +36,10 @@
padding-left: var(--spacing-l);
padding-right: var(--spacing-l);
}
.paddingX-XL {
padding-left: var(--spacing-xl);
padding-right: var(--spacing-xl);
}
.paddingY-S {
padding-top: var(--spacing-s);
padding-bottom: var(--spacing-s);
@ -48,6 +52,10 @@
padding-top: var(--spacing-l);
padding-bottom: var(--spacing-l);
}
.paddingY-XL {
padding-top: var(--spacing-xl);
padding-bottom: var(--spacing-xl);
}
.gap-XXS {
grid-gap: var(--spacing-xs);
}

View File

@ -1,42 +1,21 @@
<script>
import Icon from "../Icon/Icon.svelte"
import { copyToClipboard } from "../helpers"
import { notifications } from "../Stores/notifications"
export let value
const onClick = e => {
const onClick = async e => {
e.stopPropagation()
copyToClipboard(value)
}
const copyToClipboard = value => {
return new Promise(res => {
if (navigator.clipboard && window.isSecureContext) {
// Try using the clipboard API first
navigator.clipboard.writeText(value).then(res)
} else {
// Fall back to the textarea hack
let textArea = document.createElement("textarea")
textArea.value = value
textArea.style.position = "fixed"
textArea.style.left = "-9999px"
textArea.style.top = "-9999px"
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
document.execCommand("copy")
textArea.remove()
res()
}
})
.then(() => {
notifications.success("Copied to clipboard")
})
.catch(() => {
notifications.error(
"Failed to copy to clipboard. Check the dev console for the value."
)
console.warn("Failed to copy the value", value)
})
try {
await copyToClipboard(value)
notifications.success("Copied to clipboard")
} catch (error) {
notifications.error(
"Failed to copy to clipboard. Check the dev console for the value."
)
console.warn("Failed to copy the value", value)
}
}
</script>

View File

@ -108,7 +108,7 @@
padding-left: var(--spacing-xl);
padding-right: var(--spacing-xl);
position: relative;
border-bottom: var(--border-light);
border-bottom: 1px solid var(--spectrum-global-color-gray-300);
}
.spectrum-Tabs-content {
margin-top: var(--spectrum-global-dimension-static-size-150);

View File

@ -106,3 +106,29 @@ export const deepSet = (obj, key, value) => {
export const cloneDeep = obj => {
return JSON.parse(JSON.stringify(obj))
}
/**
* Copies a value to the clipboard
* @param value the value to copy
*/
export const copyToClipboard = value => {
return new Promise(res => {
if (navigator.clipboard && window.isSecureContext) {
// Try using the clipboard API first
navigator.clipboard.writeText(value).then(res)
} else {
// Fall back to the textarea hack
let textArea = document.createElement("textarea")
textArea.value = value
textArea.style.position = "fixed"
textArea.style.left = "-9999px"
textArea.style.top = "-9999px"
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
document.execCommand("copy")
textArea.remove()
res()
}
})
}

View File

@ -53,10 +53,10 @@
to-gfm-code-block "^0.1.1"
year "^0.2.1"
"@budibase/string-templates@^1.0.104":
version "1.0.104"
resolved "https://registry.yarnpkg.com/@budibase/string-templates/-/string-templates-1.0.104.tgz#f812700f2b21f638fd1e48dde065ae693fae2897"
integrity sha512-3caq3qwpIieyb9m8eSl8OhcE0ppzuyJ/0ubDlWmtpbmwmG2v3ynI+DwxpbG4CcVQFuebD2yxU0CZfioU76vKCQ==
"@budibase/string-templates@^1.0.105-alpha.4":
version "1.0.108"
resolved "https://registry.yarnpkg.com/@budibase/string-templates/-/string-templates-1.0.108.tgz#14949560148ef11b6b385952ed5787c12b890f2c"
integrity sha512-7Tts91Dzy+A7OdObTIaBNAdaixC7wmabnNTWYqk1d6TM6H5yv++bd/a9gVdUM7ptsuMy7uoP/ZoTZZRhp3ozfA==
dependencies:
"@budibase/handlebars-helpers" "^0.11.8"
dayjs "^1.10.4"

View File

@ -1,5 +1,5 @@
import { createAPIClient } from "@budibase/frontend-core"
import { notificationStore, authStore } from "../stores"
import { notificationStore, authStore, devToolsStore } from "../stores"
import { get } from "svelte/store"
export const API = createAPIClient({
@ -21,6 +21,12 @@ export const API = createAPIClient({
if (auth?.csrfToken) {
headers["x-csrf-token"] = auth.csrfToken
}
// Add role header
const role = get(devToolsStore).role
if (role) {
headers["x-budibase-role"] = role
}
},
// Show an error notification for all API failures.

View File

@ -14,6 +14,8 @@
routeStore,
builderStore,
themeStore,
appStore,
devToolsStore,
} from "stores"
import NotificationDisplay from "components/overlay/NotificationDisplay.svelte"
import ConfirmationDisplay from "components/overlay/ConfirmationDisplay.svelte"
@ -28,6 +30,8 @@
import CustomThemeWrapper from "./CustomThemeWrapper.svelte"
import DNDHandler from "components/preview/DNDHandler.svelte"
import KeyboardManager from "components/preview/KeyboardManager.svelte"
import DevToolsHeader from "components/devtools/DevToolsHeader.svelte"
import DevTools from "components/devtools/DevTools.svelte"
// Provide contexts
setContext("sdk", SDK)
@ -55,8 +59,22 @@
if ($authStore) {
// There is a logged in user, so handle them
if ($screenStore.screens.length) {
let firstRoute
// If using devtools, find the first screen matching our role
if ($devToolsStore.role) {
const roleRoutes = $screenStore.screens.filter(
screen => screen.routing?.roleId === $devToolsStore.role
)
firstRoute = roleRoutes[0]?.routing?.route || "/"
}
// Otherwise just use the first route
else {
firstRoute = $screenStore.screens[0]?.routing?.route ?? "/"
}
// Screens exist so navigate back to the home screen
const firstRoute = $screenStore.screens[0].routing?.route ?? "/"
routeStore.actions.navigate(firstRoute)
} else {
// No screens likely means the user has no permissions to view this app
@ -70,6 +88,8 @@
}
}
}
$: isDevPreview = $appStore.isDevApp && !$builderStore.inBuilder
</script>
{#if dataLoaded}
@ -109,39 +129,49 @@
>
<!-- Actual app -->
<div id="app-root">
<CustomThemeWrapper>
{#key `${$screenStore.activeLayout._id}-${$builderStore.previewType}`}
<Component
isLayout
instance={$screenStore.activeLayout.props}
/>
{/key}
{#if isDevPreview}
<DevToolsHeader />
{/if}
<!--
Flatpickr needs to be inside the theme wrapper.
It also needs its own container because otherwise it hijacks
key events on the whole page. It is painful to work with.
-->
<div id="flatpickr-root" />
<div id="app-body">
<CustomThemeWrapper>
{#key `${$screenStore.activeLayout._id}-${$builderStore.previewType}`}
<Component
isLayout
instance={$screenStore.activeLayout.props}
/>
{/key}
<!-- Modal container to ensure they sit on top -->
<div class="modal-container" />
<!--
Flatpickr needs to be inside the theme wrapper.
It also needs its own container because otherwise it hijacks
key events on the whole page. It is painful to work with.
-->
<div id="flatpickr-root" />
<!-- Layers on top of app -->
<NotificationDisplay />
<ConfirmationDisplay />
<PeekScreenDisplay />
</CustomThemeWrapper>
<!-- Modal container to ensure they sit on top -->
<div class="modal-container" />
<!-- Layers on top of app -->
<NotificationDisplay />
<ConfirmationDisplay />
<PeekScreenDisplay />
</CustomThemeWrapper>
{#if $appStore.isDevApp && !$builderStore.inBuilder}
<DevTools />
{/if}
</div>
</div>
<!-- Selection indicators should be bounded by device -->
<!--
We don't want to key these by componentID as they control their own
re-mounting to avoid flashes.
-->
{#if $builderStore.inBuilder}
<!-- Preview and dev tools utilities -->
{#if $appStore.isDevApp}
<SelectionIndicator />
{/if}
{#if $builderStore.inBuilder || $devToolsStore.allowSelection}
<HoverIndicator />
{/if}
{#if $builderStore.inBuilder}
<DNDHandler />
{/if}
</div>
@ -167,6 +197,7 @@
justify-content: center;
align-items: center;
}
#clip-root {
max-width: 100%;
max-height: 100%;
@ -176,10 +207,24 @@
overflow: hidden;
background-color: transparent;
}
#app-root {
overflow: hidden;
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: stretch;
}
#app-body {
flex: 1 1 auto;
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: stretch;
overflow: hidden;
}
.error {
@ -192,19 +237,23 @@
text-align: center;
padding: 20px;
}
.error :global(svg) {
fill: var(--spectrum-global-color-gray-500);
width: 80px;
height: 80px;
}
.error :global(h1),
.error :global(p) {
color: var(--spectrum-global-color-gray-800);
}
.error :global(p) {
font-style: italic;
margin-top: -0.5em;
}
.error :global(h1) {
font-weight: 400;
}
@ -214,14 +263,17 @@
#clip-root.preview {
padding: 2px;
}
#clip-root.tablet-preview {
width: calc(1024px + 6px);
height: calc(768px + 6px);
}
#clip-root.mobile-preview {
width: calc(390px + 6px);
height: calc(844px + 6px);
}
.preview #app-root {
border: 1px solid var(--spectrum-global-color-gray-300);
border-radius: 4px;

View File

@ -9,12 +9,16 @@
</script>
<script>
import { getContext, setContext } from "svelte"
import { getContext, setContext, onMount, onDestroy } from "svelte"
import { writable, get } from "svelte/store"
import * as AppComponents from "components/app"
import Router from "./Router.svelte"
import { enrichProps, propsAreSame } from "utils/componentProps"
import { builderStore } from "stores"
import {
enrichProps,
propsAreSame,
getSettingsDefinition,
} from "utils/componentProps"
import { builderStore, devToolsStore, componentStore, appStore } from "stores"
import { Helpers } from "@budibase/bbui"
import Manifest from "manifest.json"
import { getActiveConditions, reduceConditionActions } from "utils/conditions"
@ -30,8 +34,8 @@
const insideScreenslot = !!getContext("screenslot")
// Create component context
const componentStore = writable({})
setContext("component", componentStore)
const store = writable({})
setContext("component", store)
// Ref to the svelte component
let ref
@ -90,7 +94,7 @@
// leading to the selected component
$: selected =
$builderStore.inBuilder && $builderStore.selectedComponentId === id
$: inSelectedPath = $builderStore.selectedComponentPath?.includes(id)
$: inSelectedPath = $componentStore.selectedComponentPath?.includes(id)
$: inDragPath = inSelectedPath && $builderStore.editMode
// Derive definition properties which can all be optional, so need to be
@ -101,10 +105,12 @@
// Interactive components can be selected, dragged and highlighted inside
// the builder preview
$: interactive =
$: builderInteractive =
$builderStore.inBuilder &&
($builderStore.previewType === "layout" || insideScreenslot) &&
!isBlock
$: devToolsInteractive = $devToolsStore.allowSelection && !isBlock
$: interactive = builderInteractive || devToolsInteractive
$: editing = editable && selected && $builderStore.editMode
$: draggable =
!inDragPath &&
@ -133,7 +139,7 @@
$: applySettings(staticSettings, enrichedSettings, conditionalSettings)
// Update component context
$: componentStore.set({
$: store.set({
id,
children: children.length,
styles: {
@ -217,22 +223,6 @@
return type ? Manifest[type] : null
}
// Gets the definition of this component's settings from the manifest
const getSettingsDefinition = definition => {
if (!definition) {
return []
}
let settings = []
definition.settings?.forEach(setting => {
if (setting.section) {
settings = settings.concat(setting.settings || [])
} else {
settings.push(setting)
}
})
return settings
}
const getSettingsDefinitionMap = settingsDefinition => {
let map = {}
settingsDefinition?.forEach(setting => {
@ -385,6 +375,28 @@
})
}
}
onMount(() => {
if (
$appStore.isDevApp &&
!componentStore.actions.isComponentRegistered(id)
) {
componentStore.actions.registerInstance(id, {
getSettings: () => cachedSettings,
getRawSettings: () => ({ ...staticSettings, ...dynamicSettings }),
getDataContext: () => get(context),
})
}
})
onDestroy(() => {
if (
$appStore.isDevApp &&
componentStore.actions.isComponentRegistered(id)
) {
componentStore.actions.unregisterInstance(id)
}
})
</script>
{#if constructor && initialSettings && (visible || inSelectedPath)}
@ -419,12 +431,15 @@
.component {
display: contents;
}
.interactive :global(*:hover) {
cursor: pointer;
}
.draggable :global(*:hover) {
cursor: grab;
}
.editing :global(*:hover) {
cursor: auto;
}

View File

@ -179,6 +179,7 @@
justify-content: flex-start;
align-items: stretch;
height: 100%;
flex: 1 1 auto;
overflow: auto;
overflow-x: hidden;
position: relative;

View File

@ -5,7 +5,7 @@
export let step = 1
const { styleable, builderStore } = getContext("sdk")
const { styleable, builderStore, componentStore } = getContext("sdk")
const component = getContext("component")
const formContext = getContext("form")
@ -22,7 +22,7 @@
if (
formContext &&
$builderStore.inBuilder &&
$builderStore.selectedComponentPath?.includes($component.id)
$componentStore.selectedComponentPath?.includes($component.id)
) {
formContext.formApi.setStep(step)
}

View File

@ -1,6 +1,6 @@
<script>
import Provider from "./Provider.svelte"
import { authStore } from "stores"
import { authStore, devToolsStore } from "stores"
import { ActionTypes } from "constants"
import { Constants } from "@budibase/frontend-core"
@ -17,6 +17,10 @@
]
</script>
<Provider key="user" data={$authStore} {actions}>
<Provider
key="user"
data={{ ...$authStore, roleId: $devToolsStore.role || $authStore?.roleId }}
{actions}
>
<slot />
</Provider>

View File

@ -0,0 +1,69 @@
<script>
import { getContext } from "svelte"
import { Layout, Heading, Tabs, Tab, Icon } from "@budibase/bbui"
import DevToolsStatsTab from "./DevToolsStatsTab.svelte"
import DevToolsComponentTab from "./DevToolsComponentTab.svelte"
import { devToolsStore } from "stores"
const context = getContext("context")
</script>
<div
class="devtools"
class:hidden={!$devToolsStore.visible}
class:mobile={$context.device.mobile}
>
{#if $devToolsStore.visible}
<Layout noPadding gap="XS">
<div class="header">
<Heading size="XS">Budibase DevTools</Heading>
<Icon
hoverable
name="Close"
on:click={() => devToolsStore.actions.setVisible(false)}
/>
</div>
<Tabs selected="Application">
<Tab title="Application">
<div class="tab-content">
<DevToolsStatsTab />
</div>
</Tab>
<Tab title="Components">
<div class="tab-content">
<DevToolsComponentTab />
</div>
</Tab>
</Tabs>
</Layout>
{/if}
</div>
<style>
.devtools {
background: var(--spectrum-alias-background-color-primary);
flex: 0 0 320px;
border-left: 1px solid var(--spectrum-global-color-gray-300);
overflow: auto;
transition: margin-right 300ms ease;
margin-right: 0;
}
.devtools.hidden {
margin-right: -320px;
}
.devtools.mobile {
display: none;
}
.header {
padding: var(--spacing-xl) var(--spacing-xl) 0 var(--spacing-xl);
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
}
.tab-content {
padding: 0 var(--spacing-xl);
}
</style>

View File

@ -0,0 +1,113 @@
<script>
import { Layout, Select, Body } from "@budibase/bbui"
import { componentStore } from "stores/index.js"
import DevToolsStat from "./DevToolsStat.svelte"
const ReadableBindingMap = {
user: "Current user",
state: "State",
url: "URL",
device: "Device",
rowSelection: "Selected rows",
}
let category
$: selectedInstance = $componentStore.selectedComponentInstance
$: context = selectedInstance?.getDataContext()
$: bindingCategories = getContextProviders(context)
$: bindings = Object.entries(context?.[category] || {})
const getContextProviders = context => {
const filteredContext = { ...context }
// Remove some keys from context
delete filteredContext.key
delete filteredContext.closestComponentId
delete filteredContext.user_RefreshDataSource
// Keep track of encountered IDs so we can find actions
let actions = []
let encounteredCategories = []
// Create readable bindings
let categories = []
Object.keys(filteredContext)
.sort()
.forEach(category => {
let isAction = false
for (let cat of encounteredCategories) {
if (category.startsWith(`${cat}_`)) {
isAction = true
break
}
}
if (isAction) {
actions.push(category)
return
}
// Mark category as encountered so we can find any matching actions
encounteredCategories.push(category)
// Map any static categories to pretty names
if (ReadableBindingMap[category]) {
categories.push({
label: ReadableBindingMap[category],
value: category,
})
} else {
const component = componentStore.actions.getComponentById(category)
if (component) {
categories.push({
label: component._instanceName,
value: category,
})
} else {
// Check if its a block
if (category.includes("-")) {
const split = category.split("-")
const potentialId = split[0]
const component =
componentStore.actions.getComponentById(potentialId)
if (component) {
categories.push({
label: `${component._instanceName} (${split[1]})`,
value: category,
})
return
}
}
// Otherwise we don't know
categories.push({
label: "Unknown - " + category,
value: category,
})
}
}
})
return categories
}
</script>
<Layout noPadding gap="S">
<Body size="S">
Choose a category to see the value of all its available bindings.
</Body>
<Select bind:value={category} label="Category" options={bindingCategories} />
{#if bindings?.length}
<Layout noPadding gap="XS">
{#each bindings as binding}
<DevToolsStat
copyable
label={binding[0]}
value={JSON.stringify(binding[1])}
/>
{/each}
</Layout>
{:else if category}
<Body size="XS">There aren't any bindings available in this category.</Body>
{/if}
</Layout>

View File

@ -0,0 +1,13 @@
<script>
import DevToolsStat from "./DevToolsStat.svelte"
export let name
export let value
export let settingsMap
$: prettyName = settingsMap?.[name]?.label
</script>
{#if prettyName}
<DevToolsStat label={prettyName} value={JSON.stringify(value)} />
{/if}

View File

@ -0,0 +1,30 @@
<script>
import { Layout, Toggle } from "@budibase/bbui"
import DevToolsStat from "./DevToolsStat.svelte"
import { componentStore } from "stores/index.js"
import { getSettingsDefinition } from "utils/componentProps.js"
let showEnrichedSettings = true
$: selectedInstance = $componentStore.selectedComponentInstance
$: settingsDefinition = getSettingsDefinition(
$componentStore.selectedComponentDefinition
)
$: rawSettings = selectedInstance?.getRawSettings()
$: settings = selectedInstance?.getSettings()
</script>
<Layout noPadding gap="S">
<Toggle text="Show enriched settings" bind:value={showEnrichedSettings} />
<Layout noPadding gap="XS">
{#each settingsDefinition as setting}
<DevToolsStat
copyable
label={setting.label}
value={JSON.stringify(
(showEnrichedSettings ? settings : rawSettings)?.[setting.key]
)}
/>
{/each}
</Layout>
</Layout>

View File

@ -0,0 +1,102 @@
<script>
import { Body, Layout, Heading, Button, Tabs, Tab } from "@budibase/bbui"
import { builderStore, devToolsStore, componentStore } from "stores"
import DevToolsStat from "./DevToolsStat.svelte"
import DevToolsComponentSettingsTab from "./DevToolsComponentSettingsTab.svelte"
import DevToolsComponentContextTab from "./DevToolsComponentContextTab.svelte"
$: {
// Reset selection store if we can't find a matching instance
if (!$componentStore.selectedComponentInstance) {
builderStore.actions.selectComponent(null)
}
}
</script>
{#if !$builderStore.selectedComponentId}
<Layout noPadding gap="S">
<Heading size="XS">Please choose a component</Heading>
<Body size="S">
Press the button below to enable component selection, then click a
component in your app to view its settings and available data bindings.
</Body>
<div>
<Button
cta
on:click={() => devToolsStore.actions.setAllowSelection(true)}
>
Choose component
</Button>
</div>
</Layout>
{:else}
<Layout noPadding gap="S">
<Heading size="XS">
{$componentStore.selectedComponent?._instanceName}
</Heading>
<Layout noPadding gap="XS">
<DevToolsStat
label="Type"
value={$componentStore.selectedComponentDefinition?.name}
/>
<DevToolsStat
copyable
label="Component ID"
value={$componentStore.selectedComponent?._id}
/>
</Layout>
<div class="buttons">
<Button
cta
on:click={() => devToolsStore.actions.setAllowSelection(true)}
>
Change component
</Button>
<Button
quiet
secondary
on:click={() => builderStore.actions.selectComponent(null)}
>
Reset
</Button>
</div>
<div class="data">
<Layout noPadding gap="XS">
<Tabs selected="Settings">
<Tab title="Settings">
<div class="tab-content">
<DevToolsComponentSettingsTab />
</div>
</Tab>
<Tab title="Bindings">
<div class="tab-content">
<DevToolsComponentContextTab />
</div>
</Tab>
</Tabs>
</Layout>
</div>
</Layout>
{/if}
<style>
.buttons {
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
gap: var(--spacing-xs);
}
.data {
margin: 0 calc(-1 * var(--spacing-xl));
}
.data :global(.spectrum-Textfield-input) {
min-height: 200px !important;
white-space: pre;
font-size: var(--font-size-s);
}
.tab-content {
padding: 0 var(--spacing-xl);
}
</style>

View File

@ -0,0 +1,74 @@
<script>
import { Heading, Button, Select } from "@budibase/bbui"
import { devToolsStore } from "../../stores"
import { getContext } from "svelte"
const context = getContext("context")
$: previewOptions = [
{
label: "View as yourself",
value: "self",
},
{
label: "View as public user",
value: "PUBLIC",
},
{
label: "View as basic user",
value: "BASIC",
},
{
label: "View as power user",
value: "POWER",
},
{
label: "View as admin user",
value: "ADMIN",
},
]
</script>
<div class="dev-preview-header" class:mobile={$context.device.mobile}>
<Heading size="XS">Budibase App Preview</Heading>
<Select
quiet
options={previewOptions}
value={$devToolsStore.role || "self"}
placeholder={null}
autoWidth
on:change={e => devToolsStore.actions.changeRole(e.detail)}
/>
{#if !$context.device.mobile}
<Button
quiet
overBackground
icon="Code"
on:click={() => devToolsStore.actions.setVisible(!$devToolsStore.visible)}
>
{$devToolsStore.visible ? "Close" : "Open"} DevTools
</Button>
{/if}
</div>
<style>
.dev-preview-header {
flex: 0 0 50px;
height: 50px;
display: grid;
align-items: center;
background-color: var(--spectrum-global-color-blue-400);
padding: 0 var(--spacing-xl);
grid-template-columns: 1fr auto auto;
grid-gap: var(--spacing-xl);
}
.dev-preview-header.mobile {
flex: 0 0 50px;
grid-template-columns: 1fr auto;
}
.dev-preview-header :global(.spectrum-Heading),
.dev-preview-header :global(.spectrum-Picker-menuIcon),
.dev-preview-header :global(.spectrum-Picker-label) {
color: white !important;
}
</style>

View File

@ -0,0 +1,75 @@
<script>
import { Helpers } from "@budibase/bbui"
import { notificationStore } from "stores"
export let label
export let value
export let copyable = false
$: prettyLabel = label == null ? "-" : label
$: prettyValue = value == null ? "-" : value
$: empty = value == null
$: canCopy = copyable && !empty
const copyValue = async () => {
try {
await Helpers.copyToClipboard(value)
notificationStore.actions.success("Copied to clipboard")
} catch (error) {
notificationStore.actions.error(
"Failed to copy to clipboard. Check the dev console for the value."
)
console.warn("Failed to copy the value", value)
}
}
</script>
<div class="stat">
<div class="stat-label" title={prettyLabel}>{prettyLabel}</div>
<div
class="stat-value"
class:copyable={canCopy}
class:empty
title={prettyValue}
on:click={canCopy ? copyValue : null}
>
{prettyValue}
</div>
</div>
<style>
.stat {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
gap: var(--spacing-xl);
}
.stat-label {
font-size: var(--font-size-xs);
color: var(--spectrum-global-color-gray-600);
text-transform: uppercase;
flex: 0 0 auto;
width: 120px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.stat-value {
flex: 1 1 auto;
width: 0;
text-align: right;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
transition: color var(--spectrum-global-animation-duration-100, 130ms)
ease-in-out;
}
.stat-value.empty {
color: var(--spectrum-global-color-gray-500);
}
.stat-value.copyable:hover {
color: var(--spectrum-global-color-blue-600);
cursor: pointer;
}
</style>

View File

@ -0,0 +1,27 @@
<script>
import { Layout } from "@budibase/bbui"
import { authStore, appStore, screenStore, componentStore } from "stores"
import DevToolsStat from "./DevToolsStat.svelte"
</script>
<Layout noPadding gap="XS">
<DevToolsStat label="App" value={$appStore.application?.name} />
<DevToolsStat label="Tenant" value={$appStore.application?.tenantId} />
<DevToolsStat label="Version" value={$appStore.application?.version} />
{#if $appStore.clientLoadTime}
<DevToolsStat
label="Client load time"
value={`${$appStore.clientLoadTime} ms`}
/>
{/if}
<DevToolsStat label="App layouts" value={$screenStore.layouts?.length || 0} />
<DevToolsStat label="Active layout" value={$screenStore.activeLayout?.name} />
<DevToolsStat label="App screens" value={$screenStore.screens?.length || 0} />
<DevToolsStat
label="Active screen"
value={$screenStore.activeScreen?.routing.route}
/>
<DevToolsStat label="Components" value={$componentStore.mountedComponents} />
<DevToolsStat label="User" value={$authStore.email} />
<DevToolsStat label="Role" value={$authStore.roleId} />
</Layout>

View File

@ -2,6 +2,7 @@
import { onMount, onDestroy } from "svelte"
import Indicator from "./Indicator.svelte"
import { domDebounce } from "utils/domDebounce"
import { builderStore } from "stores"
export let componentId
export let color
@ -13,6 +14,7 @@
let interval
let text
$: visibleIndicators = indicators.filter(x => x.visible)
$: offset = $builderStore.inBuilder ? 0 : 2
let updating = false
let observers = []
@ -88,8 +90,8 @@
const elBounds = child.getBoundingClientRect()
nextIndicators.push({
top: elBounds.top + scrollY - deviceBounds.top,
left: elBounds.left + scrollX - deviceBounds.left,
top: elBounds.top + scrollY - deviceBounds.top - offset,
left: elBounds.left + scrollX - deviceBounds.left - offset,
width: elBounds.width + 4,
height: elBounds.height + 4,
visible: false,

View File

@ -3,7 +3,7 @@
import SettingsButton from "./SettingsButton.svelte"
import SettingsColorPicker from "./SettingsColorPicker.svelte"
import SettingsPicker from "./SettingsPicker.svelte"
import { builderStore } from "stores"
import { builderStore, componentStore } from "stores"
import { domDebounce } from "utils/domDebounce"
const verticalOffset = 28
@ -15,7 +15,7 @@
let self
let measured = false
$: definition = $builderStore.selectedComponentDefinition
$: definition = $componentStore.selectedComponentDefinition
$: showBar = definition?.showSettingsBar && !$builderStore.isDragging
$: settings = getBarSettings(definition)
@ -163,9 +163,7 @@
<SettingsButton
icon="Delete"
on:click={() => {
builderStore.actions.deleteComponent(
$builderStore.selectedComponent._id
)
builderStore.actions.deleteComponent($builderStore.selectedComponentId)
}}
title="Delete component"
/>

View File

@ -1,6 +1,6 @@
<script>
import { Icon } from "@budibase/bbui"
import { builderStore } from "stores"
import { builderStore, componentStore } from "stores"
import { createEventDispatcher } from "svelte"
export let prop
@ -11,7 +11,7 @@
export let bool = false
const dispatch = createEventDispatcher()
$: currentValue = $builderStore.selectedComponent?.[prop]
$: currentValue = $componentStore.selectedComponent?.[prop]
$: active = prop && (bool ? !!currentValue : currentValue === value)
</script>

View File

@ -1,10 +1,10 @@
<script>
import { ColorPicker } from "@budibase/bbui"
import { builderStore } from "stores"
import { builderStore, componentStore } from "stores"
export let prop
$: currentValue = $builderStore.selectedComponent?.[prop]
$: currentValue = $componentStore.selectedComponent?.[prop]
</script>
<div>

View File

@ -1,12 +1,12 @@
<script>
import { Select } from "@budibase/bbui"
import { builderStore } from "stores"
import { builderStore, componentStore } from "stores"
export let prop
export let options
export let label
$: currentValue = $builderStore.selectedComponent?.[prop]
$: currentValue = $componentStore.selectedComponent?.[prop]
</script>
<div>

View File

@ -1,8 +1,14 @@
import { API } from "api"
import { get, writable } from "svelte/store"
const initialState = {
appId: null,
isDevApp: false,
clientLoadTime: window.INIT_TIME ? Date.now() - window.INIT_TIME : null,
}
const createAppStore = () => {
const store = writable(null)
const store = writable(initialState)
// Fetches the app definition including screens, layouts and theme
const fetchAppDefinition = async () => {
@ -13,11 +19,13 @@ const createAppStore = () => {
try {
const appDefinition = await API.fetchAppPackage(appId)
store.set({
...initialState,
...appDefinition,
appId: appDefinition?.application?.appId,
isDevApp: appId.startsWith("app_dev"),
})
} catch (error) {
store.set(null)
store.set(initialState)
}
}

View File

@ -1,7 +1,6 @@
import { writable, derived, get } from "svelte/store"
import Manifest from "manifest.json"
import { findComponentById, findComponentPathById } from "../utils/components"
import { writable, get } from "svelte/store"
import { API } from "api"
import { devToolsStore } from "./devTools.js"
const dispatchEvent = (type, data = {}) => {
window.parent.postMessage({ type, data })
@ -22,38 +21,18 @@ const createBuilderStore = () => {
previewDevice: "desktop",
isDragging: false,
}
const writableStore = writable(initialState)
const derivedStore = derived(writableStore, $state => {
// Avoid any of this logic if we aren't in the builder preview
if (!$state.inBuilder) {
return $state
}
// Derive the selected component instance and definition
const { layout, screen, previewType, selectedComponentId } = $state
const asset = previewType === "layout" ? layout : screen
const component = findComponentById(asset?.props, selectedComponentId)
const prefix = "@budibase/standard-components/"
const type = component?._component?.replace(prefix, "")
const definition = type ? Manifest[type] : null
// Derive the selected component path
const path = findComponentPathById(asset.props, selectedComponentId) || []
return {
...$state,
selectedComponent: component,
selectedComponentDefinition: definition,
selectedComponentPath: path?.map(component => component._id),
}
})
const store = writable(initialState)
const actions = {
selectComponent: id => {
if (id === get(writableStore).selectedComponentId) {
if (id === get(store).selectedComponentId) {
return
}
writableStore.update(state => ({ ...state, editMode: false }))
store.update(state => ({
...state,
editMode: false,
selectedComponentId: id,
}))
devToolsStore.actions.setAllowSelection(false)
dispatchEvent("select-component", { id })
},
updateProp: (prop, value) => {
@ -76,7 +55,7 @@ const createBuilderStore = () => {
}
},
setSelectedPath: path => {
writableStore.update(state => ({ ...state, selectedPath: path }))
store.update(state => ({ ...state, selectedPath: path }))
},
moveComponent: (componentId, destinationComponentId, mode) => {
dispatchEvent("move-component", {
@ -86,22 +65,21 @@ const createBuilderStore = () => {
})
},
setDragging: dragging => {
if (dragging === get(writableStore).isDragging) {
if (dragging === get(store).isDragging) {
return
}
writableStore.update(state => ({ ...state, isDragging: dragging }))
store.update(state => ({ ...state, isDragging: dragging }))
},
setEditMode: enabled => {
if (enabled === get(writableStore).editMode) {
if (enabled === get(store).editMode) {
return
}
writableStore.update(state => ({ ...state, editMode: enabled }))
store.update(state => ({ ...state, editMode: enabled }))
},
}
return {
...writableStore,
set: state => writableStore.set({ ...initialState, ...state }),
subscribe: derivedStore.subscribe,
...store,
set: state => store.set({ ...initialState, ...state }),
actions,
}
}

View File

@ -0,0 +1,81 @@
import { get, writable, derived } from "svelte/store"
import Manifest from "manifest.json"
import { findComponentById, findComponentPathById } from "../utils/components"
import { devToolsStore } from "./devTools"
import { screenStore } from "./screens"
import { builderStore } from "./builder"
const createComponentStore = () => {
const store = writable({})
const derivedStore = derived(
[store, builderStore, devToolsStore, screenStore],
([$store, $builderState, $devToolsState, $screenState]) => {
// Avoid any of this logic if we aren't in the builder preview
if (!$builderState.inBuilder && !$devToolsState.visible) {
return {}
}
// Derive the selected component instance and definition
let asset
const { layout, screen, previewType, selectedComponentId } = $builderState
if ($builderState.inBuilder) {
asset = previewType === "layout" ? layout : screen
} else {
asset = $screenState.activeScreen
}
const component = findComponentById(asset?.props, selectedComponentId)
const prefix = "@budibase/standard-components/"
const type = component?._component?.replace(prefix, "")
const definition = type ? Manifest[type] : null
// Derive the selected component path
const path =
findComponentPathById(asset?.props, selectedComponentId) || []
return {
selectedComponentInstance: $store[selectedComponentId],
selectedComponent: component,
selectedComponentDefinition: definition,
selectedComponentPath: path?.map(component => component._id),
mountedComponents: Object.keys($store).length,
currentAsset: asset,
}
}
)
const registerInstance = (id, instance) => {
store.update(state => ({
...state,
[id]: instance,
}))
}
const unregisterInstance = id => {
store.update(state => {
delete state[id]
return state
})
}
const isComponentRegistered = id => {
return get(store)[id] != null
}
const getComponentById = id => {
const asset = get(derivedStore).currentAsset
return findComponentById(asset?.props, id)
}
return {
...derivedStore,
actions: {
registerInstance,
unregisterInstance,
isComponentRegistered,
getComponentById,
},
}
}
export const componentStore = createComponentStore()

View File

@ -0,0 +1,47 @@
import { get } from "svelte/store"
import { createLocalStorageStore } from "@budibase/frontend-core"
import { appStore } from "./app"
import { initialise } from "./initialise"
import { authStore } from "./auth"
const initialState = {
visible: false,
allowSelection: false,
role: null,
}
const createDevToolStore = () => {
const localStorageKey = `${get(appStore).appId}.devTools`
const store = createLocalStorageStore(localStorageKey, initialState)
const setVisible = visible => {
store.update(state => ({
...state,
visible: visible,
}))
}
const setAllowSelection = allowSelection => {
store.update(state => ({
...state,
allowSelection,
}))
}
const changeRole = async role => {
store.update(state => ({
...state,
role: role === "self" ? null : role,
}))
// location.reload()
await authStore.actions.fetchUser()
await initialise()
}
return {
subscribe: store.subscribe,
actions: { setVisible, setAllowSelection, changeRole },
}
}
export const devToolsStore = createDevToolStore()

View File

@ -9,6 +9,8 @@ export { confirmationStore } from "./confirmation"
export { peekStore } from "./peek"
export { stateStore } from "./state"
export { themeStore } from "./theme"
export { devToolsStore } from "./devTools"
export { componentStore } from "./components"
export { uploadStore } from "./uploads.js"
export { rowSelectionStore } from "./rowSelection.js"
// Context stores are layered and duplicated, so it is not a singleton

View File

@ -66,7 +66,6 @@ const createScreenStore = () => {
}
let children = []
findChildrenByType(component, type, children)
console.log(children)
return children
},
}

View File

@ -107,3 +107,21 @@ export const propsUseBinding = (props, bindingKey) => {
}
return false
}
/**
* Gets the definition of this component's settings from the manifest
*/
export const getSettingsDefinition = definition => {
if (!definition) {
return []
}
let settings = []
definition.settings?.forEach(setting => {
if (setting.section) {
settings = settings.concat(setting.settings || [])
} else {
settings.push(setting)
}
})
return settings
}

View File

@ -78,6 +78,9 @@
app.
</h2>
</div>
<script type="application/javascript">
window.INIT_TIME = Date.now()
</script>
<script type="application/javascript" src={clientLibPath}>
</script>
<script type="application/javascript">

View File

@ -4,7 +4,7 @@ const {
getCookie,
clearCookie,
} = require("@budibase/backend-core/utils")
const { Cookies } = require("@budibase/backend-core/constants")
const { Cookies, Headers } = require("@budibase/backend-core/constants")
const { getRole } = require("@budibase/backend-core/roles")
const { BUILTIN_ROLE_IDS } = require("@budibase/backend-core/roles")
const { generateUserMetadataID, isDevAppID } = require("../db/utils")
@ -63,6 +63,21 @@ module.exports = async (ctx, next) => {
appId = requestAppId
// retrieving global user gets the right role
roleId = globalUser.roleId || roleId
// Allow builders to specify their role via a header
const isBuilder =
globalUser && globalUser.builder && globalUser.builder.global
const isDevApp = appId && isDevAppID(appId)
const roleHeader = ctx.request && ctx.request.headers[Headers.PREVIEW_ROLE]
if (isBuilder && isDevApp && roleHeader) {
// Ensure the role is valid by ensuring a definition exists
try {
await getRole(roleHeader)
roleId = roleHeader
} catch (error) {
// Swallow error and do nothing
}
}
}
// nothing more to do