ext-apps/src/react/useApp.examples.tsx
Jonathan Hefner f0c7cc1b14 Refine JSDoc examples for consistency and type safety
Follow-up to the examples extraction: pass dependencies as function
parameters instead of using global stub declarations, rename region
names to match method names (e.g., `AppBridge_guestCapabilities_*` →
`AppBridge_getAppCapabilities_*`), and simplify examples using optional
chaining.

Also clarifies `RESOURCE_URI_META_KEY` documentation to indicate it's
for tool definition metadata (from `tools/list`), not tool result
metadata, and removes the redundant `setNotificationHandler` example
in favor of the simpler event setter approach.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 20:43:47 -06:00

65 lines
1.7 KiB
TypeScript

/**
* Type-checked examples for the useApp hook.
*
* @module
*/
import { useState } from "react";
import type { McpUiHostContext } from "../types.js";
import { useApp } from "./index.js";
/**
* Example: Register an event handler in onAppCreated.
*/
function useApp_registerHandler() {
//#region useApp_registerHandler
useApp({
appInfo: { name: "MyApp", version: "1.0.0" },
capabilities: {},
onAppCreated: (app) => {
app.ontoolresult = (result) => {
console.log("Tool result:", result);
};
},
});
//#endregion useApp_registerHandler
}
/**
* Example: Basic usage of useApp hook with common event handlers.
*/
function useApp_basicUsage() {
//#region useApp_basicUsage
function MyApp() {
const [hostContext, setHostContext] = useState<
McpUiHostContext | undefined
>(undefined);
const { app, isConnected, error } = useApp({
appInfo: { name: "MyApp", version: "1.0.0" },
capabilities: {},
onAppCreated: (app) => {
app.ontoolinput = (input) => {
console.log("Tool input:", input);
};
app.ontoolresult = (result) => {
console.log("Tool result:", result);
};
app.ontoolcancelled = (params) => {
console.log("Tool cancelled:", params.reason);
};
app.onerror = (error) => {
console.log("Error:", error);
};
app.onhostcontextchanged = (params) => {
setHostContext((prev) => ({ ...prev, ...params }));
};
},
});
if (error) return <div>Error: {error.message}</div>;
if (!isConnected) return <div>Connecting...</div>;
return <div>Theme: {hostContext?.theme}</div>;
}
//#endregion useApp_basicUsage
}