Skip to content
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

[widgets] Add temporary messages for a fetch proxy #997

Merged
merged 8 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/long-rats-end.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@osdk/widget-client.unstable": minor
"@osdk/widget-api.unstable": minor
---

Add fetch proxy
2 changes: 2 additions & 0 deletions packages/e2e.sandbox.todowidget/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
"transpile": "monorepo.tool.transpile"
},
"dependencies": {
"@osdk/client": "workspace:~",
"@osdk/foundry.datasets": "~2.5.0",
"@osdk/widget-client-react.unstable": "workspace:~",
"@osdk/widget-client.unstable": "workspace:~",
"@radix-ui/react-icons": "^1.3.1",
Expand Down
66 changes: 61 additions & 5 deletions packages/e2e.sandbox.todowidget/src/app.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { ExclamationTriangleIcon } from "@radix-ui/react-icons";
import type { Dataset } from "@osdk/foundry.datasets";
import { Datasets } from "@osdk/foundry.datasets";
import { type AsyncValue } from "@osdk/widget-client.unstable";
import { ExclamationTriangleIcon, TableIcon } from "@radix-ui/react-icons";
import {
Box,
Button,
Expand All @@ -9,22 +12,57 @@ import {
Heading,
Skeleton,
Table,
Text,
TextField,
} from "@radix-ui/themes";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useWidgetContext } from "./context.js";

export const App: React.FC = () => {
const { parameters, hostEventTarget, emitEvent } = useWidgetContext();
const { headerText, todoItems, showWarning } = parameters.values;
const { parameters, hostEventTarget, emitEvent, createOntologyClient } =
useWidgetContext();
const { headerText, todoItems, showWarning, datasetRid } = parameters.values;
const [newTodoItem, setNewTodoItem] = useState("");
const [dataset, setDataset] = useState<AsyncValue<Dataset>>({
type: "not-started",
});
const client = useMemo(
() => createOntologyClient("ri.ontology.main.ontology.0000-0000-0000-0000"),
[createOntologyClient],
);

useEffect(() => {
hostEventTarget.addEventListener("host.update-parameters", (event) => {
console.log("Received event:", event);
});
}, []);

useEffect(() => {
if (datasetRid != null) {
setDataset((prevDataset) => {
if (prevDataset.type !== "not-started") {
return {
type: "reloading",
value: prevDataset.value,
};
}
return { type: "loading" };
});
Datasets.get(client, datasetRid).then((dataset) => {
setDataset({
type: "loaded",
value: dataset,
});
}).catch((error) => {
setDataset(prevDataset => ({
type: "failed",
error: error as Error,
value: prevDataset.value,
}));
});
}
}, [datasetRid]);

const handleAddTodoItem = useCallback(() => {
emitEvent("updateTodoItems", {
parameterUpdates: {
Expand Down Expand Up @@ -59,6 +97,23 @@ export const App: React.FC = () => {
<Callout.Text>This is a data warning</Callout.Text>
</Callout.Root>
)}
<Heading size="2">
{dataset.type === "loading" || dataset.type === "reloading"
? <Skeleton>Loading dataset…</Skeleton>
: dataset.type === "loaded"
? (
<>
<TableIcon /> {dataset.value?.name}
</>
)
: dataset.type === "failed"
? (
<Text>
<ExclamationTriangleIcon /> Failed to load dataset
</Text>
)
: "No dataset loaded"}
</Heading>
<Table.Root>
<Table.Header>
<Table.Row>
Expand All @@ -69,7 +124,8 @@ export const App: React.FC = () => {

<Table.Body>
{(parameters.state === "loading"
|| parameters.state === "not-started") && (
|| parameters.state === "not-started"
|| parameters.state === "reloading") && (
<>
<Table.Row>
<Table.Cell>
Expand Down
4 changes: 4 additions & 0 deletions packages/e2e.sandbox.todowidget/src/main.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ export default defineConfig({
displayName: "Widget title",
type: "string",
},
datasetRid: {
displayName: "Dataset RID",
type: "string",
},
showWarning: {
displayName: "Show warning callout",
type: "boolean",
Expand Down
3 changes: 3 additions & 0 deletions packages/widget.api.unstable/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,14 @@ export type {
} from "./manifest.js";
export { MANIFEST_FILE_LOCATION } from "./manifest.js";
export {
_unstable_isHostFetchResponseFailedMessage,
_unstable_isHostFetchResponseSuccessMessage,
HostMessage,
isHostParametersUpdatedMessage,
visitHostMessage,
} from "./messages/hostMessages.js";
export {
_unstable_isWidgetFetchMessage,
isWidgetEmitEventMessage,
isWidgetReadyMessage,
visitWidgetMessage,
Expand Down
65 changes: 63 additions & 2 deletions packages/widget.api.unstable/src/messages/hostMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,27 +30,88 @@ export namespace HostMessage {
export interface UpdateParameters<C extends WidgetConfig<C["parameters"]>> {
parameters: AsyncParameterValueMap<C>;
}

/**
* Temporary fetch proxy response
* Will be removed in favor of server side proxy
*/
export interface _unstable_FetchResponseSuccess {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i prefixed these with _unstable_ because i don't think they should be long lived

id: string;
status: number;
statusText: string;
headers: Record<string, string>;
body: string;
}

/**
* Temporary fetch proxy response
* Will be removed in favor of server side proxy
*/
export interface _unstable_FetchResponseFailed {
id: string;
error: string;
}
}

export type Payload =
| Payload.UpdateParameters<any>
| Payload._unstable_FetchResponseSuccess
| Payload._unstable_FetchResponseFailed;

export interface UpdateParameters<C extends WidgetConfig<C["parameters"]>>
extends
HostBaseMessage<
"host.update-parameters",
Payload.UpdateParameters<C>
>
{}

/**
* Temporary fetch proxy response
* Will be removed in favor of server side proxy
*/
export interface _unstable_FetchResponseSuccess extends
HostBaseMessage<
"host._unstable.fetch-response-success",
Payload._unstable_FetchResponseSuccess
>
{}

/**
* Temporary fetch proxy response
* Will be removed in favor of server side proxy
*/
export interface _unstable_FetchResponseFailed extends
HostBaseMessage<
"host._unstable.fetch-response-failed",
Payload._unstable_FetchResponseFailed
>
{}
}

// Union type
export type HostMessage<C extends WidgetConfig<C["parameters"]>> =
HostMessage.UpdateParameters<C>;
| HostMessage.UpdateParameters<C>
| HostMessage._unstable_FetchResponseSuccess
| HostMessage._unstable_FetchResponseFailed;

export function isHostParametersUpdatedMessage<
C extends WidgetConfig<C["parameters"]>,
>(event: HostMessage<C>): event is HostMessage.UpdateParameters<C> {
return event.type === "host.update-parameters";
}

export function _unstable_isHostFetchResponseSuccessMessage<
C extends WidgetConfig<C["parameters"]>,
>(event: HostMessage<C>): event is HostMessage._unstable_FetchResponseSuccess {
return event.type === "host._unstable.fetch-response-success";
}

export function _unstable_isHostFetchResponseFailedMessage<
C extends WidgetConfig<C["parameters"]>,
>(event: HostMessage<C>): event is HostMessage._unstable_FetchResponseFailed {
return event.type === "host._unstable.fetch-response-failed";
}

type HostMessageVisitor<C extends WidgetConfig<C["parameters"]>> =
& {
[T in HostMessage<C>["type"]]: (
Expand Down
35 changes: 33 additions & 2 deletions packages/widget.api.unstable/src/messages/widgetMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,24 @@ export namespace WidgetMessage {

export type EmitEvent<C extends WidgetConfig<C["parameters"]>> =
EmitEventIdMap<C>[EventId<C>];

/**
* Temporary fetch proxy
* Will be removed in favor of server side proxy
*/
export interface _unstable_FetchRequest {
id: string;
url: string;
method: string;
headers: Record<string, string>;
body?: string;
}
}

export type Payload<C extends WidgetConfig<C["parameters"]>> =
| Payload.Ready
| Payload.EmitEvent<C>;
| Payload.EmitEvent<C>
| Payload._unstable_FetchRequest;

/**
* Emit when the widget is ready to start receiving messages from the host Foundry UI
Expand All @@ -62,11 +75,23 @@ export namespace WidgetMessage {
export interface EmitEvent<C extends WidgetConfig<C["parameters"]>>
extends WidgetBaseMessage<"widget.emit-event", Payload.EmitEvent<C>>
{}

/**
* Temporary fetch proxy
* Will be removed in favor of server side proxy
*/
export interface _unstable_FetchRequest extends
WidgetBaseMessage<
"widget._unstable.fetch-request",
Payload._unstable_FetchRequest
>
{}
}

export type WidgetMessage<C extends WidgetConfig<C["parameters"]>> =
| WidgetMessage.Ready
| WidgetMessage.EmitEvent<C>;
| WidgetMessage.EmitEvent<C>
| WidgetMessage._unstable_FetchRequest;

export function isWidgetReadyMessage<C extends WidgetConfig<C["parameters"]>>(
event: WidgetMessage<C>,
Expand All @@ -80,6 +105,12 @@ export function isWidgetEmitEventMessage<
return event.type === "widget.emit-event";
}

export function _unstable_isWidgetFetchMessage<
C extends WidgetConfig<C["parameters"]>,
>(event: WidgetMessage<C>): event is WidgetMessage._unstable_FetchRequest {
return event.type === "widget._unstable.fetch-request";
}

type WidgetMessageVisitor<C extends WidgetConfig<C["parameters"]>> =
& {
[T in WidgetMessage<C>["type"]]: (
Expand Down
6 changes: 6 additions & 0 deletions packages/widget.api.unstable/src/utils/asyncValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,26 @@

export interface AsyncNotStartedLoadingValue {
type: "not-started";
value?: never;
error?: never;
}

export interface AsyncLoadingValue {
type: "loading";
value?: never;
error?: never;
}

export interface AsyncLoadedValue<V> {
type: "loaded";
value: V | undefined;
error?: never;
}

export interface AsyncReloadingValue<V> {
type: "reloading";
value: V | undefined;
error?: never;
}

export interface AsyncFailedValue<V, E = Error> {
Expand Down
2 changes: 2 additions & 0 deletions packages/widget.client-react.unstable/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@
"transpile": "monorepo.tool.transpile"
},
"peerDependencies": {
"@osdk/client": "^2",
"@osdk/widget-client.unstable": "^0.1.0",
"@types/react": "^18",
"@types/react-dom": "^18",
"react": "^18",
"react-dom": "18"
},
"devDependencies": {
"@osdk/client": "workspace:~",
"@osdk/monorepo.api-extractor": "workspace:~",
"@osdk/monorepo.tsconfig": "workspace:~",
"@osdk/monorepo.tsup": "workspace:~",
Expand Down
6 changes: 2 additions & 4 deletions packages/widget.client-react.unstable/src/client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,13 +153,11 @@ export const FoundryWidget = <C extends WidgetConfig<C["parameters"]>>({
<FoundryWidgetContext.Provider
value={{
emitEvent: client.emitEvent,
createOntologyClient: client.createOntologyClient,
hostEventTarget: client.hostEventTarget,
asyncParameterValues,
parameters: {
values: allParameterValues.type === "not-started"
|| allParameterValues.type === "loading"
? {}
: allParameterValues.value,
values: allParameterValues.value ?? {},
state: allParameterValues.type,
},
// Unfortunately the context is statically defined so we can't use the generic type, hence the cast
Expand Down
10 changes: 10 additions & 0 deletions packages/widget.client-react.unstable/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* limitations under the License.
*/

import type { Client } from "@osdk/client";
import {
type AsyncParameterValueMap,
type AsyncValue,
Expand All @@ -29,6 +30,10 @@ export interface FoundryWidgetClientContext<
C extends WidgetConfig<C["parameters"]>,
> {
emitEvent: FoundryWidgetClient<C>["emitEvent"];
/**
* Creates a new OSDK client for the given Ontology, automatically inferring the correct URL to make API requests to.
*/
createOntologyClient: (ontologyRid: string) => Client;
hostEventTarget: FoundryHostEventTarget<C>;

/**
Expand All @@ -49,6 +54,11 @@ export const FoundryWidgetContext = React.createContext<
FoundryWidgetClientContext<WidgetConfig<ParameterConfig>>
>({
emitEvent: () => {},
createOntologyClient: () => {
throw new Error(
"createOntologyClient is not implemented in this context",
);
},
hostEventTarget: new FoundryHostEventTarget<WidgetConfig<ParameterConfig>>(),
asyncParameterValues: {},
parameters: {
Expand Down
Loading