The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: add templates form
Jonathan Summers-Muir289930698840
diff --git a/studio/components/interfaces/Auth/EmailTemplates.tsx b/studio/components/interfaces/Auth/EmailTemplates.tsxnew file mode 100644index 00000000000..6f6ce831ecf--- /dev/null+++ b/studio/components/interfaces/Auth/EmailTemplates.tsx@@ -0,0 +1,212 @@+import { Alert, Form, Input, InputNumber, Loading, Tabs, Toggle } from '@supabase/ui'+import CodeEditor from 'components/ui/CodeEditor'+import { useStore } from 'hooks'+import { toJS } from 'mobx'+import { observer } from 'mobx-react-lite'+import { loadavg } from 'os'+import auth from 'pages/project/[ref]/auth'+import React from 'react'+import { useState } from 'react'+import { useEffect } from 'react'+import ReactMarkdown from 'react-markdown'+import { TEMPLATES_SCHEMAS } from 'stores/authConfig/schema'+import { boolean, number, object, string } from 'yup'+import {+ FormActions,+ FormHeader,+ FormPanel,+ FormSection,+ FormSectionContent,+ FormSectionLabel,+} from '../../ui/Forms'++const EmailTemplates = observer(() => {+ const { authConfig, ui } = useStore()+ const [enableSmtp, setEnableSmtp] = useState(false)++ const isLoaded = authConfig.isLoaded++ return (+ <div>+ <FormHeader+ title="Email Templates"+ description={`You can use your own SMTP server instead of the built-in email service.`}+ />+ <FormPanel>+ <Tabs+ defaultActiveId={TEMPLATES_SCHEMAS[0].title.trim().replace(/\s+/g, '-')}+ type="underlined"+ listClassNames="px-8 pt-4"+ size="small"+ scrollable+ >+ {TEMPLATES_SCHEMAS.map((template) => {+ const INITIAL_VALUES: { [x: string]: string } = {}++ /**+ * construct values for INITIAL_VALUES+ *+ * return empty string `""` rather than `null`+ * as it breaks form. null is not a valid value.+ */+ Object.keys(template.properties).forEach((key) => {+ INITIAL_VALUES[key] = authConfig.config[key] ?? ''+ })++ const messageSlug = `MAILER_TEMPLATES_${template.id}_CONTENT`+ const messageProperty = template.properties[messageSlug]++ return (+ <Tabs.Panel id={template.title.trim().replace(/\s+/g, '-')} label={template.title}>+ <Form+ id="auth-config-email-templates"+ className="!border-t-0"+ initialValues={INITIAL_VALUES}+ onSubmit={async (values: any, { setSubmitting, resetForm }: any) => {+ const payload = { ...values }++ try {+ setSubmitting(true)+ await authConfig.update(payload)+ setSubmitting(false)++ ui.setNotification({+ category: 'success',+ message: `Updated settings`,+ })+ } catch (error) {+ ui.setNotification({+ category: 'error',+ message: `Failed to update settings`,+ })+ setSubmitting(false)+ }+ }}+ >+ {({ isSubmitting, handleReset, resetForm, values, initialValues }: any) => {+ /**+ * Tracks changes in form+ */+ const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)++ /**+ * Form is reset once remote data is loaded in store+ */+ useEffect(() => {+ resetForm({+ values: authConfig.config,+ initialValues: authConfig.config,+ })+ }, [authConfig.isLoaded])++ return (+ <>+ <FormSection+ className="!border-t-0"+ header={+ <FormSectionLabel>+ <span>SMTP Provider Settings</span>+ <p className="text-scale-900 my-4">+ Your SMTP Credentials will always be encrypted in our database.+ </p>+ </FormSectionLabel>+ }+ >+ <FormSectionContent loading={!isLoaded}>+ {Object.keys(template.properties).map((x: string) => {+ /**+ * Properties of the form+ */+ const properties = template.properties[x]++ /**+ * Conditionally hide properties based on value of key+ */+ if (properties.type === 'code') {+ return null+ }++ switch (properties.type) {+ case 'string':+ return (+ <Input+ size="small"+ layout="vertical"+ id={x}+ key={x}+ name={x}+ label={properties.title}+ descriptionText={+ properties.description ? (+ <ReactMarkdown+ unwrapDisallowed+ disallowedElements={['p']}+ >+ {properties.description}+ </ReactMarkdown>+ ) : null+ }+ //+ // @ts-expect-error+ //+ // to do: change to "string" | React.ReactNode | undefined+ //+ labelOptional={+ properties.descriptionOptional ? (+ <ReactMarkdown+ unwrapDisallowed+ disallowedElements={['p']}+ >+ {properties.descriptionOptional}+ </ReactMarkdown>+ ) : null+ }+ />+ )+ break+ }+ })}+ </FormSectionContent>+ </FormSection>+ <FormSection className="grid-cols-12 !border-t-0">+ <FormSectionContent loading={!isLoaded} fullWidth>+ {messageProperty && (+ <CodeEditor+ id="code-id"+ loading={!isLoaded}+ language="html"+ className="h-96 overflow-hidden rounded border"+ defaultValue={authConfig?.config?.[messageSlug] || ''}+ onInputChange={(e) => console.log(e)}+ options={{ wordWrap: 'off', contextmenu: false }}+ />+ )}+ <div className="col-span-12 flex w-full justify-between">+ <FormActions+ handleReset={() => {+ resetForm({+ values: authConfig.config,+ initialValues: authConfig.config,+ })+ }}+ isSubmitting={isSubmitting}+ hasChanges={hasChanges}+ helper={'Learn more about global Auth settings'}+ />+ </div>+ </FormSectionContent>+ </FormSection>+ </>+ )+ }}+ </Form>+ </Tabs.Panel>+ )+ })}+ </Tabs>+ </FormPanel>+ </div>+ )+})++export { EmailTemplates }diff --git a/studio/components/interfaces/Auth/SmtpForm.tsx b/studio/components/interfaces/Auth/SmtpForm.tsxindex 0c17b223f50..ed7df1185e6 100644--- a/studio/components/interfaces/Auth/SmtpForm.tsx+++ b/studio/components/interfaces/Auth/SmtpForm.tsx@@ -20,6 +20,12 @@ const SmtpForm = observer(() => {const { authConfig, ui } = useStore()const [enableSmtp, setEnableSmtp] = useState(false)+ // let enableSmtp = false++ // function setEnableSmtp(value: boolean) {+ // enableSmtp = value+ // }+function generateInitialValues(config: any) {return {ENABLE_SMTP: enableSmtp,@@ -36,15 +42,6 @@ const SmtpForm = observer(() => {// const INITIAL_VALUES = generateInitialValues(authConfig.config)function checkSmtpState(config: any, resetForm: () => void) {- console.log(- config.SMTP_ADMIN_EMAIL,- config.SMTP_SENDER_NAME,- config.SMTP_USER,- config.SMTP_HOST,- config.SMTP_PASS,- config.SMTP_PORT,- config.SMTP_MAX_FREQUENCY- )if (config.SMTP_ADMIN_EMAIL &&config.SMTP_SENDER_NAME &&@@ -56,11 +53,11 @@ const SmtpForm = observer(() => {) {console.log('TRUE')setEnableSmtp(true)- resetForm()+ return resetForm} else {console.log('FALSE')setEnableSmtp(false)- resetForm()+ return resetForm}}@@ -174,10 +171,14 @@ const SmtpForm = observer(() => {message: `Updated settings`,})console.log('payload', payload)- resetForm({- values: !enableSmtp ? generateInitialValues(payload) : payload,- initialValues: generateInitialValues(payload),- })++ checkSmtpState(+ payload,+ resetForm({+ values: !enableSmtp ? generateInitialValues(payload) : payload,+ initialValues: generateInitialValues(payload),+ })+ )} catch (error) {ui.setNotification({category: 'error',@@ -216,7 +217,14 @@ const SmtpForm = observer(() => {footer={<div className="flex justify-between py-4 px-8"><FormActions- handleReset={handleReset}+ handleReset={() => {+ checkSmtpState(authConfig.config, () =>+ resetForm({+ values: generateInitialValues(authConfig.config),+ initialValues: generateInitialValues(authConfig.config),+ })+ )+ }}isSubmitting={isSubmitting}hasChanges={hasChanges}helper={'Learn more about global Auth settings'}@@ -231,9 +239,10 @@ const SmtpForm = observer(() => {size="small"label="Enable Custom SMTP"layout="flex"+ checked={enableSmtp}onChange={() => {resetForm({- values: values,+ values: generateInitialValues(authConfig.config),initialValues: generateInitialValues(authConfig.config),})setEnableSmtp(!enableSmtp)@@ -242,8 +251,9 @@ const SmtpForm = observer(() => {/></FormSectionContent></FormSection>- <div className="border-scale-400 border-t"></div>+<FormSection+ visible={enableSmtp}header={<FormSectionLabel>Sender details</FormSectionLabel>}disabled={!enableSmtp}>@@ -264,8 +274,9 @@ const SmtpForm = observer(() => {/></FormSectionContent></FormSection>- <div className="border-scale-400 border-t"></div>+<FormSection+ visible={enableSmtp}disabled={!enableSmtp}header={<FormSectionLabel>diff --git a/studio/components/interfaces/Auth/index.tsx b/studio/components/interfaces/Auth/index.tsxindex a8a7bdfbee1..acf40966d8e 100644--- a/studio/components/interfaces/Auth/index.tsx+++ b/studio/components/interfaces/Auth/index.tsx@@ -1,4 +1,5 @@import AuthProvidersForm from './AuthProvidersForm'import { SmtpForm } from './SmtpForm'+import { EmailTemplates } from './EmailTemplates'-export { AuthProvidersForm, SmtpForm }+export { AuthProvidersForm, SmtpForm, EmailTemplates }diff --git a/studio/components/ui/CodeEditor/CodeEditor.tsx b/studio/components/ui/CodeEditor/CodeEditor.tsxindex 06d1d68a30b..cffc6a5ccfa 100644--- a/studio/components/ui/CodeEditor/CodeEditor.tsx+++ b/studio/components/ui/CodeEditor/CodeEditor.tsx@@ -1,18 +1,22 @@import { FC, useEffect, useRef } from 'react'-import Editor from '@monaco-editor/react'+import Editor, { EditorProps } from '@monaco-editor/react'import { timeout } from 'lib/helpers'import Connecting from '../Loading'import { alignEditor } from './CodeEditor.utils'+import { merge } from 'lodash'interface Props {id: string- language: 'pgsql' | 'json'+ language: 'pgsql' | 'json' | 'html'defaultValue?: stringisReadOnly?: booleanonInputChange: (value?: string) => voidonInputRun?: (value: string) => voidhideLineNumbers?: boolean+ className?: string+ loading?: boolean+ options?: EditorProps['options']}const CodeEditor: FC<Props> = ({@@ -23,6 +27,9 @@ const CodeEditor: FC<Props> = ({hideLineNumbers = false,onInputChange = () => {},onInputRun = () => {},+ className,+ loading,+ options,}) => {const editorRef = useRef()@@ -53,27 +60,34 @@ const CodeEditor: FC<Props> = ({editorRef.current = editor}+ const optionsMerged = merge(+ {+ tabSize: 2,+ fontSize: 13,+ readOnly: isReadOnly,+ minimap: { enabled: false },+ wordWrap: 'on',+ fixedOverflowWidgets: true,+ contextmenu: true,+ lineNumbers: hideLineNumbers ? 'off' : undefined,+ glyphMargin: hideLineNumbers ? false : undefined,+ lineNumbersMinChars: hideLineNumbers ? 0 : undefined,+ folding: hideLineNumbers ? false : undefined,+ },+ options+ )++ merge({ cpp: '12' }, { java: '23' }, { python: '35' })+return (<Editorpath={id}theme="supabase"- className="monaco-editor"+ className={`monaco-editor ${className}`}defaultLanguage={language}defaultValue={defaultValue}- loading={<Connecting />}- options={{- tabSize: 2,- fontSize: 13,- readOnly: isReadOnly,- minimap: { enabled: false },- wordWrap: 'on',- fixedOverflowWidgets: true,- contextmenu: true,- lineNumbers: hideLineNumbers ? 'off' : undefined,- glyphMargin: hideLineNumbers ? false : undefined,- lineNumbersMinChars: hideLineNumbers ? 0 : undefined,- folding: hideLineNumbers ? false : undefined,- }}+ loading={loading || <Connecting />}+ options={optionsMerged}onMount={onMount}onChange={onInputChange}/>diff --git a/studio/components/ui/Forms/FormPanel.tsx b/studio/components/ui/Forms/FormPanel.tsxindex f168ef1dd7a..870676b1738 100644--- a/studio/components/ui/Forms/FormPanel.tsx+++ b/studio/components/ui/Forms/FormPanel.tsx@@ -13,7 +13,7 @@ const FormPanel = ({ children, header, footer }: Props) => (className="bg-scale-100dark:bg-scale-300- border-scale-400+ border-scale-400overflow-hiddenrounded-md border shadow">@@ -22,7 +22,7 @@ const FormPanel = ({ children, header, footer }: Props) => ({header}</div>)}- <div className="space-y-6 py-6">{children}</div>+ <div className="divide-scale-400 flex flex-col gap-0 divide-y">{children}</div>{footer && (<><div className="border-scale-400 border-t"></div>diff --git a/studio/components/ui/Forms/FormSection.tsx b/studio/components/ui/Forms/FormSection.tsxindex 5b4436d7dc4..9f112b470b7 100644--- a/studio/components/ui/Forms/FormSection.tsx+++ b/studio/components/ui/Forms/FormSection.tsx@@ -2,19 +2,24 @@ const FormSection = ({children,header,disabled,+ visible = true,+ className,}: {children: React.ReactNodeheader?: React.ReactNodedisabled?: boolean+ visible?: boolean+ className?: string}) => {- const classes = `- grid grid-cols-12 gap-6 px-8 py-2 lg:gap-12- transition-opacity- ${disabled ? 'opacity-30 pointer-events-none' : 'opacity-100'}- `+ const classes = [+ 'grid grid-cols-12 gap-6 px-8 py-8 lg:gap-12',+ `${disabled ? ' opacity-30' : ' opacity-100'}`,+ `${visible ? ' block' : ' hidden'}`,+ `${className}`,+ ]return (- <div className={classes}>+ <div className={classes.join(' ')}>{header}{children}</div>@@ -27,12 +32,22 @@ const FormSectionLabel = ({ children }: { children: React.ReactNode | string })const FormSectionContent = ({children,loading = true,+ fullWidth,+ className,}: {children: React.ReactNode | stringloading?: boolean+ fullWidth?: boolean+ className?: string}) => {return (- <div className="relative col-span-12 flex flex-col gap-6 lg:col-span-7">+ <div+ className={`+ relative col-span-12 flex flex-col gap-6 lg:col-span-7+ ${fullWidth && '!col-span-12'}+ ${className}+ `}+ >{loading ? (<div className="flex w-full flex-col gap-2"><div className="shimmering-loader h-2 w-1/3 rounded"></div>diff --git a/studio/components/ui/Forms/FormsContainer.tsx b/studio/components/ui/Forms/FormsContainer.tsxindex a8f5f3f00c9..be2c58e1eba 100644--- a/studio/components/ui/Forms/FormsContainer.tsx+++ b/studio/components/ui/Forms/FormsContainer.tsx@@ -1,5 +1,10 @@-function FormsContainer(props: { children: React.ReactNode }) {- return <div className="mx-auto max-w-4xl space-y-20 px-5 pt-12 pb-20">{props.children}</div>+function FormsContainer(props: { children: React.ReactNode; header?: string }) {+ return (+ <div className="mx-auto max-w-4xl px-5 pt-12 pb-20">+ {props.header && <h1 className="text-scale-1200 mb-8 text-3xl">{props.header}</h1>}+ <div className="space-y-20">{props.children}</div>+ </div>+ )}export { FormsContainer }diff --git a/studio/pages/project/[ref]/auth/templates-new.tsx b/studio/pages/project/[ref]/auth/templates-new.tsxindex 04f59cb4e46..6459554e8bc 100644--- a/studio/pages/project/[ref]/auth/templates-new.tsx+++ b/studio/pages/project/[ref]/auth/templates-new.tsx@@ -1,4 +1,4 @@-import { SmtpForm } from 'components/interfaces'+import { EmailTemplates, SmtpForm } from 'components/interfaces'import { AuthLayout } from 'components/layouts'import { FormsContainer } from 'components/ui/Forms'import { useStore } from 'hooks'@@ -16,8 +16,9 @@ const PageLayout: NextPageWithLayout = () => {if (authConfig) {return (- <FormsContainer>+ <FormsContainer header="Email"><SmtpForm />+ <EmailTemplates /></FormsContainer>)}diff --git a/studio/stores/authConfig/schema/AuthProviders/AuthTemplatesValidation.tsx b/studio/stores/authConfig/schema/AuthProviders/AuthTemplatesValidation.tsxnew file mode 100644index 00000000000..dba4447c81e--- /dev/null+++ b/studio/stores/authConfig/schema/AuthProviders/AuthTemplatesValidation.tsx@@ -0,0 +1,157 @@+import { FormSchema } from 'types'+import { boolean, number, object, string } from 'yup'++const JSON_SCHEMA_VERSION = 'http://json-schema.org/draft-07/schema#'++export const CONFIRMATION: FormSchema = {+ $schema: JSON_SCHEMA_VERSION,+ id: 'CONFIRMATION',+ type: 'object',+ title: 'Confirm signup',+ properties: {+ MAILER_SUBJECTS_CONFIRMATION: {+ title: 'Subject heading',+ type: 'string',+ },+ MAILER_TEMPLATES_CONFIRMATION_CONTENT: {+ title: 'Message',+ type: 'code',+ },+ },+ validationSchema: object().shape({+ MAILER_SUBJECTS_CONFIRMATION: string().required('"Subject heading is required.'),+ }),+ misc: {+ iconKey: 'email-icon2',+ helper: `To complete setup, add this authorisation callback URL to your app's configuration in the Apple Developer Console.+ [Learn more](https://supabase.com/docs/guides/auth/auth-apple#configure-your-services-id)`,+ },+}++export const INVITE: FormSchema = {+ $schema: JSON_SCHEMA_VERSION,+ id: 'INVITE',+ type: 'object',+ title: 'Invite user',+ properties: {+ MAILER_SUBJECTS_INVITE: {+ title: 'Subject heading',+ type: 'string',+ },+ MAILER_TEMPLATES_INVITE_CONTENT: {+ title: 'Message',+ type: 'code',+ },+ },+ validationSchema: object().shape({+ MAILER_SUBJECTS_INVITE: string().required('"Subject heading is required.'),+ }),+ misc: {+ iconKey: 'email-icon2',+ helper: `To complete setup, add this authorisation callback URL to your app's configuration in the Apple Developer Console.+ [Learn more](https://supabase.com/docs/guides/auth/auth-apple#configure-your-services-id)`,+ },+}++export const MAGIC_LINK: FormSchema = {+ $schema: JSON_SCHEMA_VERSION,+ id: 'MAGIC_LINK',+ type: 'object',+ title: 'Magic Link',+ properties: {+ MAILER_SUBJECTS_MAGIC_LINK: {+ title: 'Subject heading',+ type: 'string',+ },+ MAILER_TEMPLATES_MAGIC_LINK_CONTENT: {+ title: 'Message',+ type: 'code',+ },+ },+ validationSchema: object().shape({+ MAILER_SUBJECTS_MAGIC_LINK: string().required('"Subject heading is required.'),+ }),+ misc: {+ iconKey: 'email-icon2',+ helper: `To complete setup, add this authorisation callback URL to your app's configuration in the Apple Developer Console.+ [Learn more](https://supabase.com/docs/guides/auth/auth-apple#configure-your-services-id)`,+ },+}++export const EMAIL_CHANGE: FormSchema = {+ $schema: JSON_SCHEMA_VERSION,+ id: 'EMAIL_CHANGE',+ type: 'object',+ title: 'Change Email Address',+ properties: {+ MAILER_SUBJECTS_EMAIL_CHANGE: {+ title: 'Subject heading',+ type: 'string',+ },+ MAILER_TEMPLATES_EMAIL_CHANGE_CONTENT: {+ title: 'Message',+ type: 'code',+ },+ },+ validationSchema: object().shape({+ MAILER_SUBJECTS_EMAIL_CHANGE: string().required('"Subject heading is required.'),+ }),+ misc: {+ iconKey: 'email-icon2',+ helper: `To complete setup, add this authorisation callback URL to your app's configuration in the Apple Developer Console.+ [Learn more](https://supabase.com/docs/guides/auth/auth-apple#configure-your-services-id)`,+ },+}++export const RECOVERY: FormSchema = {+ $schema: JSON_SCHEMA_VERSION,+ id: 'RECOVERY',+ type: 'object',+ title: 'Reset Password',+ properties: {+ MAILER_SUBJECTS_RECOVERY: {+ title: 'Subject heading',+ type: 'string',+ },+ MAILER_TEMPLATES_RECOVERY_CONTENT: {+ title: 'Message',+ type: 'code',+ },+ },+ validationSchema: object().shape({+ MAILER_SUBJECTS_RECOVERY: string().required('"Subject heading is required.'),+ }),+ misc: {+ iconKey: 'email-icon2',+ helper: `To complete setup, add this authorisation callback URL to your app's configuration in the Apple Developer Console.+ [Learn more](https://supabase.com/docs/guides/auth/auth-apple#configure-your-services-id)`,+ },+}++export const SMS: FormSchema = {+ $schema: JSON_SCHEMA_VERSION,+ id: 'SMS',+ type: 'object',+ title: 'SMS Message',+ properties: {+ SMS_VONAGE_FROM: {+ title: 'Subject heading',+ type: 'string',+ },+ SMS_TEMPLATE: {+ title: 'Message',+ type: 'string',+ },+ },+ validationSchema: object().shape({+ SMS_VONAGE_FROM: string().required('"Subject heading is required.'),+ SMS_TEMPLATE: string().required('"SMS template is required.'),+ }),+ misc: {+ iconKey: 'email-icon2',+ helper: `To complete setup, add this authorisation callback URL to your app's configuration in the Apple Developer Console.+ [Learn more](https://supabase.com/docs/guides/auth/auth-apple#configure-your-services-id)`,+ },+}++export const TEMPLATES_SCHEMAS = [CONFIRMATION, INVITE, MAGIC_LINK, EMAIL_CHANGE, RECOVERY, SMS]diff --git a/studio/stores/authConfig/schema/index.ts b/studio/stores/authConfig/schema/index.tsindex e9b8d674cb5..05aa9d8f6c5 100644--- a/studio/stores/authConfig/schema/index.ts+++ b/studio/stores/authConfig/schema/index.ts@@ -1 +1,2 @@export { PROVIDERS_SCHEMAS } from './AuthProviders/AuthProvidersFormValidation'+export { TEMPLATES_SCHEMAS } from './AuthProviders/AuthTemplatesValidation'diff --git a/studio/types/form.ts b/studio/types/form.tsnew file mode 100644index 00000000000..061b8a7105c--- /dev/null+++ b/studio/types/form.ts@@ -0,0 +1,35 @@+interface Enum {+ label: string+ value: string+ icon: string+}++export interface FormSchema {+ $schema: string+ id?: string+ type: 'object'+ title: string+ properties: {+ [x: string]: {+ title: string+ type: 'boolean' | 'string' | 'select' | 'number' | 'code'+ description?: string+ descriptionOptional?: string+ enum?: Enum[]+ show?: {+ key: string+ matches: string+ }+ }+ }+ validationSchema: any // todo: use Yup type+ misc?: {+ iconKey?: string+ requiresRedirect?: true+ helper?: string+ alert?: {+ title?: string+ description?: string+ }+ }+}diff --git a/studio/types/index.ts b/studio/types/index.tsindex 29bd20bcbc3..2b216043452 100644--- a/studio/types/index.ts+++ b/studio/types/index.ts@@ -2,3 +2,4 @@ export * from './base'export * from './ui'export * from './userContent'export * from './next'+export * from './form'