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

fix: persist state between Cache/History and Network #68

Merged
merged 1 commit into from
Jul 7, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
165 changes: 8 additions & 157 deletions packages/swr-devtools-panel/src/components/NetworkPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,177 +1,28 @@
import React, {
MouseEvent,
useCallback,
useLayoutEffect,
useRef,
useState,
} from "react";
import React, { MouseEvent, useCallback, useState } from "react";
import styled from "styled-components";
import { Cache } from "swr";
import { EventEmitter, RequestsById, useRequests, useTracks } from "../request";

import { PanelType } from "./SWRDevToolPanel";
import { Timeline } from "./timeline";

type EventListener = (...args: any[]) => void;
export type EventEmitter = {
subscribe(fn: EventListener): () => void;
};

type SWRRequest = {
id: number;
key: string;
type: "success" | "error" | "discarded" | "ongoing";
startTime: Date;
endTime: Date | null;
};

function useRequests(events: EventEmitter) {
const [requestsById, setRequestsById] = useState<
Record<string, SWRRequest[]>
>({});
const activeRequestsRef = useRef<Record<number | string, SWRRequest>>({});

useLayoutEffect(() => {
// Which channel does this request belong to.
const idMap: Record<number, string> = {};

return events.subscribe(
(type, { id, key }: { id: number; key: string }) => {
setRequestsById((currentRequestsByKey) => {
let channelKey = key;
let channelNum = 0;

let currentRequests;
const activeRequests = activeRequestsRef.current;

switch (type) {
case "request_start":
// There can be only 1 ongoing request at a time for each channel. Move it to a new one.
while (activeRequests[channelKey]) {
channelKey = `${key}-${++channelNum}`;
}

currentRequests = currentRequestsByKey[channelKey] || [];

activeRequests[id] = {
id,
key,
type: "ongoing",
startTime: new Date(),
endTime: null,
};
activeRequests[channelKey] = activeRequests[id];

currentRequests.push(activeRequests[id]);
idMap[id] = channelKey;

// Always mutate the object.
return {
...currentRequestsByKey,
[channelKey]: currentRequests,
};
case "request_success":
if (activeRequests[id]) {
channelKey = idMap[id];

activeRequests[id].type = "success";
activeRequests[id].endTime = new Date();
delete activeRequests[id];
delete activeRequests[channelKey];

return { ...currentRequestsByKey };
}
break;
case "request_error":
if (activeRequests[id]) {
channelKey = idMap[id];

activeRequests[id].type = "error";
activeRequests[id].endTime = new Date();
delete activeRequests[id];
delete activeRequests[channelKey];

return { ...currentRequestsByKey };
}
break;
case "request_discarded":
if (activeRequests[id]) {
channelKey = idMap[id];

activeRequests[id].type = "discarded";
activeRequests[id].endTime = new Date();
delete activeRequests[id];
delete activeRequests[channelKey];

return { ...currentRequestsByKey };
}
break;
}
return currentRequestsByKey;
});
}
);
}, [events]);

return requestsById;
}

function formatTime(time: number, step: number) {
if (step >= 500) return time / 1000 + "s";
if (time >= 10000) return time / 1000 + "s";
return time + "ms";
}

export const NetworkPanel = ({
cache,
type,
events,
requestsById,
tracks,
startTime,
}: {
cache: Cache;
events: EventEmitter;
type: PanelType;
requestsById: RequestsById;
tracks: any[];
startTime: number;
}) => {
const startTime = useState(() => Date.now())[0];
const requestsById = useRequests(events);
const [requestDetail, setRequestDetail] = useState<null | string>(null);

const tracks = React.useMemo(() => {
const t: any[] = [];

[...Object.entries(requestsById)].forEach(([channelKey, requests]) => {
const title = requests[0] ? requests[0].key : channelKey;
const shouldMergeKey = requests[0] && channelKey !== requests[0].key;

t.push({
key: channelKey,
data: {
title,
shouldMergeKey,
},
items: requests.map((request) => {
return {
key: request.id,
data: request,
start: request.startTime.getTime(),
end: (request.endTime || new Date()).getTime(),
};
}),
});
});

t.sort((a, b) => {
if (a.data.title < b.data.title) return -1;
if (a.data.title > b.data.title) return 1;
return 0;
});

// Re-assign indexes.
t.forEach((t_, i) => {
t_.data.index = i;
});

return t;
}, [requestsById]);

const [trackScale, setTrackScale] = React.useState(5);
const [timelineHoverX, setTimelineHoverX] = React.useState(-1);

Expand Down
12 changes: 4 additions & 8 deletions packages/swr-devtools-panel/src/components/Panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,20 @@ import { SearchInput } from "./SearchInput";
import { DevToolsCacheData } from "swr-devtools/lib/swr-cache";

export const Panel = ({
cache,
cacheData,
type,
selectedItemKey,
onSelectItem,
}: {
cache: Cache;
cacheData: DevToolsCacheData[];
type: PanelType;
selectedItemKey: DevToolsCacheData | null;
onSelectItem: (devToolsCacheData: DevToolsCacheData) => void;
}) => {
const [currentDevToolsCacheData, historyDevToolsCacheData] =
useDevToolsCache(cache);
const [filterText, setFilterText] = useState("");
const allDevToolsCacheData =
type === "history" ? historyDevToolsCacheData : currentDevToolsCacheData;
const selectedDevToolsCacheData =
selectedItemKey &&
allDevToolsCacheData.find(
cacheData.find(
(c) =>
c.key === selectedItemKey.key &&
(type === "current" || c.timestamp === selectedItemKey.timestamp)
Expand All @@ -40,7 +36,7 @@ export const Panel = ({
onChange={(text: string) => setFilterText(text)}
/>
<CacheItems>
{allDevToolsCacheData
{cacheData
.filter(({ key }) => filterText === "" || key.includes(filterText))
.map((devToolsCacheData) => (
<CacheItem
Expand Down
20 changes: 17 additions & 3 deletions packages/swr-devtools-panel/src/components/SWRDevToolPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import React, { useState } from "react";
import styled, { createGlobalStyle } from "styled-components";
import { Cache } from "swr";
import { NetworkPanel, EventEmitter } from "./NetworkPanel";
import { NetworkPanel } from "./NetworkPanel";
import { DevToolsCacheData } from "swr-devtools/lib/swr-cache";

import { Panel } from "./Panel";
import { Tab } from "./Tab";
import { EventEmitter, useRequests, useTracks } from "../request";
import { useDevToolsCache } from "../devtools-cache";

export type PanelType = "current" | "history" | "network";
export type Panel = { label: string; key: PanelType };
Expand Down Expand Up @@ -77,6 +79,12 @@ export const SWRDevToolPanel = ({ cache, events }: Props) => {
const [activePanel, setActivePanel] = useState<Panel["key"]>("current");
const [selectedDevToolsCacheData, selectDevToolsCacheData] =
useState<DevToolsCacheData | null>(null);

const requestsById = useRequests(events);
const tracks = useTracks(requestsById);
const startTime = useState(() => Date.now())[0];
const [currentCacheData, historyCacheData] = useDevToolsCache(cache);

return (
<DevToolWindow>
{/* @ts-expect-error https://github.com/styled-components/styled-components/issues/3738 */}
Expand All @@ -103,10 +111,16 @@ export const SWRDevToolPanel = ({ cache, events }: Props) => {
<PanelWrapper>
{cache !== null && events !== null ? (
activePanel === "network" ? (
<NetworkPanel cache={cache} events={events} type={activePanel} />
<NetworkPanel
requestsById={requestsById}
tracks={tracks}
startTime={startTime}
/>
) : (
<Panel
cache={cache}
cacheData={
activePanel === "current" ? currentCacheData : historyCacheData
}
type={activePanel}
selectedItemKey={selectedDevToolsCacheData}
onSelectItem={selectDevToolsCacheData}
Expand Down
3 changes: 2 additions & 1 deletion packages/swr-devtools-panel/src/devtools-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,14 @@ const retrieveCache = (
};

export const useDevToolsCache = (
cache: Cache
cache: Cache | null
): [DevToolsCacheData[], DevToolsCacheData[]] => {
const [cacheData, setCacheData] = useState<
[DevToolsCacheData[], DevToolsCacheData[]]
>([[], []]);

useEffect(() => {
if (cache === null) return;
const subscribe = createDevToolsCache(cache);
const unsubscribe = subscribe(
(key_: string, value_: Partial<DevToolsCacheData>) => {
Expand Down
Loading