Skip to content

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

Email in Invitation of Team Members is Case Sensitive.

gitstart42a0f79e71ad
diff --cc studio/components/grid/components/common/ConfirmAlert.tsx
index 00000000000,00000000000..294e3916cc0
new file mode 100644
--- /dev/null
+++ b/studio/components/grid/components/common/ConfirmAlert.tsx
@@@ -1,0 -1,0 +1,94 @@@
++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-scale-1100 py-4 text-sm">{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 --cc studio/components/grid/components/header/filter/Filter.utils.ts
index 00000000000,00000000000..9e317a3f920
new file mode 100644
--- /dev/null
+++ b/studio/components/grid/components/header/filter/Filter.utils.ts
@@@ -1,0 -1,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 --cc studio/components/grid/components/menu/RowMenu.tsx
index 00000000000,00000000000..bff5b03eaab
new file mode 100644
--- /dev/null
+++ b/studio/components/grid/components/menu/RowMenu.tsx
@@@ -1,0 -1,0 +1,90 @@@
++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 { saveAs } from 'file-saver'
++import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'
++
++type RowMenuProps = {}
++
++const RowMenu: React.FC<RowMenuProps> = ({}) => {
++ const state = useTrackedState()
++ const dispatch = useDispatch()
++ const { selectedRows, rows: allRows, editable } = state
++
++ function onRowsDelete() {
++ confirmAlert({
++ 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;' })
++ 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;' })
++ 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"
++ className="opacity-50"
++ icon={<IconChevronDown />}
++ style={{ padding: '3px' }}
++ />
++ </Dropdown>
++ </>
++ )
++}
++export default RowMenu
diff --cc studio/components/grid/store/reducers/filter.ts
index 00000000000,00000000000..c9f051326b3
new file mode 100644
--- /dev/null
+++ b/studio/components/grid/store/reducers/filter.ts
@@@ -1,0 -1,0 +1,106 @@@
++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 --cc studio/components/grid/store/reducers/sort.ts
index 00000000000,00000000000..dd7abce1cfe
new file mode 100644
--- /dev/null
+++ b/studio/components/grid/store/reducers/sort.ts
@@@ -1,0 -1,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 --cc studio/components/grid/utils/filter.ts
index 00000000000,00000000000..d81d59f0939
new file mode 100644
--- /dev/null
+++ b/studio/components/grid/utils/filter.ts
@@@ -1,0 -1,0 +1,16 @@@
++import { uuidv4 } from 'lib/helpers'
++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.map((filter) => ({ ...filter, id: filter?.id || uuidv4() }))
++ }
++ }
++ return []
++}
diff --cc studio/components/grid/utils/sort.ts
index 00000000000,00000000000..a723255c01c
new file mode 100644
--- /dev/null
+++ b/studio/components/grid/utils/sort.ts
@@@ -1,0 -1,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 --cc studio/components/interfaces/Organization/InviteMemberModal.tsx
index b8ea3f5c220,b8ea3f5c220..ccb99433d74
--- a/studio/components/interfaces/Organization/InviteMemberModal.tsx
+++ b/studio/components/interfaces/Organization/InviteMemberModal.tsx
@@@ -35,7 -35,7 +35,7 @@@ function InviteMemberModal({ organizati
setAddMemberLoading(true)
const response = await post(`${API_URL}/organizations/${orgSlug}/members/invite`, {
-- invited_email: emailAddress,
++ invited_email: emailAddress.toLowerCase(),
owner_id: toJS(user.id),
})
diff --cc studio/components/to-be-cleaned/ModalsDeprecated/InviteMemberModal.js
index 00000000000,00000000000..2540a49ed6c
new file mode 100644
--- /dev/null
+++ b/studio/components/to-be-cleaned/ModalsDeprecated/InviteMemberModal.js
@@@ -1,0 -1,0 +1,323 @@@
++import { createContext, useContext, useCallback, useState, useEffect } from 'react'
++import { debounce, isNil } from 'lodash'
++import { observer, useLocalObservable } from 'mobx-react-lite'
++import { post } from 'lib/common/fetch'
++import { Button, IconKey, IconLoader, IconUser, IconX, Input, Typography } from '@supabase/ui'
++import { Modal } from '@supabase/ui'
++
++import { API_URL } from 'lib/constants'
++import { Transition } from '@headlessui/react'
++import { useOrganizationDetail, useStore } from 'hooks'
++
++/**
++ * Modal to invite member to Organization
++ *
++ * @param {Object} organization // organization detail
++ * @param {Array} members // organization members list
++ */
++
++const PageContext = createContext(null)
++function InviteMemberModal({ organization, members = [] }) {
++ const PageState = useLocalObservable(() => ({
++ members: [],
++ keywords: '',
++ profiles: null,
++ selectedProfile: null,
++ addMemberLoading: false,
++ get addBtnText() {
++ if (this.selectedProfile) return `Add ${this.selectedProfile.username} to organization`
++ return 'Select a member above'
++ },
++ get addBtnDisable() {
++ return !this.selectedProfile || this.addMemberLoading
++ },
++ setProfiles(profiles) {
++ let temp = profiles
++ if (profiles) {
++ temp = profiles
++ .map((profile) => {
++ const foundMember = this.members.find((x) => x.profile.id == profile.id)
++ return { ...profile, isMember: foundMember !== undefined }
++ })
++ .sort((a, b) => a.username.localeCompare(b.username))
++ }
++ this.profiles = temp
++ },
++ }))
++ const { ui } = useStore()
++ const { mutateOrgMembers } = useOrganizationDetail(ui.selectedOrganization?.slug || '')
++ const [isOpen, setIsOpen] = useState(false)
++ const { id: orgId, slug: orgSlug } = organization
++
++ useEffect(() => {
++ PageState.members = members
++ }, [members])
++
++ function toggle() {
++ // reset data before showing modal again
++ if (!isOpen) {
++ PageState.keywords = ''
++ PageState.selectedProfile = null
++ PageState.profiles = null
++ PageState.addMemberLoading = false
++ }
++ setIsOpen(!isOpen)
++ }
++
++ async function addMember() {
++ PageState.addMemberLoading = true
++ const response = await post(`${API_URL}/organizations/${orgSlug}/members/add`, {
++ org_id: orgId,
++ user_id: PageState.selectedProfile.id,
++ })
++ if (isNil(response)) {
++ ui.setNotification({ category: 'error', message: 'Failed to add member' })
++ } else if (response?.error) {
++ ui.setNotification({
++ category: 'error',
++ message: `Failed to add member: ${response.error.message}`,
++ })
++ PageState.addMemberLoading = false
++ } else {
++ const newMember = response
++ mutateOrgMembers([...PageState.members, newMember], false)
++ toggle()
++ ui.setNotification({ category: 'success', message: 'Successfully added new member' })
++ }
++ }
++
++ return (
++ <PageContext.Provider value={PageState}>
++ <Button onClick={toggle}>Invite</Button>
++ <Modal
++ size="small"
++ className="!overflow-visible"
++ icon={<IconKey size="xlarge" background="brand" />}
++ visible={isOpen}
++ onCancel={toggle}
++ header="Invite a member to organization"
++ description="Members you'd like to invite must already be registered on Supabase"
++ layout="vertical"
++ hideFooter
++ >
++ <div className="w-full py-4 space-y-4">
++ <Modal.Content>
++ <div className="text-center">
++ <InputSearchWithResults className="" />
++ </div>
++ </Modal.Content>
++ <Modal.Seperator />
++ <Modal.Content>
++ <div className="">
++ <Button
++ onClick={addMember}
++ loading={PageState.addMemberLoading}
++ disabled={PageState.addBtnDisable}
++ block
++ >
++ {PageState.addBtnText}
++ </Button>
++ </div>
++ </Modal.Content>
++ </div>
++ </Modal>
++ </PageContext.Provider>
++ )
++}
++export default observer(InviteMemberModal)
++
++const InputSearchWithResults = observer(({ className }) => {
++ const PageState = useContext(PageContext)
++ const { ui } = useStore()
++ const [loading, setLoading] = useState(false)
++ const debounceSearchProfile = useCallback(debounce(searchProfile, 500), [PageState.keywords])
++
++ useEffect(() => {
++ debounceSearchProfile()
++ // Cancel the debounce on useEffect cleanup.
++ return debounceSearchProfile.cancel
++ }, [PageState.keywords, debounceSearchProfile])
++
++ async function searchProfile() {
++ if (PageState.keywords.length === 0) {
++ PageState.setProfiles(null)
++ return
++ }
++ setLoading(true)
++ const response = await post(`${API_URL}/profile/search`, { keywords: PageState.keywords })
++ if (isNil(response)) {
++ ui.setNotification({ category: 'error', message: 'Failed to search profile' })
++ } else if (response.error) {
++ ui.setNotification({
++ category: 'error',
++ message: `Failed to search profile: ${response.error.message}`,
++ })
++ setLoading(false)
++ } else {
++ PageState.setProfiles(response)
++ setLoading(false)
++ }
++ }
++
++ function onInputChange(e) {
++ PageState.keywords = e.target.value
++ }
++
++ function reset() {
++ PageState.keywords = ''
++ PageState.setProfiles(null)
++ PageState.selectedProfile = null
++ }
++
++ if (PageState.selectedProfile) {
++ const fullName = `${PageState.selectedProfile.first_name || ''} ${
++ PageState.selectedProfile.last_name || ''
++ }`
++ return (
++ <div className={className}>
++ <div className="flex px-6 py-2 items-center rounded bg-scale-400 border">
++ <div className="flex-grow text-left">
++ <p className="text-scale-1200 font-medium">{PageState.selectedProfile.username}</p>
++ <p className="text-sm leading-5 text-scale-1100">
++ {fullName !== ' ' ? `${fullName} • Invite collaborator` : 'Invite collaborator'}
++ </p>
++ </div>
++ <button className="text-scale-900 hover:text-scale-1200">
++ <IconX strokeWidth={2} onClick={reset} />
++ </button>
++ </div>
++ </div>
++ )
++ }
++
++ const onSelectDropdownOption = (e, option) => {
++ if (!option.isMember) PageState.selectedProfile = option
++ }
++
++ return (
++ <div className={className}>
++ <div className="relative rounded-md shadow-sm">
++ <Input
++ icon={<IconUser />}
++ autoFocus
++ id="email"
++ type="text"
++ className="form-input"
++ onChange={onInputChange}
++ autoComplete="off"
++ value={PageState.keywords}
++ placeholder="search by username or email"
++ />
++ <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
++ {loading && <IconLoader className="animate-spin" size={16} />}
++ </div>
++ </div>
++ {PageState.profiles && PageState.profiles.length !== 0 ? (
++ <>
++ <div className="flex flex-col gap-1 py-4">
++ {PageState.profiles.map((profile, i) => {
++ const { first_name, last_name, username, isMember } = profile
++ const fullName = `${first_name || ''} ${last_name || ''}`
++ let subText = isMember ? 'Already in this organization' : 'Invite collaborator'
++ if (fullName !== ' ') subText = `${fullName} • ${subText}`
++ return (
++ <Button
++ block
++ key={`option_${i}`}
++ className={`px-3 py-1 ${
++ isMember
++ ? 'cursor-not-allowed opacity-50'
++ : 'cursor-pointer hover:bg-bg-alt-light dark:hover:bg-bg-alt-dark'
++ } first:rounded-t-md last:rounded-b-md`}
++ onClick={(e) => onSelectDropdownOption(e, profile)}
++ type="default"
++ style={{ justifyContent: 'flex-start' }}
++ size="medium"
++ >
++ <div className="flex items-center gap-2">
++ <span className="block truncate">{username}</span>
++ <span className="text-scale-900 block truncate" type="secondary">
++ {subText}
++ </span>
++ </div>
++ </Button>
++ )
++ })}
++ </div>
++ </>
++ ) : PageState.profiles &&
++ PageState.profiles.length === 0 &&
++ !loading &&
++ PageState.keywords ? (
++ <>
++ <p className="text-sm text-scale-1200 mt-4">Could not find account.</p>
++ <p className="text-sm text-scale-1100">Has the user already signed up?</p>
++ </>
++ ) : null}
++ </div>
++ )
++})
++
++const ProfileDropdown = observer(({ className }) => {
++ const PageState = useContext(PageContext)
++
++ const onSelectDropdownOption = (e, option) => {
++ if (!option.isMember) PageState.selectedProfile = option
++ }
++
++ if (!PageState.profiles) return null
++ return (
++ <div className={className}>
++ <Transition
++ show={!PageState.selectedProfile}
++ enter="transition ease-out duration-100"
++ enterFrom="transform opacity-0 scale-95"
++ enterTo="transform opacity-100 scale-100"
++ leave="transition ease-in duration-75"
++ leaveFrom="transform opacity-100 scale-100"
++ leaveTo="transform opacity-0 scale-95"
++ >
++ <div className="origin-top-right w-full max-h-48 rounded-md shadow-lg overflow-y-auto z-100 fixed">
++ <div className="rounded-md bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 text-left">
++ <div
++ className="py-1"
++ role="menu"
++ aria-orientation="vertical"
++ aria-labelledby="options-menu"
++ >
++ {PageState.profiles.length === 0 && (
++ <div className="px-3 py-2">
++ <p className="text-base leading-6 font-medium">
++ Could not find account. Has the user already signed up?
++ </p>
++ </div>
++ )}
++ {PageState.profiles.map((profile, i) => {
++ const { first_name, last_name, username, isMember } = profile
++ const fullName = `${first_name || ''} ${last_name || ''}`
++ let subText = isMember ? 'Already in this organization' : 'Invite collaborator'
++ if (fullName !== ' ') subText = `${fullName} • ${subText}`
++ return (
++ <div
++ key={`option_${i}`}
++ className={`px-3 py-1 ${
++ isMember
++ ? 'cursor-not-allowed opacity-50'
++ : 'cursor-pointer hover:bg-bg-alt-light dark:hover:bg-bg-alt-dark'
++ } first:rounded-t-md last:rounded-b-md`}
++ onClick={(e) => onSelectDropdownOption(e, profile)}
++ >
++ <Typography.Text className="block">{username}</Typography.Text>
++ <Typography.Text className="block" type="secondary">
++ {subText}
++ </Typography.Text>
++ </div>
++ )
++ })}
++ </div>
++ </div>
++ </div>
++ </Transition>
++ </div>
++ )
++})
diff --cc studio/pages/project/[ref]/database/backups.tsx
index 00000000000,00000000000..3b46cc4d52a
new file mode 100644
--- /dev/null
+++ b/studio/pages/project/[ref]/database/backups.tsx
@@@ -1,0 -1,0 +1,25 @@@
++import { observer } from 'mobx-react-lite'
++
++import { DatabaseLayout } from 'components/layouts'
++import { BackupsList } from 'components/interfaces/Database'
++import { NextPageWithLayout } from 'types'
++
++const DatabaseBackups: NextPageWithLayout = () => {
++ return (
++ <div className="flex">
++ <div className="my-2 mx-auto w-full max-w-4xl space-y-8 p-4">
++ <h3 className="text-2xl">Backups</h3>
++ <div className="space-y-4">
++ <p className="text-scale-1100 text-sm">
++ Projects are backed up daily and can be restored at any time.
++ </p>
++ <BackupsList />
++ </div>
++ </div>
++ </div>
++ )
++}
++
++DatabaseBackups.getLayout = (page) => <DatabaseLayout title="Database">{page}</DatabaseLayout>
++
++export default observer(DatabaseBackups)
diff --cc studio/stores/content/ProjectContentStore.ts
index 00000000000,00000000000..8cd3d288a56
new file mode 100644
--- /dev/null
+++ b/studio/stores/content/ProjectContentStore.ts
@@@ -1,0 -1,0 +1,337 @@@
++import { makeAutoObservable } from 'mobx'
++import { keyBy } from 'lodash'
++
++import { uuidv4 } from 'lib/helpers'
++import { get, post, patch, delete_ } from 'lib/common/fetch'
++import { LogSqlSnippets, UserContent, UserContentMap } from 'types'
++import { IRootStore } from '../RootStore'
++import { API_URL } from 'lib/constants'
++
++// [Joshen] This will be the new ProjectContentStore
++// but use the one under the stores folder projectContentStore first while we transition
++
++type CustomFilter = (content: UserContent) => boolean
++export interface IProjectContentStore {
++ isLoading: boolean
++ isInitialized: boolean
++ isLoaded: boolean
++ savingState: 'IDLE' | 'CREATING' | 'CREATING_FAILED' | 'UPDATING' | 'UPDATING_FAILED'
++ error: any
++ recentLogSqlSnippets: LogSqlSnippets.Content[]
++
++ baseUrl: string
++ projectRef?: string
++
++ load: () => Promise<UserContentMap | undefined>
++ loadPersistentData: () => Promise<void>
++ save: (
++ content: UserContent
++ ) => Promise<{ data: UserContent; error: null } | { data: null; error: { message: string } }>
++ create: (
++ content: UserContent
++ ) => Promise<{ data: UserContent; error: null } | { data: null; error: { message: string } }>
++ createOptimistically: (content: UserContent) => { data: UserContent; error: null }
++ list: (filter?: any) => any[]
++ reports: (filter?: any) => any[]
++ sqlSnippets: (filter?: any) => any[]
++ savedLogSqlSnippets: (filter?: CustomFilter) => UserContent[]
++ addRecentLogSqlSnippet: (snippet: Partial<LogSqlSnippets.Content>) => void
++ clearRecentLogSqlSnippets: () => void
++ setProjectRef: (ref?: string) => void
++ update: (
++ id: any,
++ updates: any,
++ type: UserContent['type']
++ ) => Promise<
++ | {
++ data: UserContent
++ error: null
++ }
++ | {
++ data: null
++ error: unknown
++ }
++ >
++
++ del(id: any): Promise<{ data: boolean; error: unknown }>
++ delOptimistically(id: string): { data: boolean; error: null }
++}
++
++export default class ProjectContentStore implements IProjectContentStore {
++ rootStore: IRootStore
++
++ STATES = {
++ INITIAL: 'initial',
++ LOADING: 'loading',
++ ERROR: 'error',
++ LOADED: 'loaded',
++ }
++
++ baseUrl: string
++ localStorageKey: string
++ recentLogSqlKey: string
++ projectRef: string
++
++ data: UserContentMap = {}
++ recentLogSqlSnippets: LogSqlSnippets.Content[] = []
++
++ state = this.STATES.INITIAL
++ savingState: 'IDLE' | 'CREATING' | 'CREATING_FAILED' | 'UPDATING' | 'UPDATING_FAILED'
++ error = null
++
++ constructor(rootStore: IRootStore, options: { projectRef: string }) {
++ const { projectRef } = options
++ this.projectRef = projectRef
++ this.rootStore = rootStore
++ this.localStorageKey = `project-content-${projectRef}`
++ this.recentLogSqlKey = `${this.localStorageKey}-recent-log-sql`
++ this.loadPersistentData()
++ this.baseUrl = ``
++ this.savingState = 'IDLE'
++ makeAutoObservable(this)
++ }
++
++ get isLoading() {
++ return this.state === this.STATES.INITIAL || this.state === this.STATES.LOADING
++ }
++
++ get isInitialized() {
++ return this.state !== this.STATES.INITIAL
++ }
++
++ get isLoaded() {
++ return this.state === this.STATES.LOADED
++ }
++
++ async fetchData() {
++ const headers = {
++ 'Content-Type': 'application/json',
++ }
++ const response = await get(this.baseUrl, { headers })
++ if (response.error) {
++ throw response.error
++ }
++ this.data = keyBy(response.data, 'id')
++ return response
++ }
++
++ async load() {
++ let { LOADING, ERROR, LOADED } = this.STATES
++ try {
++ this.error = null
++ this.state = LOADING
++ await this.fetchData()
++ this.state = LOADED
++ return this.data
++ } catch (e: any) {
++ console.error('Failed to load project content', e.message)
++ this.error = e
++ this.state = ERROR
++ }
++ }
++
++ async loadPersistentData() {
++ this.loadRecentLogSqlSnippets()
++ }
++
++ async loadRemotePersistentData(userId: any) {
++ const sqlSnippets = this.sqlSnippets((x: any) => x.owner_id === userId)
++ }
++
++ loadRecentLogSqlSnippets() {
++ if (typeof window === 'undefined') return
++ this.recentLogSqlSnippets = JSON.parse(
++ (window as any).localStorage.getItem(this.recentLogSqlKey) || '[]'
++ )
++ }
++
++ list(filter?: any) {
++ const arr = Object.values(this.data)
++ if (!!filter) {
++ return arr.filter(filter).sort((a, b) => a.name.localeCompare(b.name))
++ } else {
++ return arr.sort((a, b) => a.name.localeCompare(b.name))
++ }
++ }
++
++ byId(id: any) {
++ return this.data[id]
++ }
++
++ reports(filter?: any) {
++ let arr = Object.values(this.data)
++ if (!!filter) {
++ return arr
++ .filter((x) => x.type == 'report')
++ .filter(filter)
++ .sort((a, b) => a.name.localeCompare(b.name))
++ } else {
++ return arr.filter((x) => x.type == 'report').sort((a, b) => a.name.localeCompare(b.name))
++ }
++ }
++
++ sqlSnippets(filter?: any) {
++ let arr = Object.values(this.data)
++ if (!!filter) {
++ const arr_filtered = arr
++ .filter((x) => x.type == 'sql')
++ .filter(filter)
++ .sort((a, b) => a.name.localeCompare(b.name))
++
++ return arr_filtered
++ } else {
++ const arr_filtered = arr
++ .filter((x) => x.type == 'sql')
++ .sort((a, b) => a.name.localeCompare(b.name))
++
++ return arr_filtered
++ }
++ }
++
++ addRecentLogSqlSnippet(snippet: Partial<LogSqlSnippets.Content>) {
++ if (typeof window === 'undefined') return
++ const defaults: LogSqlSnippets.Content = {
++ schema_version: '1',
++ favorite: false,
++ sql: '',
++ content_id: '',
++ }
++ this.recentLogSqlSnippets.push({ ...defaults, ...snippet })
++ ;(window as any).localStorage.setItem(
++ this.recentLogSqlKey,
++ JSON.stringify(this.recentLogSqlSnippets)
++ )
++ }
++
++ clearRecentLogSqlSnippets() {
++ if (typeof window === 'undefined') return
++ this.recentLogSqlSnippets = []
++ ;(window as any).localStorage.setItem(this.recentLogSqlKey, JSON.stringify([]))
++ }
++
++ savedLogSqlSnippets(filter?: CustomFilter) {
++ let arr = Object.values(this.data) as UserContent[]
++ let snippets = arr.filter((c) => c.type === 'log_sql')
++ if (filter) {
++ snippets = snippets.filter(filter)
++ }
++ return snippets.sort((a, b) => a.name.localeCompare(b.name))
++ }
++
++ /**
++ * Creates a new content item, but does not update local store
++ */
++ async save(payload: UserContent) {
++ try {
++ this.savingState = 'CREATING'
++
++ const headers = {
++ 'Content-Type': 'application/json',
++ }
++ const created = await post<UserContent>(this.baseUrl, payload, { headers })
++ if (created.error) throw created.error
++
++ this.savingState = 'IDLE'
++
++ return { data: created as UserContent, error: null }
++ } catch (error) {
++ this.savingState = 'CREATING_FAILED'
++
++ return { data: null, error: error as { message: string } }
++ }
++ }
++
++ /**
++ * Creates a new content item, and updates local store
++ */
++ async create(payload: UserContent) {
++ const { data, error } = await this.save(payload)
++
++ if (error) {
++ return { data: null, error }
++ }
++
++ if (data && data['id']) {
++ this.data[data['id']] = data
++ }
++
++ return { data: data as UserContent, error: null }
++ }
++
++ /**
++ * Creates a new content item locally in store without saving to the server
++ */
++ createOptimistically(payload: UserContent) {
++ const created = { ...payload, id: uuidv4() }
++
++ this.data[created.id] = created
++
++ return { data: created, error: null }
++ }
++
++ async update(id: any, updates: any, type?: UserContent['type']) {
++ try {
++ this.savingState = 'UPDATING'
++
++ const headers = {
++ 'Content-Type': 'application/json',
++ }
++ let payload = {
++ ...updates,
++ id,
++ }
++ if (type) {
++ payload.type = type
++ }
++
++ const url = `${this.baseUrl}?id=${id}`
++ const updated = await patch<UserContent[]>(url, payload, { headers })
++ if (updated.error) throw updated.error
++
++ const localUpdate = { ...this.data[id], ...payload }
++ this.data[id] = localUpdate
++ this.savingState = 'IDLE'
++
++ return { data: localUpdate, error: null }
++ } catch (error) {
++ this.savingState = 'UPDATING_FAILED'
++
++ return { data: null, error }
++ }
++ }
++
++ async updateSql(id: any, updates: any) {
++ return this.update(id, updates, 'sql')
++ }
++
++ async updateReport(id: any, updates: any) {
++ return this.update(id, updates, 'report')
++ }
++
++ async del(id: any) {
++ try {
++ const headers = {
++ 'Content-Type': 'application/json',
++ }
++ const url = `${this.baseUrl}?id=${id}`
++ const deleted = await delete_(url, {}, { headers })
++ if (deleted.error) throw deleted.error
++ delete this.data[id]
++ return { data: true, error: null }
++ } catch (error) {
++ return { data: false, error }
++ }
++ }
++
++ delOptimistically(id: string) {
++ delete this.data[id]
++ return { data: true, error: null }
++ }
++
++ setProjectRef(ref?: string) {
++ if (ref) {
++ this.projectRef = ref
++ this.baseUrl = `${API_URL}/projects/${ref}/content`
++ }
++ }
++}
diff --cc studio/stores/functions/ProjectFunctionsStore.ts
index 00000000000,00000000000..b8d9e564884
new file mode 100644
--- /dev/null
+++ b/studio/stores/functions/ProjectFunctionsStore.ts
@@@ -1,0 -1,0 +1,205 @@@
++import { makeAutoObservable, toJS } from 'mobx'
++import { keyBy } from 'lodash'
++
++import { get, post, patch, delete_ } from 'lib/common/fetch'
++import { UserContent, UserContentMap } from 'types'
++import { IRootStore } from '../RootStore'
++
++// [Joshen] This will be the new ProjectContentStore
++// but use the one under the stores folder projectContentStore first while we transition
++
++export interface IProjectFunctionsStore {
++ isLoading: boolean
++ isInitialized: boolean
++ isLoaded: boolean
++ error: any
++
++ baseUrl: string
++ projectRef: string
++
++ load: () => void
++ list: (filter?: any) => any[]
++ byId: (id?: any) => any
++ reports: (filter?: any) => any[]
++ sqlSnippets: (filter?: any) => any[]
++ setProjectRef: (ref?: string) => void
++}
++
++export default class ProjectFunctionsStore implements IProjectFunctionsStore {
++ rootStore: IRootStore
++
++ STATES = {
++ INITIAL: 'initial',
++ LOADING: 'loading',
++ ERROR: 'error',
++ LOADED: 'loaded',
++ }
++
++ baseUrl: string
++ projectRef: string
++ // @ts-ignore
++ data: UserContentMap = []
++
++ state = this.STATES.INITIAL
++ error = null
++
++ constructor(rootStore: IRootStore, options: { projectRef: string }) {
++ const { projectRef } = options
++ this.projectRef = projectRef
++ this.rootStore = rootStore
++ this.baseUrl = ``
++ makeAutoObservable(this)
++ }
++
++ get isLoading() {
++ return this.state === this.STATES.INITIAL || this.state === this.STATES.LOADING
++ }
++
++ get isInitialized() {
++ return this.state !== this.STATES.INITIAL
++ }
++
++ get isLoaded() {
++ return this.state === this.STATES.LOADED
++ }
++
++ async fetchData() {
++ const headers = {
++ 'Content-Type': 'application/json',
++ }
++ const response = await get(this.baseUrl, { headers })
++ if (response.error) {
++ throw response.error
++ }
++ this.data = keyBy(response, 'id')
++ return response
++ }
++
++ async load() {
++ let { LOADING, ERROR, LOADED } = this.STATES
++ try {
++ this.error = null
++ this.state = LOADING
++ await this.fetchData()
++ this.state = LOADED
++ return this.data
++ } catch (e: any) {
++ console.error('Failed to load project content', e.message)
++ this.error = e
++ this.state = ERROR
++ }
++ }
++
++ async loadPersistentData() {}
++
++ async loadRemotePersistentData(userId: any) {
++ const sqlSnippets = this.sqlSnippets((x: any) => x.owner_id === userId)
++ }
++
++ list(filter?: any) {
++ const arr = Object.values(this.data)
++ if (!!filter) {
++ return arr.filter(filter).sort((a, b) => a.name.localeCompare(b.name))
++ } else {
++ return arr.sort((a, b) => a.name.localeCompare(b.name))
++ }
++ }
++
++ byId(id: any) {
++ return toJS(this.data)[id]
++ }
++
++ reports(filter?: any) {
++ let arr = Object.values(this.data)
++ if (!!filter) {
++ return arr
++ .filter((x) => x.type == 'report')
++ .filter(filter)
++ .sort((a, b) => a.name.localeCompare(b.name))
++ } else {
++ return arr.filter((x) => x.type == 'report').sort((a, b) => a.name.localeCompare(b.name))
++ }
++ }
++
++ sqlSnippets(filter?: any) {
++ let arr = Object.values(this.data)
++ if (!!filter) {
++ const arr_filtered = arr
++ .filter((x) => x.type == 'sql')
++ .filter(filter)
++ .sort((a, b) => a.name.localeCompare(b.name))
++
++ return arr_filtered
++ } else {
++ const arr_filtered = arr
++ .filter((x) => x.type == 'sql')
++ .sort((a, b) => a.name.localeCompare(b.name))
++
++ return arr_filtered
++ }
++ }
++
++ async create(payload: any) {
++ try {
++ const headers = {
++ 'Content-Type': 'application/json',
++ }
++ const created = await post(this.baseUrl, payload, { headers })
++ if (created.error) throw created.error
++ this.data[created['id']] = created
++ return { data: created, error: null }
++ } catch (error) {
++ return { data: null, error }
++ }
++ }
++
++ async update(id: any, updates: any, type: UserContent['type']) {
++ try {
++ const headers = {
++ 'Content-Type': 'application/json',
++ }
++ let payload = {
++ ...updates,
++ type,
++ id,
++ }
++ const url = `${this.baseUrl}?id=${id}`
++ const updated = await patch(url, payload, { headers })
++ if (updated.error) throw updated.error
++ this.data[id] = updated
++ return { data: updated, error: null }
++ } catch (error) {
++ return { data: null, error }
++ }
++ }
++
++ async updateSql(id: any, updates: any) {
++ return this.update(id, updates, 'sql')
++ }
++
++ async updateReport(id: any, updates: any) {
++ return this.update(id, updates, 'report')
++ }
++
++ async del(id: any) {
++ try {
++ const headers = {
++ 'Content-Type': 'application/json',
++ }
++ const url = `${this.baseUrl}?id=${id}`
++ const deleted = await delete_(url, {}, { headers })
++ if (deleted.error) throw deleted.error
++ delete this.data[id]
++ return { data: true, error: null }
++ } catch (error) {
++ return { data: false, error }
++ }
++ }
++
++ setProjectRef(ref?: string) {
++ if (ref) {
++ this.projectRef = ref
++ this.baseUrl = `${process.env.NEXT_PUBLIC_API_ADMIN_URL}/projects/${ref}/functions`
++ }
++ }
++}