### 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 (
);
};
// 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()}
>
);
};
```
--------------------------------
### 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 (
}
```
--------------------------------
### 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
};
(