Skip to content

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

Move grid files

Terry Sutton639214f13ed7
diff --git a/studio/components/grid/SupabaseGrid.tsx b/studio/components/grid/SupabaseGrid.tsx
new file mode 100644
index 00000000000..4f192d036d5
--- /dev/null
+++ b/studio/components/grid/SupabaseGrid.tsx
@@ -0,0 +1,159 @@
+import React from 'react';
+import { createPortal } from 'react-dom';
+import { useMonaco } from '@monaco-editor/react';
+import { DndProvider } from 'react-dnd';
+import { HTML5Backend } from 'react-dnd-html5-backend';
+import { Dictionary, SupabaseGridProps, SupabaseGridRef } from './types';
+import { DataGridHandle } from '@supabase/react-data-grid';
+import { RowContextMenu } from './components/menu';
+import { StoreProvider, useDispatch, useTrackedState } from './store';
+import { fetchCount, fetchPage, refreshPageDebounced } from './utils';
+import { REFRESH_PAGE_IMMEDIATELY, TOTAL_ROWS_RESET } from './constants';
+import { Grid } from './components/grid';
+import { Shortcuts } from './components/common';
+import Header from './components/header';
+import Footer from './components/footer';
+import {
+ cleanupProps,
+ initTable,
+ saveStorageDebounced,
+} from './SupabaseGrid.utils';
+
+/**
+ * Supabase Grid.
+ *
+ * React component to render database table.
+ */
+export const SupabaseGrid = React.forwardRef<
+ SupabaseGridRef,
+ SupabaseGridProps
+>((props, ref) => {
+ const monaco = useMonaco();
+ const _props = cleanupProps(props);
+ const { theme } = _props;
+
+ React.useEffect(() => {
+ if (monaco) {
+ const darkTheme = theme && theme === 'dark' ? true : false;
+
+ monaco.editor.defineTheme('supabase', {
+ base: 'vs-dark', // can also be vs-dark or hc-black
+ inherit: true, // can also be false to completely replace the builtin rules
+ rules: [
+ { token: 'string.sql', foreground: '24b47e' },
+ { token: 'comment', foreground: '666666' },
+ { token: 'predefined.sql', foreground: 'D4D4D4' },
+ ],
+ colors: {
+ 'editor.background': darkTheme ? '#1f1f1f' : '#30313f',
+ },
+ });
+ }
+ }, [monaco]);
+
+ return (
+ <StoreProvider>
+ <DndProvider backend={HTML5Backend}>
+ <SupabaseGridLayout ref={ref} {..._props} />
+ </DndProvider>
+ </StoreProvider>
+ );
+});
+
+const SupabaseGridLayout = React.forwardRef<SupabaseGridRef, SupabaseGridProps>(
+ (props, ref) => {
+ const { editable, storageRef, gridProps, headerActions } = props;
+ const dispatch = useDispatch();
+ const state = useTrackedState();
+ const gridRef = React.useRef<DataGridHandle>(null);
+ const [mounted, setMount] = React.useState(false);
+
+ React.useImperativeHandle(ref, () => ({
+ rowAdded(row: Dictionary<any>) {
+ dispatch({
+ type: 'ADD_NEW_ROW',
+ payload: row,
+ });
+ },
+ rowEdited(row: Dictionary<any>, idx: number) {
+ dispatch({
+ type: 'EDIT_ROW',
+ payload: { row, idx },
+ });
+ },
+ }));
+
+ React.useEffect(() => {
+ if (!mounted) setMount(true);
+ }, []);
+
+ React.useEffect(() => {
+ if (state.isInitialComplete && storageRef && state.table) {
+ saveStorageDebounced(state, storageRef);
+ }
+ }, [
+ state.table,
+ state.isInitialComplete,
+ state.gridColumns,
+ state.sorts,
+ state.filters,
+ storageRef,
+ ]);
+
+ React.useEffect(() => {
+ if (state.refreshPageFlag == REFRESH_PAGE_IMMEDIATELY) {
+ fetchPage(state, dispatch);
+ } else if (state.refreshPageFlag != 0) {
+ refreshPageDebounced(state, dispatch);
+ }
+ }, [state.refreshPageFlag]);
+
+ React.useEffect(() => {
+ if (state.totalRows === TOTAL_ROWS_RESET) {
+ fetchCount(state, dispatch);
+ }
+ }, [state.totalRows]);
+
+ React.useEffect(() => {
+ if (!state.metaService) {
+ dispatch({
+ type: 'INIT_CLIENT',
+ payload: { onSqlQuery: props.onSqlQuery },
+ });
+ dispatch({
+ type: 'INIT_CALLBACK',
+ payload: { ...props },
+ });
+ }
+ }, [state.metaService]);
+
+ React.useEffect(() => {
+ if (!state.metaService) return;
+
+ if (
+ !state.table ||
+ (typeof props.table == 'string' &&
+ state.table!.name != props.table &&
+ state.table!.schema != props.schema) ||
+ (typeof props.table != 'string' &&
+ JSON.stringify(props.table) !== JSON.stringify(state.table))
+ ) {
+ initTable(props, state, dispatch);
+ }
+ }, [state.metaService, state.table, props.table, props.schema]);
+
+ return (
+ <div className="sb-grid">
+ <Header
+ onAddRow={editable ? props.onAddRow : undefined}
+ onAddColumn={editable ? props.onAddColumn : undefined}
+ headerActions={headerActions}
+ />
+ <Grid ref={gridRef} {...gridProps} />
+ <Footer />
+ <Shortcuts gridRef={gridRef} />
+ {mounted && createPortal(<RowContextMenu />, document.body)}
+ </div>
+ );
+ }
+);
diff --git a/studio/components/grid/SupabaseGrid.utils.ts b/studio/components/grid/SupabaseGrid.utils.ts
new file mode 100644
index 00000000000..d3f65bf7833
--- /dev/null
+++ b/studio/components/grid/SupabaseGrid.utils.ts
@@ -0,0 +1,223 @@
+import AwesomeDebouncePromise from 'awesome-debounce-promise';
+import { STORAGE_KEY_PREFIX } from './constants';
+import { IMetaService } from './services/meta';
+import { InitialStateType } from './store/reducers';
+import { Dictionary, SupabaseGridProps, SupaColumn, SupaTable } from './types';
+import { getGridColumns } from './utils/gridColumns';
+
+export function defaultErrorHandler(error: any) {
+ console.log('Supabase grid error: ', error);
+}
+
+/**
+ * Ensure that if editable is false, we should remove all editing actions
+ * to prevent rare-case bugs with the UI
+ */
+export function cleanupProps(props: SupabaseGridProps) {
+ const { editable } = props;
+ if (!editable) {
+ return {
+ ...props,
+ onAddColumn: undefined,
+ onAddRow: undefined,
+ onEditColumn: undefined,
+ onDeleteColumn: undefined,
+ onEditRow: undefined,
+ };
+ } else {
+ return props;
+ }
+}
+
+export function initTable(
+ props: SupabaseGridProps,
+ state: InitialStateType,
+ dispatch: (value: any) => void
+) {
+ function onInitTable(table: SupaTable, props: SupabaseGridProps) {
+ const gridColumns = getGridColumns(table, {
+ editable: props.editable,
+ defaultWidth: props.gridProps?.defaultColumnWidth,
+ onAddColumn: props.editable ? props.onAddColumn : undefined,
+ });
+
+ let savedState;
+ if (props.storageRef) {
+ savedState = onLoadStorage(props.storageRef, table.name, table.schema);
+ }
+
+ dispatch({
+ type: 'INIT_TABLE',
+ payload: {
+ table,
+ gridProps: props.gridProps,
+ gridColumns,
+ savedState,
+ editable: props.editable,
+ onSqlQuery: props.onSqlQuery,
+ onError: props.onError ?? defaultErrorHandler,
+ },
+ });
+ }
+
+ if (typeof props.table === 'string') {
+ const fetchMethod = props.editable
+ ? fetchEditableInfo(state.metaService!, props.table, props.schema)
+ : fetchReadOnlyInfo(state.metaService!, props.table, props.schema);
+
+ fetchMethod.then((res) => {
+ if (res) onInitTable(res, props);
+ else {
+ if (props.onError) {
+ props.onError({ message: 'fetch table info failed' });
+ }
+ }
+ });
+ } else {
+ onInitTable(props.table, props);
+ }
+}
+
+async function fetchEditableInfo(
+ service: IMetaService,
+ tableName: string,
+ schema?: string
+): Promise<SupaTable | null> {
+ const resTable = await service.fetchInfo(tableName, schema);
+ const resColumns = await service.fetchColumns(tableName, schema);
+ const resPrimaryKeys = await service.fetchPrimaryKeys(tableName, schema);
+ const resRelationships = await service.fetchRelationships(tableName, schema);
+ if (
+ resTable.data &&
+ resColumns.data &&
+ resPrimaryKeys.data &&
+ resRelationships.data &&
+ resColumns.data.length > 0
+ ) {
+ const supaTable = parseSupaTable({
+ table: resTable.data,
+ columns: resColumns.data,
+ primaryKeys: resPrimaryKeys.data,
+ relationships: resRelationships.data,
+ });
+ return supaTable;
+ }
+ return null;
+}
+
+async function fetchReadOnlyInfo(
+ service: IMetaService,
+ name: string,
+ schema?: string
+): Promise<SupaTable | null> {
+ const { data } = await service.fetchColumns(name, schema);
+
+ if (data) {
+ const supaColumns: SupaColumn[] = data.map((x, index) => {
+ return {
+ name: x.name,
+ dataType: x.format,
+ format: x.format,
+ position: index,
+ isUpdatable: false,
+ };
+ });
+
+ return {
+ name: name,
+ schema: schema,
+ columns: supaColumns,
+ };
+ }
+ return null;
+}
+
+export function parseSupaTable(data: {
+ table: Dictionary<any>;
+ columns: Dictionary<any>[];
+ primaryKeys: Dictionary<any>[];
+ relationships: Dictionary<any>[];
+}): SupaTable {
+ const { table, columns, primaryKeys, relationships } = data;
+ const supaColumns: SupaColumn[] = columns.map((x) => {
+ const temp = {
+ position: x.ordinal_position,
+ name: x.name,
+ defaultValue: x.default_value,
+ dataType: x.data_type,
+ format: x.format,
+ isPrimaryKey: false,
+ isIdentity: x.is_identity,
+ isGeneratable: x.identity_generation == 'BY DEFAULT',
+ isNullable: x.is_nullable,
+ isUpdatable: x.is_updatable,
+ enum: x.enums,
+ comment: x.comment,
+ targetTableSchema: null,
+ targetTableName: null,
+ targetColumnName: null,
+ };
+ const primaryKey = primaryKeys.find((pk) => pk.name == x.name);
+ temp.isPrimaryKey = !!primaryKey;
+
+ const relationship = relationships.find((r) => {
+ return r.source_column_name == x.name;
+ });
+ if (relationship) {
+ temp.targetTableSchema = relationship.target_table_schema;
+ temp.targetTableName = relationship.target_table_name;
+ temp.targetColumnName = relationship.target_column_name;
+ }
+ return temp;
+ });
+
+ return {
+ name: table.name,
+ comment: table.comment,
+ schema: table.schema,
+ columns: supaColumns,
+ };
+}
+
+export function onLoadStorage(
+ storageRef: string,
+ tableName: string,
+ schema?: string | null
+) {
+ const storageKey = getStorageKey(STORAGE_KEY_PREFIX, storageRef);
+ const jsonStr = localStorage.getItem(storageKey);
+ if (!jsonStr) return;
+ const json = JSON.parse(jsonStr);
+ const tableKey =
+ !schema || schema == 'public' ? tableName : `${schema}.${tableName}`;
+ return json[tableKey];
+}
+
+export const saveStorageDebounced = AwesomeDebouncePromise(saveStorage, 500);
+
+function saveStorage(state: InitialStateType, storageRef: string) {
+ if (!state.table) return;
+
+ const config = {
+ gridColumns: state.gridColumns,
+ sorts: state.sorts,
+ filters: state.filters,
+ };
+ const storageKey = getStorageKey(STORAGE_KEY_PREFIX, storageRef);
+ const savedStr = localStorage.getItem(storageKey);
+
+ let savedJson;
+ const { name, schema } = state.table;
+ const tableKey = !schema || schema == 'public' ? name : `${schema}.${name}`;
+ if (savedStr) {
+ savedJson = JSON.parse(savedStr);
+ savedJson = { ...savedJson, [tableKey]: config };
+ } else {
+ savedJson = { [tableKey]: config };
+ }
+ localStorage.setItem(storageKey, JSON.stringify(savedJson));
+}
+
+function getStorageKey(prefix: string, ref: string) {
+ return `${prefix}_${ref}`;
+}
diff --git a/studio/components/grid/components/common/BlockKeys.tsx b/studio/components/grid/components/common/BlockKeys.tsx
new file mode 100644
index 00000000000..a78eefb17d6
--- /dev/null
+++ b/studio/components/grid/components/common/BlockKeys.tsx
@@ -0,0 +1,45 @@
+import * as React from 'react';
+
+type BlockKeysProps = {
+ onEscape?: (value: string | null) => void;
+ onEnter?: (value: string | null) => void;
+ value: string | null;
+};
+
+/**
+ * Blocks key events from propagating
+ * We use this with cell editor to allow editor component to handle keys.
+ * Example: press enter to add newline on textEditor
+ */
+export const BlockKeys: React.FC<BlockKeysProps> = ({
+ onEscape,
+ onEnter,
+ value,
+ children,
+}) => {
+ const handleKeyDown = React.useCallback(
+ (ev: React.KeyboardEvent<HTMLDivElement>) => {
+ switch (ev.key) {
+ case 'Escape':
+ ev.stopPropagation();
+ if (onEscape) onEscape(value);
+ break;
+ case 'Enter':
+ ev.stopPropagation();
+ if (onEnter) onEnter(value);
+ break;
+ }
+ },
+ [value]
+ );
+
+ function onBlur() {
+ if (onEscape) onEscape(value);
+ }
+
+ return (
+ <div onKeyDown={handleKeyDown} onBlur={onBlur}>
+ {children}
+ </div>
+ );
+};
diff --git a/studio/components/grid/components/common/ConfirmAlert.tsx b/studio/components/grid/components/common/ConfirmAlert.tsx
new file mode 100644
index 00000000000..d1e0dd7f03a
--- /dev/null
+++ b/studio/components/grid/components/common/ConfirmAlert.tsx
@@ -0,0 +1,98 @@
+import * as React from 'react';
+import { Button, Modal } from '@supabase/ui';
+import { render, unmountComponentAtNode } from 'react-dom';
+
+type ConfirmModalProps = {
+ title: string;
+ message: string;
+ onConfirm?: () => void;
+ onAsyncConfirm?: () => Promise<void>;
+ variant?: 'danger' | 'warning' | 'success' | undefined;
+};
+const ConfirmModal: React.FC<ConfirmModalProps> = ({
+ title,
+ message,
+ onConfirm,
+ onAsyncConfirm,
+ variant = 'danger',
+}) => {
+ const [loading, setLoading] = React.useState(false);
+
+ function onCancelClick() {
+ if (!loading) onClose();
+ }
+
+ async function onConfirmClick() {
+ if (onAsyncConfirm) {
+ setLoading(true);
+ await onAsyncConfirm();
+
+ onClose();
+ } else if (onConfirm) {
+ onConfirm();
+ onClose();
+ }
+ }
+
+ function onClose() {
+ removeElement();
+ }
+
+ return (
+ <Modal
+ variant={variant}
+ visible={true}
+ header={title}
+ showIcon={false}
+ size="small"
+ confirmText="OK"
+ cancelText="Cancel"
+ onCancel={onCancelClick}
+ loading={loading}
+ customFooter={
+ <>
+ <div className="flex items-center gap-2">
+ <Button type="default" onClick={() => onCancelClick()}>
+ Cancel
+ </Button>
+ <Button
+ type="primary"
+ loading={loading}
+ onClick={() => onConfirmClick()}
+ >
+ Confirm
+ </Button>
+ </div>
+ </>
+ }
+ >
+ <Modal.Content>
+ <p className="text-sm text-scale-1100">{message}</p>
+ </Modal.Content>
+ </Modal>
+ );
+};
+
+function removeElement() {
+ const target = document.getElementById('supabase-ui-confirm-alert');
+ if (target) {
+ unmountComponentAtNode(target);
+ target?.parentNode?.removeChild(target);
+ }
+}
+
+function createElement(props: ConfirmModalProps) {
+ let divTarget = document.getElementById('supabase-ui-confirm-alert');
+ if (divTarget) {
+ render(<ConfirmModal {...props} />, divTarget);
+ } else {
+ divTarget = document.createElement('div');
+ divTarget.id = 'supabase-ui-confirm-alert';
+ document.body.appendChild(divTarget);
+ render(<ConfirmModal {...props} />, divTarget);
+ }
+}
+
+export function showConfirmAlert(props: ConfirmModalProps) {
+ createElement(props);
+}
diff --git a/studio/components/grid/components/common/DropdownControl.tsx b/studio/components/grid/components/common/DropdownControl.tsx
new file mode 100644
index 00000000000..0a00a4d2436
--- /dev/null
+++ b/studio/components/grid/components/common/DropdownControl.tsx
@@ -0,0 +1,63 @@
+import * as React from 'react';
+import { Dropdown, Typography } from '@supabase/ui';
+
+type DropdownControlProps = {
+ options: {
+ value: string | number;
+ label: string;
+ postLabel?: string;
+ preLabel?: string;
+ }[];
+ onSelect: (value: string | number) => void;
+ className?: string;
+ side?: 'bottom' | 'left' | 'top' | 'right' | undefined;
+ align?: 'start' | 'center' | 'end' | undefined;
+ isNested?: boolean;
+};
+
+export const DropdownControl: React.FC<DropdownControlProps> = (p) => {
+ const { className, children, side, align, isNested } = p;
+ return (
+ <Dropdown
+ className={className}
+ side={side}
+ align={align}
+ overlay={<DropdownItems {...p} />}
+ isNested={isNested}
+ >
+ {children}
+ </Dropdown>
+ );
+};
+
+const DropdownItems: React.FC<DropdownControlProps> = ({
+ options,
+ onSelect,
+}) => {
+ return (
+ <div className="dropdown-control" style={{ maxHeight: '30vh' }}>
+ {options.length == 0 && (
+ <Typography.Text className="dropdown-control__empty-text">
+ No more items
+ </Typography.Text>
+ )}
+ {options.map((x) => {
+ return (
+ <Dropdown.Item key={x.value} onClick={() => onSelect(x.value)}>
+ <div className="flex items-center gap-2">
+ {x.preLabel && (
+ <span className="text-xs text-scale-900 grow">
+ {x.preLabel}
+ </span>
+ )}
+ <span>{x.label}</span>
+ {x.postLabel && (
+ <span className="text-xs text-scale-900">{x.postLabel}</span>
+ )}
+ </div>
+ </Dropdown.Item>
+ );
+ })}
+ </div>
+ );
+};
diff --git a/studio/components/grid/components/common/EmptyValue.tsx b/studio/components/grid/components/common/EmptyValue.tsx
new file mode 100644
index 00000000000..1a32e29aaf5
--- /dev/null
+++ b/studio/components/grid/components/common/EmptyValue.tsx
@@ -0,0 +1,11 @@
+import * as React from 'react';
+
+type EmptyValueProps = {};
+
+export const EmptyValue: React.FC<EmptyValueProps> = ({}) => {
+ return (
+ <span className="sb-grid-empty-value" style={{ opacity: 0.5 }}>
+ EMPTY
+ </span>
+ );
+};
diff --git a/studio/components/grid/components/common/ForeignTableModal/FilterHeader.tsx b/studio/components/grid/components/common/ForeignTableModal/FilterHeader.tsx
new file mode 100644
index 00000000000..150d1630825
--- /dev/null
+++ b/studio/components/grid/components/common/ForeignTableModal/FilterHeader.tsx
@@ -0,0 +1,122 @@
+import React, { FC, useState } from 'react';
+import { Button, Input, IconChevronDown, IconSearch } from '@supabase/ui';
+import { DropdownControl } from '../../common';
+import { FilterOperatorOptions } from '../../header/filter';
+import { Filter, FilterOperator } from '../../../types';
+import AwesomeDebouncePromise from 'awesome-debounce-promise';
+
+interface FilterProps {
+ defaultColumnName?: string;
+ defaultValue?: string;
+ foreignColumnNames: string[];
+ onChange: (value: Filter) => void;
+}
+
+export const FilterHeader: FC<FilterProps> = ({
+ defaultColumnName,
+ defaultValue,
+ foreignColumnNames,
+ onChange,
+}) => {
+ const [columnName, setColumnName] = useState(
+ defaultColumnName
+ ? defaultColumnName
+ : foreignColumnNames.length > 0
+ ? foreignColumnNames[0]
+ : ''
+ );
+ const [condition, setCondition] = useState(FilterOperatorOptions[0].value);
+ const [filterText, setFilterText] = useState(defaultValue ?? '');
+
+ const columnOptions =
+ foreignColumnNames.map((x) => {
+ return { value: x, label: x };
+ }) || [];
+
+ function triggerOnChange(
+ columnName: string,
+ condition: string,
+ filterText: string
+ ) {
+ onFilterChangeDebounced(
+ {
+ column: columnName,
+ operator: condition as FilterOperator,
+ value: filterText,
+ },
+ onChange
+ );
+ }
+
+ function onColumnChange(value: string | number) {
+ const str = value + '';
+ setColumnName(str);
+ triggerOnChange(str, condition, filterText);
+ }
+
+ function onConditionChange(value: string | number) {
+ const str = value + '';
+ setCondition(str);
+ triggerOnChange(columnName, str, filterText);
+ }
+
+ function onFilterChange(event: React.ChangeEvent<HTMLInputElement>) {
+ const value = event.target.value;
+ setFilterText(value);
+ triggerOnChange(columnName, condition, value);
+ }
+
+ return (
+ <div className="foreign-table-modal__filter">
+ <DropdownControl
+ side="bottom"
+ align="start"
+ options={columnOptions}
+ onSelect={onColumnChange}
+ >
+ <Button as="span" type="outline" iconRight={<IconChevronDown />}>
+ <span className="foreign-table-modal__filter__trigger-content">
+ <span className="foreign-table-modal__filter__trigger-content__label">
+ Column
+ </span>
+ <span className="foreign-table-modal__filter__trigger-content__name">
+ {columnName}
+ </span>
+ </span>
+ </Button>
+ </DropdownControl>
+ <DropdownControl
+ side="bottom"
+ align="start"
+ options={FilterOperatorOptions}
+ onSelect={onConditionChange}
+ >
+ <Button as="span" type="outline" iconRight={<IconChevronDown />}>
+ <span className="foreign-table-modal__filter__trigger-content">
+ <span className="foreign-table-modal__filter__trigger-content__label">
+ Filter
+ </span>
+ <span className="foreign-table-modal__filter__trigger-content__name">
+ {condition}
+ </span>
+ </span>
+ </Button>
+ </DropdownControl>
+ <Input
+ size="tiny"
+ className="foreign-table-modal__filter__search-input"
+ placeholder="Find a record"
+ value={filterText}
+ onChange={onFilterChange}
+ icon={<IconSearch size="small" />}
+ />
+ </div>
+ );
+};
+
+const onFilterChangeDebounced = AwesomeDebouncePromise(
+ (filter: Filter, onChange: (value: Filter) => void) => {
+ onChange(filter);
+ },
+ 500
+);
diff --git a/studio/components/grid/components/common/ForeignTableModal/RowItem.tsx b/studio/components/grid/components/common/ForeignTableModal/RowItem.tsx
new file mode 100644
index 00000000000..81e65eb660f
--- /dev/null
+++ b/studio/components/grid/components/common/ForeignTableModal/RowItem.tsx
@@ -0,0 +1,46 @@
+import * as React from 'react';
+import { Menu, Typography } from '@supabase/ui';
+import { Dictionary } from '../../../types';
+
+interface RowItemProps {
+ item: Dictionary<any>;
+ onSelect: (item: Dictionary<any>) => void;
+ columnNames: string[],
+}
+
+export const RowItem: React.FC<RowItemProps> = ({ item, onSelect, columnNames }) => {
+ return (
+ <div className="foreign-table-modal__row-item">
+ <Menu.Item onClick={() => onSelect(item)} style={{minWidth: 'min-content'}}>
+ <div className="foreign-table-modal__row-item__inner">
+ {columnNames.map((key, j) => {
+ //
+ // limit to 5 attributes
+ //
+ // this could be improved so the user could pick which attributes to display
+ // @mildtomato
+ if (j > 5) return null;
+
+ return (
+ <div
+ className="foreign-table-modal__row-item__inner__key-item"
+ key={`item-${j}`}
+ >
+ <Typography.Text
+ small
+ type="secondary"
+ className="foreign-table-modal__row-item__inner__key-item__key"
+ >
+ {key}
+ </Typography.Text>
+ <Typography.Text small strong>
+ {item[key] ? (typeof item[key] === 'object') ? JSON.stringify(item[key]) : item[key] : '[null]'}
+ </Typography.Text>
+ </div>
+ );
+ })}
+ </div>
+ </Menu.Item>
+ </div>
+ );
+};
diff --git a/studio/components/grid/components/common/ForeignTableModal/index.tsx b/studio/components/grid/components/common/ForeignTableModal/index.tsx
new file mode 100644
index 00000000000..fb1fd526463
--- /dev/null
+++ b/studio/components/grid/components/common/ForeignTableModal/index.tsx
@@ -0,0 +1,162 @@
+import * as React from 'react';
+import { Button, Modal, Menu, IconExternalLink, IconTrash } from '@supabase/ui';
+import { useTrackedState } from '../../../store';
+import { Dictionary, Filter } from '../../../types';
+import { RowItem } from './RowItem';
+import { FilterHeader } from './FilterHeader';
+import Query from '../../../query';
+
+type ForeignTableModalProps = {
+ columnName?: string;
+ defaultValue?: string;
+ onChange: (value: any | null) => void;
+};
+
+export const ForeignTableModal: React.FC<ForeignTableModalProps> = ({
+ columnName,
+ defaultValue,
+ onChange,
+}) => {
+ const [visible, setVisible] = React.useState(false);
+ const [foreignColumnNames, setForeignColumnNames] = React.useState<string[]>(
+ []
+ );
+ const [rows, setRows] = React.useState<Dictionary<any>[] | null>(null);
+ const state = useTrackedState();
+ const columnDefinition = state.table?.columns.find(
+ (x) => x.name == columnName
+ );
+
+ React.useEffect(() => {
+ if (!visible) return;
+
+ fetchColumns();
+
+ if (defaultValue && columnDefinition) {
+ fetchData({
+ column: columnDefinition.targetColumnName!,
+ operator: '=',
+ value: defaultValue,
+ });
+ } else {
+ fetchData();
+ }
+ }, [visible]);
+
+ async function fetchColumns() {
+ if (
+ !state.metaService ||
+ !columnDefinition?.targetTableName ||
+ !columnDefinition?.targetTableSchema
+ )
+ return;
+
+ const { data } = await state.metaService.fetchColumns(
+ columnDefinition?.targetTableName,
+ columnDefinition?.targetTableSchema
+ );
+ if (data && data.length > 0) {
+ const columnNames = data.map((x) => x.name);
+ setForeignColumnNames(columnNames);
+ }
+ }
+
+ async function fetchData(filter?: Filter) {
+ if (!state.onSqlQuery || !columnDefinition?.targetTableName) return;
+
+ const query = new Query();
+ let queryChains = query
+ .from(
+ columnDefinition?.targetTableName,
+ columnDefinition?.targetTableSchema ?? undefined
+ )
+ .select();
+
+ if (filter && filter.value && filter.value != '') {
+ const { column, operator, value } = filter;
+ queryChains = queryChains.filter(column, operator, value);
+ }
+
+ // TODO: How to let users know that filter result limit at 20 results
+ // should we allow a higher value?
+ const sql = queryChains.range(0, 20).toSql();
+ const { data, error } = await state.onSqlQuery(sql);
+ if (error) {
+ setRows(null);
+ } else {
+ setRows(data);
+ }
+ }
+
+ function toggle(event: React.MouseEvent<HTMLButtonElement, MouseEvent>) {
+ if (event && event.stopPropagation) event.stopPropagation();
+ setVisible(!visible);
+ }
+
+ function onItemSelect(item: Dictionary<any>) {
+ if (item && columnDefinition && columnDefinition.targetColumnName) {
+ const value = item[columnDefinition.targetColumnName];
+ onChange(value);
+ }
+
+ setVisible(false);
+ }
+
+ function renderRows() {
+ if (!rows) return null;
+ const temp = rows.map((x, i) => {
+ return <RowItem key={`menu-${i}`} item={x} onSelect={onItemSelect} columnNames={foreignColumnNames} />;
+ });
+ return <Menu className="foreign-table-modal__menu">{temp}</Menu>;
+ }
+
+ function onFilterChange(filter: Filter) {
+ if (filter && filter.value && filter.value != '') fetchData(filter);
+ }
+
+ function onClearValueClick() {
+ onChange(null);
+ setVisible(false);
+ }
+
+ return (
+ <>
+ <Button
+ type="text"
+ onClick={toggle}
+ icon={<IconExternalLink />}
+ style={{ padding: '3px' }}
+ />
+ <Modal
+ visible={visible}
+ onCancel={toggle}
+ closable
+ customFooter={
+ <Button block danger icon={<IconTrash />} onClick={onClearValueClick}>
+ Clear value
+ </Button>
+ }
+ >
+ <Modal.Content>
+ <FilterHeader
+ defaultColumnName={columnDefinition?.targetColumnName ?? undefined}
+ defaultValue={defaultValue}
+ foreignColumnNames={foreignColumnNames}
+ onChange={onFilterChange}
+ />
+ </Modal.Content>
+ <Modal.Seperator />
+ <Modal.Content>
+ <div className="foreign-table-modal__content-container">
+ <div
+ className="foreign-table-modal__content-container__inner__overflow"
+ style={{ minHeight: '21rem', maxHeight: '20rem' }}
+ >
+ {renderRows()}
+ </div>
+ </div>
+ </Modal.Content>
+ </Modal>
+ </>
+ );
+};
diff --git a/studio/components/grid/components/common/Hooks.tsx b/studio/components/grid/components/common/Hooks.tsx
new file mode 100644
index 00000000000..2efd87710be
--- /dev/null
+++ b/studio/components/grid/components/common/Hooks.tsx
@@ -0,0 +1,81 @@
+import * as React from 'react';
+
+function includes(array: string[], element: string) {
+ return array.indexOf(element) >= 0;
+}
+
+/**
+ * Hook for listening on key events.
+ *
+ * @param {Object|Map} keyMap Key names mapped to event handlers. If a key name exists, its
+ * default behavior will be suppressed.
+ * @param {Array} whitelistNodes If target element is in the whitelist nodes array, will not
+ * trigger shortcut event
+ * @param {Array} whitelistClasses If target class is in the whitelist classes array, will not
+ * trigger shortcut event
+ */
+export function useKeyboardShortcuts(
+ keyMap: { [id: string]: (event: KeyboardEvent) => void },
+ whitelistNodes: string[] = [],
+ whitelistClasses: string[] = []
+) {
+ const [lastKeydown, setLastKeydown] = React.useState<string | null>();
+
+ const handleKeydown = (event: any) => {
+ if (
+ !keyMap ||
+ includes(whitelistNodes, event.target.nodeName) ||
+ includes(whitelistClasses, event.target.className)
+ ) {
+ return;
+ }
+
+ let keyPressed = getKeyPresses(event);
+
+ if (keyMap[keyPressed]) {
+ /**
+ * combined keymap will trigger action on KeyDown event
+ * while single keymap will trigger action on KeyUp event
+ */
+ if (keyPressed.includes('+')) {
+ event.preventDefault();
+ keyMap[keyPressed](event);
+ setLastKeydown(null);
+ } else {
+ setLastKeydown(event.key);
+ event.preventDefault();
+ }
+ }
+ };
+
+ const handleKeyup = (event: any) => {
+ if (!keyMap) return;
+
+ if (keyMap[event.key] && lastKeydown === event.key) {
+ event.preventDefault();
+ keyMap[event.key](event);
+ setLastKeydown(null);
+ }
+ };
+
+ function getKeyPresses(event: KeyboardEvent) {
+ return event.metaKey && event.shiftKey
+ ? `Command+Shift+${event.key}`
+ : event.metaKey
+ ? `Command+${event.key}`
+ : event.shiftKey && event.key === 'Enter'
+ ? `Shift+${event.key}`
+ : event.ctrlKey && event.key
+ ? `Control+${event.key}`
+ : event.key;
+ }
+
+ React.useEffect(() => {
+ window.addEventListener('keydown', handleKeydown);
+ window.addEventListener('keyup', handleKeyup);
+ return () => {
+ window.removeEventListener('keydown', handleKeydown);
+ window.removeEventListener('keyup', handleKeyup);
+ };
+ });
+}
diff --git a/studio/components/grid/components/common/MonacoEditor.tsx b/studio/components/grid/components/common/MonacoEditor.tsx
new file mode 100644
index 00000000000..8ec385d0ce7
--- /dev/null
+++ b/studio/components/grid/components/common/MonacoEditor.tsx
@@ -0,0 +1,72 @@
+import * as React from 'react';
+import Editor from '@monaco-editor/react';
+
+type MonacoEditorProps = {
+ width?: string | number | undefined;
+ height?: string | number | undefined;
+ value?: string | undefined;
+ language?: string | undefined;
+ onChange: (value: string | undefined) => void;
+ onMount?: (editor: any) => void;
+};
+
+export const MonacoEditor: React.FC<MonacoEditorProps> = ({
+ width,
+ height,
+ value,
+ language,
+ onChange,
+ onMount,
+}) => {
+ function handleEditorOnMount(editor: any) {
+ // add margin above first line
+ editor.changeViewZones((accessor: any) => {
+ accessor.addZone({
+ afterLineNumber: 0,
+ heightInPx: 4,
+ domNode: document.createElement('div'),
+ });
+ });
+
+ // move cursor to the end of document
+ const model = editor.getModel();
+ const position = model.getPositionAt(value?.length);
+ editor.setPosition(position);
+
+ // auto focus on mount
+ setTimeout(() => {
+ editor?.focus();
+ }, 0);
+
+ if (onMount) onMount(editor);
+ }
+
+ return (
+ <Editor
+ width={width}
+ height={height || '200px'}
+ theme="supabase"
+ wrapperProps={{
+ className: 'grid-monaco-editor-container',
+ }}
+ className="grid-monaco-editor"
+ defaultLanguage={language || 'plaintext'}
+ defaultValue={value}
+ onChange={onChange}
+ onMount={handleEditorOnMount}
+ options={{
+ tabSize: 2,
+ fontSize: 13,
+ minimap: {
+ enabled: false,
+ },
+ glyphMargin: false,
+ folding: false,
+ lineNumbers: 'off',
+ lineNumbersMinChars: 0,
+ scrollBeyondLastLine: false,
+ wordWrap: 'on',
+ }}
+ />
+ );
+};
diff --git a/studio/components/grid/components/common/NullValue.tsx b/studio/components/grid/components/common/NullValue.tsx
new file mode 100644
index 00000000000..aea4d62ccda
--- /dev/null
+++ b/studio/components/grid/components/common/NullValue.tsx
@@ -0,0 +1,11 @@
+import * as React from 'react';
+
+type NullValueProps = {};
+
+export const NullValue: React.FC<NullValueProps> = ({}) => {
+ return (
+ <span className="null-value" style={{ opacity: 0.5 }}>
+ NULL
+ </span>
+ );
+};
diff --git a/studio/components/grid/components/common/Shortcuts.tsx b/studio/components/grid/components/common/Shortcuts.tsx
new file mode 100644
index 00000000000..3e7f3af6ffc
--- /dev/null
+++ b/studio/components/grid/components/common/Shortcuts.tsx
@@ -0,0 +1,87 @@
+import * as React from 'react';
+import { useTrackedState } from '../../store';
+import { useKeyboardShortcuts } from './Hooks';
+import { DataGridHandle } from '@supabase/react-data-grid';
+import { formatClipboardValue, copyToClipboard } from '../../utils';
+
+type ShortcutsProps = {
+ gridRef: React.RefObject<DataGridHandle>;
+};
+
+export function Shortcuts({ gridRef }: ShortcutsProps) {
+ const state = useTrackedState();
+ const { rows, gridColumns, selectedCellPosition } = state;
+ const [metaKey, setMetaKey] = React.useState('Command');
+
+ React.useEffect(() => {
+ function getClientOS() {
+ return navigator?.appVersion.indexOf('Win') !== -1
+ ? 'windows'
+ : navigator?.appVersion.indexOf('Mac') !== -1
+ ? 'macos'
+ : 'unknown';
+ }
+ const metakey = getClientOS() === 'windows' ? 'Control' : 'Command';
+ setMetaKey(metakey);
+ }, []);
+
+ useKeyboardShortcuts(
+ {
+ [`${metaKey}+ArrowUp`]: event => {
+ event.stopPropagation();
+ if (selectedCellPosition) {
+ const position = {
+ idx: selectedCellPosition?.idx ?? 0,
+ rowIdx: 0,
+ };
+ gridRef.current!.selectCell(position);
+ } else {
+ gridRef.current!.scrollToRow(Number(0));
+ }
+ },
+ [`${metaKey}+ArrowDown`]: event => {
+ event.stopPropagation();
+ if (selectedCellPosition) {
+ const position = {
+ idx: selectedCellPosition?.idx ?? 0,
+ rowIdx: rows.length > 1 ? rows.length - 1 : 0,
+ };
+ gridRef.current!.selectCell(position);
+ } else {
+ gridRef.current!.scrollToRow(Number(rows.length));
+ }
+ },
+ [`${metaKey}+ArrowLeft`]: event => {
+ event.stopPropagation();
+ const fronzenColumns = gridColumns.filter(x => x.frozen);
+ const position = {
+ idx: fronzenColumns.length,
+ rowIdx: selectedCellPosition?.rowIdx ?? 0,
+ };
+ gridRef.current!.selectCell(position);
+ },
+ [`${metaKey}+ArrowRight`]: event => {
+ event.stopPropagation();
+ gridRef.current?.selectCell({
+ idx: gridColumns.length - 1,
+ rowIdx: selectedCellPosition?.rowIdx ?? 0,
+ });
+ },
+ [`${metaKey}+c`]: event => {
+ event.stopPropagation();
+ if (selectedCellPosition) {
+ const { idx, rowIdx } = selectedCellPosition;
+ if (idx > 0) {
+ const colKey = gridColumns[idx].key;
+ const cellValue = rows[rowIdx]?.[colKey] ?? '';
+ const value = formatClipboardValue(cellValue);
+ copyToClipboard(value);
+ }
+ }
+ },
+ },
+ ['INPUT', 'TEXTAREA', 'SELECT']
+ );
+
+ return null;
+}
diff --git a/studio/components/grid/components/common/index.ts b/studio/components/grid/components/common/index.ts
new file mode 100644
index 00000000000..ad34f221222
--- /dev/null
+++ b/studio/components/grid/components/common/index.ts
@@ -0,0 +1,8 @@
+export * from './BlockKeys';
+export * from './ConfirmAlert';
+export * from './DropdownControl';
+export * from './MonacoEditor';
+export * from './NullValue';
+export * from './Hooks';
+export * from './Shortcuts';
+export * from './EmptyValue';
diff --git a/studio/components/grid/components/editor/BooleanEditor.tsx b/studio/components/grid/components/editor/BooleanEditor.tsx
new file mode 100644
index 00000000000..114188539c8
--- /dev/null
+++ b/studio/components/grid/components/editor/BooleanEditor.tsx
@@ -0,0 +1,30 @@
+import * as React from 'react';
+import { EditorProps } from '@supabase/react-data-grid';
+
+export function BooleanEditor<TRow, TSummaryRow = unknown>({
+ row,
+ column,
+ onRowChange,
+ onClose,
+}: EditorProps<TRow, TSummaryRow>) {
+ function onChange(event: React.ChangeEvent<HTMLInputElement>) {
+ onRowChange({ ...row, [column.key]: event.target.checked });
+ }
+
+ function onBlur() {
+ onClose(true);
+ }
+
+ return (
+ <div className="sb-grid-checkbox-editor">
+ <input
+ className="sb-grid-checkbox-editor__input"
+ checked={row[column.key as keyof TRow] as unknown as boolean}
+ onChange={onChange}
+ onBlur={onBlur}
+ type="checkbox"
+ style={{ margin: 'auto' }}
+ />
+ </div>
+ );
+}
diff --git a/studio/components/grid/components/editor/DateEditor.tsx b/studio/components/grid/components/editor/DateEditor.tsx
new file mode 100644
index 00000000000..3c2bb6c2b1b
--- /dev/null
+++ b/studio/components/grid/components/editor/DateEditor.tsx
@@ -0,0 +1,33 @@
+import * as React from 'react';
+import { EditorProps } from '@supabase/react-data-grid';
+
+function autoFocusAndSelect(input: HTMLInputElement | null) {
+ input?.focus();
+ input?.select();
+}
+
+export function DateEditor<TRow, TSummaryRow = unknown>({
+ row,
+ column,
+ onRowChange,
+ onClose,
+}: EditorProps<TRow, TSummaryRow>) {
+ const value = (row[column.key as keyof TRow] as unknown) as string;
+
+ function onChange(event: React.ChangeEvent<HTMLInputElement>) {
+ let _value = event.target.value;
+ if (_value == '') onRowChange({ ...row, [column.key]: null });
+ else onRowChange({ ...row, [column.key]: _value });
+ }
+
+ return (
+ <input
+ className="sb-grid-date-editor"
+ ref={autoFocusAndSelect}
+ value={value ?? ''}
+ onChange={onChange}
+ onBlur={() => onClose(true)}
+ type="date"
+ />
+ );
+}
diff --git a/studio/components/grid/components/editor/DateTimeEditor.tsx b/studio/components/grid/components/editor/DateTimeEditor.tsx
new file mode 100644
index 00000000000..5ca91200406
--- /dev/null
+++ b/studio/components/grid/components/editor/DateTimeEditor.tsx
@@ -0,0 +1,65 @@
+import * as React from 'react';
+import { EditorProps } from '@supabase/react-data-grid';
+import dayjs from 'dayjs';
+import customParseFormat from 'dayjs/plugin/customParseFormat';
+
+dayjs.extend(customParseFormat);
+
+function autoFocusAndSelect(input: HTMLInputElement | null) {
+ input?.focus();
+ input?.select();
+}
+
+interface DateTimeEditorProps<TRow, TSummaryRow = unknown>
+ extends EditorProps<TRow, TSummaryRow> {
+ format: string;
+}
+
+const INPUT_DATE_TIME_FORMAT = 'YYYY-MM-DDTHH:mm:ss';
+
+function BaseEditor<TRow, TSummaryRow = unknown>({
+ row,
+ column,
+ format,
+ onRowChange,
+ onClose,
+}: DateTimeEditorProps<TRow, TSummaryRow>) {
+ const value = row[column.key as keyof TRow] as unknown as string;
+ const timeValue = value
+ ? dayjs(value, format).format(INPUT_DATE_TIME_FORMAT)
+ : value;
+
+ function onChange(event: React.ChangeEvent<HTMLInputElement>) {
+ let _value = event.target.value;
+ if (_value == '') {
+ onRowChange({ ...row, [column.key]: null });
+ } else {
+ const _timeValue = dayjs(_value, INPUT_DATE_TIME_FORMAT).format(format);
+ onRowChange({ ...row, [column.key]: _timeValue });
+ }
+ }
+
+ return (
+ <input
+ className="sb-grid-datetime-editor"
+ ref={autoFocusAndSelect}
+ value={timeValue ?? ''}
+ onChange={onChange}
+ onBlur={() => onClose(true)}
+ type="datetime-local"
+ step="1"
+ />
+ );
+}
+
+export function DateTimeEditor<TRow, TSummaryRow = unknown>(
+ props: EditorProps<TRow, TSummaryRow>
+) {
+ return <BaseEditor {...props} format="YYYY-MM-DDTHH:mm:ss" />;
+}
+
+export function DateTimeWithTimezoneEditor<TRow, TSummaryRow = unknown>(
+ props: EditorProps<TRow, TSummaryRow>
+) {
+ return <BaseEditor {...props} format="YYYY-MM-DDTHH:mm:ssZ" />;
+}
diff --git a/studio/components/grid/components/editor/JsonEditor.tsx b/studio/components/grid/components/editor/JsonEditor.tsx
new file mode 100644
index 00000000000..63a2e5e1120
--- /dev/null
+++ b/studio/components/grid/components/editor/JsonEditor.tsx
@@ -0,0 +1,103 @@
+import * as React from 'react';
+import { Popover } from 'react-tiny-popover';
+import { EditorProps } from '@supabase/react-data-grid';
+import { useTrackedState } from '../../store';
+import { BlockKeys, MonacoEditor, NullValue } from '../common';
+
+export function JsonEditor<TRow, TSummaryRow = unknown>({
+ row,
+ column,
+ onRowChange,
+}: EditorProps<TRow, TSummaryRow>) {
+ const state = useTrackedState();
+ const [isPopoverOpen, setIsPopoverOpen] = React.useState(true);
+ const gridColumn = state.gridColumns.find(x => x.name == column.key);
+ const initialValue = row[column.key as keyof TRow] as unknown;
+ const jsonString = initialValue ? JSON.stringify(initialValue) : '';
+ const prettyJsonValue = prettifyJSON(jsonString);
+ const [value, setValue] = React.useState<string | null>(prettyJsonValue);
+
+ const onEscape = React.useCallback((newValue: string | null) => {
+ commitChange(newValue);
+ setIsPopoverOpen(false);
+ }, []);
+
+ function onChange(_value: string | undefined) {
+ if (!_value || _value == '') setValue(null);
+ else setValue(_value);
+ }
+
+ function commitChange(newValue: string | null) {
+ if (!newValue) {
+ onRowChange({ ...row, [column.key]: null }, true);
+ } else if (verifyJSON(newValue)) {
+ const jsonValue = JSON.parse(newValue);
+ onRowChange({ ...row, [column.key]: jsonValue }, true);
+ } else {
+ const { onError } = state;
+ if (onError) onError(Error('invalid input'));
+ }
+ }
+
+ return (
+ <Popover
+ isOpen={isPopoverOpen}
+ padding={-35}
+ containerClassName=""
+ positions={['bottom', 'top', 'left']}
+ align="start"
+ content={
+ <BlockKeys value={value} onEscape={onEscape}>
+ <MonacoEditor
+ width={`${gridColumn?.width || column.width}px`}
+ value={value ?? ''}
+ language="json"
+ onChange={onChange}
+ />
+ </BlockKeys>
+ }
+ >
+ <div
+ className={`${
+ !!value && jsonString.trim().length == 0
+ ? 'sb-grid-fill-container'
+ : ''
+ } sb-grid-json-editor__trigger`}
+ onClick={() => setIsPopoverOpen(!isPopoverOpen)}
+ >
+ {value === null || value === '' ? <NullValue /> : jsonString}
+ </div>
+ </Popover>
+ );
+}
+
+export const prettifyJSON = (value: string) => {
+ if (value.length > 0) {
+ try {
+ return JSON.stringify(JSON.parse(value), undefined, 2);
+ } catch (err) {
+ // dont need to throw error, just return text value
+ // Users have to fix format if they want to save
+ return value;
+ }
+ } else {
+ return value;
+ }
+};
+
+export const minifyJSON = (value: string) => {
+ try {
+ return JSON.stringify(JSON.parse(value));
+ } catch (err) {
+ throw err;
+ }
+};
+
+export const verifyJSON = (value: string) => {
+ try {
+ JSON.parse(value);
+ return true;
+ } catch (err) {
+ return false;
+ }
+};
diff --git a/studio/components/grid/components/editor/NullableBooleanEditor.tsx b/studio/components/grid/components/editor/NullableBooleanEditor.tsx
new file mode 100644
index 00000000000..72e90865163
--- /dev/null
+++ b/studio/components/grid/components/editor/NullableBooleanEditor.tsx
@@ -0,0 +1,51 @@
+import React, { useEffect } from 'react';
+import { EditorProps } from '@supabase/react-data-grid';
+import { Button, IconX } from '@supabase/ui';
+
+export function NullableBooleanEditor<TRow, TSummaryRow = unknown>({
+ row,
+ column,
+ onRowChange,
+ onClose,
+}: EditorProps<TRow, TSummaryRow>) {
+ const value = row[column.key as keyof TRow] as unknown as boolean | null;
+
+ useEffect(() => {
+ // if value is null, set it to false on initial render
+ if (value === null) {
+ onRowChange({ ...row, [column.key]: false });
+ }
+ }, []);
+
+ function onChange(event: React.ChangeEvent<HTMLInputElement>) {
+ onRowChange({ ...row, [column.key]: event.target.checked });
+ }
+
+ function onBlur() {
+ onClose(true);
+ }
+
+ function onClear() {
+ onRowChange({ ...row, [column.key]: null }, true);
+ }
+
+ return (
+ <div className="sb-grid-checkbox-editor">
+ <input
+ className="sb-grid-checkbox-editor__input"
+ checked={value === null ? false : value}
+ onChange={onChange}
+ onBlur={onBlur}
+ type="checkbox"
+ style={{ margin: 'auto' }}
+ />
+ <Button
+ type="text"
+ title="Clear"
+ icon={<IconX size="tiny" strokeWidth={2} />}
+ onClick={onClear}
+ style={{ padding: '3px', margin: 'auto 5px auto auto' }}
+ />
+ </div>
+ );
+}
diff --git a/studio/components/grid/components/editor/NumberEditor.tsx b/studio/components/grid/components/editor/NumberEditor.tsx
new file mode 100644
index 00000000000..d8e020da217
--- /dev/null
+++ b/studio/components/grid/components/editor/NumberEditor.tsx
@@ -0,0 +1,37 @@
+import * as React from 'react';
+import { EditorProps } from '@supabase/react-data-grid';
+
+function autoFocusAndSelect(input: HTMLInputElement | null) {
+ input?.focus();
+ input?.select();
+}
+
+export function NumberEditor<TRow, TSummaryRow = unknown>({
+ row,
+ column,
+ onRowChange,
+ onClose,
+}: EditorProps<TRow, TSummaryRow>) {
+ const value = (row[column.key as keyof TRow] as unknown) as string;
+
+ function onChange(event: React.ChangeEvent<HTMLInputElement>) {
+ const _value = event.target.value;
+ if (_value == '') onRowChange({ ...row, [column.key]: null });
+ else onRowChange({ ...row, [column.key]: _value });
+ }
+
+ function onBlur() {
+ onClose(true);
+ }
+
+ return (
+ <input
+ className="sb-grid-number-editor"
+ ref={autoFocusAndSelect}
+ value={value ?? ''}
+ onChange={onChange}
+ onBlur={onBlur}
+ type="number"
+ />
+ );
+}
diff --git a/studio/components/grid/components/editor/SelectEditor.tsx b/studio/components/grid/components/editor/SelectEditor.tsx
new file mode 100644
index 00000000000..e721b3df832
--- /dev/null
+++ b/studio/components/grid/components/editor/SelectEditor.tsx
@@ -0,0 +1,47 @@
+import * as React from 'react';
+import { EditorProps } from '@supabase/react-data-grid';
+
+interface SelectEditorProps<TRow, TSummaryRow = unknown>
+ extends EditorProps<TRow, TSummaryRow> {
+ options: { label: string; value: string }[];
+}
+
+export function SelectEditor<TRow, TSummaryRow = unknown>({
+ row,
+ column,
+ onRowChange,
+ onClose,
+ options,
+}: SelectEditorProps<TRow, TSummaryRow>) {
+ const value = (row[column.key as keyof TRow] as unknown) as string;
+
+ function onChange(event: React.ChangeEvent<HTMLSelectElement>) {
+ const value = event.target.value;
+ if (!value || value == '') {
+ onRowChange({ ...row, [column.key]: null }, true);
+ } else {
+ onRowChange({ ...row, [column.key]: value }, true);
+ }
+ }
+
+ function onBlur() {
+ onClose(false);
+ }
+
+ return (
+ <select
+ className="sb-grid-select-editor"
+ value={value ?? ''}
+ onChange={onChange}
+ onBlur={onBlur}
+ autoFocus
+ >
+ <option value={''}>[null]</option>
+ {options.map(({ label, value }) => (
+ <option key={value} value={value}>
+ {label}
+ </option>
+ ))}
+ </select>
+ );
+}
diff --git a/studio/components/grid/components/editor/TextEditor.tsx b/studio/components/grid/components/editor/TextEditor.tsx
new file mode 100644
index 00000000000..d9604a25cd2
--- /dev/null
+++ b/studio/components/grid/components/editor/TextEditor.tsx
@@ -0,0 +1,55 @@
+import * as React from 'react';
+import { Popover } from 'react-tiny-popover';
+import { EditorProps } from '@supabase/react-data-grid';
+import { useTrackedState } from '../../store';
+import { BlockKeys, MonacoEditor, NullValue, EmptyValue } from '../common';
+
+export function TextEditor<TRow, TSummaryRow = unknown>({
+ row,
+ column,
+ onRowChange,
+}: EditorProps<TRow, TSummaryRow>) {
+ const state = useTrackedState();
+ const [isPopoverOpen, setIsPopoverOpen] = React.useState(true);
+ const gridColumn = state.gridColumns.find(x => x.name == column.key);
+ const initialValue = (row[column.key as keyof TRow] as unknown) as string;
+ const [value, setValue] = React.useState<string | null>(initialValue);
+
+ const onEscape = React.useCallback((newValue: string | null) => {
+ onRowChange({ ...row, [column.key]: newValue }, true);
+ setIsPopoverOpen(false);
+ }, []);
+
+ function onChange(_value: string | undefined) {
+ if (!_value) setValue('');
+ else setValue(_value);
+ }
+
+ return (
+ <Popover
+ isOpen={isPopoverOpen}
+ padding={-35}
+ containerClassName=""
+ positions={['bottom', 'top', 'left']}
+ align="start"
+ content={
+ <BlockKeys value={value} onEscape={onEscape}>
+ <MonacoEditor
+ width={`${gridColumn?.width || column.width}px`}
+ value={value ?? ''}
+ onChange={onChange}
+ />
+ </BlockKeys>
+ }
+ >
+ <div
+ className={`${
+ !!value && value.trim().length == 0 ? 'sb-grid-fill-container' : ''
+ } sb-grid-text-editor__trigger`}
+ onClick={() => setIsPopoverOpen(!isPopoverOpen)}
+ >
+ {value === null ? <NullValue /> : value === '' ? <EmptyValue /> : value}
+ </div>
+ </Popover>
+ );
+}
diff --git a/studio/components/grid/components/editor/TimeEditor.tsx b/studio/components/grid/components/editor/TimeEditor.tsx
new file mode 100644
index 00000000000..72004b72a99
--- /dev/null
+++ b/studio/components/grid/components/editor/TimeEditor.tsx
@@ -0,0 +1,69 @@
+import * as React from 'react';
+import { EditorProps } from '@supabase/react-data-grid';
+import dayjs from 'dayjs';
+import customParseFormat from 'dayjs/plugin/customParseFormat';
+
+dayjs.extend(customParseFormat);
+
+function autoFocusAndSelect(input: HTMLInputElement | null) {
+ input?.focus();
+ input?.select();
+}
+
+interface TimeEditorProps<TRow, TSummaryRow = unknown>
+ extends EditorProps<TRow, TSummaryRow> {
+ format: string;
+}
+
+/**
+ * original input time format 'HH:mm'
+ * when step=1, it becomes 'HH:mm:ss'
+ */
+const INPUT_TIME_FORMAT = 'HH:mm:ss';
+
+function BaseEditor<TRow, TSummaryRow = unknown>({
+ row,
+ column,
+ format,
+ onRowChange,
+ onClose,
+}: TimeEditorProps<TRow, TSummaryRow>) {
+ const value = row[column.key as keyof TRow] as unknown as string;
+ const timeValue = value
+ ? dayjs(value, format).format(INPUT_TIME_FORMAT)
+ : value;
+
+ function onChange(event: React.ChangeEvent<HTMLInputElement>) {
+ const _value = event.target.value;
+ if (_value == '') {
+ onRowChange({ ...row, [column.key]: null });
+ } else {
+ const _timeValue = dayjs(_value, INPUT_TIME_FORMAT).format(format);
+ onRowChange({ ...row, [column.key]: _timeValue });
+ }
+ }
+
+ return (
+ <input
+ className="sb-grid-time-editor"
+ ref={autoFocusAndSelect}
+ value={timeValue ?? ''}
+ onChange={onChange}
+ onBlur={() => onClose(true)}
+ type="time"
+ step="1"
+ />
+ );
+}
+
+export function TimeEditor<TRow, TSummaryRow = unknown>(
+ props: EditorProps<TRow, TSummaryRow>
+) {
+ return <BaseEditor {...props} format="HH:mm:ss" />;
+}
+
+export function TimeWithTimezoneEditor<TRow, TSummaryRow = unknown>(
+ props: EditorProps<TRow, TSummaryRow>
+) {
+ return <BaseEditor {...props} format="HH:mm:ssZZ" />;
+}
diff --git a/studio/components/grid/components/editor/index.ts b/studio/components/grid/components/editor/index.ts
new file mode 100644
index 00000000000..56379b8f45a
--- /dev/null
+++ b/studio/components/grid/components/editor/index.ts
@@ -0,0 +1,9 @@
+export * from './BooleanEditor';
+export * from './DateEditor';
+export * from './DateTimeEditor';
+export * from './JsonEditor';
+export * from './NullableBooleanEditor';
+export * from './NumberEditor';
+export * from './SelectEditor';
+export * from './TextEditor';
+export * from './TimeEditor';
diff --git a/studio/components/grid/components/footer/Footer.tsx b/studio/components/grid/components/footer/Footer.tsx
new file mode 100644
index 00000000000..86f6248d068
--- /dev/null
+++ b/studio/components/grid/components/footer/Footer.tsx
@@ -0,0 +1,15 @@
+import * as React from 'react';
+import Pagination from './pagination';
+
+type FooterProps = {};
+
+const Footer: React.FC<FooterProps> = () => {
+ return (
+ <div className="sb-grid-footer">
+ <div className="sb-grid-footer__inner">
+ <Pagination />
+ </div>
+ </div>
+ );
+};
+export default Footer;
diff --git a/studio/components/grid/components/footer/index.ts b/studio/components/grid/components/footer/index.ts
new file mode 100644
index 00000000000..ced11e5251b
--- /dev/null
+++ b/studio/components/grid/components/footer/index.ts
@@ -0,0 +1,3 @@
+import Footer from './Footer';
+
+export default Footer;
diff --git a/studio/components/grid/components/footer/pagination/Pagination.tsx b/studio/components/grid/components/footer/pagination/Pagination.tsx
new file mode 100644
index 00000000000..4e9a317db08
--- /dev/null
+++ b/studio/components/grid/components/footer/pagination/Pagination.tsx
@@ -0,0 +1,123 @@
+import * as React from 'react';
+import AwesomeDebouncePromise from 'awesome-debounce-promise';
+import {
+ Button,
+ InputNumber,
+ Typography,
+ IconArrowRight,
+ IconArrowLeft,
+} from '@supabase/ui';
+import { DropdownControl } from '../../common';
+import { useDispatch, useTrackedState } from '../../../store';
+
+const updatePage = (payload: number, dispatch: (value: unknown) => void) => {
+ dispatch({
+ type: 'SET_PAGE',
+ payload: payload,
+ });
+};
+const updatePageDebounced = AwesomeDebouncePromise(updatePage, 550);
+
+const rowsPerPageOptions = [
+ { value: 100, label: '100 rows' },
+ { value: 500, label: '500 rows' },
+ { value: 1000, label: '1000 rows' },
+];
+
+type PaginationProps = {};
+
+const Pagination: React.FC<PaginationProps> = () => {
+ const state = useTrackedState();
+ const dispatch = useDispatch();
+ const [page, setPage] = React.useState(state.page);
+ const maxPages = Math.ceil(state.totalRows / state.rowsPerPage);
+ const totalPages = state.totalRows > 0 ? maxPages : 1;
+
+ React.useEffect(() => {
+ if (state.page != page) setPage(state.page);
+ }, [state.page, page]);
+
+ function onPreviousPage() {
+ if (state.page > 1) {
+ const previousPage = state.page - 1;
+ setPage(previousPage);
+ dispatch({ type: 'SET_PAGE', payload: previousPage });
+ }
+ }
+
+ function onNextPage() {
+ if (state.page < maxPages) {
+ const nextPage = state.page + 1;
+ setPage(nextPage);
+ dispatch({ type: 'SET_PAGE', payload: nextPage });
+ }
+ }
+
+ function onPageChange(event: React.ChangeEvent<HTMLInputElement>) {
+ const value = event.target.value;
+ const pageNum = Number(value);
+ setPage(pageNum);
+ updatePageDebounced(pageNum, dispatch);
+ }
+
+ function onRowsPerPageChange(value: string | number) {
+ dispatch({ type: 'SET_ROWS_PER_PAGE', payload: value });
+ }
+
+ return (
+ <div className="sb-grid-pagination">
+ {state.totalRows < 0 ? (
+ <Typography.Text>... loading total records</Typography.Text>
+ ) : (
+ <>
+ <Button
+ icon={<IconArrowLeft />}
+ type="outline"
+ disabled={state.page <= 1}
+ onClick={onPreviousPage}
+ style={{ padding: '3px 10px' }}
+ />
+ <Typography.Text>Page</Typography.Text>
+ <div className="sb-grid-pagination-input-container">
+ <InputNumber
+ value={page}
+ onChange={onPageChange}
+ className="sb-grid-pagination-input"
+ size="tiny"
+ style={{
+ width: '3rem',
+ }}
+ max={maxPages}
+ min={1}
+ />
+ </div>
+ <Typography.Text>{`of ${totalPages}`}</Typography.Text>
+ <Button
+ icon={<IconArrowRight />}
+ type="outline"
+ disabled={state.page >= maxPages}
+ onClick={onNextPage}
+ style={{ padding: '3px 10px' }}
+ />
+
+ <DropdownControl
+ options={rowsPerPageOptions}
+ onSelect={onRowsPerPageChange}
+ side="top"
+ align="start"
+ >
+ <Button
+ as="span"
+ type="outline"
+ style={{ padding: '3px 10px' }}
+ >{`${state.rowsPerPage} rows`}</Button>
+ </DropdownControl>
+ <Typography.Text>
+ {`${state.totalRows.toLocaleString()} records`}
+ </Typography.Text>
+ </>
+ )}
+ </div>
+ );
+};
+export default Pagination;
diff --git a/studio/components/grid/components/footer/pagination/index.ts b/studio/components/grid/components/footer/pagination/index.ts
new file mode 100644
index 00000000000..9ed530b1f60
--- /dev/null
+++ b/studio/components/grid/components/footer/pagination/index.ts
@@ -0,0 +1,3 @@
+import Pagination from './Pagination';
+
+export default Pagination;
diff --git a/studio/components/grid/components/formatter/BooleanFormatter.tsx b/studio/components/grid/components/formatter/BooleanFormatter.tsx
new file mode 100644
index 00000000000..34fa3bd2cc7
--- /dev/null
+++ b/studio/components/grid/components/formatter/BooleanFormatter.tsx
@@ -0,0 +1,12 @@
+import * as React from 'react';
+import { FormatterProps } from '@supabase/react-data-grid';
+import { SupaRow } from '../../types';
+import { NullValue } from '../common';
+
+export const BooleanFormatter = (
+ p: React.PropsWithChildren<FormatterProps<SupaRow, unknown>>
+) => {
+ const value = p.row[p.column.key] as boolean | null;
+ if (value === null) return <NullValue />;
+ return <>{value ? 'true' : 'false'}</>;
+};
diff --git a/studio/components/grid/components/formatter/DefaultFormatter.tsx b/studio/components/grid/components/formatter/DefaultFormatter.tsx
new file mode 100644
index 00000000000..4ce80783aa4
--- /dev/null
+++ b/studio/components/grid/components/formatter/DefaultFormatter.tsx
@@ -0,0 +1,17 @@
+import * as React from 'react';
+import { FormatterProps } from '@supabase/react-data-grid';
+import { SupaRow } from '../../types';
+import { NullValue } from '../common';
+import { EmptyValue } from '../common/EmptyValue';
+
+export const DefaultFormatter = (
+ p: React.PropsWithChildren<FormatterProps<SupaRow, unknown>>
+) => {
+ let value = p.row[p.column.key];
+ if (value === null) return <NullValue />;
+ if(value === '') return <EmptyValue />;
+ if (typeof value == 'object' || Array.isArray(value)) {
+ value = JSON.stringify(value);
+ }
+ return <>{value}</>;
+};
diff --git a/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx b/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx
new file mode 100644
index 00000000000..47959030de9
--- /dev/null
+++ b/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx
@@ -0,0 +1,47 @@
+import * as React from 'react';
+import { FormatterProps } from '@supabase/react-data-grid';
+import { SupaRow } from '../../types';
+import { NullValue } from '../common';
+import { ForeignTableModal } from '../common/ForeignTableModal';
+import { useDispatch, useTrackedState } from '../../store';
+import { deepClone } from '../../utils';
+
+export const ForeignKeyFormatter = (
+ p: React.PropsWithChildren<FormatterProps<SupaRow, unknown>>
+) => {
+ const state = useTrackedState();
+ const dispatch = useDispatch();
+ const value = p.row[p.column.key];
+
+ function onRowChange(_value: any | null) {
+ const rowData = deepClone(p.row);
+ rowData[p.column.key] = _value;
+
+ const { error } = state.rowService!.update(rowData, p.column.key);
+ if (error) {
+ if (state.onError) state.onError(error);
+ } else {
+ dispatch({
+ type: 'EDIT_ROW',
+ payload: { row: rowData, idx: p.row.idx },
+ });
+ }
+ }
+
+ function onChange(_value: any | null) {
+ onRowChange(_value);
+ }
+
+ return (
+ <div className="sb-grid-foreign-key-formatter">
+ <p className="sb-grid-foreign-key-formatter__text">
+ {value === null ? <NullValue /> : value}
+ </p>
+ <ForeignTableModal
+ columnName={p.column.key}
+ defaultValue={value}
+ onChange={onChange}
+ />
+ </div>
+ );
+};
diff --git a/studio/components/grid/components/formatter/index.ts b/studio/components/grid/components/formatter/index.ts
new file mode 100644
index 00000000000..a8becfed3df
--- /dev/null
+++ b/studio/components/grid/components/formatter/index.ts
@@ -0,0 +1,3 @@
+export * from './BooleanFormatter';
+export * from './DefaultFormatter';
+export * from './ForeignKeyFormatter';
diff --git a/studio/components/grid/components/grid/AddColumn.tsx b/studio/components/grid/components/grid/AddColumn.tsx
new file mode 100644
index 00000000000..1783ef685ee
--- /dev/null
+++ b/studio/components/grid/components/grid/AddColumn.tsx
@@ -0,0 +1,49 @@
+import * as React from 'react';
+import { CalculatedColumn } from '@supabase/react-data-grid';
+import { Button, IconPlus } from '@supabase/ui';
+import { ADD_COLUMN_KEY } from '../../constants';
+import { useTrackedState } from '../../store';
+import { DefaultFormatter } from '../formatter';
+
+export const AddColumn: CalculatedColumn<any, any> = {
+ key: ADD_COLUMN_KEY,
+ name: '',
+ idx: 999,
+ width: 100,
+ maxWidth: 100,
+ resizable: false,
+ sortable: false,
+ frozen: false,
+ isLastFrozenColumn: false,
+ rowGroup: false,
+ headerRenderer(props) {
+ return (
+ <AddColumnHeader
+ aria-label="Add New Row"
+ value={props.allRowsSelected}
+ onChange={props.onAllRowsSelectionChange}
+ />
+ );
+ },
+ formatter: DefaultFormatter,
+};
+
+type SharedInputProps = Pick<
+ React.InputHTMLAttributes<HTMLInputElement>,
+ 'disabled' | 'tabIndex' | 'onClick' | 'aria-label' | 'aria-labelledby'
+>;
+
+interface AddColumnHeaderProps extends SharedInputProps {
+ value: boolean;
+ onChange: (value: boolean, isShiftClick: boolean) => void;
+}
+
+const AddColumnHeader: React.FC<AddColumnHeaderProps> = () => {
+ const state = useTrackedState();
+ const { onAddColumn } = state;
+ return (
+ <div className="sb-grid-add-column">
+ <Button block type="text" onClick={onAddColumn!} icon={<IconPlus />} />
+ </div>
+ );
+};
diff --git a/studio/components/grid/components/grid/ColumnHeader.tsx b/studio/components/grid/components/grid/ColumnHeader.tsx
new file mode 100644
index 00000000000..63b00dbbcb1
--- /dev/null
+++ b/studio/components/grid/components/grid/ColumnHeader.tsx
@@ -0,0 +1,152 @@
+import * as React from 'react';
+import { IconKey, IconLink } from '@supabase/ui';
+import { useDrag, useDrop, DropTargetMonitor } from 'react-dnd';
+import { XYCoord } from 'dnd-core';
+import { useDispatch } from '../../store';
+import { ColumnHeaderProps, ColumnType, DragItem } from '../../types';
+import { ColumnMenu } from '../menu';
+import { useTrackedState } from '../../store';
+
+export function ColumnHeader<R>({
+ column,
+ columnType,
+ isPrimaryKey,
+ format,
+}: ColumnHeaderProps<R>) {
+ const ref = React.useRef<HTMLDivElement>(null);
+ const dispatch = useDispatch();
+ const columnIdx = column.idx;
+ const columnKey = column.key;
+ const columnFormat = getColumnFormat(columnType, format);
+ const state = useTrackedState();
+
+ // keep state.gridColumns' order in sync with data grid component
+ if (state.gridColumns[columnIdx].key != columnKey) {
+ dispatch({
+ type: 'UPDATE_COLUMN_IDX',
+ payload: { columnKey, columnIdx },
+ });
+ }
+
+ const [{ isDragging }, drag] = useDrag({
+ type: 'column-header',
+ item: () => {
+ return { key: columnKey, index: columnIdx };
+ },
+ canDrag: () => !column.frozen,
+ collect: (monitor: any) => ({
+ isDragging: monitor.isDragging(),
+ }),
+ });
+
+ const [{ handlerId }, drop] = useDrop({
+ accept: 'column-header',
+ collect(monitor) {
+ return {
+ handlerId: monitor.getHandlerId(),
+ };
+ },
+ hover(item: DragItem, monitor: DropTargetMonitor) {
+ if (!ref.current) {
+ return;
+ }
+
+ if (column.frozen) {
+ return;
+ }
+
+ const dragIndex = item.index;
+ const dragKey = item.key;
+ const hoverIndex = columnIdx;
+ const hoverKey = columnKey;
+
+ // Don't replace items with themselves
+ if (dragIndex === hoverIndex) {
+ return;
+ }
+
+ // Determine rectangle on screen
+ const hoverBoundingRect = ref.current?.getBoundingClientRect();
+
+ // Get horizontal middle
+ const hoverMiddleX =
+ (hoverBoundingRect.right - hoverBoundingRect.left) / 2;
+
+ // Determine mouse position
+ const clientOffset = monitor.getClientOffset();
+
+ // Get pixels to the top
+ const hoverClientX = (clientOffset as XYCoord).x - hoverBoundingRect.left;
+
+ // Only perform the move when the mouse has crossed half of the items width
+
+ // Dragging left
+ if (dragIndex < hoverIndex && hoverClientX < hoverMiddleX) {
+ return;
+ }
+
+ // Dragging right
+ if (dragIndex > hoverIndex && hoverClientX > hoverMiddleX) {
+ return;
+ }
+
+ // Time to actually perform the action
+ moveColumn(dragKey, hoverKey);
+
+ // Note: we're mutating the monitor item here!
+ // Generally it's better to avoid mutations,
+ // but it's good here for the sake of performance
+ // to avoid expensive index searches.
+ item.index = hoverIndex;
+ },
+ });
+
+ const moveColumn = (fromKey: string, toKey: string) => {
+ if (fromKey == toKey) return;
+ dispatch({
+ type: 'MOVE_COLUMN',
+ payload: { fromKey, toKey },
+ });
+ };
+
+ const opacity = isDragging ? 0 : 1;
+ const cursor = column.frozen ? 'sb-grid-column-header--cursor' : '';
+ drag(drop(ref));
+
+ return (
+ <div ref={ref} data-handler-id={handlerId} style={{ opacity }}>
+ <div className={`sb-grid-column-header ${cursor}`}>
+ <div className="sb-grid-column-header__inner">
+ {renderColumnIcon(columnType)}
+ {isPrimaryKey && (
+ <div className="sb-grid-column-header__inner__primary-key">
+ <IconKey size="tiny" strokeWidth={2} />
+ </div>
+ )}
+ <span className="sb-grid-column-header__inner__name">
+ {column.name}
+ </span>
+ <span className="sb-grid-column-header__inner__format">
+ {columnFormat}
+ </span>
+ </div>
+ <ColumnMenu column={column} />
+ </div>
+ </div>
+ );
+}
+
+function renderColumnIcon(type: ColumnType) {
+ switch (type) {
+ case 'foreign_key':
+ return <IconLink size="tiny" strokeWidth={2} />;
+ default:
+ return null;
+ }
+}
+
+function getColumnFormat(type: ColumnType, format: string) {
+ if (type == 'array') {
+ return `${format.replace('_', '')}[]`;
+ } else return format;
+}
diff --git a/studio/components/grid/components/grid/Grid.tsx b/studio/components/grid/components/grid/Grid.tsx
new file mode 100644
index 00000000000..43f2757aa2b
--- /dev/null
+++ b/studio/components/grid/components/grid/Grid.tsx
@@ -0,0 +1,123 @@
+import * as React from 'react';
+import { memo } from 'react-tracked';
+import DataGrid, {
+ DataGridHandle,
+ RowsChangeData,
+} from '@supabase/react-data-grid';
+import { IconLoader } from '@supabase/ui';
+import { GridProps, SupaRow } from '../../types';
+import { useDispatch, useTrackedState } from '../../store';
+import RowRenderer from './RowRenderer';
+import AwesomeDebouncePromise from 'awesome-debounce-promise';
+
+function rowKeyGetter(row: SupaRow) {
+ return row.idx;
+}
+
+export const Grid = memo(
+ React.forwardRef<DataGridHandle, GridProps>(
+ (
+ { width, height, containerClass, gridClass, rowClass },
+ ref: React.Ref<DataGridHandle> | undefined
+ ) => {
+ const dispatch = useDispatch();
+ const state = useTrackedState();
+ // workaround to force state tracking on state.gridColumns
+ const columnHeaders = state.gridColumns.map(
+ (x) => `${x.key}_${x.frozen}`
+ );
+ const { gridColumns, rows, onError: onErrorFunc } = state;
+
+ function onColumnResize(index: number, width: number) {
+ updateColumnResizeDebounced(index, width, dispatch);
+ }
+
+ function onRowsChange(
+ rows: SupaRow[],
+ data: RowsChangeData<SupaRow, unknown>
+ ) {
+ const rowData = rows[data.indexes[0]];
+ const originRowData = state.rows.find((x) => x.idx == rowData.idx);
+ const changedColumn = Object.keys(rowData).find((name) => rowData[name] !== originRowData![name]);
+ if (changedColumn) {
+ const { error } = state.rowService!.update(rowData, changedColumn);
+ if (error) {
+ if (onErrorFunc) onErrorFunc(error);
+ } else {
+ dispatch({
+ type: 'SET_ROWS',
+ payload: { rows },
+ });
+ }
+ }
+ }
+
+ function onSelectedRowsChange(selectedRows: ReadonlySet<number>) {
+ dispatch({
+ type: 'SELECTED_ROWS_CHANGE',
+ payload: { selectedRows },
+ });
+ }
+
+ function onSelectedCellChange(position: { idx: number; rowIdx: number }) {
+ dispatch({
+ type: 'SELECTED_CELL_CHANGE',
+ payload: { position },
+ });
+ }
+
+ if (!columnHeaders || columnHeaders.length == 0) {
+ return (
+ <div
+ className="sb-grid-grid--loading"
+ style={{ width: width || '100%', height: height || '50vh' }}
+ >
+ <div className="sb-grid-grid--loading__inner flex items-center gap-2">
+ <div className="animate-spin text-scale-900">
+ <IconLoader />
+ </div>
+ <div className="text-sm text-scale-1100">Loading...</div>
+ </div>
+ </div>
+ );
+ }
+ return (
+ <div
+ className={containerClass}
+ style={{ width: width || '100%', height: height || '50vh' }}
+ >
+ <DataGrid
+ ref={ref}
+ columns={gridColumns}
+ rows={rows ?? []}
+ rowRenderer={RowRenderer}
+ rowKeyGetter={rowKeyGetter}
+ selectedRows={state.selectedRows}
+ onColumnResize={onColumnResize}
+ onRowsChange={onRowsChange}
+ onSelectedCellChange={onSelectedCellChange}
+ onSelectedRowsChange={onSelectedRowsChange}
+ className={gridClass}
+ rowClass={rowClass}
+ style={{ height: '100%' }}
+ />
+ </div>
+ );
+ }
+ )
+);
+
+const updateColumnResize = (
+ index: number,
+ width: number,
+ dispatch: (value: unknown) => void
+) => {
+ dispatch({
+ type: 'UPDATE_COLUMN_SIZE',
+ payload: { index, width: Math.round(width) },
+ });
+};
+const updateColumnResizeDebounced = AwesomeDebouncePromise(
+ updateColumnResize,
+ 500
+);
diff --git a/studio/components/grid/components/grid/RowRenderer.tsx b/studio/components/grid/components/grid/RowRenderer.tsx
new file mode 100644
index 00000000000..da7fec46a2a
--- /dev/null
+++ b/studio/components/grid/components/grid/RowRenderer.tsx
@@ -0,0 +1,19 @@
+import * as React from 'react';
+import { TriggerEvent, useContextMenu } from 'react-contexify';
+import { Row, RowRendererProps } from '@supabase/react-data-grid';
+import { MENU_IDS } from '../menu';
+import { SupaRow } from '../../types';
+
+export default function RowRenderer(props: RowRendererProps<SupaRow>) {
+ const { show: showContextMenu } = useContextMenu();
+
+ function displayMenu(e: TriggerEvent) {
+ const menuId = MENU_IDS.ROW_CONTEXT_MENU_ID;
+ showContextMenu(e, {
+ id: menuId,
+ props: { rowIdx: props.rowIdx },
+ });
+ }
+
+ return <Row {...props} onContextMenu={displayMenu} />;
+}
diff --git a/studio/components/grid/components/grid/SelectColumn.tsx b/studio/components/grid/components/grid/SelectColumn.tsx
new file mode 100644
index 00000000000..d62ced31951
--- /dev/null
+++ b/studio/components/grid/components/grid/SelectColumn.tsx
@@ -0,0 +1,178 @@
+import * as React from 'react';
+import {
+ CalculatedColumn,
+ FormatterProps,
+ GroupFormatterProps,
+ useRowSelection,
+} from '@supabase/react-data-grid';
+import { Button, IconMaximize2 } from '@supabase/ui';
+import { SupaRow } from '../../types';
+import { RowMenu } from '../menu';
+import { SELECT_COLUMN_KEY } from '../../constants';
+import { useFocusRef } from '../../utils';
+import { useTrackedState } from '../../store';
+
+export const SelectColumn: CalculatedColumn<any, any> = {
+ key: SELECT_COLUMN_KEY,
+ name: '',
+ idx: 0,
+ width: 65,
+ maxWidth: 65,
+ resizable: false,
+ sortable: false,
+ frozen: true,
+ isLastFrozenColumn: false,
+ rowGroup: false,
+ headerRenderer: props => {
+ return (
+ <SelectCellHeader
+ aria-label="Select All"
+ value={props.allRowsSelected}
+ onChange={props.onAllRowsSelectionChange}
+ />
+ );
+ },
+ formatter: (props: FormatterProps<SupaRow>) => {
+ const [isRowSelected, onRowSelectionChange] = useRowSelection();
+ return (
+ <SelectCellFormatter
+ aria-label="Select"
+ tabIndex={-1}
+ isCellSelected={props.isCellSelected}
+ value={isRowSelected}
+ row={props.row}
+ onChange={(checked, isShiftClick) => {
+ onRowSelectionChange({ row: props.row, checked, isShiftClick });
+ }}
+ // Stop propagation to prevent row selection
+ onClick={stopPropagation}
+ />
+ );
+ },
+ groupFormatter: (props: GroupFormatterProps<SupaRow>) => {
+ const [isRowSelected, onRowSelectionChange] = useRowSelection();
+ return (
+ <SelectCellFormatter
+ aria-label="Select Group"
+ tabIndex={-1}
+ isCellSelected={props.isCellSelected}
+ value={isRowSelected}
+ onChange={checked => {
+ onRowSelectionChange({
+ row: props.row,
+ checked,
+ isShiftClick: false,
+ });
+ }}
+ // Stop propagation to prevent row selection
+ onClick={stopPropagation}
+ />
+ );
+ },
+};
+
+function stopPropagation(event: React.SyntheticEvent) {
+ event.stopPropagation();
+}
+
+type SharedInputProps = Pick<
+ React.InputHTMLAttributes<HTMLInputElement>,
+ 'disabled' | 'tabIndex' | 'onClick' | 'aria-label' | 'aria-labelledby'
+>;
+
+interface SelectCellFormatterProps extends SharedInputProps {
+ isCellSelected: boolean;
+ value: boolean;
+ row?: SupaRow;
+ onChange: (value: boolean, isShiftClick: boolean) => void;
+}
+
+function SelectCellFormatter({
+ row,
+ value,
+ tabIndex,
+ isCellSelected,
+ disabled,
+ onClick,
+ onChange,
+ 'aria-label': ariaLabel,
+ 'aria-labelledby': ariaLabelledBy,
+}: SelectCellFormatterProps) {
+ const state = useTrackedState();
+ const { onEditRow } = state;
+ const inputRef = useFocusRef<HTMLInputElement>(isCellSelected);
+
+ function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
+ onChange(e.target.checked, (e.nativeEvent as MouseEvent).shiftKey);
+ }
+
+ function onEditClick(e: React.MouseEvent) {
+ e.stopPropagation();
+ if (onEditRow && row) {
+ onEditRow(row);
+ }
+ }
+
+ return (
+ <div className="sb-grid-select-cell__formatter">
+ <input
+ aria-label={ariaLabel}
+ aria-labelledby={ariaLabelledBy}
+ tabIndex={tabIndex}
+ ref={inputRef}
+ type="checkbox"
+ className="rdg-row__select-column__select-action"
+ disabled={disabled}
+ checked={value}
+ onChange={handleChange}
+ onClick={onClick}
+ />
+ {onEditRow && row && (
+ <Button
+ type="text"
+ size="tiny"
+ className="rdg-row__select-column__edit-action"
+ icon={<IconMaximize2 size="tiny" />}
+ onClick={onEditClick}
+ style={{ padding: '2px' }}
+ />
+ )}
+ </div>
+ );
+}
+
+interface SelectCellHeaderProps extends SharedInputProps {
+ value: boolean;
+ onChange: (value: boolean, isShiftClick: boolean) => void;
+}
+
+function SelectCellHeader({
+ disabled,
+ tabIndex,
+ value,
+ onChange,
+ onClick,
+ 'aria-label': ariaLabel,
+ 'aria-labelledby': ariaLabelledBy,
+}: SelectCellHeaderProps) {
+ function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
+ onChange(e.target.checked, (e.nativeEvent as MouseEvent).shiftKey);
+ }
+
+ return (
+ <div className="sb-grid-select-cell__header">
+ <input
+ aria-label={ariaLabel}
+ aria-labelledby={ariaLabelledBy}
+ tabIndex={tabIndex}
+ type="checkbox"
+ className="sb-grid-select-cell__header__input"
+ disabled={disabled}
+ checked={value}
+ onChange={handleChange}
+ onClick={onClick}
+ />
+ <RowMenu />
+ </div>
+ );
+}
diff --git a/studio/components/grid/components/grid/index.ts b/studio/components/grid/components/grid/index.ts
new file mode 100644
index 00000000000..4d5f13be998
--- /dev/null
+++ b/studio/components/grid/components/grid/index.ts
@@ -0,0 +1,4 @@
+export * from './ColumnHeader';
+export * from './Grid';
+export * from './SelectColumn';
+export * from './AddColumn';
diff --git a/studio/components/grid/components/header/Header.tsx b/studio/components/grid/components/header/Header.tsx
new file mode 100644
index 00000000000..f3ec5f36a83
--- /dev/null
+++ b/studio/components/grid/components/header/Header.tsx
@@ -0,0 +1,191 @@
+import * as React from 'react';
+import { useDispatch, useTrackedState } from '../../store';
+import {
+ Button,
+ Divider,
+ IconDownload,
+ IconPlus,
+ IconX,
+ IconTrash,
+ Typography,
+} from '@supabase/ui';
+import FileSaver from 'file-saver';
+import FilterDropdown from './filter';
+import SortPopover from './sort';
+import StatusLabel from './StatusLabel';
+import RefreshButton from './RefreshButton';
+import { exportRowsToCsv } from '../../utils';
+import { showConfirmAlert } from '../common';
+
+type HeaderProps = {
+ onAddColumn?: () => void;
+ onAddRow?: () => void;
+ headerActions?: React.ReactNode;
+};
+
+const Header: React.FC<HeaderProps> = ({
+ onAddColumn,
+ onAddRow,
+ headerActions,
+}) => {
+ const state = useTrackedState();
+ const { selectedRows } = state;
+
+ return (
+ <div className="sb-grid-header">
+ <div className="sb-grid-header__inner">
+ {selectedRows.size > 0 ? (
+ <RowHeader />
+ ) : (
+ <DefaultHeader onAddColumn={onAddColumn} onAddRow={onAddRow} />
+ )}
+ </div>
+ <div className="sb-grid-header__inner">
+ {headerActions}
+ <StatusLabel />
+ </div>
+ </div>
+ );
+};
+export default Header;
+
+type DefaultHeaderProps = {
+ onAddColumn?: () => void;
+ onAddRow?: () => void;
+};
+const DefaultHeader: React.FC<DefaultHeaderProps> = ({
+ onAddColumn,
+ onAddRow,
+}) => {
+ const renderNewColumn = (onAddColumn?: () => void) => {
+ if (!onAddColumn) return null;
+ return (
+ <Button type="text" onClick={onAddColumn} style={{ padding: '4px 8px' }}>
+ New Column
+ </Button>
+ );
+ };
+
+ const renderAddRow = (onAddRow?: () => void) => {
+ if (!onAddRow) return null;
+ return (
+ <Button
+ style={{ padding: '4px 8px' }}
+ icon={<IconPlus size="tiny" />}
+ onClick={onAddRow}
+ >
+ Insert row
+ </Button>
+ );
+ };
+
+ return (
+ <>
+ <RefreshButton />
+ <FilterDropdown />
+ <SortPopover />
+ <Divider
+ light
+ type="vertical"
+ className="sb-grid-header__inner__divider"
+ />
+ {renderNewColumn(onAddColumn)}
+ {renderAddRow(onAddRow)}
+ </>
+ );
+};
+
+type RowHeaderProps = {};
+const RowHeader: React.FC<RowHeaderProps> = ({}) => {
+ const state = useTrackedState();
+ const dispatch = useDispatch();
+
+ const { selectedRows, rows: allRows, editable } = state;
+
+ const onRowsDelete = () => {
+ showConfirmAlert({
+ title: 'Confirm to delete',
+ message:
+ 'Are you sure you want to delete the selected rows? This action cannot be undone.',
+ onConfirm: async () => {
+ const rowIdxs = Array.from(selectedRows) as number[];
+ const rows = allRows.filter((x) => rowIdxs.includes(x.idx));
+ const { error } = state.rowService!.delete(rows);
+ if (error) {
+ if (state.onError) state.onError(error);
+ } else {
+ dispatch({ type: 'REMOVE_ROWS', payload: { rowIdxs } });
+ dispatch({
+ type: 'SELECTED_ROWS_CHANGE',
+ payload: { selectedRows: new Set() },
+ });
+ }
+ },
+ });
+ };
+
+ function onRowsExportCsv() {
+ const rows = allRows.filter((x) => selectedRows.has(x.idx));
+ const csv = exportRowsToCsv(state.table!.columns, rows);
+ const csvData = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
+ FileSaver.saveAs(csvData, `${state.table!.name}_rows.csv`);
+ }
+
+ function deselectRows() {
+ dispatch({
+ type: 'SELECTED_ROWS_CHANGE',
+ payload: { selectedRows: new Set() },
+ });
+ }
+
+ return (
+ <>
+ <Button
+ type="text"
+ style={{ padding: '4px' }}
+ icon={<IconX size="tiny" strokeWidth={2} />}
+ onClick={deselectRows}
+ />
+ <div>
+ <Typography.Text
+ small
+ type="secondary"
+ className="row_header__selected-rows"
+ >
+ {selectedRows.size > 1
+ ? `${selectedRows.size} rows selected`
+ : `${selectedRows.size} row selected`}
+ </Typography.Text>
+ </div>
+ <Button
+ type="primary"
+ size="tiny"
+ style={{ padding: '4px 8px' }}
+ icon={<IconDownload />}
+ onClick={onRowsExportCsv}
+ >
+ Export to csv
+ </Button>
+ {editable && (
+ <>
+ <Divider
+ type="vertical"
+ className="sb-grid-header__inner__divider"
+ light
+ />
+ <Button
+ type="default"
+ size="tiny"
+ style={{ padding: '4px 8px' }}
+ icon={<IconTrash size="tiny" />}
+ onClick={onRowsDelete}
+ >
+ {selectedRows.size > 1
+ ? `Delete ${selectedRows.size} rows`
+ : `Delete ${selectedRows.size} row`}
+ </Button>
+ </>
+ )}
+ </>
+ );
+};
diff --git a/studio/components/grid/components/header/RefreshButton.tsx b/studio/components/grid/components/header/RefreshButton.tsx
new file mode 100644
index 00000000000..fd162104fa8
--- /dev/null
+++ b/studio/components/grid/components/header/RefreshButton.tsx
@@ -0,0 +1,32 @@
+import * as React from 'react';
+import { Button, IconRefreshCw } from '@supabase/ui';
+import { useDispatch, useTrackedState } from '../../store';
+import { fetchCount, fetchPage } from '../../utils';
+
+type RefreshButtonProps = {};
+
+const RefreshButton: React.FC<RefreshButtonProps> = ({}) => {
+ const [loading, setLoading] = React.useState(false);
+ const state = useTrackedState();
+ const dispatch = useDispatch();
+
+ async function onClick() {
+ setLoading(true);
+ await fetchCount(state, dispatch);
+ await fetchPage(state, dispatch);
+ setLoading(false);
+ }
+
+ return (
+ <Button
+ type="text"
+ style={{ padding: '4px 8px' }}
+ icon={<IconRefreshCw />}
+ onClick={onClick}
+ loading={loading}
+ >
+ Refresh
+ </Button>
+ );
+};
+export default RefreshButton;
diff --git a/studio/components/grid/components/header/StatusLabel.tsx b/studio/components/grid/components/header/StatusLabel.tsx
new file mode 100644
index 00000000000..d08ec33361d
--- /dev/null
+++ b/studio/components/grid/components/header/StatusLabel.tsx
@@ -0,0 +1,43 @@
+import * as React from 'react';
+import { SupabaseGridQueue } from '../../constants';
+import { Typography } from '@supabase/ui';
+
+type StatusLabelProps = {};
+
+const StatusLabel: React.FC<StatusLabelProps> = ({}) => {
+ const [msg, setMsg] = React.useState<string | undefined>(undefined);
+
+ React.useEffect(() => {
+ let isMounted = true;
+ let timer: number | null;
+
+ SupabaseGridQueue.on('active', () => {
+ if (timer) clearTimeout(timer);
+
+ if (isMounted) setMsg('Saving...');
+ });
+ SupabaseGridQueue.on('idle', () => {
+ if (timer) clearTimeout(timer);
+ timer = window.setTimeout(() => setMsg(undefined), 2000);
+
+ if (isMounted) setMsg('All changes saved');
+ });
+
+ return () => {
+ isMounted = false;
+ if (timer) clearTimeout(timer);
+ };
+ }, []);
+
+ return (
+ <div className="sb-grid-status-label">
+ {msg && <Typography.Text>{msg}</Typography.Text>}
+ {!msg && (
+ <div className="sb-grid-status-label__no-msg">
+ <div></div>
+ </div>
+ )}
+ </div>
+ );
+};
+export default StatusLabel;
diff --git a/studio/components/grid/components/header/filter/Filter.constants.ts b/studio/components/grid/components/header/filter/Filter.constants.ts
new file mode 100644
index 00000000000..7e651635fc9
--- /dev/null
+++ b/studio/components/grid/components/header/filter/Filter.constants.ts
@@ -0,0 +1,16 @@
+export const FilterOperatorOptions = [
+ { value: '=', label: 'equals', preLabel: '[ = ]' },
+ { value: '<>', label: 'not equal', preLabel: '[ <> ]' },
+ { value: '>', label: 'greater than', preLabel: '[ > ]' },
+ { value: '<', label: 'less than', preLabel: '[ < ]' },
+ { value: '>=', label: 'greater than or equal', preLabel: '[ >= ]' },
+ { value: '<=', label: 'less than or equal', preLabel: '[ <= ]' },
+ { value: '~~', label: 'like operator', preLabel: '[ ~~ ]' },
+ { value: '~~*', label: 'ilike operator', preLabel: '[ ~~* ]' },
+ { value: 'in', label: 'one of a list of values', preLabel: '[ in ]' },
+ {
+ value: 'is',
+ label: 'checking for (null,not null,true,false)',
+ preLabel: '[ is ]',
+ },
+];
diff --git a/studio/components/grid/components/header/filter/Filter.utils.ts b/studio/components/grid/components/header/filter/Filter.utils.ts
new file mode 100644
index 00000000000..9e317a3f920
--- /dev/null
+++ b/studio/components/grid/components/header/filter/Filter.utils.ts
@@ -0,0 +1,19 @@
+import AwesomeDebouncePromise from 'awesome-debounce-promise';
+import { Filter } from '../../../types';
+
+const updateFilterValue = (
+ payload: {
+ filterIdx: number;
+ value: Filter;
+ },
+ dispatch: (value: unknown) => void
+) => {
+ dispatch({
+ type: 'UPDATE_FILTER',
+ payload: payload,
+ });
+};
+export const updateFilterValueDebounced = AwesomeDebouncePromise(
+ updateFilterValue,
+ 550
+);
diff --git a/studio/components/grid/components/header/filter/FilterPopover.tsx b/studio/components/grid/components/header/filter/FilterPopover.tsx
new file mode 100644
index 00000000000..512b6000117
--- /dev/null
+++ b/studio/components/grid/components/header/filter/FilterPopover.tsx
@@ -0,0 +1,79 @@
+import React, { FC } from 'react';
+import { Button, IconPlus, IconFilter, Popover } from '@supabase/ui';
+import { useDispatch, useTrackedState } from '../../../store';
+import FilterRow from './FilterRow';
+
+const FilterPopover: FC = () => {
+ const state = useTrackedState();
+ const btnText =
+ state.filters.length > 0
+ ? `Filtered by ${state.filters.length} rule${
+ state.filters.length > 1 ? 's' : ''
+ }`
+ : 'Filter';
+
+ return (
+ <Popover
+ size="large"
+ align="start"
+ className="sb-grid-filter-popover"
+ overlay={<Filter />}
+ >
+ <Button
+ as={'span'}
+ type="text"
+ icon={<IconFilter />}
+ style={{ padding: '4px 8px' }}
+ >
+ {btnText}
+ </Button>
+ </Popover>
+ );
+};
+export default FilterPopover;
+
+const Filter: FC = () => {
+ const state = useTrackedState();
+ const dispatch = useDispatch();
+
+ function onAddFilter() {
+ dispatch({
+ type: 'ADD_FILTER',
+ payload: {
+ column: state.table?.columns[0].name,
+ operator: '=',
+ value: '',
+ },
+ });
+ }
+
+ return (
+ <div className="space-y-2 py-2">
+ <div className="space-y-2">
+ {state.filters.map((_, index) => (
+ <FilterRow
+ key={`filter-${index}`}
+ filterIdx={index}
+ now={Date.now()}
+ />
+ ))}
+ {state.filters.length == 0 && (
+ <div className="space-y-1 px-3">
+ <h5 className="text-sm text-scale-1100">
+ No filters applied to this view
+ </h5>
+ <p className="text-xs text-scale-900">
+ Add a column below to filter the view
+ </p>
+ </div>
+ )}
+ </div>
+ <Popover.Seperator />
+ <div className="px-3">
+ <Button icon={<IconPlus />} type="text" onClick={onAddFilter}>
+ Add filter
+ </Button>
+ </div>
+ </div>
+ );
+};
diff --git a/studio/components/grid/components/header/filter/FilterRow.tsx b/studio/components/grid/components/header/filter/FilterRow.tsx
new file mode 100644
index 00000000000..bd84fde4366
--- /dev/null
+++ b/studio/components/grid/components/header/filter/FilterRow.tsx
@@ -0,0 +1,119 @@
+import * as React from 'react';
+import { Button, Input, IconChevronDown, IconX } from '@supabase/ui';
+import { DropdownControl } from '../../common';
+import { useDispatch, useTrackedState } from '../../../store';
+import { FilterOperatorOptions } from './Filter.constants';
+import { updateFilterValueDebounced } from './Filter.utils';
+
+/**
+ * use `now` to trigger re-render as filterIdx won't change value
+ * if not filterText state will not updated on delete filter
+ */
+type FilterRowProps = {
+ filterIdx: number;
+ now: number;
+};
+
+const FilterRow: React.FC<FilterRowProps> = ({ filterIdx, now }) => {
+ const state = useTrackedState();
+ const dispatch = useDispatch();
+ const filter = state.filters[filterIdx];
+ const column = state.table?.columns.find((x) => x.name === filter.column);
+ const columnOptions =
+ state.table?.columns?.map((x) => {
+ return { value: x.name, label: x.name, postLabel: x.dataType };
+ }) || [];
+ const [filterValue, setFilterValue] = React.useState(filter.value);
+
+ React.useEffect(() => {
+ const filter = state.filters[filterIdx];
+ setFilterValue(filter.value);
+ }, [filterIdx, now]);
+
+ function onColumnChange(column: string | number) {
+ dispatch({
+ type: 'UPDATE_FILTER',
+ payload: { filterIdx, value: { ...filter, column } },
+ });
+ }
+
+ function onOperatorChange(operator: string | number) {
+ dispatch({
+ type: 'UPDATE_FILTER',
+ payload: { filterIdx, value: { ...filter, operator } },
+ });
+ }
+
+ function onFilterChange(event: React.ChangeEvent<HTMLInputElement>) {
+ const value = event.target.value;
+ setFilterValue(value);
+ updateFilterValueDebounced(
+ {
+ filterIdx,
+ value: { ...filter, value: value },
+ },
+ dispatch
+ );
+ }
+
+ function onRemoveFilter() {
+ dispatch({
+ type: 'REMOVE_FILTER',
+ payload: { index: filterIdx },
+ });
+ }
+
+ return (
+ <div className="sb-grid-filter-row px-3">
+ <DropdownControl
+ align="start"
+ options={columnOptions}
+ onSelect={onColumnChange}
+ >
+ <Button
+ as="span"
+ type="outline"
+ icon={
+ <div className="text-scale-900">
+ <IconChevronDown strokeWidth={1.5} size={14} />
+ </div>
+ }
+ className="w-32"
+ >
+ {column?.name || ''}
+ </Button>
+ </DropdownControl>
+ <DropdownControl
+ align="start"
+ options={FilterOperatorOptions}
+ onSelect={onOperatorChange}
+ >
+ <Button
+ as="span"
+ type="outline"
+ icon={
+ <div className="text-scale-900">
+ <IconChevronDown strokeWidth={1.5} size={14} />
+ </div>
+ }
+ >
+ {filter.operator}
+ </Button>
+ </DropdownControl>
+ <Input
+ size="tiny"
+ className="w-full"
+ placeholder="Enter a value"
+ value={filterValue}
+ onChange={onFilterChange}
+ />
+ <Button
+ icon={<IconX strokeWidth={1.5} size={14} />}
+ size="tiny"
+ type="text"
+ onClick={onRemoveFilter}
+ />
+ </div>
+ );
+};
+export default React.memo(FilterRow);
diff --git a/studio/components/grid/components/header/filter/index.ts b/studio/components/grid/components/header/filter/index.ts
new file mode 100644
index 00000000000..c2649a3b187
--- /dev/null
+++ b/studio/components/grid/components/header/filter/index.ts
@@ -0,0 +1,4 @@
+import FilterPopover from './FilterPopover';
+
+export * from './Filter.constants';
+export default FilterPopover;
diff --git a/studio/components/grid/components/header/index.ts b/studio/components/grid/components/header/index.ts
new file mode 100644
index 00000000000..a9ce1058c39
--- /dev/null
+++ b/studio/components/grid/components/header/index.ts
@@ -0,0 +1,3 @@
+import Header from './Header';
+
+export default Header;
diff --git a/studio/components/grid/components/header/sort/SortPopover.tsx b/studio/components/grid/components/header/sort/SortPopover.tsx
new file mode 100644
index 00000000000..30431861154
--- /dev/null
+++ b/studio/components/grid/components/header/sort/SortPopover.tsx
@@ -0,0 +1,97 @@
+import React, { FC } from 'react';
+import { Button, IconList, IconChevronDown, Popover } from '@supabase/ui';
+import { DropdownControl } from '../../common';
+import { useDispatch, useTrackedState } from '../../../store';
+import SortRow from './SortRow';
+
+const SortPopover: FC = () => {
+ const state = useTrackedState();
+ const btnText =
+ state.sorts.length > 0
+ ? `Sorted by ${state.sorts.length} rule${
+ state.sorts.length > 1 ? 's' : ''
+ }`
+ : 'Sort';
+
+ return (
+ <Popover
+ size="large"
+ align="start"
+ className="sb-grid-sort-popover"
+ overlay={<Sort />}
+ >
+ <Button
+ as={'span'}
+ type="text"
+ icon={<IconList />}
+ style={{ padding: '4px 8px' }}
+ >
+ {btnText}
+ </Button>
+ </Popover>
+ );
+};
+export default SortPopover;
+
+const Sort: FC = () => {
+ const state = useTrackedState();
+ const dispatch = useDispatch();
+ const columns = state?.table?.columns!.filter((x) => {
+ const found = state.sorts.find((y) => y.column == x.name);
+ return !found;
+ });
+ const dropdownOptions =
+ columns?.map((x) => {
+ return { value: x.name, label: x.name };
+ }) || [];
+
+ function onAddSort(columnName: string | number) {
+ dispatch({
+ type: 'ADD_SORT',
+ payload: { column: columnName, ascending: true },
+ });
+ }
+
+ return (
+ <div className="py-2 space-y-2">
+ {state.sorts.map((x, index) => (
+ <SortRow key={x.column} columnName={x.column} index={index} />
+ ))}
+ {state.sorts.length == 0 && (
+ <div className="space-y-1 px-3">
+ <h5 className="text-sm text-scale-1100">
+ No sorts applied to this view
+ </h5>
+ <p className="text-xs text-scale-900">
+ Add a column below to sort the view
+ </p>
+ </div>
+ )}
+
+ <Popover.Seperator />
+ <div className="px-3">
+ {columns && columns.length > 0 ? (
+ <DropdownControl
+ options={dropdownOptions}
+ onSelect={onAddSort}
+ side="bottom"
+ align="start"
+ >
+ <Button
+ as="span"
+ type="text"
+ iconRight={<IconChevronDown />}
+ className="sb-grid-dropdown__item-trigger"
+ >
+ {`Pick ${
+ state.sorts.length > 1 ? 'another' : 'a'
+ } column to sort by`}
+ </Button>
+ </DropdownControl>
+ ) : (
+ <p className="text-sm text-scale-1100">All columns have been added</p>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/studio/components/grid/components/header/sort/SortRow.tsx b/studio/components/grid/components/header/sort/SortRow.tsx
new file mode 100644
index 00000000000..e4c840d38f3
--- /dev/null
+++ b/studio/components/grid/components/header/sort/SortRow.tsx
@@ -0,0 +1,151 @@
+import * as React from 'react';
+import { Button, IconMenu, Toggle, IconX } from '@supabase/ui';
+import { useDrag, useDrop, DropTargetMonitor } from 'react-dnd';
+import { XYCoord } from 'dnd-core';
+import { useDispatch, useTrackedState } from '../../../store';
+import { DragItem } from '../../../types';
+
+type SortRowProps = {
+ columnName: string;
+ index: number;
+};
+
+const SortRow: React.FC<SortRowProps> = ({ columnName, index }) => {
+ const state = useTrackedState();
+ const dispatch = useDispatch();
+ const column = state?.table?.columns.find((x) => x.name === columnName);
+ const sort = state?.sorts.find((x) => x.column === columnName);
+ if (!column || !sort) return null;
+
+ const ref = React.useRef<HTMLDivElement>(null);
+
+ const [{ isDragging }, drag] = useDrag({
+ type: 'sort-row',
+ item: () => {
+ return { key: columnName, index };
+ },
+ collect: (monitor: any) => ({
+ isDragging: monitor.isDragging(),
+ }),
+ });
+
+ const [{ handlerId }, drop] = useDrop({
+ accept: 'sort-row',
+ collect(monitor) {
+ return {
+ handlerId: monitor.getHandlerId(),
+ };
+ },
+ hover(item: DragItem, monitor: DropTargetMonitor) {
+ if (!ref.current) {
+ return;
+ }
+ const dragIndex = item.index;
+ const hoverIndex = index;
+
+ // Don't replace items with themselves
+ if (dragIndex === hoverIndex) {
+ return;
+ }
+
+ // Determine rectangle on screen
+ const hoverBoundingRect = ref.current?.getBoundingClientRect();
+
+ // Get vertical middle
+ const hoverMiddleY =
+ (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
+
+ // Determine mouse position
+ const clientOffset = monitor.getClientOffset();
+
+ // Get pixels to the top
+ const hoverClientY = (clientOffset as XYCoord).y - hoverBoundingRect.top;
+
+ // Only perform the move when the mouse has crossed half of the items height
+ // When dragging downwards, only move when the cursor is below 50%
+ // When dragging upwards, only move when the cursor is above 50%
+
+ // Dragging downwards
+ if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
+ return;
+ }
+
+ // Dragging upwards
+ if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
+ return;
+ }
+
+ // Time to actually perform the action
+ moveSort(dragIndex, hoverIndex);
+
+ // Note: we're mutating the monitor item here!
+ // Generally it's better to avoid mutations,
+ // but it's good here for the sake of performance
+ // to avoid expensive index searches.
+ item.index = hoverIndex;
+ },
+ });
+
+ function onToogle(value: boolean) {
+ dispatch({
+ type: 'UPDATE_SORT',
+ payload: { column: columnName, ascending: value },
+ });
+ }
+
+ function onDeleteClick() {
+ dispatch({
+ type: 'REMOVE_SORT',
+ payload: { column: columnName },
+ });
+ }
+
+ const moveSort = (dragIndex: number, hoverIndex: number) => {
+ if (dragIndex == hoverIndex) return;
+ dispatch({
+ type: 'MOVE_SORT',
+ payload: { fromIndex: dragIndex, toIndex: hoverIndex },
+ });
+ };
+
+ const opacity = isDragging ? 0 : 1;
+ drag(drop(ref));
+
+ return (
+ <div
+ className="flex items-center gap-3 px-3"
+ ref={ref}
+ style={{ opacity }}
+ data-handler-id={handlerId}
+ >
+ <Button
+ icon={<IconX strokeWidth={1.5} size={14} />}
+ size="tiny"
+ type="text"
+ onClick={onDeleteClick}
+ />
+ <div className="grow">
+ <span className="flex items-center gap-1 grow text-sm text-scale-1200 truncate">
+ <span className="text-xs text-scale-900">
+ {index > 0 ? 'then by' : 'sort by'}
+ </span>
+ {column.name}
+ </span>
+ </div>
+ <div className="flex items-center gap-1">
+ <label className="text-xs text-scale-900">ascending:</label>
+ <Toggle
+ size="tiny"
+ layout="flex"
+ defaultChecked={sort.ascending}
+ // @ts-ignore
+ onChange={(e: boolean) => onToogle(e)}
+ />
+ </div>
+ <span className="transition-color text-scale-900 hover:text-scale-1100">
+ <IconMenu strokeWidth={2} size={16} />
+ </span>
+ </div>
+ );
+};
+export default React.memo(SortRow);
diff --git a/studio/components/grid/components/header/sort/index.ts b/studio/components/grid/components/header/sort/index.ts
new file mode 100644
index 00000000000..cd4307ac38c
--- /dev/null
+++ b/studio/components/grid/components/header/sort/index.ts
@@ -0,0 +1,3 @@
+import SortPopover from './SortPopover';
+
+export default SortPopover;
diff --git a/studio/components/grid/components/menu/ColumnMenu.tsx b/studio/components/grid/components/menu/ColumnMenu.tsx
new file mode 100644
index 00000000000..de22fe84909
--- /dev/null
+++ b/studio/components/grid/components/menu/ColumnMenu.tsx
@@ -0,0 +1,93 @@
+import { CalculatedColumn } from '@supabase/react-data-grid';
+import {
+ Button,
+ Dropdown,
+ IconChevronDown,
+ Divider,
+ IconEdit,
+ IconTrash,
+ IconLock,
+ IconUnlock,
+} from '@supabase/ui';
+import * as React from 'react';
+import { useDispatch, useTrackedState } from '../../store';
+
+type ColumnMenuProps = {
+ column: CalculatedColumn<any, unknown>;
+};
+
+const ColumnMenu: React.FC<ColumnMenuProps> = ({ column }) => {
+ const state = useTrackedState();
+ const dispatch = useDispatch();
+ const {
+ onEditColumn: onEditColumnFunc,
+ onDeleteColumn: onDeleteColumnFunc,
+ } = state;
+
+ const columnKey = column.key;
+
+ function onFreezeColumn() {
+ dispatch({ type: 'FREEZE_COLUMN', payload: { columnKey } });
+ }
+
+ function onUnfreezeColumn() {
+ dispatch({ type: 'UNFREEZE_COLUMN', payload: { columnKey } });
+ }
+
+ function onEditColumn() {
+ if (onEditColumnFunc) onEditColumnFunc(columnKey);
+ }
+
+ function onDeleteColumn() {
+ if (onDeleteColumnFunc) onDeleteColumnFunc(columnKey);
+ }
+
+ function renderMenu() {
+ return (
+ <>
+ {state.editable && onEditColumn !== undefined && (
+ <Dropdown.Item onClick={onEditColumn} icon={<IconEdit size="tiny" />}>
+ Edit column
+ </Dropdown.Item>
+ )}
+ <Dropdown.Item
+ onClick={column.frozen ? onUnfreezeColumn : onFreezeColumn}
+ icon={
+ column.frozen ? (
+ <IconUnlock size="tiny" />
+ ) : (
+ <IconLock size="tiny" />
+ )
+ }
+ >
+ {column.frozen ? 'Unfreeze column' : 'Freeze column'}
+ </Dropdown.Item>
+ {state.editable && onDeleteColumn !== undefined && (
+ <>
+ <Divider light />
+ <Dropdown.Item
+ onClick={onDeleteColumn}
+ icon={<IconTrash size="tiny" stroke="red" />}
+ >
+ Delete Column
+ </Dropdown.Item>
+ </>
+ )}
+ </>
+ );
+ }
+
+ return (
+ <>
+ <Dropdown align="end" side="bottom" overlay={renderMenu()}>
+ <Button
+ as={'span'}
+ type="text"
+ icon={<IconChevronDown />}
+ style={{ padding: '3px' }}
+ />
+ </Dropdown>
+ </>
+ );
+};
+export default ColumnMenu;
diff --git a/studio/components/grid/components/menu/RowContextMenu.tsx b/studio/components/grid/components/menu/RowContextMenu.tsx
new file mode 100644
index 00000000000..0db4c8749c0
--- /dev/null
+++ b/studio/components/grid/components/menu/RowContextMenu.tsx
@@ -0,0 +1,90 @@
+import * as React from 'react';
+import { Menu, Item, ItemParams, PredicateParams } from 'react-contexify';
+import { IconTrash, IconClipboard, IconEdit } from '@supabase/ui';
+import { useDispatch, useTrackedState } from '../../store';
+import { formatClipboardValue, copyToClipboard } from '../../utils';
+import { showConfirmAlert } from '../common';
+
+export const ROW_CONTEXT_MENU_ID = 'row-context-menu-id';
+
+type RowContextMenuProps = {};
+
+const RowContextMenu: React.FC<RowContextMenuProps> = ({}) => {
+ const state = useTrackedState();
+ const dispatch = useDispatch();
+
+ function onDeleteRow(p: ItemParams) {
+ showConfirmAlert({
+ title: 'Confirm to delete',
+ message:
+ 'Are you sure you want to delete this row? This action cannot be undone.',
+ onConfirm: async () => {
+ const { props } = p;
+ const { rowIdx } = props;
+ const row = state.rows[rowIdx];
+ const { error } = state.rowService!.delete([row]);
+ if (error) {
+ if (state.onError) state.onError(error);
+ } else {
+ dispatch({ type: 'REMOVE_ROWS', payload: { rowIdxs: [row.idx] } });
+ dispatch({
+ type: 'SELECTED_ROWS_CHANGE',
+ payload: { selectedRows: new Set() },
+ });
+ }
+ },
+ });
+ }
+
+ function onEditRowClick(p: ItemParams) {
+ const { props } = p;
+ const { rowIdx } = props;
+ const row = state.rows[rowIdx];
+ if (state.onEditRow) state.onEditRow(row);
+ }
+
+ function isItemHidden({ data }: PredicateParams) {
+ if (data === 'edit') return state.onEditRow == undefined;
+ if (data === 'delete') return !state.editable;
+ return false;
+ }
+
+ function onCopyCellContent(p: ItemParams) {
+ const { props } = p;
+
+ if (!state.selectedCellPosition || !props) {
+ return;
+ }
+
+ const { rowIdx } = props;
+ const row = state.rows[rowIdx];
+
+ const columnKey =
+ state.gridColumns[state.selectedCellPosition?.idx as number].key;
+
+ const value = row[columnKey];
+ const text = formatClipboardValue(value);
+
+ copyToClipboard(text);
+ }
+
+ return (
+ <>
+ <Menu id={ROW_CONTEXT_MENU_ID} animation={false}>
+ <Item onClick={onCopyCellContent}>
+ <IconClipboard size="tiny" />
+ <span className="sb-grid-context-menu__label">Copy cell content</span>
+ </Item>
+ <Item onClick={onEditRowClick} hidden={isItemHidden} data="edit">
+ <IconEdit size="tiny" />
+ <span className="sb-grid-context-menu__label">Edit row</span>
+ </Item>
+ <Item onClick={onDeleteRow} hidden={isItemHidden} data="delete">
+ <IconTrash size="tiny" stroke="red" />
+ <span className="sb-grid-context-menu__label">Delete row</span>
+ </Item>
+ </Menu>
+ </>
+ );
+};
+export default RowContextMenu;
diff --git a/studio/components/grid/components/menu/RowMenu.tsx b/studio/components/grid/components/menu/RowMenu.tsx
new file mode 100644
index 00000000000..566d527c84f
--- /dev/null
+++ b/studio/components/grid/components/menu/RowMenu.tsx
@@ -0,0 +1,106 @@
+import {
+ Button,
+ Dropdown,
+ IconChevronDown,
+ Divider,
+ IconEdit,
+ IconTrash,
+} from '@supabase/ui';
+import * as React from 'react';
+import { useDispatch, useTrackedState } from '../../store';
+import { exportRowsToCsv } from '../../utils';
+import FileSaver from 'file-saver';
+import { showConfirmAlert } from '../common';
+
+type RowMenuProps = {};
+
+const RowMenu: React.FC<RowMenuProps> = ({}) => {
+ const state = useTrackedState();
+ const dispatch = useDispatch();
+ const { selectedRows, rows: allRows, editable } = state;
+
+ function onRowsDelete() {
+ showConfirmAlert({
+ title: 'Confirm to delete',
+ message:
+ 'Are you sure you want to delete the selected rows? This action cannot be undone.',
+ onConfirm: async () => {
+ const rowIdxs = Array.from(selectedRows) as number[];
+ const rows = allRows.filter(x => rowIdxs.includes(x.idx));
+ const { error } = state.rowService!.delete(rows);
+ if (error) {
+ if (state.onError) state.onError(error);
+ } else {
+ dispatch({ type: 'REMOVE_ROWS', payload: { rowIdxs } });
+ dispatch({
+ type: 'SELECTED_ROWS_CHANGE',
+ payload: { selectedRows: new Set() },
+ });
+ }
+ },
+ });
+ }
+
+ function onRowsExportCsv() {
+ const rows = allRows.filter(x => selectedRows.has(x.idx));
+ const csv = exportRowsToCsv(state.table!.columns, rows);
+ const csvData = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
+ FileSaver.saveAs(csvData, `${state.table!.name}_rows.csv`);
+ }
+
+ function onAllRowsExportCsv() {
+ const csv = exportRowsToCsv(state.table!.columns, allRows);
+ const csvData = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
+ FileSaver.saveAs(csvData, `${state.table!.name}_allRows.csv`);
+ }
+
+ return (
+ <>
+ <Dropdown
+ align="end"
+ side="bottom"
+ overlay={
+ <>
+ {selectedRows.size == 0 && (
+ <Dropdown.Item
+ onClick={onAllRowsExportCsv}
+ icon={<IconEdit size="tiny" />}
+ >
+ Export all rows to csv
+ </Dropdown.Item>
+ )}
+
+ {selectedRows.size > 0 && (
+ <Dropdown.Item
+ onClick={onRowsExportCsv}
+ icon={<IconEdit size="tiny" />}
+ >
+ Export to csv
+ </Dropdown.Item>
+ )}
+
+ {editable && selectedRows.size > 0 && (
+ <>
+ <Divider light />
+ <Dropdown.Item
+ onClick={onRowsDelete}
+ icon={<IconTrash size="tiny" stroke="red" />}
+ >
+ Delete selected rows
+ </Dropdown.Item>
+ </>
+ )}
+ </>
+ }
+ >
+ <Button
+ as={'span'}
+ type="text"
+ icon={<IconChevronDown />}
+ style={{ padding: '3px' }}
+ />
+ </Dropdown>
+ </>
+ );
+};
+export default RowMenu;
diff --git a/studio/components/grid/components/menu/index.ts b/studio/components/grid/components/menu/index.ts
new file mode 100644
index 00000000000..5e11311837f
--- /dev/null
+++ b/studio/components/grid/components/menu/index.ts
@@ -0,0 +1,7 @@
+import ColumnMenu from './ColumnMenu';
+import RowMenu from './RowMenu';
+import RowContextMenu, { ROW_CONTEXT_MENU_ID } from './RowContextMenu';
+
+const MENU_IDS = { ROW_CONTEXT_MENU_ID };
+
+export { ColumnMenu, RowContextMenu, RowMenu, MENU_IDS };
diff --git a/studio/components/grid/constants.ts b/studio/components/grid/constants.ts
new file mode 100644
index 00000000000..8706a6bd394
--- /dev/null
+++ b/studio/components/grid/constants.ts
@@ -0,0 +1,17 @@
+import PQueue from 'p-queue';
+
+export const SupabaseGridQueue = new PQueue({ concurrency: 1 });
+
+export const COLUMN_MIN_WIDTH = 100;
+
+export const STORAGE_KEY_PREFIX = 'supabase_grid';
+
+export const REFRESH_PAGE_IMMEDIATELY = -1;
+export const TOTAL_ROWS_INITIAL = -1;
+export const TOTAL_ROWS_RESET = -2;
+
+export const SELECT_COLUMN_KEY = 'supabase-grid-select-row';
+export const ADD_COLUMN_KEY = 'supabase-grid-add-column';
+
+export const ERROR_PRIMARY_KEY_NOTFOUND =
+ 'Please add a primary key column to your table to update or delete rows';
diff --git a/studio/components/grid/index.ts b/studio/components/grid/index.ts
new file mode 100644
index 00000000000..9914484540a
--- /dev/null
+++ b/studio/components/grid/index.ts
@@ -0,0 +1,7 @@
+export * from './SupabaseGrid';
+export { parseSupaTable } from './SupabaseGrid.utils';
+export * from './types';
+
+import Query from './query';
+
+export { Query };
diff --git a/studio/components/grid/query/Query.ts b/studio/components/grid/query/Query.ts
new file mode 100644
index 00000000000..ef5fe1e7ea3
--- /dev/null
+++ b/studio/components/grid/query/Query.ts
@@ -0,0 +1,18 @@
+import { IQueryAction, QueryAction } from './QueryAction';
+
+interface IQuery {
+ from: (table: string, schema?: string) => IQueryAction;
+}
+
+export class Query implements IQuery {
+ /**
+ * @param name the table name.
+ * @param schema the table schema, by default set to 'public'.
+ */
+ from(name: string, schema?: string) {
+ return new QueryAction({
+ name,
+ schema: schema ?? 'public',
+ });
+ }
+}
diff --git a/studio/components/grid/query/Query.utils.ts b/studio/components/grid/query/Query.utils.ts
new file mode 100644
index 00000000000..cca3a2dbaf2
--- /dev/null
+++ b/studio/components/grid/query/Query.utils.ts
@@ -0,0 +1,220 @@
+import { ident, literal, format } from '@scaleleap/pg-format';
+import {
+ Dictionary,
+ Filter,
+ QueryPagination,
+ QueryTable,
+ Sort,
+} from '../types';
+
+export function countQuery(
+ table: QueryTable,
+ options?: {
+ filters?: Filter[];
+ }
+) {
+ let query = `select count(*) from ${queryTable(table)}`;
+ const { filters } = options ?? {};
+ if (filters) {
+ query = applyFilters(query, filters);
+ }
+ return query + ';';
+}
+
+export function deleteQuery(
+ table: QueryTable,
+ filters?: Filter[],
+ options?: {
+ returning?: boolean;
+ }
+) {
+ if (!filters || filters.length == 0) {
+ throw { message: 'no filters for this delete query' };
+ }
+ let query = `delete from ${queryTable(table)}`;
+ const { returning } = options ?? {};
+ if (filters) {
+ query = applyFilters(query, filters);
+ }
+ if (returning) {
+ query += ' returning *';
+ }
+ return query + ';';
+}
+
+export function insertQuery(
+ table: QueryTable,
+ values: Dictionary<any>[],
+ options?: {
+ returning?: boolean;
+ }
+) {
+ if (!values || values.length == 0) {
+ throw { message: 'no value to insert' };
+ }
+ const { returning } = options ?? {};
+ const queryColumns = Object.keys(values[0])
+ .map((x) => ident(x))
+ .join(',');
+ let query = '';
+ if (queryColumns.length == 0) {
+ query = format(
+ 'insert into %1$s select from jsonb_populate_recordset(null::%1$s, %2$s)',
+ queryTable(table),
+ literal(JSON.stringify(values))
+ );
+ } else {
+ query = format(
+ 'insert into %1$s (%2$s) select %2$s from jsonb_populate_recordset(null::%1$s, %3$s)',
+ queryTable(table),
+ queryColumns,
+ literal(JSON.stringify(values))
+ );
+ }
+ if (returning) {
+ query += ' returning *';
+ }
+ return query + ';';
+}
+
+export function selectQuery(
+ table: QueryTable,
+ columns?: string[],
+ options?: {
+ filters?: Filter[];
+ pagination?: QueryPagination;
+ sorts?: Sort[];
+ }
+) {
+ let query = '';
+ const queryColumn = columns?.map((x) => ident(x)).join(', ') ?? '*';
+ query += `select ${queryColumn} from ${queryTable(table)}`;
+
+ const { filters, pagination, sorts } = options ?? {};
+ if (filters) {
+ query = applyFilters(query, filters);
+ }
+ if (sorts) {
+ query = applySorts(query, sorts);
+ }
+ if (pagination) {
+ const { limit, offset } = pagination ?? {};
+ query += ` limit ${literal(limit)} offset ${literal(offset)}`;
+ }
+ return query + ';';
+}
+
+export function updateQuery(
+ table: QueryTable,
+ value: Dictionary<any>,
+ options?: {
+ filters?: Filter[];
+ returning?: boolean;
+ }
+) {
+ const { filters, returning } = options ?? {};
+ if (!filters || filters.length == 0) {
+ throw { message: 'no filters for this update query' };
+ }
+ const queryColumns = Object.keys(value)
+ .map((x) => ident(x))
+ .join(',');
+ let query = format(
+ 'update %1$s set (%2$s) = (select %2$s from json_populate_record(null::%1$s, %3$s))',
+ queryTable(table),
+ queryColumns,
+ literal(JSON.stringify(value))
+ );
+ if (filters) {
+ query = applyFilters(query, filters);
+ }
+ if (returning) {
+ query += ' returning *';
+ }
+ return query + ';';
+}
+
+//============================================================
+// Filter Utils
+//============================================================
+
+function applyFilters(query: string, filters: Filter[]) {
+ if (filters.length == 0) return query;
+ query += ` where ${filters
+ .map((filter) => {
+ switch (filter.operator) {
+ case 'in':
+ return inFilterSql(filter);
+ case 'is':
+ return isFilterSql(filter);
+ default:
+ return `${ident(filter.column)} ${filter.operator} ${filterLiteral(
+ filter.value
+ )}`;
+ }
+ })
+ .join(' and ')}`;
+ return query;
+}
+
+function inFilterSql(filter: Filter) {
+ let values;
+ if (Array.isArray(filter.value)) {
+ values = filter.value.map((x: any) => filterLiteral(x));
+ } else {
+ const filterValueTxt = String(filter.value);
+ values = filterValueTxt.split(',').map((x: any) => filterLiteral(x));
+ }
+ return `${ident(filter.column)} ${filter.operator} (${values.join(',')})`;
+}
+
+function isFilterSql(filter: Filter) {
+ const filterValueTxt = String(filter.value);
+ switch (filterValueTxt) {
+ case 'null':
+ case 'false':
+ case 'true':
+ case 'not null':
+ return `${ident(filter.column)} ${filter.operator} ${filterValueTxt}`;
+ default:
+ return `${ident(filter.column)} ${filter.operator} ${filterLiteral(
+ filter.value
+ )}`;
+ }
+}
+
+function filterLiteral(value: any) {
+ if (typeof value === 'string') {
+ const temp = value.trim();
+ if (temp?.startsWith('ARRAY[') && temp?.endsWith(']')) {
+ return temp;
+ } else {
+ return literal(temp);
+ }
+ }
+ return value;
+}
+
+//============================================================
+// Sort Utils
+//============================================================
+
+function applySorts(query: string, sorts: Sort[]) {
+ if (sorts.length == 0) return query;
+ query += ` order by ${sorts
+ .map((x) => {
+ const order = x.ascending ? 'asc' : 'desc';
+ const nullOrder = x.nullsFirst ? 'nulls first' : 'nulls last';
+ return `${ident(x.column)} ${order} ${nullOrder}`;
+ })
+ .join(', ')}`;
+ return query;
+}
+
+//============================================================
+// Misc
+//============================================================
+
+function queryTable(table: QueryTable) {
+ return `${ident(table.schema)}.${ident(table.name)}`;
+}
diff --git a/studio/components/grid/query/QueryAction.ts b/studio/components/grid/query/QueryAction.ts
new file mode 100644
index 00000000000..b7fe77431a8
--- /dev/null
+++ b/studio/components/grid/query/QueryAction.ts
@@ -0,0 +1,65 @@
+import { Dictionary, QueryTable } from '../types';
+import { IQueryFilter, QueryFilter } from './QueryFilter';
+
+export interface IQueryAction {
+ count: () => IQueryFilter;
+ delete: (options?: { returning: boolean }) => IQueryFilter;
+ insert: (
+ values: Dictionary<any> | Dictionary<any>[],
+ options?: { returning: boolean }
+ ) => IQueryFilter;
+ select: (columns?: string[]) => IQueryFilter;
+ update: (
+ value: Dictionary<any>,
+ options?: { returning: boolean }
+ ) => IQueryFilter;
+}
+
+export class QueryAction implements IQueryAction {
+ constructor(protected table: QueryTable) {}
+
+ /**
+ * Performs a COUNT on the table.
+ */
+ count() {
+ return new QueryFilter(this.table, 'count');
+ }
+
+ /**
+ * Performs a DELETE on the table.
+ *
+ * @param options.returning If `true`, return the deleted row(s) in the response.
+ */
+ delete(options?: { returning: boolean }) {
+ return new QueryFilter(this.table, 'delete', undefined, options);
+ }
+
+ /**
+ * Performs an INSERT into the table.
+ *
+ * @param values The values to insert.
+ * @param options.returning If `true`, return the inserted row(s) in the response.
+ */
+ insert(values: Dictionary<any>[], options?: { returning: boolean }) {
+ return new QueryFilter(this.table, 'insert', values, options);
+ }
+
+ /**
+ * Performs vertical filtering with SELECT.
+ *
+ * @param columns the query columns, by default set to '*'.
+ */
+ select(columns?: string[]) {
+ return new QueryFilter(this.table, 'select', columns);
+ }
+
+ /**
+ * Performs an UPDATE on the table.
+ *
+ * @param value The value to update.
+ * @param options.returning If `true`, return the updated row(s) in the response.
+ */
+ update(value: Dictionary<any>, options?: { returning: boolean }) {
+ return new QueryFilter(this.table, 'update', value, options);
+ }
+}
diff --git a/studio/components/grid/query/QueryFilter.ts b/studio/components/grid/query/QueryFilter.ts
new file mode 100644
index 00000000000..41e1ffbac11
--- /dev/null
+++ b/studio/components/grid/query/QueryFilter.ts
@@ -0,0 +1,66 @@
+import { Dictionary, Filter, FilterOperator, QueryTable, Sort } from '../types';
+import { IQueryModifier, QueryModifier } from './QueryModifier';
+
+export interface IQueryFilter {
+ filter: (
+ column: string,
+ operator: FilterOperator,
+ value: string
+ ) => IQueryFilter;
+ match: (criteria: Dictionary<any>) => IQueryFilter;
+ order: (
+ column: string,
+ ascending?: boolean,
+ nullsFirst?: boolean
+ ) => IQueryFilter;
+}
+
+export class QueryFilter implements IQueryFilter, IQueryModifier {
+ protected filters: Filter[] = [];
+ protected sorts: Sort[] = [];
+
+ constructor(
+ protected table: QueryTable,
+ protected action: 'count' | 'delete' | 'insert' | 'select' | 'update',
+ protected actionValue?: string[] | Dictionary<any> | Dictionary<any>[],
+ protected actionOptions?: { returning: boolean }
+ ) {}
+
+ filter(column: string, operator: FilterOperator, value: any) {
+ this.filters.push({ column, operator, value });
+ return this;
+ }
+
+ match(criteria: Dictionary<any>) {
+ Object.entries(criteria).map(([column, value]) => {
+ this.filters.push({ column, operator: '=', value });
+ });
+ return this;
+ }
+
+ order(column: string, ascending = true, nullsFirst = false) {
+ this.sorts.push({
+ column: column,
+ ascending,
+ nullsFirst,
+ });
+ return this;
+ }
+
+ range(from: number, to: number) {
+ return this._getQueryModifier().range(from, to);
+ }
+
+ toSql() {
+ return this._getQueryModifier().toSql();
+ }
+
+ _getQueryModifier() {
+ return new QueryModifier(this.table, this.action, {
+ actionValue: this.actionValue,
+ actionOptions: this.actionOptions,
+ filters: this.filters,
+ sorts: this.sorts,
+ });
+ }
+}
diff --git a/studio/components/grid/query/QueryModifier.ts b/studio/components/grid/query/QueryModifier.ts
new file mode 100644
index 00000000000..bec0a75c43b
--- /dev/null
+++ b/studio/components/grid/query/QueryModifier.ts
@@ -0,0 +1,87 @@
+import {
+ Dictionary,
+ Filter,
+ QueryPagination,
+ QueryTable,
+ Sort,
+} from '../types';
+import {
+ countQuery,
+ deleteQuery,
+ insertQuery,
+ selectQuery,
+ updateQuery,
+} from './Query.utils';
+
+export interface IQueryModifier {
+ range: (from: number, to: number) => QueryModifier;
+ toSql: () => string;
+}
+
+export class QueryModifier implements IQueryModifier {
+ protected pagination?: QueryPagination;
+
+ constructor(
+ protected table: QueryTable,
+ protected action: 'count' | 'delete' | 'insert' | 'select' | 'update',
+ protected options?: {
+ actionValue?: string[] | Dictionary<any> | Dictionary<any>[];
+ actionOptions?: { returning: boolean };
+ filters?: Filter[];
+ sorts?: Sort[];
+ }
+ ) {}
+
+ /**
+ * Limits the result to rows within the specified range, inclusive.
+ *
+ * @param from The starting index from which to limit the result, inclusive.
+ * @param to The last index to which to limit the result, inclusive.
+ */
+ range(from: number, to: number) {
+ this.pagination = { offset: from, limit: to - from + 1 };
+ return this;
+ }
+
+ /**
+ * Return SQL string for query chains
+ */
+ toSql() {
+ try {
+ const { actionValue, actionOptions, filters, sorts } = this.options ?? {};
+ switch (this.action) {
+ case 'count': {
+ return countQuery(this.table, { filters });
+ }
+ case 'delete': {
+ return deleteQuery(this.table, filters, {
+ returning: actionOptions?.returning,
+ });
+ }
+ case 'insert': {
+ return insertQuery(this.table, actionValue as Dictionary<any>[], {
+ returning: actionOptions?.returning,
+ });
+ }
+ case 'select': {
+ return selectQuery(this.table, actionValue as string[] | undefined, {
+ filters,
+ pagination: this.pagination,
+ sorts,
+ });
+ }
+ case 'update': {
+ return updateQuery(this.table, actionValue as Dictionary<any>, {
+ filters,
+ returning: actionOptions?.returning,
+ });
+ }
+ default: {
+ return '';
+ }
+ }
+ } catch (error) {
+ throw error;
+ }
+ }
+}
diff --git a/studio/components/grid/query/index.ts b/studio/components/grid/query/index.ts
new file mode 100644
index 00000000000..27ced1506de
--- /dev/null
+++ b/studio/components/grid/query/index.ts
@@ -0,0 +1,3 @@
+import { Query } from './Query';
+
+export default Query;
diff --git a/studio/components/grid/services/meta/SqlMetaService.sqls.ts b/studio/components/grid/services/meta/SqlMetaService.sqls.ts
new file mode 100644
index 00000000000..a8ccea92cc3
--- /dev/null
+++ b/studio/components/grid/services/meta/SqlMetaService.sqls.ts
@@ -0,0 +1,192 @@
+import { format } from '@scaleleap/pg-format';
+
+export function getColumnsSql(filter_schema: string, filter_name: string) {
+ return format(columnsSql, filter_schema, filter_name);
+}
+const columnsSql = `
+SELECT
+ c.oid :: int8 AS table_id,
+ nc.nspname AS schema,
+ c.relname AS table,
+ (c.oid || '.' || a.attnum) AS id,
+ a.attnum AS ordinal_position,
+ a.attname AS name,
+ CASE
+ WHEN a.atthasdef THEN pg_get_expr(ad.adbin, ad.adrelid)
+ ELSE NULL
+ END AS default_value,
+ CASE
+ WHEN t.typtype = 'd' THEN CASE
+ WHEN bt.typelem <> 0 :: oid
+ AND bt.typlen = -1 THEN 'ARRAY'
+ WHEN nbt.nspname = 'pg_catalog' THEN format_type(t.typbasetype, NULL)
+ ELSE 'USER-DEFINED'
+ END
+ ELSE CASE
+ WHEN t.typelem <> 0 :: oid
+ AND t.typlen = -1 THEN 'ARRAY'
+ WHEN nt.nspname = 'pg_catalog' THEN format_type(a.atttypid, NULL)
+ ELSE 'USER-DEFINED'
+ END
+ END AS data_type,
+ COALESCE(bt.typname, t.typname) AS format,
+ CASE
+ WHEN a.attidentity IN ('a', 'd') THEN TRUE
+ ELSE FALSE
+ END AS is_identity,
+ CASE
+ a.attidentity
+ WHEN 'a' THEN 'ALWAYS'
+ WHEN 'd' THEN 'BY DEFAULT'
+ ELSE NULL
+ END AS identity_generation,
+ CASE
+ WHEN a.attnotnull
+ OR t.typtype = 'd'
+ AND t.typnotnull THEN FALSE
+ ELSE TRUE
+ END AS is_nullable,
+ CASE
+ WHEN (
+ c.relkind IN ('r', 'p')
+ )
+ OR (
+ c.relkind IN ('v', 'f')
+ )
+ AND pg_column_is_updatable(c.oid, a.attnum, FALSE) THEN TRUE
+ ELSE FALSE
+ END AS is_updatable,
+ array_to_json(
+ array(
+ SELECT
+ enumlabel
+ FROM
+ pg_catalog.pg_enum enums
+ WHERE
+ quote_ident(COALESCE(bt.typname, t.typname)) = format_type(enums.enumtypid, NULL)
+ ORDER BY
+ enums.enumsortorder
+ )
+ ) AS enums,
+ col_description(c.oid, a.attnum) AS comment
+FROM
+ pg_attribute a
+ LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid
+ AND a.attnum = ad.adnum
+ JOIN (
+ pg_class c
+ JOIN pg_namespace nc ON c.relnamespace = nc.oid
+ ) ON a.attrelid = c.oid
+ JOIN (
+ pg_type t
+ JOIN pg_namespace nt ON t.typnamespace = nt.oid
+ ) ON a.atttypid = t.oid
+ LEFT JOIN (
+ pg_type bt
+ JOIN pg_namespace nbt ON bt.typnamespace = nbt.oid
+ ) ON t.typtype = 'd'
+ AND t.typbasetype = bt.oid
+WHERE
+ NOT pg_is_other_temp_schema(nc.oid)
+ AND nc.nspname = %L
+ AND c.relname = %L
+ AND a.attnum > 0
+ AND NOT a.attisdropped
+ AND (c.relkind IN ('r', 'v', 'f', 'p'))
+ AND (
+ pg_has_role(c.relowner, 'USAGE')
+ OR has_column_privilege(
+ c.oid,
+ a.attnum,
+ 'SELECT, INSERT, UPDATE, REFERENCES'
+ )
+ )
+`;
+
+export function getPrimaryKeysSql(filter_schema: string, filter_name: string) {
+ return format(primaryKeysSql, filter_schema, filter_name);
+}
+const primaryKeysSql = `
+SELECT
+ n.nspname AS schema,
+ c.relname AS table_name,
+ a.attname AS name,
+ c.oid :: int8 AS table_id
+FROM
+ pg_index i,
+ pg_class c,
+ pg_attribute a,
+ pg_namespace n
+WHERE
+ n.nspname = %L
+ AND c.relname = %L
+ AND i.indrelid = c.oid
+ AND c.relnamespace = n.oid
+ AND a.attrelid = c.oid
+ AND a.attnum = ANY (i.indkey)
+ AND i.indisprimary
+`;
+
+export function getRelationshipsSql(
+ filter_schema: string,
+ filter_name: string
+) {
+ return format(relationshipsSql, filter_schema, filter_name);
+}
+const relationshipsSql = `
+SELECT
+ c.oid :: int8 AS id,
+ c.conname AS constraint_name,
+ nsa.nspname AS source_schema,
+ csa.relname AS source_table_name,
+ sa.attname AS source_column_name,
+ nta.nspname AS target_table_schema,
+ cta.relname AS target_table_name,
+ ta.attname AS target_column_name
+FROM
+ pg_constraint c
+ JOIN (
+ pg_attribute sa
+ JOIN pg_class csa ON sa.attrelid = csa.oid
+ JOIN pg_namespace nsa ON csa.relnamespace = nsa.oid
+ ) ON sa.attrelid = c.conrelid
+ AND sa.attnum = ANY (c.conkey)
+ JOIN (
+ pg_attribute ta
+ JOIN pg_class cta ON ta.attrelid = cta.oid
+ JOIN pg_namespace nta ON cta.relnamespace = nta.oid
+ ) ON ta.attrelid = c.confrelid
+ AND ta.attnum = ANY (c.confkey)
+WHERE
+ c.contype = 'f'
+ AND nsa.nspname = %L
+ AND csa.relname = %L;
+`;
+
+export function getTableSql(filter_schema: string, filter_name: string) {
+ return format(tableSql, filter_schema, filter_name);
+}
+const tableSql = `
+SELECT
+ c.oid :: int8 AS id,
+ nc.nspname AS schema,
+ c.relname AS name,
+ pg_stat_get_live_tuples(c.oid) AS live_rows_estimate,
+ obj_description(c.oid) AS comment
+FROM
+ pg_namespace nc
+ JOIN pg_class c ON nc.oid = c.relnamespace
+WHERE
+ nc.nspname = %L
+ AND c.relname = %L
+ AND c.relkind IN ('r', 'p')
+ AND NOT pg_is_other_temp_schema(nc.oid)
+ AND (
+ pg_has_role(c.relowner, 'USAGE')
+ OR has_table_privilege(
+ c.oid,
+ 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'
+ )
+ OR has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES')
+ )
+`;
diff --git a/studio/components/grid/services/meta/SqlMetaService.ts b/studio/components/grid/services/meta/SqlMetaService.ts
new file mode 100644
index 00000000000..9d5da5ca165
--- /dev/null
+++ b/studio/components/grid/services/meta/SqlMetaService.ts
@@ -0,0 +1,56 @@
+import { IMetaService } from '.';
+import {
+ getColumnsSql,
+ getPrimaryKeysSql,
+ getRelationshipsSql,
+ getTableSql,
+} from './SqlMetaService.sqls';
+
+export class SqlMetaService implements IMetaService {
+ constructor(
+ protected onSqlQuery: (
+ query: string
+ ) => Promise<{ data?: any; error?: any }>
+ ) {}
+
+ async fetchInfo(name: string, schema?: string | undefined) {
+ const sql = getTableSql(schema ?? 'public', name);
+ const { data, error } = await this.onSqlQuery(sql);
+ if (error) {
+ return { error };
+ } else {
+ if (data?.length == 1) {
+ return { data: data[0] };
+ } else {
+ return { error: { message: 'fetch table info failed' } };
+ }
+ }
+ }
+ async fetchColumns(name: string, schema?: string | undefined) {
+ const sql = getColumnsSql(schema ?? 'public', name);
+ const { data, error } = await this.onSqlQuery(sql);
+ if (error) {
+ return { error };
+ } else {
+ return { data };
+ }
+ }
+ async fetchPrimaryKeys(name: string, schema?: string | undefined) {
+ const sql = getPrimaryKeysSql(schema ?? 'public', name);
+ const { data, error } = await this.onSqlQuery(sql);
+ if (error) {
+ return { error };
+ } else {
+ return { data };
+ }
+ }
+ async fetchRelationships(name: string, schema?: string | undefined) {
+ const sql = getRelationshipsSql(schema ?? 'public', name);
+ const { data, error } = await this.onSqlQuery(sql);
+ if (error) {
+ return { error };
+ } else {
+ return { data };
+ }
+ }
+}
diff --git a/studio/components/grid/services/meta/index.ts b/studio/components/grid/services/meta/index.ts
new file mode 100644
index 00000000000..48caf4dfe99
--- /dev/null
+++ b/studio/components/grid/services/meta/index.ts
@@ -0,0 +1,22 @@
+import { Dictionary, ServiceError } from '../../types';
+
+export interface IMetaService {
+ fetchInfo: (
+ name: string,
+ schema?: string
+ ) => Promise<{ data?: Dictionary<any>; error?: ServiceError }>;
+ fetchColumns: (
+ name: string,
+ schema?: string
+ ) => Promise<{ data?: Dictionary<any>[]; error?: ServiceError }>;
+ fetchPrimaryKeys: (
+ name: string,
+ schema?: string
+ ) => Promise<{ data?: Dictionary<any>[]; error?: ServiceError }>;
+ fetchRelationships: (
+ name: string,
+ schema?: string
+ ) => Promise<{ data?: Dictionary<any>[]; error?: ServiceError }>;
+}
+
+export * from './SqlMetaService';
diff --git a/studio/components/grid/services/row/SqlRowService.ts b/studio/components/grid/services/row/SqlRowService.ts
new file mode 100644
index 00000000000..057d56ad3d0
--- /dev/null
+++ b/studio/components/grid/services/row/SqlRowService.ts
@@ -0,0 +1,157 @@
+import { IRowService } from '.';
+import { Filter, ServiceError, Sort, SupaRow, SupaTable } from '../../types';
+import { ERROR_PRIMARY_KEY_NOTFOUND, SupabaseGridQueue } from '../../constants';
+import Query from '../../query';
+import { isNumericalColumn } from '../../utils';
+
+export class SqlRowService implements IRowService {
+ protected query = new Query();
+
+ constructor(
+ protected table: SupaTable,
+ protected onSqlQuery: (
+ query: string
+ ) => Promise<{ data?: any; error?: any }>,
+ protected onError: (error: any) => void
+ ) {}
+
+ async count(filters: Filter[]) {
+ let queryChains = this.query
+ .from(this.table.name, this.table.schema ?? undefined)
+ .count();
+ filters
+ .filter((x) => x.value && x.value != '')
+ .forEach((x) => {
+ const value = this.formatFilterValue(x);
+ queryChains = queryChains.filter(x.column, x.operator, value);
+ });
+
+ const query = queryChains.toSql();
+ const { data, error } = await this.onSqlQuery(query);
+ if (error) {
+ return { error };
+ } else {
+ if (data?.length == 1) {
+ return { data: data[0].count };
+ } else {
+ return { error: { message: 'fetch rows count failed' } };
+ }
+ }
+ }
+
+ async create(row: SupaRow) {
+ console.log('create: ', row);
+ return { error: { message: 'not implemented' } };
+ }
+
+ delete(rows: SupaRow[]) {
+ const { primaryKeys, error } = this.getPrimaryKeys();
+ if (error) return { error };
+
+ let queryChains = this.query
+ .from(this.table.name, this.table.schema ?? undefined)
+ .delete();
+
+ primaryKeys!.forEach((key) => {
+ const primaryKeyValues = rows.map((x) => x[key]);
+ queryChains = queryChains.filter(key, 'in', primaryKeyValues);
+ });
+
+ const query = queryChains.toSql();
+ SupabaseGridQueue.add(async () => {
+ const { error } = await this.onSqlQuery(query);
+ if (error) throw error;
+ }).catch((error) => {
+ this.onError(error);
+ });
+
+ return {};
+ }
+
+ async fetchPage(
+ page: number,
+ rowsPerPage: number,
+ filters: Filter[],
+ sorts: Sort[]
+ ) {
+ const pageFromZero = page > 0 ? page - 1 : page;
+ const from = pageFromZero * rowsPerPage;
+ const to = (pageFromZero + 1) * rowsPerPage - 1;
+ let queryChains = this.query
+ .from(this.table.name, this.table.schema ?? undefined)
+ .select();
+ filters
+ .filter((x) => x.value && x.value != '')
+ .forEach((x) => {
+ const value = this.formatFilterValue(x);
+ queryChains = queryChains.filter(x.column, x.operator, value);
+ });
+ sorts.forEach((x) => {
+ queryChains = queryChains.order(x.column, x.ascending, x.nullsFirst);
+ });
+
+ const query = queryChains.range(from, to).toSql();
+ const { data, error } = await this.onSqlQuery(query);
+ if (error) {
+ this.onError(error);
+ return { data: { rows: [] } };
+ } else {
+ const rows = data?.map((x: any, index: number) => {
+ return { idx: index, ...x } as SupaRow;
+ });
+ return { data: { rows } };
+ }
+ }
+
+ update(row: SupaRow, changedColumn?: string) {
+ const { primaryKeys, error } = this.getPrimaryKeys();
+ if (error) {
+ return { error };
+ }
+ const { idx, ...value } = row;
+ const matchValues: any = {};
+ primaryKeys!.forEach((key) => {
+ matchValues[key] = row[key];
+ // fix: https://github.com/supabase/grid/issues/94
+ // remove primary key from updated value object
+ delete value[key];
+ });
+ const query = this.query
+ .from(this.table.name, this.table.schema ?? undefined)
+ .update(changedColumn ? {
+ [changedColumn]: value[changedColumn]
+ }: value)
+ .match(matchValues)
+ .toSql();
+ SupabaseGridQueue.add(async () => {
+ const { error } = await this.onSqlQuery(query);
+ if (error) throw error;
+ }).catch((error) => {
+ this.onError(error);
+ });
+
+ return {};
+ }
+
+ getPrimaryKeys(): { primaryKeys?: string[]; error?: ServiceError } {
+ const pkColumns = this.table.columns.filter((x) => x.isPrimaryKey);
+ if (!pkColumns || pkColumns.length == 0) {
+ return { error: { message: ERROR_PRIMARY_KEY_NOTFOUND } };
+ }
+ return { primaryKeys: pkColumns.map((x) => x.name) };
+ }
+
+ /**
+ * temporary fix until we impliment a better filter UI
+ * which validate input value base on the column type
+ */
+ formatFilterValue(filter: Filter) {
+ const column = this.table.columns.find((x) => x.name == filter.column);
+ if (column && isNumericalColumn(column.format)) {
+ const numberValue = Number(filter.value);
+ if (Number.isNaN(numberValue)) return filter.value;
+ else return Number(filter.value);
+ }
+ return filter.value;
+ }
+}
diff --git a/studio/components/grid/services/row/index.tsx b/studio/components/grid/services/row/index.tsx
new file mode 100644
index 00000000000..36bbb934ff3
--- /dev/null
+++ b/studio/components/grid/services/row/index.tsx
@@ -0,0 +1,33 @@
+import { Filter, ServiceError, Sort, SupaRow } from '../../types';
+
+export interface IRowService {
+ count: (
+ filters: Filter[]
+ ) => Promise<{ data?: number; error?: ServiceError }>;
+
+ create: (row: SupaRow) => Promise<{ data?: SupaRow; error?: ServiceError }>;
+
+ fetchPage: (
+ page: number,
+ rowsPerPage: number,
+ filters: Filter[],
+ sorts: Sort[]
+ ) => Promise<{
+ data?: { rows: SupaRow[] };
+ error?: ServiceError;
+ }>;
+
+ /**
+ * TODO: should return a promise.
+ * We should show loading indicator when deleting rows (on row level).
+ * Only remove rows from the grid when delete returns success result.
+ * ---
+ * Right now, we remove rows immediately, so it's confused when delete operation fails
+ * and rows are already removed from the grid
+ */
+ delete: (rows: SupaRow[]) => { error?: ServiceError };
+
+ update: (row: SupaRow, changedColumn?: string) => { error?: ServiceError };
+}
+
+export * from './SqlRowService';
diff --git a/studio/components/grid/store/Store.tsx b/studio/components/grid/store/Store.tsx
new file mode 100644
index 00000000000..99a9659b05c
--- /dev/null
+++ b/studio/components/grid/store/Store.tsx
@@ -0,0 +1,37 @@
+import { useReducer } from 'react';
+import { createContainer } from 'react-tracked';
+import {
+ BaseReducer,
+ CallbackReducer,
+ ColumnReducer,
+ FilterReducer,
+ RowReducer,
+ SortReducer,
+ initialState,
+ InitialStateType,
+} from './reducers';
+
+const combineReducers = (...reducers: Function[]) => (
+ state: any = initialState,
+ action: any
+): any => {
+ for (let i = 0; i < reducers.length; i++) state = reducers[i](state, action);
+ return state;
+};
+
+const storeReducers = combineReducers(
+ BaseReducer,
+ CallbackReducer,
+ ColumnReducer,
+ FilterReducer,
+ RowReducer,
+ SortReducer
+);
+
+const useValue = () => useReducer(storeReducers, initialState);
+
+export const {
+ Provider: StoreProvider,
+ useTrackedState,
+ useUpdate: useDispatch,
+} = createContainer<InitialStateType, React.Dispatch<any>, unknown>(useValue);
diff --git a/studio/components/grid/store/index.ts b/studio/components/grid/store/index.ts
new file mode 100644
index 00000000000..47e0805c13b
--- /dev/null
+++ b/studio/components/grid/store/index.ts
@@ -0,0 +1 @@
+export * from './Store';
diff --git a/studio/components/grid/store/reducers/base.ts b/studio/components/grid/store/reducers/base.ts
new file mode 100644
index 00000000000..2a7a6d463e6
--- /dev/null
+++ b/studio/components/grid/store/reducers/base.ts
@@ -0,0 +1,74 @@
+import { CalculatedColumn } from '@supabase/react-data-grid';
+import { GridProps, SavedState, SupaTable } from '../../types';
+import { REFRESH_PAGE_IMMEDIATELY } from '../../constants';
+import { IRowService, SqlRowService } from '../../services/row';
+import { IMetaService, SqlMetaService } from '../../services/meta';
+
+export interface BaseInitialState {
+ table: SupaTable | null;
+ metaService: IMetaService | null;
+ rowService: IRowService | null;
+ refreshPageFlag: number;
+ isInitialComplete: boolean;
+ editable: boolean;
+}
+
+export const baseInitialState: BaseInitialState = {
+ table: null,
+ metaService: null,
+ rowService: null,
+ refreshPageFlag: 0,
+ isInitialComplete: false,
+ editable: false,
+};
+
+export type INIT_ACTIONTYPE =
+ | {
+ type: 'INIT_CLIENT';
+ payload: {
+ onSqlQuery: (query: string) => Promise<{ data?: any; error?: any }>;
+ };
+ }
+ | {
+ type: 'INIT_TABLE';
+ payload: {
+ table: SupaTable;
+ gridColumns: CalculatedColumn<any, any>[];
+ gridProps?: GridProps;
+ savedState?: SavedState;
+ editable?: boolean;
+ onSqlQuery: (query: string) => Promise<{ data?: any; error?: any }>;
+ onError: (error: any) => void;
+ };
+ };
+
+type BASE_ACTIONTYPE = INIT_ACTIONTYPE;
+
+const BaseReducer = (state: BaseInitialState, action: BASE_ACTIONTYPE) => {
+ switch (action.type) {
+ case 'INIT_CLIENT': {
+ return {
+ ...state,
+ metaService: new SqlMetaService(action.payload.onSqlQuery),
+ };
+ }
+ case 'INIT_TABLE': {
+ return {
+ ...state,
+ table: action.payload.table,
+ rowService: new SqlRowService(
+ action.payload.table,
+ action.payload.onSqlQuery,
+ action.payload.onError
+ ),
+ refreshPageFlag: REFRESH_PAGE_IMMEDIATELY,
+ isInitialComplete: true,
+ editable: action.payload.editable || false,
+ };
+ }
+ default:
+ return state;
+ }
+};
+
+export default BaseReducer;
diff --git a/studio/components/grid/store/reducers/callback.ts b/studio/components/grid/store/reducers/callback.ts
new file mode 100644
index 00000000000..edb6060008d
--- /dev/null
+++ b/studio/components/grid/store/reducers/callback.ts
@@ -0,0 +1,61 @@
+import { SupaRow } from '../../types';
+
+export interface CallbackInitialState {
+ onAddColumn: (() => void) | null;
+ onAddRow: (() => void) | null;
+ onError: ((error: any) => void) | null;
+ onEditRow: ((row: SupaRow) => void) | null;
+ onEditColumn: ((columnName: string) => void) | null;
+ onDeleteColumn: ((columnName: string) => void) | null;
+ onSqlQuery: ((query: string) => Promise<{ data?: any; error?: any }>) | null;
+}
+
+export const callbackInitialState: CallbackInitialState = {
+ onAddColumn: null,
+ onAddRow: null,
+ onError: null,
+ onEditRow: null,
+ onEditColumn: null,
+ onDeleteColumn: null,
+ onSqlQuery: null,
+};
+
+type CALLBACK_ACTIONTYPE = {
+ type: 'INIT_CALLBACK';
+ payload: {
+ onAddColumn: (() => void) | null;
+ onAddRow: (() => void) | null;
+ onError: ((error: any) => void) | null;
+ onEditRow: ((row: SupaRow) => void) | null;
+ onEditColumn: ((columnName: string) => void) | null;
+ onDeleteColumn: ((columnName: string) => void) | null;
+ onSqlQuery:
+ | ((query: string) => Promise<{ data?: any; error?: any }>)
+ | null;
+ };
+};
+
+const CallbackReducer = (
+ state: CallbackInitialState,
+ action: CALLBACK_ACTIONTYPE
+) => {
+ switch (action.type) {
+ case 'INIT_CALLBACK': {
+ return {
+ ...state,
+ onAddColumn: action.payload.onAddColumn,
+ onAddRow: action.payload.onAddRow,
+ onError: action.payload.onError,
+ onEditRow: action.payload.onEditRow,
+ onEditColumn: action.payload.onEditColumn,
+ onDeleteColumn: action.payload.onDeleteColumn,
+ onSqlQuery: action.payload.onSqlQuery,
+ };
+ }
+
+ default:
+ return state;
+ }
+};
+
+export default CallbackReducer;
diff --git a/studio/components/grid/store/reducers/column.ts b/studio/components/grid/store/reducers/column.ts
new file mode 100644
index 00000000000..b63afe14ce7
--- /dev/null
+++ b/studio/components/grid/store/reducers/column.ts
@@ -0,0 +1,124 @@
+import update from 'immutability-helper';
+import { CalculatedColumn } from '@supabase/react-data-grid';
+import { cloneColumn, getInitialGridColumns } from '../../utils';
+import { INIT_ACTIONTYPE } from './base';
+
+export interface ColumnInitialState {
+ gridColumns: CalculatedColumn <any, any>[];
+}
+
+export const columnInitialState: ColumnInitialState = {
+ gridColumns: [],
+};
+
+type COLUMN_ACTIONTYPE =
+ | INIT_ACTIONTYPE
+ | {
+ type: 'MOVE_COLUMN';
+ payload: { fromKey: string; toKey: string };
+ }
+ | {
+ type: 'UPDATE_COLUMN_SIZE';
+ payload: { index: number; width: number };
+ }
+ | {
+ type: 'FREEZE_COLUMN';
+ payload: { columnKey: string };
+ }
+ | {
+ type: 'UNFREEZE_COLUMN';
+ payload: { columnKey: string };
+ }
+ | {
+ type: 'UPDATE_COLUMN_IDX';
+ payload: { columnKey: string; columnIdx: number };
+ };
+
+const ColumnReducer = (
+ state: ColumnInitialState,
+ action: COLUMN_ACTIONTYPE
+) => {
+ switch (action.type) {
+ case 'INIT_TABLE': {
+ return {
+ ...state,
+ gridColumns: getInitialGridColumns(
+ action.payload.gridColumns,
+ action.payload.savedState
+ ),
+ };
+ }
+ case 'MOVE_COLUMN': {
+ const fromIdx = state.gridColumns.findIndex(
+ x => x.key === action.payload.fromKey
+ );
+ const toIdx = state.gridColumns.findIndex(
+ x => x.key === action.payload.toKey
+ );
+ const moveItem = state.gridColumns[fromIdx];
+ return {
+ ...state,
+ gridColumns: update(state.gridColumns, {
+ $splice: [
+ [fromIdx, 1],
+ [toIdx, 0, moveItem],
+ ],
+ }),
+ };
+ }
+ case 'UPDATE_COLUMN_SIZE': {
+ const updated = cloneColumn(state.gridColumns[action.payload.index]);
+ updated.width = action.payload.width;
+ return {
+ ...state,
+ gridColumns: update(state.gridColumns, {
+ [action.payload.index]: { $set: updated },
+ }),
+ };
+ }
+ case 'FREEZE_COLUMN': {
+ const columnIdx = state.gridColumns.findIndex(
+ x => x.key === action.payload.columnKey
+ );
+ const updated = cloneColumn(state.gridColumns[columnIdx]);
+ updated.frozen = true;
+ return {
+ ...state,
+ gridColumns: update(state.gridColumns, {
+ [columnIdx]: { $set: updated },
+ }),
+ };
+ }
+ case 'UNFREEZE_COLUMN': {
+ const columnIdx = state.gridColumns.findIndex(
+ x => x.key === action.payload.columnKey
+ );
+ const updated = cloneColumn(state.gridColumns[columnIdx]);
+ updated.frozen = false;
+ return {
+ ...state,
+ gridColumns: update(state.gridColumns, {
+ [columnIdx]: { $set: updated },
+ }),
+ };
+ }
+ case 'UPDATE_COLUMN_IDX': {
+ const index = state.gridColumns.findIndex(
+ x => x.key === action.payload.columnKey
+ );
+ const updated = cloneColumn(state.gridColumns[index]);
+ updated.idx = action.payload.columnIdx;
+ return {
+ ...state,
+ gridColumns: update(state.gridColumns, {
+ [index]: { $set: updated },
+ })
+ .sort((a, b) => a.idx - b.idx),
+ };
+ }
+ default:
+ return state;
+ }
+};
+
+export default ColumnReducer;
diff --git a/studio/components/grid/store/reducers/filter.ts b/studio/components/grid/store/reducers/filter.ts
new file mode 100644
index 00000000000..da342e35144
--- /dev/null
+++ b/studio/components/grid/store/reducers/filter.ts
@@ -0,0 +1,116 @@
+import update from 'immutability-helper';
+import { TOTAL_ROWS_RESET } from '../../constants';
+import { Filter } from '../../types';
+import { getInitialFilters } from '../../utils';
+import { INIT_ACTIONTYPE } from './base';
+
+export interface FilterInitialState {
+ filters: Filter[];
+}
+
+export const filterInitialState: FilterInitialState = { filters: [] };
+
+type FILTER_ACTIONTYPE =
+ | INIT_ACTIONTYPE
+ | {
+ type: 'SET_FILTERS';
+ payload: Filter[];
+ }
+ | {
+ type: 'ADD_FILTER';
+ payload: Filter;
+ }
+ | {
+ type: 'REMOVE_FILTER';
+ payload: { index: number };
+ }
+ | {
+ type: 'UPDATE_FILTER';
+ payload: {
+ filterIdx: number;
+ value: Filter;
+ };
+ };
+
+const FilterReducer = (
+ state: FilterInitialState,
+ action: FILTER_ACTIONTYPE
+) => {
+ switch (action.type) {
+ case 'INIT_TABLE': {
+ return {
+ ...state,
+ filters: getInitialFilters(
+ action.payload.table,
+ action.payload.savedState
+ ),
+ };
+ }
+ case 'SET_FILTERS':
+ return {
+ ...state,
+ filters: action.payload,
+ };
+ case 'ADD_FILTER': {
+ const isValid = isValidFilter(action.payload);
+ const newState: any = {
+ ...state,
+ filters: update(state.filters, { $push: [action.payload] }),
+ };
+ if (isValid) {
+ newState.page = 1;
+ newState.refreshPageFlag = Date.now();
+ newState.totalRows = TOTAL_ROWS_RESET;
+ }
+ return newState;
+ }
+ case 'REMOVE_FILTER': {
+ const removeIdx = action.payload.index;
+ const removeFilter = state.filters[removeIdx];
+ const isValid = isValidFilter(removeFilter);
+ const newState: any = {
+ ...state,
+ filters: update(state.filters, {
+ $splice: [[removeIdx, 1]],
+ }),
+ };
+ if (isValid) {
+ newState.page = 1;
+ newState.refreshPageFlag = Date.now();
+ newState.totalRows = TOTAL_ROWS_RESET;
+ }
+ return newState;
+ }
+ case 'UPDATE_FILTER': {
+ const updatedFilter = state.filters[action.payload.filterIdx];
+ const previousIsValid = isValidFilter(updatedFilter);
+ const afterIsValid = isValidFilter(action.payload.value);
+ const newState: any = {
+ ...state,
+ filters: update(state.filters, {
+ [action.payload.filterIdx]: { $set: action.payload.value },
+ }),
+ };
+ if (previousIsValid || afterIsValid) {
+ newState.page = 1;
+ newState.refreshPageFlag = Date.now();
+ newState.totalRows = TOTAL_ROWS_RESET;
+ }
+ return newState;
+ }
+ default:
+ return state;
+ }
+};
+
+export default FilterReducer;
+
+function isValidFilter(filter: Filter) {
+ return (
+ filter &&
+ filter.column &&
+ filter.column != '' &&
+ filter.value &&
+ filter.value != ''
+ );
+}
diff --git a/studio/components/grid/store/reducers/index.ts b/studio/components/grid/store/reducers/index.ts
new file mode 100644
index 00000000000..19d326ca810
--- /dev/null
+++ b/studio/components/grid/store/reducers/index.ts
@@ -0,0 +1,41 @@
+import BaseReducer, { BaseInitialState, baseInitialState } from './base';
+import CallbackReducer, {
+ CallbackInitialState,
+ callbackInitialState,
+} from './callback';
+import ColumnReducer, {
+ ColumnInitialState,
+ columnInitialState,
+} from './column';
+import RowReducer, { RowInitialState, rowInitialState } from './row';
+import SortReducer, { SortInitialState, sortInitialState } from './sort';
+import FilterReducer, {
+ FilterInitialState,
+ filterInitialState,
+} from './filter';
+
+export interface InitialStateType
+ extends BaseInitialState,
+ CallbackInitialState,
+ ColumnInitialState,
+ FilterInitialState,
+ RowInitialState,
+ SortInitialState {}
+
+export const initialState = {
+ ...baseInitialState,
+ ...callbackInitialState,
+ ...columnInitialState,
+ ...filterInitialState,
+ ...rowInitialState,
+ ...sortInitialState,
+};
+
+export {
+ BaseReducer,
+ CallbackReducer,
+ ColumnReducer,
+ FilterReducer,
+ RowReducer,
+ SortReducer,
+};
diff --git a/studio/components/grid/store/reducers/row.ts b/studio/components/grid/store/reducers/row.ts
new file mode 100644
index 00000000000..569aa5a5815
--- /dev/null
+++ b/studio/components/grid/store/reducers/row.ts
@@ -0,0 +1,143 @@
+import update from 'immutability-helper';
+import {
+ REFRESH_PAGE_IMMEDIATELY,
+ TOTAL_ROWS_INITIAL,
+ TOTAL_ROWS_RESET,
+} from '../../constants';
+import { Dictionary, SupaRow } from '../../types';
+import { INIT_ACTIONTYPE } from './base';
+
+export interface RowInitialState {
+ rows: SupaRow[];
+ selectedRows: ReadonlySet<number>;
+ selectedCellPosition: { idx: number; rowIdx: number } | null;
+ page: number;
+ rowsPerPage: number;
+ totalRows: number;
+}
+
+export const rowInitialState: RowInitialState = {
+ rows: [],
+ selectedRows: new Set(),
+ selectedCellPosition: null,
+ page: 1,
+ rowsPerPage: 100,
+ totalRows: TOTAL_ROWS_INITIAL,
+};
+
+type ROW_ACTIONTYPE =
+ | INIT_ACTIONTYPE
+ | {
+ type: 'SELECTED_CELL_CHANGE';
+ payload: { position: { idx: number; rowIdx: number } };
+ }
+ | {
+ type: 'SELECTED_ROWS_CHANGE';
+ payload: { selectedRows: ReadonlySet<number> };
+ }
+ | { type: 'SET_PAGE'; payload: number }
+ | { type: 'SET_ROWS_PER_PAGE'; payload: number }
+ | {
+ type: 'SET_ROWS';
+ payload: { rows: SupaRow[] };
+ }
+ | {
+ type: 'SET_ROWS_COUNT';
+ payload: number;
+ }
+ | { type: 'ADD_ROWS'; payload: SupaRow[] }
+ | { type: 'ADD_NEW_ROW'; payload: Dictionary<any> }
+ | { type: 'EDIT_ROW'; payload: { row: Dictionary<any>; idx: number } }
+ | { type: 'REMOVE_ROWS'; payload: { rowIdxs: number[] } };
+
+const RowReducer = (state: RowInitialState, action: ROW_ACTIONTYPE) => {
+ switch (action.type) {
+ case 'INIT_TABLE': {
+ return {
+ ...state,
+ page: 1,
+ selectedCellPosition: null,
+ selectedRows: new Set(),
+ totalRows: TOTAL_ROWS_RESET,
+ };
+ }
+ case 'SELECTED_CELL_CHANGE': {
+ return {
+ ...state,
+ selectedCellPosition: action.payload.position,
+ };
+ }
+ case 'SELECTED_ROWS_CHANGE': {
+ return {
+ ...state,
+ selectedRows: action.payload.selectedRows,
+ };
+ }
+ case 'SET_PAGE': {
+ return {
+ ...state,
+ page: action.payload,
+ refreshPageFlag: REFRESH_PAGE_IMMEDIATELY,
+ };
+ }
+ case 'SET_ROWS_PER_PAGE': {
+ return {
+ ...state,
+ page: 1,
+ rowsPerPage: action.payload,
+ refreshPageFlag: REFRESH_PAGE_IMMEDIATELY,
+ };
+ }
+ case 'SET_ROWS': {
+ return {
+ ...state,
+ rows: action.payload.rows,
+ refreshPageFlag: 0,
+ };
+ }
+ case 'SET_ROWS_COUNT': {
+ return {
+ ...state,
+ totalRows: action.payload,
+ };
+ }
+ case 'ADD_ROWS': {
+ const totalRows = state.totalRows + action.payload.length;
+ return {
+ ...state,
+ rows: update(state.rows, { $push: action.payload }),
+ totalRows: totalRows,
+ };
+ }
+ case 'ADD_NEW_ROW': {
+ const supaRow = { ...action.payload, idx: state.rows.length };
+ const totalRows = state.totalRows + 1;
+ return {
+ ...state,
+ rows: update(state.rows, { $push: [supaRow] }),
+ totalRows: totalRows,
+ };
+ }
+ case 'EDIT_ROW': {
+ const supaRow = { ...action.payload.row, idx: action.payload.idx };
+ return {
+ ...state,
+ rows: update(state.rows, {
+ [action.payload.idx]: { $set: supaRow },
+ }),
+ };
+ }
+ case 'REMOVE_ROWS': {
+ const totalRows = state.totalRows - action.payload.rowIdxs.length;
+ return {
+ ...state,
+ rows: state.rows.filter((x) => !action.payload.rowIdxs.includes(x.idx)),
+ totalRows: totalRows,
+ };
+ }
+ default:
+ return state;
+ }
+};
+
+export default RowReducer;
diff --git a/studio/components/grid/store/reducers/sort.ts b/studio/components/grid/store/reducers/sort.ts
new file mode 100644
index 00000000000..dd7abce1cfe
--- /dev/null
+++ b/studio/components/grid/store/reducers/sort.ts
@@ -0,0 +1,81 @@
+import update from 'immutability-helper';
+import { Sort } from '../../types';
+import { getInitialSorts } from '../../utils';
+import { INIT_ACTIONTYPE } from './base';
+
+export interface SortInitialState {
+ sorts: Sort[];
+}
+
+export const sortInitialState: SortInitialState = { sorts: [] };
+
+type SORT_ACTIONTYPE =
+ | INIT_ACTIONTYPE
+ | {
+ type: 'SET_SORTS';
+ payload: Sort[];
+ }
+ | { type: 'ADD_SORT'; payload: Sort }
+ | { type: 'REMOVE_SORT'; payload: { column: string } }
+ | {
+ type: 'UPDATE_SORT';
+ payload: Sort;
+ }
+ | {
+ type: 'MOVE_SORT';
+ payload: { fromIndex: number; toIndex: number };
+ };
+
+const SortReducer = (state: SortInitialState, action: SORT_ACTIONTYPE) => {
+ switch (action.type) {
+ case 'INIT_TABLE': {
+ return {
+ ...state,
+ sorts: getInitialSorts(action.payload.table, action.payload.savedState),
+ };
+ }
+ case 'SET_SORTS':
+ return {
+ ...state,
+ sorts: action.payload,
+ };
+ case 'ADD_SORT':
+ return {
+ ...state,
+ sorts: update(state.sorts, { $push: [action.payload] }),
+ refreshPageFlag: Date.now(),
+ };
+ case 'REMOVE_SORT':
+ return {
+ ...state,
+ sorts: state.sorts.filter((x) => x.column !== action.payload.column),
+ refreshPageFlag: Date.now(),
+ };
+ case 'UPDATE_SORT':
+ return {
+ ...state,
+ sorts: state.sorts.map((x) => {
+ if (x.column == action.payload.column) return action.payload;
+ return x;
+ }),
+ refreshPageFlag: Date.now(),
+ };
+ case 'MOVE_SORT': {
+ const moveItem = state.sorts[action.payload.fromIndex];
+ return {
+ ...state,
+ sorts: update(state.sorts, {
+ $splice: [
+ [action.payload.fromIndex, 1],
+ [action.payload.toIndex, 0, moveItem],
+ ],
+ }),
+ refreshPageFlag: Date.now(),
+ };
+ }
+ default:
+ return state;
+ }
+};
+
+export default SortReducer;
diff --git a/studio/components/grid/types/base.ts b/studio/components/grid/types/base.ts
new file mode 100644
index 00000000000..56ccfbd4650
--- /dev/null
+++ b/studio/components/grid/types/base.ts
@@ -0,0 +1,65 @@
+import {
+ CalculatedColumn,
+ HeaderRendererProps,
+} from '@supabase/react-data-grid';
+
+export interface Dictionary<T> {
+ [Key: string]: T;
+}
+
+export interface Sort {
+ column: string;
+ ascending?: boolean;
+ nullsFirst?: boolean;
+}
+
+export type FilterOperator =
+ | '='
+ | '<>'
+ | '>'
+ | '<'
+ | '>='
+ | '<='
+ | '~~'
+ | '~~*'
+ | '!~~'
+ | '!~~*'
+ | 'in'
+ | 'is';
+
+export interface Filter {
+ column: string;
+ operator: FilterOperator;
+ value: any;
+}
+
+export interface SavedState {
+ filters: Filter[];
+ gridColumns: CalculatedColumn<any, any>[];
+ sorts: Sort[];
+}
+
+export interface DragItem {
+ index: number;
+ key: string;
+}
+
+export type ColumnType =
+ | 'array'
+ | 'boolean'
+ | 'date'
+ | 'datetime'
+ | 'enum'
+ | 'foreign_key'
+ | 'json'
+ | 'number'
+ | 'primary_key'
+ | 'text'
+ | 'time'
+ | 'unknown';
+
+export interface ColumnHeaderProps<R> extends HeaderRendererProps<R> {
+ columnType: ColumnType;
+ isPrimaryKey: Boolean | undefined;
+ format: string;
+}
diff --git a/studio/components/grid/types/grid.ts b/studio/components/grid/types/grid.ts
new file mode 100644
index 00000000000..92581029b05
--- /dev/null
+++ b/studio/components/grid/types/grid.ts
@@ -0,0 +1,88 @@
+import React from 'react';
+import { Dictionary } from './base';
+import { SupaRow, SupaTable } from './table';
+
+export interface GridProps {
+ width?: string | number;
+ height?: string | number;
+ defaultColumnWidth?: string | number;
+ containerClass?: string;
+ gridClass?: string;
+ rowClass?: ((row: SupaRow) => string | undefined) | undefined;
+}
+
+export interface SupabaseGridProps {
+ /**
+ * database table swagger or table name
+ */
+ table: SupaTable | string;
+ /**
+ * run sql query
+ */
+ onSqlQuery: (query: string) => Promise<{ data?: any; error?: any }>;
+
+ /**
+ * Optional react node to display in grid header
+ */
+ headerActions?: React.ReactNode;
+ /**
+ * enable table editor
+ */
+ editable?: boolean;
+ /**
+ * props to config grid view
+ */
+ gridProps?: GridProps;
+ /**
+ * table schema. Default set to 'public' if not provided
+ */
+ schema?: string;
+ /**
+ * storageRef is used to save state on localstorage
+ */
+ storageRef?: string;
+ /**
+ * Optional grid theme
+ */
+ theme?: 'dark' | 'light';
+ /**
+ * show create new column button if available
+ */
+ onAddColumn?: () => void;
+ /**
+ * show add row button if available
+ */
+ onAddRow?: () => void;
+ /**
+ * show delete column menu if available
+ */
+ onDeleteColumn?: (columnName: string) => void;
+ /**
+ * show edit column menu if available
+ */
+ onEditColumn?: (columnName: string) => void;
+ /**
+ * show edit row button if available
+ */
+ onEditRow?: (row: SupaRow) => void;
+ /**
+ * error handler
+ */
+ onError?: (error: any) => void;
+}
+
+export interface SupabaseGridRef {
+ /**
+ * callback when a new row is added
+ *
+ * @param row newly added row data
+ */
+ rowAdded(row: Dictionary<any>): void;
+ /**
+ * callback when a row is edited
+ *
+ * @param row edited row data
+ * @param idx edited row index
+ */
+ rowEdited(row: Dictionary<any>, idx: number): void;
+}
diff --git a/studio/components/grid/types/index.ts b/studio/components/grid/types/index.ts
new file mode 100644
index 00000000000..6918ebeeb63
--- /dev/null
+++ b/studio/components/grid/types/index.ts
@@ -0,0 +1,5 @@
+export * from './base';
+export * from './grid';
+export * from './query';
+export * from './service';
+export * from './table';
diff --git a/studio/components/grid/types/query.ts b/studio/components/grid/types/query.ts
new file mode 100644
index 00000000000..72219b8bb04
--- /dev/null
+++ b/studio/components/grid/types/query.ts
@@ -0,0 +1,9 @@
+export interface QueryTable {
+ name: string;
+ schema: string;
+}
+
+export interface QueryPagination {
+ limit: number;
+ offset: number;
+}
diff --git a/studio/components/grid/types/service.ts b/studio/components/grid/types/service.ts
new file mode 100644
index 00000000000..6f109f6a712
--- /dev/null
+++ b/studio/components/grid/types/service.ts
@@ -0,0 +1,3 @@
+export interface ServiceError {
+ message: string;
+}
diff --git a/studio/components/grid/types/table.ts b/studio/components/grid/types/table.ts
new file mode 100644
index 00000000000..48ecf6f44b8
--- /dev/null
+++ b/studio/components/grid/types/table.ts
@@ -0,0 +1,30 @@
+import { Dictionary } from './base';
+
+export interface SupaColumn {
+ readonly dataType: string;
+ readonly format: string;
+ readonly name: string;
+ readonly comment?: string | null;
+ readonly defaultValue?: string | null;
+ readonly enum?: string[] | null;
+ readonly isPrimaryKey?: boolean;
+ readonly isIdentity?: boolean;
+ readonly isGeneratable?: boolean;
+ readonly isNullable?: boolean;
+ readonly isUpdatable?: boolean;
+ readonly targetTableSchema?: string | null;
+ readonly targetTableName?: string | null;
+ readonly targetColumnName?: string | null;
+ position: number;
+}
+
+export interface SupaTable {
+ readonly columns: SupaColumn[];
+ readonly name: string;
+ readonly schema?: string | null;
+ readonly comment?: string | null;
+}
+
+export interface SupaRow extends Dictionary<any> {
+ readonly idx: number;
+}
diff --git a/studio/components/grid/typings.d.ts b/studio/components/grid/typings.d.ts
new file mode 100644
index 00000000000..444f793772f
--- /dev/null
+++ b/studio/components/grid/typings.d.ts
@@ -0,0 +1,4 @@
+declare module '*.css' {
+ const content: { [className: string]: string };
+ export default content;
+}
diff --git a/studio/components/grid/utils/column.ts b/studio/components/grid/utils/column.ts
new file mode 100644
index 00000000000..aecc6bd7299
--- /dev/null
+++ b/studio/components/grid/utils/column.ts
@@ -0,0 +1,57 @@
+import { CalculatedColumn } from '@supabase/react-data-grid';
+import { ADD_COLUMN_KEY, SELECT_COLUMN_KEY } from '../constants';
+import { SavedState } from '../types';
+import { deepClone } from './common';
+
+export function cloneColumn(column: CalculatedColumn<any, any>) {
+ const cloned = deepClone(column);
+ // these properties can't be cloned. Need to manual re-set again
+ cloned.editor = column.editor;
+ cloned.headerRenderer = column.headerRenderer;
+ cloned.formatter = column.formatter;
+ return cloned;
+}
+
+export function getInitialGridColumns(
+ gridColumns: CalculatedColumn<any, any>[],
+ savedState?: SavedState
+) {
+ let result = gridColumns;
+
+ if (savedState?.gridColumns) {
+ result = [];
+
+ // filter utility columns select, add-column
+ const stateColumnsFiltered = savedState.gridColumns.filter(
+ (x) => x?.name !== ''
+ );
+
+ for (let i = 0; i < stateColumnsFiltered.length; i++) {
+ const state = stateColumnsFiltered[i];
+ const found = gridColumns.find((y) => y.key === state.key);
+ // merge with savedState item props: width
+ if (found)
+ result.push({ ...found, width: state.width, frozen: state.frozen });
+ }
+
+ // check for newly created columns
+ const newGridColumns = gridColumns.filter((x) => {
+ // no existed in stateColumnsFiltered and not utility column
+ const found = stateColumnsFiltered.find((state) => state.key === x.key);
+ return !found && x.name !== '';
+ });
+ result = result.concat(newGridColumns);
+
+ // process utility columns
+ const selectColumn = gridColumns.find((x) => x.key === SELECT_COLUMN_KEY);
+ if (selectColumn) {
+ result = [selectColumn, ...result];
+ }
+ const addColumn = gridColumns.find((x) => x.key === ADD_COLUMN_KEY);
+ if (addColumn) {
+ result.push(addColumn);
+ }
+ }
+
+ return result;
+}
diff --git a/studio/components/grid/utils/common.ts b/studio/components/grid/utils/common.ts
new file mode 100644
index 00000000000..83fdec70d23
--- /dev/null
+++ b/studio/components/grid/utils/common.ts
@@ -0,0 +1,57 @@
+import { SupaColumn, SupaRow } from '../types';
+
+export function deepClone(obj: unknown) {
+ try {
+ return JSON.parse(JSON.stringify(obj));
+ } catch (e) {
+ throw e;
+ }
+}
+
+export function exportRowsToCsv(
+ columns: SupaColumn[],
+ rows: SupaRow[],
+ separator: string = ','
+) {
+ const keys = columns.map(x => x.name) || [];
+ const csv =
+ keys.join(separator) +
+ '\n' +
+ rows
+ .map(row => {
+ return keys
+ .map(k => {
+ let cell = row[k] === null || row[k] === undefined ? '' : row[k];
+ cell =
+ cell instanceof Date
+ ? cell.toLocaleString()
+ : typeof cell == 'object' || Array.isArray(cell)
+ ? JSON.stringify(cell).replace(/"/g, '""')
+ : cell.toString().replace(/"/g, '""');
+ if (cell.search(/("|,|\n)/g) >= 0) {
+ cell = `"${cell}"`;
+ }
+ return cell;
+ })
+ .join(separator);
+ })
+ .join('\n');
+ return csv;
+}
+
+export function formatClipboardValue(value: any) {
+ if (value === null) return '';
+ if (typeof value == 'object' || Array.isArray(value)) {
+ return JSON.stringify(value);
+ }
+ return value;
+}
+
+export const copyToClipboard = (str: string, callback = () => {}) => {
+ const focused = window.document.hasFocus();
+ if (focused) {
+ window.navigator?.clipboard?.writeText(str).then(callback);
+ } else {
+ console.warn('Unable to copy to clipboard');
+ }
+};
diff --git a/studio/components/grid/utils/filter.ts b/studio/components/grid/utils/filter.ts
new file mode 100644
index 00000000000..1b11a6807e1
--- /dev/null
+++ b/studio/components/grid/utils/filter.ts
@@ -0,0 +1,16 @@
+import { Filter, SavedState, SupaTable } from '../types';
+
+export function getInitialFilters(
+ table: SupaTable,
+ savedState?: SavedState
+): Filter[] {
+ if (savedState?.filters) {
+ // verify column still exists
+ const filters = savedState.filters.filter((x) => {
+ const found = table.columns.find((y) => y.name === x.column);
+ return found ? true : false;
+ });
+ if (filters?.length > 0) return filters;
+ }
+ return [];
+}
diff --git a/studio/components/grid/utils/gridColumns.tsx b/studio/components/grid/utils/gridColumns.tsx
new file mode 100644
index 00000000000..200a92eb397
--- /dev/null
+++ b/studio/components/grid/utils/gridColumns.tsx
@@ -0,0 +1,183 @@
+import * as React from 'react';
+import { CalculatedColumn } from '@supabase/react-data-grid';
+import { ColumnType, SupaColumn, SupaRow, SupaTable } from '../types';
+import {
+ isArrayColumn,
+ isBoolColumn,
+ isDateColumn,
+ isDateTimeColumn,
+ isEnumColumn,
+ isForeignKeyColumn,
+ isJsonColumn,
+ isNumericalColumn,
+ isTextColumn,
+ isTimeColumn,
+} from './types';
+import {
+ BooleanEditor,
+ DateEditor,
+ DateTimeEditor,
+ DateTimeWithTimezoneEditor,
+ JsonEditor,
+ NullableBooleanEditor,
+ NumberEditor,
+ SelectEditor,
+ TextEditor,
+ TimeEditor,
+ TimeWithTimezoneEditor,
+} from '../components/editor';
+import { AddColumn, ColumnHeader, SelectColumn } from '../components/grid';
+import { COLUMN_MIN_WIDTH } from '../constants';
+import {
+ BooleanFormatter,
+ DefaultFormatter,
+ ForeignKeyFormatter,
+} from '../components/formatter';
+
+export function getGridColumns(
+ table: SupaTable,
+ options?: {
+ editable?: boolean;
+ defaultWidth?: string | number;
+ onAddColumn?: () => void;
+ }
+): any[] {
+ const columns = table.columns.map((x, idx) => {
+ const columnType = getColumnType(x);
+ const columnDefinition: CalculatedColumn<SupaRow> = {
+ key: x.name,
+ name: x.name,
+ idx: idx + 1,
+ resizable: true,
+ sortable: true,
+ width: options?.defaultWidth || getColumnWidth(x),
+ minWidth: COLUMN_MIN_WIDTH,
+ frozen: x.isPrimaryKey || false,
+ isLastFrozenColumn: false,
+ rowGroup: false,
+ headerRenderer: (props) => (
+ <ColumnHeader
+ {...props}
+ columnType={columnType}
+ isPrimaryKey={x.isPrimaryKey}
+ format={x.format}
+ />
+ ),
+ editor: options?.editable ? getColumnEditor(x, columnType) : undefined,
+ formatter: getColumnFormatter(x, columnType),
+ };
+
+ return columnDefinition;
+ });
+
+ const gridColumns = [SelectColumn, ...columns];
+ if (options?.onAddColumn) {
+ gridColumns.push(AddColumn);
+ }
+
+ return gridColumns;
+}
+
+function getColumnEditor(columnDefinition: SupaColumn, columnType: ColumnType) {
+ if (columnDefinition.isPrimaryKey || !columnDefinition.isUpdatable) {
+ return;
+ }
+
+ switch (columnType) {
+ case 'boolean': {
+ return columnDefinition.isNullable
+ ? NullableBooleanEditor
+ : BooleanEditor;
+ }
+ case 'date': {
+ return DateEditor;
+ }
+ case 'datetime': {
+ return columnDefinition.format.endsWith('z')
+ ? DateTimeWithTimezoneEditor
+ : DateTimeEditor;
+ }
+ case 'time': {
+ return columnDefinition.format.endsWith('z')
+ ? TimeWithTimezoneEditor
+ : TimeEditor;
+ }
+ case 'enum': {
+ const options = columnDefinition.enum!.map((x) => {
+ return { label: x, value: x };
+ });
+ return (p: any) => <SelectEditor {...p} options={options} />;
+ }
+ case 'array':
+ case 'json': {
+ return JsonEditor;
+ }
+ case 'number': {
+ return NumberEditor;
+ }
+ case 'text': {
+ return TextEditor;
+ }
+ default: {
+ return undefined;
+ }
+ }
+}
+
+function getColumnFormatter(columnDef: SupaColumn, columnType: ColumnType) {
+ switch (columnType) {
+ case 'boolean': {
+ return BooleanFormatter;
+ }
+ case 'foreign_key': {
+ if (columnDef.isPrimaryKey || !columnDef.isUpdatable) {
+ return DefaultFormatter;
+ } else {
+ return ForeignKeyFormatter;
+ }
+ }
+ default: {
+ return DefaultFormatter;
+ }
+ }
+}
+
+function getColumnType(columnDef: SupaColumn): ColumnType {
+ if (isForeignKeyColumn(columnDef)) {
+ return 'foreign_key';
+ } else if (isNumericalColumn(columnDef.dataType)) {
+ return 'number';
+ } else if (isArrayColumn(columnDef.dataType)) {
+ return 'array';
+ } else if (isJsonColumn(columnDef.dataType)) {
+ return 'json';
+ } else if (isTextColumn(columnDef.dataType)) {
+ return 'text';
+ } else if (isDateColumn(columnDef.format)) {
+ return 'date';
+ } else if (isTimeColumn(columnDef.format)) {
+ return 'time';
+ } else if (isDateTimeColumn(columnDef.format)) {
+ return 'datetime';
+ } else if (isBoolColumn(columnDef.dataType)) {
+ return 'boolean';
+ } else if (isEnumColumn(columnDef.dataType)) {
+ return 'enum';
+ } else return 'unknown';
+}
+
+function getColumnWidth(columnDef: SupaColumn): string | number | undefined {
+ if (isNumericalColumn(columnDef.dataType)) {
+ return 120;
+ } else if (
+ isDateTimeColumn(columnDef.format) ||
+ isDateColumn(columnDef.format) ||
+ isTimeColumn(columnDef.format)
+ ) {
+ return 150;
+ } else if (isBoolColumn(columnDef.dataType)) {
+ return 120;
+ } else if (isEnumColumn(columnDef.dataType)) {
+ return 150;
+ } else return 250;
+}
diff --git a/studio/components/grid/utils/hooks.tsx b/studio/components/grid/utils/hooks.tsx
new file mode 100644
index 00000000000..724a77c3b52
--- /dev/null
+++ b/studio/components/grid/utils/hooks.tsx
@@ -0,0 +1,13 @@
+import * as React from 'react';
+
+export function useFocusRef<T extends HTMLOrSVGElement>(
+ isCellSelected: boolean
+) {
+ const ref = React.useRef<T>(null);
+ React.useLayoutEffect(() => {
+ if (!isCellSelected) return;
+ ref.current?.focus({ preventScroll: true });
+ }, [isCellSelected]);
+
+ return ref;
+}
diff --git a/studio/components/grid/utils/index.ts b/studio/components/grid/utils/index.ts
new file mode 100644
index 00000000000..93cc0994931
--- /dev/null
+++ b/studio/components/grid/utils/index.ts
@@ -0,0 +1,7 @@
+export * from './common';
+export * from './column';
+export * from './hooks';
+export * from './filter';
+export * from './row';
+export * from './sort';
+export * from './types';
diff --git a/studio/components/grid/utils/row.ts b/studio/components/grid/utils/row.ts
new file mode 100644
index 00000000000..718fa4b1d77
--- /dev/null
+++ b/studio/components/grid/utils/row.ts
@@ -0,0 +1,40 @@
+import AwesomeDebouncePromise from 'awesome-debounce-promise';
+import { InitialStateType } from '../store/reducers';
+
+export async function fetchCount(
+ state: InitialStateType,
+ dispatch: (value: unknown) => void
+) {
+ if (!state.rowService) return;
+ const { data, error } = await state.rowService.count(state.filters);
+ if (error) {
+ // TODO: handle fetch rows count error
+ } else {
+ dispatch({
+ type: 'SET_ROWS_COUNT',
+ payload: data ?? 0,
+ });
+ }
+}
+
+export async function fetchPage(
+ state: InitialStateType,
+ dispatch: (value: unknown) => void
+) {
+ if (!state.rowService) return;
+ const { data, error } = await state.rowService.fetchPage(
+ state.page,
+ state.rowsPerPage,
+ state.filters,
+ state.sorts
+ );
+ if (error) {
+ // TODO: handle fetch rows data error
+ } else {
+ dispatch({
+ type: 'SET_ROWS',
+ payload: { rows: data?.rows ?? [] },
+ });
+ }
+}
+export const refreshPageDebounced = AwesomeDebouncePromise(fetchPage, 500);
diff --git a/studio/components/grid/utils/sort.ts b/studio/components/grid/utils/sort.ts
new file mode 100644
index 00000000000..a723255c01c
--- /dev/null
+++ b/studio/components/grid/utils/sort.ts
@@ -0,0 +1,20 @@
+import { SavedState, Sort, SupaTable } from '../types';
+
+export function getInitialSorts(
+ table: SupaTable,
+ savedState?: SavedState
+): Sort[] {
+ if (savedState?.sorts) {
+ // verify column still exists
+ const sorts = savedState.sorts.filter((x) => {
+ const found = table.columns.find((y) => y.name === x.column);
+ return found ? true : false;
+ });
+ if (sorts?.length > 0) return sorts;
+ }
+
+ // default sorts
+ if (!table?.columns || table?.columns?.length <= 0) return [];
+ const firstColumn = table?.columns[0];
+ return [{ column: firstColumn.name, ascending: true }];
+}
diff --git a/studio/components/grid/utils/types.ts b/studio/components/grid/utils/types.ts
new file mode 100644
index 00000000000..a8144b6a3a7
--- /dev/null
+++ b/studio/components/grid/utils/types.ts
@@ -0,0 +1,70 @@
+import { SupaColumn } from '../types';
+
+const NUMERICAL_TYPES = [
+ 'smallint',
+ 'integer',
+ 'bigint',
+ 'decimal',
+ 'numeric',
+ 'real',
+ 'double precision',
+ 'serial',
+ 'bigserial',
+ 'int2',
+ 'int4',
+ 'int8',
+ 'float4',
+ 'float8',
+ 'smallserial',
+ 'serial2',
+ 'serial4',
+ 'serial8',
+];
+export function isNumericalColumn(type: string) {
+ return NUMERICAL_TYPES.indexOf(type.toLowerCase()) > -1;
+}
+
+const JSON_TYPES = ['json', 'jsonb', 'array'];
+export function isJsonColumn(type: string) {
+ return JSON_TYPES.indexOf(type.toLowerCase()) > -1;
+}
+
+const ARRAY_TYPES = ['array'];
+export function isArrayColumn(type: string) {
+ return ARRAY_TYPES.indexOf(type.toLowerCase()) > -1;
+}
+
+const TEXT_TYPES = ['text', 'character varying'];
+export function isTextColumn(type: string) {
+ return TEXT_TYPES.indexOf(type.toLowerCase()) > -1;
+}
+
+const TIMESTAMP_TYPES = ['timestamp', 'timestamptz'];
+export function isDateTimeColumn(type: string) {
+ return TIMESTAMP_TYPES.indexOf(type.toLowerCase()) > -1;
+}
+
+const DATE_TYPES = ['date'];
+export function isDateColumn(type: string) {
+ return DATE_TYPES.indexOf(type.toLowerCase()) > -1;
+}
+
+const TIME_TYPES = ['time', 'timetz'];
+export function isTimeColumn(type: string) {
+ return TIME_TYPES.indexOf(type.toLowerCase()) > -1;
+}
+
+const BOOL_TYPES = ['boolean', 'bool'];
+export function isBoolColumn(type: string) {
+ return BOOL_TYPES.indexOf(type.toLowerCase()) > -1;
+}
+
+const ENUM_TYPES = ['user-defined'];
+export function isEnumColumn(type: string) {
+ return ENUM_TYPES.indexOf(type.toLowerCase()) > -1;
+}
+
+export function isForeignKeyColumn(columnDef: SupaColumn) {
+ const { targetTableSchema, targetTableName, targetColumnName } = columnDef;
+ return !!targetTableSchema && !!targetTableName && !!targetColumnName;
+}
diff --git a/studio/components/interfaces/Billing/Subscription/Subscription.tsx b/studio/components/interfaces/Billing/Subscription/Subscription.tsx
index 2c1dcb66f09..10b8589194a 100644
--- a/studio/components/interfaces/Billing/Subscription/Subscription.tsx
+++ b/studio/components/interfaces/Billing/Subscription/Subscription.tsx
@@ -3,7 +3,7 @@ import dayjs from 'dayjs'
import { sum } from 'lodash'
import { useRouter } from 'next/router'
import { Loading, Button } from '@supabase/ui'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { formatBytes } from 'lib/helpers'
import { STRIPE_PRODUCT_IDS } from 'lib/constants'
diff --git a/studio/components/interfaces/Database/Functions/CreateFunction.tsx b/studio/components/interfaces/Database/Functions/CreateFunction.tsx
index dafd57350fe..2b00ddd0815 100644
--- a/studio/components/interfaces/Database/Functions/CreateFunction.tsx
+++ b/studio/components/interfaces/Database/Functions/CreateFunction.tsx
@@ -13,7 +13,7 @@ import {
IconPlus,
Toggle,
} from '@supabase/ui'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { makeAutoObservable } from 'mobx'
import { useStore } from 'hooks'
diff --git a/studio/components/interfaces/Database/Hooks/CreateHook/index.tsx b/studio/components/interfaces/Database/Hooks/CreateHook/index.tsx
index 5d3a19d882e..7d6047c67e3 100644
--- a/studio/components/interfaces/Database/Hooks/CreateHook/index.tsx
+++ b/studio/components/interfaces/Database/Hooks/CreateHook/index.tsx
@@ -2,7 +2,7 @@ import { makeAutoObservable } from 'mobx'
import { FC, useEffect, createContext } from 'react'
import { observer, useLocalObservable } from 'mobx-react-lite'
import { isEmpty, mapValues, has, filter, keyBy, isUndefined } from 'lodash'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { Badge, Input, SidePanel } from '@supabase/ui'
import { useStore } from 'hooks'
diff --git a/studio/components/interfaces/Database/Triggers/ChooseFunctionForm.tsx b/studio/components/interfaces/Database/Triggers/ChooseFunctionForm.tsx
index d5aaf807f6b..d432c5b33be 100644
--- a/studio/components/interfaces/Database/Triggers/ChooseFunctionForm.tsx
+++ b/studio/components/interfaces/Database/Triggers/ChooseFunctionForm.tsx
@@ -11,7 +11,7 @@ import {
SidePanel,
Typography,
} from '@supabase/ui'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import SqlEditor from 'components/to-be-cleaned/SqlEditor'
import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
import InformationBox from 'components/ui/InformationBox'
diff --git a/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx b/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx
index be5299e1298..99e32f54b9e 100644
--- a/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx
+++ b/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx
@@ -14,7 +14,7 @@ import {
Badge,
Button,
} from '@supabase/ui'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { useRouter } from 'next/router'
import SVG from 'react-inlinesvg'
@@ -695,17 +695,17 @@ const FunctionEmpty: FC = observer(({}) => {
<button
type="button"
onClick={() => _localState!.setChooseFunctionFormVisible(true)}
- className="w-full relative
+ className="w-full relative
transition-all
-
- shadow-sm
+
+ shadow-sm
border bg-scale-200 dark:bg-scale-400
border-scale-600
rounded
hover:border-scale-700
hover:bg-scale-300 dark:hover:bg-scale-500
- px-5 py-1
-
+ px-5 py-1
+
"
>
<FormEmptyBox
@@ -723,17 +723,17 @@ const FunctionWithArguments: FC = observer(({}) => {
<>
<div
className="
-
-
+
+
w-full
- relative
- transition-shadow shadow-sm
+ relative
+ transition-shadow shadow-sm
border border-scale-200 dark:border-scale-500
rounded
- px-5 py-4
+ px-5 py-4
flex space-x-3 items-center justify-between"
>
<div className="flex items-center gap-2">
diff --git a/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx b/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx
index 84e89d1e83b..0f73f5dd1b3 100644
--- a/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx
+++ b/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx
@@ -1,6 +1,6 @@
import { FC, useState } from 'react'
import { isEqual } from 'lodash'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { Form, Input, Button, Select } from '@supabase/ui'
import { useStore } from 'hooks'
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.constants.ts b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.constants.ts
index 3e89d80a958..fe770d2d081 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.constants.ts
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.constants.ts
@@ -1,4 +1,4 @@
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { Suggestion } from './ColumnEditor.types'
const defaultTimeBasedExpressions: Suggestion[] = [
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
index a6677cd53a1..2581b186e5f 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
@@ -1,6 +1,6 @@
import { FC, useEffect, useState } from 'react'
import { isUndefined, isEmpty } from 'lodash'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { Checkbox, SidePanel, Space, Input, Divider } from '@supabase/ui'
import {
PostgresColumn,
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
index b20856fb6cd..df51a368199 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
@@ -1,5 +1,5 @@
import { find, isUndefined, isEqual, isNull } from 'lodash'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import {
PostgresColumn,
PostgresRelationship,
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
index eafa70659dd..6573eebe098 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
@@ -1,6 +1,6 @@
import React, { FC, useEffect, useState } from 'react'
import { get, find, isEmpty, sortBy } from 'lodash'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { SidePanel, Typography, Listbox, IconHelpCircle } from '@supabase/ui'
import { PostgresTable, PostgresColumn } from '@supabase/postgres-meta'
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/DrilldownViewer/DrilldownPane.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/DrilldownViewer/DrilldownPane.tsx
index f1cabb8240c..4049fc1f140 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/DrilldownViewer/DrilldownPane.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/DrilldownViewer/DrilldownPane.tsx
@@ -1,7 +1,7 @@
import { FC } from 'react'
import { IconChevronRight } from '@supabase/ui'
import { isNull } from 'lodash'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
interface Props {
pane: number
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/DrilldownViewer/DrilldownViewer.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/DrilldownViewer/DrilldownViewer.tsx
index 4c3a4f32ddb..24a568a8e6c 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/DrilldownViewer/DrilldownViewer.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/DrilldownViewer/DrilldownViewer.tsx
@@ -2,7 +2,7 @@ import { FC, useState } from 'react'
import { isEmpty, last } from 'lodash'
import DrilldownPane from './DrilldownPane'
import DrilldownBreadCrumbs from './DrilldownBreadCrumbs'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
interface Props {
jsonData: Dictionary<any>
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx
index 683b0821872..40dc8b0ac7e 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx
@@ -1,7 +1,8 @@
import { FC, useEffect, useState } from 'react'
import { isUndefined, partition, isEmpty } from 'lodash'
import { SidePanel } from '@supabase/ui'
-import { Dictionary, Query } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
+import { Query } from 'components/grid/query/Query'
import { PostgresTable } from '@supabase/postgres-meta'
import { useStore } from 'hooks'
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.utils.ts b/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.utils.ts
index 5af3bb3f45d..94f4f39d8d7 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.utils.ts
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.utils.ts
@@ -1,6 +1,6 @@
import dayjs from 'dayjs'
import { find, isUndefined, compact, includes, isEqual, omitBy, isNull, isString } from 'lodash'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { PostgresTable } from '@supabase/postgres-meta'
import { uuidv4, minifyJSON, tryParseJson } from 'lib/helpers'
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index be55d449d95..19a25d79b17 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -1,6 +1,6 @@
import { FC, useState } from 'react'
import { find, isUndefined } from 'lodash'
-import { Query, Dictionary } from '@supabase/grid'
+import { Query, Dictionary } from 'components/grid'
import { Modal } from '@supabase/ui'
import {
PostgresRelationship,
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/SpreadsheetImport/SpreadsheetImport.types.ts b/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/SpreadsheetImport/SpreadsheetImport.types.ts
index 4ce7e40a845..d1ebbd3c11f 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/SpreadsheetImport/SpreadsheetImport.types.ts
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/SpreadsheetImport/SpreadsheetImport.types.ts
@@ -1,4 +1,4 @@
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
export interface SpreadsheetData {
headers: string[]
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types.ts b/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types.ts
index 42eb07ad32b..4e7d4ecdc64 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types.ts
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types.ts
@@ -1,4 +1,4 @@
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { ColumnField } from '../SidePanelEditor.types'
export interface TableField {
diff --git a/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
index 7adaa5c79af..085a3fbe76d 100644
--- a/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
+++ b/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
@@ -2,7 +2,7 @@ import { FC, useRef } from 'react'
import { useRouter } from 'next/router'
import { observer } from 'mobx-react-lite'
import { isUndefined, find } from 'lodash'
-import { SupabaseGrid, SupabaseGridRef, parseSupaTable, Dictionary } from '@supabase/grid'
+import { SupabaseGrid, SupabaseGridRef, parseSupaTable, Dictionary } from 'components/grid'
import { PostgresTable, PostgresColumn } from '@supabase/postgres-meta'
import { useStore } from 'hooks'
diff --git a/studio/components/to-be-cleaned/Charts/ChartHandler.tsx b/studio/components/to-be-cleaned/Charts/ChartHandler.tsx
index cf8798a2588..92976bdd670 100644
--- a/studio/components/to-be-cleaned/Charts/ChartHandler.tsx
+++ b/studio/components/to-be-cleaned/Charts/ChartHandler.tsx
@@ -9,7 +9,7 @@ import {
IconLoader,
Typography,
} from '@supabase/ui'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { API_URL } from 'lib/constants'
import { get } from 'lib/common/fetch'
diff --git a/studio/components/to-be-cleaned/Integration/Vercel.utils.ts b/studio/components/to-be-cleaned/Integration/Vercel.utils.ts
index ede2f67413b..7d67251b89d 100644
--- a/studio/components/to-be-cleaned/Integration/Vercel.utils.ts
+++ b/studio/components/to-be-cleaned/Integration/Vercel.utils.ts
@@ -1,6 +1,6 @@
import { post, get } from 'lib/common/fetch'
import { INTEGRATION_ENVS_ALIAS } from 'lib/vercelConfigs'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { API_URL } from 'lib/constants'
export async function fetchVercelProjects({
diff --git a/studio/package-lock.json b/studio/package-lock.json
index 3b58832ab0d..96a8b9a4b9f 100644
--- a/studio/package-lock.json
+++ b/studio/package-lock.json
@@ -13,11 +13,11 @@
"@next/bundle-analyzer": "^12.0.4",
"@radix-ui/react-portal": "^0.1.1",
"@radix-ui/react-tooltip": "^0.1.6",
+ "@scaleleap/pg-format": "^1.0.0",
"@sentry/browser": "^6.15.0",
"@sentry/nextjs": "^6.15.0",
"@stripe/react-stripe-js": "^1.7.0",
"@stripe/stripe-js": "^1.25.0",
- "@supabase/grid": "v2.5.0-alpha.13",
"@supabase/postgres-meta": "^0.26.1",
"@supabase/react-data-grid": "^7.1.0-beta.7",
"@supabase/shared-types": "^0.1.18",
@@ -25,10 +25,13 @@
"@supabase/ui": "0.37.0-alpha.55",
"ajv": "^8.6.3",
"analytics-node": "^3.5.0",
+ "awesome-debounce-promise": "^2.1.0",
"clipboard": "^2.0.8",
"configcat-js": "^5.6.0",
"crypto-js": "^4.1.1",
"dayjs": "^1.11.0",
+ "file-saver": "^2.0.5",
+ "immutability-helper": "^3.1.1",
"lodash": "^4.17.21",
"lottie-react": "^2.1.0",
"markdown-table": "=2.0.0",
@@ -37,24 +40,31 @@
"next": "11.1.3",
"next-compose-plugins": "^2.2.1",
"openapi-types": "^9.1.0",
+ "p-queue": "6.6.2",
"papaparse": "^5.3.1",
"parse-numeric-range": "^1.3.0",
"path-to-regexp": "^6.2.0",
"prism-react-renderer": "^1.2.1",
"react": "^17.0.2",
"react-beautiful-dnd": "^13.1.0",
+ "react-contexify": "^5.0.0",
"react-csv": "^2.0.3",
"react-datepicker": "^4.6.0",
+ "react-dnd": "^14.0.3",
+ "react-dnd-html5-backend": "^14.0.1",
"react-dom": "^17.0.2",
"react-grid-layout": "^1.3.0",
"react-hot-toast": "^2.1.1",
"react-inlinesvg": "^2.3.0",
"react-split": "^2.0.13",
+ "react-tiny-popover": "^6.0.5",
+ "react-tracked": "^1.7.4",
"react-virtualized-auto-sizer": "^1.0.6",
"react-window": "^1.8.6",
"react-window-infinite-loader": "^1.0.7",
"recharts": "^2.1.6",
"sass": "^1.43.4",
+ "scheduler": "^0.20.2",
"semver": "^6.3.0",
"sqlstring": "^2.3.2",
"swr": "^1.2.1",
@@ -90,7 +100,7 @@
"@types/semver": "^7.3.9",
"@types/sqlstring": "^2.3.0",
"@types/zxcvbn": "^4.4.1",
- "autoprefixer": "^10.4.2",
+ "autoprefixer": "10.4.5",
"babel-loader": "^8.2.3",
"jest": "^27.4.0",
"jest-canvas-mock": "^2.3.1",
@@ -8773,61 +8783,6 @@
"cross-fetch": "^3.0.6"
}
},
- "node_modules/@supabase/grid": {
- "version": "2.5.0-alpha.13",
- "resolved": "https://registry.npmjs.org/@supabase/grid/-/grid-2.5.0-alpha.13.tgz",
- "integrity": "sha512-5YDMUfCjgzBYY32S1c2tThQX0wwkY4UZuk0dek2I12KG0Og2DgxgcoTfbfVBcQ10pwjj1/gq0nmIL/pT1WCzug==",
- "dependencies": {
- "@monaco-editor/react": "^4.3.1",
- "@scaleleap/pg-format": "^1.0.0",
- "awesome-debounce-promise": "^2.1.0",
- "dayjs": "^1.10.4",
- "file-saver": "^2.0.5",
- "immutability-helper": "^3.1.1",
- "p-queue": "6.6.2",
- "react-contexify": "^5.0.0",
- "react-dnd": "^14.0.3",
- "react-dnd-html5-backend": "^14.0.1",
- "react-tiny-popover": "^6.0.5",
- "react-tracked": "^1.7.4",
- "scheduler": "^0.20.2"
- },
- "peerDependencies": {
- "@supabase/react-data-grid": "^7.1.0-beta.7",
- "@supabase/ui": "^0.37.0-alpha.50",
- "react": "^16.14 || ^17.0.0",
- "react-dom": "^16.14 || ^17.0.0"
- }
- },
- "node_modules/@supabase/grid/node_modules/react-dnd": {
- "version": "14.0.5",
- "resolved": "https://registry.npmjs.org/react-dnd/-/react-dnd-14.0.5.tgz",
- "integrity": "sha512-9i1jSgbyVw0ELlEVt/NkCUkxy1hmhJOkePoCH713u75vzHGyXhPDm28oLfc2NMSBjZRM1Y+wRjHXJT3sPrTy+A==",
- "dependencies": {
- "@react-dnd/invariant": "^2.0.0",
- "@react-dnd/shallowequal": "^2.0.0",
- "dnd-core": "14.0.1",
- "fast-deep-equal": "^3.1.3",
- "hoist-non-react-statics": "^3.3.2"
- },
- "peerDependencies": {
- "@types/hoist-non-react-statics": ">= 3.3.1",
- "@types/node": ">= 12",
- "@types/react": ">= 16",
- "react": ">= 16.14"
- },
- "peerDependenciesMeta": {
- "@types/hoist-non-react-statics": {
- "optional": true
- },
- "@types/node": {
- "optional": true
- },
- "@types/react": {
- "optional": true
- }
- }
- },
"node_modules/@supabase/postgres-meta": {
"version": "0.26.1",
"resolved": "https://registry.npmjs.org/@supabase/postgres-meta/-/postgres-meta-0.26.1.tgz",
@@ -10390,9 +10345,9 @@
}
},
"node_modules/autoprefixer": {
- "version": "10.4.7",
- "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.7.tgz",
- "integrity": "sha512-ypHju4Y2Oav95SipEcCcI5J7CGPuvz8oat7sUtYj3ClK44bldfvtvcxK6IEK++7rqB7YchDGzweZIBG+SD0ZAA==",
+ "version": "10.4.5",
+ "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.5.tgz",
+ "integrity": "sha512-Fvd8yCoA7lNX/OUllvS+aS1I7WRBclGXsepbvT8ZaPgrH24rgXpZzF0/6Hh3ZEkwg+0AES/Osd196VZmYoEFtw==",
"funding": [
{
"type": "opencollective",
@@ -10404,8 +10359,8 @@
}
],
"dependencies": {
- "browserslist": "^4.20.3",
- "caniuse-lite": "^1.0.30001335",
+ "browserslist": "^4.20.2",
+ "caniuse-lite": "^1.0.30001332",
"fraction.js": "^4.2.0",
"normalize-range": "^0.1.2",
"picocolors": "^1.0.0",
@@ -22586,6 +22541,35 @@
"react-dom": "^16.8.0 || ^17 || ^18"
}
},
+ "node_modules/react-dnd": {
+ "version": "14.0.5",
+ "resolved": "https://registry.npmjs.org/react-dnd/-/react-dnd-14.0.5.tgz",
+ "integrity": "sha512-9i1jSgbyVw0ELlEVt/NkCUkxy1hmhJOkePoCH713u75vzHGyXhPDm28oLfc2NMSBjZRM1Y+wRjHXJT3sPrTy+A==",
+ "dependencies": {
+ "@react-dnd/invariant": "^2.0.0",
+ "@react-dnd/shallowequal": "^2.0.0",
+ "dnd-core": "14.0.1",
+ "fast-deep-equal": "^3.1.3",
+ "hoist-non-react-statics": "^3.3.2"
+ },
+ "peerDependencies": {
+ "@types/hoist-non-react-statics": ">= 3.3.1",
+ "@types/node": ">= 12",
+ "@types/react": ">= 16",
+ "react": ">= 16.14"
+ },
+ "peerDependenciesMeta": {
+ "@types/hoist-non-react-statics": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/react-dnd-html5-backend": {
"version": "14.1.0",
"resolved": "https://registry.npmjs.org/react-dnd-html5-backend/-/react-dnd-html5-backend-14.1.0.tgz",
@@ -34715,40 +34699,6 @@
"cross-fetch": "^3.0.6"
}
},
- "@supabase/grid": {
- "version": "2.5.0-alpha.13",
- "resolved": "https://registry.npmjs.org/@supabase/grid/-/grid-2.5.0-alpha.13.tgz",
- "integrity": "sha512-5YDMUfCjgzBYY32S1c2tThQX0wwkY4UZuk0dek2I12KG0Og2DgxgcoTfbfVBcQ10pwjj1/gq0nmIL/pT1WCzug==",
- "requires": {
- "@monaco-editor/react": "^4.3.1",
- "@scaleleap/pg-format": "^1.0.0",
- "awesome-debounce-promise": "^2.1.0",
- "dayjs": "^1.10.4",
- "file-saver": "^2.0.5",
- "immutability-helper": "^3.1.1",
- "p-queue": "6.6.2",
- "react-contexify": "^5.0.0",
- "react-dnd": "^14.0.3",
- "react-dnd-html5-backend": "^14.0.1",
- "react-tiny-popover": "^6.0.5",
- "react-tracked": "^1.7.4",
- "scheduler": "^0.20.2"
- },
- "dependencies": {
- "react-dnd": {
- "version": "14.0.5",
- "resolved": "https://registry.npmjs.org/react-dnd/-/react-dnd-14.0.5.tgz",
- "integrity": "sha512-9i1jSgbyVw0ELlEVt/NkCUkxy1hmhJOkePoCH713u75vzHGyXhPDm28oLfc2NMSBjZRM1Y+wRjHXJT3sPrTy+A==",
- "requires": {
- "@react-dnd/invariant": "^2.0.0",
- "@react-dnd/shallowequal": "^2.0.0",
- "dnd-core": "14.0.1",
- "fast-deep-equal": "^3.1.3",
- "hoist-non-react-statics": "^3.3.2"
- }
- }
- }
- },
"@supabase/postgres-meta": {
"version": "0.26.1",
"resolved": "https://registry.npmjs.org/@supabase/postgres-meta/-/postgres-meta-0.26.1.tgz",
@@ -36115,12 +36065,12 @@
"devOptional": true
},
"autoprefixer": {
- "version": "10.4.7",
- "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.7.tgz",
- "integrity": "sha512-ypHju4Y2Oav95SipEcCcI5J7CGPuvz8oat7sUtYj3ClK44bldfvtvcxK6IEK++7rqB7YchDGzweZIBG+SD0ZAA==",
+ "version": "10.4.5",
+ "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.5.tgz",
+ "integrity": "sha512-Fvd8yCoA7lNX/OUllvS+aS1I7WRBclGXsepbvT8ZaPgrH24rgXpZzF0/6Hh3ZEkwg+0AES/Osd196VZmYoEFtw==",
"requires": {
- "browserslist": "^4.20.3",
- "caniuse-lite": "^1.0.30001335",
+ "browserslist": "^4.20.2",
+ "caniuse-lite": "^1.0.30001332",
"fraction.js": "^4.2.0",
"normalize-range": "^0.1.2",
"picocolors": "^1.0.0",
@@ -45585,6 +45535,18 @@
}
}
},
+ "react-dnd": {
+ "version": "14.0.5",
+ "resolved": "https://registry.npmjs.org/react-dnd/-/react-dnd-14.0.5.tgz",
+ "integrity": "sha512-9i1jSgbyVw0ELlEVt/NkCUkxy1hmhJOkePoCH713u75vzHGyXhPDm28oLfc2NMSBjZRM1Y+wRjHXJT3sPrTy+A==",
+ "requires": {
+ "@react-dnd/invariant": "^2.0.0",
+ "@react-dnd/shallowequal": "^2.0.0",
+ "dnd-core": "14.0.1",
+ "fast-deep-equal": "^3.1.3",
+ "hoist-non-react-statics": "^3.3.2"
+ }
+ },
"react-dnd-html5-backend": {
"version": "14.1.0",
"resolved": "https://registry.npmjs.org/react-dnd-html5-backend/-/react-dnd-html5-backend-14.1.0.tgz",
diff --git a/studio/package.json b/studio/package.json
index 35538aaa94d..a7a678d4b94 100644
--- a/studio/package.json
+++ b/studio/package.json
@@ -17,11 +17,11 @@
"@next/bundle-analyzer": "^12.0.4",
"@radix-ui/react-portal": "^0.1.1",
"@radix-ui/react-tooltip": "^0.1.6",
+ "@scaleleap/pg-format": "^1.0.0",
"@sentry/browser": "^6.15.0",
"@sentry/nextjs": "^6.15.0",
"@stripe/react-stripe-js": "^1.7.0",
"@stripe/stripe-js": "^1.25.0",
- "@supabase/grid": "v2.5.0-alpha.13",
"@supabase/postgres-meta": "^0.26.1",
"@supabase/react-data-grid": "^7.1.0-beta.7",
"@supabase/shared-types": "^0.1.18",
@@ -29,10 +29,15 @@
"@supabase/ui": "0.37.0-alpha.55",
"ajv": "^8.6.3",
"analytics-node": "^3.5.0",
+ "awesome-debounce-promise": "^2.1.0",
"clipboard": "^2.0.8",
"configcat-js": "^5.6.0",
"crypto-js": "^4.1.1",
"dayjs": "^1.11.0",
+ "file-saver": "^2.0.5",
+ "immutability-helper": "^3.1.1",
+ "p-queue": "6.6.2",
+
"lodash": "^4.17.21",
"lottie-react": "^2.1.0",
"markdown-table": "=2.0.0",
@@ -47,18 +52,24 @@
"prism-react-renderer": "^1.2.1",
"react": "^17.0.2",
"react-beautiful-dnd": "^13.1.0",
+ "react-contexify": "^5.0.0",
"react-csv": "^2.0.3",
"react-datepicker": "^4.6.0",
"react-dom": "^17.0.2",
+ "react-dnd": "^14.0.3",
+ "react-dnd-html5-backend": "^14.0.1",
"react-grid-layout": "^1.3.0",
"react-hot-toast": "^2.1.1",
"react-inlinesvg": "^2.3.0",
"react-split": "^2.0.13",
+ "react-tiny-popover": "^6.0.5",
+ "react-tracked": "^1.7.4",
"react-virtualized-auto-sizer": "^1.0.6",
"react-window": "^1.8.6",
"react-window-infinite-loader": "^1.0.7",
"recharts": "^2.1.6",
"sass": "^1.43.4",
+ "scheduler": "^0.20.2",
"semver": "^6.3.0",
"sqlstring": "^2.3.2",
"swr": "^1.2.1",
@@ -94,7 +105,7 @@
"@types/semver": "^7.3.9",
"@types/sqlstring": "^2.3.0",
"@types/zxcvbn": "^4.4.1",
- "autoprefixer": "^10.4.5",
+ "autoprefixer": "10.4.5",
"babel-loader": "^8.2.3",
"jest": "^27.4.0",
"jest-canvas-mock": "^2.3.1",
diff --git a/studio/pages/_app.tsx b/studio/pages/_app.tsx
index 5633656aedb..c47a40f3221 100644
--- a/studio/pages/_app.tsx
+++ b/studio/pages/_app.tsx
@@ -9,6 +9,7 @@ import 'styles/monaco.scss'
import 'styles/contextMenu.scss'
import 'styles/react-data-grid-logs.scss'
import 'styles/date-picker.scss'
+import 'styles/grid.css'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
diff --git a/studio/pages/project/[ref]/editor/[id].tsx b/studio/pages/project/[ref]/editor/[id].tsx
index 1f7f80e9ad1..38dced079e9 100644
--- a/studio/pages/project/[ref]/editor/[id].tsx
+++ b/studio/pages/project/[ref]/editor/[id].tsx
@@ -3,7 +3,7 @@ import { NextPage } from 'next'
import { useRouter } from 'next/router'
import { observer } from 'mobx-react-lite'
import { isUndefined, isNaN } from 'lodash'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { PostgresTable, PostgresColumn } from '@supabase/postgres-meta'
import Base64 from 'lib/base64'
diff --git a/studio/pages/vercel/integrate.tsx b/studio/pages/vercel/integrate.tsx
index 7fb5595db7e..3f724e72248 100644
--- a/studio/pages/vercel/integrate.tsx
+++ b/studio/pages/vercel/integrate.tsx
@@ -14,7 +14,7 @@ import {
} from '@supabase/ui'
import Divider from 'components/ui/Divider'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { useStore, withAuth } from 'hooks'
import { API_URL } from 'lib/constants'
@@ -285,7 +285,7 @@ const IntegrationProject: FC = observer(() => {
</Select>
</div>
<div
- className="w-full bg-panel-header-light dark:bg-panel-header-dark border
+ className="w-full bg-panel-header-light dark:bg-panel-header-dark border
border-border-secondary-light dark:border-border-secondary-dark rounded-sm"
>
<div className="flex justify-between items-center p-6">
diff --git a/studio/pages/vercel/setupProject.tsx b/studio/pages/vercel/setupProject.tsx
index ea4488e3d94..3c0a13b3ada 100644
--- a/studio/pages/vercel/setupProject.tsx
+++ b/studio/pages/vercel/setupProject.tsx
@@ -5,7 +5,7 @@ import { observer, useLocalObservable } from 'mobx-react-lite'
import { makeAutoObservable } from 'mobx'
import { debounce } from 'lodash'
import { Button, Input, Listbox, Typography } from '@supabase/ui'
-import { Dictionary } from '@supabase/grid'
+import { Dictionary } from 'components/grid'
import { useStore } from 'hooks'
import { post } from 'lib/common/fetch'
diff --git a/studio/stores/pgmeta/MetaStore.ts b/studio/stores/pgmeta/MetaStore.ts
index 01539696585..33d6f852ebb 100644
--- a/studio/stores/pgmeta/MetaStore.ts
+++ b/studio/stores/pgmeta/MetaStore.ts
@@ -1,7 +1,8 @@
import Papa from 'papaparse'
import { makeObservable, observable } from 'mobx'
import { find, isUndefined, isEqual, isEmpty, chunk } from 'lodash'
-import { Query } from '@supabase/grid'
+import { Query } from 'components/grid/query/Query'
+
import {
PostgresColumn,
PostgresTable,
diff --git a/studio/styles/grid.css b/studio/styles/grid.css
new file mode 100644
index 00000000000..9c17bddebf2
--- /dev/null
+++ b/studio/styles/grid.css
@@ -0,0 +1,704 @@
+.sb-grid {
+ @apply flex flex-col h-full;
+}
+
+.sb-grid-fill-container:after {
+ content: '';
+ display: inline-block;
+ width: 100%;
+}
+
+.rdg-cell {
+ @apply border-r border-b border-scale-400 dark:border-scale-500 text-sm;
+ @apply text-typography-body-light dark:text-typography-body-dark;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.rdg-cell-frozen-last {
+ @apply border-r-4 border-scale-400 dark:border-scale-500 shadow-none;
+}
+
+.rdg-cell-selected {
+ box-shadow: inset 0 0 0 1px #24b47e;
+}
+
+.rdg {
+ @apply bg-transparent box-border overflow-x-auto overflow-y-scroll select-none;
+ @apply border-t border-b border-r-0 border-l-0 border-scale-400 dark:border-scale-500;
+ contain: strict;
+ -webkit-user-select: none;
+ font-size: 14px;
+}
+
+.rdg *,
+.rdg ::after,
+.rdg ::before {
+ box-sizing: inherit;
+}
+
+@supports not (contain: strict) {
+ .rdg {
+ position: relative;
+ z-index: 0;
+ }
+}
+
+.rdg-focus-sink {
+ position: sticky;
+ top: 0;
+ left: 0;
+ height: 0;
+ width: 0;
+ outline: 0;
+}
+
+/*
+ Row header
+*/
+
+.rdg-header-row {
+ @apply bg-table-header-light dark:bg-table-header-dark border-none select-none;
+}
+
+.rdg-header-row {
+ height: var(--header-row-height);
+ line-height: var(--header-row-height);
+ top: 0;
+}
+
+.rdg-header-row .rdg-cell {
+ @apply bg-table-header-light dark:bg-table-header-dark border-b border-scale-400 dark:border-scale-500;
+ /* @apply text-typography-body-light dark:text-typography-body-dark; */
+}
+.rdg-header-row .rdg-cell p,
+/* .rdg-cell svg */ {
+ @apply text-typography-body-light dark:text-typography-body-dark;
+}
+.rdg-header-row .rdg-cell .react-contextmenu-wrapper {
+ @apply h-full flex items-center px-2 transition ease-in-out duration-100;
+}
+.rdg-header-row .rdg-cell .react-contextmenu-wrapper:hover {
+ @apply bg-scale-400;
+}
+.rdg-header-row .rdg-checkbox {
+ @apply border bg-table-header-light dark:bg-table-header-dark rounded-sm border-scale-400 dark:border-scale-500;
+}
+.rdg-header-row .rdg-checkbox-input:checked + .rdg-checkbox {
+ @apply border-4 bg-green-900 border-scale-400 dark:border-scale-500;
+}
+.rdg-header-row .rdg-checkbox-input:focus + .rdg-checkbox {
+ box-shadow: none;
+}
+
+.rdg-cell .Select {
+ max-height: 30px;
+ font-size: 12px;
+ font-weight: 400;
+}
+
+/*
+ Row
+*/
+
+.rdg-row {
+ @apply bg-table-body-light dark:bg-table-body-dark transition-colors;
+ @apply hover:bg-table-header-light dark:hover:bg-table-header-dark;
+}
+
+/* edit button */
+.rdg-row__select-column__edit-action {
+ @apply text-typography-body-light dark:text-typography-body-dark;
+ opacity: 0;
+}
+.rdg-row:hover .rdg-row__select-column__edit-action {
+ opacity: 0.5;
+}
+.rdg-row__select-column__edit-action:hover {
+ opacity: 1;
+}
+
+/* select row */
+.rdg-row[aria-selected='true'] {
+ @apply bg-bg-secondary-light dark:bg-bg-secondary-dark;
+ @apply hover:bg-bg-secondary-light dark:hover:bg-bg-secondary-dark;
+}
+
+.rdg-row .rdg-cell span,
+/* .rdg-row .rdg-cell svg, */
+.rdg-row .rdg-cell div {
+ @apply text-typography-body-light dark:text-typography-body-dark;
+}
+
+.tab-cursor {
+ cursor: pointer !important;
+}
+
+/*
+ Checkbox
+*/
+
+/* reset styles */
+[type='checkbox'] {
+ webkit-appearance: none;
+ -moz-appearance: none;
+ appearance: none;
+ padding: 0;
+ -webkit-print-color-adjust: exact;
+ color-adjust: exact;
+ display: inline-block;
+ vertical-align: middle;
+ background-origin: border-box;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+ user-select: none;
+ flex-shrink: 0;
+ height: 1rem;
+ width: 1rem;
+ color: #2563eb;
+ background-color: #fff;
+ border-color: #6b7280;
+ border-width: 1px;
+}
+
+[type='checkbox']:checked {
+ background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M12.207 4.793a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0l-2-2a1 1 0 011.414-1.414L6.5 9.086l4.293-4.293a1 1 0 011.414 0z'/%3e%3c/svg%3e");
+}
+
+[type='checkbox']:checked {
+ @apply dark:bg-brand-900;
+ @apply bg-brand-900;
+ border-color: transparent;
+ background-size: 100% 100%;
+ background-position: center;
+ background-repeat: no-repeat;
+}
+
+[type='checkbox'] {
+ @apply border border-solid rounded cursor-pointer;
+
+ @apply text-brand-600 border-scale-400 transition-all;
+ @apply hover:border-brand-900 focus:ring-brand-500 focus:outline-none;
+
+ @apply dark:bg-transparent dark:border-scale-500 dark:text-white;
+ @apply dark:hover:border-green-900;
+
+ margin-top: 2px;
+}
+
+/*
+ React Contexify
+*/
+
+.react-contexify {
+ position: fixed;
+ opacity: 0;
+ user-select: none;
+ background-color: #fff;
+ box-sizing: border-box;
+ box-shadow: 0px 10px 30px -5px rgba(0, 0, 0, 0.3);
+ border-radius: 6px;
+ padding: 6px 0;
+ min-width: 200px;
+ z-index: 100;
+}
+.react-contexify__submenu--is-open,
+.react-contexify__submenu--is-open > .react-contexify__item__content {
+ color: white;
+ background-color: #4393e6;
+}
+.react-contexify__submenu--is-open > .react-contexify__submenu {
+ pointer-events: initial;
+ opacity: 1;
+}
+.react-contexify .react-contexify__submenu {
+ position: absolute;
+ /* negate padding */
+ top: -6px;
+ pointer-events: none;
+ transition: opacity 0.275s;
+}
+.react-contexify__submenu-arrow {
+ margin-left: auto;
+ font-size: 12px;
+}
+.react-contexify__separator {
+ width: 100%;
+ height: 1px;
+ cursor: default;
+ margin: 4px 0;
+ background-color: rgba(0, 0, 0, 0.2);
+}
+.react-contexify__will-leave--disabled {
+ pointer-events: none;
+}
+.react-contexify__item {
+ cursor: pointer;
+ position: relative;
+}
+.react-contexify__item:focus {
+ outline: 0;
+}
+.react-contexify__item:not(.react-contexify__item--disabled):hover
+ > .react-contexify__item__content,
+.react-contexify__item:not(.react-contexify__item--disabled):focus
+ > .react-contexify__item__content {
+ color: white;
+ background-color: #4393e6;
+}
+.react-contexify__item:not(.react-contexify__item--disabled):hover
+ > .react-contexify__submenu {
+ pointer-events: initial;
+ opacity: 1;
+}
+.react-contexify__item--disabled {
+ cursor: default;
+ opacity: 0.5;
+}
+.react-contexify__item__content {
+ font-size: 13px;
+ padding: 6px 12px;
+ display: flex;
+ align-items: center;
+ white-space: nowrap;
+ color: #333;
+ position: relative;
+}
+
+.rdg__segmented-control {
+ @apply relative mx-2 border rounded-md h-8 border-scale-400 dark:border-scale-500;
+}
+
+.rdg__segmented-control__button {
+ @apply absolute inline-flex h-full items-center justify-center top-0;
+ @apply text-xs font-medium;
+ @apply text-scale-400;
+ @apply hover:text-white focus:z-10 focus:outline-none active:bg-scale-100;
+ @apply transition ease-in-out duration-150;
+ @apply cursor-pointer;
+ z-index: 1;
+}
+
+.rdg__segmented-control__button--option {
+ @apply text-scale-200;
+}
+
+.rdg__segmented-control__button--right {
+ @apply right-0;
+}
+
+.rdg__segmented-control__button--left {
+ @apply left-0;
+}
+
+.rdg__segmented-control__label {
+ @apply z-0 inline-block rounded h-full bg-scale-600 shadow transform transition ease-in-out duration-200 border border-scale-600;
+}
+
+.rdg__segmented-control__label--left {
+ @apply translate-x-0;
+}
+
+.rdg__segmented-control__label--right {
+ @apply translate-x-12;
+}
+
+.rdg__segmented-control__options-label {
+ @apply uppercase;
+ color: inherit;
+}
+
+/*
+ DropdownControl
+*/
+
+.dropdown-control {
+ @apply overflow-auto;
+}
+
+.dropdown-control .sbui-typography {
+ @apply block px-2 py-4;
+}
+
+/*
+ ForeignTableModal
+*/
+
+.foreign-table-modal__content-container {
+ @apply w-full;
+}
+
+/* .foreign-table-modal__content-container__inner {
+ @apply px-6;
+} */
+
+.foreign-table-modal__content-container__inner__overflow {
+ @apply w-full overflow-scroll;
+}
+
+.foreign-table-modal__filter {
+ @apply flex items-center space-x-2 mt-2;
+}
+
+.foreign-table-modal__filter__trigger-content {
+ @apply space-x-2;
+}
+
+.foreign-table-modal__filter__trigger-content__label {
+ @apply text-typography-body-light dark:text-typography-body-dark;
+}
+
+.foreign-table-modal__filter__trigger-content__name {
+ @apply text-typography-body-strong-light dark:text-typography-body-strong-dark font-bold;
+}
+
+.foreign-table-modal__filter__search-input {
+ @apply flex-grow;
+}
+
+.foreign-table-modal__menu {
+ @apply flex flex-col space-y-2;
+}
+
+.foreign-table-modal__row-item {
+ @apply border border-solid border-scale-400 dark:border-scale-500 rounded shadow-sm first:mt-2 overflow-hidden;
+}
+
+.foreign-table-modal__row-item__inner {
+ @apply flex space-x-4;
+}
+
+.foreign-table-modal__row-item__inner__key-item {
+ @apply flex flex-col flex-initial;
+}
+
+.foreign-table-modal__row-item__inner__key-item__key {
+ @apply font-mono;
+}
+
+/*
+ NullValue
+*/
+
+.null-value {
+ @apply block;
+}
+
+/*
+ CheckboxEditor
+*/
+
+.sb-grid-checkbox-editor {
+ @apply flex w-full h-full;
+}
+
+.sb-grid-checkbox-editor__input {
+ @apply w-4 h-4;
+}
+
+/*
+ DateEditor
+*/
+
+.sb-grid-date-editor {
+ @apply w-full h-full px-2;
+}
+
+/*
+ DateTimeEditor
+*/
+
+.sb-grid-datetime-editor {
+ @apply w-full h-full px-2;
+}
+
+/*
+ JsonEditor
+*/
+
+.sb-grid-json-editor__trigger {
+ @apply px-2 text-sm overflow-hidden overflow-ellipsis;
+}
+
+/*
+ NumberEditor
+*/
+
+.sb-grid-number-editor {
+ @apply w-full h-full px-2;
+}
+
+/*
+ SelectEditor
+*/
+
+.sb-grid-select-editor {
+ @apply w-full h-full;
+}
+
+/*
+ TextEditor
+*/
+
+.sb-grid-text-editor__trigger {
+ @apply px-2 text-sm overflow-hidden overflow-ellipsis;
+}
+
+/*
+ TimeEditor
+*/
+
+.sb-grid-time-editor {
+ @apply w-full h-full px-2;
+}
+
+/*
+ Pagination
+*/
+
+.sb-grid-pagination {
+ @apply flex items-center space-x-2;
+}
+
+.sb-grid-pagination-input-container {
+ @apply w-12;
+}
+.sb-grid-pagination-input {
+ @apply w-12 block;
+}
+
+.sb-grid-pagination-input .sbui-inputnumber {
+ padding-top: 0.25rem;
+ padding-bottom: 0.25rem;
+}
+
+/*
+ Footer
+*/
+
+.sb-grid-footer {
+ @apply flex justify-between h-10 px-2 bg-scale-100 dark:bg-scale-300 items-center;
+}
+
+.sb-grid-footer__inner {
+ @apply flex items-center;
+}
+
+/*
+ ForeignKeyFormatter
+*/
+
+.sb-grid-foreign-key-formatter {
+ @apply flex items-center px-2;
+}
+
+.sb-grid-foreign-key-formatter__text {
+ @apply m-0 flex-grow text-sm overflow-hidden overflow-ellipsis;
+}
+
+/*
+ AddColumn
+*/
+
+.sb-grid-add-column {
+ @apply flex h-full;
+}
+
+/*
+ ColumnHeader
+*/
+
+.sb-grid-column-header {
+ @apply flex items-center justify-between;
+}
+
+.sb-grid-column-header--cursor {
+ @apply cursor-default;
+}
+
+.sb-grid-column-header__inner {
+ @apply flex items-center space-x-2 overflow-hidden overflow-ellipsis;
+}
+
+.sb-grid-column-header__inner__name {
+ @apply overflow-hidden overflow-ellipsis text-sm;
+ @apply text-typography-body-light dark:text-typography-body-dark;
+}
+
+.sb-grid-column-header__inner__format {
+ @apply text-xs;
+ @apply font-normal overflow-hidden overflow-ellipsis;
+ @apply text-typography-body-secondary-light dark:text-typography-body-secondary-dark;
+}
+
+.sb-grid-column-header__inner__primary-key {
+ @apply transform rotate-45 flex items-center;
+}
+
+.sb-grid-column-header__inner svg {
+ @apply mr-1;
+ @apply text-green-900 border-green-900 dark:text-green-900 dark:border-green-900;
+}
+
+/*
+ Grid
+*/
+
+.sb-grid-grid--loading {
+ @apply flex justify-center bg-transparent;
+}
+
+.sb-grid-grid--loading__inner {
+ @apply flex items-center;
+}
+
+.sb-grid-grid--loading__inner__text {
+ @apply m-8;
+}
+
+/*
+ SelectColumn
+*/
+
+.sb-grid-select-cell__formatter {
+ @apply flex justify-between items-center h-full;
+}
+
+.sb-grid-select-cell__header {
+ @apply flex justify-between items-center h-full;
+}
+
+.sb-grid-select-cell__header__input {
+ /* @apply focus:ring-brand-500; */
+ @apply border-scale-300;
+}
+
+/*
+ header/filter/FilterDropdown
+*/
+
+.sb-grid-filter-popover {
+ @apply overflow-visible;
+}
+
+.sb-grid-filter-popover__misc {
+ @apply py-2;
+}
+
+.sb-grid-filter-popover__misc__text {
+ @apply block;
+}
+
+/*
+ header/filter/FilterRow
+*/
+
+.sb-grid-filter-row {
+ @apply flex items-center justify-between w-full space-x-1;
+}
+
+/* .sb-grid-filter-row__inner__close {
+ @apply p-0 bg-transparent hover:bg-transparent;
+} */
+
+/*
+ header/sort/SortDropdown
+*/
+
+.sb-grid-sort-popover {
+ @apply w-96;
+}
+
+.sb-grid-dropdown__empty {
+ @apply py-2;
+}
+
+.sb-grid-dropdown__empty__text {
+ @apply block;
+}
+
+.sb-grid-dropdown__item-trigger {
+ @apply my-1;
+}
+
+/*
+ header/sort/SortRow
+*/
+
+.sb-grid-sort-row {
+ @apply flex justify-between space-x-3;
+}
+
+.sb-grid-sort-row__item {
+ @apply flex items-center space-x-3;
+}
+
+.sb-grid-sort-row__item__remove {
+ @apply p-0 bg-transparent hover:bg-transparent;
+}
+
+.sb-grid-sort-row__item__label {
+ @apply flex items-center space-x-2;
+}
+
+.sb-grid-sort-row__item_toogle {
+ @apply flex items-center space-x-3 gap-0 w-28;
+}
+
+.sb-grid-sort-row__item__move {
+ @apply flex cursor-move;
+}
+
+/*
+ Header
+*/
+
+.sb-grid-header {
+ @apply flex justify-between h-10 px-2 bg-scale-100 dark:bg-scale-300;
+}
+
+.sb-grid-header__inner {
+ @apply flex items-center space-x-2;
+}
+
+.sb-grid-header__inner__divider {
+ @apply py-2;
+}
+
+.row_header__selected-rows {
+ @apply ml-2 mr-2;
+}
+
+/*
+ StatusLabel
+*/
+
+.sb-grid-status-label {
+ @apply text-white text-sm;
+}
+
+.sb-grid-status-label__no-msg {
+ @apply flex w-5 h-5;
+}
+
+.sb-grid-status-label__no-msg > div {
+ @apply m-auto w-2 h-2 rounded-full bg-green-900;
+}
+
+/*
+ Empty value
+*/
+
+.sb-grid-empty-value {
+ @apply block;
+}
+
+/*
+ RowContextMenu
+*/
+
+.sb-grid-context-menu__label {
+ @apply ml-2;
+}