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

[WEB-4087] - New Examples index page with filtering & search #2347

Draft
wants to merge 7 commits into
base: web-4082-docs-nav-redesign
Choose a base branch
from

Conversation

aralovelace
Copy link
Contributor

@aralovelace aralovelace commented Dec 17, 2024

Description

A PR description indicating the purpose of the PR.

WEB-4087

Review

Instructions on how to review the PR.

Summary by CodeRabbit

  • New Features

    • Introduced new components: ExamplesCheckbox, ExamplesContent, ExamplesFilter, ExamplesGrid, ExamplesNoResults.
    • Added functionality for filtering examples based on products and use cases.
    • Enhanced the user interface with styled checkboxes and a grid layout for displaying examples.
    • Implemented a search feature to dynamically filter displayed examples.
  • Bug Fixes

    • Updated the @ably/ui package dependency for improved performance and stability.
  • Documentation

    • Added interfaces for Example and Examples to define data structures.
  • Style

    • Introduced new CSS rules for styling disabled checkboxes.

Copy link

coderabbitai bot commented Dec 17, 2024

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces a comprehensive implementation of an Examples page with advanced filtering and search capabilities. The changes include creating multiple React components for rendering examples, implementing a dynamic filtering mechanism, and adding supporting data structures. The new implementation allows users to filter examples by products, use cases, and search terms, providing a flexible and interactive way to explore different code examples.

Changes

File Change Summary
package.json Updated @ably/ui dependency from ^15.1.0 to ^15.1.9
src/components/Examples/... Added new components: ExamplesCheckbox, ExamplesContent, ExamplesFilter, ExamplesGrid, ExamplesNoResults
src/components/Examples/examples-checkbox.css Added CSS rules for styling disabled checkbox inputs
src/components/Examples/filter-search-examples.ts Added utility function for filtering examples
src/components/Image.tsx Added optional name property to ImageProps type
src/data/examples.ts Defined interfaces and data for examples and use cases
src/pages/examples.tsx Created new Examples page component with GraphQL query

Assessment against linked issues

Objective Addressed Explanation
Implement Examples index page
Add filtering by products
Add filtering by use cases
Implement search functionality

Poem

🐰 Hop, hop, through examples galore,
Filtering magic from tail to core!
Products, use cases, search so bright,
A rabbit's code brings pure delight! 🔍✨


🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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 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 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.

@aralovelace aralovelace changed the title Web 4087 [WEB-4087] - New Examples index page with filtering & search Dec 17, 2024
@aralovelace aralovelace self-assigned this Dec 17, 2024
@ably-ci ably-ci temporarily deployed to ably-docs-web-4087-rblztuthhnh December 17, 2024 17:32 Inactive
@aralovelace aralovelace temporarily deployed to ably-docs-web-4087-rblztuthhnh December 17, 2024 17:32 Inactive
@aralovelace aralovelace temporarily deployed to ably-docs-web-4087-rblztuthhnh December 17, 2024 17:33 Inactive
@aralovelace aralovelace temporarily deployed to ably-docs-web-4087-rblztuthhnh December 18, 2024 09:29 Inactive
@GregHolmes GregHolmes temporarily deployed to ably-docs-web-4087-rblztuthhnh December 18, 2024 12:04 Inactive
@GregHolmes GregHolmes temporarily deployed to ably-docs-web-4087-rblztuthhnh December 18, 2024 12:20 Inactive
@aralovelace aralovelace temporarily deployed to ably-docs-web-4087-rblztuthhnh December 19, 2024 10:58 Inactive
@aralovelace aralovelace temporarily deployed to ably-docs-web-4087-rblztuthhnh December 19, 2024 18:26 Inactive
@aralovelace aralovelace temporarily deployed to ably-docs-web-4087-rblztuthhnh December 19, 2024 22:09 Inactive
@aralovelace aralovelace temporarily deployed to ably-docs-web-4087-rblztuthhnh December 19, 2024 22:10 Inactive
@aralovelace
Copy link
Contributor Author

@coderabbitai review

Copy link

coderabbitai bot commented Dec 19, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@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: 12

🧹 Nitpick comments (17)
src/components/Examples/examples-checkbox.css (1)

6-6: Remove extra space in CSS selector

There's a double space in the selector between the + combinator and .ui-checkbox-styled-tick.

-.ui-checkbox-input:disabled +  .ui-checkbox-styled-tick {
+.ui-checkbox-input:disabled + .ui-checkbox-styled-tick {
src/components/Examples/filter-search-examples.ts (2)

6-6: Consider using consistent types for selectedProducts

The parameter type allows both ProductName and string[], which could lead to inconsistent handling. Consider using a single type for better type safety.

-selectedProducts: ProductName | string[],
+selectedProducts: ProductName[],

4-19: Consider adding input validation

The function should validate its inputs to handle edge cases gracefully.

 export const filterSearchExamples = (
   examples: Example[],
   selectedProducts: ProductName[],
   selectedUseCases: string[],
   searchTerm: string,
 ) => {
+  if (!Array.isArray(examples) || !Array.isArray(selectedProducts) || !Array.isArray(selectedUseCases)) {
+    return [];
+  }
+  if (typeof searchTerm !== 'string') {
+    searchTerm = '';
+  }
   const normalizedSearchTerm = searchTerm.toLowerCase();
   return examples.filter(
     // ... rest of the implementation
   );
 };
src/components/Examples/ExamplesNoResults.tsx (3)

5-5: Fix variable naming and move data to constants

The variable name should be plural, and the search terms should be moved to a constants file for better maintainability.

-const popularSearchTerm = ['Avatar stack', 'Live Cursors', 'Occupancy', 'Presence'];
+import { POPULAR_SEARCH_TERMS } from '../../constants/examples';

4-26: Add TypeScript interface for component props

Even though the component currently doesn't accept props, it's good practice to define an interface for future extensibility.

+interface ExamplesNoResultsProps {
+  // Add future props here
+}

-const ExamplesNoResults = () => {
+const ExamplesNoResults: React.FC<ExamplesNoResultsProps> = () => {

12-16: Use semantic HTML for list of terms

The search terms should be rendered as a list for better semantics.

-{popularSearchTerm.map((term) => (
-  <Badge key={`search-term-${term}`} className="text-neutral-1300 ui-text-menu3 font-medium">
-    {term}
-  </Badge>
-))}
+<ul className="flex mt-8 gap-x-6 list-none p-0">
+  {POPULAR_SEARCH_TERMS.map((term) => (
+    <li key={`search-term-${term}`}>
+      <Badge className="text-neutral-1300 ui-text-menu3 font-medium">
+        {term}
+      </Badge>
+    </li>
+  ))}
+</ul>
src/components/Image.tsx (1)

10-10: Consider documenting the relationship between 'name', 'base', and 'src' properties

The addition of the optional name property alongside existing base and src properties could lead to confusion about when to use each. Consider adding JSDoc comments to clarify the intended usage of each property and their relationships.

+ /** Unique identifier for the image, used primarily in the Examples feature */
  name?: string;
src/components/Examples/ExamplesCheckbox.tsx (2)

33-33: Simplify the onChange handler

The arrow function wrapper is unnecessary since you're just passing the event through.

-        onChange={(e) => selectProductOrUseCase(e)}
+        onChange={selectProductOrUseCase}

22-41: Enhance accessibility features

While the component includes basic accessibility features, consider adding:

  1. aria-label for better screen reader support
  2. role="checkbox" for explicit semantics
  3. aria-checked state for custom checkbox styling
     <div className="flex items-center mb-0">
       <input
         data-ui-checkbox-native=""
         type="checkbox"
         id={name}
         name={name}
         className="ui-checkbox-input"
         value={value}
         checked={isChecked || isDefaultChecked}
         disabled={disabled}
         onChange={selectProductOrUseCase}
+        aria-label={label}
+        role="checkbox"
+        aria-checked={isChecked || isDefaultChecked}
       />
src/pages/examples.tsx (1)

39-53: Add TypeScript type generation for GraphQL query

Consider adding TypeScript type generation for the GraphQL query to ensure type safety and better IDE support.

Add a type annotation for the query:

export const query: GatsbyGraphQLQuery = graphql`
  query ExamplesPageQuery {
    allFile(filter: { relativeDirectory: { eq: "examples" } }) {
      images: nodes {
        name
        extension
        base
        publicURL
        childImageSharp {
          gatsbyImageData
        }
      }
    }
  }
`;
src/components/Examples/ExamplesFilter.tsx (1)

8-24: Props interface should be extracted for better maintainability

Consider extracting the props interface to improve code organization and reusability.

+interface ExamplesFilterProps {
+  selectProduct: (e: React.ChangeEvent<HTMLInputElement>) => void;
+  selectUseCases: (e: React.ChangeEvent<HTMLInputElement>) => void;
+  handleSearch: (e: React.ChangeEvent<HTMLInputElement>) => void;
+  checkAllProducts: boolean;
+  selectedProducts: string[];
+  checkAllUseCases: boolean;
+  selectedUseCases: string[];
+}

-const ExamplesFilter = ({
+const ExamplesFilter = ({
   selectProduct,
   selectUseCases,
   handleSearch,
   checkAllProducts,
   selectedProducts,
   checkAllUseCases,
   selectedUseCases,
-}: {
-  selectProduct: (e: React.ChangeEvent<HTMLInputElement>) => void;
-  selectUseCases: (e: React.ChangeEvent<HTMLInputElement>) => void;
-  handleSearch: (e: React.ChangeEvent<HTMLInputElement>) => void;
-  checkAllProducts: boolean;
-  selectedProducts: string[];
-  checkAllUseCases: boolean;
-  selectedUseCases: string[];
-})
+}: ExamplesFilterProps)
src/components/Examples/ExamplesGrid.tsx (1)

16-31: Move color mapping to a configuration object

The switch statement for badge colors should be extracted to a configuration object for better maintainability.

+const PRODUCT_COLORS: Record<ProductName, string> = {
+  chat: 'text-violet-400',
+  spaces: 'text-pink-500',
+  liveSync: 'text-blue-600',
+  assetTracking: 'text-green-600',
+  liveObjects: 'text-green-600',
+} as const;

 const badgeColorForProduct = (product: ProductName) => {
-  switch (product) {
-    case 'chat':
-      return 'text-violet-400';
-    case 'spaces':
-      return 'text-pink-500';
-    case 'liveSync':
-      return 'text-blue-600';
-    case 'assetTracking':
-      return 'text-green-600';
-    case 'liveObjects':
-      return 'text-green-600';
-    default:
-      return 'text-orange-700';
-  }
+  return PRODUCT_COLORS[product] ?? 'text-orange-700';
 };
src/components/Examples/ExamplesContent.tsx (2)

11-16: Consider using useReducer for complex state management

The component manages multiple related state variables that could be simplified using useReducer.

interface FilterState {
  selectedProducts: string[];
  selectedUseCases: string[];
  checkAllProducts: boolean;
  checkAllUseCases: boolean;
  searchTerm: string;
  filteredExamples: typeof examples.examples;
}

type FilterAction =
  | { type: 'SELECT_PRODUCT'; payload: { value: string; checked: boolean } }
  | { type: 'SELECT_USE_CASE'; payload: { value: string; checked: boolean } }
  | { type: 'SET_SEARCH_TERM'; payload: string }
  | { type: 'SET_FILTERED_EXAMPLES'; payload: typeof examples.examples };

This would consolidate the state updates and make the component's logic more maintainable.


100-107: Consider lazy loading decorative images

The StaticImage components are decorative and could be lazy loaded to improve initial page load.

 <StaticImage
   src="./images/GridPattern.png"
   placeholder="blurred"
   width={660}
   height={282}
   alt="Grid Pattern"
+  loading="lazy"
+  aria-hidden="true"
   className="absolute z-0 right-0 top-64 hidden sm:block w-[60%] md:w-[40%]"
 />

Also applies to: 109-115

src/data/examples.ts (3)

1-13: Consider strengthening type safety with string literals

The interfaces are well-structured, but could benefit from additional type safety:

+type SupportedLanguage = 'javascript' | 'react';
+type Product = 'spaces' | 'chat' | 'pubsub';
+type UseCase = 'multiplayer' | 'live-chat' | 'data-broadcast' | 'data-sync' | 'notifications';

 export interface Example {
   name: string;
   description: string;
-  languages: string[];
-  products: string[];
-  useCases: string[];
-  image: string;
+  languages: SupportedLanguage[];
+  products: Product[];
+  useCases: UseCase[];
+  image: string & {};  // non-empty string
 }

 export interface Examples {
   examples: Example[];
-  useCases: { [key: string]: { label: string } };
+  useCases: { [K in UseCase]: { label: string } };
 }

123-123: Consider removing type assertion

The type assertion as Example[] can be avoided by properly typing the array literal.

-  ] as Example[],
+  ]: Example[],

1-141: Consider separating types and data

For better maintainability, consider splitting this file into:

  1. types/examples.ts for interfaces
  2. data/examples-data.ts for the actual data
  3. constants/use-cases.ts for use case definitions

This separation would make it easier to maintain and test each aspect independently.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 31b11d6 and 99b32b3.

⛔ Files ignored due to path filters (14)
  • src/components/Examples/images/GridMobile.png is excluded by !**/*.png
  • src/components/Examples/images/GridPattern.png is excluded by !**/*.png
  • src/components/blocks/Html/__snapshots__/Html.test.tsx.snap is excluded by !**/*.snap
  • src/components/blocks/wrappers/__snapshots__/ConditionalChildrenLanguageDisplay.test.js.snap is excluded by !**/*.snap
  • src/images/examples/example-avatar-stack.png is excluded by !**/*.png
  • src/images/examples/example-component-locking.png is excluded by !**/*.png
  • src/images/examples/example-generate-token.png is excluded by !**/*.png
  • src/images/examples/example-live-cursors.png is excluded by !**/*.png
  • src/images/examples/example-member-location.png is excluded by !**/*.png
  • src/images/examples/example-occupancy.png is excluded by !**/*.png
  • src/images/examples/example-presence.png is excluded by !**/*.png
  • src/images/examples/example-room-reactions.png is excluded by !**/*.png
  • src/images/examples/example-typing-indicator.png is excluded by !**/*.png
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (11)
  • package.json (1 hunks)
  • src/components/Examples/ExamplesCheckbox.tsx (1 hunks)
  • src/components/Examples/ExamplesContent.tsx (1 hunks)
  • src/components/Examples/ExamplesFilter.tsx (1 hunks)
  • src/components/Examples/ExamplesGrid.tsx (1 hunks)
  • src/components/Examples/ExamplesNoResults.tsx (1 hunks)
  • src/components/Examples/examples-checkbox.css (1 hunks)
  • src/components/Examples/filter-search-examples.ts (1 hunks)
  • src/components/Image.tsx (1 hunks)
  • src/data/examples.ts (1 hunks)
  • src/pages/examples.tsx (1 hunks)
🔇 Additional comments (3)
package.json (1)

42-42: Verify @ably/ui version update compatibility

The update from ^15.1.0 to ^15.1.9 looks reasonable as it's a minor version bump. However, let's verify the version and check for any potential issues.

✅ Verification successful

@ably/ui version update is safe to proceed

The version update from ^15.1.0 to ^15.1.9 appears safe based on:

  • Extensive usage of @ably/ui components throughout the codebase, primarily core utilities and UI components
  • No breaking changes detected in the usage patterns
  • The codebase shows consistent integration with @ably/ui components
  • The caret (^) version constraint allows for safe minor version updates

The update aligns with the PR's objective of implementing a new Examples index page with filtering & search, as evidenced by the new components using @ably/ui (ExamplesGrid.tsx, ExamplesFilter.tsx, etc.).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify @ably/ui package version and check for potential issues

# Check latest version on npm
echo "Checking latest version..."
npm view @ably/ui version

# Check for known vulnerabilities
echo "Checking for vulnerabilities..."
npm audit @ably/[email protected]

# Fetch changelog to check for breaking changes
echo "Checking changelog..."
curl -s https://raw.githubusercontent.com/ably/ably-ui/main/CHANGELOG.md | head -n 50

Length of output: 715


Script:

#!/bin/bash
# Let's check the package-lock.json for any existing version of @ably/ui
# and look for any direct dependencies or potential conflicts

# Check if package-lock.json exists and look for @ably/ui entries
echo "Checking package-lock.json..."
if [ -f package-lock.json ]; then
    rg "@ably/ui" package-lock.json -A 5 -B 1
fi

# Check for any imports of @ably/ui components in the codebase
echo -e "\nChecking @ably/ui usage in codebase..."
rg "from ['|\"]@ably/ui" -A 1

# Look for any peer dependencies or related configuration
echo -e "\nChecking for peer dependencies..."
rg '"@ably/ui"' package.json -A 3 -B 3

Length of output: 12706

src/components/Examples/examples-checkbox.css (1)

1-4: LGTM! Good use of CSS variables

The styling follows best practices by using CSS variables for colors, making it maintainable and consistent with the design system.

Also applies to: 6-8

src/data/examples.ts (1)

53-53: ⚠️ Potential issue

Missing image assets could affect UI rendering

Several examples have empty image properties. This might cause UI issues if the components aren't prepared to handle missing images.

Consider:

  1. Adding placeholder images
  2. Making the image property optional in the Example interface
  3. Implementing fallback UI for missing images

Also applies to: 77-77, 85-85, 102-102, 110-110

src/components/Examples/filter-search-examples.ts Outdated Show resolved Hide resolved
src/components/Examples/ExamplesNoResults.tsx Outdated Show resolved Hide resolved
src/components/Examples/ExamplesCheckbox.tsx Outdated Show resolved Hide resolved
src/pages/examples.tsx Outdated Show resolved Hide resolved
src/pages/examples.tsx Outdated Show resolved Hide resolved
src/components/Examples/ExamplesGrid.tsx Outdated Show resolved Hide resolved
src/components/Examples/ExamplesContent.tsx Outdated Show resolved Hide resolved
src/components/Examples/ExamplesContent.tsx Outdated Show resolved Hide resolved
src/data/examples.ts Outdated Show resolved Hide resolved
src/data/examples.ts Show resolved Hide resolved
@jamiehenson jamiehenson force-pushed the WEB-4087 branch 2 times, most recently from f0e6a1d to 69b2787 Compare January 9, 2025 17:05
@jamiehenson jamiehenson changed the base branch from main to web-4082-docs-nav-redesign January 9, 2025 17:05
@jamiehenson jamiehenson force-pushed the WEB-4087 branch 2 times, most recently from 4de27e3 to ad94b29 Compare January 10, 2025 11:08
@jamiehenson jamiehenson temporarily deployed to ably-docs-web-4087-917v9h1o8ja January 13, 2025 15:26 Inactive
@jamiehenson jamiehenson force-pushed the web-4082-docs-nav-redesign branch 4 times, most recently from 1b979c6 to a66396f Compare January 13, 2025 17:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

4 participants