-
Notifications
You must be signed in to change notification settings - Fork 26
Create reference docs for client-side API #87
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jonathanbossenger
wants to merge
5
commits into
trunk
Choose a base branch
from
docs/javascript-client
base: trunk
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+187
−0
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
af1ad61
AI generated docs
jonathanbossenger 775312a
Re-adding the package readme which was incorrectly deleted
jonathanbossenger f45c9d1
Focus on core API and examples
jonathanbossenger 818224d
Updates to API examples
jonathanbossenger 54849b9
Fix indenting issue
jonathanbossenger File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,186 @@ | ||
# 7. JavaScript/TypeScript Client | ||
|
||
The JavaScript client provides an interface for discovering and executing WordPress Abilities from the browser. | ||
|
||
## Overview | ||
|
||
The JavaScript client enables frontend code to interact with the Abilities API system. It can: | ||
|
||
- Discover all registered abilities on your WordPress site | ||
- Execute server-side PHP abilities | ||
- Register and execute client-side JavaScript abilities | ||
|
||
You can read more about installation and setup in the [package readme](../packages/client/README.md). | ||
|
||
## Core API Functions | ||
|
||
### getAbilities() | ||
|
||
Returns an array of all registered abilities (both server-side and client-side). | ||
|
||
**Parameters:** None | ||
|
||
**Returns:** `Promise<Array>` - Array of ability objects | ||
|
||
**Example:** | ||
|
||
```javascript | ||
const abilities = await getAbilities(); | ||
console.log(`Found ${abilities.length} abilities`); | ||
|
||
// List all abilities | ||
abilities.forEach(ability => { | ||
console.log(`${ability.name}: ${ability.description}`); | ||
}); | ||
``` | ||
|
||
### getAbility(name) | ||
|
||
Retrieves a specific ability by name. | ||
|
||
**Parameters:** | ||
- `name` (string) - The ability name (e.g., 'my-plugin/get-posts') | ||
|
||
**Returns:** `Promise<Object|null>` - The ability object or null if not found | ||
|
||
**Example:** | ||
|
||
```javascript | ||
const ability = await getAbility('my-plugin/get-site-info'); | ||
if (ability) { | ||
console.log('Label:', ability.label); | ||
console.log('Description:', ability.description); | ||
console.log('Input Schema:', ability.input_schema); | ||
} | ||
``` | ||
|
||
### executeAbility(name, input) | ||
|
||
Executes an ability with the provided input data. | ||
|
||
**Parameters:** | ||
- `name` (string) - The ability name | ||
- `input` (object, optional) - Input data for the ability | ||
|
||
**Returns:** `Promise<any>` - The ability's output | ||
|
||
**Example:** | ||
|
||
```javascript | ||
// Execute without input | ||
const siteTitle = await executeAbility('my-plugin/get-site-title'); | ||
console.log('Site:', siteTitle); | ||
|
||
// Execute with input parameters | ||
const posts = await executeAbility('my-plugin/get-posts', { | ||
category: 'news', | ||
limit: 5 | ||
}); | ||
posts.forEach(post => console.log(post.title)); | ||
``` | ||
|
||
### registerAbility(ability) | ||
|
||
Registers a client-side ability that runs in the browser. | ||
|
||
**Parameters:** | ||
- `ability` (object) - The ability configuration object | ||
|
||
**Returns:** `void` | ||
|
||
**Example:** | ||
|
||
```javascript | ||
// showNotification function | ||
const showNotification = (message) => { | ||
new Notification(message); | ||
return { success: true, displayed: message }; | ||
} | ||
|
||
// Register a notification ability which calls the showNotification function | ||
registerAbility({ | ||
name: 'my-plugin/show-notification', | ||
label: 'Show Notification', | ||
description: 'Display a notification message to the user', | ||
input_schema: { | ||
type: 'object', | ||
properties: { | ||
message: { type: 'string' }, | ||
type: { type: 'string', enum: ['success', 'error', 'warning', 'info'] } | ||
}, | ||
required: ['message'] | ||
}, | ||
callback: async ({ message, type = 'info' }) => { | ||
// Show browser notification | ||
if (!("Notification" in window)) { | ||
alert("This browser does not support desktop notification"); | ||
return { success: false, error: 'Browser does not support notifications' }; | ||
} | ||
if (Notification.permission !== 'granted') { | ||
Notification.requestPermission().then((permission) => { | ||
if (permission === "granted") { | ||
return showNotification(message); | ||
} | ||
}); | ||
} | ||
return showNotification(message); | ||
}, | ||
permissionCallback: () => { | ||
return !!wp.data.select('core').getCurrentUser(); | ||
} | ||
}); | ||
|
||
// Use the registered ability | ||
const result = await executeAbility('my-plugin/show-notification', { | ||
message: 'Hello World!', | ||
type: 'success' | ||
}); | ||
``` | ||
|
||
### unregisterAbility(name) | ||
|
||
Removes a previously registered client-side ability. | ||
|
||
**Parameters:** | ||
- `name` (string) - The ability name to unregister | ||
|
||
**Returns:** `boolean` - True if the ability was found and removed | ||
|
||
**Example:** | ||
|
||
```javascript | ||
// Unregister an ability | ||
const wasRemoved = unregisterAbility('my-plugin/old-ability'); | ||
if (wasRemoved) { | ||
console.log('Ability successfully removed'); | ||
} | ||
|
||
// Check if ability is gone | ||
const ability = await getAbility('my-plugin/old-ability'); | ||
console.log('Ability exists:', ability !== null); | ||
``` | ||
|
||
## Error Handling | ||
|
||
All functions return promises that may reject with specific error codes: | ||
|
||
```javascript | ||
try { | ||
const result = await executeAbility('my-plugin/restricted-action', input); | ||
console.log('Success:', result); | ||
} catch (error) { | ||
switch (error.code) { | ||
case 'ability_permission_denied': | ||
console.error('Permission denied:', error.message); | ||
break; | ||
case 'ability_invalid_input': | ||
console.error('Invalid input:', error.message); | ||
break; | ||
case 'rest_ability_not_found': | ||
console.error('Ability not found:', error.message); | ||
break; | ||
default: | ||
console.error('Execution failed:', error.message); | ||
} | ||
} | ||
``` |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.