Skip to content

Commit

Permalink
Minor refactor to remove some more redundancy (#1409)
Browse files Browse the repository at this point in the history
  • Loading branch information
jerelmiller committed Jun 12, 2024
1 parent 226ba49 commit 2b4ffcf
Show file tree
Hide file tree
Showing 8 changed files with 43 additions and 82 deletions.
5 changes: 5 additions & 0 deletions .changeset/brave-meals-agree.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"apollo-client-devtools": patch
---

Refactor away some redundancy on starting/cancelling the request interval to get client data from the devtools scripts.
5 changes: 5 additions & 0 deletions .changeset/many-guests-flow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"apollo-client-devtools": patch
---

Clear the data on screen when the client is no longer connected to the devtools.
40 changes: 6 additions & 34 deletions src/application/machines.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,10 @@
import type { QueryInfo } from "../extension/tab/helpers";
import type { JSONObject } from "./types/json";

import type { StateMachine } from "@xstate/fsm";
import { createMachine, assign } from "@xstate/fsm";
import { createMachine } from "@xstate/fsm";

export interface ClientContext {
clientVersion: string | null;
queries: QueryInfo[];
mutations: QueryInfo[];
cache: JSONObject;
}
interface Context {
clientContext: ClientContext;
}
type Context = Record<string, never>;

type Events =
| { type: "connect"; clientContext: ClientContext }
| { type: "connect" }
| { type: "timeout" }
| { type: "disconnect" }
| { type: "clientNotFound" }
Expand All @@ -36,22 +25,14 @@ type State = {

type Actions = {
connectToClient: StateMachine.ActionFunction<Context, Events>;
cancelRequestInterval: StateMachine.ActionFunction<Context, Events>;
startRequestInterval: StateMachine.ActionFunction<Context, Events>;
unsubscribeFromAll: StateMachine.ActionFunction<Context, Events>;
};

export function createDevtoolsMachine({ actions }: { actions: Actions }) {
return createMachine<Context, Events, State>(
{
initial: "initialized",
context: {
clientContext: {
clientVersion: null,
queries: [],
mutations: [],
cache: {},
},
},
states: {
initialized: {
on: {
Expand All @@ -71,31 +52,22 @@ export function createDevtoolsMachine({ actions }: { actions: Actions }) {
on: {
disconnect: "disconnected",
},
entry: [
"startRequestInterval",
assign({
clientContext: (ctx, event) =>
"clientContext" in event
? event.clientContext
: ctx.clientContext,
}),
],
entry: ["startRequestInterval"],
},
disconnected: {
on: {
connect: "connected",
timeout: "timedout",
clientNotFound: "notFound",
},
entry: ["unsubscribeFromAll"],
entry: ["cancelRequestInterval"],
},
timedout: {},
notFound: {
on: {
retry: "retrying",
connect: "connected",
},
entry: "unsubscribeFromAll",
},
},
},
Expand Down
6 changes: 1 addition & 5 deletions src/extension/actor.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import type browser from "webextension-polyfill";
import type {
ApolloClientDevtoolsEventMessage,
MessageFormat,
} from "./messages";
import { MessageType, isEventMessage } from "./messages";
import type { NoInfer } from "../types";
import type { MessageAdapter } from "./messageAdapters";
import {
createPortMessageAdapter,
createWindowMessageAdapter,
} from "./messageAdapters";
import { createWindowMessageAdapter } from "./messageAdapters";

export interface Actor<Messages extends MessageFormat> {
on: <TName extends Messages["type"]>(
Expand Down
46 changes: 12 additions & 34 deletions src/extension/devtools/devtools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,21 @@ const devtoolsMachine = interpret(
createDevtoolsMachine({
actions: {
connectToClient,
cancelRequestInterval: () => cancelRequestInterval?.(),
startRequestInterval: () => {
clearTimeout(connectTimeoutId);

if (!panelHidden) {
unsubscribers.add(startRequestInterval());
cancelRequestInterval = startRequestInterval();
}
},
unsubscribeFromAll: (_, event) => {
if (event.type === "clientNotFound") {
clearTimeout(connectTimeoutId);
}
unsubscribeFromAll();
},
},
})
).start();

let panelHidden = true;
let connectTimeoutId: NodeJS.Timeout;
let cancelRequestInterval: (() => void) | undefined;

const portAdapter = createPortMessageAdapter(() =>
browser.runtime.connect({ name: inspectedTabId.toString() })
Expand All @@ -45,12 +41,6 @@ const portAdapter = createPortMessageAdapter(() =>
const clientPort = createActor<ClientMessage>(portAdapter);
const rpcClient = createRpcClient<DevtoolsRPCMessage>(portAdapter);

devtoolsMachine.subscribe(({ value }) => {
if (value === "connected") {
clearTimeout(connectTimeoutId);
}
});

function connectToClient() {
clientPort.send({ type: "connectToClient" });
startConnectTimeout();
Expand All @@ -69,15 +59,12 @@ function startConnectTimeout() {
}, 10_000);
}

clientPort.on("connectToDevtools", (message) => {
devtoolsMachine.send({
type: "connect",
clientContext: message.payload,
});
clientPort.on("connectToDevtools", () => {
devtoolsMachine.send({ type: "connect" });
});

clientPort.on("registerClient", (message) => {
devtoolsMachine.send({ type: "connect", clientContext: message.payload });
clientPort.on("registerClient", () => {
devtoolsMachine.send({ type: "connect" });
});

clientPort.on("clientTerminated", disconnectFromDevtools);
Expand All @@ -100,20 +87,11 @@ function startRequestInterval(ms = 500) {
}
}

if (devtoolsMachine.state.value === "connected") {
getClientData();
}
getClientData();

return () => clearTimeout(id);
}

const unsubscribers = new Set<() => void>();

function unsubscribeFromAll() {
unsubscribers.forEach((unsubscribe) => unsubscribe());
unsubscribers.clear();
}

let connectedToPanel = false;
let panelWindow: Actor<PanelMessage>;

Expand All @@ -124,14 +102,14 @@ async function createDevtoolsPanel() {
"panel.html"
);

panel.onShown.addListener((window) => {
panel.onShown.addListener(async (window) => {
panelWindow = getPanelActor(window);

if (!connectedToPanel) {
panelWindow.send({
type: "initializePanel",
state: devtoolsMachine.state.value,
payload: devtoolsMachine.state.context.clientContext,
payload: await rpcClient.request("getClientOperations"),
});

panelWindow.on("retryConnection", () => {
Expand All @@ -150,15 +128,15 @@ async function createDevtoolsPanel() {
}

if (devtoolsMachine.state.value === "connected" && panelHidden) {
unsubscribers.add(startRequestInterval());
cancelRequestInterval = startRequestInterval();
}

panelHidden = false;
});

panel.onHidden.addListener(() => {
panelHidden = true;
unsubscribeFromAll();
cancelRequestInterval?.();
});
}

Expand Down
2 changes: 1 addition & 1 deletion src/extension/devtools/panel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ panelWindow.on("initializePanel", (message) => {
panelWindow.on("devtoolsStateChanged", (message) => {
devtoolsState(message.state);

if (message.state === "connected") {
if (message.state !== "connected") {
client.resetStore();
}
});
Expand Down
17 changes: 11 additions & 6 deletions src/extension/messages.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { ExplorerResponse, SafeAny } from "../types";
import type { StateValues, ClientContext } from "../application/machines";
import type { StateValues } from "../application/machines";
import type { JSONObject } from "../application/types/json";
import type { FetchPolicy, DocumentNode } from "@apollo/client";
import type { QueryInfo } from "./tab/helpers";

export interface MessageFormat {
type: string;
Expand Down Expand Up @@ -81,13 +82,17 @@ type ExplorerSubscriptionTerminationMessage = {
type: "explorerSubscriptionTermination";
};

interface ClientContext {
clientVersion: string | null;
queries: QueryInfo[];
mutations: QueryInfo[];
cache: JSONObject;
}

export type ClientMessage =
| { type: "registerClient"; payload: ClientContext }
| { type: "registerClient" }
| { type: "connectToClient" }
| {
type: "connectToDevtools";
payload: ClientContext;
}
| { type: "connectToDevtools" }
| { type: "clientTerminated" }
| ExplorerRequestMessage
| ExplorerResponseMessage
Expand Down
4 changes: 2 additions & 2 deletions src/extension/tab/hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ handleRpc("getClientOperations", getClientData);

tab.on("connectToClient", () => {
if (hook.ApolloClient) {
tab.send({ type: "connectToDevtools", payload: getClientData() });
tab.send({ type: "connectToDevtools" });
}
});

Expand Down Expand Up @@ -232,7 +232,7 @@ function registerClient(client: ApolloClient<any>) {
if (!knownClients.has(client)) {
knownClients.add(client);
watchForClientTermination(client);
tab.send({ type: "registerClient", payload: getClientData() });
tab.send({ type: "registerClient" });
}

hook.ApolloClient = client;
Expand Down

0 comments on commit 2b4ffcf

Please sign in to comment.