### Configure Datastar for Hypermedia API WordPress Plugin Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This example demonstrates how to configure the Hypermedia API plugin to use Datastar. It sets Datastar as the active library, loads it from local files, and enables its backend integration. ```php add_filter('hmapi/default_options', function($defaults) { $defaults['active_library'] = 'datastar'; $defaults['load_from_cdn'] = false; $defaults['load_datastar_backend'] = true; return $defaults; }); ``` -------------------------------- ### Install Hypermedia API WordPress Plugin via Composer Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This command installs the Hypermedia API for WordPress plugin as a Composer dependency. It allows developers to integrate the plugin's functionalities into their own themes or plugins without needing to install it separately through WordPress. ```bash composer require estebanforge/hypermedia-api-wordpress ``` -------------------------------- ### Configure HTMX with Common Extensions in WordPress Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This example shows a complete configuration for using HTMX with the Hypermedia API plugin, enabling specific HTMX extensions like debug, loading states, preload, and SSE, and setting `hxboost` for progressive enhancement. It configures the plugin to use local files. ```php add_filter('hmapi/default_options', function($defaults) { $defaults['active_library'] = 'htmx'; $defaults['load_from_cdn'] = false; // Use local files $defaults['load_hyperscript'] = true; $defaults['set_htmx_hxboost'] = true; // Progressive enhancement $defaults['load_htmx_backend'] = true; // Use in admin too // Enable commonly used HTMX extensions $defaults['load_extension_debug'] = true; $defaults['load_extension_loading-states'] = true; $defaults['load_extension_preload'] = true; $defaults['load_extension_sse'] = true; return $defaults; }); ``` -------------------------------- ### PHP Request Validation Examples Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Illustrates various use cases for the `hm_validate_request` function in PHP, including basic nonce validation, validating specific actions, and validating custom data arrays. It also provides an example of real-time form validation using Datastar SSE, demonstrating how to read signals and patch elements/signals based on validation results for email and password fields. ```php // Basic nonce validation (works for all hypermedia libraries) if (!hm_validate_request()) { hm_die('Security check failed'); } // Validate specific action if (!hm_validate_request($_REQUEST, 'delete_post')) { hm_die('Invalid action'); } // Validate custom data array $custom_data = ['action' => 'save_settings', '_wpnonce' => $_POST['_wpnonce']]; if (!hm_validate_request($custom_data, 'save_settings')) { hm_die('Validation failed'); } // Datastar SSE endpoint with real-time validation // hypermedia/validate-form.hm.php $signals = hm_ds_read_signals(); $email = $signals['email'] ?? ''; $password = $signals['password'] ?? ''; // Validate email in real-time if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) { hm_ds_patch_elements('
Valid email required
', ['selector' => '#email-error']); hm_ds_patch_signals(['email_valid' => false]); } else { hm_ds_remove_elements('#email-error'); hm_ds_patch_signals(['email_valid' => true]); } // Validate password strength if (strlen($password) < 8) { hm_ds_patch_elements('
Password must be 8+ characters
', ['selector' => '#password-error']); hm_ds_patch_signals(['password_valid' => false]); } else { hm_ds_remove_elements('#password-error'); hm_ds_patch_signals(['password_valid' => true]); } ``` -------------------------------- ### Integrate Rate Limiting with User Feedback in Hypermedia API Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This example demonstrates how to implement client-side rate limit awareness using HTML attributes and server-side rate limiting logic in PHP for a Hypermedia API. It includes real-time user feedback for requests remaining and rate limit exceeded states, ensuring a robust and user-friendly experience by automatically updating the UI via signals. ```html

Real-time Chat

Rate limit reached. Please wait before sending more messages.
Requests remaining:
``` ```php 10, 'time_window_seconds' => 60, 'identifier' => 'chat_' . get_current_user_id(), 'error_message' => __('Message rate limit exceeded. You can send 10 messages per minute.', 'api-for-htmx'), 'error_selector' => '#chat-errors' ])) { // Rate limit exceeded - user is notified via SSE // The rate limiting helper automatically updates signals and shows error return; } // Get message from signals $signals = hm_ds_read_signals(); $message = trim($signals['message'] ?? ''); // Validate message if (empty($message)) { hm_ds_patch_elements( '
' . esc_html__('Message cannot be empty', 'api-for-htmx') . '
', ['selector' => '#chat-errors'] ); return; } if (strlen($message) > 500) { hm_ds_patch_elements( '
' . esc_html__('Message too long (max 500 characters)', 'api-for-htmx') . '
', ['selector' => '#chat-errors'] ); return; } // Clear any errors hm_ds_remove_elements('#chat-errors .error'); // Save message (example) $user = wp_get_current_user(); $chat_message = [ 'user' => $user->display_name, 'message' => esc_html($message), 'timestamp' => current_time('H:i:s') ]; // Add message to chat $message_html = sprintf( '
%s %s
%s
', $chat_message['user'], $chat_message['timestamp'], $chat_message['message'] ); hm_ds_patch_elements($message_html, [ 'selector' => '#chat-messages', 'mode' => 'append' ]); // Clear input field hm_ds_patch_signals(['message' => '']); // Show success feedback hm_ds_execute_script("\n // Scroll to bottom of chat\n const chatMessages = document.getElementById('chat-messages');\n chatMessages.scrollTop = chatMessages.scrollHeight;\n\n // Brief success indicator\n const input = document.querySelector('[data-bind-message]');\n input.style.borderColor = '#28a745';\n setTimeout(() => { input.style.borderColor = ''; }, 1000);\n"); // The rate limiting helper automatically updates the requests_remaining signal // So the frontend will show the updated count automatically ?> ``` -------------------------------- ### Loading Hypermedia Templates with Custom Namespaces Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This PHP example illustrates how to generate URLs for hypermedia templates that have been registered with a custom namespace. The `hm_get_endpoint_url()` function is used, prefixing the template name with the registered namespace and a colon (e.g., 'my-plugin:template-name') to specify the template's location within the custom path. ```php // Loads the template from: YOUR_PLUGIN_PATH/hypermedia/template-name.hm.php echo hm_get_endpoint_url( 'my-plugin:template-name' ); // Loads the template from: YOUR_PLUGIN_PATH/hypermedia/parts/header.hm.php echo hm_get_endpoint_url( 'my-plugin:parts/header' ); ``` -------------------------------- ### Redirect Browser via Datastar SSE in PHP Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Redirects the client's browser to a new URL using Server-Sent Events. This function provides a way to initiate client-side navigation from the server, useful for post-processing redirects or guiding users to different pages after an action. It supports both internal and external URLs. ```php // Redirect after processing hm_ds_location('/dashboard'); // Redirect to external URL hm_ds_location('https://example.com/success'); ``` -------------------------------- ### PHP Conditional Logic based on WordPress Library Mode Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Demonstrates how to use `hm_is_library_mode` in PHP to apply conditional configurations and actions. Examples include configuring default options via filters when the plugin is used as a Composer library (e.g., setting active hypermedia library, CDN loading, backend loading) and adding WordPress-specific actions like admin menus or inline scripts when it's running as a full plugin. ```php if (hm_is_library_mode()) { // Running as composer library - no admin interface // Configure via filters only add_filter('hmapi/default_options', function($defaults) { $defaults['active_library'] = 'htmx'; return $defaults; }); } else { // Running as WordPress plugin - full functionality available add_action('admin_menu', 'my_admin_menu'); } // Datastar-specific library mode configuration if (hm_is_library_mode()) { // Configure Datastar for production use as library add_filter('hmapi/default_options', function($defaults) { $defaults['active_library'] = 'datastar'; $defaults['load_from_cdn'] = false; // Use local files for reliability $defaults['load_datastar_backend'] = true; // Enable in wp-admin return $defaults; }); // Register custom SSE endpoints for the plugin using this library add_filter('hmapi/register_template_path', function($paths) { $paths['my-plugin'] = plugin_dir_path(__FILE__) . 'datastar-templates/'; return $paths; }); } else { // Plugin mode - users can configure via admin interface // Add custom Datastar functionality only when running as main plugin add_action('wp_enqueue_scripts', function() { if (get_option('hmapi_active_library') === 'datastar') { wp_add_inline_script('datastar', 'console.log("Datastar ready for SSE!");'); } }); } ``` -------------------------------- ### Disable Hypermedia API Admin Interface and Configure Programmatically Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This PHP snippet shows how to completely disable the Hypermedia API plugin's admin interface by defining the `HMAPI_LIBRARY_MODE` constant. It also illustrates how to configure default options programmatically using the `hmapi/default_options` filter when the admin UI is hidden, allowing for headless or programmatic setups. ```php // In wp-config.php or a custom plugin file define('HMAPI_LIBRARY_MODE', true); // You can then configure the plugin using filters as needed add_filter('hmapi/default_options', function($defaults) { // Your configuration here. See above for examples. return $defaults; }); ``` -------------------------------- ### Production-Ready HTMX Configuration with CDN and Extensions Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This snippet provides a production-optimized configuration for HTMX, loading it from a CDN for better performance. It enables `hxboost` and includes essential extensions like loading states, preload, and response targets. ```php add_filter('hmapi/default_options', function($defaults) { $defaults['active_library'] = 'htmx'; $defaults['load_from_cdn'] = true; // Better performance $defaults['load_hyperscript'] = true; $defaults['set_htmx_hxboost'] = true; // Enable production-useful extensions $defaults['load_extension_loading-states'] = true; $defaults['load_extension_preload'] = true; $defaults['load_extension_response-targets'] = true; return $defaults; }); ``` -------------------------------- ### PHP Backend for User Search Execution with Rate Limiting Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This PHP template executes the user search operation. It enforces rate limiting, retrieves the search query from Datastar signals, and simulates a delay before performing a WordPress user search. It then constructs HTML for the search results and uses `hm_ds_patch_elements` and `hm_ds_patch_signals` to update the frontend with results, loading states, and notifications, demonstrating dynamic UI updates via SSE. ```php 20, 'time_window_seconds' => 60, 'identifier' => 'user_search_' . get_current_user_id(), 'error_message' => __('Search rate limit exceeded. Please wait before searching again.', 'api-for-htmx'), 'error_selector' => '#search-errors' ])) { // Rate limit exceeded - error already sent to client via SSE return; } // Get search parameters $signals = hm_ds_read_signals(); $query = sanitize_text_field($signals['query'] ?? ''); // Set loading state hm_ds_patch_signals(['loading' => true, 'results' => []]); hm_ds_patch_elements('
Searching users...
', ['selector' => '#search-results']); // Simulate search delay usleep(500000); // 0.5 seconds // Perform user search (example with WordPress users) $users = get_users([ 'search' => '*' . $query . '*', 'search_columns' => ['user_login', 'user_email', 'display_name'], 'number' => 10 ]); // Build results HTML $results_html = '
'; $results_data = []; foreach ($users as $user) { $results_data[] = [ 'id' => $user->ID, 'name' => $user->display_name, 'email' => $user->user_email ]; $results_html .= sprintf( '
%s (%s)
', $user->ID, esc_html($user->display_name), esc_html($user->user_email), hm_get_endpoint_url('user-details'), $user->ID ); } $results_html .= '
'; // Update UI with results if (count($users) > 0) { hm_ds_patch_elements($results_html, ['selector' => '#search-results']); hm_ds_patch_signals([ 'loading' => false, 'results' => $results_data, 'result_count' => count($users) ]); // Show success notification hm_ds_execute_script(" const notification = document.createElement('div'); notification.className = 'notification success'; notification.textContent = 'Found " . count($users) . " users'; document.body.appendChild(notification); setTimeout(() => notification.remove(), 3000); "); } else { hm_ds_patch_elements('
No users found for \"' . esc_html($query) . '\"
', ['selector' => '#search-results']); hm_ds_patch_signals(['loading' => false, 'results' => []]); } ?> ``` -------------------------------- ### Consuming Server-Sent Events (SSE) with Datastar in HTML Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Client-side HTML structure to consume a Datastar SSE endpoint. It shows how to set initial signal values with `data-signals-delay`, bind signals to form inputs using `data-bind-delay`, and trigger the SSE stream with a button click via `data-on-click`. ```html

Datastar SDK Demo

SSE events will be streamed from the backend to the frontend.

Hello, world!
``` -------------------------------- ### Implementing Server-Sent Events (SSE) with Datastar in PHP Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Server-side PHP implementation for a Datastar SSE endpoint. It demonstrates rate limiting (`hm_ds_is_rate_limited`), SSE initialization (`hm_ds_sse`), reading client signals (`hm_ds_read_signals`), and streaming messages character by character using `hm_ds_patch_elements` for real-time updates. ```php // In your hypermedia template file, e.g., hypermedia/my-sse-endpoint.hm.php // Apply rate limiting for SSE endpoint if (hm_ds_is_rate_limited()) { return; // Rate limited } // Initialize SSE (headers are sent automatically) $sse = hm_ds_sse(); if (!$sse) { hm_die('SSE not available'); } // Read client signals $signals = hm_ds_read_signals(); $delay = $signals['delay'] ?? 0; $message = 'Hello, world!'; // Stream message character by character for ($i = 0; $i < strlen($message); $i++) { hm_ds_patch_elements('
' . substr($message, 0, $i + 1) . '
'); // Sleep for the provided delay in milliseconds usleep($delay * 1000); } // Script will automatically exit and send the SSE stream ``` -------------------------------- ### Datastar Frontend for Live User Search Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This HTML snippet defines the frontend structure for a live user search application using Datastar. It includes an input field for the search query, a search button, and containers for displaying search results and validation messages. Datastar attributes handle binding, event triggers, and conditional display based on signals like `query`, `results`, and `loading`. ```html

User Search

No users found
``` -------------------------------- ### Initialize Datastar SSE Generator in PHP Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Retrieves or creates the ServerSentEventGenerator instance for Datastar. This function is crucial for enabling real-time communication via Server-Sent Events. It returns null if the Datastar SDK is not available, requiring a check before proceeding with SSE operations. ```php $sse = hm_ds_sse(); if ($sse) { // SSE is available, proceed with real-time updates $sse->patchElements('
Connected
'); } ``` -------------------------------- ### Managing Hypermedia Libraries with NPM Scripts Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Bash commands for updating hypermedia libraries (HTMX, Alpine.js, Hyperscript, Datastar) using npm scripts. These scripts ensure local development environments are synchronized with the latest library versions, facilitating consistent development. ```bash # Update all libraries npm run update-all # Update specific library npm run update-htmx npm run update-alpinejs npm run update-hyperscript npm run update-datastar npm run update-all ``` -------------------------------- ### Datastar SSE Rate Limiting Options Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Configuration options for the `hm_ds_is_rate_limited()` function, allowing fine-grained control over rate limiting behavior. These options define the window, request limits, identification, and client feedback mechanisms. ```APIDOC hm_ds_is_rate_limited(array $options = []): bool - Checks if current request is rate limited for Datastar SSE endpoints. - Parameters (options array): - requests_per_window (int): Maximum requests allowed per time window. Default: 10 - time_window_seconds (int): Time window in seconds. Default: 60 - identifier (string): Custom identifier for rate limiting. Default: IP + user ID - send_sse_response (bool): Send SSE error response when rate limited. Default: true - error_message (string): Custom error message. Default: translatable 'Rate limit exceeded...' - Returns: bool - True if rate limited, false otherwise. ``` -------------------------------- ### Basic Full Viewport CSS Styling Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/src/Admin/index.html This CSS snippet provides fundamental styling for HTML and body elements, setting padding and margin to zero, hiding overflow, and ensuring they occupy the full viewport height and width. It also applies the same full viewport dimensions to iframes, making them fill the entire screen without scrollbars. ```CSS html, body { padding: 0; margin: 0; overflow: hidden; height: 100vh; width: 100vw; } iframe { height: 100vh; width: 100vw; } ``` -------------------------------- ### Using No-Swap Hypermedia Templates for Background Processing Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Illustrates API endpoints for 'no-swap' templates, which perform server-side processing without returning HTML. These templates are loaded from the `hypermedia/noswap` folder and can still send HTTP responses, useful for actions like saving or deleting data. ```APIDOC /wp-html/v1/noswap/save-user?user_id=5&name=John&last_name=Doe /wp-html/v1/noswap/delete-user?user_id=5 ``` -------------------------------- ### API Documentation: Hypermedia API Filters and Functions Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This section provides comprehensive API documentation for key filters and functions provided by the Hypermedia API for WordPress. It covers how to register custom template paths, generate endpoint URLs for hypermedia templates, and programmatically detect if the library is running in standalone or library mode. ```APIDOC Filter: hmapi/register_template_path - Purpose: Allows registration of custom template directories for hypermedia templates. - Parameters: - $paths (array): An associative array where keys are chosen namespaces (string) and values are absolute paths (string) to template directories. - Returns: (array) The modified array of template paths. - Usage: Add a filter callback to append new paths to the existing array. Function: hm_get_endpoint_url( $template_path ) - Purpose: Generates a URL for a specified hypermedia template. - Parameters: - $template_path (string): The path to the template. Can include a namespace prefix (e.g., 'my-plugin:template-name') or be a direct path within the theme's hypermedia directory. - Returns: (string) The generated URL for the template. - Behavior: - If a namespace is used, the template is loaded from the registered path for that namespace. No fallback to theme directory. - If no namespace is used, the template is loaded from the active theme's `hypermedia` directory. - Returns 404 if the namespace is not registered, the template file does not exist, or is not allowed. Function: hm_is_library_mode() - Purpose: Detects if the Hypermedia API is running as a Composer library (not an active plugin). - Parameters: None. - Returns: (bool) True if running in library mode, false otherwise. - Behavior: Determined automatically based on plugin activation status and admin area context. When true, the plugin's admin options page is not registered. ``` -------------------------------- ### Generate Hypermedia API Endpoint URLs in WordPress Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Provides functions to generate and output full URLs for hypermedia templates within a WordPress environment. Automatically handles the `/wp-html/v1/` prefix and proper URL formatting. Useful for linking to hypermedia endpoints in frontend frameworks like HTMX, Datastar, and Alpine Ajax. ```APIDOC hm_get_endpoint_url(string $template_path = ''): string - Generates the full URL for your hypermedia templates. - Parameters: - $template_path: (string, optional) The path to the hypermedia template (e.g., 'live-search', 'admin/user-list', 'my-plugin:dashboard/stats'). - Returns: (string) The full URL for the endpoint. - Usage Examples: // Basic usage echo hm_get_endpoint_url('live-search'); // Output: http://your-site.com/wp-html/v1/live-search // With subdirectories echo hm_get_endpoint_url('admin/user-list'); // Output: http://your-site.com/wp-html/v1/admin/user-list // With namespaced templates (plugin/theme specific) echo hm_get_endpoint_url('my-plugin:dashboard/stats'); // Output: http://your-site.com/wp-html/v1/my-plugin:dashboard/stats hm_endpoint_url(string $template_path = ''): void - Same as hm_get_endpoint_url() but echoes the result directly. - Parameters: - $template_path: (string, optional) The path to the hypermedia template. - Returns: (void) Echoes the URL directly. - Usage Examples: // HTMX usage
Loading...
// Datastar usage
Load Profile
// Alpine Ajax usage
Refresh Stats
``` -------------------------------- ### Read Datastar Client Signals in PHP Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Reads signals sent from the Datastar client, allowing the server to react to client-side state or user input. It returns an associative array of signals, or an empty array if the Datastar SDK is not present. This enables dynamic server-side processing based on client data. ```php // Read client signals $signals = hm_ds_read_signals(); $user_input = $signals['search_query'] ?? ''; $page_number = $signals['page'] ?? 1; // Use signals for processing if (!empty($user_input)) { $results = search_posts($user_input, $page_number); hm_ds_patch_elements($results_html, ['selector' => '#results']); } ``` -------------------------------- ### Basic CSS for Full Viewport Styling Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/includes/index.html This CSS snippet provides fundamental styling for HTML and body elements, along with iframes, to ensure they occupy the full viewport height and width. It resets default padding and margin, prevents content overflow, and is suitable for single-page applications or embedded content that needs to fill the entire screen. ```CSS html, body { padding: 0; margin: 0; overflow: hidden; height: 100vh; width: 100vw; } iframe { height: 100vh; width: 100vw; } ``` -------------------------------- ### Configure Alpine.js for AJAX with WordPress Plugin Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This snippet configures the Hypermedia API plugin to use Alpine.js for AJAX functionality. It sets Alpine.js as the active library, loads it from a CDN for the latest version, and enables its backend integration. ```php add_filter('hmapi/default_options', function($defaults) { $defaults['active_library'] = 'alpinejs'; $defaults['load_from_cdn'] = true; // Use CDN for latest version $defaults['load_alpinejs_backend'] = true; return $defaults; }); ``` -------------------------------- ### Loading Hypermedia Templates from Theme Directory Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This PHP snippet demonstrates how to generate URLs for hypermedia templates located directly within the active WordPress theme's `hypermedia` directory. When no namespace is provided to `hm_get_endpoint_url()`, the function defaults to searching for the template within the theme's designated hypermedia folder. ```php // Loads: wp-content/themes/your-theme/hypermedia/live-search.hm.php echo hm_get_endpoint_url( 'live-search' ); // Loads: wp-content/themes/your-theme/hypermedia/subfolder/my-listing.hm.php echo hm_get_endpoint_url( 'subfolder/my-listing' ); ``` -------------------------------- ### Basic CSS for Full Viewport Layout and Reset Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/src/index.html This CSS snippet provides a fundamental reset for padding and margin on `html` and `body` elements. It ensures both elements, along with any `iframe`, occupy the full height and width of the viewport, effectively creating a full-screen layout. The `overflow: hidden;` property prevents scrollbars. ```CSS html, body { padding: 0; margin: 0; overflow: hidden; height: 100vh; width: 100vw; } iframe { height: 100vh; width: 100vw; } ``` -------------------------------- ### Passing Data to Hypermedia Templates via URL Parameters Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Demonstrates how to pass data to hypermedia templates using URL query parameters for GET/POST requests. The parameters become available as an `$hmvals` array within the template, enabling dynamic content generation. ```APIDOC /wp-html/v1/live-search?search=hello /wp-html/v1/related-posts?category_id=5 ``` -------------------------------- ### Basic CSS for Full-Screen Viewport Layout Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/hypermedia/noswap/index.html This CSS snippet defines styles for `html`, `body`, and `iframe` elements to ensure they fill the entire viewport. It removes default padding and margins, hides overflow, and sets dimensions to 100% of the viewport height and width, commonly used for full-page applications or embedded content. ```css html, body { padding: 0; margin: 0; overflow: hidden; height: 100vh; width: 100vw; } iframe { height: 100vh; width: 100vw; } ``` -------------------------------- ### PHP Backend for Real-time Search Query Validation Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This PHP template handles real-time validation of the search query. It applies rate limiting, reads the query from Datastar signals, and validates its length. Based on validation, it uses `hm_ds_patch_elements` to display error messages or hints and `hm_ds_patch_signals` to update the `query_valid` signal, providing immediate feedback to the frontend. ```php 0) { hm_ds_patch_elements( '
Please enter at least 2 characters
', ['selector' => '#search-validation'] ); hm_ds_patch_signals(['query_valid' => false]); } elseif (strlen($query) >= 2) { hm_ds_remove_elements('#search-validation .validation-error'); hm_ds_patch_signals(['query_valid' => true]); // Show search suggestion hm_ds_patch_elements( '
Press Enter or click Search to find users
', ['selector' => '#search-validation'] ); } ?> ``` -------------------------------- ### Execute Client-Side JavaScript via Datastar SSE in PHP Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Sends JavaScript code to the client for immediate execution via Server-Sent Events. This provides a powerful mechanism for triggering complex client-side operations or interacting with the browser's DOM directly from the server. It's useful for scenarios requiring dynamic client-side logic. ```php // Simple script execution hm_ds_execute_script('console.log("Server says hello!");'); // Complex client-side operations hm_ds_execute_script(' document.querySelector("#progress").style.width = "100%"; setTimeout(() => { location.reload(); }, 2000); '); ``` -------------------------------- ### Access Hypermedia Templates via WordPress API Endpoint Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This section details the API endpoints used to access and load hypermedia templates. Developers can make GET/POST requests to these URLs, corresponding to their template files, to retrieve the rendered hypermedia content without specifying the file extension. ```APIDOC Endpoint: /wp-html/v1/ Usage: GET /wp-html/v1/live-search GET /wp-html/v1/related-posts GET /wp-html/v1/private/author GET /wp-html/v1/private/author-posts Description: Accesses a hypermedia template by its path relative to the 'hypermedia' folder in your theme, without the '.hm.php' extension. Supports both GET and POST requests for loading template content. ``` -------------------------------- ### Apply Full Viewport CSS to HTML, Body, and iFrame Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/assets/js/index.html This CSS snippet ensures that the `html`, `body`, and `iframe` elements take up 100% of the viewport height and width. It removes default padding and margin, and hides any overflow, making it suitable for full-page applications or embedded content. ```css html, body { padding: 0; margin: 0; overflow: hidden; height: 100vh; width: 100vw; } iframe { height: 100vh; width: 100vw; } ``` -------------------------------- ### Apply Full-Screen CSS Reset and Iframe Styling Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/index.html This CSS snippet provides a basic reset for `html` and `body` elements, removing default padding and margin, and setting them to occupy the full viewport. It also styles an `iframe` to fill the entire screen, ensuring a full-page display without scrollbars. ```css html, body { padding: 0; margin: 0; overflow: hidden; height: 100vh; width: 100vw; } iframe { height: 100vh; width: 100vw; } ``` -------------------------------- ### Basic Full-Viewport CSS Styling Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/assets/index.html This CSS snippet applies fundamental styling to the html, body, and iframe elements. It removes default padding and margins, hides overflow, and sets their dimensions to 100% of the viewport height and width, commonly used for full-page applications or embedded content. ```css html, body { padding: 0; margin: 0; overflow: hidden; height: 100vh; width: 100vw; } iframe { height: 100vh; width: 100vw; } ``` -------------------------------- ### Patch HTML Elements via Datastar SSE in PHP Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Sends HTML content to the client to patch elements in the DOM using Server-Sent Events. This function supports various patching modes (e.g., append, prepend, replace) and can optionally utilize view transitions for smoother UI updates. It's a core function for dynamic content delivery. ```php // Basic element patching hm_ds_patch_elements('
Hello World
'); // Advanced patching with options hm_ds_patch_elements( '
Task completed
', [ 'selector' => '.notifications', 'mode' => 'append', 'useViewTransition' => true ] ); ``` -------------------------------- ### Hypermedia API WordPress REST Endpoint Security and Sanitization Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Documentation for the `wp-html` REST endpoint, detailing its automatic nonce validation, basic sanitization of GET/POST parameters, and access limitations. It also lists the available filters (`hmapi/sanitize_param_key`, `hmapi/sanitize_param_value`, `hmapi/sanitize_param_array_value`) for custom sanitization logic. ```APIDOC Endpoint: wp-html Description: The primary REST endpoint for Hypermedia API requests. Security: - Nonce Validation: Automatically checks for a valid nonce. Requests are rejected if the nonce is invalid. The nonce is auto-generated and added to all Hypermedia requests. Sanitization: - Basic Sanitization: Performs basic sanitization of calls to prevent security issues like directory traversal attacks. - Access Limitation: Limits access to files exclusively within the 'hypermedia' folder of your theme. - Parameter Sanitization: - Parameter Keys (GET/POST): Sanitized using WordPress's `sanitize_key()` function. - Parameter Values (GET/POST): Sanitized using WordPress's `sanitize_text_field()` function. Customization Filters: - hmapi/sanitize_param_key (string $sanitized_key, string $original_key): - Purpose: Allows modification of the sanitization process for parameter keys. - Parameters: - $sanitized_key: The key after default sanitization. - $original_key: The original, unsanitized key. - hmapi/sanitize_param_value (mixed $sanitized_value, mixed $original_value): - Purpose: Allows modification of the sanitization process for single parameter values. - Parameters: - $sanitized_value: The value after default sanitization. - $original_value: The original, unsanitized value. - hmapi/sanitize_param_array_value (array $sanitized_array, array $original_array): - Purpose: Allows modification of the sanitization process for array parameter values. - Parameters: - $sanitized_array: The array after default sanitization. - $original_array: The original, unsanitized array. - Deprecated Filters: `hxwp/sanitize_param_key`, `hxwp/sanitize_param_value` (supported for backward compatibility). Developer Responsibility: Developers are responsible for validating and sanitizing any data received from the user and ensuring unsanitized data is not returned or used in a way that could pose a security issue for the site. ``` -------------------------------- ### Define Hypermedia Template File Structure in WordPress Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This snippet illustrates the recommended directory structure and naming convention for hypermedia templates within a WordPress theme. Templates must reside in a 'hypermedia' folder at the theme's root and end with the '.hm.php' extension to be recognized by the plugin. ```php hypermedia/live-search.hm.php hypermedia/related-posts.hm.php hypermedia/private/author.hm.php hypermedia/private/author-posts.hm.php ``` -------------------------------- ### Apply Fullscreen Styles to HTML, Body, and Iframe Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/hypermedia/index.html This CSS snippet applies basic styling to the `html`, `body`, and `iframe` elements to ensure they fill the entire viewport. It removes default padding and margins, hides overflow, and sets height and width to 100% of the viewport dimensions, commonly used for embedding content or creating full-page layouts. ```css html, body { padding: 0; margin: 0; overflow: hidden; height: 100vh; width: 100vw; } iframe { height: 100vh; width: 100vw; } ``` -------------------------------- ### Manage Hypermedia API Responses and Termination Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Functions for handling hypermedia-compatible responses and gracefully terminating script execution in a WordPress hypermedia API. `hm_send_header_response` is for non-visual actions, sending data via headers, while `hm_die` provides a controlled termination with error information. ```APIDOC hm_send_header_response(array $data = [], string $action = null): void - Sends hypermedia-compatible header responses for non-visual actions. - Automatically validates nonces and terminates execution. - Parameters: - $data: (array, optional) An associative array of data to send in headers (e.g., 'status', 'message', 'user_id'). - $action: (string, optional) An action identifier for nonce validation. - Returns: (void) Terminates script execution after sending headers. - Usage Examples: // Success response (works with HTMX/Alpine Ajax) hm_send_header_response([ 'status' => 'success', 'message' => 'User saved successfully', 'user_id' => 123 ], 'save_user'); // Error response hm_send_header_response([ 'status' => 'error', 'message' => 'Invalid email address' ], 'save_user'); // Silent success (no user notification) hm_send_header_response([ 'status' => 'silent-success', 'data' => ['updated_count' => 5] ]); // For Datastar SSE endpoints, use the ds helpers instead: // hypermedia/save-user-sse.hm.php // Get user data from Datastar signals $signals = hm_ds_read_signals(); $user_data = $signals; // Signals contain the form data $result = save_user($user_data); if ($result['success']) { // Update UI with success state hm_ds_patch_elements('
User saved!
', ['selector' => '#message']); hm_ds_patch_signals(['user_saved' => true, 'user_id' => $result['user_id']]); } else { // Show error message hm_ds_patch_elements('
Save failed: ' . $result['error'] . '
', ['selector' => '#message']); hm_ds_patch_signals(['user_saved' => false, 'error' => $result['error']]); } hm_die(string $message = '', bool $display_error = false): void - Terminates template execution with a 200 status code (allowing hypermedia libraries to process the response) and sends error information via headers. - Parameters: - $message: (string, optional) The error message to send. - $display_error: (bool, optional) If true, the error message is intended to be displayed to the user. - Returns: (void) Terminates script execution. - Usage Examples: // Die with hidden error message hm_die('Database connection failed'); // Die with visible error message hm_die('Please fill in all required fields', true); ``` -------------------------------- ### Implement Rate Limiting for Datastar SSE in PHP Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md Checks if the current request is rate-limited for Datastar SSE endpoints, preventing abuse and protecting server resources. It uses WordPress transients for persistence and supports custom configurations for requests per window, time window, and identifiers. This function can also send SSE error responses to the client. ```php // Basic rate limiting (10 requests per 60 seconds) if (hm_ds_is_rate_limited()) { hm_die(__('Rate limit exceeded', 'api-for-htmx')); } // Custom rate limiting configuration if (hm_ds_is_rate_limited([ 'requests_per_window' => 30, // Allow 30 requests 'time_window_seconds' => 120, // Per 2 minutes 'identifier' => 'search_' . get_current_user_id(), // Custom identifier 'error_message' => __('Search rate limit exceeded. Please wait.', 'api-for-htmx'), 'error_selector' => '#search-errors' ])) { // Rate limit exceeded - SSE error already sent to client return; } // Strict rate limiting without SSE feedback if (hm_ds_is_rate_limited([ 'requests_per_window' => 10, 'time_window_seconds' => 60, 'send_sse_response' => false // Don't send SSE feedback ])) { hm_die(__('Too many requests', 'api-for-htmx')); } // Different rate limits for different actions $action = hm_ds_read_signals()['action'] ?? ''; switch ($action) { case 'search': $rate_config = ['requests_per_window' => 20, 'time_window_seconds' => 60]; break; case 'upload': $rate_config = ['requests_per_window' => 5, 'time_window_seconds' => 300]; break; default: $rate_config = ['requests_per_window' => 30, 'time_window_seconds' => 60]; } if (hm_ds_is_rate_limited($rate_config)) { return; // Rate limited } ``` -------------------------------- ### Deprecated Functions for Hypermedia API Backward Compatibility Source: https://github.com/estebanforge/hypermedia-api-wordpress/blob/main/README.md This section lists functions that are deprecated in the Hypermedia API and their recommended replacements. While these functions are still available for backward compatibility, it is strongly advised to use their modern counterparts in new development to ensure future compatibility and adherence to best practices. ```APIDOC Deprecated Functions: hxwp_api_url() - Replaced by: hm_get_endpoint_url() - Description: Retrieves the URL for an API endpoint. hxwp_send_header_response() - Replaced by: hm_send_header_response() - Description: Sends an HTTP header response. hxwp_die() - Replaced by: hm_die() - Description: Terminates script execution with a message. hxwp_validate_request() - Replaced by: hm_validate_request() - Description: Validates an incoming API request. ```