FlatFilers / flatfile-core-libraries

MIT License
0 stars 2 forks source link

fix: Re-Attach Listener After AccessToken Updates #166

Closed bangarang closed 3 months ago

bangarang commented 3 months ago

Fixes a bug that doesn't re-attach linked listener code when changes to the Browser Driver happen. This happens when the accessToken is set after Space creation, so can cause a state where the listener is not attached to the client instance initially if it is not set inline.

Example of test:

'use client'
import { workbook } from '@/utils/workbook'
import FlatfileListener from '@flatfile/listener'
import { recordHook } from '@flatfile/plugin-record-hook'
import {
  FlatfileProvider,
  Sheet,
  Space,
  useFlatfile,
  useListener
} from '@flatfile/react'
import { useMemo, useState } from 'react'
import styles from './page.module.css'

export const AppWrapper = ({
  PUBLISHABLE_KEY,
}: {
  PUBLISHABLE_KEY: string
}) => {
  const [listenerVersion, setListenerVersion] = useState<number>(0)

  const contactsRecordHooks = [
    (client: FlatfileListener) => {
      client.use(
        recordHook('contacts', (record) => {
          record.set('lastName', 'Listener 1')
          return record
        })
      )
    },
    (client: FlatfileListener) => {
      client.use(
        recordHook('contacts', (record) => {
          record.set('lastName', 'Listener 2')
          return record
        })
      )
    },
    (client: FlatfileListener) => {
      client.use(
        recordHook('contacts', (record) => {
          record.set('lastName', 'Listener 3')
          return record
        })
      )
    },
  ]

  const selectedListener = useMemo(() => {
    return (client: FlatfileListener) => {
      contactsRecordHooks[listenerVersion](client)
    }
  }, [listenerVersion])

  return (
    <FlatfileProvider publishableKey={PUBLISHABLE_KEY}>
      <select
        value={listenerVersion}
        onChange={(e) => setListenerVersion(Number(e.target.value))}
        style={{ marginBottom: '10px' }}
      >
        <option value={0}>Listener 1</option>
        <option value={1}>Listener 2</option>
        <option value={2}>Listener 3</option>
      </select>
      <App selectedListener={selectedListener} />
    </FlatfileProvider>
  )
}

export const App = ({
  selectedListener,
}: {
  selectedListener: (cb: FlatfileListener) => void
}) => {
  const { openPortal } = useFlatfile()

  useListener(selectedListener, [selectedListener])

  return (
    <div className={styles.main}>
      <button onClick={openPortal}>Open Portal</button>
      <Space
        config={{
          name: 'Test Space',
          metadata: {
            sidebarConfig: {
              showSidebar: true,
            },
          },
        }}
      >
        <Sheet
          config={{
            ...workbook.sheets![0],
            slug: 'contacts',
            name: 'Contacts',
          }}
        />
      </Space>
    </div>
  )
}

export default function Home() {
  const PUBLISHABLE_KEY = process.env.NEXT_PUBLIC_FLATFILE_PUBLISHABLE_KEY
  if (!PUBLISHABLE_KEY) return <>No Publishable Key Available</>

  return <AppWrapper PUBLISHABLE_KEY={PUBLISHABLE_KEY} />
}
coderabbitai[bot] commented 3 months ago

Walkthrough

The recent updates enhance the @flatfile/react package by improving event listener management and integrating an accessToken feature across several hooks. The useEvent, useListener, and usePlugin functions now utilize the accessToken from FlatfileContext, ensuring that event handling and plugin functionalities are more responsive and context-aware. These changes aim to provide a more robust user experience by optimizing the flow of event listeners and maintaining synchronization with the context state.

Changes

Files Change Summary
.changeset/fast-peaches-return.md Introduced a patch to improve flexibility in adding/modifying listeners in @flatfile/react, enhancing component interactivity.
packages/react/src/hooks/useEvent.ts, packages/react/src/hooks/useListener.ts, packages/react/src/hooks/usePlugin.ts Added accessToken to context in all hooks, updating useEffect to improve event handling and ensure synchronization with context changes.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant C as FlatfileContext
    participant E as Event System

    U->>C: Request access token
    C-->>U: Provide access token
    U->>E: Register event listener with access token
    E->>E: Validate listener and access token
    E-->>U: Listen for events
    U->>E: Trigger event
    E->>U: Notify event execution

Recent review details **Configuration used: CodeRabbit UI** **Review profile: CHILL**
Commits Files that changed from the base of the PR and between d9149d363489c1246b9ece20cdee81884f194641 and bbe8ff994cb5fb61ba5e785510d45657e08221bd.
Files selected for processing (1) * .changeset/fast-peaches-return.md (1 hunks)
Files skipped from review as they are similar to previous changes (1) * .changeset/fast-peaches-return.md
---
Tips ### Chat There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai): - Review comments: Directly reply to a review comment made by CodeRabbit. Example: - `I pushed a fix in commit .` - `Generate unit testing code for this file.` - `Open a follow-up GitHub issue for this discussion.` - Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples: - `@coderabbitai generate unit testing code for this file.` - `@coderabbitai modularize this function.` - PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples: - `@coderabbitai generate interesting stats about this repository and render them as a table.` - `@coderabbitai show all the console.log statements in this repository.` - `@coderabbitai read src/utils.ts and generate unit testing code.` - `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.` - `@coderabbitai help me debug CodeRabbit configuration file.` Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. ### CodeRabbit Commands (invoked as PR comments) - `@coderabbitai pause` to pause the reviews on a PR. - `@coderabbitai resume` to resume the paused reviews. - `@coderabbitai review` to trigger an incremental review. This is useful when automatic reviews are disabled for the repository. - `@coderabbitai full review` to do a full review from scratch and review all the files again. - `@coderabbitai summary` to regenerate the summary of the PR. - `@coderabbitai resolve` resolve all the CodeRabbit review comments. - `@coderabbitai configuration` to show the current CodeRabbit configuration for the repository. - `@coderabbitai help` to get help. Additionally, you can add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed. ### CodeRabbit Configuration File (`.coderabbit.yaml`) - You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository. - Please see the [configuration documentation](https://docs.coderabbit.ai/guides/configure-coderabbit) for more information. - If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json` ### Documentation and Community - Visit our [Documentation](https://coderabbit.ai/docs) for detailed information on how to use CodeRabbit. - Join our [Discord Community](https://discord.com/invite/GsXnASn26c) to get help, request features, and share feedback. - Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.