Merge pull request #15623 from Budibase/feat/pc-ts-conversions

Typescript conversion for some BBUI components
This commit is contained in:
Peter Clement 2025-03-03 11:34:39 +00:00 committed by GitHub
commit 355fbd1b8c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
29 changed files with 263 additions and 259 deletions

View File

@ -1,6 +1,6 @@
<script>
export let small = false
export let disabled
<script lang="ts">
export let small: boolean = false
export let disabled: boolean = false
</script>
<button

View File

@ -1,24 +1,24 @@
<script>
<script lang="ts">
import Field from "./Field.svelte"
import Checkbox from "./Core/Checkbox.svelte"
import { createEventDispatcher } from "svelte"
export let value = null
export let label = null
export let labelPosition = "above"
export let text = null
export let disabled = false
export let error = null
export let size = "M"
export let helpText = null
export let value: boolean | undefined = undefined
export let label: string | undefined = undefined
export let labelPosition: "above" | "below" = "above"
export let text: string | undefined = undefined
export let disabled: boolean = false
export let error: string | undefined = undefined
export let size: "S" | "M" | "L" | "XL" = "M"
export let helpText: string | undefined = undefined
const dispatch = createEventDispatcher()
const onChange = e => {
const onChange = (e: CustomEvent<boolean>) => {
value = e.detail
dispatch("change", e.detail)
}
</script>
<Field {helpText} {label} {labelPosition} {error}>
<Checkbox {error} {disabled} {text} {value} {size} on:change={onChange} />
<Checkbox {disabled} {text} {value} {size} on:change={onChange} />
</Field>

View File

@ -10,7 +10,7 @@
export let secondary: boolean = false
export let overBackground: boolean = false
export let target: string | undefined = undefined
export let download: boolean | undefined = undefined
export let download: string | undefined = undefined
export let disabled: boolean = false
export let tooltip: string | null = null

View File

@ -1,63 +0,0 @@
<script>
import { getContext } from "svelte"
const multilevel = getContext("sidenav-type")
import Badge from "../Badge/Badge.svelte"
export let href = ""
export let external = false
export let heading = ""
export let icon = ""
export let selected = false
export let disabled = false
export let badge = ""
</script>
<!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<li
class="spectrum-SideNav-item"
class:is-selected={selected}
class:is-disabled={disabled}
on:click
>
{#if heading}
<h2 class="spectrum-SideNav-heading" id="nav-heading-{heading}">
{heading}
</h2>
{/if}
<a
target={external ? "_blank" : ""}
{href}
class="spectrum-SideNav-itemLink"
aria-current="page"
>
{#if icon}
<svg
class="spectrum-Icon spectrum-Icon--sizeM spectrum-SideNav-itemIcon"
focusable="false"
aria-hidden="true"
>
<use xlink:href="#spectrum-icon-18-{icon}" />
</svg>
{/if}
<slot />
{#if badge}
<div class="badge">
<Badge active size="S">{badge}</Badge>
</div>
{/if}
</a>
{#if multilevel && $$slots.subnav}
<ul class="spectrum-SideNav">
<slot name="subnav" />
</ul>
{/if}
</li>
<style>
.badge {
margin-left: 10px;
}
</style>

View File

@ -1,13 +0,0 @@
<script>
import { setContext } from "svelte"
import "@spectrum-css/sidenav/dist/index-vars.css"
export let multilevel = false
setContext("sidenav-type", multilevel)
</script>
<nav>
<ul class="spectrum-SideNav" class:spectrum-SideNav--multiLevel={multilevel}>
<slot />
</ul>
</nav>

View File

@ -7,17 +7,26 @@ export const BANNER_TYPES = {
WARNING: "warning",
}
interface BannerConfig {
message?: string
type?: string
extraButtonText?: string
extraButtonAction?: () => void
onChange?: () => void
}
interface DefaultConfig {
messages: BannerConfig[]
}
export function createBannerStore() {
const DEFAULT_CONFIG = {
const DEFAULT_CONFIG: DefaultConfig = {
messages: [],
}
const banner = writable(DEFAULT_CONFIG)
const banner = writable<DefaultConfig>(DEFAULT_CONFIG)
const show = async (
// eslint-disable-next-line
config = { message, type, extraButtonText, extraButtonAction, onChange }
) => {
const show = async (config: BannerConfig = {}) => {
banner.update(store => {
return {
...store,
@ -27,7 +36,7 @@ export function createBannerStore() {
}
const showStatus = async () => {
const config = {
const config: BannerConfig = {
message: "Some systems are experiencing issues",
type: BANNER_TYPES.NEGATIVE,
extraButtonText: "View Status",
@ -37,18 +46,24 @@ export function createBannerStore() {
await queue([config])
}
const queue = async entries => {
const priority = {
const queue = async (entries: Array<BannerConfig>) => {
const priority: Record<string, number> = {
[BANNER_TYPES.NEGATIVE]: 0,
[BANNER_TYPES.WARNING]: 1,
[BANNER_TYPES.INFO]: 2,
}
banner.update(store => {
const sorted = [...store.messages, ...entries].sort((a, b) => {
if (priority[a.type] == priority[b.type]) {
if (
priority[a.type as keyof typeof priority] ===
priority[b.type as keyof typeof priority]
) {
return 0
}
return priority[a.type] < priority[b.type] ? -1 : 1
return priority[a.type as keyof typeof priority] <
priority[b.type as keyof typeof priority]
? -1
: 1
})
return {
...store,

View File

@ -2,9 +2,21 @@ import { writable } from "svelte/store"
const NOTIFICATION_TIMEOUT = 3000
interface Notification {
id: string
type: string
message: string
icon: string
dismissable: boolean
action: (() => void) | null
actionMessage: string | null
wide: boolean
dismissTimeout: number
}
export const createNotificationStore = () => {
const timeoutIds = new Set()
const _notifications = writable([], () => {
const timeoutIds = new Set<ReturnType<typeof setTimeout>>()
const _notifications = writable<Notification[]>([], () => {
return () => {
// clear all the timers
timeoutIds.forEach(timeoutId => {
@ -21,7 +33,7 @@ export const createNotificationStore = () => {
}
const send = (
message,
message: string,
{
type = "default",
icon = "",
@ -30,7 +42,15 @@ export const createNotificationStore = () => {
actionMessage = null,
wide = false,
dismissTimeout = NOTIFICATION_TIMEOUT,
}
}: {
type?: string
icon?: string
autoDismiss?: boolean
action?: (() => void) | null
actionMessage?: string | null
wide?: boolean
dismissTimeout?: number
} = {}
) => {
if (block) {
return
@ -60,7 +80,7 @@ export const createNotificationStore = () => {
}
}
const dismissNotification = id => {
const dismissNotification = (id: string) => {
_notifications.update(state => {
return state.filter(n => n.id !== id)
})
@ -71,17 +91,18 @@ export const createNotificationStore = () => {
return {
subscribe,
send,
info: msg => send(msg, { type: "info", icon: "Info" }),
error: msg =>
info: (msg: string) => send(msg, { type: "info", icon: "Info" }),
error: (msg: string) =>
send(msg, { type: "error", icon: "Alert", autoDismiss: false }),
warning: msg => send(msg, { type: "warning", icon: "Alert" }),
success: msg => send(msg, { type: "success", icon: "CheckmarkCircle" }),
warning: (msg: string) => send(msg, { type: "warning", icon: "Alert" }),
success: (msg: string) =>
send(msg, { type: "success", icon: "CheckmarkCircle" }),
blockNotifications,
dismiss: dismissNotification,
}
}
function id() {
function id(): string {
return "_" + Math.random().toString(36).slice(2, 9)
}

View File

@ -1,8 +1,8 @@
<script>
<script lang="ts">
import "@spectrum-css/label/dist/index-vars.css"
import Badge from "../Badge/Badge.svelte"
export let value
export let value: string | string[]
const displayLimit = 5

View File

@ -1,15 +1,15 @@
<script>
<script lang="ts">
import Link from "../Link/Link.svelte"
export let value
export let value: { name: string; url: string; extension: string }[]
const displayLimit = 5
$: attachments = value?.slice(0, displayLimit) ?? []
$: leftover = (value?.length ?? 0) - attachments.length
const imageExtensions = ["png", "tiff", "gif", "raw", "jpg", "jpeg"]
const isImage = extension => {
return imageExtensions.includes(extension?.toLowerCase())
const imageExtensions: string[] = ["png", "tiff", "gif", "raw", "jpg", "jpeg"]
const isImage = (extension: string | undefined): boolean => {
return imageExtensions.includes(extension?.toLowerCase() ?? "")
}
</script>

View File

@ -1,5 +1,5 @@
<script>
export let value
<script lang="ts">
export let value: string
</script>
<div class="bold">{value}</div>

View File

@ -1,7 +1,7 @@
<script>
<script lang="ts">
import "@spectrum-css/checkbox/dist/index-vars.css"
export let value
export let value: boolean
</script>
<label

View File

@ -1,4 +1,4 @@
<script>
<script lang="ts">
import StringRenderer from "./StringRenderer.svelte"
import BooleanRenderer from "./BooleanRenderer.svelte"
import DateTimeRenderer from "./DateTimeRenderer.svelte"
@ -8,14 +8,14 @@
import InternalRenderer from "./InternalRenderer.svelte"
import { processStringSync } from "@budibase/string-templates"
export let row
export let schema
export let value
export let customRenderers = []
export let snippets
export let row: Record<string, any>
export let schema: Record<string, any>
export let value: Record<string, any>
export let customRenderers: { column: string; component: any }[] = []
export let snippets: any
let renderer
const typeMap = {
let renderer: any
const typeMap: Record<string, any> = {
boolean: BooleanRenderer,
datetime: DateTimeRenderer,
link: RelationshipRenderer,
@ -33,7 +33,7 @@
$: renderer = customRenderer?.component ?? typeMap[type] ?? StringRenderer
$: cellValue = getCellValue(value, schema.template)
const getType = schema => {
const getType = (schema: any): string => {
// Use a string renderer for dates if we use a custom template
if (schema?.type === "datetime" && schema?.template) {
return "string"
@ -41,7 +41,7 @@
return schema?.type || "string"
}
const getCellValue = (value, template) => {
const getCellValue = (value: any, template: string | undefined): any => {
if (!template) {
return value
}

View File

@ -1,5 +1,5 @@
<script>
export let value
<script lang="ts">
export let value: string
</script>
<code>{value}</code>

View File

@ -1,13 +1,13 @@
<script>
<script lang="ts">
import dayjs from "dayjs"
export let value
export let schema
export let value: string | Date
export let schema: { timeOnly?: boolean; dateOnly?: boolean }
// adding the 0- will turn a string like 00:00:00 into a valid ISO
// date, but will make actual ISO dates invalid
$: time = new Date(`0-${value}`)
$: isTimeOnly = !isNaN(time) || schema?.timeOnly
$: isTimeOnly = !isNaN(time as any) || schema?.timeOnly
$: isDateOnly = schema?.dateOnly
$: format = isTimeOnly
? "HH:mm:ss"

View File

@ -1,11 +1,11 @@
<script>
<script lang="ts">
import Icon from "../Icon/Icon.svelte"
import { copyToClipboard } from "../helpers"
import { notifications } from "../Stores/notifications"
export let value
export let value: string
const onClick = async e => {
const onClick = async (e: MouseEvent): Promise<void> => {
e.stopPropagation()
try {
await copyToClipboard(value)

View File

@ -1,11 +1,11 @@
<script>
<script lang="ts">
import "@spectrum-css/label/dist/index-vars.css"
import { createEventDispatcher } from "svelte"
import Badge from "../Badge/Badge.svelte"
export let row
export let value
export let schema
export let row: { tableId: string; _id: string }
export let value: { primaryDisplay?: string }[] | undefined
export let schema: { name?: string }
const dispatch = createEventDispatcher()
const displayLimit = 5
@ -13,7 +13,7 @@
$: relationships = value?.slice(0, displayLimit) ?? []
$: leftover = (value?.length ?? 0) - relationships.length
const onClick = e => {
const onClick = (e: MouseEvent) => {
e.stopPropagation()
dispatch("clickrelationship", {
tableId: row.tableId,

View File

@ -1,12 +1,12 @@
<script>
<script lang="ts">
import Checkbox from "../Form/Checkbox.svelte"
import ActionButton from "../ActionButton/ActionButton.svelte"
export let selected
export let onEdit
export let allowSelectRows = false
export let allowEditRows = false
export let data
export let selected: boolean | undefined
export let onEdit: (_e: Event) => void
export let allowSelectRows: boolean = false
export let allowEditRows: boolean = false
export let data: Record<string, any>
</script>
<div>

View File

@ -1,6 +1,6 @@
<script>
export let value
export let schema
<script lang="ts">
export let value: string | object
export let schema: { capitalise?: boolean }
</script>
<div class:capitalise={schema?.capitalise}>

View File

@ -1,4 +1,4 @@
<script>
<script lang="ts">
import { createEventDispatcher } from "svelte"
import "@spectrum-css/table/dist/index-vars.css"
import CellRenderer from "./CellRenderer.svelte"
@ -8,6 +8,7 @@
import Checkbox from "../Form/Checkbox.svelte"
/**
/**
* The expected schema is our normal couch schemas for our tables.
* Each field schema can be enriched with a few extra properties to customise
* the behaviour.
@ -24,42 +25,42 @@
* borderLeft: show a left border
* borderRight: show a right border
*/
export let data = []
export let schema = {}
export let showAutoColumns = false
export let rowCount = 0
export let quiet = false
export let loading = false
export let allowSelectRows
export let allowEditRows = true
export let allowEditColumns = true
export let allowClickRows = true
export let selectedRows = []
export let customRenderers = []
export let disableSorting = false
export let autoSortColumns = true
export let compact = false
export let customPlaceholder = false
export let showHeaderBorder = true
export let placeholderText = "No rows found"
export let snippets = []
export let defaultSortColumn = undefined
export let defaultSortOrder = "Ascending"
export let data: any[] = []
export let schema: Record<string, any> = {}
export let showAutoColumns: boolean = false
export let rowCount: number = 0
export let quiet: boolean = false
export let loading: boolean = false
export let allowSelectRows: boolean = false
export let allowEditRows: boolean = true
export let allowEditColumns: boolean = true
export let allowClickRows: boolean = true
export let selectedRows: any[] = []
export let customRenderers: any[] = []
export let disableSorting: boolean = false
export let autoSortColumns: boolean = true
export let compact: boolean = false
export let customPlaceholder: boolean = false
export let showHeaderBorder: boolean = true
export let placeholderText: string = "No rows found"
export let snippets: any[] = []
export let defaultSortColumn: string | undefined = undefined
export let defaultSortOrder: "Ascending" | "Descending" = "Ascending"
const dispatch = createEventDispatcher()
// Config
const headerHeight = 36
const headerHeight: number = 36
$: rowHeight = compact ? 46 : 55
// Sorting state
let sortColumn
let sortOrder
let sortColumn: string | undefined
let sortOrder: "Ascending" | "Descending" | undefined
// Table state
let height = 0
let loaded = false
let checkboxStatus = false
let height: number = 0
let loaded: boolean = false
let checkboxStatus: boolean = false
$: schema = fixSchema(schema)
$: if (!loading) loaded = true
@ -95,8 +96,8 @@
}
}
const fixSchema = schema => {
let fixedSchema = {}
const fixSchema = (schema: Record<string, any>): Record<string, any> => {
let fixedSchema: Record<string, any> = {}
Object.entries(schema || {}).forEach(([fieldName, fieldSchema]) => {
if (typeof fieldSchema === "string") {
fixedSchema[fieldName] = {
@ -120,7 +121,13 @@
return fixedSchema
}
const getVisibleRowCount = (loaded, height, allRows, rowCount, rowHeight) => {
const getVisibleRowCount = (
loaded: boolean,
height: number,
allRows: number,
rowCount: number,
rowHeight: number
): number => {
if (!loaded) {
return rowCount || 0
}
@ -131,12 +138,12 @@
}
const getHeightStyle = (
visibleRowCount,
rowCount,
totalRowCount,
rowHeight,
loading
) => {
visibleRowCount: number,
rowCount: number,
totalRowCount: number,
rowHeight: number,
loading: boolean
): string => {
if (loading) {
return `height: ${headerHeight + visibleRowCount * rowHeight}px;`
}
@ -146,7 +153,11 @@
return `height: ${headerHeight + visibleRowCount * rowHeight}px;`
}
const getGridStyle = (fields, schema, showEditColumn) => {
const getGridStyle = (
fields: string[],
schema: Record<string, any>,
showEditColumn: boolean
): string => {
let style = "grid-template-columns:"
if (showEditColumn) {
style += " auto"
@ -163,7 +174,11 @@
return style
}
const sortRows = (rows, sortColumn, sortOrder) => {
const sortRows = (
rows: any[],
sortColumn: string | undefined,
sortOrder: string | undefined
): any[] => {
sortColumn = sortColumn ?? defaultSortColumn
sortOrder = sortOrder ?? defaultSortOrder
if (!sortColumn || !sortOrder || disableSorting) {
@ -180,7 +195,7 @@
})
}
const sortBy = fieldSchema => {
const sortBy = (fieldSchema: Record<string, any>): void => {
if (fieldSchema.sortable === false) {
return
}
@ -193,7 +208,7 @@
dispatch("sort", { column: sortColumn, order: sortOrder })
}
const getDisplayName = schema => {
const getDisplayName = (schema: Record<string, any>): string => {
let name = schema?.displayName
if (schema && name === undefined) {
name = schema.name
@ -201,9 +216,13 @@
return name || ""
}
const getFields = (schema, showAutoColumns, autoSortColumns) => {
let columns = []
let autoColumns = []
const getFields = (
schema: Record<string, any>,
showAutoColumns: boolean,
autoSortColumns: boolean
): string[] => {
let columns: any[] = []
let autoColumns: any[] = []
Object.entries(schema || {}).forEach(([field, fieldSchema]) => {
if (!field || !fieldSchema) {
return
@ -235,17 +254,17 @@
.map(column => column.name)
}
const editColumn = (e, field) => {
const editColumn = (e: Event, field: any): void => {
e.stopPropagation()
dispatch("editcolumn", field)
}
const editRow = (e, row) => {
const editRow = (e: Event, row: any): void => {
e.stopPropagation()
dispatch("editrow", cloneDeep(row))
}
const toggleSelectRow = row => {
const toggleSelectRow = (row: any): void => {
if (!allowSelectRows) {
return
}
@ -258,7 +277,7 @@
}
}
const toggleSelectAll = e => {
const toggleSelectAll = (e: CustomEvent): void => {
const select = !!e.detail
if (select) {
// Add any rows which are not already in selected rows
@ -278,8 +297,10 @@
}
}
const computeCellStyles = schema => {
let styles = {}
const computeCellStyles = (
schema: Record<string, any>
): Record<string, string> => {
let styles: Record<string, string> = {}
Object.keys(schema || {}).forEach(field => {
styles[field] = ""
if (schema[field].color) {

View File

@ -1,28 +1,48 @@
<script>
<script lang="ts">
import "@spectrum-css/tabs/dist/index-vars.css"
import { writable } from "svelte/store"
import { onMount, setContext, createEventDispatcher } from "svelte"
export let selected
export let vertical = false
export let noPadding = false
// added as a separate option as noPadding is used for vertical padding
export let noHorizPadding = false
export let quiet = false
export let emphasized = false
export let onTop = false
export let size = "M"
export let beforeSwitch = null
interface TabInfo {
width?: number
height?: number
left?: number
top?: number
}
let thisSelected = undefined
interface TabState {
title: string
id: string
emphasized: boolean
info?: TabInfo
}
export let selected: string
export let vertical: boolean = false
export let noPadding: boolean = false
// added as a separate option as noPadding is used for vertical padding
export let noHorizPadding: boolean = false
export let quiet: boolean = false
export let emphasized: boolean = false
export let onTop: boolean = false
export let size: "S" | "M" | "L" = "M"
export let beforeSwitch: ((_title: string) => boolean) | null = null
let thisSelected: string | undefined = undefined
let container: HTMLElement | undefined
let _id = id()
const tab = writable({ title: selected, id: _id, emphasized })
const tab = writable<TabState>({ title: selected, id: _id, emphasized })
setContext("tab", tab)
let container
let top: string | undefined
let left: string | undefined
let width: string | undefined
let height: string | undefined
const dispatch = createEventDispatcher()
const dispatch = createEventDispatcher<{
select: string
}>()
$: {
if (thisSelected !== selected) {
@ -44,29 +64,34 @@
}
if ($tab.title !== thisSelected) {
tab.update(state => {
state.title = thisSelected
state.title = thisSelected as string
return state
})
}
}
let top, left, width, height
$: calculateIndicatorLength($tab)
$: calculateIndicatorOffset($tab)
$: $tab && calculateIndicatorLength()
$: $tab && calculateIndicatorOffset()
function calculateIndicatorLength() {
if (!vertical) {
width = $tab.info?.width + "px"
width = ($tab.info?.width ?? 0) + "px"
} else {
height = $tab.info?.height + 4 + "px"
height = ($tab.info?.height ?? 0) + 4 + "px"
}
}
function calculateIndicatorOffset() {
if (!vertical) {
left = $tab.info?.left - container?.getBoundingClientRect().left + "px"
left =
($tab.info?.left ?? 0) -
(container?.getBoundingClientRect().left ?? 0) +
"px"
} else {
top = $tab.info?.top - container?.getBoundingClientRect().top + "px"
top =
($tab.info?.top ?? 0) -
(container?.getBoundingClientRect().top ?? 0) +
"px"
}
}
@ -75,7 +100,7 @@
calculateIndicatorOffset()
})
function id() {
function id(): string {
return "_" + Math.random().toString(36).slice(2, 9)
}
</script>

View File

@ -1,13 +1,13 @@
<script>
<script lang="ts">
import "@spectrum-css/tags/dist/index-vars.css"
import Avatar from "../Avatar/Avatar.svelte"
import ClearButton from "../ClearButton/ClearButton.svelte"
export let icon = ""
export let avatar = ""
export let invalid = false
export let disabled = false
export let closable = false
export let icon: string = ""
export let avatar: string = ""
export let invalid: boolean = false
export let disabled: boolean = false
export let closable: boolean = false
</script>
<div

View File

@ -1,4 +1,4 @@
<script>
<script lang="ts">
import "@spectrum-css/tags/dist/index-vars.css"
</script>

View File

@ -1,10 +1,10 @@
<script>
<script lang="ts">
import Icon from "../Icon/Icon.svelte"
import AbsTooltip from "./AbsTooltip.svelte"
export let tooltip = ""
export let size = "M"
export let disabled = true
export let tooltip: string = ""
export let size: "S" | "M" = "M"
export let disabled: boolean = true
</script>
<div class:container={!!tooltip}>

View File

@ -1,9 +1,9 @@
<script>
export let selected = false
export let open = false
export let href = false
export let title
export let icon
<script lang="ts">
export let selected: boolean = false
export let open: boolean = false
export let href: string | null = null
export let title: string
export let icon: string | undefined
</script>
<li

View File

@ -1,9 +1,9 @@
<script>
<script lang="ts">
import "@spectrum-css/treeview/dist/index-vars.css"
export let quiet = false
export let standalone = true
export let width = "250px"
export let quiet: boolean = false
export let standalone: boolean = true
export let width: string = "250px"
</script>
<ul

View File

@ -1,8 +1,8 @@
<script>
<script lang="ts">
import "@spectrum-css/typography/dist/index-vars.css"
// Sizes
export let size = "M"
export let size: "S" | "M" | "L" = "M"
</script>
<code class="spectrum-Code spectrum-Code--size{size}">

View File

@ -1,9 +1,9 @@
<script>
<script lang="ts">
import "@spectrum-css/typography/dist/index-vars.css"
export let size = "M"
export let serif = false
export let weight = 600
export let size: "S" | "M" | "L" = "M"
export let serif: boolean = false
export let weight: number | null = null
</script>
<p

View File

@ -65,8 +65,6 @@ export { default as Modal } from "./Modal/Modal.svelte"
export { default as ModalContent, keepOpen } from "./Modal/ModalContent.svelte"
export { default as NotificationDisplay } from "./Notification/NotificationDisplay.svelte"
export { default as Notification } from "./Notification/Notification.svelte"
export { default as SideNavigation } from "./SideNavigation/Navigation.svelte"
export { default as SideNavigationItem } from "./SideNavigation/Item.svelte"
export { default as Context } from "./context"
export { default as Table } from "./Table/Table.svelte"
export { default as Tabs } from "./Tabs/Tabs.svelte"