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

[WIP] Split types into Field & Admin-View packages #745

Closed
wants to merge 2 commits into from
Closed
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: 1 addition & 1 deletion .changeset/8bd0589c/changes.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
- Allow adding related items from the Relationship field
- Allow adding related items from the Relationship field
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ reports
test-projects/**/cypress
website/.cache/**/*
website/public/**/*
packages/**/dist/*
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ module.exports = {
'**/tests/**/*.js',
'**/examples/**/*.js',
'**/build/**/*.js',
'**/fields/**/filterTests.js',
],
},
],
Expand Down
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ website/public/**/*
demo-projects/todo/.cache
demo-projects/todo/dist
demo-projects/blog/app/.next
packages/**/dist/*
2 changes: 1 addition & 1 deletion demo-projects/todo/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Keystone imports
const { Keystone } = require('@voussoir/core');
const { AdminUI } = require('@voussoir/admin-ui');
const { Text } = require('@voussoir/fields');
const Text = require('@voussoir/field-text');
const { WebServer } = require('@voussoir/server');
const { MongooseAdapter } = require('@voussoir/adapter-mongoose');
const express = require('express');
Expand Down
4 changes: 2 additions & 2 deletions demo-projects/todo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
"dependencies": {
"@voussoir/adapter-mongoose": "^2.0.0",
"@voussoir/admin-ui": "^1.0.0",
"@voussoir/core": "^2.1.0",
"@voussoir/fields": "^3.0.0",
"@voussoir/core": "^2.0.0",
"@voussoir/field-text": "^1.0.0",
"@voussoir/server": "^1.0.0",
"express": "^4.16.3"
}
Expand Down
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@
"pino": "5.0.0-rc.4",
"pluralize": "^7.0.0",
"popper.js": "^1.14.6",
"preconstruct": "^0.0.41",
"preconstruct": "^0.0.42",
"prettier": "^1.15.3",
"pretty-proptypes": "^0.5.0",
"prism-react-renderer": "^0.1.5",
Expand Down Expand Up @@ -207,6 +207,7 @@
"packages/*",
"!packages/arch",
"packages/arch/packages/*",
"packages/fields/types/*",
"demo-projects/*",
"test-projects/*",
"website"
Expand All @@ -215,7 +216,9 @@
"preconstruct": {
"packages": [
"packages/arch/packages/*",
"packages/apollo-helpers"
"packages/apollo-helpers",
"packages/fields/types/*AdminView",
"packages/fields/types/admin-view"
]
},
"jest": {
Expand All @@ -236,6 +239,7 @@
"gatsby": "^2.0.111",
"gatsby-source-filesystem": "^2.0.20",
"gatsby-transformer-remark": "^2.2.3",
"globby": "^9.0.0",
"jade": "^1.11.0",
"junit-merge": "^2.0.0",
"lodash.omitby": "^4.6.0",
Expand Down
65 changes: 54 additions & 11 deletions packages/admin-ui/client/classes/List.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import gql from 'graphql-tag';

import FieldTypes from '../FIELD_TYPES';
import { viewMeta, loadView } from '../FIELD_TYPES';
import { arrayToObject } from '@voussoir/utils';

export const gqlCountQueries = lists => gql`{
Expand All @@ -10,14 +10,11 @@ export const gqlCountQueries = lists => gql`{
export default class List {
constructor(config, adminMeta) {
this.config = config;
this.adminMeta = adminMeta;

// TODO: undo this
Object.assign(this, config);

this.fields = config.fields.map(fieldConfig => {
const { Controller } = FieldTypes[config.key][fieldConfig.path];
return new Controller(fieldConfig, this, adminMeta);
});
delete this.fields;

this.createMutation = gql`
mutation create($data: ${this.gqlNames.createInputName}!) {
Expand Down Expand Up @@ -68,11 +65,52 @@ export default class List {
`;
}

/**
* @return Promise<undefined> resolves when all the field modules are loaded
*/
initFields() {
// Ensure we only trigger loading once, and any new requests to load are
// resolved when the first request is resolved (or rejected);
if (!this._loadingPromise) {
// NOTE: We purposely don't `await` here as we want the `_loadingPromise` to
// be resolved _after_ the `.then()` because it contains the
// `this._fields` assignment.
this._loadingPromise = Promise.all(
this.config.fields.map(fieldConfig => loadView(viewMeta[this.config.key][fieldConfig.path]))
).then(fieldModules => {
this._fields = fieldModules.map(({ Controller, ...views }, index) => {
const controller = new Controller(this.config.fields[index], this, this.adminMeta);
// Mix the `.views` fields into the controller for use throughout the
// UI
controller.views = views;
return controller;
});

// Flag as loaded
this._fieldsLoaded = true;
});
}

return this._loadingPromise;
}

getFields() {
if (!this.loaded()) {
throw new Error(
`Attempted to read fields from list ${this.config.key} before they were laoded`
);
}
return this._fields;
}

loaded() {
return !!this._fieldsLoaded;
}

buildQuery(queryName, queryArgs = '', fields = []) {
return `
${queryName}${queryArgs} {
id
_label_
${fields.map(field => field.getQueryFragment()).join(' ')}
}`;
}
Expand All @@ -93,16 +131,19 @@ export default class List {

getItemQuery(itemId) {
return gql`{
${this.buildQuery(this.gqlNames.itemQueryName, `(where: { id: "${itemId}" })`, this.fields)}
${this.buildQuery(
this.gqlNames.itemQueryName,
`(where: { id: "${itemId}" })`,
this.getFields()
)}
}`;
}

getQuery({ fields, filters, search, orderBy, skip, first }) {
const queryArgs = List.getQueryArgs({ first, filters, search, skip, orderBy });
const metaQueryArgs = List.getQueryArgs({ filters, search });
const safeFields = fields.filter(field => field.path !== '_label_');
return gql`{
${this.buildQuery(this.gqlNames.listQueryName, queryArgs, safeFields)}
${this.buildQuery(this.gqlNames.listQueryName, queryArgs, fields)}
${this.countQuery(metaQueryArgs)}
}`;
}
Expand All @@ -119,7 +160,9 @@ export default class List {
}

getInitialItemData() {
return arrayToObject(this.fields, 'path', field => field.getInitialData());
return arrayToObject(this.getFields().filter(field => field.isEditable()), 'path', field =>
field.getInitialData()
);
}
formatCount(items) {
const count = Array.isArray(items) ? items.length : items;
Expand Down
144 changes: 91 additions & 53 deletions packages/admin-ui/client/components/CreateItemModal.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** @jsx jsx */
import { jsx } from '@emotion/core';
import { Component, Fragment, useCallback, useMemo } from 'react';
import { Component, Fragment, useCallback, useMemo, useEffect, useState } from 'react';
import { Mutation } from 'react-apollo';

import { Button } from '@arch-ui/button';
Expand All @@ -9,17 +9,81 @@ import { resolveAllKeys, arrayToObject } from '@voussoir/utils';
import { gridSize } from '@arch-ui/theme';
import { AutocompleteCaptor } from '@arch-ui/input';

import FieldTypes from '../FIELD_TYPES';
import PageWithListFields from '../pages/PageWithListFields';
import PageLoading from './PageLoading';

let Render = ({ children }) => children();

class CreateItemModal extends Component {
constructor(props) {
super(props);
const { list } = props;
const item = list.getInitialItemData();
this.state = { item };
const CreateItemBody = ({ list, onChange, item }) => {
const [defaultsLoaded, setDefaultsLoaded] = useState(false);
useEffect(
() => {
if (!defaultsLoaded) {
const initialData = list.getInitialItemData();
setDefaultsLoaded(true);
onChange(initialData);
}
},
[list, defaultsLoaded, setDefaultsLoaded]
);

if (!defaultsLoaded) {
// Don't render anything on the first pass, we'll have actual data next time
// through once the useEffect() hook has run
return <PageLoading />;
}

return (
<Fragment>
<AutocompleteCaptor />
{list
.getFields()
.filter(field => field.isEditable())
.map((field, i) => {
const { Field } = field.views;
if (!Field) {
return null;
}
// TODO: Replace this with an access on the `list._fields[]` object?
// It should have all the views, etc, loaded by now
return (
<Render key={field.path}>
{() => {
// eslint-disable-next-line react-hooks/rules-of-hooks
let onFieldChange = useCallback(
value => {
onChange({
...item,
[field.path]: value,
});
},
[onChange, item]
);
// eslint-disable-next-line react-hooks/rules-of-hooks
return useMemo(
() => (
<Field
autoFocus={!i}
value={item[field.path]}
field={field}
/* TODO: Permission query results */
// error={}
onChange={onFieldChange}
renderContext="dialog"
/>
),
[i, item[field.path], field, item, onFieldChange]
);
}}
</Render>
);
})}
</Fragment>
);
};

class CreateItemModal extends Component {
state = { item: {} };
onCreate = event => {
// prevent form submission
event.preventDefault();
Expand All @@ -32,24 +96,24 @@ class CreateItemModal extends Component {
// propagate through portals as if they aren't there
event.stopPropagation();

const {
list: { fields },
createItem,
isLoading,
} = this.props;
if (isLoading) return;
const { list, createItem, isSaving } = this.props;
if (isSaving) return;
const { item } = this.state;

resolveAllKeys(arrayToObject(fields, 'path', field => field.getValue(item)))
resolveAllKeys(
arrayToObject(list.getFields().filter(field => field.isEditable()), 'path', field =>
field.getValue(item)
)
)
.then(data => createItem({ variables: { data } }))
.then(data => {
this.props.onCreate(data);
this.setState({ item: this.props.list.getInitialItemData() });
});
};
onClose = () => {
const { isLoading } = this.props;
if (isLoading) return;
const { isSaving } = this.props;
if (isSaving) return;
this.props.onClose();
};
onKeyDown = event => {
Expand All @@ -61,8 +125,7 @@ class CreateItemModal extends Component {
};
formComponent = props => <form autoComplete="off" onSubmit={this.onCreate} {...props} />;
render() {
const { isLoading, isOpen, list } = this.props;
const { item } = this.state;
const { isSaving, isOpen, list } = this.props;
return (
<Drawer
closeOnBlanketClick
Expand All @@ -75,7 +138,7 @@ class CreateItemModal extends Component {
footer={
<Fragment>
<Button appearance="create" type="submit">
{isLoading ? 'Loading...' : 'Create'}
{isSaving ? 'Loading...' : 'Create'}
</Button>
<Button appearance="warning" variant="subtle" onClick={this.onClose}>
Cancel
Expand All @@ -89,38 +152,13 @@ class CreateItemModal extends Component {
marginTop: gridSize,
}}
>
<AutocompleteCaptor />
{list.fields.map((field, i) => {
const { Field } = FieldTypes[list.key][field.path];
return (
<Render key={field.path}>
{() => {
let onChange = useCallback(value => {
this.setState(({ item }) => ({
item: {
...item,
[field.path]: value,
},
}));
}, []);
return useMemo(
() => (
<Field
autoFocus={!i}
value={item[field.path]}
field={field}
/* TODO: Permission query results */
// error={}
onChange={onChange}
renderContext="dialog"
/>
),
[i, item[field.path], field, onChange]
);
}}
</Render>
);
})}
<PageWithListFields list={this.props.list}>
<CreateItemBody
list={this.props.list}
item={this.state.item}
onChange={item => console.log(item) || this.setState({ item })}
/>
</PageWithListFields>
</div>
</Drawer>
);
Expand All @@ -133,7 +171,7 @@ export default class CreateItemModalWithMutation extends Component {
return (
<Mutation mutation={list.createMutation}>
{(createItem, { loading }) => (
<CreateItemModal createItem={createItem} isLoading={loading} {...this.props} />
<CreateItemModal createItem={createItem} isSaving={loading} {...this.props} />
)}
</Mutation>
);
Expand Down
Loading