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

enhance: Introduce dataviews component and update webpack. #2497

Open
wants to merge 14 commits into
base: update/vendor-dashboard-structure
Choose a base branch
from

Conversation

MdAsifHossainNadim
Copy link
Contributor

@MdAsifHossainNadim MdAsifHossainNadim commented Jan 1, 2025

All Submissions:

  • My code follow the WordPress' coding standards
  • My code satisfies feature requirements
  • My code is tested
  • My code passes the PHPCS tests
  • My code has proper inline documentation
  • I've included related pull request(s) (optional)
  • I've included developer documentation (optional)
  • I've added proper labels to this pull request

Changes proposed in this Pull Request:

Related Pull Request(s)

#4047

Closes

  • Closes #

How to test the changes in this Pull Request:

  • Steps or issue link

Changelog entry

Title

Detailed Description of the pull request. What was previous behaviour
and what will be changed in this PR.

Before Changes

Describe the issue before changes with screenshots(s).

After Changes

Describe the issue after changes with screenshot(s).

Feature Video (optional)

Link of detailed video if this PR is for a feature.

PR Self Review Checklist:

  • Code is not following code style guidelines
  • Bad naming: make sure you would understand your code if you read it a few months from now.
  • KISS: Keep it simple, Sweetie (not stupid!).
  • DRY: Don't Repeat Yourself.
  • Code that is not readable: too many nested 'if's are a bad sign.
  • Performance issues
  • Complicated constructions that need refactoring or comments: code should almost always be self-explanatory.
  • Grammar errors.

FOR PR REVIEWER ONLY:

As a reviewer, your feedback should be focused on the idea, not the person. Seek to understand, be respectful, and focus on constructive dialog.

As a contributor, your responsibility is to learn from suggestions and iterate your pull request should it be needed based on feedback. Seek to collaborate and produce the best possible contribution to the greater whole.

  • Correct — Does the change do what it’s supposed to? ie: code 100% fulfilling the requirements?
  • Secure — Would a nefarious party find some way to exploit this change? ie: everything is sanitized/escaped appropriately for any SQL or XSS injection possibilities?
  • Readable — Will your future self be able to understand this change months down the road?
  • Elegant — Does the change fit aesthetically within the overall style and architecture?

Summary by CodeRabbit

Release Notes

New Features

  • Added a new DataView Table component for enhanced data management
  • Introduced comprehensive REST API controllers for customers, countries, and continents
  • Implemented vendor navigation menu management
  • Enhanced routing capabilities for dashboard application

Improvements

  • Updated Tailwind CSS configuration with scoped styles
  • Improved asset management and frontend component loading
  • Added support for downloadable product filtering in REST API
  • Enhanced permission handling for REST API endpoints

Documentation

  • Added detailed documentation for REST controllers
  • Provided guidelines for menu and template overrides in React applications

Bug Fixes

  • Refined REST API permission checks
  • Improved error handling for API requests

Performance

  • Optimized webpack configuration
  • Added more efficient asset loading strategies

Development

  • Updated development dependencies
  • Added new testing infrastructure for REST controllers and services

Copy link
Contributor

coderabbitai bot commented Jan 1, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

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 set of changes to the Dokan plugin, focusing on enhancing the REST API, implementing new React components, and introducing a sophisticated Tailwind CSS configuration. The modifications span across multiple areas including REST controllers, frontend routing, layout components, and styling infrastructure. Key additions include new abstract REST controllers, a vendor navigation menu checker, React dashboard components, and a scoped Tailwind CSS configuration that provides enhanced styling capabilities.

Changes

File Change Summary
base-tailwind.config.js New Tailwind CSS configuration with scoped styles and theme extensions
docs/api/api.md Comprehensive documentation for REST controllers and their implementation
includes/Abstracts/ New abstract REST controllers for base, admin, vendor, and customer endpoints
includes/REST/ New REST API controllers for customers, data, and orders with enhanced functionality
src/Components/ New DataViews component and related styling
src/Layout/ New layout components for dashboard, header, footer, and content area
src/Routing/ Enhanced routing mechanism with higher-order router component
package.json Updated dependencies, including Tailwind CSS and WordPress packages

Sequence Diagram

sequenceDiagram
    participant Client
    participant Router
    participant Layout
    participant ContentArea
    participant DataViews
    participant RESTController

    Client->>Router: Request Dashboard
    Router->>Layout: Render Layout
    Layout->>ContentArea: Render Content
    ContentArea->>DataViews: Initialize Table
    DataViews->>RESTController: Fetch Data
    RESTController-->>DataViews: Return Data
    DataViews->>Layout: Render Table
Loading

Possibly related PRs

Suggested Labels

Needs: Testing, Needs: Dev Review, Upcoming Release

Suggested Reviewers

  • mrabbani
  • shohag121

Poem

🐰 Hopping through code with glee,
A Dokan dashboard, fresh and free!
Tailwind styles, routes so bright,
REST controllers taking flight!
React components dancing light! 🌈


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

@MdAsifHossainNadim MdAsifHossainNadim changed the base branch from develop to update/vendor-dashboard-structure January 1, 2025 10:34
@MdAsifHossainNadim MdAsifHossainNadim self-assigned this Jan 1, 2025
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 7

🧹 Nitpick comments (47)
includes/Abstracts/DokanRESTBaseController.php (1)

35-66: Consider bounding the pagination size.
The format_collection_response method is well-structured, but setting a maximum bound for per_page can guard against excessively large queries. Otherwise, this implementation aligns with standard WordPress REST patterns.

includes/REST/DokanDataCountriesController.php (1)

85-98: Role-based access in get_items_permissions_check.
Granting access to dokan_admin_menu_capability() and 'dokandar' is appropriate for your plugin's roles. If you expand roles in the future, consider centralizing role checks to maintain clarity.

includes/VendorNavMenuChecker.php (2)

69-78: Dependency resolution for routes.
is_dependency_cleared checks overridden templates to conditionally adjust route usage. This is a neat approach to gracefully degrade or adjust menu links.


103-120: Resolving overridden templates.
get_template_dependencies_resolutions transforms dependencies into actual template checks. Ensure the 'dokan_get_dashboard_nav_template_dependency_resolutions' filter remains well-documented for plugin devs.

includes/REST/CustomersController.php (3)

26-50: Clarify route documentation
While the docblock mentions the purpose of the new route, it would be beneficial to add more explicit documentation (e.g., expected parameters, examples) for the /search route. Clear docs help both internal developers and external consumers of this REST API.


52-83: Refine permission checks for better extensibility
The check_permission method currently maps a fixed set of actions (view, create, edit, delete, batch, search) to vendor permissions. Considering future expansions, using a filter or more granular role checks can make permission handling easier to extend or override.


280-285: Consider switching from filter toggling to using capabilities
perform_vendor_action temporarily adds and removes woocommerce_rest_check_permissions filters. An alternative approach might be hooking in more granular capabilities or using dedicated Woocommerce permission callbacks. This can reduce side effects and keep permission logic in a single place.

tests/php/src/REST/CustomersControllerTest.php (3)

35-59: Expand test data coverage
You've created multiple customers for testing, which is excellent. Consider adding a scenario with edge-case user data (e.g., empty last name, special characters in username) to more thoroughly test the controller’s resilience.


112-147: Add negative tests for get_items
There are tests for per_page and ordering, but also verify negative or borderline cases (e.g., invalid per_page, extremely large page number). This ensures the controller handles them gracefully.


278-330: Assert database changes after batch operations
The test verifies the response after create, update, and delete. Also consider verifying that changes are truly reflected in the database or user store for fully integrated testing.

includes/Assets.php (3)

5-5: Validate the availability of WCAdminAssets
Ensure that Automattic\WooCommerce\Internal\Admin\WCAdminAssets is available in all supported WooCommerce versions. If older versions of WooCommerce are in use, consider fallback logic to avoid potential class-not-found issues.


536-597: Ensure script sizes remain reasonable
The new scripts (login-form-popup, sweetalert2, dokan-util-helper, etc.) may increase the admin bundle size. Consider lazy-loading them or conditionally enqueuing them only when needed to reduce overhead.


904-914: Safeguard admin script registration
Registering and then enqueuing dokan-react-frontend and dokan-react-components in the dashboard is excellent. As you leverage WCAdminAssets, double-check if these scripts are only loaded in contexts where they are actually used, preventing unnecessary load in the entire WP admin.

src/Components/index.tsx (1)

1-2: Clarify usage
Exporting DataViews and useWindowDimensions is helpful for reuse. If these exports are central to critical app workflows, add a short comment or descriptive doc to guide other developers on their usage.

src/Layout/ContentArea.tsx (2)

1-3: Optimize imports
You are importing Slot from @wordpress/components, which is fine. If more WordPress components are anticipated, consider grouping them in a single import statement to keep code tidy.


4-15: Avoid unintentional re-renders
ContentArea returns a fragment and includes <Sidebar> plus multiple <Slot> components. If performance becomes an issue, consider memoizing child components or using a layout approach that prevents unnecessary re-renders.

includes/Abstracts/DokanRESTCustomerController.php (1)

19-19: Consider clarifying or translating $rest_base further in docs.
Although 'customer' conveys the endpoint, you might want to specify in the docblock that this endpoint is primarily used for authenticated customer requests, distinguishing it from the vendor or admin endpoints.

includes/Abstracts/DokanRESTVendorController.php (1)

19-19: Document the $rest_base property more explicitly.
Although 'vendor' is self-explanatory, adding a bit of contextual detail in the docblock about how this endpoint fits into the overall Dokan REST architecture could help maintainers.

src/Layout/Header.tsx (2)

4-5: Add prop type definitions for maintainability.
Even a simple interface or type annotation clarifying that title?: string helps future contributors understand what props are expected here.

-const Header = ( { title = '' } ) => {
+import { FC } from 'react';
+interface HeaderProps {
+  title?: string;
+}
+
+const Header: FC<HeaderProps> = ( { title = '' } ) => {
   const navigate = useNavigate();

8-18: Ensure placeholders or fallback for empty Slot usage.
If downstream components don’t supply fills for these slots, the layout might look inconsistent. Consider default placeholders or at least a graceful fallback.

src/Dashboard/index.tsx (1)

11-12: Correct the variable name to "mappedRoutes".
Improve clarity and consistency by fixing the spelling. This helps future contributors understand the variable’s purpose at a glance.

-const mapedRoutes = routes.map( ( route ) => {
+const mappedRoutes = routes.map( ( route ) => {
src/Hooks/ViewportDimensions.ts (2)

8-14: Add or update inline tags for clarity.
You might consider adding an explicit @returns JSDoc tag or clarifying param usage for @since.


23-43: Ensure optimal performance or consider a debounce.
While using requestAnimationFrame throttles dimension updates, frequent resizing in some browsers can still lead to multiple calls per frame. If performance is a concern, you might consider a short debounce or further optimization.

includes/REST/OrderControllerV3.php (1)

16-25: Versioning documentation.
Since this is a new version (v3), confirm that the relevant doc comments or changelog references the correct version to avoid confusion with older controllers.

src/Layout/index.tsx (1)

1-4: Imports are logically grouped and descriptive.
Consider adding a short doc comment for each imported component to clarify usage if needed.

src/Components/DataViews/DataViewTable.tsx (3)

1-6: Ensure consistent import ordering and naming.
You may want to keep the imports from external libraries (e.g., @wordpress/dataviews, @wordpress/components) together, then local hooks, then type definitions, and finally styles. This improves readability and makes it easier for newcomers to navigate the file.


39-57: Add fallback or warning when no data is present.
If props.data is empty, the table might render no rows. Consider showing a fallback message or a spinner if isLoading is true. This enhances the user experience by providing clarity.


59-59: Export as named export as well.
Consider adding a named export for DataViewTable to simplify imports in other parts of the codebase. This can be done alongside the default export, facilitating tree-shaking and more flexible importing patterns.

+ export { DataViewTable };
export default DataViewTable;
src/Routing/index.tsx (3)

1-7: Use consistent import ordering and identify potential code splitting.
This file imports both WordPress packages and React Router functionality. Evaluate whether any route definitions or large components can be code-split to reduce initial bundle size.


8-40: Avoid dynamic checking of valid elements in withRouter.
While cloning or creating an element is a valid approach, you might simplify the logic by ensuring Component is always a function or class-based component. This approach can be more predictable and reduce potential type-safety issues.

+ // Example approach:
+ // Make withRouter a higher-order function that returns a new functional component 
+ // and pass the router props directly, rather than checking if `Component` is a valid element.

42-79: Leverage code splitting for NotFound or other large components.
If NotFound or other components might be less frequently used, you could dynamically import them to optimize performance for the main flow.

base-tailwind.config.js (2)

6-7: Clarify usage of custom .dokan-layout class.
Ensure all relevant parent containers or root elements are wrapped with this class so that the styling is consistently applied and doesn’t leak outside.


8-94: Ensure critical styles remain unscoped if needed.
Some utilities, such as reset or normalizing styles, may need to remain unscoped for consistency across the entire page layout. Confirm that scoping them under .dokan-layout does not cause visual discrepancies in other areas.

webpack.config.js (1)

12-12: Name your new entry point meaningfully.
The key "frontend" is a bit generic. Consider more descriptive names, for instance "dokan-dashboard-frontend" or "dokan-frontend-react", to differentiate from other frontends.

src/Layout/WPostsDataView.tsx (3)

177-177: Remove redundant double-negation to simplify condition.
The value from view?.sort?.field is already coerced to boolean in a conditional. There is no need for !!.

- if ( !! view?.sort?.field ) {
+ if (view?.sort?.field) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 177-177: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)


182-182: Remove redundant double-negation to simplify condition.
Similar reasoning applies here; using view?.sort?.direction on its own is sufficient.

- if ( !! view?.sort?.direction ) {
+ if (view?.sort?.direction) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 182-182: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)


187-187: Remove redundant double-negation to simplify condition.
Again, no need for !! view?.filters.

- if ( !! view?.filters ) {
+ if (view?.filters) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 187-187: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)

includes/REST/ProductController.php (1)

75-85: Check for potential performance overhead in meta queries.
Repeated meta queries (e.g., _downloadable) can impact performance on large product sets. If this filter is widely used, consider adding an index or caching strategy.

src/base-tailwind.scss (1)

6-21: Consider preserving minimal spacing for better readability.

While resetting table styles is good for consistency, completely zeroing out all spacing might affect readability. Consider maintaining minimal padding for better content legibility.

 @layer base {
     .dokan-layout {
         table, th, td {
-            margin: 0;
-            padding: 0;
+            margin: 0;
+            padding: 0.25rem 0.5rem;
             border: 0;
             border-spacing: 0;
             border-collapse: collapse;
docs/feature-override/readme.md (3)

63-64: Fix React capitalization and improve clarity.

Ensure consistent capitalization of "React" as it's a proper noun. Also, consider restructuring the sentences to improve readability.

-This will be used to determine if the menu is pointing to the react Application or to the Legacy PHP Route.
+This will be used to determine if the menu is pointing to the React application or to the legacy PHP route.

-The `route` property should be the same as the route defined in the `React` application in Router Array.
+The `route` property should be the same as the route defined in the `React` application's router configuration.

Also applies to: 66-69

🧰 Tools
🪛 LanguageTool

[grammar] ~63-~63: “React” is a proper noun and needs to be capitalized.
Context: ...h menu which we are indicating that the react route is available. This will be used ...

(A_GOOGLE)


[grammar] ~64-~64: “React” is a proper noun and needs to be capitalized.
Context: ...etermine if the menu is pointing to the react Application or to the Legacy PHP Route....

(A_GOOGLE)


91-92: Improve clarity of migration documentation.

The explanation about when to define override templates is a bit convoluted. Consider breaking it into clearer steps.

-If you are writing a new feature or modifying an existing feature in the `React` application, you do not need to define the override templates for the `React` route.
-But if you are modifying or migrating an existing feature written in PHP to the `React` application and you want that if some of the PHP template is overridden by the existing PHP template then the legacy PHP page will be displayed, then you need to define the override templates for the `React` route.
+Override templates are only needed when:
+1. You are migrating an existing PHP feature to React
+2. The existing PHP feature has template overrides
+3. You want to maintain compatibility with these overridden templates
+
+For new React features, you do not need to define override templates.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~92-~92: Use a comma before ‘and’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...ritten in PHP to the React application and you want that if some of the PHP templa...

(COMMA_COMPOUND_SENTENCE)


136-145: Add type information to the template structure documentation.

The array structure documentation would benefit from type information for better clarity.

 [ 
-    'route_name' => [ 
+    'route_name' => [ // string
             [
-                'slug' => 'template-slug', 
-                'name' => 'template-name' // (Optional),
-                'args' = [] // (Optional)
+                'slug' => 'template-slug',    // string (required)
+                'name' => 'template-name',    // string (optional)
+                'args' => []                  // array  (optional)
             ], 
         ]
 ]
docs/api/api.md (2)

5-5: Fix typo in anchor link

There's a typo in the anchor link "role-specifix-controllers" which should be "role-specific-controllers".

-## 1. Role-Specifix Controllers.
+## 1. Role-Specific Controllers
🧰 Tools
🪛 Markdownlint (0.37.0)

5-5: null
Link fragments should be valid

(MD051, link-fragments)


96-98: Add error handling to check_permission method

The permission check should handle potential errors when the user capability check fails.

Consider adding error handling:

public function check_permission() {
    if ( ! current_user_can( 'dokandar' ) ) {
        return new WP_Error(
            'dokan_rest_cannot_view',
            __( 'Sorry, you are not allowed to view this resource.', 'dokan' ),
            [ 'status' => rest_authorization_required_code() ]
        );
    }
    return true;
}
docs/frontend/dataviews.md (3)

27-27: Fix grammatical error in component description

The sentence has a subject-verb agreement error.

-Also, an example component are designed to interact with WordPress REST APIs
+Also, an example component is designed to interact with WordPress REST APIs
🧰 Tools
🪛 LanguageTool

[grammar] ~27-~27: “component” is a singular noun. It appears that the verb form is incorrect.
Context: ...r dashboard. Also, an example component are designed to interact with WordPress RES...

(PCT_SINGULAR_NOUN_PLURAL_VERB_AGREEMENT)


39-65: Add error handling for asset registration

The script registration example should include error handling for missing assets.

Consider adding error handling:

$script_assets = 'add your script assets path here';

if ( ! file_exists( $script_assets ) ) {
    error_log( sprintf( 'Error: Asset file %s does not exist', $script_assets ) );
    return;
}

try {
    $vendor_asset = require $script_assets;
    // ... rest of the registration code
} catch ( Exception $e ) {
    error_log( sprintf( 'Error loading asset file: %s', $e->getMessage() ) );
    return;
}

708-708: Remove duplicate text in callback description

The callback description contains duplicate text.

-When we need to click & redirect action to another page, we can use this property. When we need to click \& redirect action to another page, we can use this property.
+When we need to click & redirect action to another page, we can use this property.
🛑 Comments failed to post (7)
includes/Abstracts/DokanRESTCustomerController.php (1)

28-30: 🛠️ Refactor suggestion

Validate user’s role in addition to checking login status.
While is_user_logged_in() ensures authentication, you may also consider confirming the user’s role matches “customer.” This helps safeguard against unauthorized usage by other roles who are merely logged in.

 public function check_permission() {
-    return is_user_logged_in();
+    return is_user_logged_in() && current_user_can( 'customer_capability' ); 
 }

Committable suggestion skipped: line range outside the PR's diff.

src/Dashboard/index.tsx (1)

38-42: 🛠️ Refactor suggestion

Handle missing .dashboard-content-area gracefully.
Using the non-null assertion ! is convenient, but you risk runtime errors if the element isn’t present. A fallback or error message could improve resilience.

 const rootElement = document.querySelector( '.dashboard-content-area' );
-if ( rootElement ) {
-  const root = createRoot( rootElement );
-  root.render( <App /> );
-}
+if (!rootElement) {
+  console.error('Root element not found for the dashboard');
+  return;
+}
+const root = createRoot(rootElement);
+root.render(<App />);
📝 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.

domReady( function () {
    const rootElement = document.querySelector( '.dashboard-content-area' );
    if (!rootElement) {
        console.error('Root element not found for the dashboard');
        return;
    }
    const root = createRoot(rootElement);
    root.render( <App /> );
} );
src/Components/DataViews/DataViewTable.tsx (1)

35-37: ⚠️ Potential issue

Guard against missing hooks object.
wp.hooks.applyFilters implies the global wp object is available. Consider gracefully handling the situation if wp or wp.hooks is undefined, to avoid a runtime error in non-WordPress environments.

+ if (typeof wp?.hooks?.applyFilters !== 'function') {
+   return element;
+ }

Committable suggestion skipped: line range outside the PR's diff.

webpack.config.js (1)

76-80: ⚠️ Potential issue

Check for library collisions.
Defining a global window library named ['dokan', '[name]'] can cause collisions if multiple bundles share the same name. Ensure name uniqueness, especially if the plugin can be active in parallel with other code that uses the same global space.

docs/api/api.md (2)

21-23: 🛠️ Refactor suggestion

Add implementation details for format_collection_response

The format_collection_response method implementation details are missing. This is a crucial method that handles pagination and response formatting.

Consider adding the implementation details:

public function format_collection_response( $response, $request, $total_items ) {
    $total_pages = ceil( $total_items / (int) $request['per_page'] );
    
    $response->header( 'X-WP-Total', (int) $total_items );
    $response->header( 'X-WP-TotalPages', (int) $total_pages );

    return $response;
}

260-260: ⚠️ Potential issue

Fix syntax error in permission check

There's a duplicate semicolon in the permission check condition.

-return is_user_logged_in() || dokan_is_seller_enabled( get_current_user_id() );;
+return is_user_logged_in() || dokan_is_seller_enabled( get_current_user_id() );
📝 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.

        return is_user_logged_in() || dokan_is_seller_enabled( get_current_user_id() );
docs/frontend/dataviews.md (1)

669-671: ⚠️ Potential issue

Fix incorrect slot name in after-table slot

The after-table slot is using the same name as the before-table slot.

-<Slot name={ `dokan-before-vendor-data-table-${ props?.namespace }` } fillProps={{ ...filteredProps }} />
+<Slot name={ `dokan-after-vendor-data-table-${ props?.namespace }` } fillProps={{ ...filteredProps }} />
📝 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.

        {/* After dokan data table rendered slot */}
        <Slot name={ `dokan-after-vendor-data-table-${ props?.namespace }` } fillProps={{ ...filteredProps }} />
    </div>

@MdAsifHossainNadim MdAsifHossainNadim added the Needs: Dev Review It requires a developer review and approval label Jan 2, 2025
webpack.config.js Outdated Show resolved Hide resolved
Copy link
Member

@mrabbani mrabbani left a comment

Choose a reason for hiding this comment

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

Pls also update docs by removing the images.

includes/Assets.php Outdated Show resolved Hide resolved
src/Components/DataViews/DataViewTable.tsx Outdated Show resolved Hide resolved
src/Components/DataViews/DataViewTable.tsx Outdated Show resolved Hide resolved
@mrabbani mrabbani added Needs: Author Reply and removed Needs: Dev Review It requires a developer review and approval labels Jan 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants