├── .gitignore ├── .npmignore ├── .prettierignore ├── .prettierrc ├── CHANGELOG.md ├── LICENSE.md ├── README.md ├── babel.config.js ├── package.json ├── setupTests.js ├── src ├── SWRDevtools │ ├── Cache.test.ts │ ├── Cache.ts │ ├── Context.tsx │ ├── Data.tsx │ ├── DefaultOpenComponent.tsx │ ├── Icons │ │ ├── AlignBottomIcon.tsx │ │ ├── AlignLeftIcon.tsx │ │ ├── AlignRightIcon.tsx │ │ ├── CloseIcon.tsx │ │ ├── GithubIcon.tsx │ │ └── ReloadIcon.tsx │ ├── Keys │ │ ├── KeyItem.tsx │ │ ├── index.tsx │ │ ├── keys.test.tsx │ │ └── useKeysState.tsx │ ├── Panel │ │ ├── index.tsx │ │ └── usePanelState.tsx │ ├── hooks.tsx │ ├── index.test.tsx │ ├── index.tsx │ ├── themes.tsx │ └── types.ts ├── index.tsx └── test-utils.tsx ├── tsconfig.json └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | esm 4 | *.log 5 | *.tgz 6 | .env 7 | .next 8 | .DS_Store 9 | .idea 10 | examples/**/yarn.lock 11 | package-lock.json 12 | .rts2_cache_cjs/** -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | *.log 3 | *.tgz 4 | .env 5 | .next 6 | .DS_Store -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jjordy/swr-devtools/b216d263ef08fd170fca88d65923bd1346596e5f/.prettierignore -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": true, 3 | "singleQuote": false, 4 | "useTabs": false, 5 | "tabWidth": 2 6 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | ## [v0.2.27] 4 | 5 | ** Fixes ** 6 | - Update documentation to follow latest api signatures 7 | - Remove positioning functionality in lieu of moveable and resizable window. 8 | - Remove open component icon in lieu of smaller and less obtrusive button with text. 9 | - Remember resized width and height when you reopen devtools. (IndexDB) 10 | 11 | ## [1.0.0] 12 | ** Package and security updates 4/26/2021 ** 13 | - Update all packages to latest versions 14 | - Fix a few small bugs 15 | - update theme switcher to simple button 16 | - cleanup padding in keys 17 | 18 | ## [1.0.1] 19 | - Remove validating keys from cache for display 20 | - Further cleanup padding and UI (still work in progress) 21 | 22 | ## [1.0.2] 23 | - Feature make the keys window draggable 24 | 25 | ## [1.0.3] 26 | - Fixed default styling (tricked by tailwind and storybook) 27 | 28 | ## [1.0.4] 29 | - Fixed Data window to always be current width and height 30 | 31 | ## [2.0.0] 32 | - Upgrade to SWR 1.0 33 | - Slightly change implementation to work with new cache from swr. 34 | - Upgrade dependencies 35 | 36 | ## [2.0.4] 37 | - Implement custom cache to bring back old subscribe functionality 38 | ## [2.0.6] 39 | - More fixes and remove indexdb approach store 1 theme value in localstorage instead. 40 | 41 | # [2.1.2] 42 | - Fixes middleware issues using post message. Clearing and mutating should work again as well. 43 | - Cleaned up UI. 44 | # [2.2.0] 45 | - Add search bar to filter keys by query term. 46 | - More UI Cleanup 47 | - Cleanup placement logic for initial window try to support more screen sizes so the window doesnt appear half way off the screen. -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright (c) 2010-2020 Jordan Addison. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SWR Devtools 2 | 3 | Devtools for [swr](https://swr.now.sh/) 4 | 5 | ## Table of Contents 6 | 7 | * [Screenshot](#Screenshot) 8 | * [Live Demo](#live-demo) 9 | * [CodeSandbox](#codesandbox) 10 | * [Install](#install) 11 | * [Usage](#usage) 12 | * [Props](#props) 13 | * [Maintainers](#maintainers) 14 | * [License](#license) 15 | 16 | ## Live Demo 17 | [![Edit swr-devtools (forked)](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/exciting-benz-t5pq0?file=/src/App.tsx) 18 | 19 | 20 | ## Install 21 | 22 | #### NPM 23 | 24 | ```bash 25 | npm install @jjordy/swr-devtools 26 | ``` 27 | 28 | #### Yarn 29 | 30 | ```bash 31 | yarn add @jjordy/swr-devtools 32 | ``` 33 | 34 | #### Usage 35 | 36 | **``swr - 1.0.0`` is required at minimum .** 37 | 38 | Import SWRDevtools and our custom devtools cache and use like below. 39 | Custom cache is required > 1.0 swr to re-implement subscribe behavior which swr devtools relys on. 40 | The SWRConfig with custom devtools cache should be above any request using swr. 41 | ```javascript 42 | import { SWRConfig } from "swr"; 43 | import SWRDevtools from "@jjordy/swr-devtools"; 44 | 45 | export default function App({ Component, pageProps }) { 46 | return ( 47 | 48 | 49 | 50 | ); 51 | } 52 | ``` 53 | 54 | #### Props 55 | 56 | 57 | | Name | Type | Required | Default | 58 | |---|---|---|---| 59 | | CustomOpenComponent | `React.ReactNode` | no | 60 | | debug | `boolean` | no | 61 | | position | `string`: `"right","left"` | no | right 62 | 63 | 64 | 65 | ## Maintainers 66 | 67 | * Jordan Addison 68 | 69 | ## License 70 | 71 | The MIT License (MIT) 72 | 73 | Copyright (c) 2021 Jordan Addison 74 | 75 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 76 | 77 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 78 | 79 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | // babel.config.js 2 | module.exports = { 3 | presets: [ 4 | ["@babel/preset-env", { targets: { node: "current" } }], 5 | "@babel/preset-react", 6 | "@babel/preset-typescript", 7 | ], 8 | }; 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@jjordy/swr-devtools", 3 | "version": "2.2.0", 4 | "description": "Devtools for SWR", 5 | "private": false, 6 | "main": "./dist/index.js", 7 | "module": "./esm/index.js", 8 | "types": "./dist/index.d.ts", 9 | "files": [ 10 | "dist/**", 11 | "esm/**" 12 | ], 13 | "scripts": { 14 | "build": "rimraf esm && rimraf dist && npm run build:esm && npm run build:cjs", 15 | "build:esm": "tsc --target ESNext --module ES6 --outDir esm", 16 | "build:cjs": "ncc build src/index.tsx -o dist -m -e react", 17 | "dev": "tsc --watch", 18 | "storybook": "start-storybook -p 9001", 19 | "test": "jest", 20 | "watch": "tsc --watch" 21 | }, 22 | "keywords": [ 23 | "SWR", 24 | "Devtools", 25 | "Devtool" 26 | ], 27 | "jest": { 28 | "testEnvironment": "jsdom", 29 | "roots": [ 30 | "/src" 31 | ], 32 | "setupFilesAfterEnv": [ 33 | "./setupTests.js" 34 | ] 35 | }, 36 | "author": "Jordan Addison ", 37 | "license": "MIT", 38 | "devDependencies": { 39 | "@babel/preset-env": "^7.15.8", 40 | "@babel/preset-react": "^7.14.5", 41 | "@babel/preset-typescript": "^7.15.0", 42 | "@testing-library/jest-dom": "^5.14.1", 43 | "@testing-library/react": "^12.1.2", 44 | "@types/jest": "^27.0.2", 45 | "@types/node": "^16.11.1", 46 | "@types/react": "^17.0.30", 47 | "@types/react-dom": "^17.0.9", 48 | "@vercel/ncc": "^0.31.1", 49 | "babel-jest": "^27.3.1", 50 | "jest": "^27.3.1", 51 | "react-test-renderer": "^17.0.2", 52 | "rimraf": "^3.0.2", 53 | "swr": "^1.0.1", 54 | "typescript": "^4.4.4" 55 | }, 56 | "dependencies": { 57 | "react-json-view": "^1.21.3", 58 | "react-rnd": "^10.3.5" 59 | }, 60 | "peerDependencies": { 61 | "react": "^17.0.2", 62 | "react-dom": "^17.0.2", 63 | "swr": "^1.0.0" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /setupTests.js: -------------------------------------------------------------------------------- 1 | // optional: configure or set up a testing framework before each test 2 | // if you delete this file, remove `setupFilesAfterEnv` from `jest.config.js` 3 | 4 | // used for __tests__/testing-library.js 5 | // learn more: https://github.com/testing-library/jest-dom 6 | import "@testing-library/jest-dom/extend-expect"; 7 | import "@testing-library/jest-dom"; -------------------------------------------------------------------------------- /src/SWRDevtools/Cache.test.ts: -------------------------------------------------------------------------------- 1 | import { expect, test, describe, jest } from "@jest/globals" 2 | 3 | describe("(TODO) Updated Cache tests", () => { 4 | test("It Creates a Cache", () => { 5 | expect.assertions(1); 6 | expect(true).toBe(true) 7 | }); 8 | }) -------------------------------------------------------------------------------- /src/SWRDevtools/Cache.ts: -------------------------------------------------------------------------------- 1 | import { Cache } from "swr"; 2 | 3 | export type SWRCacheData = { 4 | id: number; 5 | key: string; 6 | data: any; 7 | isValidating: boolean; 8 | error: string; 9 | timestamp: Date; 10 | timestampString: string; 11 | }; 12 | 13 | export const injectSWRCache = ( 14 | cache: Cache, 15 | watcher: (key: string, value: any) => void 16 | ): void => { 17 | // intercept operations modifying the cache store 18 | const originalSet = cache.set; 19 | cache.set = (key: string, value: any) => { 20 | watcher(key, value); 21 | return originalSet.call(cache, key, value); 22 | }; 23 | const originalDelete = cache.delete; 24 | cache.delete = (key: string) => { 25 | watcher(key, undefined); 26 | return originalDelete.call(cache, key); 27 | }; 28 | 29 | }; 30 | 31 | export const isMetaCache = (key: string) => { 32 | return /^\$(?:req|err|ctx|len)\$/.test(key); 33 | }; 34 | 35 | export const isInfiniteCache = (key: string) => { 36 | return /^\$inf\$/.test(key); 37 | }; 38 | 39 | export const getInfiniteCacheKey = (key: string) => { 40 | const match = key.match(/^\$inf\$(?.*)?/); 41 | return match?.groups?.cacheKey ?? key; 42 | }; 43 | -------------------------------------------------------------------------------- /src/SWRDevtools/Context.tsx: -------------------------------------------------------------------------------- 1 | import React, { useCallback, useState } from "react"; 2 | 3 | export const DevToolsContext = React.createContext({ 4 | data: {}, 5 | add: (_key: string, _value: any) => {}, 6 | }); 7 | 8 | export const ContextProvider = ({ children }) => { 9 | const [data, setData] = useState({}); 10 | const add = useCallback( 11 | (key: string, value: any) => { 12 | setData({ ...data, [key]: value }); 13 | }, 14 | [data, setData] 15 | ); 16 | return ( 17 | 23 | {children} 24 | 25 | ); 26 | }; 27 | -------------------------------------------------------------------------------- /src/SWRDevtools/Data.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, memo } from "react"; 2 | import themes from "./themes"; 3 | import { DataProps } from "./types"; 4 | 5 | const isPrimitive = (val) => { 6 | if (val === null) { 7 | return true; 8 | } 9 | 10 | if (typeof val == "object" || typeof val == "function") { 11 | return false; 12 | } else { 13 | return true; 14 | } 15 | }; 16 | 17 | export default memo(function Data({ JsonViewer, data, theme, resizing }: DataProps) { 18 | useEffect(() => { 19 | JsonViewer.current = require("react-json-view").default; 20 | }, []); 21 | return ( 22 |
23 |
34 | {!resizing && ( 35 | 42 | )} 43 |
44 |
45 | ); 46 | }); 47 | -------------------------------------------------------------------------------- /src/SWRDevtools/DefaultOpenComponent.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const DefaultOpenComponent = ( 4 | 17 | SWR DEVTOOLS 18 | 19 | ); 20 | 21 | export default DefaultOpenComponent; 22 | -------------------------------------------------------------------------------- /src/SWRDevtools/Icons/AlignBottomIcon.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | export default function AlignBottomIcon() { 4 | return ( 5 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | ); 41 | } 42 | -------------------------------------------------------------------------------- /src/SWRDevtools/Icons/AlignLeftIcon.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | export default function AlignLeftIcon () { 4 | return ( 5 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | ); 21 | } -------------------------------------------------------------------------------- /src/SWRDevtools/Icons/AlignRightIcon.tsx: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | 3 | export default function AlignRightIcon () { 4 | return ( 5 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | ); 21 | } -------------------------------------------------------------------------------- /src/SWRDevtools/Icons/CloseIcon.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | export default function CloseIcon ({ fill = "white", height = 16, width = 16}) { 4 | return ( 5 | 14 | 15 | 16 | ); 17 | } -------------------------------------------------------------------------------- /src/SWRDevtools/Icons/GithubIcon.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | export default function GithubIcon({ fill = "white", width = 16, height = 16}) { 4 | return ( 5 | 13 | GitHub icon 14 | 15 | 16 | ); 17 | } 18 | -------------------------------------------------------------------------------- /src/SWRDevtools/Icons/ReloadIcon.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | export default function ReloadIcon() { 4 | return ( 5 | 16 | 17 | 18 | 26 | 27 | 28 | 29 | 30 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | ); 57 | } 58 | -------------------------------------------------------------------------------- /src/SWRDevtools/Keys/KeyItem.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import CloseIcon from "../Icons/CloseIcon"; 3 | import ReloadIcon from "../Icons/ReloadIcon"; 4 | 5 | export default function KeyItem({ cacheKey, onSelect, selectedKey, onClear, onRevalidate }) { 6 | return ( 7 |
onSelect(cacheKey)} 9 | style={{ 10 | width: "100%", 11 | boxSizing: "border-box", 12 | backgroundColor: cacheKey === selectedKey ? "#90DAE880" : undefined, 13 | // padding: "0.4rem", 14 | }} 15 | > 16 |
25 |
26 | 43 |
44 | 61 | 75 | {cacheKey} 76 | 77 |
78 |
79 | ); 80 | } 81 | -------------------------------------------------------------------------------- /src/SWRDevtools/Keys/index.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { Rnd } from "react-rnd"; 3 | import themes from "../themes"; 4 | import { KeysProps } from "../types"; 5 | import useKeysState from "./useKeysState"; 6 | import KeyItem from "./KeyItem"; 7 | import CloseIcon from "../Icons/CloseIcon"; 8 | 9 | export default function Keys({ 10 | keys, 11 | selectedKey, 12 | onSelect, 13 | onClear, 14 | onRevalidate, 15 | theme, 16 | panelWidth, 17 | children = <>, 18 | }: KeysProps) { 19 | const { 20 | handleResize, 21 | query, 22 | handleSetQuery, 23 | handleClearQuery, 24 | state: { width, height }, 25 | } = useKeysState(); 26 | return ( 27 | <> 28 | 29 |
40 |
51 | 64 | 78 |
79 | {!query && 80 | keys.map((cacheKey: string) => ( 81 | 89 | ))} 90 | {query && 91 | keys 92 | .filter((k) => k.includes(query)) 93 | .map((cacheKey: string) => ( 94 | 102 | ))} 103 |
104 |
105 |
108 | {children} 109 |
110 | 111 | ); 112 | } 113 | -------------------------------------------------------------------------------- /src/SWRDevtools/Keys/keys.test.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import KeysComponent from "."; 3 | import { describe, test, expect } from "@jest/globals"; 4 | import { render, screen } from "../../test-utils"; 5 | import "fake-indexeddb/auto"; 6 | 7 | export interface KeysProps { 8 | keys: string[]; 9 | selectedKey: string; 10 | onSelect: (key: string) => void; 11 | onClear: (key: string) => void; 12 | onRevalidate: (key: string) => void; 13 | theme: string; 14 | children?: React.ReactNode; 15 | panelWidth?: number; 16 | } 17 | 18 | const keys=['https://test.com/test/1', 'https://test.com/test/2'] 19 | 20 | describe("SWR Devtools", () => { 21 | test("Should render a component", async () => { 22 | expect.assertions(1); 23 | await render( 24 | {}} 28 | onClear={() => {}} 29 | onRevalidate={() => {}} 30 | theme={"Dark"} 31 | /> 32 | ); 33 | const title = await screen.getByText("Cache Keys"); 34 | expect(title).toBe(title); 35 | }); 36 | }); 37 | -------------------------------------------------------------------------------- /src/SWRDevtools/Keys/useKeysState.tsx: -------------------------------------------------------------------------------- 1 | import { useCallback, useState } from "react"; 2 | import { throttle } from "../hooks"; 3 | 4 | export default function useKeysState() { 5 | const [query, setQuery] = useState(""); 6 | const [state, setState] = useState({ width: 325, height: 400 }); 7 | const handle = throttle((width, position) => { 8 | setState({ 9 | height: 400, 10 | width, 11 | ...position, 12 | }); 13 | }, 25); 14 | const handleResize = useCallback( 15 | //@ts-ignore 16 | async (e, direction, ref, delta, position) => { 17 | handle(parseInt(ref.style.width, 10), position); 18 | }, 19 | [setState] 20 | ); 21 | 22 | const handleSetQuery = useCallback( 23 | (evt) => { 24 | setQuery(evt.target.value); 25 | }, 26 | [setQuery] 27 | ); 28 | 29 | const handleClearQuery = useCallback(() => { 30 | setQuery(""); 31 | }, [setQuery]) 32 | return { 33 | handleResize, 34 | state, 35 | query, 36 | handleSetQuery, 37 | handleClearQuery, 38 | }; 39 | } 40 | -------------------------------------------------------------------------------- /src/SWRDevtools/Panel/index.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import usePanelState from "./usePanelState"; 3 | import { Rnd } from "react-rnd"; 4 | import { PanelProps } from "../types"; 5 | import GithubIcon from "../Icons/GithubIcon"; 6 | import CloseIcon from "../Icons/CloseIcon"; 7 | import themes from "../themes"; 8 | 9 | export default function Panel({ 10 | toolbarPosition, 11 | previousToolbarPosition, 12 | show, 13 | children, 14 | toggleShow, 15 | debug, 16 | }: PanelProps) { 17 | const { 18 | theme, 19 | handleChangeTheme, 20 | width, 21 | height, 22 | x, 23 | y, 24 | setResizing, 25 | resizing, 26 | handleResize, 27 | } = usePanelState({ 28 | toolbarPosition, 29 | previousToolbarPosition, 30 | debug, 31 | show, 32 | }); 33 | return ( 34 | <> 35 | {show && ( 36 | { 39 | if (!resizing) { 40 | setResizing(true) 41 | } 42 | }} 43 | default={{ 44 | x, 45 | y, 46 | width, 47 | height, 48 | }} 49 | style={{ 50 | cursor: "auto", 51 | position: "fixed", 52 | zIndex: 999999, 53 | }} 54 | > 55 |
56 |
57 | 64 | SWR Devtools 65 | 66 |
67 | 80 |
81 |
82 | {children({ theme, width, resizing })} 83 |
84 | 89 | 90 | 91 |
92 | 100 | 126 |
127 |
128 |
129 |
130 | )} 131 | 132 | ); 133 | } 134 | -------------------------------------------------------------------------------- /src/SWRDevtools/Panel/usePanelState.tsx: -------------------------------------------------------------------------------- 1 | import { useState, useCallback, useEffect } from "react"; 2 | import { useWindowSize } from "../hooks"; 3 | import { UsePanelStateProps } from "../types"; 4 | 5 | const getX = (windowWidth, width) => { 6 | let x = 0; 7 | if (typeof window !== "undefined") { 8 | x = windowWidth / 2 - width / 2; 9 | } 10 | return x; 11 | }; 12 | 13 | const getY = (windowHeight, _height) => { 14 | let y = 0; 15 | if (typeof window !== "undefined") { 16 | y = (windowHeight / 2) + window.scrollY - 200; 17 | } 18 | return y; 19 | }; 20 | 21 | export default function usePanelState({ show }: UsePanelStateProps) { 22 | const [theme, setTheme] = useState("Dark"); 23 | const [resizing, setResizing] = useState(false); 24 | const { width: windowWidth, height: windowHeight } = useWindowSize(); 25 | const [width, setWidth] = useState(800); 26 | const [height, setHeight] = useState(400); 27 | 28 | useEffect(() => { 29 | const existingSelectedTheme = localStorage.getItem("__SWR__DEVTOOLS__THEME__"); 30 | if (existingSelectedTheme) { 31 | setTheme(existingSelectedTheme); 32 | } 33 | }, []) 34 | const handleResize = useCallback( 35 | async ( 36 | //@ts-ignore 37 | e: MouseEvent | TouchEvent, 38 | //@ts-ignore 39 | dir: any, 40 | refToElement: React.ElementRef<"div"> 41 | ) => { 42 | setWidth(refToElement.offsetWidth); 43 | setHeight(refToElement.offsetHeight); 44 | setResizing(false); 45 | }, 46 | [setResizing, setWidth, setHeight] 47 | ); 48 | const handleChangeTheme = useCallback( 49 | async (theme) => { 50 | localStorage.setItem("__SWR__DEVTOOLS__THEME__", theme); 51 | setTheme(theme); 52 | }, 53 | [show] 54 | ); 55 | return { 56 | theme, 57 | handleChangeTheme, 58 | handleResize, 59 | resizing, 60 | setResizing, 61 | x: getX(windowWidth, width), 62 | y: getY(windowHeight, height), 63 | height, 64 | width, 65 | }; 66 | } 67 | -------------------------------------------------------------------------------- /src/SWRDevtools/hooks.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useRef } from "react"; 2 | 3 | const events = new Set<() => void>(); 4 | const onResize = () => events.forEach((fn) => fn()); 5 | 6 | export function useWindowSize(options: { throttleMs?: number } = {}) { 7 | const { throttleMs = 100 } = options; 8 | const [size, setSize] = React.useState({ 9 | width: typeof window !== "undefined" ? window.innerWidth : 0, 10 | height: typeof window !== "undefined" ? window.innerHeight : 0, 11 | }); 12 | 13 | const handle = throttle(() => { 14 | setSize({ 15 | width: window.innerWidth, 16 | height: window.innerHeight, 17 | }); 18 | }, throttleMs); 19 | 20 | useEffect(() => { 21 | if (events.size === 0) { 22 | window.addEventListener("resize", onResize, true); 23 | } 24 | 25 | events.add(handle); 26 | 27 | return () => { 28 | events.delete(handle); 29 | 30 | if (events.size === 0) { 31 | window.removeEventListener("resize", onResize, true); 32 | } 33 | }; 34 | }, []); 35 | 36 | return size; 37 | } 38 | 39 | export function throttle void>( 40 | func: T, 41 | threshold: number = 250, 42 | scope?: any 43 | ): T { 44 | let last: number, deferTimer: any; 45 | return function (this: any) { 46 | let context = scope || this; 47 | 48 | let now = Date.now(), 49 | args = arguments; 50 | if (last && now < last + threshold) { 51 | // hold on to it 52 | clearTimeout(deferTimer); 53 | deferTimer = setTimeout(function () { 54 | last = now; 55 | func.apply(context, args as any); 56 | }, threshold); 57 | } else { 58 | last = now; 59 | func.apply(context, args as any); 60 | } 61 | } as T; 62 | } 63 | 64 | export function usePrevious(value: any) { 65 | const ref = useRef(); 66 | useEffect(() => { 67 | ref.current = value; 68 | }); 69 | return ref.current; 70 | } 71 | -------------------------------------------------------------------------------- /src/SWRDevtools/index.test.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import SWRDevtools from "."; 3 | import { describe, test, expect } from "@jest/globals"; 4 | import { render, screen } from "../test-utils"; 5 | 6 | describe("SWR Devtools", () => { 7 | test("Should render a component", async () => { 8 | expect.assertions(1); 9 | render(Hello WOrld); 10 | const title = await screen.getByTitle("Open SWR Devtools"); 11 | //@ts-ignore 12 | expect(title).toHaveTextContent("SWR DEVTOOLS"); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /src/SWRDevtools/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect, useRef, useMemo } from "react"; 2 | import Data from "./Data"; 3 | import Keys from "./Keys"; 4 | import Panel from "./Panel"; 5 | import { ToolbarPositions, SWRDevtoolsProps } from "./types"; 6 | import { usePrevious } from "./hooks"; 7 | import { useSWRConfig } from "swr"; 8 | import DefaultOpenComponent from "./DefaultOpenComponent"; 9 | 10 | export function SWRDevtoolsInternal({ 11 | debug = false, 12 | position = "right", 13 | CustomOpenComponent, 14 | openBtnPosition = "left", 15 | defaultOpen = false, 16 | }: SWRDevtoolsProps) { 17 | const [data, setData] = useState({}); 18 | const { cache, mutate } = useSWRConfig(); 19 | const [show, toggleShow] = useState(false); 20 | //@ts-ignore 21 | const ReactJson = useRef((props: any) => <>); 22 | const [toolbarPosition, setToolbarPosition] = 23 | useState(position); 24 | const prevPosition = usePrevious(toolbarPosition); 25 | const [selectedCacheItemData, setSelectedCacheItemData] = useState(null); 26 | const [selectedCacheKey, setSelectedCacheKey] = useState(null); 27 | const handleToggleShow = () => toggleShow(!show); 28 | const handlePostMessage = (event) => { 29 | if (debug) { 30 | console.log(event) 31 | } 32 | if (event.data) { 33 | const { key, value } = event.data; 34 | setData({ ...data, [key]: value }); 35 | } 36 | }; 37 | useEffect(() => { 38 | if (debug) { 39 | console.log("Message listenered added for SWR - Devtools"); 40 | } 41 | window.addEventListener("message", handlePostMessage); 42 | return () => { 43 | window.removeEventListener("message", handlePostMessage); 44 | }; 45 | }, [handlePostMessage]); 46 | useEffect(() => toggleShow(defaultOpen), [defaultOpen]); 47 | 48 | const handleSelectedCacheItem = (key: string) => { 49 | setSelectedCacheKey(key); 50 | setSelectedCacheItemData(cache.get(key)); 51 | }; 52 | 53 | const clearCacheByKey = (key: string) => { 54 | cache.set(key, null); 55 | }; 56 | 57 | const revalidate = (_key: string) => { 58 | mutate(_key).then((d) => setSelectedCacheItemData(d)); 59 | }; 60 | const keys = useMemo(() => (data ? Object.keys(data) : []), [data]); 61 | return ( 62 | <> 63 | {!show && ( 64 |
74 | 85 |
86 | )} 87 | 95 | {({ theme, width: panelWidth, resizing }) => ( 96 |
104 |
105 | 114 | 122 | 123 |
124 |
125 | )} 126 |
127 | 128 | ); 129 | } 130 | 131 | export default SWRDevtoolsInternal; 132 | -------------------------------------------------------------------------------- /src/SWRDevtools/themes.tsx: -------------------------------------------------------------------------------- 1 | import { Themes, Theme } from "./types"; 2 | 3 | const Dark: Theme = { 4 | header: { 5 | backgroundImage: "linear-gradient(90deg,#0f2027,#203a43,#2c5364)", 6 | display: "flex", 7 | justifyContent: "space-between", 8 | paddingTop: "1rem", 9 | paddingBottom: "1rem", 10 | paddingLeft: "1rem", 11 | paddingRight: "2rem", 12 | alignItems: "center", 13 | color: "#FFF" 14 | }, 15 | container: { 16 | position: "relative", 17 | height: "100%", 18 | display: "flex", 19 | flexDirection: "column" 20 | }, 21 | keys: { 22 | backgroundColor: "#231f20E6", 23 | color: "#FFF" 24 | }, 25 | data: { 26 | backgroundColor: "#231f20" 27 | }, 28 | bottom: { 29 | opacity: 0.9, 30 | backgroundColor: "#222", 31 | display: "flex", 32 | justifyContent: "space-between", 33 | alignItems: "center", 34 | paddingRight: "2rem", 35 | paddingLeft: "2rem", 36 | paddingBottom: "0.5rem", 37 | paddingTop: "0.5rem", 38 | boxSizing: "border-box" 39 | } 40 | }; 41 | 42 | const Light: Theme = { 43 | header: { 44 | backgroundImage: "linear-gradient(120deg,#a6c0fe,#f68084)", 45 | color: "#FFF", 46 | display: "flex", 47 | justifyContent: "space-between", 48 | paddingTop: "1rem", 49 | paddingBottom: "1rem", 50 | paddingLeft: "1rem", 51 | paddingRight: "2rem", 52 | alignItems: "center", 53 | }, 54 | container: { 55 | position: "relative", 56 | display: "flex", 57 | flexDirection: "column", 58 | // backgroundColor: "#222", 59 | boxShadow: "0 10px 15px -3px rgba(0, 0, 0, 0.1)", 60 | }, 61 | keys: { 62 | backgroundColor: "#fff", 63 | color: "#222", 64 | }, 65 | data: { 66 | backgroundColor: "#fff", 67 | }, 68 | bottom: { 69 | opacity: 0.9, 70 | backgroundColor: "#fff", 71 | display: "flex", 72 | justifyContent: "space-between", 73 | alignItems: "center", 74 | paddingRight: "2rem", 75 | paddingLeft: "2rem", 76 | paddingBottom: "0.5rem", 77 | paddingTop: "0.5rem", 78 | boxSizing: "border-box", 79 | }, 80 | }; 81 | 82 | const themes: Themes = { 83 | Dark, 84 | Light 85 | }; 86 | 87 | export default themes; 88 | -------------------------------------------------------------------------------- /src/SWRDevtools/types.ts: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | export type ToolbarPositions = "right" | "left" | "bottom" | ""; 4 | 5 | export interface SWRDevtoolsProps { 6 | children: React.ReactNode; 7 | /** Custom open component to be rendered inside the open button */ 8 | CustomOpenComponent?: React.ReactNode; 9 | /** This will print relavent position information to the console */ 10 | debug?: boolean; 11 | /** Default the devtools to being open on render */ 12 | defaultOpen?: boolean; 13 | /** The default position you would like the devtools to appear in. */ 14 | position?: ToolbarPositions; 15 | /** Customize the position of the open button / component */ 16 | openBtnPosition?: "left" | "right"; 17 | } 18 | 19 | export interface UsePanelStateProps { 20 | debug?: boolean; 21 | toolbarPosition: ToolbarPositions; 22 | previousToolbarPosition: ToolbarPositions; 23 | show: boolean; 24 | } 25 | 26 | export interface PanelProps { 27 | toolbarPosition: ToolbarPositions; 28 | previousToolbarPosition: ToolbarPositions; 29 | show: boolean; 30 | children: ({ 31 | theme, 32 | width, 33 | resizing, 34 | }: { 35 | theme: string; 36 | width: number; 37 | resizing: boolean; 38 | }) => React.ReactNode; 39 | setToolbarPosition: (position: ToolbarPositions) => void; 40 | toggleShow: () => void; 41 | debug?: boolean; 42 | } 43 | 44 | export interface KeysProps { 45 | keys: string[]; 46 | selectedKey: string; 47 | onSelect: (key: string) => void; 48 | onClear: (key: string) => void; 49 | onRevalidate: (key: string) => void; 50 | theme: string; 51 | children?: React.ReactNode; 52 | panelWidth?: number; 53 | } 54 | 55 | export interface DataProps { 56 | JsonViewer: any; 57 | toolbarPosition: ToolbarPositions; 58 | data: any; 59 | resizing?: boolean; 60 | theme: string; 61 | cacheKey: string; 62 | } 63 | 64 | export interface Themes { 65 | [key: string]: Theme; 66 | } 67 | 68 | export interface Theme { 69 | container: { 70 | [key: string]: any; 71 | }; 72 | header: { 73 | [key: string]: any; 74 | }; 75 | keys: { 76 | [key: string]: any; 77 | }; 78 | data: { 79 | [key: string]: any; 80 | }; 81 | bottom: { 82 | [key: string]: any; 83 | }; 84 | } 85 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { SWRDevtoolsProps } from "./SWRDevtools/types"; 3 | import { SWRConfig, useSWRConfig, Middleware, Cache } from "swr"; 4 | import { injectSWRCache, isMetaCache } from "./SWRDevtools/Cache"; 5 | 6 | const injected = new WeakSet(); 7 | 8 | const inject = (c: Cache) => 9 | injectSWRCache(c, (key: string, value: any) => { 10 | if (isMetaCache(key)) { 11 | return; 12 | } 13 | if (typeof "window" !== undefined) { 14 | window.postMessage({ key, value }, "*"); 15 | } 16 | }); 17 | 18 | const devtools: Middleware = (useSWRNext) => (key, fn, config) => { 19 | const { cache } = useSWRConfig(); 20 | if (!injected.has(cache)) { 21 | inject(cache); 22 | injected.add(cache); 23 | } 24 | const swr = useSWRNext(key, fn, config); 25 | return swr; 26 | }; 27 | 28 | export function SWRDevtools({ children, ...rest }: SWRDevtoolsProps) { 29 | if (process.env.NODE_ENV === "development") { 30 | const Devtools = require("./SWRDevtools").default; 31 | return ( 32 | 33 | {children} 34 | 35 | 36 | ); 37 | } 38 | return <>{children}; 39 | } 40 | 41 | export default SWRDevtools; 42 | -------------------------------------------------------------------------------- /src/test-utils.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { render } from "@testing-library/react"; 3 | 4 | const WrapperForTests = ({ children }) => { 5 | return
{children}
; 6 | }; 7 | 8 | const customRender = (ui, options = {}) => 9 | render(ui, { wrapper: WrapperForTests, ...options }); 10 | 11 | // re-export everything 12 | export * from "@testing-library/react"; 13 | 14 | // override render method 15 | export { customRender as render }; 16 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "declaration": true, 4 | "esModuleInterop": true, 5 | "jsx": "react", 6 | "lib": [ 7 | "esnext", 8 | "dom" 9 | ], 10 | "module": "commonjs", 11 | "moduleResolution": "node", 12 | "noEmitOnError": true, 13 | "noFallthroughCasesInSwitch": true, 14 | "noImplicitReturns": true, 15 | "skipLibCheck": true, 16 | "noUnusedLocals": true, 17 | "noUnusedParameters": true, 18 | "outDir": "./dist", 19 | "types": [ 20 | "node" 21 | ], 22 | "target": "es5", 23 | "typeRoots": [ 24 | "./types", 25 | "./node_modules/@types" 26 | ] 27 | }, 28 | "include": [ 29 | "src/**/*" 30 | ], 31 | "exclude": [ 32 | "src/**/*.test.ts", 33 | "node_modules" 34 | ] 35 | } --------------------------------------------------------------------------------