### Playwright Initial Setup Source: https://github.com/getdokan/dokan/blob/develop/tests/pw/README.md Performs the initial setup for the project, including installing dependencies, copying the environment file, and setting up Docker. ```bash npm install && cp .env.example .env && npm run docker:full ``` -------------------------------- ### VendorAsyncSelect Quick Overview Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/vendor_asyncselect.md A basic example demonstrating the setup and usage of the VendorAsyncSelect component with state management. ```jsx import { useState } from '@wordpress/element'; import { VendorAsyncSelect } from '@dokan/components'; const Example = () => { const [vendor, setVendor] = useState(null); return ( ); }; ``` -------------------------------- ### Example Admin Controller Implementation Source: https://github.com/getdokan/dokan/blob/develop/docs/api/api.md A practical example of creating an admin controller that extends `DokanBaseAdminController`. ```APIDOC ## Admin Controller Example This example shows how to create a custom admin controller extending `DokanBaseAdminController`. ### Endpoint: GET /dokan/v1/example-admin ### Description Retrieves a collection of example admin resources. ### Method GET ### Endpoint `/dokan/v1/example-admin` ### Parameters #### Query Parameters - **context** (string) - Optional - Controls the output for the response. - **page** (integer) - Optional - Current page of the collection. - **per_page** (integer) - Optional - Maximum number of items to be returned in a page. - **search** (string) - Optional - Limit results to those matching a string. - **exclude** (array) - Optional - Limit results to those not excluding an ID range. - **include** (array) - Optional - Limit results to those including a specific ID range. - **offset** (integer) - Optional - Offsets the result of the collection. - **order** (string) - Optional - Order sort attribute ascending or descending. - **orderby** (string) - Optional - Fields to order the collection by. - **slug** (string) - Optional - Limit results to those matching a specific slug. ### Request Example ```json { "example": "GET /dokan/v1/example-admin?per_page=10&page=1" } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the item. - **name** (string) - The name of the item. - **slug** (string) - The slug of the item. #### Response Example ```json { "example": "[{"id": 1, "name": "Example Item", "slug": "example-item"}]" } ``` ### Endpoint: GET /dokan/v1/example-admin/ ### Description Retrieves a single example admin resource by its ID. ### Method GET ### Endpoint `/dokan/v1/example-admin/` ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the resource to retrieve. ### Request Example ```json { "example": "GET /dokan/v1/example-admin/123" } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the item. - **name** (string) - The name of the item. - **slug** (string) - The slug of the item. #### Response Example ```json { "example": "{"id": 123, "name": "Specific Example Item", "slug": "specific-example-item"}" } ``` ### Code Snippet ```php use WeDevs\Dokan\REST\DokanBaseAdminController; class ExampleAdminController extends DokanBaseAdminController { protected $namespace = 'dokan/v1'; // default namespace is 'dokan/v1/admin' in `DokanBaseAdminController` protected $rest_base = 'example-admin'; public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, [ [ 'methods' => WP_REST_Server::READABLE, 'callback' => [ $this, 'get_items' ], 'permission_callback' => [ $this, 'check_permission' ], 'args' => $this->get_collection_params(), ] ] ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P\d+)', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [ $this, 'get_item' ], 'permission_callback' => [ $this, 'check_permission' ], 'args' => [ 'id' => [ 'description' => __( 'Unique identifier for the resource.' ), 'type' => 'integer', 'validate_callback' => function($param, $request, $key) { return is_numeric( $param ); } ], ], ] ); } /** * Retrieve a single customer. * * @param WP_REST_Request $request Request details. * @return WP_Error|WP_REST_Response */ public function get_item( $request ) { $id = (int) $request['id']; $user_data = get_userdata( $id ); if ( empty( $id ) || empty( $user_data->ID ) ) { return new WP_Error( 'woocommerce_rest_invalid_id', __( 'Invalid resource ID.', 'woocommerce' ), [ 'status' => 404 ] ); } $customer = $this->prepare_item_for_response( $user_data, $request ); return rest_ensure_response( $customer ); } /** * Formats a single customer for response output. * * @param WP_User $user_data User object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response data. */ public function prepare_item_for_response( $user_data, $request ) { // TODO: Implement API response formatting $response = [ 'id' => $user_data->ID, 'name' => $user_data->display_name, 'slug' => $user_data->user_login ]; return apply_filters( 'dokan_rest_prepare_admin', $response, $user_data, $request ); } } ``` ``` -------------------------------- ### Install npm Dependencies for Dokan Pro Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/env-setup.md Navigate to the Dokan Pro plugin directory and install npm dependencies. Ensure Node.js and npm are installed and meet the version requirements. ```bash cd wp-content/plugins/dokan-pro npm install ``` -------------------------------- ### Install Dependencies and Seed Data Source: https://github.com/getdokan/dokan/blob/develop/tests/pw/README.md Installs Node.js dependencies, copies the environment file, and starts the Docker environment with seeded data. ```bash cd tests/pw npm install cp .env.example .env # then edit credentials and LICENSE_KEY npm run docker:full # Docker + admin user + seed data ``` -------------------------------- ### Example Admin Controller Implementation Source: https://github.com/getdokan/dokan/blob/develop/docs/api/api.md An example of an admin controller extending `DokanBaseAdminController`. It demonstrates setting the namespace and rest_base, registering routes, and implementing methods for retrieving items. ```php use WeDevs\Dokan\REST\DokanBaseAdminController; class ExampleAdminController extends DokanBaseAdminController { protected $namespace = 'dokan/v1'; // default namespace is 'dokan/v1/admin' in `DokanBaseAdminController` protected $rest_base = 'example-admin'; public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, [ [ 'methods' => WP_REST_Server::READABLE, 'callback' => [ $this, 'get_items' ], 'permission_callback' => [ $this, 'check_permission' ], 'args' => $this->get_collection_params(), ] ] ); } /** * Retrieve a single customer. * * @param WP_REST_Request $request Request details. * @return WP_Error|WP_REST_Response */ public function get_item( $request ) { $id = (int) $request['id']; $user_data = get_userdata( $id ); if ( empty( $id ) || empty( $user_data->ID ) ) { return new WP_Error( 'woocommerce_rest_invalid_id', __( 'Invalid resource ID.', 'woocommerce' ), [ 'status' => 404 ] ); } $customer = $this->prepare_item_for_response( $user_data, $request ); return rest_ensure_response( $customer ); } /** * Formats a single customer for response output. * * @param WP_User $user_data User object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response data. */ public function prepare_item_for_response( $user_data, $request ) { // TODO: Implement API response formatting return apply_filters( 'dokan_rest_prepare_admin', $response, $user_data, $request ); } } ``` -------------------------------- ### Install Mockery Source: https://github.com/getdokan/dokan/blob/develop/docs/tdd/mocking.md Install Mockery using Composer. This is a development dependency. ```bash composer require mockery/mockery --dev ``` -------------------------------- ### DateTimePicker Usage Examples Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/wp_date_time_picker.md Examples demonstrating how to use the DateTimePicker component with different configurations. ```APIDOC ## DateTimePicker Usage Examples ### 1. Basic Usage ```jsx ``` ### 2. Custom Trigger Content ```jsx ``` ### 3. Handling Clear and Ok ```jsx setDate('')} onOk={() => console.log('Date confirmed:', date)} /> ``` ``` -------------------------------- ### Install Dependencies and Build Assets Source: https://github.com/getdokan/dokan/blob/develop/README.md Commands to install PHP and npm dependencies, and to build assets for development or production. Ensure you are in the Dokan plugin directory. ```bash cd wp-content/plugins/dokan-lite composer install && composer du -o npm install # OR build for production npm run build # Build the assets in development mode with watch npm run start ``` -------------------------------- ### Example Product Slots Documentation Source: https://github.com/getdokan/dokan/blob/develop/docs/slots/README.md An example of a completed markdown file documenting product component slots, including overview, slot reference for list and form components, and props interface. ```markdown # Product Component Slots ## Overview Extension points for product listing and management features. ## Slot Reference ### Product List (`/components/products/List.tsx`) | Slot Name | Position | Props | Description | |-----------|----------|-------|-------------| | `dokan-product-list-before` | Before list | None | Content before product list | | `dokan-product-list-actions` | Action area | `{ selection }` | Bulk actions for products | | `dokan-product-list-after` | After list | None | Content after product list | ### Product Form (`/components/products/Form.tsx`) | Slot Name | Position | Props | Description | |-----------|----------|-------|-------------| | `dokan-product-form-before` | Before form | `{ product }` | Content before product form | | `dokan-product-form-fields` | Form fields | `{ product }` | Additional form fields | ## Props Interface ( If there are no props, you can skip this section but keep the heading and mention "None" ) ```typescript interface ProductProps { product: Product; selection?: number[]; } ``` ``` -------------------------------- ### Quick Overview of SearchInput Component Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/search_input.md Demonstrates the basic setup and usage of the SearchInput component with internal state management. ```jsx import { useState } from '@wordpress/element'; import { SearchInput } from '@dokan/components'; const Example = () => { const [query, setQuery] = useState(''); return ( ); }; ``` -------------------------------- ### Install Composer Dependencies Source: https://github.com/getdokan/dokan/blob/develop/DEVELOPER.md Install PHP dependencies using Composer and optimize the autoloader. ```bash composer install && composer du -o ``` -------------------------------- ### Create and Configure .env File Source: https://github.com/getdokan/dokan/blob/develop/tests/pw/README.md Copies the example environment file and prompts the user to edit it with necessary credentials like license keys and passwords. ```bash cp .env.example .env ``` -------------------------------- ### Withdraw Export Example Source: https://github.com/getdokan/dokan/blob/develop/docs/export-controller-usage.md Example demonstrating how to initiate and check the status of a withdraw export. ```APIDOC ## Withdraw Export Example ### Description This example shows the usage of the export and status endpoints specifically for withdraw data. ### Request Example (Start Export) ```bash curl -X POST "https://yoursite.com/wp-json/dokan/v1/reports/withdraws/export" \ -H "Content-Type: application/json" \ -d '{ "report_args": { "status": "approved", "user_id": 123, "after": "2023-01-01T00:00:00" }, "email": false }' ``` ### Response Example (Start Export) ```json { "message": "Your report file is being generated.", "export_id": "1642534567890" } ``` ### Request Example (Check Status) ```bash curl "https://yoursite.com/wp-json/dokan/v1/reports/withdraws/export/1642534567890/status" ``` ### Response Example (Status - Complete) ```json { "percent_complete": 100, "download_url": "https://yoursite.com/wp-admin/admin.php?action=woocommerce_admin_download_report_csv&filename=wc-withdraws-report-export-1642534567890" } ``` ``` -------------------------------- ### Install NPM Dependencies Source: https://github.com/getdokan/dokan/blob/develop/DEVELOPER.md Install JavaScript dependencies using npm. ```bash npm install ``` -------------------------------- ### Boot Environment and Seed Database Source: https://github.com/getdokan/dokan/blob/develop/tests/pw/README.md Starts the Dockerized WordPress environment, creates an admin user, and sets up the database with plugins, vendors, and products. ```bash npm run docker:full ``` -------------------------------- ### Start Development Server with Watch Mode Source: https://github.com/getdokan/dokan/blob/develop/DEVELOPER.md Build frontend assets and enable webpack watch mode for development with hot reloading. ```bash npm run start ``` -------------------------------- ### ProductAsyncSelect Basic Usage Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/product_asyncselect.md A minimal example of using ProductAsyncSelect with default options and a clear button. This component requires a WordPress environment with REST API access. ```jsx ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/getdokan/dokan/blob/develop/tests/pw/README.md Executes the complete suite of end-to-end, API, and setup tests. ```bash npm test ``` -------------------------------- ### Basic DokanTab Usage Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/tab.md Demonstrates the basic setup of the DokanTab component without providing content slots. Ensure '@dokan/components' is imported. ```jsx import { DokanTab } from '@dokan/components'; const MyTabs = () => { const tabs = [ { name: 'tab1', title: 'Tab 1' }, { name: 'tab2', title: 'Tab 2', icon: 'settings' }, { name: 'tab3', title: 'Tab 3', disabled: true } ]; return ( console.log('Selected tab:', tabName)} /> ); }; ``` -------------------------------- ### Real-world Form Example with Dokan Components Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/utilities.md A complete React component example showing how to integrate `formatNumber`, `unformatNumber`, and `DokanMaskInput` for handling numeric input in a form, including data loading and submission. ```jsx import { snakeCase, formatNumber, unformatNumber } from '@dokan/utilities'; import { DokanMaskInput } from '@dokan/components'; import { useState, useEffect } from 'react'; // Case conversion examples snakeCase('fooBar'); // → "foo_bar" // Accounting examples const formattedNumber = formatNumber(1234.56); // → "1,234.56" (with US settings) const numericValue = unformatNumber("1,234.56"); // → 1234.56 // Real-world example: Form with numeric input const OrderForm = () => { const [formattedTotal, setFormattedTotal] = useState(''); // Load initial data useEffect(() => { // API response with numeric value const order = { total: 42.99 }; // Format for display setFormattedTotal(formatNumber(order.total)); }, []); // Handle form submission const handleSubmit = () => { // Convert back to numeric for calculations and API const numericTotal = unformatNumber(formattedTotal); // Now safe to perform calculations const tax = numericTotal * 0.1; // Submit to API with numeric values submitOrder({ total: numericTotal, tax: tax }); }; return (
setFormattedTotal(e.target.value)} /> ); }; // Dummy functions for example completeness const submitOrder = (data) => console.log('Submitting order:', data); const submitToAPI = (data) => console.log('Submitting to API:', data); const setFormattedValue = (value) => console.log('Formatted value set:', value); const data = { amount: 100.50 }; const formattedValue = formatNumber(data.amount); const unformatNumber = (str) => parseFloat(str.replace(/,/g, '')); const formatPrice = (num) => `$${num.toFixed(2)}`; const snakeCase = (str) => str.replace(/([A-Z])/g, '_$1').toLowerCase(); const camelCase = (str) => str.replace(/_([a-z])/g, (g) => g[1].toUpperCase()); const kebabCase = (str) => str.replace(/_/g, '-'); ``` -------------------------------- ### DateRangePicker Usage Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/components.md Implement the DateRangePicker for selecting date ranges. This example shows state management for dates and visibility, and custom formatting. ```jsx import {useState} from '@wordpress/element'; import {DateRangePicker} from '@dokan/components'; import {dateI18n, getSettings} from '@wordpress/date'; const ReportFilter = () => { const [isOpen, setIsOpen] = useState(false); const [after, setAfter] = useState('2023-01-01'); const [afterText, setAfterText] = useState(''); const [before, setBefore] = useState('2023-01-31'); const [beforeText, setBeforeText] = useState(''); const [focusedInput, setFocusedInput] = useState('startDate'); return ( { if (update.after) { setAfter(update.after); } if (update.afterText) { setAfterText(update.afterText); } if (update.before) { setBefore(update.before); } if (update.beforeText) { setBeforeText(update.beforeText); } if (update.focusedInput) { setFocusedInput(update.focusedInput); if (update.focusedInput !== 'endDate') { setIsOpen(false); } if (update.focusedInput === 'endDate' && after) { setBefore(''); setBeforeText(''); setIsOpen(true); } } }} shortDateFormat="MM/DD/YYYY" focusedInput={focusedInput} isInvalidDate={(date) => new Date(date) > new Date()} >
{dateI18n(getSettings().formats.date, after)} - {dateI18n(getSettings().formats.date, before)}
); }; ``` -------------------------------- ### DokanTooltip Usage Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/components.md Demonstrates the basic usage of the DokanTooltip component. It wraps a button with a tooltip that appears on hover, providing contextual information. ```jsx import { __ } from '@wordpress/i18n'; import { DokanTooltip } from '@dokan/components'; const TooltipExample = () => { return (
); }; ``` -------------------------------- ### Combined Dokan Component Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/color-guidelines.md This example demonstrates combining multiple Dokan components like badges, buttons, and alerts within a card-like structure. ```jsx

Vendor Status

Active
Your store is currently visible to customers.
``` -------------------------------- ### CouponAsyncSelect Custom Query Params Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/coupon_asyncselect.md Demonstrates how to override the default query parameters for fetching coupons. This example sets the number of results per page and filters by status. ```jsx ({ search: term, per_page: 50, status: 'publish' })} /> ``` -------------------------------- ### Dokan Badge Usage Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/components.md Shows how to use the DokanBadge component with different variants and labels. Import DokanBadge from '@dokan/components'. ```jsx import { DokanBadge } from '@dokan/components'; const StatusBadges = () => { return (
); }; ``` -------------------------------- ### CouponAsyncSelect Basic Usage Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/coupon_asyncselect.md Demonstrates the basic integration of the CouponAsyncSelect component. It requires setting up state for the selected coupon and providing a placeholder. ```jsx import { useState } from '@wordpress/element'; import { CouponAsyncSelect } from '@dokan/components'; const Example = () => { const [coupon, setCoupon] = useState(null); return ( ); }; ``` -------------------------------- ### Basic DateTimePicker Usage Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/wp_date_time_picker.md Shows the minimal setup for the DateTimePicker component. It relies on the `currentDate` and `onChange` props for state management. ```jsx ``` -------------------------------- ### Basic Async Loading Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/asyncselect.md Demonstrates the fundamental usage of AsyncSelect for loading options asynchronously. The `loadOptions` prop is essential for fetching data on demand. ```jsx ``` -------------------------------- ### Dokan Button Usage Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/components.md Demonstrates various variants, sizes, and states of the DokanButton component. Ensure DokanButton is imported from '@dokan/components'. ```jsx import { DokanButton } from '@dokan/components'; const ButtonsExample = () => { return (
{/* Action Variants */} Primary Button Secondary Button Tertiary Button {/* Status Variants */} Info Button Success Button Warning Button Danger Button {/* Button Sizes */} Small Button Default Size Large Button {/* Button States */} Disabled Button Loading Button
); }; ``` -------------------------------- ### Quick Confirmation Modal Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/dokan-modal.md Demonstrates how to use the DokanModal component to create a simple confirmation dialog. Ensure 'dokan-react-components' is registered as a dependency. ```tsx import { __ } from '@wordpress/i18n'; import { DokanModal } from '@dokan/components'; const QuickConfirm = () => { const [ isOpen, setIsOpen ] = useState( false ); const handleConfirm = () => { // Handle confirm action setIsOpen( false ); }; return ( handleConfirm() } onClose={ () => setIsOpen( false ) } confirmationTitle={ __( 'Quick Confirmation', 'dokan-lite' ) } confirmationDescription={ __( 'Are you sure?', 'dokan-lite' ) } /> ); } export default QuickConfirm; ``` -------------------------------- ### Basic Filter Implementation Example Source: https://github.com/getdokan/dokan/blob/develop/docs/filters-hooks/README.md Demonstrates how to add a filter using the `wp.hooks.addFilter` function. Ensure the correct filter name, namespace, and callback function are provided. ```javascript wp.hooks.addFilter( 'filter-name', 'namespace', function(value) { return modifiedValue; } ); ``` ```javascript wp.hooks.addFilter( 'dokan-product-form-fields', 'my-plugin', function(fields) { return [...fields, newField]; } ); ``` -------------------------------- ### Basic SearchInput Usage Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/search_input.md A simple example of using the SearchInput component without any custom configurations. The onChange handler logs the search term. ```jsx console.log('Search term:', val) } /> ``` -------------------------------- ### Access Product Data with useSelect Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/stores.md Use the `useSelect` hook to retrieve product data from the `productStore`. This example shows how to get all items and a specific item by ID. ```javascript import { useSelect,resolveSelect } from '@wordpress/data'; import productStore from '@dokan/stores/products'; const App = () => { const products = useSelect( ( select ) => { return select( productStore ).getItems(); }, []); const singleProduct = useSelect( ( select ) => { return select( productStore ).getItem( 1 ); // Get product with ID 1 }, []); ``` -------------------------------- ### Create New Step Class in PHP Source: https://github.com/getdokan/dokan/blob/develop/docs/admin/setup-guide/readme.md Extend the AbstractStep class to define a new step for the Dokan onboarding setup. Configure its ID, priority, skippable status, storage key, and settings options. Implement methods for default settings, asset registration, UI description, and data saving. ```php 'default_value_1', 'option_2' => 'default_value_2', ] ); } /** * Register assets */ public function register(): void { // Register scripts or localize data for current step if needed } /** * Scripts to enqueue */ public function scripts(): array { return []; // Add dependency scripts handler here. } /** * Styles to enqueue */ public function styles(): array { return []; // Add dependency styles handler here. } /** * Define the UI structure for this step */ public function describe_settings(): void { // Get default and current settings $default_settings = $this->get_default_settings(); $current_options = get_option( 'dokan_your_settings_option', $default_settings ); // Define the UI using ComponentFactory $this->set_title( esc_html__( 'Your New Step', 'dokan-lite' ) ) ->add( Factory::section( 'main_section' ) ->set_title( esc_html__( 'Section Title', 'dokan-lite' ) ) ->add( Factory::field( 'option_1', 'text' ) ->set_title( esc_html__( 'Option 1', 'dokan-lite' ) ) ->set_description( esc_html__( 'Description for option 1', 'dokan-lite' ) ) ->set_default( $default_settings['option_1'] ) ->set_value( $current_options['option_1'] ?? $default_settings['option_1'] ) ) // Add more fields as needed ); } /** * Additional settings for frontend */ public function settings(): array { return []; } /** * Save settings when submitted from frontend * * @param mixed $data Data submitted from frontend */ public function option_dispatcher( $data ): void { $default_settings = $this->get_default_settings(); $current_options = get_option( 'dokan_your_settings_option', $default_settings ); // Update settings from submitted data. if ( isset( $data['main_section'] ) ) { $current_options['option_1'] = $data['main_section']['option_1'] ?? $default_settings['option_1']; $current_options['option_2'] = $data['main_section']['option_2'] ?? $default_settings['option_2']; } // Save to database update_option( 'dokan_your_settings_option', $current_options ); } } ``` -------------------------------- ### Install Node Dependencies and Chromium Source: https://github.com/getdokan/dokan/blob/develop/tests/pw/README.md Installs Node.js dependencies and downloads the specific Chromium browser version required by Playwright. ```bash npm install npm run install:chromium ``` -------------------------------- ### Install Chromium Browser for Playwright Source: https://github.com/getdokan/dokan/blob/develop/tests/pw/README.md Installs the Chromium browser required by Playwright. This is necessary when the binary is missing or a version mismatch occurs. ```bash npm run install:chromium ``` -------------------------------- ### Basic ProductAsyncSelect Usage Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/product_asyncselect.md Demonstrates the basic setup for the ProductAsyncSelect component, including state management for the selected product and a placeholder for search input. Ensure `@dokan/components` is registered and WordPress REST API is accessible. ```jsx import { useState } from '@wordpress/element'; import { ProductAsyncSelect } from '@dokan/components'; const Example = () => { const [product, setProduct] = useState(null); return ( ); }; ``` -------------------------------- ### Implement Product Tabs with DokanTab Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/tab.md Example implementation of a product tab interface using the DokanTab component. Requires importing DokanTab and defining tab content components. ```jsx import { DokanTab } from '@dokan/components'; const ProductTabs = () => { const tabs = [ { name: 'general', title: 'General', icon: 'admin-generic' }, { name: 'inventory', title: 'Inventory', icon: 'archive' }, { name: 'shipping', title: 'Shipping', icon: 'cart' } ]; const renderTabContent = (tab) => { switch (tab.name) { case 'general': return ; case 'inventory': return ; case 'shipping': return ; default: return null; } }; return ( { // Handle tab selection console.log('Selected tab:', tabName); }} > {renderTabContent} ); }; ``` -------------------------------- ### Build Frontend Assets Source: https://github.com/getdokan/dokan/blob/develop/DEVELOPER.md Build the frontend assets for production. ```bash npm run build ``` -------------------------------- ### Build Assets for Dokan Pro Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/env-setup.md Commands to build assets for Dokan Pro. Use 'npm run start' for development with watch mode, and 'npm run build' for a production build. ```bash npm run start ``` ```bash npm run build ``` -------------------------------- ### Create Release Zip Source: https://github.com/getdokan/dokan/blob/develop/DEVELOPER.md Creates a product build zip file of Dokan lite. ```bash npm run release ``` -------------------------------- ### Example Filter Implementation with State Management Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/filter.md An example of implementing the Filter component within a table component, managing filter state and handling server requests. Custom filter fields like CustomerFilter and DateFilter are used. ```jsx import { Filter, CustomerFilter, DateFilter } from '@your-package/components'; const MyTableComponent = () => { const [filterArgs, setFilterArgs] = useState({}); const [searchedCustomer, setSearchedCustomer] = useState(null); const handleFilter = () => { // Process request payload through applyFilters const requestPayload = applyFilters('dokan_subscription_filter_request_param', { ...filterArgs, per_page: perPage, page: currentPage, } ); // Make server request with processed payload fetchFilteredData(requestPayload); }; const clearFilter = () => { setFilterArgs({}); setSearchedCustomer(null); }; const handleCustomerSearch = (customer) => { setSearchedCustomer(customer); }; return (
, ]} onFilter={handleFilter} onReset={clearFilter} showFilter={true} showReset={true} namespace="my_table_filters" /> {/* Table component */}
); }; ``` -------------------------------- ### Custom Filter Field Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/filter.md A basic example of a custom filter field component. It manages its own state and updates the parent's filterArgs via props. Ensure it includes a unique 'key' prop when used with the Filter component. ```jsx const CustomFilter = ({ filterArgs, setFilterArgs }) => { const handleChange = (value) => { setFilterArgs({ ...filterArgs, customField: value }); }; return ( handleChange(e.target.value)} /> ); }; ``` -------------------------------- ### AsyncSelect Quick Overview Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/asyncselect.md A basic example demonstrating how to import and use the AsyncSelect component with a custom loadOptions function. Ensure Dokan UI and its dependencies are available in your build. ```jsx import { AsyncSelect } from '@dokan/components'; const loadVendors = async (inputValue) => { // return array of { value, label } const data = await apiFetch( { path: `/wp-json/dokan/v1/stores?search=${encodeURIComponent(inputValue)}`, } ); return Array.isArray(data) ? data.map( s => ({ value: s.id, label: s.store_name || s.name }) ) : []; }; ``` -------------------------------- ### SortableList Component Usage Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/sortable-list.md Example of how to use the SortableList component with its essential props. ```APIDOC ## SortableList Component Usage ### Description This section demonstrates the basic implementation of the `SortableList` component, showcasing its core props for rendering and managing sortable items. ### Component Example ```tsx ``` ### Component Properties #### `SortableList` Props - **items** (array) - Required - The data array to be rendered in the sortable list. Can be an array of single items, array of objects with or without ordering. - **namespace** (string) - Required - Unique identifier for the sortable container. Used for filtering and slots. - **onChange** (function) - Required - Callback function triggered when item order changes. Receives the updated items array as an argument. - **renderItem** (function) - Required - Function to render individual items. Receives the item as an argument. - **orderProperty** (string) - Optional - Property name used to track item order in array of objects. - **strategy** (string) - Optional - Layout strategy for the list. Options are `vertical`, `horizontal`, and `grid`. Default is `vertical`. - **className** (string) - Optional - Additional CSS classes for the container. - **gridColumns** (string) - Optional - Number of columns for grid layout. Default is `4`. - **id** (string | number) - Optional - Unique identifier for the sortable item. Optional property. ``` -------------------------------- ### Check Dokan Plugins, Users, and Modules Source: https://github.com/getdokan/dokan/blob/develop/tests/pw/README.md Use these commands to list active plugins, test users, and count active Dokan modules for environment verification. ```bash npm run check:plugins # lists active plugins npm run check:users # lists test users npm run check:modules # counts active Dokan modules ``` -------------------------------- ### GET /wp-json/dokan/v1/reports/{your-report-type}/export/{export_id}/status Source: https://github.com/getdokan/dokan/blob/develop/docs/export-controller-usage.md Retrieves the current status of an ongoing export process. ```APIDOC ## GET /wp-json/dokan/v1/reports/{your-report-type}/export/{export_id}/status ### Description Checks the progress and status of a previously initiated background export. ### Method GET ### Endpoint `/wp-json/dokan/v1/reports/{your-report-type}/export/{export_id}/status` ### Parameters #### Path Parameters - **export_id** (string) - Required - The unique identifier of the export process. ### Response #### Success Response (200) - **percent_complete** (integer) - The percentage of the export process that has been completed. - **download_url** (string) - The URL to download the exported file. This will be present once the export is complete. #### Response Example ```json { "percent_complete": 100, "download_url": "https://yoursite.com/wp-admin/admin.php?action=woocommerce_admin_download_report_csv&filename=wc-withdraws-report-export-1642534567890" } ``` ``` -------------------------------- ### Create Product with Seller and Custom Details Source: https://github.com/getdokan/dokan/blob/develop/docs/tdd/factories.md Create a product associated with a seller, setting custom details like name and price. Use `set_seller_id` before creating the product. ```php $seller_id = $this->factory()->seller->create(); $product_id = $this->factory()->product ->set_seller_id( $seller_id ) ->create( array( 'name' => 'Test Product', 'regular_price' => '19.99', ) ); $product = wc_get_product( $product_id ); ``` -------------------------------- ### DokanLink Navigation Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/components.md Use DokanLink for creating navigation menus. Ensure the parent element has appropriate spacing classes. ```jsx ``` -------------------------------- ### Register New Step in Service Provider Source: https://github.com/getdokan/dokan/blob/develop/docs/admin/setup-guide/readme.md Include your custom step class in the $services array of the AdminSetupGuideServiceProvider to register it within the Dokan setup flow. Ensure the class is imported at the top of the file. ```php {(tab) =>
Tertiary tab content
}
``` -------------------------------- ### Configure Dokan Appearance Options Source: https://github.com/getdokan/dokan/blob/develop/tests/pw/README.md Set essential Dokan appearance options for the React UI (vendor dashboard, product editor) using wp-cli. This is automatically handled by `docker:setup`. ```bash npm run wp-env run tests-cli wp eval ' $a = get_option("dokan_appearance", []); $a["vendor_layout_style"] = "latest"; $a["vendor_product_editor"] = "latest"; update_option("dokan_appearance", $a); ' ``` -------------------------------- ### Secondary Variant Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/tab.md Renders a tab component with the secondary variant style. Ensure the 'tabs' prop is an array of Tab objects. ```jsx {(tab) =>
Secondary tab content
}
``` -------------------------------- ### Primary Variant Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/tab.md Renders a tab component with the primary variant style. Ensure the 'tabs' prop is an array of Tab objects. ```jsx {(tab) =>
Primary tab content
}
``` -------------------------------- ### Simple Array Sortable List Example Source: https://github.com/getdokan/dokan/blob/develop/docs/frontend/sortable-list.md Use this when your list items are primitive values. Ensure a unique namespace is provided for the component. ```tsx const [ simpleItems, setSimpleItems ] = useState([ __( 'Item 1', 'dokan-lite' ), __( 'Item 2', 'dokan-lite' ), __( 'Item 3', 'dokan-lite' ) ]); const handleOrderUpdate = ( updatedItems ) => { setSimpleItems( [ ...updatedItems ] ); // Update items array. console.log( updatedItems ); // Get updated items array. // Handle any additional logic after order update }; (
{ item }
)} ... /> ```