Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Add onSubmit config for React #193

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
5 changes: 5 additions & 0 deletions .changeset/tall-dolphins-laugh.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@flatfile/react': patch
---

Fix bug with Workbook onSubmit
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,5 @@ dist
.flatfile
.flatfilerc.json

*.code-workspace
*.code-workspace
.aider*
9 changes: 7 additions & 2 deletions apps/react/app/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,13 @@ const App = () => {
record.set('email', 'SHEET 3 RECORDHOOK')
return record
}}
onSubmit={async (sheet) => {
console.log('onSubmit from Sheet 3', { sheet })
onSubmit={{
handler: async (sheet) => {
console.log('onSubmit from Sheet 3', { sheet })
},
config: {
label: 'Sheet 3 Submit',
},
}}
/>
<Sheet
Expand Down
23 changes: 23 additions & 0 deletions apps/react/app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "react-example",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"example:reuse-space": "next dev"
},
"dependencies": {
"@flatfile/react": "^7.3.1",
"next": "^13.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "^18.11.7",
"@types/react": "^18.0.24",
"typescript": "^4.8.4"
}
}
43 changes: 43 additions & 0 deletions apps/react/app/reuse-space-example/ReusableSpaceExample.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import React, { useState } from 'react'
import { useSpace } from '@flatfile/react'

const ReusableSpaceExample: React.FC = () => {
const [spaceId, setSpaceId] = useState<string | null>(null)
const { space, loading, error } = useSpace({
name: 'Reusable Space Example',
publishableKey: 'YOUR_PUBLISHABLE_KEY',
environmentId: 'YOUR_ENVIRONMENT_ID',
spaceId: spaceId,
})

const handleCreateSpace = async () => {
if (space) {
const newSpace = await space.create()
setSpaceId(newSpace.id)
}
}

const handleOpenSpace = () => {
if (space) {
space.open()
}
}

if (loading) return <div>Loading...</div>
if (error) return <div>Error: {error.message}</div>

return (
<div>
<h1>Reusable Space Example</h1>
<button onClick={handleCreateSpace} disabled={!!spaceId}>
Create Space
</button>
<button onClick={handleOpenSpace} disabled={!spaceId}>
Open Space
</button>
{spaceId && <p>Space ID: {spaceId}</p>}
</div>
)
}

export default ReusableSpaceExample
3 changes: 3 additions & 0 deletions apps/react/app/reuse-space-example/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import ReusableSpaceExample from './ReusableSpaceExample'

export default ReusableSpaceExample
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"format": "prettier --ignore-path .gitignore --write \"**/*.{js,jsx,ts,tsx,md}\"",
"changeset": "changeset",
"changeset-apply": "changeset version",
"release": "turbo run build && changeset publish"
"release": "turbo run build && changeset publish",
"example:reuse-space": "npm run example:reuse-space -w apps/react/app"
},
"devDependencies": {
"@changesets/cli": "^2.23.0",
Expand Down
5 changes: 4 additions & 1 deletion packages/react/src/components/FlatfileProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export const FlatfileProvider: React.FC<ExclusiveFlatfileProviderProps> = ({
const [internalAccessToken, setInternalAccessToken] = useState<
string | undefined | null
>(accessToken)

const [listener, setListener] = useState(new FlatfileListener())
const [open, setOpen] = useState<boolean>(false)
const [sessionSpace, setSessionSpace] = useState<
Expand Down Expand Up @@ -166,7 +167,9 @@ export const FlatfileProvider: React.FC<ExclusiveFlatfileProviderProps> = ({
defaultPage.current = undefined
}

const sheetWorkbookAction = workbookOnSubmitAction(sheetToRemove.slug)
const sheetWorkbookAction = workbookOnSubmitAction({
sheetSlug: sheetToRemove.slug,
})

const updatedWorkbookActions = prevSpace.workbook?.actions?.filter(
(action) => action.operation !== sheetWorkbookAction.operation
Expand Down
30 changes: 21 additions & 9 deletions packages/react/src/components/Sheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ import { useEvent, usePlugin } from '../hooks'
import { OnSubmitAction, workbookOnSubmitAction } from '../utils/constants'
import { useDeepCompareEffect } from '../utils/useDeepCompareEffect'
import FlatfileContext from './FlatfileContext'
import { OnSubmitActionWithConfig } from './Workbook'

type SheetProps = {
config: Flatfile.SheetConfig
onSubmit?: SimpleOnboarding['onSubmit']
onSubmit?: SimpleOnboarding['onSubmit'] | OnSubmitActionWithConfig
submitSettings?: SimpleOnboarding['submitSettings']
onRecordHook?: SimpleOnboarding['onRecordHook']
defaultPage?: boolean
Expand Down Expand Up @@ -68,16 +69,20 @@ export const Sheet: React.FC<SheetProps> = (props: SheetProps) => {
const { addSheet, updateWorkbook, createSpace, setDefaultPage, removeSheet } =
useContext(FlatfileContext)
const sheetRef = useRef<Flatfile.SheetConfig>()

useDeepCompareEffect(() => {
const updateSheetConfig = () => {
sheetRef.current = config
if (onSubmit && !createSpace.workbook?.actions?.some(
(action: Flatfile.Action) =>
action.operation === workbookOnSubmitAction(config.slug).operation
)) {
if (
onSubmit &&
!createSpace.workbook?.actions?.some(
(action: Flatfile.Action) =>
action.operation ===
workbookOnSubmitAction({ sheetSlug: config.slug, config: 'config' in onSubmit ? onSubmit.config : undefined }).operation
)
) {
updateWorkbook({
actions: [workbookOnSubmitAction(config.slug)],
actions: [workbookOnSubmitAction({ sheetSlug: config.slug, config: 'config' in onSubmit ? onSubmit.config : undefined })],
})
}
addSheet(config)
Expand All @@ -90,7 +95,10 @@ export const Sheet: React.FC<SheetProps> = (props: SheetProps) => {
}
}

if (!sheetRef.current || (sheetRef.current.slug && sheetRef.current.slug !== config.slug)) {
if (
!sheetRef.current ||
(sheetRef.current.slug && sheetRef.current.slug !== config.slug)
) {
if (sheetRef.current?.slug) {
removeSheet(sheetRef.current.slug)
}
Expand Down Expand Up @@ -120,7 +128,11 @@ export const Sheet: React.FC<SheetProps> = (props: SheetProps) => {

useEvent(
'job:ready',
{ job: `workbook:${workbookOnSubmitAction(config.slug).operation}` },
{
job: `workbook:${
workbookOnSubmitAction({ sheetSlug: config.slug }).operation
}`,
},
onSubmit
? OnSubmitAction(onSubmit, {
...DefaultSubmitSettings,
Expand Down
40 changes: 30 additions & 10 deletions packages/react/src/components/Workbook.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,14 @@ type HookConfig<T> = [string, onRecordHook<T>] | [onRecordHook<T>]

export type onRecordHooks<T> = HookConfig<T>[]

export type OnSubmitActionWithConfig = {
handler: SimpleOnboarding['onSubmit']
config: Partial<Flatfile.Action>
}

type WorkbookProps = Partial<{
config: Flatfile.CreateWorkbookConfig
onSubmit: SimpleOnboarding['onSubmit']
onSubmit: SimpleOnboarding['onSubmit'] | OnSubmitActionWithConfig
submitSettings: SimpleOnboarding['submitSettings']
onRecordHooks: onRecordHooks<FlatfileRecord<TRecordDataWithLinks<TPrimitive>>>
children: React.ReactNode
Expand Down Expand Up @@ -72,15 +77,24 @@ export const Workbook = (props: WorkbookProps) => {
// Accept a workbook onSubmit function and add it to the workbook actions

useDeepCompareEffect(() => {
// adds workbook action if onSubmit is passed along
updateWorkbook(
const submitAction = workbookOnSubmitAction()
const existingActions = createSpace.workbook?.actions || []

let updatedActions = [...existingActions, ...(config?.actions || [])]

if (
!updatedActions.some(
(action) => action.operation === submitAction.operation
) &&
onSubmit
? {
...config,
actions: [workbookOnSubmitAction(), ...(config?.actions || [])],
}
: config
)
) {
updatedActions = [submitAction, ...updatedActions]
}

updateWorkbook({
...config,
actions: updatedActions.length > 0 ? updatedActions : undefined,
})
}, [config])

usePlugin(
Expand Down Expand Up @@ -117,7 +131,13 @@ export const Workbook = (props: WorkbookProps) => {

useEvent(
'job:ready',
{ job: `workbook:${workbookOnSubmitAction().operation}` },
{
job: `workbook:${
workbookOnSubmitAction(
onSubmit && 'config' in onSubmit ? { config: onSubmit.config } : {}
).operation
}`,
},
onSubmit
? OnSubmitAction(onSubmit, {
...DefaultSubmitSettings,
Expand Down
18 changes: 15 additions & 3 deletions packages/react/src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,15 @@ import {
SimpleOnboarding,
} from '@flatfile/embedded-utils'
import { FlatfileEvent } from '@flatfile/listener'
import { OnSubmitActionWithConfig } from '../components'

export const workbookOnSubmitAction = (sheetSlug?: string): Flatfile.Action => {
export const workbookOnSubmitAction = ({
sheetSlug,
config,
}: {
sheetSlug?: string
config?: Partial<Flatfile.Action>
} = {}): Flatfile.Action => {
const operation = sheetSlug
? `sheetSubmitAction-${sheetSlug}`
: 'workbookSubmitAction'
Expand All @@ -16,11 +23,12 @@ export const workbookOnSubmitAction = (sheetSlug?: string): Flatfile.Action => {
label: 'Submit',
description: 'Action for handling data inside of onSubmit',
primary: true,
...config,
}
}

export const OnSubmitAction = (
onSubmit: SimpleOnboarding['onSubmit'],
onSubmit: SimpleOnboarding['onSubmit'] | OnSubmitActionWithConfig,
onSubmitSettings: SimpleOnboarding['submitSettings']
) => {
return async (event: FlatfileEvent) => {
Expand All @@ -41,7 +49,11 @@ export const OnSubmitAction = (
const sheet = new SheetHandler(workbookSheets[0].id)

if (onSubmit) {
await onSubmit({ job, sheet, event })
if (typeof onSubmit === 'function') {
await onSubmit({ job, sheet, event })
} else if (typeof onSubmit.handler === 'function') {
await onSubmit.handler({ job, sheet, event })
}
}

await FlatfileAPI.jobs.complete(jobId, {
Expand Down