The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
add in clickDropdown helper, radix setup file for dropdown workaroud, added interval dropdown
TzeYiing96daaac848e0
diff --git a/studio/components/interfaces/Home/ProjectUsage.tsx b/studio/components/interfaces/Home/ProjectUsage.tsxindex 02542221b4e..56ce89df5ac 100644--- a/studio/components/interfaces/Home/ProjectUsage.tsx+++ b/studio/components/interfaces/Home/ProjectUsage.tsx@@ -1,31 +1,42 @@import useSWR from 'swr'import dayjs from 'dayjs'import Link from 'next/link'-import { FC } from 'react'+import { FC, useState } from 'react'import { useRouter } from 'next/router'-import { IconArchive, IconDatabase, IconKey, IconZap, Typography } from '@supabase/ui'+import {+ IconArchive,+ IconDatabase,+ IconKey,+ IconZap,+ Typography,+ Button,+ Dropdown,+} from '@supabase/ui'import Panel from 'components/to-be-cleaned/Panel'import ChartHandler from 'components/to-be-cleaned/Charts/ChartHandler'import { ProjectUsageMinimal } from 'components/to-be-cleaned/Usage'-import { useIsActive } from 'hooks'import { get } from 'lib/common/fetch'import { API_URL, METRICS, DATE_FORMAT } from 'lib/constants'const DATETIME_FORMAT = 'MMM D, ha'-+const CHART_INTERVALS = [+ ['minutely', '60 minutes'],+ ['hourly', '24 hours'],+ ['daily', '7 days'],+]interface Props {project: any}const ProjectUsage: FC<Props> = ({ project }) => {+ const [interval, setInterval] = useState<string>('minutely')const router = useRouter()const { ref } = router.query- const isActive = useIsActive()const { data, error }: any = useSWR(// only fetch when browser window is active- `${API_URL}/projects/${ref}/log-stats`,+ `${API_URL}/projects/${ref}/log-stats?interval=${interval}`,get// increase refresh rate x10 to 30s when focus lost// conditional fetching will cause cached data to clear (not desirable)@@ -34,10 +45,30 @@ const ProjectUsage: FC<Props> = ({ project }) => {const startDate = dayjs().subtract(7, 'day').format(DATE_FORMAT)const endDate = dayjs().format(DATE_FORMAT)const charts = data?.data-+ const selectedInterval = CHART_INTERVALS.find(([k, _l]) => k === interval) || CHART_INTERVALS[1]return (<div className="mx-6 space-y-6">- <Typography.Title level={4}>Statistics for past 24 hours</Typography.Title>+ <div className="flex flex-row justify-between w-full">+ <Typography.Title level={4}>Statistics for past {selectedInterval[1]}</Typography.Title>++ <Dropdown+ side="bottom"+ align="center"+ overlay={+ <>+ <Dropdown.RadioGroup value={interval} onChange={setInterval}>+ {CHART_INTERVALS.map(([k, l]) => (+ <Dropdown.Radio key={k} value={k}>+ <Typography.Text>{l}</Typography.Text>+ </Dropdown.Radio>+ ))}+ </Dropdown.RadioGroup>+ </>+ }+ >+ <Button type="outline">{selectedInterval[1]}</Button>+ </Dropdown>+ </div><div className="">{startDate && endDate && (<div className="grid lg:grid-cols-4 lg:gap-8">diff --git a/studio/jest.config.js b/studio/jest.config.jsindex b36d3b52c99..b07758343ba 100644--- a/studio/jest.config.js+++ b/studio/jest.config.js@@ -1,7 +1,7 @@module.exports = {moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],moduleDirectories: ['<rootDir>', 'node_modules'],- setupFiles: ["jest-canvas-mock"],+ setupFiles: ["jest-canvas-mock", "./tests/setup/radix"],testEnvironment: 'jsdom',testRegex: '(.*\\.test.(js|jsx|ts|tsx)$)',transform: { '^.+\\.(t|j)sx?$': 'ts-jest' },diff --git a/studio/tests/components/Home/ProjectUsage.test.js b/studio/tests/components/Home/ProjectUsage.test.jsindex e87eb1142fd..c2f6860bf32 100644--- a/studio/tests/components/Home/ProjectUsage.test.js+++ b/studio/tests/components/Home/ProjectUsage.test.js@@ -1,4 +1,3 @@-import ProjectUsage from 'components/interfaces/Home/ProjectUsage'import { render, waitFor, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'jest.mock('lib/common/fetch')@@ -7,43 +6,84 @@ import { get } from 'lib/common/fetch'// mock the routerjest.mock('next/router')import { useRouter } from 'next/router'+import { clickDropdown } from 'tests/helpers'useRouter.mockReturnValue({ query: { ref: '123' } })+// need to wrap component with SWRConfig in order to clear cache between tests+// TODO: abstract out to global setup+import { SWRConfig } from 'swr'+const ProjectUsage = jest.fn()+ProjectUsage.mockImplementation((props) => {+ const Original = jest.requireActual('components/interfaces/Home/ProjectUsage').default+ // wrap with SWR to reset the cache each time+ return (+ <SWRConfig value={{ provider: () => new Map() }}>+ <Original {...props} />+ </SWRConfig>+ )+})++beforeEach(() => {get.mockReset()})+const MOCK_CHART_DATA = {+ data: [+ {+ total_auth_requests: 123,+ total_realtime_requests: 223,+ total_storage_requests: 323,+ total_rest_requests: 333,+ timestamp: new Date().getTime() / 1000,+ },+ ],+ total: 123 + 223 + 323,+ totalAverage: 123 + 223 + 323,+ totalGrouped: {+ total_auth_requests: 123,+ total_realtime_requests: 223,+ total_storage_requests: 323,+ total_rest_requests: 333,+ },+}+test('mounts correctly', async () => {get.mockImplementation((url) => {if (url.includes('usage')) return {}- return {- data: {- data: [- {- total_auth_requests: 123,- total_realtime_requests: 223,- total_storage_requests: 323,- total_rest_requests: 333,- timestamp: new Date().getTime() / 1000,- },- ],- total: 123 + 223 + 323,- totalAverage: 123 + 223 + 323,- totalGrouped: {- total_auth_requests: 123,- total_realtime_requests: 223,- total_storage_requests: 323,- total_rest_requests: 333,- },- },- }+ return { data: MOCK_CHART_DATA }})render(<ProjectUsage project="12345" />)- await waitFor(() => screen.getByText('Statistics for past 24 hours'))+ await waitFor(() => screen.getByText(/Statistics for past 60 minutes/))await waitFor(() => screen.getByText(/123/))await waitFor(() => screen.getByText(/223/))await waitFor(() => screen.getByText(/323/))await waitFor(() => screen.getByText(/333/))})-test.todo('dropdown options changes chart query')+test('dropdown options changes chart query', async () => {+ get.mockImplementation((url) => {+ console.log(url)+ if (url.includes('usage')) return {}+ return { data: MOCK_CHART_DATA }+ })+ render(<ProjectUsage project="12345" />)+ await waitFor(() => screen.getByText(/Statistics for past 60 minutes/))+ await waitFor(() => screen.getAllByRole('button', { name: '60 minutes' }))+ console.log(get.mock.calls)+ await waitFor(()=>{+ expect(get).toHaveBeenCalledWith(expect.stringContaining('interval=minutely'))++ })+ // find button that has radix id+ const [btn] = screen.getAllByRole('button', { name: '60 minutes' }).filter((e) => e.id)+ clickDropdown(btn)+ await waitFor(() => screen.getByText(/7 days/))+ await waitFor(() => screen.getByText(/24 hours/))++ // simulate changing of dropdown+ userEvent.click(screen.getByText(/24 hours/))+ await waitFor(() => screen.getByText(/Statistics for past 24 hours/))+ expect(get).toHaveBeenCalledWith(expect.stringContaining('interval=hourly'))++})\ No newline at end of filediff --git a/studio/tests/helpers.ts b/studio/tests/helpers.tsindex 2e622dcdc6b..0b785005932 100644--- a/studio/tests/helpers.ts+++ b/studio/tests/helpers.ts@@ -1,5 +1,4 @@-import { screen, getByText } from '@testing-library/react'-+import { screen, getByText, fireEvent } from '@testing-library/react'interface SelectorOptions {container?: HTMLElement}@@ -24,4 +23,14 @@ export const getToggleByText = (text: string | RegExp, options: SelectorOptionsreturn textNode}+}++export const clickDropdown = (elem: HTMLElement) => {+ fireEvent.pointerDown(+ elem,+ new window.PointerEvent('pointerdown', {+ ctrlKey: false,+ button: 0,+ })+ );}\ No newline at end of filediff --git a/studio/tests/setup/radix.js b/studio/tests/setup/radix.jsnew file mode 100644index 00000000000..84e704ffc1d--- /dev/null+++ b/studio/tests/setup/radix.js@@ -0,0 +1,53 @@+/**+ * Required setup adapted from https://github.com/radix-ui/primitives/issues/856#issuecomment-928704064+ *+ * Implements a custom PointerEvent that can then be used to trigger the radix dropdown.+ * This is required as JSdom has not implemented the PointerEvent (see https://github.com/testing-library/react-testing-library/issues/838#issuecomment-735259406)+ *+ * Furthermore, ResizeObserver and DomRect are both not available in JSdom (see https://github.com/radix-ui/primitives/issues/856)+ *+ * Effects of this setup file:+ * - sets PointerEvent to window+ * - sets ResizeObserver to window+ * - sets DOMRect to window+ *+ * Needed to interact with dropdown components, with the `clickDropdown` helper.+ */++class PointerEvent extends Event {+ constructor(type, props) {+ super(type, props)+ if (props.button != null) {+ this.button = props.button+ }+ if (props.ctrlKey != null) {+ this.ctrlKey = props.ctrlKey+ }+ }+}++window.PointerEvent = PointerEvent;++// https://github.com/radix-ui/primitives/issues/420#issuecomment-771615182+window.ResizeObserver = class ResizeObserver {+ constructor(cb) {+ this.cb = cb;+ }+ observe() {+ this.cb([{ borderBoxSize: { inlineSize: 0, blockSize: 0 } }]);+ }+ unobserve() {}+ disconnect() {}+};++window.DOMRect = {+ fromRect: () => ({+ top: 0,+ left: 0,+ bottom: 0,+ right: 0,+ width: 0,+ height: 0,+ }),+};+diff --git a/studio/tsconfig.test.json b/studio/tsconfig.test.jsonindex 4fd5045d7dc..ef182dc954a 100644--- a/studio/tsconfig.test.json+++ b/studio/tsconfig.test.json@@ -1,6 +1,8 @@{"extends": "./tsconfig.json","compilerOptions": {+ // minimal target of es6 required for extending Event using es6 class features, see radix setup file (tests/setup/radix.js)+ "target": "es6","jsx": "react-jsx"}}