Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Add datepicker to logs explorer, ux fixes

TzeYiingda05d31247c8
diff --git a/studio/components/interfaces/Settings/Logs/Logs.DatePickers.tsx b/studio/components/interfaces/Settings/Logs/Logs.DatePickers.tsx
index 4683deb94f9..d8ddaa3c32e 100644
--- a/studio/components/interfaces/Settings/Logs/Logs.DatePickers.tsx
+++ b/studio/components/interfaces/Settings/Logs/Logs.DatePickers.tsx
@@ -4,32 +4,60 @@ import { useState, useEffect } from 'react'
type ToFrom = { to: string; from: string }
interface Props {
- to?: string
- from?: string
+ to: string
+ from: string
onChange: ({ to, from }: ToFrom) => void
+ helpers?: Helper[]
+ changeOnMount?: boolean
+}
+interface Helper {
+ text: string
+ calcTo: () => string
+ calcFrom: () => string
}
-const HELPERS = [
- { text: 'Last hour', value: '1_hour' },
- { text: 'Last 3 hours', value: '3_hour' },
- { text: 'Last day', value: '1_day' },
+const DEFAULT_HELPERS: Helper[] = [
+ {
+ text: 'Last hour',
+ calcTo: () => new Date(new Date().getTime() - 60 * 60 * 1000).toISOString(),
+ calcFrom: () => '',
+ },
+ {
+ text: 'Last 3 hours',
+ calcTo: () => new Date(new Date().getTime() - 3 * 60 * 60 * 1000).toISOString(),
+ calcFrom: () => '',
+ },
+ {
+ text: 'Last day',
+ calcTo: () => new Date(new Date().getTime() - 24 * 60 * 60 * 1000).toISOString(),
+ calcFrom: () => '',
+ },
]
-const DEFAULT_HELPER_VALUE = HELPERS[0].value
-
-const DatePickers: React.FC<Props> = ({ to, from, onChange }) => {
- const [helperValue, setHelperValue] = useState<string>('')
+const DatePickers: React.FC<Props> = ({
+ to,
+ from,
+ onChange,
+ helpers = DEFAULT_HELPERS,
+ changeOnMount = false,
+}) => {
+ const defaultHelper = helpers[0]
+ const [helperValue, setHelperValue] = useState<string>(to || from ? '' : defaultHelper.text)
+ const selectedHelper = helpers.find((h) => h.text === helperValue)
const handleHelperChange = (newValue: string) => {
setHelperValue(newValue)
- const toDate = new Date()
- const fromDate = {
- '1_hour': new Date(toDate.getTime() - 60 * 60 * 1000),
- '3_hour': new Date(toDate.getTime() - 3 * 60 * 60 * 1000),
- '1_day': new Date(toDate.getTime() - 24 * 60 * 60 * 1000),
- }[newValue]
- if (onChange) onChange({ to: toDate.toISOString(), from: fromDate?.toISOString() as string })
+ const selectedHelper = helpers.find((h) => h.text === newValue)
+ if (onChange && selectedHelper) {
+ onChange({ to: selectedHelper.calcTo(), from: selectedHelper.calcFrom() })
+ }
}
- const selectedHelper = HELPERS.find((h) => h.value === (helperValue || DEFAULT_HELPER_VALUE))
+ // trigger change if flag is provided
+ useEffect(() => {
+ if (changeOnMount) {
+ handleHelperChange(helperValue)
+ }
+ }, [])
+
return (
<div className="flex items-center">
<Dropdown
@@ -38,12 +66,9 @@ const DatePickers: React.FC<Props> = ({ to, from, onChange }) => {
align="start"
overlay={
<>
- <Dropdown.RadioGroup
- onChange={handleHelperChange}
- value={helperValue || DEFAULT_HELPER_VALUE}
- >
- {HELPERS.map((helper) => (
- <Dropdown.Radio key={helper.value} value={helper.value}>
+ <Dropdown.RadioGroup onChange={handleHelperChange} value={selectedHelper?.text || ''}>
+ {helpers.map((helper) => (
+ <Dropdown.Radio key={helper.text} value={helper.text}>
{helper.text}
</Dropdown.Radio>
))}
@@ -57,7 +82,7 @@ const DatePickers: React.FC<Props> = ({ to, from, onChange }) => {
icon={<IconClock size={12} />}
className="rounded-r-none"
>
- {selectedHelper?.text}
+ {selectedHelper?.text || defaultHelper.text}
</Button>
</Dropdown>
<DatePicker
diff --git a/studio/components/interfaces/Settings/Logs/Logs.types.ts b/studio/components/interfaces/Settings/Logs/Logs.types.ts
index 2d2036353d8..71d9d1ac18c 100644
--- a/studio/components/interfaces/Settings/Logs/Logs.types.ts
+++ b/studio/components/interfaces/Settings/Logs/Logs.types.ts
@@ -1,17 +1,25 @@
interface Metadata {
[key: string]: string | number | Object | Object[]
}
-export type LogSearchCallback = (filters: { query: string; to?: string; from?: string; fromMicro?: number, toMicro?: number }) => void
+export type LogSearchCallback = (filters: {
+ query: string
+ to?: string
+ from?: string
+ fromMicro?: number
+ toMicro?: number
+}) => void
export interface LogsEndpointParams {
// project ref
project: string
- // micro unix timestamp
+ // depreacted, micro unix timestamp
timestamp_start?: string
- // micro timestamp
timestamp_end?: string
+ // deprecated, iso timestamps
period_start?: string
period_end?: string
+ iso_timestamp_start?: string
+ iso_timestamp_end?: string
sql: string
rawSql: string
}
@@ -65,7 +73,6 @@ export interface FilterObject {
te?: string
}
-
export interface FilterSet {
label: string
key: string
diff --git a/studio/components/interfaces/Settings/Logs/LogsQueryPanel.tsx b/studio/components/interfaces/Settings/Logs/LogsQueryPanel.tsx
index 91d60213a50..fff40d4b79a 100644
--- a/studio/components/interfaces/Settings/Logs/LogsQueryPanel.tsx
+++ b/studio/components/interfaces/Settings/Logs/LogsQueryPanel.tsx
@@ -1,6 +1,8 @@
import { Button, Dropdown, Typography, IconChevronDown, IconPlay } from '@supabase/ui'
import Flag from 'components/ui/Flag/Flag'
+import dayjs from 'dayjs'
import { LogsTableName, LOGS_SOURCE_DESCRIPTION, LogTemplate } from '.'
+import DatePickers from './Logs.DatePickers'
interface Props {
templates?: LogTemplate[]
onSelectTemplate: (template: LogTemplate) => void
@@ -10,6 +12,9 @@ interface Props {
onSave?: () => void
hasEditorValue: boolean
isLoading: boolean
+ onDateChange: (time: { to: string; from: string }) => void
+ defaultTo: string
+ defaultFrom: string
}
const LogsQueryPanel: React.FC<Props> = ({
@@ -21,6 +26,9 @@ const LogsQueryPanel: React.FC<Props> = ({
onSave,
onSelectSource,
isLoading,
+ defaultFrom,
+ defaultTo,
+ onDateChange,
}) => (
<div
className="
@@ -63,6 +71,29 @@ bg-panel-header-light dark:bg-panel-header-dark
Templates
</Button>
</Dropdown>
+ <DatePickers
+ changeOnMount
+ to={defaultTo}
+ from={defaultFrom}
+ onChange={onDateChange}
+ helpers={[
+ {
+ text: 'Last day',
+ calcFrom: () => dayjs().subtract(1, 'day').startOf('day').toISOString(),
+ calcTo: () => '',
+ },
+ {
+ text: 'Last 3 days',
+ calcFrom: () => dayjs().subtract(3, 'day').startOf('day').toISOString(),
+ calcTo: () => '',
+ },
+ {
+ text: 'Last 7 days',
+ calcFrom: () => dayjs().subtract(7, 'day').startOf('day').toISOString(),
+ calcTo: () => '',
+ },
+ ]}
+ />
</div>
<div>
<div className="flex items-center gap-4">
diff --git a/studio/hooks/analytics/useLogsQuery.tsx b/studio/hooks/analytics/useLogsQuery.tsx
index a9523b3951c..6e40a298c1c 100644
--- a/studio/hooks/analytics/useLogsQuery.tsx
+++ b/studio/hooks/analytics/useLogsQuery.tsx
@@ -5,6 +5,7 @@ import useSWRInfinite, { SWRInfiniteKeyLoader } from 'swr/infinite/dist/infinite
import { API_URL } from 'lib/constants'
import useSWR, { mutate } from 'swr'
import { get } from 'lib/common/fetch'
+import dayjs from 'dayjs'
interface Data {
params: LogsEndpointParams
isLoading: boolean
@@ -14,6 +15,7 @@ interface Data {
interface Handlers {
changeQuery: (newQuery?: string) => void
runQuery: () => void
+ setParams: Dispatch<SetStateAction<LogsEndpointParams>>
}
const useLogsQuery = (
@@ -24,8 +26,8 @@ const useLogsQuery = (
project: projectRef,
sql: '',
rawSql: '',
- // timestamp_start: '',
- // timestamp_end: '',
+ iso_timestamp_start: '',
+ iso_timestamp_end: '',
...initialParams,
})
@@ -36,7 +38,9 @@ const useLogsQuery = (
isValidating: isLoading,
mutate,
} = useSWR<Logs>(
- params.sql ? `${API_URL}/projects/${projectRef}/analytics/endpoints/logs.all?${queryParams}` : null,
+ params.sql
+ ? `${API_URL}/projects/${projectRef}/analytics/endpoints/logs.all?${queryParams}`
+ : null,
get,
{ revalidateOnFocus: false }
)
@@ -51,7 +55,7 @@ const useLogsQuery = (
return [
{ params, isLoading, logData: data?.result ? data?.result : [], error },
- { changeQuery, runQuery: () => mutate() },
+ { changeQuery, runQuery: () => mutate(), setParams },
]
}
export default useLogsQuery
diff --git a/studio/pages/project/[ref]/logs-explorer/index.tsx b/studio/pages/project/[ref]/logs-explorer/index.tsx
index 85059a869e4..21459b15fa4 100644
--- a/studio/pages/project/[ref]/logs-explorer/index.tsx
+++ b/studio/pages/project/[ref]/logs-explorer/index.tsx
@@ -22,32 +22,42 @@ import toast from 'react-hot-toast'
export const LogsExplorerPage: NextPage = () => {
const router = useRouter()
- const { ref, q } = router.query
+ const { ref, q, ite, its } = router.query
const [editorId, setEditorId] = useState<string>(uuidv4())
const [editorValue, setEditorValue] = useState<string>('')
const [saveModalOpen, setSaveModalOpen] = useState<boolean>(false)
const { content } = useStore()
- const [{ logData, error, isLoading }, { changeQuery, runQuery }] = useLogsQuery(ref as string)
+ const [{ params, logData, error, isLoading }, { changeQuery, runQuery, setParams }] =
+ useLogsQuery(ref as string)
useEffect(() => {
// on mount, set initial values
- if (q !== undefined && q !== '') {
- changeQuery(q as string)
- runQuery()
+ if (q) {
onSelectTemplate({
mode: 'custom',
searchString: q as string,
})
}
- }, [q])
+ if (its || ite) {
+ setParams((prev) => ({
+ ...prev,
+ iso_timestamp_start: (its || '') as string,
+ iso_timestamp_end: (ite || '') as string,
+ }))
+ }
+ }, [])
const onSelectTemplate = (template: LogTemplate) => {
setEditorValue(template.searchString)
changeQuery(template.searchString)
setEditorId(uuidv4())
runQuery()
+ router.push({
+ pathname: router.pathname,
+ query: { ...router.query, q: template.searchString },
+ })
}
const handleRun = () => {
@@ -74,11 +84,26 @@ export const LogsExplorerPage: NextPage = () => {
setSaveModalOpen(!saveModalOpen)
}
+ const handleDateChange = ({ to, from }: { to: string; from: string }) => {
+ setParams((prev) => ({
+ ...prev,
+ iso_timestamp_start: from,
+ iso_timestamp_end: to,
+ }))
+ router.push({
+ pathname: router.pathname,
+ query: { ...router.query, its: from, ite: to },
+ })
+ }
+
return (
<LogsExplorerLayout>
<div className="h-full flex flex-col flex-grow gap-4">
<div className="border rounded">
<LogsQueryPanel
+ defaultFrom={params.iso_timestamp_start!}
+ defaultTo={params.iso_timestamp_end!}
+ onDateChange={handleDateChange}
onSelectSource={handleInsertSource}
onClear={handleClear}
onRun={handleRun}
diff --git a/studio/tests/pages/projects/LogsQueryPanel.test.js b/studio/tests/pages/projects/LogsQueryPanel.test.js
index 0eeb11152c5..ab57bc4313d 100644
--- a/studio/tests/pages/projects/LogsQueryPanel.test.js
+++ b/studio/tests/pages/projects/LogsQueryPanel.test.js
@@ -22,5 +22,4 @@ test('run and clear', async () => {
const clear = await screen.findByText(/Clear/)
userEvent.click(clear)
expect(mockClear).toBeCalled()
-
})
diff --git a/studio/tests/pages/projects/logs-query.test.js b/studio/tests/pages/projects/logs-query.test.js
index 3979f81ef69..10f45aa6ac3 100644
--- a/studio/tests/pages/projects/logs-query.test.js
+++ b/studio/tests/pages/projects/logs-query.test.js
@@ -62,7 +62,8 @@ const LogsExplorerPage = (props) => (
import { render, fireEvent, waitFor, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { logDataFixture } from '../../fixtures'
-
+import { clickDropdown } from 'tests/helpers'
+import dayjs from 'dayjs'
beforeEach(() => {
// reset mocks between tests
get.mockReset()
@@ -80,7 +81,7 @@ test('can display log data', async () => {
}),
],
})
- const {container} = render(<LogsExplorerPage />)
+ const { container } = render(<LogsExplorerPage />)
let editor = container.querySelector('.monaco-editor')
await waitFor(() => {
editor = container.querySelector('.monaco-editor')
@@ -90,7 +91,7 @@ test('can display log data', async () => {
userEvent.type(editor, 'select \ncount(*) as my_count \nfrom edge_logs')
userEvent.click(await screen.findByText(/Run/))
- const row = await screen.findByText("some-event-happened")
+ const row = await screen.findByText('some-event-happened')
userEvent.click(row)
await screen.findByText(/something_value/)
})
@@ -105,6 +106,27 @@ test('q= query param will populate the query input', async () => {
expect(get).toHaveBeenCalledWith(expect.stringContaining('sql=some_query'))
})
})
+test('ite= and its= query param will populate the datepicker', async () => {
+ const router = defaultRouterMock()
+ const start = dayjs().subtract(1, 'day')
+ const end = dayjs()
+ router.query = {
+ ...router.query,
+ type: 'api',
+ q: 'some_query',
+ its: start.toISOString(),
+ ite: end.toISOString(),
+ }
+ useRouter.mockReturnValue(router)
+ render(<LogsExplorerPage />)
+ // should populate editor with the query param
+ await waitFor(() => {
+ expect(get).toHaveBeenCalledWith(
+ expect.stringContaining(encodeURIComponent(start.toISOString()))
+ )
+ expect(get).toHaveBeenCalledWith(expect.stringContaining(encodeURIComponent(end.toISOString())))
+ })
+})
test('custom sql querying', async () => {
get.mockImplementation((url) => {
@@ -155,3 +177,18 @@ test('custom sql querying', async () => {
// should not see chronological features
await expect(screen.findByText(/Load older/)).rejects.toThrow()
})
+
+test('datepicker interaction updates query params', async () => {
+ render(<LogsExplorerPage />)
+ clickDropdown(await screen.findByText(/Last day/))
+ userEvent.click(await screen.findByText(/Last 3 days/))
+
+ const router = useRouter()
+ expect(router.push).toBeCalledWith(
+ expect.objectContaining({
+ query: expect.objectContaining({
+ its: expect.any(String),
+ }),
+ })
+ )
+})