Files
baserow/web-frontend/modules/dashboard/store/dashboardApplication.js
Jonathan Adelineandpeter_baserow a26c5ce6b0 feat: filter dashboard widgets by date or date range (#6954)
* fix: handle calendar boundaries in date comparisons

* feat: add a single-date filter to the dashboard API

* feat: send the viewer timezone with dashboard data requests

* refactor: share dashboard filter controls and target settings

* feat: configure dashboard filter conditions on date fields

* feat: add the Date filter to the dashboard widget picker

Implement the single-date mode of #6886.

* fix: restore dragging dashboard filters by their titles

* feat: persist the dashboard date filter display format

* feat: choose how dashboard filter dates are displayed

* test: align numeric filter checks with shared dashboard controls

* style: format the dashboard date filter component test

* fix: accept fixed UTC offsets in dashboard date filters

* fix: expose dashboard filter dates as ISO strings in formulas

* fix: seed dashboard conditions with compatible operators

* feat: expose date ranges in dashboard formulas and viewer selections

* feat: configure inclusive date range conditions for dashboard targets

* feat: persist and dispatch inclusive dashboard date ranges

* docs: describe date range selections in the dashboard dispatch API

* feat: select and configure dashboard date ranges

* fix: let viewers clear each dashboard date range endpoint

* fix: preserve unfinished dashboard date range bounds on refresh

* fix: refresh public dashboards after a date filter mode change

* test: group dashboard date filter mode transitions

* fix: warn about incompatible date range formula operands

* fix: convert dashboard date defaults from the saved widget

* fix: keep dashboard filter controls aligned when a condition has a warning

* fix: clear incompatible dashboard conditions when switching date modes

* fix: show cleared date conditions without warnings or redundant saves

* fix: ignore empty dashboard date conditions after switching modes

* fix: ignore dashboard date conditions without a single date and simplify mode switch clearing

---------

Co-authored-by: peter_baserow <peter@baserow.io>
2026-12-03 20:40:18 +04:00

1368 lines
44 KiB
JavaScript

import { DataProviderType } from '@baserow/modules/core/dataProviderTypes'
import { useNuxtApp } from '#app'
import WidgetService from '@baserow/modules/dashboard/services/widget'
import DataSourceService from '@baserow/modules/dashboard/services/dataSource'
import PublicDashboardService from '@baserow/modules/dashboard/services/publicDashboard'
import IntegrationService from '@baserow/modules/core/services/integration'
import { getToken, setToken } from '@baserow/modules/core/utils/auth'
import { getBrowserTimezone } from '@baserow/modules/core/utils/date'
import { ConcurrentPriorityTaskQueue } from '@baserow/modules/core/utils/queue'
import debounce from 'lodash/debounce'
import isEqual from 'lodash/isEqual'
import { WidgetValueUpdate } from '@baserow/modules/dashboard/utils/widgetValueUpdate'
import { sortWidgetsByGridPosition } from '@baserow/modules/dashboard/utils/widgetGridLayout'
export const state = () => ({
dashboardId: null,
dashboardGeneration: 0,
widgetFetchGeneration: 0,
dataSourceCollectionFetchGeneration: 0,
dataSourceDispatchGenerations: {},
dataSourceMutationGenerations: {},
loading: false,
editMode: false,
selectedWidgetId: null,
widgets: [],
widgetValues: {},
widgetSelections: {},
widgetSaveGenerations: {},
dataSources: [],
integrations: [],
// A cache for data that has been
// returned as a result of dispatching
// a data source. The keys are data source ids.
data: {},
// Set while a publicly shared dashboard is shown. Its data sources are then
// dispatched through the public endpoint of the slug, with the token of a
// password protected dashboard.
publicSlug: null,
publicAuthToken: null,
withoutLiveData: false,
})
const widgetUpdates = new WeakMap()
const widgetLayoutUpdates = new WeakMap()
const DEFAULT_DATA_SOURCE_DISPATCH_CONCURRENCY = 5
const DATA_SOURCE_DISPATCH_MAX_RETRIES = 3
const DATA_SOURCE_DISPATCH_RETRY_DELAY_MS = 250
const dataSourceDispatchQueues = new WeakMap()
const dataSourceRefreshes = new WeakMap()
/** Include both old and new targets while their configuration is being saved. */
const getWidgetSaveSourceIds = (state, registry, widget, values) => {
const type = widget && registry?.get?.('dashboardWidget', widget.type)
if (type?.isFilterWidget) {
const updatedWidget = { ...widget, ...values }
// Every dispatch includes all viewer values, and the API validates all of
// them. Changes to their shape or validation also affect unrelated sources.
if (
type.getDispatchValueFormat(widget) !==
type.getDispatchValueFormat(updatedWidget)
) {
return state.dataSources.map(({ id }) => id)
}
const targets = new Set([
...type.getTargetWidgetIds(widget),
...type.getTargetWidgetIds(updatedWidget),
])
return state.widgets.flatMap((target) => {
const targetType = registry.get('dashboardWidget', target.type)
return targetType.isDisplayWidget && targets.has(target.id)
? [targetType.getDataSourceId(target)]
: []
})
}
if (
type?.isDisplayWidget &&
type.getDataSourceId(widget) !==
type.getDataSourceId({ ...widget, ...values })
) {
return [
type.getDataSourceId(widget),
type.getDataSourceId({ ...widget, ...values }),
].filter((id) => id != null)
}
return []
}
/** Attach a debounce to the local Vuex action context, including template stores. */
const ensureDataSourceRefresh = (state, dispatch) => {
if (!dataSourceRefreshes.has(state)) {
const refresh = { ids: new Set(), saves: new Set() }
refresh.run = debounce(() => {
for (const dataSourceId of refresh.ids) {
// Keep only affected sources waiting. Completion of their saves will
// schedule the next attempt, without polling or blocking other sources.
if ([...refresh.saves].some((save) => save.sourceIds.has(dataSourceId)))
continue
refresh.ids.delete(dataSourceId)
dispatch('dispatchDataSource', { dataSourceId })
}
}, 300)
dataSourceRefreshes.set(state, refresh)
}
return dataSourceRefreshes.get(state)
}
const cancelDataSourceRefresh = (state) => {
dataSourceRefreshes.get(state)?.run.cancel()
dataSourceRefreshes.delete(state)
}
const getDataSourceDispatchQueue = (state, concurrency) => {
let queue = dataSourceDispatchQueues.get(state)
if (queue === undefined) {
queue = new ConcurrentPriorityTaskQueue({ concurrency })
dataSourceDispatchQueues.set(state, queue)
} else {
queue.setConcurrency(concurrency)
}
return queue
}
export const getDataSourceDispatchConcurrency = ($config) => {
const configuredValue = Number.parseInt(
$config?.public?.baserowDashboardDataSourceDispatchConcurrency,
10
)
return Number.isFinite(configuredValue) && configuredValue > 0
? configuredValue
: DEFAULT_DATA_SOURCE_DISPATCH_CONCURRENCY
}
/**
* Orders data sources according to the position of their first widget. Sources
* without a widget are kept last, in the order returned by the backend.
*/
export const prioritizeDataSources = (dataSources, widgets) => {
const widgetPositionByDataSourceId = new Map()
;[...widgets]
.sort(
(a, b) =>
(a.grid_y ?? 0) - (b.grid_y ?? 0) || (a.grid_x ?? 0) - (b.grid_x ?? 0)
)
.forEach((widget, index) => {
if (!widgetPositionByDataSourceId.has(widget.data_source_id)) {
widgetPositionByDataSourceId.set(widget.data_source_id, index)
}
})
return dataSources
.map((dataSource, index) => ({ dataSource, index }))
.sort((a, b) => {
const aPriority =
widgetPositionByDataSourceId.get(a.dataSource.id) ??
Number.MAX_SAFE_INTEGER
const bPriority =
widgetPositionByDataSourceId.get(b.dataSource.id) ??
Number.MAX_SAFE_INTEGER
return aPriority - bPriority || a.index - b.index
})
.map(({ dataSource }) => dataSource)
}
/** Returns whether the request was rejected by a concurrency or rate limit. */
const isTooManyRequestsError = (error) =>
error?.isTooManyRequests?.() || error?.response?.status === 429
const getRetryAfterMs = (error, attempt) => {
const headers = error?.response?.headers
const retryAfter = headers?.get?.('retry-after') ?? headers?.['retry-after']
if (retryAfter !== undefined) {
const seconds = Number.parseFloat(retryAfter)
if (Number.isFinite(seconds) && seconds >= 0) {
return seconds * 1000
}
const retryAt = Date.parse(retryAfter)
if (Number.isFinite(retryAt)) {
return Math.max(0, retryAt - Date.now())
}
}
return DATA_SOURCE_DISPATCH_RETRY_DELAY_MS * 2 ** attempt
}
const normalizeDashboardFetchRequest = (request, state, generationKey) => {
const requestValues =
typeof request === 'object' && request !== null
? request
: { dashboardId: request }
return {
dashboardId: requestValues.dashboardId,
dashboardGeneration:
requestValues.dashboardGeneration ?? state.dashboardGeneration,
generation: requestValues.generation ?? state[generationKey],
}
}
const normalizeDataSourceRequestContext = (request, state) => {
const requestValues =
typeof request === 'object' && request !== null
? request
: { dataSourceId: request }
return {
dataSourceId: requestValues.dataSourceId,
dashboardId: requestValues.dashboardId ?? state.dashboardId,
dashboardGeneration:
requestValues.dashboardGeneration ?? state.dashboardGeneration,
}
}
const getDataSourceDispatchGeneration = (state, dataSourceId) =>
state.dataSourceDispatchGenerations[dataSourceId] ?? 0
const getDataSourceMutationGeneration = (state, dataSourceId) =>
state.dataSourceMutationGenerations[dataSourceId] ?? 0
const getDataSourceDispatchRequest = (request, state) => {
const requestContext = normalizeDataSourceRequestContext(request, state)
return {
...requestContext,
generation: getDataSourceDispatchGeneration(
state,
requestContext.dataSourceId
),
}
}
const getDataSourceMutationRequest = (request, state) => {
const requestContext = normalizeDataSourceRequestContext(request, state)
return {
...requestContext,
generation: getDataSourceMutationGeneration(
state,
requestContext.dataSourceId
),
}
}
const isDashboardRequestCurrent = (state, request) => {
return (
state.dashboardId === request.dashboardId &&
state.dashboardGeneration === request.dashboardGeneration
)
}
const isFetchRequestCurrent = (state, request, generationKey) => {
return (
isDashboardRequestCurrent(state, request) &&
state[generationKey] === request.generation
)
}
const isDataSourceDispatchCurrent = (state, request) => {
return (
isDashboardRequestCurrent(state, request) &&
state.dataSources.some(
(dataSource) => dataSource.id === request.dataSourceId
) &&
getDataSourceDispatchGeneration(state, request.dataSourceId) ===
request.generation
)
}
const isDataSourceMutationCurrent = (state, request) => {
return (
isDashboardRequestCurrent(state, request) &&
state.dataSources.some(
(dataSource) => dataSource.id === request.dataSourceId
) &&
getDataSourceMutationGeneration(state, request.dataSourceId) ===
request.generation
)
}
const refreshAfterWidgetCreation = async (dispatch, dashboard) => {
const refreshes = [
() => dispatch('fetchNewDataSources', dashboard.id),
() => dispatch('application/refreshPermissions', dashboard, { root: true }),
]
const results = await Promise.allSettled(
refreshes.map((refresh) => Promise.resolve().then(refresh))
)
const retries = results.flatMap((result, index) => {
return result.status === 'rejected'
? [Promise.resolve().then(refreshes[index])]
: []
})
await Promise.allSettled(retries)
}
/** Invoke a registered widget lifecycle hook using this store's local action context. */
const notifyWidgetHook = (context, registry, hook, widget, ...args) => {
if (!widget?.type) return
return registry
?.get?.('dashboardWidget', widget.type)
?.[hook]?.(widget, { ...context, registry }, ...args)
}
const applyWidgetUpdate = (context, registry, { widgetId, values }) => {
const widget = context.state.widgets.find((widget) => widget.id === widgetId)
if (!widget) return
const previous = { ...widget }
context.commit('UPDATE_WIDGET', { widgetId, values })
notifyWidgetHook(context, registry, 'afterUpdate', widget, previous)
}
const applyWidgetCreate = (context, registry, widget) => {
const previous = context.state.widgets.find(
(existing) => existing.id === widget.id
)
if (previous)
return applyWidgetUpdate(context, registry, {
widgetId: widget.id,
values: widget,
})
context.commit('ADD_WIDGET', widget)
notifyWidgetHook(context, registry, 'afterCreate', widget)
}
const applyWidgetDelete = (context, registry, widgetId) => {
const widget = context.state.widgets.find((widget) => widget.id === widgetId)
context.commit('DELETE_WIDGET', widgetId)
if (widget) notifyWidgetHook(context, registry, 'afterDelete', widget)
}
/** Reconcile lifecycle hooks for a full list, including creations, updates, and removals. */
const applyWidgetCollection = (context, registry, widgets) => {
const previous = new Map(
context.state.widgets.map((widget) => [widget.id, { ...widget }])
)
context.commit('SET_WIDGETS', widgets)
for (const widget of previous.values()) {
if (!widgets.some((current) => current.id === widget.id))
notifyWidgetHook(context, registry, 'afterDelete', widget)
}
for (const widget of widgets) {
const original = previous.get(widget.id)
notifyWidgetHook(
context,
registry,
original ? 'afterUpdate' : 'afterCreate',
widget,
original
)
}
}
export const mutations = {
INVALIDATE_WIDGET_SAVE(state, widgetId) {
state.widgetSaveGenerations[widgetId] =
(state.widgetSaveGenerations[widgetId] || 0) + 1
},
RECORD_WIDGET_SELECTION(state, { widgetId, value }) {
// Object identity records a new user choice even when its value repeats.
state.widgetSelections[widgetId] = { value }
},
SET_WIDGET_VALUE(state, { widgetId, value }) {
state.widgetValues = { ...state.widgetValues, [widgetId]: value }
},
DELETE_WIDGET_VALUE(state, widgetId) {
delete state.widgetValues[widgetId]
delete state.widgetSelections[widgetId]
},
RESET(state) {
dataSourceDispatchQueues.get(state)?.cancelPending()
state.dashboardId = null
state.dashboardGeneration += 1
state.widgetFetchGeneration += 1
state.dataSourceCollectionFetchGeneration += 1
state.dataSourceDispatchGenerations = {}
state.dataSourceMutationGenerations = {}
state.editMode = false
state.selectedWidgetId = null
cancelDataSourceRefresh(state)
state.widgetValues = {}
state.widgetSelections = {}
state.widgetSaveGenerations = {}
state.widgets = []
state.dataSources = []
state.integrations = []
state.data = {}
state.publicSlug = null
state.publicAuthToken = null
state.withoutLiveData = false
},
SET_WITHOUT_LIVE_DATA(state, value) {
state.withoutLiveData = value
},
SET_PUBLIC(state, { slug, authToken = null }) {
state.publicSlug = slug
state.publicAuthToken = authToken
},
SET_DASHBOARD_ID(state, dashboardId) {
if (state.dashboardId !== dashboardId) {
cancelDataSourceRefresh(state)
state.widgetValues = {}
state.widgetSelections = {}
state.widgetSaveGenerations = {}
dataSourceDispatchQueues.get(state)?.cancelPending()
state.dashboardGeneration += 1
state.widgetFetchGeneration += 1
state.dataSourceCollectionFetchGeneration += 1
state.dataSourceDispatchGenerations = {}
state.dataSourceMutationGenerations = {}
}
state.dashboardId = dashboardId
},
INVALIDATE_WIDGET_FETCH(state) {
state.widgetFetchGeneration += 1
},
INVALIDATE_DATA_SOURCE_COLLECTION_FETCH(state) {
state.dataSourceCollectionFetchGeneration += 1
},
INVALIDATE_DATA_SOURCE_DISPATCH(state, dataSourceId) {
state.dataSourceDispatchGenerations[dataSourceId] =
getDataSourceDispatchGeneration(state, dataSourceId) + 1
},
INVALIDATE_DATA_SOURCE_MUTATION(state, dataSourceId) {
state.dataSourceMutationGenerations[dataSourceId] =
getDataSourceMutationGeneration(state, dataSourceId) + 1
},
TOGGLE_EDIT_MODE(state) {
state.editMode = !state.editMode
},
ADD_WIDGET(state, widget) {
const existingWidget = state.widgets.find(
(existingWidget) => existingWidget.id === widget.id
)
if (existingWidget) {
Object.assign(existingWidget, widget)
} else {
state.widgets.push(widget)
}
},
SET_WIDGETS(state, widgets) {
state.widgets = widgets
if (!widgets.some((widget) => widget.id === state.selectedWidgetId)) {
state.selectedWidgetId = null
}
},
ADD_DATA_SOURCE(state, dataSource) {
const existingDataSource = state.dataSources.find(
(existingDataSource) => existingDataSource.id === dataSource.id
)
if (existingDataSource) {
Object.assign(existingDataSource, dataSource)
} else {
state.dataSources.push(dataSource)
}
},
SET_DATA_SOURCES(state, dataSources) {
const dataSourceIds = new Set(dataSources.map(({ id }) => id))
for (const existingDataSource of state.dataSources) {
if (!dataSourceIds.has(existingDataSource.id)) {
state.dataSourceDispatchGenerations[existingDataSource.id] =
getDataSourceDispatchGeneration(state, existingDataSource.id) + 1
state.dataSourceMutationGenerations[existingDataSource.id] =
getDataSourceMutationGeneration(state, existingDataSource.id) + 1
delete state.data[existingDataSource.id]
}
}
const existingDataSourcesById = Object.fromEntries(
state.dataSources.map((dataSource) => [dataSource.id, dataSource])
)
state.dataSources = dataSources.map((dataSource) => {
const existingDataSource = existingDataSourcesById[dataSource.id]
if (existingDataSource) {
Object.assign(existingDataSource, dataSource)
return existingDataSource
}
return dataSource
})
},
UPDATE_DATA_SOURCE(state, { dataSourceId, values }) {
const dataSource = state.dataSources.find(
(dataSource) => dataSource.id === dataSourceId
)
if (dataSource) {
Object.assign(dataSource, values)
} else {
state.dataSources.push({ id: dataSourceId, ...values })
}
},
UPDATE_DATA(state, { dataSourceId, values }) {
if (state.data[dataSourceId] === undefined) {
state.data[dataSourceId] = {}
}
state.data = {
...state.data,
[dataSourceId]: { ...values },
}
},
ADD_INTEGRATION(state, integration) {
state.integrations.push(integration)
},
SELECT_WIDGET(state, widgetId) {
state.selectedWidgetId = widgetId
},
UPDATE_WIDGET(state, { widgetId, values }) {
const widget = state.widgets.find((widget) => widget.id === widgetId)
if (!widget) {
return
}
Object.assign(widget, values)
},
UPDATE_WIDGET_LAYOUTS(state, layouts) {
const widgetsById = new Map(
state.widgets.map((widget) => [widget.id, widget])
)
layouts.forEach(({ id, grid_x, grid_y, grid_width, grid_height }) => {
const widget = widgetsById.get(id)
if (widget) {
Object.assign(widget, { grid_x, grid_y, grid_width, grid_height })
}
})
},
DELETE_WIDGET(state, widgetId) {
const index = state.widgets.findIndex((widget) => widget.id === widgetId)
if (index !== -1) {
state.widgets.splice(index, 1)
}
if (state.selectedWidgetId === widgetId) {
state.selectedWidgetId = null
}
},
SET_LOADING(state, value) {
state.loading = value
},
}
export const actions = {
/** Reconcile defaults and viewer selection after local option resolution. */
async reconcileWidgetOptions(context, { widgetId, options }) {
const widget = context.state.widgets.find(
(widget) => widget.id === widgetId
)
if (widget)
await notifyWidgetHook(
context,
this.$registry,
'afterOptionsLoad',
widget,
options
)
},
forceSetWidgets(context, widgets) {
applyWidgetCollection(context, this.$registry, widgets)
},
forceCreateWidget(context, widget) {
applyWidgetCreate(context, this.$registry, widget)
},
forceUpdateWidget(context, values) {
applyWidgetUpdate(context, this.$registry, values)
},
forceDeleteWidget(context, widgetId) {
applyWidgetDelete(context, this.$registry, widgetId)
},
/** Invalidate immediately and coalesce source refreshes per local store. */
refreshDataSources({ state, commit, dispatch }, sourceIds) {
if (!sourceIds.length) return
ensureDataSourceRefresh(state, dispatch)
const refresh = dataSourceRefreshes.get(state)
for (const id of sourceIds) {
commit('INVALIDATE_DATA_SOURCE_DISPATCH', id)
refresh.ids.add(id)
}
refresh.run()
},
setWidgetValue(context, { widgetId, value }) {
const widget = context.state.widgets.find(
(widget) => widget.id === widgetId
)
if (widget) context.commit('RECORD_WIDGET_SELECTION', { widgetId, value })
notifyWidgetHook(context, this.$registry, 'valueChanged', widget, value)
},
reset({ commit }) {
commit('RESET')
},
toggleEditMode({ commit }) {
commit('TOGGLE_EDIT_MODE')
},
enterEditMode({ getters, commit }) {
if (!getters.isEditMode) {
commit('TOGGLE_EDIT_MODE')
}
},
selectWidget({ commit }, widgetId) {
commit('SELECT_WIDGET', widgetId)
},
async updateWidget(context, change) {
const { state, commit, dispatch } = context
const { widgetId, values, originalValues, optimistic = true } = change
// A server-confirmed edit can derive other fields from their persisted values.
// Send it on its own, in order with earlier and later edits to this widget.
const saves = dataSourceRefreshes.get(state)?.saves ?? []
const pending = [...saves].filter(
(save) => save.widgetId === widgetId && (!optimistic || !save.optimistic)
)
if (pending.length) {
await Promise.all(pending.map((save) => save.run.flush()))
if (isDashboardRequestCurrent(state, pending[0].request))
return dispatch('updateWidget', change)
return
}
return new Promise((resolve, reject) => {
const { $client, $registry } = this
commit('INVALIDATE_WIDGET_FETCH')
commit('INVALIDATE_WIDGET_SAVE', widgetId)
const request = normalizeDashboardFetchRequest(
state.dashboardId,
state,
'widgetFetchGeneration'
)
const sourceIds = getWidgetSaveSourceIds(
state,
$registry,
state.widgets.find((widget) => widget.id === widgetId),
values
)
const previousWidgetValue = state.widgetValues[widgetId]
if (optimistic)
applyWidgetUpdate(context, $registry, { widgetId, values })
const updatedWidgetValue = state.widgetValues[widgetId]
if (!widgetUpdates.has(state)) widgetUpdates.set(state, new Map())
const updates = widgetUpdates.get(state)
let batch = updates.get(widgetId)
if (
batch &&
!batch.started &&
isDashboardRequestCurrent(state, batch.request)
) {
// Keep every caller waiting for the combined save, with the latest value
// for each field and the earliest value for rolling that field back.
batch.valueUpdate.merge(
previousWidgetValue,
updatedWidgetValue,
state.widgetSelections[widgetId]
)
batch.saveGeneration = state.widgetSaveGenerations[widgetId]
Object.assign(batch.values, values)
batch.originalValues = { ...originalValues, ...batch.originalValues }
batch.request = request
sourceIds.forEach((id) => batch.sourceIds.add(id))
batch.waiters.push({ resolve, reject })
batch.run()
return
}
batch = {
widgetId,
optimistic,
values: { ...values },
originalValues: { ...originalValues },
valueUpdate: new WidgetValueUpdate(
previousWidgetValue,
updatedWidgetValue,
state.widgetSelections[widgetId]
),
saveGeneration: state.widgetSaveGenerations[widgetId],
request,
waiters: [{ resolve, reject }],
started: false,
sourceIds: new Set(sourceIds),
}
ensureDataSourceRefresh(state, dispatch)
const refresh = dataSourceRefreshes.get(state)
refresh.saves.add(batch)
batch.run = debounce(async () => {
batch.started = true
const { values, originalValues, request } = batch
try {
const { data } = await WidgetService($client).update(widgetId, values)
if (updates.get(widgetId) === batch) updates.delete(widgetId)
if (isDashboardRequestCurrent(state, request)) {
// Server normalization can populate copied filter conditions. Apply
// it before callers open the editor, without overwriting newer edits.
if (
state.widgetSaveGenerations[widgetId] === batch.saveGeneration
) {
applyWidgetUpdate(context, $registry, { widgetId, values: data })
}
const widget = state.widgets.find(
(widget) => widget.id === widgetId
)
await notifyWidgetHook(
context,
$registry,
'afterSave',
widget,
values
)
}
if (
isDashboardRequestCurrent(state, request) &&
!isFetchRequestCurrent(state, request, 'widgetFetchGeneration')
) {
await dispatch('fetchWidgets', request.dashboardId)
}
batch.waiters.forEach(({ resolve }) => resolve())
} catch (error) {
if (updates.get(widgetId) === batch) updates.delete(widgetId)
try {
if (
isFetchRequestCurrent(state, request, 'widgetFetchGeneration')
) {
applyWidgetUpdate(context, $registry, {
widgetId,
values: originalValues,
})
} else if (isDashboardRequestCurrent(state, request)) {
await dispatch('fetchWidgets', request.dashboardId)
}
} catch {
// Report the original save error even if refreshing server state fails.
} finally {
// Collection fetches are dashboard-wide; viewer rollback belongs to
// this widget's save and must not undo a newer save of the same widget.
if (
isDashboardRequestCurrent(state, request) &&
state.widgetSaveGenerations[widgetId] === batch.saveGeneration
) {
batch.valueUpdate.restore(context, $registry, widgetId)
}
// A failed recovery must also release every waiting component.
batch.waiters.forEach(({ reject }) => reject(error))
}
} finally {
refresh.saves.delete(batch)
if (dataSourceRefreshes.get(state) === refresh && refresh.ids.size) {
refresh.run()
}
}
}, 1000)
updates.set(widgetId, batch)
batch.run()
if (!optimistic) batch.run.flush()
})
},
async handleWidgetUpdated(context, widget) {
const { state, commit, dispatch } = context
commit('INVALIDATE_WIDGET_FETCH')
if (
state.loading ||
!state.widgets.some((existingWidget) => existingWidget.id === widget.id)
) {
await dispatch('fetchWidgets', state.dashboardId)
return
}
applyWidgetUpdate(context, this.$registry, {
widgetId: widget.id,
values: widget,
})
},
async updateDataSource(
{ state, commit, dispatch },
{ dataSourceId, values, widget, linkFilterWidgetId = null }
) {
const { $client, $registry } = this
const previousTableId = state.dataSources.find(
({ id }) => id === dataSourceId
)?.table_id
const previousData = state.data[dataSourceId]
commit('INVALIDATE_DATA_SOURCE_COLLECTION_FETCH')
commit('INVALIDATE_DATA_SOURCE_DISPATCH', dataSourceId)
commit('INVALIDATE_DATA_SOURCE_MUTATION', dataSourceId)
const request = getDataSourceMutationRequest({ dataSourceId }, state)
commit('UPDATE_DATA', { dataSourceId, values: null })
let data
try {
const response = await DataSourceService($client).update(dataSourceId, {
...values,
...(linkFilterWidgetId == null
? {}
: { link_filter_widget_id: linkFilterWidgetId }),
})
data = response.data
} catch (error) {
if (isDataSourceMutationCurrent(state, request)) {
const hasPreviousData =
previousData && Object.keys(previousData).length > 0
commit('UPDATE_DATA', {
dataSourceId,
values: hasPreviousData ? previousData : { _error: true },
})
}
throw error
}
if (!isDataSourceMutationCurrent(state, request)) {
return
}
commit('INVALIDATE_DATA_SOURCE_COLLECTION_FETCH')
commit('UPDATE_DATA_SOURCE', {
dataSourceId,
values: data,
})
try {
if (data.table_id !== previousTableId) {
// The backend resets linked filter conditions in the same transaction.
await dispatch('fetchWidgets', request.dashboardId)
if (!isDataSourceMutationCurrent(state, request)) return
}
if (widget) {
const widgetType = $registry.get('dashboardWidget', widget.type)
await widgetType.dataSourceUpdated(widget, data)
if (!isDataSourceMutationCurrent(state, request)) {
return
}
}
await dispatch('dispatchDataSource', {
dataSourceId,
dashboardId: request.dashboardId,
dashboardGeneration: request.dashboardGeneration,
})
} catch (error) {
if (isDataSourceMutationCurrent(state, request)) {
commit('UPDATE_DATA', {
dataSourceId,
values: { _error: true },
})
}
throw error
}
},
async handleDataSourceUpdated({ state, commit, dispatch }, dataSource) {
commit('INVALIDATE_DATA_SOURCE_COLLECTION_FETCH')
commit('INVALIDATE_DATA_SOURCE_MUTATION', dataSource.id)
commit('UPDATE_DATA_SOURCE', {
dataSourceId: dataSource.id,
values: dataSource,
})
await dispatch('dispatchDataSource', {
dataSourceId: dataSource.id,
dashboardId: state.dashboardId,
dashboardGeneration: state.dashboardGeneration,
})
},
/**
* Shows a publicly shared dashboard. Its widgets and data sources come from
* the public info endpoint, so nothing is fetched here. The data sources are
* dispatched afterwards with `dispatchDataSources`, in the browser only.
*/
openPublicDashboard(
context,
{ slug, authToken = null, dashboardId, widgets, dataSources }
) {
const { commit } = context
commit('RESET')
commit('SET_DASHBOARD_ID', dashboardId)
commit('SET_PUBLIC', { slug, authToken })
applyWidgetCollection(context, this.$registry, widgets)
commit('SET_DATA_SOURCES', dataSources)
},
/** Reconcile an open public dashboard after the server rejects a filter value. */
async refreshPublicDashboardConfiguration(context) {
const { state, commit, dispatch } = context
const { $client, $registry } = this
const { dashboardId, dashboardGeneration, publicSlug, publicAuthToken } =
state
const refresh = ensureDataSourceRefresh(state, dispatch)
if (!refresh.publicConfiguration) {
refresh.publicConfiguration = PublicDashboardService($client)
.fetchInfo(publicSlug, publicAuthToken)
.then(({ data }) => {
if (
!isDashboardRequestCurrent(state, {
dashboardId,
dashboardGeneration,
}) ||
state.publicSlug !== publicSlug ||
state.publicAuthToken !== publicAuthToken
) {
return
}
const previousWidgets = new Map(
state.widgets.map((widget) => [widget.id, widget])
)
const filterFormatChanged = data.widgets.some((widget) => {
const previousWidget = previousWidgets.get(widget.id)
const type = $registry.get('dashboardWidget', widget.type)
return (
type.isFilterWidget &&
previousWidget?.type === widget.type &&
type.getDispatchValueFormat(previousWidget) !==
type.getDispatchValueFormat(widget)
)
})
if (filterFormatChanged) {
commit('SET_DATA_SOURCES', data.data_sources)
applyWidgetCollection(context, $registry, data.widgets)
dispatch(
'refreshDataSources',
state.dataSources.map(({ id }) => id)
)
}
})
.finally(() => {
delete refresh.publicConfiguration
})
}
return refresh.publicConfiguration
},
/**
* Remembers the token that the public auth endpoint handed out for the right
* password: in a cookie keyed by the slug, so that it survives a reload, and
* in the store for the navigation to the dashboard that follows.
*/
async setPublicAuthToken({ commit }, { slug, token }) {
await setToken(this.app, token, slug)
commit('SET_PUBLIC', { slug, authToken: token })
},
/**
* Returns the token remembered for the slug: the one in the store when the
* visitor just entered the password, otherwise the one in the cookie. `null`
* when there is none, which is fine for a dashboard without a password.
*/
async restorePublicAuthToken({ state }, { slug }) {
if (state.publicSlug === slug && state.publicAuthToken) {
return state.publicAuthToken
}
return (await getToken(this.app, slug)) || null
},
/**
* Dispatches every data source of the current dashboard, the ones shown by the
* top most widgets first.
*/
async dispatchDataSources({ state, dispatch }) {
const request = {
dashboardId: state.dashboardId,
dashboardGeneration: state.dashboardGeneration,
}
const queuedDataSources = prioritizeDataSources(
state.dataSources,
state.widgets
)
await Promise.allSettled(
queuedDataSources.map((dataSource, priority) =>
dispatch('dispatchDataSource', {
dataSourceId: dataSource.id,
dashboardId: request.dashboardId,
dashboardGeneration: request.dashboardGeneration,
priority,
})
)
)
},
async fetchInitial(
{ state, commit, dispatch },
{ dashboardId, forEditing, withoutLiveData = false }
) {
const { $client } = this
commit('RESET')
commit('SET_WITHOUT_LIVE_DATA', withoutLiveData)
commit('SET_LOADING', true)
commit('SET_DASHBOARD_ID', dashboardId)
const request = {
dashboardId,
dashboardGeneration: state.dashboardGeneration,
}
let widgets
do {
widgets = await dispatch('fetchWidgets', dashboardId)
} while (widgets === undefined && isDashboardRequestCurrent(state, request))
if (!isDashboardRequestCurrent(state, request)) {
return
}
// Render widgets while their data sources are still loading.
commit('SET_LOADING', false)
let dataSources
do {
dataSources = await dispatch('fetchNewDataSources', dashboardId)
} while (
dataSources === undefined &&
isDashboardRequestCurrent(state, request)
)
if (!isDashboardRequestCurrent(state, request)) {
return
}
if (forEditing) {
const { data: integrationsData } =
await IntegrationService($client).fetchAll(dashboardId)
if (!isDashboardRequestCurrent(state, request)) {
return
}
integrationsData.forEach((integration) => {
commit('ADD_INTEGRATION', integration)
})
}
},
async fetchWidgets(context, requestValues) {
const { state, commit } = context
const { $client } = this
const dashboardId =
typeof requestValues === 'object' && requestValues !== null
? requestValues.dashboardId
: requestValues
if (dashboardId !== state.dashboardId) {
return
}
commit('INVALIDATE_WIDGET_FETCH')
const request = normalizeDashboardFetchRequest(
dashboardId,
state,
'widgetFetchGeneration'
)
const { data } = await WidgetService($client).getAllWidgets(
request.dashboardId
)
if (!isFetchRequestCurrent(state, request, 'widgetFetchGeneration')) {
return
}
applyWidgetCollection(context, this.$registry, data)
return data
},
async fetchNewDataSources(
{ state, commit, dispatch, getters },
requestValues
) {
const { $client } = this
const dashboardId =
typeof requestValues === 'object' && requestValues !== null
? requestValues.dashboardId
: requestValues
if (dashboardId !== state.dashboardId) {
return
}
commit('INVALIDATE_DATA_SOURCE_COLLECTION_FETCH')
const request = normalizeDashboardFetchRequest(
dashboardId,
state,
'dataSourceCollectionFetchGeneration'
)
const { data: dataSourcesData } = await DataSourceService(
$client
).getAllDataSources(request.dashboardId)
if (
!isFetchRequestCurrent(
state,
request,
'dataSourceCollectionFetchGeneration'
)
) {
return
}
const dataSourceIdsToDispatch = new Set(
dataSourcesData.flatMap((dataSource) => {
const existingDataSource = getters.getDataSourceById(dataSource.id)
const existingData = state.data[dataSource.id]
const shouldDispatch =
!existingDataSource ||
!isEqual(existingDataSource, dataSource) ||
!existingData ||
Object.keys(existingData).length === 0
return shouldDispatch ? [dataSource.id] : []
})
)
commit('SET_DATA_SOURCES', dataSourcesData)
const queuedDataSources = prioritizeDataSources(
dataSourcesData.filter(({ id }) => dataSourceIdsToDispatch.has(id)),
state.widgets
)
await Promise.allSettled(
queuedDataSources.map((dataSource, priority) =>
dispatch('dispatchDataSource', {
dataSourceId: dataSource.id,
dashboardId: request.dashboardId,
dashboardGeneration: request.dashboardGeneration,
priority,
})
)
)
if (
!isFetchRequestCurrent(
state,
request,
'dataSourceCollectionFetchGeneration'
)
) {
return
}
return dataSourcesData
},
/**
* Create a widget and select it, unless `select` is false: an editor adding
* a widget from another widget's settings keeps working on that one.
* Notify `onCreated` after the POST succeeds, before refreshing related data.
*/
async createWidget(
{ state, dispatch },
{ dashboard, widget, select = true, onCreated }
) {
const { $client } = this
const request = {
dashboardId: dashboard.id,
dashboardGeneration: state.dashboardGeneration,
}
// The server places the new widget using the saved layout.
const layoutUpdate = widgetLayoutUpdates.get(state)
if (layoutUpdate?.dashboardId === dashboard.id) {
await layoutUpdate.promise.catch(() => {})
}
const { data: widgetData } = await WidgetService($client).create(
dashboard.id,
widget
)
if (!isDashboardRequestCurrent(state, request)) {
return widgetData
}
onCreated?.(widgetData.id)
const createdWidget = await dispatch('handleNewWidgetCreated', widgetData)
if (!isDashboardRequestCurrent(state, request)) {
return createdWidget
}
if (select) dispatch('selectWidget', createdWidget.id)
// The POST above is the creation boundary. Refreshing related client state must
// never turn a persisted widget into an apparent creation failure.
await refreshAfterWidgetCreation(dispatch, dashboard)
return createdWidget
},
handleNewWidgetCreated(context, widget) {
const { state, commit } = context
if (widget.dashboard_id !== state.dashboardId) {
return widget
}
commit('INVALIDATE_WIDGET_FETCH')
commit('INVALIDATE_DATA_SOURCE_COLLECTION_FETCH')
applyWidgetCreate(context, this.$registry, widget)
return widget
},
async dispatchDataSource({ state, commit, dispatch }, requestValues) {
if (state.withoutLiveData) {
return
}
const { $client, $config, $registry } = this
const requestContext = normalizeDataSourceRequestContext(
requestValues,
state
)
if (
!isDashboardRequestCurrent(state, requestContext) ||
!state.dataSources.some(
(dataSource) => dataSource.id === requestContext.dataSourceId
)
) {
return
}
commit('INVALIDATE_DATA_SOURCE_DISPATCH', requestContext.dataSourceId)
const request = getDataSourceDispatchRequest(requestContext, state)
commit('UPDATE_DATA', {
dataSourceId: request.dataSourceId,
values: { ...state.data[request.dataSourceId], _loading: true },
})
const queue = getDataSourceDispatchQueue(
state,
getDataSourceDispatchConcurrency($config)
)
const priority = requestValues?.priority ?? 0
try {
const response = await queue.add(
() => {
if (!isDataSourceDispatchCurrent(state, request)) {
return undefined
}
const context = {
...DataProviderType.getAllDataSourceDispatchContext(
$registry.getAll('dashboardDataProvider'),
{
dashboard: { id: state.dashboardId },
widgetValues: state.widgetValues,
}
),
timezone: getBrowserTimezone(),
}
if (state.publicSlug !== null) {
return PublicDashboardService($client).dispatch(
state.publicSlug,
request.dataSourceId,
state.publicAuthToken,
context
)
}
return DataSourceService($client).dispatch(
request.dataSourceId,
context
)
},
priority,
{
maxRetries: DATA_SOURCE_DISPATCH_MAX_RETRIES,
shouldRetry: (error) =>
isDataSourceDispatchCurrent(state, request) &&
isTooManyRequestsError(error),
retryDelay: getRetryAfterMs,
}
)
if (
response === undefined ||
!isDataSourceDispatchCurrent(state, request)
) {
return
}
commit('UPDATE_DATA', {
dataSourceId: request.dataSourceId,
values: { ...response.data, _loaded: true },
})
} catch (error) {
if (!isDataSourceDispatchCurrent(state, request)) {
return
}
if (
state.publicSlug !== null &&
error.response?.data?.error === 'ERROR_INVALID_DASHBOARD_FILTER_VALUE'
) {
await dispatch('refreshPublicDashboardConfiguration').catch(() => {})
}
if (isDataSourceDispatchCurrent(state, request)) {
commit('UPDATE_DATA', {
dataSourceId: request.dataSourceId,
values: { _error: true },
})
}
}
},
async deleteWidget({ state, commit, dispatch }, widgetId) {
const { $client } = this
commit('INVALIDATE_WIDGET_FETCH')
const request = normalizeDashboardFetchRequest(
state.dashboardId,
state,
'widgetFetchGeneration'
)
await WidgetService($client).delete(widgetId)
if (!isDashboardRequestCurrent(state, request)) {
return
}
await dispatch('fetchWidgets', request.dashboardId)
},
async handleWidgetDeleted(context, widgetId) {
const { state, commit, dispatch } = context
const widgetExists = state.widgets.some((widget) => widget.id === widgetId)
commit('INVALIDATE_WIDGET_FETCH')
if (state.loading || !widgetExists) {
await dispatch('fetchWidgets', state.dashboardId)
return
}
applyWidgetDelete(context, this.$registry, widgetId)
},
async updateWidgetLayout({ state, commit }, { dashboardId, layout }) {
const { $client } = this
commit('INVALIDATE_WIDGET_FETCH')
const request = normalizeDashboardFetchRequest(
dashboardId,
state,
'widgetFetchGeneration'
)
const update = {
dashboardId,
promise: WidgetService($client).updateLayout(dashboardId, layout),
}
widgetLayoutUpdates.set(state, update)
try {
const { data } = await update.promise
if (isFetchRequestCurrent(state, request, 'widgetFetchGeneration')) {
commit('UPDATE_WIDGET_LAYOUTS', data)
}
return data
} finally {
if (widgetLayoutUpdates.get(state) === update) {
widgetLayoutUpdates.delete(state)
}
}
},
async handleWidgetsLayoutUpdated({ state, commit, dispatch }) {
commit('INVALIDATE_WIDGET_FETCH')
commit('INVALIDATE_DATA_SOURCE_COLLECTION_FETCH')
await Promise.allSettled([
dispatch('fetchWidgets', state.dashboardId),
dispatch('fetchNewDataSources', state.dashboardId),
])
},
}
export const getters = {
getWidgetValues: (state) => state.widgetValues,
getDashboardId(state) {
return state.dashboardId
},
isEditMode(state) {
return state.editMode
},
isLoading(state) {
return state.loading
},
isWithoutLiveData(state) {
return state.withoutLiveData
},
isEmpty(state) {
return state.widgets.length === 0
},
getWidgetById: (state, getters) => (widgetId) => {
return state.widgets.find((widget) => widget.id === widgetId)
},
getWidgets(state) {
return sortWidgetsByGridPosition(state.widgets)
},
getSelectedWidgetId(state) {
return state.selectedWidgetId
},
getSelectedWidget(state) {
return state.widgets.find((widget) => widget.id === state.selectedWidgetId)
},
getDataSources: (state) => state.dataSources,
getDataSourceById: (state, getters) => (dataSourceId) => {
return state.dataSources.find(
(dataSource) => dataSource.id === dataSourceId
)
},
getData(state) {
return state.data
},
getDataForDataSource: (state, getters) => (dataSourceId) => {
return state.data[dataSourceId]
},
isPublic(state) {
return state.publicSlug !== null
},
getPublicSlug(state) {
return state.publicSlug
},
getPublicAuthToken(state) {
return state.publicAuthToken
},
getIntegrations(state) {
return state.integrations
},
getIntegrationById: (state) => (integrationId) => {
return state.integrations.find(
(integration) => integration.id === integrationId
)
},
}
export default {
namespaced: true,
state,
getters,
actions,
mutations,
}