Skip to content

Commit

Permalink
fix: examples
Browse files Browse the repository at this point in the history
  • Loading branch information
FleetAdmiralJakob committed Dec 7, 2024
1 parent 81e5ad5 commit b4ca17f
Show file tree
Hide file tree
Showing 98 changed files with 231 additions and 201 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ function Demo() {
</div>
);
}

```

%%API%%
4 changes: 2 additions & 2 deletions packages/website-docusaurus/docs/browser/useClipboard.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ function Demo() {
<button onClick={() => copy(value)}>Copy</button>
</div>
);
};
}

```

%%API%%
%%API%%
1 change: 1 addition & 0 deletions packages/website-docusaurus/docs/browser/useDarkMode.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ function Demo() {
</div>
);
}

```

%%API%%
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ function Demo() {

return <p>Device pixel ratio: {pixelRatio}</p>;
}

```

%%API%%
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ function Demo() {
</>
);
}

render(<Demo />);

```

%%API%%
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ function Demo() {
</div>
);
}

```

%%API%%
4 changes: 2 additions & 2 deletions packages/website-docusaurus/docs/browser/useEyeDropper.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ function Demo() {
}

return <span>Not Supported by Your Browser</span>;
};
}

```

%%API%%
%%API%%
4 changes: 2 additions & 2 deletions packages/website-docusaurus/docs/browser/useFavicon.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ function Demo() {
</button>
</div>
);
};
}

```

%%API%%
%%API%%
71 changes: 38 additions & 33 deletions packages/website-docusaurus/docs/browser/useFetchEventSource.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -43,42 +43,42 @@ app.post('/events', async (req, res) => {
res.setHeader('X-Accel-Buffering', 'no');
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Credentials', 'true');

// 2. Read and parse request body
let body = '';
for await (const chunk of req) {
body += chunk;
}

// 3. Parse configuration
let config;
try {
config = body ? JSON.parse(body) : {};
} catch (e) {
config = {};
}

const channel = config.channel || 'default';
const interval = parseInt(config.interval) || 3000;

// 4. Disable request timeout
req.socket.setTimeout(0);
req.socket.setNoDelay(true);
req.socket.setKeepAlive(true);

// 5. Start sending data
console.log(`New client connected to channel: ${channel}`);

// 6. Add connection to the client collection of corresponding channel
if (!clients.has(channel)) {
clients.set(channel, new Set());
}
clients.get(channel).add(res);

const totalClients = Array.from(clients.values())
.reduce((sum, set) => sum + set.size, 0);
console.log(`Client connected to channel ${channel}. Total clients: ${totalClients}`);

// 7. Send connection success message
const sendEvent = (data, eventType = null) => {
if (eventType) {
Expand All @@ -87,21 +87,21 @@ app.post('/events', async (req, res) => {
res.write(`id: ${Date.now()}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
};

// 8. Send initial message
try {
sendEvent({
sendEvent({
message: 'Connected to SSE stream',
channel: channel,
time: new Date().toISOString()
time: new Date().toISOString()
}, 'connected');

// 9. Set up periodic message sending
let messageCounter = 0;
const intervalId = setInterval(() => {
messageCounter++;
messageCount++;

try {
sendEvent({
id: messageCount,
Expand All @@ -115,7 +115,7 @@ app.post('/events', async (req, res) => {
cleanup();
}
}, interval);

// 10. Set up heartbeat
const heartbeatId = setInterval(() => {
try {
Expand All @@ -125,37 +125,37 @@ app.post('/events', async (req, res) => {
cleanup();
}
}, 15000);

// 11. Cleanup function
const cleanup = () => {
clearInterval(intervalId);
clearInterval(heartbeatId);

const channelClients = clients.get(channel);
if (channelClients) {
channelClients.delete(res);
if (channelClients.size === 0) {
clients.delete(channel);
}
}

const remainingClients = Array.from(clients.values())
.reduce((sum, set) => sum + set.size, 0);
console.log(`Client disconnected from channel ${channel}. Total clients: ${remainingClients}`);

try {
res.end();
} catch (error) {
console.error('Error ending response:', error);
}
};

// 12. Set up connection close handling
req.on('close', cleanup);
req.on('end', cleanup);
res.on('close', cleanup);
res.on('error', cleanup);

} catch (error) {
console.error(`Error in SSE connection for channel ${channel}:`, error);
res.end();
Expand Down Expand Up @@ -186,18 +186,18 @@ function handleGETConnection(req, res, channel = 'default', interval = 3000) {
};

// Send initial connection message
sendEvent({
sendEvent({
message: 'Connected to SSE stream',
channel: channel,
time: new Date().toISOString()
time: new Date().toISOString()
}, 'connected');

// Add connection to the client collection of corresponding channel
if (!clients.has(channel)) {
clients.set(channel, new Set());
}
clients.get(channel).add(res);

const totalClients = Array.from(clients.values())
.reduce((sum, set) => sum + set.size, 0);
console.log(`Client connected to channel ${channel}. Total clients: ${totalClients}`);
Expand Down Expand Up @@ -258,7 +258,7 @@ app.get('/events', (req, res) => {
// Broadcast message endpoint
app.post('/broadcast', bodyParser.json(), (req, res) => {
const { message, channel, eventType = 'broadcast' } = req.body;

let targetClients = new Set();
if (channel) {
targetClients = clients.get(channel) || new Set();
Expand All @@ -270,13 +270,13 @@ app.post('/broadcast', bodyParser.json(), (req, res) => {
);
console.log(`Broadcasting message to all channels (${targetClients.size} clients):`, message);
}

let successCount = 0;
for (const client of targetClients) {
try {
client.write(`event: ${eventType}\n`);
client.write(`id: ${Date.now()}\n`);
client.write(`data: ${JSON.stringify({
client.write(`data: ${JSON.stringify({
message,
channel: channel || 'all',
time: new Date().toISOString()
Expand All @@ -287,12 +287,12 @@ app.post('/broadcast', bodyParser.json(), (req, res) => {
}
}

res.json({
success: true,
res.json({
success: true,
clientCount: targetClients.size,
successfulBroadcasts: successCount,
channel: channel || 'all',
message: 'Broadcast sent successfully'
message: 'Broadcast sent successfully'
});
});

Expand Down Expand Up @@ -349,6 +349,7 @@ function Demo() {
</div>
);
}

```

### With POST Request
Expand Down Expand Up @@ -383,6 +384,7 @@ function Demo() {
</div>
);
}

```

### With Event Handlers
Expand Down Expand Up @@ -412,6 +414,7 @@ function Demo() {
</div>
);
}

```

### With Auto Reconnect
Expand All @@ -435,14 +438,15 @@ function Demo() {
</div>
);
}

```

### Multi Channel Example

```tsx live
function Demo() {
const [channel, setChannel] = useState('default');

const { data, close, open } = useFetchEventSource(
"http://localhost:3001/events",
{
Expand All @@ -463,8 +467,8 @@ function Demo() {

return (
<div>
<select
value={channel}
<select
value={channel}
onChange={(e) => switchChannel(e.target.value)}
>
<option value="default">Default Channel</option>
Expand All @@ -476,6 +480,7 @@ function Demo() {
</div>
);
}

```

%%API%%
%%API%%
4 changes: 2 additions & 2 deletions packages/website-docusaurus/docs/browser/useFileDialog.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ function Demo() {
)}
</div>
);
};
}

```

%%API%%
%%API%%
4 changes: 2 additions & 2 deletions packages/website-docusaurus/docs/browser/useFps.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ function Demo() {
const fps = useFps();

return <div>FPS: {fps}</div>;
};
}

```

%%API%%
%%API%%
4 changes: 2 additions & 2 deletions packages/website-docusaurus/docs/browser/useFullscreen.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ function Demo() {
</div>
</div>
);
};
}

```

%%API%%
%%API%%
4 changes: 2 additions & 2 deletions packages/website-docusaurus/docs/browser/useGeolocation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ function Demo() {
</pre>
</div>
);
};
}

```

%%API%%
%%API%%
4 changes: 2 additions & 2 deletions packages/website-docusaurus/docs/browser/useIdle.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ function Demo() {
<div>User is idle: {isIdle ? "Yes 😴" : "Nope"}</div>
</div>
);
};
}

```

%%API%%
%%API%%
Loading

0 comments on commit b4ca17f

Please sign in to comment.