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

add timeline view #4965

Merged
merged 9 commits into from
Oct 25, 2024
Merged

add timeline view #4965

merged 9 commits into from
Oct 25, 2024

Conversation

ritch
Copy link
Contributor

@ritch ritch commented Oct 22, 2024

What changes are proposed in this pull request?

Adds a new foo.types.TimelineView() for building custom animation.

How is this patch tested? If it is not, please explain why.

With the AnimatedExample panel.

Summary by CodeRabbit

  • New Features
    • Introduced the TimelineView component for rendering timelines based on provided schemas.
    • Added TimelineCreator component to initialize and display timelines with dynamic configurations.
  • Improvements
    • Enhanced event handling in the PlotlyView component for better interaction responses.
    • Optimized performance with memoization of configuration settings in PlotlyView.
    • Streamlined frame data handling and error management in the FrameLoaderView component.
  • Bug Fixes
    • Refined logic for handling selected points and event properties in the PlotlyView.
  • Chores
    • Reinstated exports for ModalView and TextView components in the index file.

Copy link
Contributor

coderabbitai bot commented Oct 22, 2024

Walkthrough

The changes involve modifications to the PlotlyView component, the introduction of a new TimelineView component, and updates to related files. The PlotlyView has enhanced event handling and performance optimizations, while TimelineView provides a new way to render timelines based on a schema. Additionally, a new class TimelineView has been added to manage timeline animations. These changes collectively improve the functionality and responsiveness of the components involved.

Changes

File Path Change Summary
app/packages/core/src/plugins/SchemaIO/components/PlotlyView.tsx - Removed useResizeHandler prop from Box component.
- Updated handleEvent function for better event handling.
- Modified createPlotlyHandlers for broader event support.
- Defined dataDefaults, layoutDefaults, and configDefaults using useMemo.
- Adjusted useEffect for smoother state updates.
app/packages/core/src/plugins/SchemaIO/components/TimelineView.tsx - Introduced TimelineView component to render timelines based on schema.
- Added TimelineCreator functional component for timeline initialization.
app/packages/core/src/plugins/SchemaIO/components/index.ts - Added export for TimelineView component.
- Reinstated exports for ModalView and TextView.
fiftyone/operators/types.py - Introduced new TimelineView class extending View for timeline management.
app/packages/core/src/plugins/SchemaIO/components/FrameLoaderView.tsx - Added frameDataRef to store frames data.
- Updated useEffect and loadRange for improved frame data handling.

Possibly related PRs

Suggested labels

app, bug

Suggested reviewers

  • imanjra
  • Br2850

Poem

In fields of data, we hop and play,
With Plotly and timelines, bright as day.
Events now dance, and frames align,
A joyful code, where rabbits dine! 🐇✨
Let's celebrate changes, both big and small,
In the world of schemas, we cherish them all!


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6f53f9a and 9c83376.

📒 Files selected for processing (1)
  • app/packages/core/src/plugins/SchemaIO/components/index.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/packages/core/src/plugins/SchemaIO/components/index.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 866c8c6 and 991398c.

📒 Files selected for processing (4)
  • app/packages/core/src/plugins/SchemaIO/components/PlotlyView.tsx (0 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/TimelineView.tsx (1 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/index.ts (1 hunks)
  • fiftyone/operators/types.py (1 hunks)
💤 Files with no reviewable changes (1)
  • app/packages/core/src/plugins/SchemaIO/components/PlotlyView.tsx
🧰 Additional context used
📓 Path-based instructions (2)
app/packages/core/src/plugins/SchemaIO/components/TimelineView.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/plugins/SchemaIO/components/index.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

🔇 Additional comments (2)
app/packages/core/src/plugins/SchemaIO/components/TimelineView.tsx (1)

1-4: LGTM! Clean imports following best practices.

app/packages/core/src/plugins/SchemaIO/components/index.ts (1)

52-52: LGTM! The export follows established patterns.

The new TimelineView export maintains consistency with existing exports and follows proper alphabetical ordering.

Let's verify the TimelineView component exists:

✅ Verification successful

TimelineView component exists and follows React patterns

The verification confirms:

  • TimelineView.tsx exists in the correct directory
  • The component is properly implemented as a React functional component
  • It follows the expected patterns with proper props handling and configuration management

The export in the barrel file is correctly referencing an existing and well-structured component.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify TimelineView component exists and follows React patterns
# Expected: Find the TimelineView.tsx file in the same directory

fd -t f "TimelineView.tsx" "app/packages/core/src/plugins/SchemaIO/components"

# Also verify the component implementation
ast-grep --pattern 'export default function TimelineView($_) {
  $$$
}'

Length of output: 2846

Comment on lines 23 to 29
const requiredParams = ["timeline_name", "total_frames"];

// for (const param of requiredParams) {
// if (!finalConfig[param]) {
// throw new Error(`Missing required parameter: ${param}`);
// }
// }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Implement or remove commented validation code

The commented validation code seems important for ensuring required parameters are present. Either implement it properly or remove it if not needed. Consider using TypeScript's type system for validation instead.

-  const requiredParams = ["timeline_name", "total_frames"];
-
-  // for (const param of requiredParams) {
-  //   if (!finalConfig[param]) {
-  //     throw new Error(`Missing required parameter: ${param}`);
-  //   }
-  // }
+  if (!timeline_name || !total_frames) {
+    throw new Error('Missing required parameters: timeline_name and total_frames are required');
+  }

Committable suggestion was skipped due to low confidence.

Comment on lines 34 to 48
export const TimelineCreator = ({ timelineName, totalFrames, loop }) => {
const { isTimelineInitialized } = useCreateTimeline({
name: timelineName,
config: {
totalFrames: totalFrames,
loop,
},
});

if (!isTimelineInitialized) {
return <div>initializing timeline...</div>;
}

return <Timeline name={timelineName} />;
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance TimelineCreator component robustness and performance

Consider the following improvements:

  1. Add error handling for timeline initialization failures
  2. Improve loading state feedback
  3. Optimize performance with useMemo
- export const TimelineCreator = ({ timelineName, totalFrames, loop }) => {
+ export const TimelineCreator = React.memo(({ timelineName, totalFrames, loop }) => {
-   const { isTimelineInitialized } = useCreateTimeline({
+   const { isTimelineInitialized, error } = useCreateTimeline({
      name: timelineName,
      config: {
        totalFrames: totalFrames,
        loop,
      },
    });

+   if (error) {
+     return <div>Error initializing timeline: {error.message}</div>;
+   }

    if (!isTimelineInitialized) {
-     return <div>initializing timeline...</div>;
+     return <div>Initializing timeline for {timelineName}...</div>;
    }

    return <Timeline name={timelineName} />;
- };
+ });

Committable suggestion was skipped due to low confidence.

fiftyone/operators/types.py Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (1)
app/packages/core/src/plugins/SchemaIO/components/FrameLoaderView.tsx (1)

Line range hint 1-99: Consider using React state management instead of custom events.

The current implementation uses custom DOM events for communication between components. This approach:

  1. Makes the component tightly coupled to the browser's event system
  2. Makes testing more difficult
  3. Could lead to memory leaks if not properly cleaned up

Consider using React's built-in state management (Context, useState) or state management libraries (Recoil, as mentioned in guidelines) for better maintainability and testability.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 991398c and 46461f9.

📒 Files selected for processing (2)
  • app/packages/core/src/plugins/SchemaIO/components/FrameLoaderView.tsx (2 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/TimelineView.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
app/packages/core/src/plugins/SchemaIO/components/FrameLoaderView.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/plugins/SchemaIO/components/TimelineView.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

🔇 Additional comments (2)
app/packages/core/src/plugins/SchemaIO/components/TimelineView.tsx (2)

5-31: Good implementation of TimelineView component

The TimelineView component correctly extracts and validates the required parameters, and passes the appropriate configuration to TimelineCreator.


37-37: ⚠️ Potential issue

Fix reference to undefined variable 'total_frames'

The variable total_frames is not defined in the scope of TimelineCreator. You should use totalFrames instead.

Apply this diff to fix the error:

-          totalFrames: total_frames,
+          totalFrames: totalFrames,

Likely invalid or redundant comment.

Copy link
Contributor

@sashankaryal sashankaryal left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looking good, request few changes

ritch and others added 3 commits October 23, 2024 12:16
…iew.tsx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
….tsx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@sashankaryal
Copy link
Contributor

lgtm! needs merge conflict resolved

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (1)
fiftyone/operators/types.py (1)

2577-2589: Consider adding timeline-specific functionality.

The timeline implementation could benefit from additional timeline-specific features:

  1. Frame rate control and synchronization
  2. Timeline markers for key events/frames
  3. Timeline segments for grouping frames
  4. Export/import timeline configurations

Example timeline configuration structure:

def __init__(self, **kwargs):
    super().__init__(**kwargs)
    self.timeline_name = kwargs.get("timeline_name", None)
    self.total_frames = kwargs.get("total_frames", None)
    self.loop = kwargs.get("loop", False)
    self.fps = kwargs.get("fps", 30)
    self.markers = kwargs.get("markers", {})
    self.segments = kwargs.get("segments", [])
    
def add_marker(self, frame, label):
    """Add a marker at a specific frame."""
    self.markers[frame] = label

def add_segment(self, start_frame, end_frame, name):
    """Add a named segment of frames."""
    self.segments.append({
        "name": name,
        "start": start_frame,
        "end": end_frame
    })
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9190e63 and 6f53f9a.

📒 Files selected for processing (4)
  • app/packages/core/src/plugins/SchemaIO/components/FrameLoaderView.tsx (3 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/TimelineView.tsx (1 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/index.ts (1 hunks)
  • fiftyone/operators/types.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/packages/core/src/plugins/SchemaIO/components/index.ts
🧰 Additional context used
📓 Path-based instructions (2)
app/packages/core/src/plugins/SchemaIO/components/FrameLoaderView.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/plugins/SchemaIO/components/TimelineView.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

🔇 Additional comments (2)
app/packages/core/src/plugins/SchemaIO/components/FrameLoaderView.tsx (1)

10-11: LGTM! Good improvements to code maintainability.

The addition of the FRAME_LOADED_EVENT constant and properly typed frameDataRef enhances code maintainability and type safety.

Also applies to: 21-21

fiftyone/operators/types.py (1)

2577-2589: Past review comment is still applicable.

The implementation issues identified in the previous review remain unaddressed.

Comment on lines +38 to +40
if (!isTimelineInitialized) {
return null;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance loading state feedback

Returning null during initialization provides no feedback to users. Consider showing a loading indicator or message.

   if (!isTimelineInitialized) {
-    return null;
+    return <div aria-busy="true" role="status">Initializing timeline...</div>;
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!isTimelineInitialized) {
return null;
}
if (!isTimelineInitialized) {
return <div aria-busy="true" role="status">Initializing timeline...</div>;
}

Comment on lines +25 to +30
if (data?.frames) frameDataRef.current = data.frames;
window.dispatchEvent(
new CustomEvent(FRAME_LOADED_EVENT, {
detail: { localId: localIdRef.current },
})
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add missing dependency and cleanup to useEffect.

The effect should include data.frames in its dependency array and implement a cleanup function.

Apply this diff:

 useEffect(() => {
   localIdRef.current = Math.random().toString(36).substring(7);
   if (data?.frames) frameDataRef.current = data.frames;
   window.dispatchEvent(
     new CustomEvent(FRAME_LOADED_EVENT, {
       detail: { localId: localIdRef.current },
     })
   );
+  return () => {
+    frameDataRef.current = null;
+  };
-}, [data?.signature]);
+}, [data?.signature, data?.frames]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (data?.frames) frameDataRef.current = data.frames;
window.dispatchEvent(
new CustomEvent(FRAME_LOADED_EVENT, {
detail: { localId: localIdRef.current },
})
);
useEffect(() => {
localIdRef.current = Math.random().toString(36).substring(7);
if (data?.frames) frameDataRef.current = data.frames;
window.dispatchEvent(
new CustomEvent(FRAME_LOADED_EVENT, {
detail: { localId: localIdRef.current },
})
);
return () => {
frameDataRef.current = null;
};
}, [data?.signature, data?.frames]);

Comment on lines +47 to +62
if (frameDataRef.current) {
bufm.current.addNewRange(range);
resolve();
} else {
const onFramesLoaded = (e) => {
if (
e instanceof CustomEvent &&
e.detail.localId === localIdRef.current
) {
window.removeEventListener(FRAME_LOADED_EVENT, onFramesLoaded);
bufm.current.addNewRange(range);
resolve();
}
};
window.addEventListener(FRAME_LOADED_EVENT, onFramesLoaded);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve event listener typing and cleanup pattern.

While the event listener cleanup is implemented, there are opportunities for improvement in typing and pattern usage.

Apply this diff for better type safety and a more robust cleanup pattern:

 if (frameDataRef.current) {
   bufm.current.addNewRange(range);
   resolve();
 } else {
-  const onFramesLoaded = (e) => {
+  const onFramesLoaded = (e: CustomEvent<{ localId: string }>) => {
+    if (e.detail.localId !== localIdRef.current) return;
+    
+    window.removeEventListener(FRAME_LOADED_EVENT, onFramesLoaded as EventListener);
+    bufm.current.addNewRange(range);
+    resolve();
+  };
-    if (
-      e instanceof CustomEvent &&
-      e.detail.localId === localIdRef.current
-    ) {
-      window.removeEventListener(FRAME_LOADED_EVENT, onFramesLoaded);
-      bufm.current.addNewRange(range);
-      resolve();
-    }
-  };
   window.addEventListener(FRAME_LOADED_EVENT, onFramesLoaded as EventListener);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (frameDataRef.current) {
bufm.current.addNewRange(range);
resolve();
} else {
const onFramesLoaded = (e) => {
if (
e instanceof CustomEvent &&
e.detail.localId === localIdRef.current
) {
window.removeEventListener(FRAME_LOADED_EVENT, onFramesLoaded);
bufm.current.addNewRange(range);
resolve();
}
};
window.addEventListener(FRAME_LOADED_EVENT, onFramesLoaded);
}
if (frameDataRef.current) {
bufm.current.addNewRange(range);
resolve();
} else {
const onFramesLoaded = (e: CustomEvent<{ localId: string }>) => {
if (e.detail.localId !== localIdRef.current) return;
window.removeEventListener(FRAME_LOADED_EVENT, onFramesLoaded as EventListener);
bufm.current.addNewRange(range);
resolve();
};
window.addEventListener(FRAME_LOADED_EVENT, onFramesLoaded as EventListener);
}

@brimoor brimoor merged commit d44e464 into develop Oct 25, 2024
11 of 13 checks passed
@brimoor brimoor deleted the feat-timeline-op-type branch October 25, 2024 03:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants