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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add react-properties package #2499

Merged
merged 4 commits into from Jun 24, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .adiorc.js
Expand Up @@ -35,6 +35,7 @@ module.exports = {
"aws-sdk",
"url",
"worker_threads",
"~tests",
"~"
],
dependencies: [
Expand Down
1 change: 1 addition & 0 deletions jest.config.base.js
Expand Up @@ -22,6 +22,7 @@ module.exports = function ({ path }, presets = []) {
},
moduleDirectories: ["node_modules"],
moduleNameMapper: {
"~tests/(.*)": `${path}/__tests__/$1`,
"~/(.*)": `${path}/src/$1`
},
modulePathIgnorePatterns: [],
Expand Down
3 changes: 2 additions & 1 deletion jest.config.js
Expand Up @@ -161,5 +161,6 @@ if (projects.length === 0) {
module.exports = {
projects,
modulePathIgnorePatterns: ["dist"],
testTimeout: 30000
testTimeout: 30000,
watchman: false
};
1 change: 1 addition & 0 deletions packages/react-properties/.babelrc.js
@@ -0,0 +1 @@
module.exports = require("../../.babel.react")({ path: __dirname });
21 changes: 21 additions & 0 deletions packages/react-properties/LICENSE
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Webiny

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:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

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.
65 changes: 65 additions & 0 deletions packages/react-properties/README.md
@@ -0,0 +1,65 @@
# React Properties

[![](https://img.shields.io/npm/dw/@webiny/react-properties.svg)](https://www.npmjs.com/package/@webiny/react-properties)
[![](https://img.shields.io/npm/v/@webiny/react-properties.svg)](https://www.npmjs.com/package/@webiny/react-properties)
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)

A tiny React properties framework, to build dynamic data objects using React components, which can be customized after initial creation. The usage is very similar to how you write XML data structures, but in this case you're using actual React.

## Basic Example

```jsx
import React, { useCallback } from "react";
import { Properties, Property, toObject } from "@webiny/react-properties";

const View = () => {
const onChange = useCallback(properties => {
console.log(toObject(properties));
}, []);

return (
<Properties onChange={onChange}>
<Property name={"group"}>
<Property name={"name"} value={"layout"} />
<Property name={"label"} value={"Layout"} />
<Property name={"toolbar"}>
<Property name={"name"} value={"basic"} />
</Property>
</Property>
<Property name={"group"}>
<Property name={"name"} value={"heroes"} />
<Property name={"label"} value={"Heroes"} />
<Property name={"toolbar"}>
<Property name={"name"} value={"heroes"} />
</Property>
</Property>
</Properties>
);
};
```

Output:

```json
{
"group": [
{
"name": "layout",
"label": "Layout",
"toolbar": {
"name": "basic"
}
},
{
"name": "heroes",
"label": "Heroes",
"toolbar": {
"name": "heroes"
}
}
]
}
```

For more examples, check out the test files.
115 changes: 115 additions & 0 deletions packages/react-properties/__tests__/cases/dashboard/App.tsx
@@ -0,0 +1,115 @@
import * as React from "react";
import { useEffect, useState } from "react";
import {
Compose,
HigherOrderComponent,
makeComposable,
CompositionProvider
} from "@webiny/react-composition";
import { Property, Properties } from "~/index";

interface AddWidgetProps {
name: string;
type: string;
}

const AddWidget = <T extends Record<string, unknown>>(props: T & AddWidgetProps) => {
return (
<Property id={props.name} name={"widget"} array>
{Object.keys(props).map(name => (
<Property key={name} id={`${props.name}:${name}`} name={name} value={props[name]} />
))}
</Property>
);
};

export interface CardWidget extends Record<string, unknown> {
title: string;
description: string;
button: React.ReactElement;
}

const createHOC =
(newChildren: React.ReactNode): HigherOrderComponent =>
BaseComponent => {
return function ConfigHOC({ children }) {
return (
<BaseComponent>
{newChildren}
{children}
</BaseComponent>
);
};
};

const DashboardConfigApply = makeComposable("DashboardConfigApply", ({ children }) => {
return <>{children}</>;
});

interface DashboardConfig extends React.FC<unknown> {
AddWidget: typeof AddWidget;
DashboardRenderer: typeof DashboardRenderer;
}

export const DashboardConfig: DashboardConfig = ({ children }) => {
return <Compose component={DashboardConfigApply} with={createHOC(children)} />;
};

const DashboardRenderer = makeComposable("DashboardRenderer", () => {
return <div>Renderer not implemented!</div>;
});

DashboardConfig.AddWidget = AddWidget;
DashboardConfig.DashboardRenderer = DashboardRenderer;

interface ViewContext {
properties: Property[];
}

const defaultContext = { properties: [] };

const ViewContext = React.createContext<ViewContext>(defaultContext);

interface DashboardViewProps {
onProperties(properties: Property[]): void;
}

const DashboardView: React.FC<DashboardViewProps> = ({ onProperties }) => {
const [properties, setProperties] = useState<Property[]>([]);
const context = { properties };

useEffect(() => {
onProperties(properties);
}, [properties]);

const stateUpdater = (properties: Property[]) => {
setProperties(properties);
};

return (
<ViewContext.Provider value={context}>
<Properties onChange={stateUpdater}>
<DashboardConfigApply />
<DashboardRenderer />
</Properties>
</ViewContext.Provider>
);
};

export const App: React.FC<DashboardViewProps> = ({ onProperties, children }) => {
return (
<CompositionProvider>
<DashboardView onProperties={onProperties} />
<DashboardConfig>
<AddWidget<CardWidget>
name="my-widget"
type="card"
title="My Widget"
description="Custom widget that shows current weather."
button={<button>Show Weather</button>}
/>
</DashboardConfig>
{children}
</CompositionProvider>
);
};
162 changes: 162 additions & 0 deletions packages/react-properties/__tests__/cases/dashboard/dashboard.test.tsx
@@ -0,0 +1,162 @@
import React from "react";
import { render } from "@testing-library/react";
import { Compose, HigherOrderComponent } from "@webiny/react-composition";
import { Property, toObject, useProperties } from "~/index";
import { App, DashboardConfig } from "./App";
import { getLastCall } from "~tests/utils";

const { AddWidget, DashboardRenderer } = DashboardConfig;

describe("Dashboard", () => {
it("should contain 2 widgets (the built-in one, and the custom one)", async () => {
const onChange = jest.fn();
/**
* <App/> contains the built-in widget, and we're using the <DashboardConfig/> component to register more widgets.
*/
const view = (
<App onProperties={onChange}>
<DashboardConfig>
<AddWidget<{ title: string; button: unknown }>
name={"new-widget"}
title={"Latest News"}
type={"card"}
button={<div />}
/>
</DashboardConfig>
</App>
);

render(view);

const properties = getLastCall(onChange);
const data = toObject(properties);

expect(data).toMatchObject({
widget: [
{
name: "my-widget",
title: "My Widget",
type: "card",
button: expect.anything()
},
{
name: "new-widget",
title: "Latest News",
type: "card",
button: <div />
}
]
});
});

it("should contain the built-in widget with modified values", async () => {
const onChange = jest.fn();
const view = (
<App onProperties={onChange}>
<DashboardConfig>
<AddWidget<{ title: string; button: unknown }>
name={"my-widget"}
title={"My own title!"}
type={"card"}
button={null}
/>
</DashboardConfig>
</App>
);

render(view);

const properties = getLastCall(onChange);
const data = toObject(properties);

expect(data).toMatchObject({
widget: [
{
name: "my-widget",
title: "My own title!",
type: "card",
button: null
}
]
});
});

it("should contain new custom properties", async () => {
/**
* Let's create a custom Dashboard renderer to render links (which are our custom property).
*/
const CustomDashboard: HigherOrderComponent = () => {
return function CustomDashboard() {
const { getObject } = useProperties();
const { link } = getObject<{ link: { title: string; url: string }[] }>();

return (
<ul>
{link.map(item => (
<li key={item.title}>
{item.title}: {item.url}
</li>
))}
</ul>
);
};
};

/**
* This custom component will allow us to expose a user-friendly API to developers, hook into the existing
* data structure of the Dashboard, and add our new properties (links in this case).
*/
interface LinkProps {
url: string;
title: string;
}

const Link: React.FC<LinkProps> = ({ url, title }) => {
return (
<Property name={"link"} array>
<Property name={"url"} value={url} />
<Property name={"title"} value={title} />
</Property>
);
};

const onChange = jest.fn();
const view = (
<App onProperties={onChange}>
<DashboardConfig>
{/* Compose the renderer, to intercept the rendering process and render custom Links. */}
<Compose component={DashboardRenderer} with={CustomDashboard} />
{/* Register new properties. */}
<Link title={"Webiny"} url={"www.webiny.com"} />
<Link title={"Google"} url={"www.google.com"} />
</DashboardConfig>
</App>
);

const { container } = render(view);

// Verify the new data structure
const properties = getLastCall(onChange);
const data = toObject(properties);

expect(data).toMatchObject({
widget: [
{
name: "my-widget",
title: "My Widget",
type: "card",
button: expect.anything()
}
],
link: [
{ title: "Webiny", url: "www.webiny.com" },
{ title: "Google", url: "www.google.com" }
]
});

// Verify that our custom renderer is rendering the expected output.
expect(container.innerHTML).toEqual(
"<ul><li>Webiny: www.webiny.com</li><li>Google: www.google.com</li></ul>"
);
});
});