Skip to content

Add URL router and local storage persistence #80

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

Merged
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
2 changes: 2 additions & 0 deletions packages/example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@
"@react-spectrum/table": "^3.0.0-alpha.7",
"@react-spectrum/tabs": "3.0.0-alpha.2",
"@spectrum-icons/workflow": "^3.2.0",
"@types/react-router-dom": "^5.1.6",
"codemirror": "^5.58.3",
"lodash": "^4.17.15",
"react": "^16.12.0",
"react-codemirror2": "^7.2.1",
"react-dom": "^16.12.0",
"react-redux": "^7.2.1",
"react-router-dom": "^5.2.0",
"redux": "^4.0.4"
},
"scripts": {
Expand Down
158 changes: 101 additions & 57 deletions packages/example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,30 @@
THE SOFTWARE.
*/

import React, { useCallback } from 'react';
import React, { useCallback, useEffect, useRef } from 'react';
import { JsonFormsDispatch, JsonFormsReduxContext } from '@jsonforms/react';
import {
Heading,
Picker,
Item,
Section,
Content,
View,
} from '@adobe/react-spectrum';
import { useParams, useHistory } from 'react-router-dom';
import { Heading, Item, Content, View } from '@adobe/react-spectrum';
import { Tabs } from '@react-spectrum/tabs';
import './App.css';
import { AppProps, initializedConnect } from './reduxUtil';
import {
initializedConnect,
ExampleStateProps,
ExampleDispatchProps,
} from './reduxUtil';
import { TextArea } from './TextArea';
import { ReactExampleDescription } from './util';
import {
getExamplesFromLocalStorage,
setExampleInLocalStorage,
localPrefix,
localLabelSuffix,
} from './persistedExamples';
import { ExamplesPicker } from './ExamplesPicker';

function App(props: AppProps) {
interface AppProps extends ExampleStateProps, ExampleDispatchProps {}

function App(props: AppProps & { selectedExample: ReactExampleDescription }) {
const setExampleByName = useCallback(
(exampleName: string | number) => {
const example = props.examples.find(
Expand All @@ -56,30 +64,33 @@ function App(props: AppProps) {

const updateCurrentSchema = useCallback(
(newSchema: string) => {
props.changeExample({
...props.selectedExample,
schema: JSON.parse(newSchema),
});
props.changeExample(
createExample(props.selectedExample, {
schema: JSON.parse(newSchema),
})
);
},
[props.changeExample, props.selectedExample]
);

const updateCurrentUISchema = useCallback(
(newUISchema: string) => {
props.changeExample({
...props.selectedExample,
uischema: JSON.parse(newUISchema),
});
props.changeExample(
createExample(props.selectedExample, {
uischema: JSON.parse(newUISchema),
})
);
},
[props.changeExample, props.selectedExample]
);

const updateCurrentData = useCallback(
(newData: string) => {
props.changeExample({
...props.selectedExample,
data: JSON.parse(newData),
});
props.changeExample(
createExample(props.selectedExample, {
data: JSON.parse(newData),
})
);
},
[props.changeExample, props.selectedExample]
);
Expand All @@ -96,7 +107,7 @@ function App(props: AppProps) {
<div className='App-Form'>
<View padding='size-100'>
<Heading>{props.selectedExample.label}</Heading>
{props.getExtensionComponent()}
{props.getComponent(props.selectedExample)}
<JsonFormsDispatch onChange={props.onChange} />
</View>
</div>
Expand All @@ -105,7 +116,7 @@ function App(props: AppProps) {
<View padding='size-100'>
<Heading>JsonForms Examples</Heading>
<ExamplesPicker {...props} onChange={setExampleByName} />
<Tabs defaultSelectedKey='schema'>
<Tabs defaultSelectedKey='boundData'>
<Item key='boundData' title='Bound data'>
<Content margin='size-100'>
<TextArea
Expand Down Expand Up @@ -148,41 +159,74 @@ function App(props: AppProps) {
);
}

export default initializedConnect(App);
function AppWithExampleInURL(props: AppProps) {
const urlParams = useParams<{ name: string | undefined }>();
const history = useHistory();
const examplesRef = useRef([
...props.examples,
...getExamplesFromLocalStorage(),
]);
const examples = examplesRef.current;

function ExamplesPicker(
props: Omit<AppProps, 'onChange'> & {
onChange: (exampleName: string | number) => void;
}
) {
const options = [
{
name: 'React Spectrum Tests',
children: props.examples
.filter((example) => example.name.startsWith('spectrum-'))
.map((item) => ({ ...item, id: item.name })),
},
{
name: 'JSONForms Tests',
children: props.examples
.filter((example) => !example.name.startsWith('spectrum-'))
.map((item) => ({ ...item, id: item.name })),
const selectedExample = urlParams.name
? examples.find(({ name }) => urlParams.name === name)
: examples[examples.length - 1];

const changeExample = useCallback(
(example: ReactExampleDescription) => {
// If we're trying to modify an item, save it to local storage and update the list of examples
if (example.name.startsWith(localPrefix)) {
setExampleInLocalStorage(example);
examplesRef.current = [
...props.examples,
...getExamplesFromLocalStorage(),
];
}
history.push(`/${example.name}`);
},
];
[props.changeExample, history]
);

// When URL changes, we have to call changeExample to dispatch some jsonforms redux actions
useEffect(() => {
if (selectedExample) {
props.changeExample(selectedExample);
}
}, [selectedExample]);

// If name is invalid, redirect to home
if (!selectedExample) {
console.error(
`Could not find an example with name "${urlParams.name}", redirecting to /`
);
history.push('/');
return null;
}

return (
<Picker
aria-label='JSONForms Examples'
items={options}
width='100%'
defaultSelectedKey={props.selectedExample.name}
onSelectionChange={props.onChange}
>
{(item) => (
<Section key={item.name} items={item.children} title={item.name}>
{(item) => <Item>{item.label}</Item>}
</Section>
)}
</Picker>
<App
{...props}
examples={examples}
selectedExample={selectedExample}
changeExample={changeExample}
/>
);
}

export const ConnectedApp = initializedConnect(AppWithExampleInURL);

function createExample(
example: ReactExampleDescription,
part: Partial<ReactExampleDescription>
): ReactExampleDescription {
return {
...example,
name: example.name.startsWith(localPrefix)
? example.name
: `${localPrefix}${example.name}`,
label: example.label.endsWith(localLabelSuffix)
? example.label
: `${example.label}${localLabelSuffix}`,
...part,
};
}
86 changes: 86 additions & 0 deletions packages/example/src/ExamplesPicker.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
The MIT License

Copyright (c) 2020 headwire.com, Inc
https://github.com/headwirecom/jsonforms-react-spectrum-renderers

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.
*/

import { Item, Picker, Section } from '@adobe/react-spectrum';
import React, { useRef } from 'react';
import './App.css';
import { localPrefix } from './persistedExamples';
import { ReactExampleDescription } from './util';

export function ExamplesPicker(props: {
examples: ReactExampleDescription[];
selectedExample: ReactExampleDescription;
onChange: (exampleName: string | number) => void;
}) {
// Re-create Picker instance (by changing key) when examples array changes, otherwise selection won't update on Save
const prevExamples = useRef(props.examples);
const keyRef = useRef(0);
if (prevExamples.current !== props.examples) {
prevExamples.current = props.examples;
keyRef.current++;
}

const options = [
{
name: 'Locally Modified Tests',
children: props.examples
.filter((example) => example.name.startsWith(localPrefix))
.map((item) => ({ ...item, id: item.name })),
},
{
name: 'React Spectrum Tests',
children: props.examples
.filter((example) => example.name.startsWith('spectrum-'))
.map((item) => ({ ...item, id: item.name })),
},
{
name: 'JSONForms Tests',
children: props.examples
.filter(
(example) =>
!example.name.startsWith('spectrum-') &&
!example.name.startsWith(localPrefix)
)
.map((item) => ({ ...item, id: item.name })),
},
].filter((category) => category.children.length);

return (
<Picker
key={keyRef.current}
aria-label='JSONForms Examples'
items={options}
width='100%'
defaultSelectedKey={props.selectedExample.name}
onSelectionChange={props.onChange}
>
{(item) => (
<Section key={item.name} items={item.children} title={item.name}>
{(item) => <Item>{item.label}</Item>}
</Section>
)}
</Picker>
);
}
18 changes: 15 additions & 3 deletions packages/example/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,15 @@
THE SOFTWARE.
*/
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Switch,
Redirect,
Route,
} from 'react-router-dom';
import React from 'react';
import './index.css';
import App from './App';
import { ConnectedApp } from './App';
import { combineReducers, createStore } from 'redux';
import { Provider } from 'react-redux';
import geoschema from './geographical-location.schema';
Expand Down Expand Up @@ -80,7 +86,6 @@ const setupStore = (
renderers: renderers,
},
examples: {
selectedExample: exampleData[exampleData.length - 1],
data: exampleData,
},
});
Expand Down Expand Up @@ -129,7 +134,14 @@ export const renderExample = (
<Provider store={store}>
<SpectrumThemeProvider colorScheme={colorScheme} theme={defaultTheme}>
<ColorSchemeContext.Provider value={colorScheme}>
<App />
<Router>
<Switch>
<Route exact path='/:name?'>
<ConnectedApp />
</Route>
<Redirect to='/' />
</Switch>
</Router>
</ColorSchemeContext.Provider>
</SpectrumThemeProvider>
</Provider>,
Expand Down
Loading