Skip to content

Commit be0c467

Browse files
committed
Refactor Next.js toolbar demo setup and docs
Simplifies environment setup by removing custom scripts and shell files, updating package.json scripts, and standardizing port usage to 8888 for WordPress. The README is rewritten for clarity, providing step-by-step instructions and improved documentation. Updates dependencies and example environment files to match the new configuration.
1 parent 218c386 commit be0c467

File tree

6 files changed

+146
-171
lines changed

6 files changed

+146
-171
lines changed
Lines changed: 137 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,35 @@
1-
# Toolbar Demo - React Hooks
1+
# Next.js Toolbar Demo
22

3-
React hooks example with Next.js App Router demonstrating the Headless WordPress Toolbar.
3+
In this example we show how to integrate the Headless WordPress Toolbar into a Next.js application using React hooks and WordPress backend using WPGraphQL.
44

5-
## Features
6-
7-
- React hooks (`useToolbar`, `useToolbarState`, `useToolbarNodes`)
8-
- Next.js App Router (App Directory)
9-
- TypeScript
10-
- Framework-agnostic state management
11-
- WordPress context integration
5+
## Getting Started
126

13-
## Quick Start
7+
> [!IMPORTANT]
8+
> Docker Desktop needs to be installed to run WordPress locally.
149
15-
```bash
16-
# Install dependencies (from monorepo root)
17-
pnpm install
10+
1. Create a `.env.local` file in the `examples/next/toolbar-demo` directory with the following content:
11+
```
12+
NEXT_PUBLIC_WP_URL=http://localhost:8888
13+
```
14+
2. Run `npm run example:setup` to install dependencies and configure the local WP server.
15+
3. Run `npm run example:start` to start the WP server and Next.js development server.
1816

19-
# Start WordPress (from this directory)
20-
npx wp-env start
2117

22-
# Start Next.js dev server (from example-app directory)
23-
cd example-app
24-
pnpm dev
25-
```
18+
>[!NOTE]
19+
> Port 8888 is the default port for wp-env.
2620
27-
Open:
28-
- Next.js App: [http://localhost:3001](http://localhost:3001)
29-
- WordPress Admin: [http://localhost:8001/wp-admin](http://localhost:8001/wp-admin)
30-
- Username: `admin`
31-
- Password: `password`
21+
The example will be available at:
22+
- **Frontend**: http://localhost:3000
23+
- **WordPress**: http://localhost:8888
24+
- **WordPress Admin**: http://localhost:8888/wp-admin (`admin` / `password`)
25+
- **GraphQL**: http://localhost:8888/?graphql
3226

33-
## Key Files
27+
> [!NOTE]
28+
> When you kill the long running process this will not shutdown the local WP instance, only Next.js. You must run `npm run example:stop` to kill the local WP server.
3429
35-
- `lib/toolbar.ts` - Singleton toolbar instance
36-
- `lib/wordpress.ts` - WordPress REST API integration
37-
- `app/components/Toolbar.tsx` - Toolbar component using React hooks
38-
- `app/page.tsx` - Demo page with WordPress integration
30+
## What This Example Shows
3931

40-
## Usage Pattern
32+
### 1. React Hooks Integration
4133

4234
```tsx
4335
import { toolbar } from '@/lib/toolbar';
@@ -48,90 +40,144 @@ function MyComponent() {
4840

4941
return (
5042
<div>
51-
{nodes.map(node => (
52-
<button key={node.id} onClick={node.onClick}>
53-
{typeof node.label === 'function' ? node.label() : node.label}
54-
</button>
55-
))}
43+
{/* Toolbar UI */}
5644
</div>
5745
);
5846
}
5947
```
6048

61-
## State Management
49+
### 2. WordPress Context Integration
50+
51+
```tsx
52+
import { fetchWordPressUser } from '@/lib/wordpress';
53+
54+
// Fetch user and set WordPress context
55+
const user = await fetchWordPressUser();
56+
toolbar.setWordPressContext({
57+
user: {
58+
id: user.id,
59+
name: user.name,
60+
email: user.email
61+
},
62+
site: {
63+
url: 'http://localhost:8888',
64+
adminUrl: 'http://localhost:8888/wp-admin'
65+
}
66+
});
67+
```
68+
69+
### 3. State Management
70+
71+
```tsx
72+
const { state, nodes } = useToolbar(toolbar);
73+
74+
// Subscribe to state changes
75+
useEffect(() => {
76+
console.log('Toolbar state:', state);
77+
}, [state]);
78+
```
79+
80+
### 4. Custom Node Registration
81+
82+
```tsx
83+
toolbar.register('home', 'Home', () => {
84+
router.push('/');
85+
});
86+
```
6287

63-
The toolbar follows modern state management patterns (TanStack/Zustand):
88+
## Features
6489

65-
1. **Framework-agnostic core** - `Toolbar` class manages state
66-
2. **React integration** - Hooks subscribe to state changes
67-
3. **Full UI control** - You render the toolbar however you want
90+
- ✅ React hooks (`useToolbar`, `useToolbarState`, `useToolbarNodes`)
91+
- ✅ Next.js App Router (App Directory)
92+
- ✅ TypeScript support
93+
- ✅ Framework-agnostic state management
94+
- ✅ WordPress context integration
95+
- ✅ Real WordPress data integration
96+
- ✅ WPGraphQL support
6897

69-
## WordPress Integration
98+
## Project Structure
7099

71-
The demo integrates with a local WordPress instance via REST API.
100+
```
101+
toolbar-demo/
102+
├── example-app/ # Next.js application
103+
│ ├── app/
104+
│ │ ├── components/ # React components
105+
│ │ │ └── Toolbar.tsx
106+
│ │ ├── globals.css
107+
│ │ ├── layout.tsx
108+
│ │ └── page.tsx # Demo page
109+
│ ├── lib/
110+
│ │ ├── toolbar.ts # Singleton toolbar instance
111+
│ │ └── wordpress.ts # WordPress API integration
112+
│ ├── next.config.ts
113+
│ ├── package.json
114+
│ └── tsconfig.json
115+
├── wp-env/ # WordPress environment
116+
├── .wp-env.json # wp-env configuration
117+
├── package.json
118+
└── README.md
119+
```
72120

73-
### Demo Authentication
121+
## Available Scripts
74122

75-
By default, the demo uses **mock authentication** to simplify the setup:
123+
```bash
124+
# Initial setup - installs dependencies and starts WordPress
125+
npm run example:setup
76126

77-
```ts
78-
// Demo user (no actual WordPress login required)
79-
const user = await getCurrentUser(); // Returns mock user
127+
# Start development servers (WordPress + Next.js)
128+
npm run example:start
80129

81-
// Public posts endpoint (no authentication needed)
82-
const posts = await getPosts(); // Fetches from /wp/v2/posts
130+
# Stop WordPress server
131+
npm run example:stop
132+
133+
# Reset everything and start fresh
134+
npm run example:prune
135+
136+
# WordPress-only commands
137+
npm run wp:start
138+
npm run wp:stop
139+
npm run wp:destroy
83140
```
84141

85-
This lets you test the toolbar immediately without WordPress login complexity.
142+
## Key Files
86143

87-
### Production Authentication
144+
- **`lib/toolbar.ts`** - Singleton toolbar instance configuration
145+
- **`lib/wordpress.ts`** - WordPress REST API integration helpers
146+
- **`app/components/Toolbar.tsx`** - Main toolbar component using React hooks
147+
- **`app/page.tsx`** - Demo page showing WordPress integration
88148

89-
For production use, implement proper authentication using **WordPress Application Passwords**:
149+
## WordPress Setup
90150

91-
1. **Generate Application Password**:
92-
- Go to WordPress Admin → Users → Profile
93-
- Scroll to "Application Passwords"
94-
- Create a new password
151+
The wp-env configuration includes:
152+
- WordPress with WPGraphQL plugin
153+
- Admin credentials: `admin` / `password`
154+
- GraphQL endpoint: `http://localhost:8888/?graphql`
155+
- REST API endpoint: `http://localhost:8888/?rest_route=/wp/v2/...`
156+
- Pretty permalinks enabled
157+
- CORS headers enabled for localhost:3000
95158

96-
2. **Configure Environment**:
97-
```bash
98-
cp .env.local.example .env.local
99-
# Add your credentials to .env.local
100-
```
159+
## Environment Configuration
101160

102-
3. **Update `lib/wordpress.ts`**:
103-
```ts
104-
const auth = btoa(`${process.env.WP_USERNAME}:${process.env.WP_APP_PASSWORD}`);
105-
106-
export async function fetchFromWordPress(endpoint: string) {
107-
const response = await fetch(`${WP_API_URL}/wp-json${endpoint}`, {
108-
headers: {
109-
'Authorization': `Basic ${auth}`
110-
}
111-
});
112-
// ...
113-
}
114-
```
161+
The example uses standard ports (3000 for frontend, 8888 for WordPress) to match other hwptoolkit examples.
162+
163+
## TypeScript Support
164+
165+
The example includes full TypeScript support with proper types for:
166+
- Toolbar state and nodes
167+
- WordPress API responses
168+
- React hook return types
115169

116-
### Features Demonstrated
170+
## Trouble Shooting
117171

118-
- **WordPress Connection**: Fetch data from WordPress REST API
119-
- **Post Management**: Load and display WordPress posts
120-
- **Dynamic Toolbar**: Nodes appear/disappear based on WordPress context
121-
- **Error Handling**: Clear error messages for connection issues
172+
To reset the WP server and re-run setup you can run `npm run example:prune` and confirm "Yes" at any prompts.
122173

123-
### Troubleshooting
174+
## Learn More
124175

125-
**CORS Errors**
126-
- Make sure wp-env is running: `npx wp-env start`
127-
- Check WordPress is accessible at http://localhost:8001
128-
- MU plugin should enable CORS headers automatically
176+
- [@wpengine/hwp-toolbar documentation](../../../packages/toolbar/README.md)
177+
- [Next.js Documentation](https://nextjs.org/docs)
178+
- [React Hooks Documentation](https://reactjs.org/docs/hooks-intro.html)
179+
- [WPGraphQL](https://www.wpgraphql.com/)
129180

130-
**Connection Failed**
131-
- Verify wp-env is running: `npx wp-env start`
132-
- Check the port matches `.wp-env.json` (default: 8001)
133-
- Try accessing http://localhost:8001 in your browser
181+
## License
134182

135-
**No Posts Available**
136-
- Create sample posts in WordPress Admin
137-
- Or run: `npx wp-env run cli wp post generate --count=5`
183+
BSD-3-Clause

examples/next/toolbar-demo/example-app/.env.local.example

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# Copy this file to .env.local and update with your values
33

44
# WordPress Site URL
5-
NEXT_PUBLIC_WP_URL=http://localhost:8891
5+
NEXT_PUBLIC_WP_URL=http://localhost:8888
66

77
# Production Authentication (optional)
88
# For real authentication, generate Application Passwords in WordPress:

examples/next/toolbar-demo/example-app/dev.sh

Lines changed: 0 additions & 5 deletions
This file was deleted.

examples/next/toolbar-demo/example-app/package.json

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,13 @@
33
"version": "0.1.0",
44
"private": true,
55
"scripts": {
6-
"predev": "node ../scripts/setup-env.js",
7-
"dev": "bash dev.sh",
6+
"dev": "next dev --port 3000",
87
"build": "next build",
98
"start": "next start"
109
},
1110
"dependencies": {
12-
"@wpengine/hwp-toolbar": "workspace:*",
13-
"next": "^15.4.7",
11+
"@wpengine/hwp-toolbar": "file:../../../../packages/toolbar",
12+
"next": "^15.5",
1413
"react": "^19.0.0",
1514
"react-dom": "^19.0.0"
1615
},

examples/next/toolbar-demo/package.json

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44
"description": "React hooks toolbar demo with Next.js App Router",
55
"private": true,
66
"scripts": {
7-
"example:dev": "npm --prefix ./example-app run dev",
8-
"example:build": "npm --prefix ./example-app run build",
9-
"example:start": "node scripts/setup-env.js && npm install && concurrently \"npm run wp:start\" \"sleep 5 && npm run example:dev\"",
7+
"example:setup": "npm run app:install && npm run wp:start",
8+
"example:start": "concurrently \"npm run wp:start\" \"sleep 5 && npm run app:dev\"",
109
"example:stop": "npm run wp:stop",
10+
"example:prune": "npm run wp:destroy && npm run example:setup && npm run example:start",
11+
"app:dev": "cd example-app && npm run dev && cd ..",
12+
"app:install": "cd example-app && npm install && cd ..",
1113
"wp:start": "wp-env start",
1214
"wp:stop": "wp-env stop",
1315
"wp:destroy": "wp-env destroy"

examples/next/toolbar-demo/scripts/setup-env.js

Lines changed: 0 additions & 67 deletions
This file was deleted.

0 commit comments

Comments
 (0)