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

ObjectInspector: Add Name #15

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 0 additions & 4 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,3 @@ workflows:
requires:
- lint
- unit-tests
filters:
branches:
only:
- master
11 changes: 11 additions & 0 deletions components/ObjectInspector/src/Context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import React from "react";

export interface ObjectInspectorContextProps {
/** The key for the root object */
name?: string;
}

/** Context that gives sub-components access to top-level props */
export const ObjectInspectorContext = React.createContext<
ObjectInspectorContextProps
>({ name: "" });
22 changes: 21 additions & 1 deletion components/ObjectInspector/src/ObjectInspector.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,26 @@ describe("ObjectInspector", () => {
});
});

test("Displays names", async () => {
const nested = {
one: {
two: {
three: "test",
},
},
};
await act(async () => {
const { getByText } = render(<ObjectInspector data={nested} />);
waitFor(() => expect(getByText("nameTest:")).not.toBeDefined());
});
act(() => {
const { getByText } = render(
<ObjectInspector data={nested} name="nameTest" />
);
waitFor(() => expect(getByText("nameTest:")).toBeDefined());
});
});

test("It calls onSelect correctly", async () => {
const onSelect = jest.fn();
const nested = {
Expand All @@ -77,7 +97,7 @@ describe("ObjectInspector", () => {

await waitFor(() => expect(getByText('"test"')).toBeDefined());

const two = getByText("two:");
const two = getByText("two");

fireEvent.click(two);

Expand Down
16 changes: 11 additions & 5 deletions components/ObjectInspector/src/ObjectInspector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
ResolvedASTNode,
} from "@devtools-ds/object-parser";
import { ThemeableElement, useTheme, ThemeProvider } from "@devtools-ds/themes";
import { ObjectInspectorContext } from "./Context";
import ObjectInspectorItem from "./ObjectInspectorItem";

import styles from "./ObjectInspector.css";
Expand All @@ -15,6 +16,8 @@ interface ObjectInspectorProps
extends Omit<ThemeableElement<"div">, "onSelect"> {
/** JSON data to render in the tree. */
data: SupportedTypes;
/** The key for the root object */
name?: string;
/** Depth of the tree that is open at first render. */
expandLevel: number;
/** Whether to sort keys like the browsers do. */
Expand All @@ -36,6 +39,7 @@ export const ObjectInspector = (props: ObjectInspectorProps) => {
theme,
colorScheme,
onSelect,
name,
...html
} = props;
const [ast, setAST] = useState<ASTNode | undefined>(undefined);
Expand All @@ -61,11 +65,13 @@ export const ObjectInspector = (props: ObjectInspectorProps) => {
>
{ast && (
<ThemeProvider theme={currentTheme} colorScheme={currentColorScheme}>
<ObjectInspectorItem
ast={ast}
expandLevel={expandLevel}
onSelect={onSelect}
/>
<ObjectInspectorContext.Provider value={{ name }}>
<ObjectInspectorItem
ast={ast}
expandLevel={expandLevel}
onSelect={onSelect}
/>
</ObjectInspectorContext.Provider>
</ThemeProvider>
)}
</div>
Expand Down
18 changes: 15 additions & 3 deletions components/ObjectInspector/src/ObjectLabel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
ASTNode,
} from "@devtools-ds/object-parser";
import ObjectValue from "./ObjectValue";
import { ObjectInspectorContext } from "./Context";
import styles from "./ObjectInspector.css";

interface ObjectLabelProps extends ThemeableElement<"span"> {
Expand Down Expand Up @@ -176,6 +177,7 @@ export const ObjectLabel = (props: ObjectLabelProps) => {
className,
...html
} = props;
const { name } = React.useContext(ObjectInspectorContext);
const { themeClass, currentTheme } = useTheme({ theme, colorScheme }, styles);
const isPrototype = ast.isPrototype || false;
const classes = makeClass(styles.objectLabel, themeClass, className, {
Expand All @@ -186,10 +188,20 @@ export const ObjectLabel = (props: ObjectLabelProps) => {

/** The key for the node */
const Key = () => {
let { key } = ast;
if (isRoot && name) key = name;

if (isRoot && !name) {
return null;
}

return (
<span className={isPrototype ? styles.prototype : styles.key}>
{isRoot ? "" : `${ast.key}: `}
</span>
<>
<span className={isPrototype ? styles.prototype : styles.key}>
{key}
</span>
{key && <span className={styles.text}>:&nbsp;</span>}
</>
);
};

Expand Down
33 changes: 29 additions & 4 deletions components/ObjectInspector/src/ObjectValue.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import makeClass from "clsx";
import { ThemeableElement, useTheme } from "@devtools-ds/themes";
import { ASTNode, isObject, getPromiseState } from "@devtools-ds/object-parser";
import styles from "./ObjectInspector.css";
import { ObjectInspectorContext } from "./Context";

interface ObjectValueProps extends ThemeableElement<"span"> {
/** Type of object. */
Expand All @@ -18,20 +19,23 @@ interface ObjectValueProps extends ThemeableElement<"span"> {
* @param value - The value string
* @param valueClass - The class to apply to the value
* @param showKey - Whether or not to show the key with the value
* @param name - The name if the value is the root
* @param depth - Current depth (so we don't put a key on root)
*/
const buildValue = (
key: string,
value: React.ReactNode,
valueClass: string,
showKey: boolean,
name: string,
depth: number
) => {
const computedKey = key.includes("-") ? `"${key}"` : key;
let computedKey = key.includes("-") ? `"${key}"` : key;
const isRoot = depth <= 0;
if (isRoot && name) computedKey = name;
return (
<span className={styles.text}>
{!isRoot && showKey && (
{(!isRoot || name) && showKey && (
<>
<span className={styles.key}>{computedKey}</span>
<span>:&nbsp;</span>
Expand All @@ -45,6 +49,8 @@ const buildValue = (

/** Display a leaf key-value pair with appropriate styles. */
export const ObjectValue = (props: ObjectValueProps) => {
const context = React.useContext(ObjectInspectorContext);
const name = context?.name || "";
const { ast, theme, showKey, colorScheme, className, ...html } = props;
const { themeClass } = useTheme({ theme, colorScheme }, styles);
const [asyncValue, setAsyncValue] = useState(<span />);
Expand All @@ -61,6 +67,7 @@ export const ObjectValue = (props: ObjectValueProps) => {
`Promise { "${await getPromiseState(promise)}" }`,
styles.key,
showKey,
name,
ast.depth
)
);
Expand All @@ -77,6 +84,7 @@ export const ObjectValue = (props: ObjectValueProps) => {
String(ast.value),
styles.number,
showKey,
name,
ast.depth
);
} else if (typeof ast.value === "boolean") {
Expand All @@ -86,6 +94,7 @@ export const ObjectValue = (props: ObjectValueProps) => {
String(ast.value),
styles.boolean,
showKey,
name,
ast.depth
);
} else if (typeof ast.value === "string") {
Expand All @@ -95,6 +104,7 @@ export const ObjectValue = (props: ObjectValueProps) => {
`"${ast.value}"`,
styles.string,
showKey,
name,
ast.depth
);
} else if (typeof ast.value === "undefined") {
Expand All @@ -104,6 +114,7 @@ export const ObjectValue = (props: ObjectValueProps) => {
"undefined",
styles.undefined,
showKey,
name,
ast.depth
);
} else if (typeof ast.value === "symbol") {
Expand All @@ -113,6 +124,7 @@ export const ObjectValue = (props: ObjectValueProps) => {
ast.value.toString(),
styles.string,
showKey,
name,
ast.depth
);
} else if (typeof ast.value === "function") {
Expand All @@ -122,19 +134,28 @@ export const ObjectValue = (props: ObjectValueProps) => {
`${ast.value.name}()`,
styles.key,
showKey,
name,
ast.depth
);
} else if (typeof ast.value === "object") {
if (ast.value === null) {
// Null
value = buildValue(ast.key, "null", styles.null, showKey, ast.depth);
value = buildValue(
ast.key,
"null",
styles.null,
showKey,
name,
ast.depth
);
} else if (Array.isArray(ast.value)) {
// Array
value = buildValue(
ast.key,
`Array(${ast.value.length})`,
styles.key,
showKey,
name,
ast.depth
);
} else if (ast.value instanceof Date) {
Expand All @@ -144,6 +165,7 @@ export const ObjectValue = (props: ObjectValueProps) => {
`Date ${ast.value.toString()}`,
styles.value,
showKey,
name,
ast.depth
);
} else if (ast.value instanceof RegExp) {
Expand All @@ -153,6 +175,7 @@ export const ObjectValue = (props: ObjectValueProps) => {
ast.value.toString(),
styles.regex,
showKey,
name,
ast.depth
);
} else if (ast.value instanceof Error) {
Expand All @@ -162,18 +185,20 @@ export const ObjectValue = (props: ObjectValueProps) => {
ast.value.toString(),
styles.error,
showKey,
name,
ast.depth
);
} else if (isObject(ast.value)) {
// Object
value = buildValue(ast.key, "{…}", styles.key, showKey, ast.depth);
value = buildValue(ast.key, "{…}", styles.key, showKey, name, ast.depth);
} else {
// WeakMap, WeakSet, Custom Classes, etc
value = buildValue(
ast.key,
ast.value.constructor.name,
styles.key,
showKey,
name,
ast.depth
);
}
Expand Down
8 changes: 8 additions & 0 deletions components/ObjectInspector/src/stories/Features.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ export const DisablePrototypes = () => (
<ObjectInspector includePrototypes={false} data={data} />
);

export const NamedObject = () => (
<ObjectInspector name="onSelect()" data={data} />
);

export const NamedValue = () => (
<ObjectInspector name="value" data="Some Data" />
);

export const FontInheritance = () => (
<div style={{ fontSize: `16px` }}>
<ObjectInspector sortKeys={false} data={data} />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from "react";
import { boolean, number } from "@storybook/addon-knobs";
import { boolean, number, text } from "@storybook/addon-knobs";
import { action } from "@storybook/addon-actions";
import { ObjectInspector } from "../ObjectInspector";
import notes from "../../README.md";
Expand Down Expand Up @@ -59,11 +59,20 @@ const data = {
},
};

const nested = {
one: {
two: {
three: "test",
},
},
};

export const Playground = () => {
const onSelect = action("onSelect");
return (
<ObjectInspector
data={data}
data={nested}
name={text("Name", "")}
expandLevel={number("Expand Level", 1)}
sortKeys={boolean("Sort Keys", true)}
includePrototypes={boolean("Include Prototypes", true)}
Expand Down
8 changes: 8 additions & 0 deletions components/ObjectInspector/src/stories/Overview.stories.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ Similarly, you can disable object `prototypes` from being included.
<Story id="components-object-inspector-features--disable-prototypes" />
</Canvas>

### Named Root

You can add a `name` to add a descriptive key to the root node,

<Canvas>
<Story id="components-object-inspector-features--named-object" />
</Canvas>

### onSelect

You can use the `onSelect` prop to get the `@devtools-ds/object-parser` AST node for the currently selected part of the object.
Expand Down
8 changes: 4 additions & 4 deletions packages/themes/src/AutoThemeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import { all } from "./themes";
import { ThemeableElement, ThemeContext } from "./utils";

/** Determine if the current browser is FireFox */
const isFirefox = () => {
export const getBrowserTheme = () => {
if (window?.navigator?.userAgent) {
if (window.navigator.userAgent.toLowerCase().includes("firefox")) {
return true;
return "firefox";
}
}

return false;
return "chrome";
};

export interface AutoThemeProviderProps extends ThemeableElement<"div"> {
Expand Down Expand Up @@ -63,7 +63,7 @@ export const AutoThemeProvider = ({
}: AutoThemeProviderProps) => {
const isDark = useDarkMode();
const colorScheme = propsColorScheme || (isDark ? "dark" : "light");
const theme = propsTheme || (isFirefox() ? "firefox" : "chrome");
const theme = propsTheme || getBrowserTheme();
const style = {
backgroundColor: all[theme][colorScheme].backgroundColor,
color: all[theme][colorScheme].textColor,
Expand Down