Skip to content

Commit

Permalink
Add blog section to website (#3306)
Browse files Browse the repository at this point in the history
  • Loading branch information
MadeByMike authored Sep 1, 2020
1 parent 285dd28 commit 234627a
Show file tree
Hide file tree
Showing 16 changed files with 1,045 additions and 155 deletions.
96 changes: 96 additions & 0 deletions docs/blog/field-types.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<!--[meta]
section: blog
title: Field types in Keystone
date: 2020-08-03
author: Mike Riethmuller
[meta]-->

# Field types

Field types in Keystone sit at the intersection of the Database, GraphQL API and User Interface. When you select and configure a field type, you are specifying how data is stored, how types in GraphQL are defined, and how the interface looks in the Admin app.

To give an example, the `Text` field creates a `TEXT` column in a Postgres database, and a `String` type in a MongoDb schema. It has a return type of `String` in the GraphQL API, and an input type (for mutations) also of `String`. The interface produces a styled `<input />` element or a `<textarea />` depending on if the `isMultiline` option is configured.

For a complete technical breakdown on the anatomy of field types and how they are built, see the [custom field type guide](/docs/guides/custom-field-types.md).

Because they sit at this intersection of concerns, it can be difficult to decide what customisations should become new field types. How many concerns need to differ before creating a new field vs adding config options or project specific customsation such as hooks?

This post provides insight into how we think about field types. Broadly speaking, field types can be grouped into one of two categories. Core field types and Non-Core field types.

## Core field types

Core field types are those included in the `@keystonejs/fields` package and fall under ths `@keystonejs/fields-*` namespace.

There's no definitive guide as to when a field should be a core field type, but generally speaking, the core fields consist of "primitive" values like:

- `Text`,
- `Number`,
- `DateTime` etc,

These usually map fairly well to primitive data types common to many programming languages and databases. However Keystone is a CMS and essential types for CMS applications extend beyond data types.

For these reasons we also consider more complex fields such as: `Select`, and `Relationship` as core field types.

## Non-core field types

If a core field represents a primitive value or common type of structured data use in applications, non-core types could be considered flavours on top of these.

A good example is the `Markdown` field. It stores values in the same way as the `Text` field. Technically speaking it's just an extension of the `Text` field that replaces the field view in the Admin UI.

Given this, it's reasonable to ask why have a new field type at all? Why not have an option on the `Text` field, similar to `isMultiline`? Both examples change the UI without changing anything about how the data is stored in the database or handled in GraphQL.

Although technically similar to the `Text` field, conceptually, `Markdown` represents a different content type. You would not arbitrarily display any text as `Markdown` in the same way you might with a multiline input.

This completes the basic criteria of how we decide on new field types over config options or project specific customsation:

1. Is data in the Database or GraphQL a different type?
1. Is it conceptually a different field type for users?
1. Is the UI incompatible with other values using the same type?

It's also important to note that`Markdown` includes `codemirror` - a sizeable third-party library used to provide a nice editor interface. We don't want to bundle `codemirror` with the core fields package, especially when a `Markdown` field is not an essential to a large majority of Keystone projects.

This forms the final part of the decision making to help determine when a field is a non-core field type. Non-core field types often:

1. share a primitive type, data structure, or use-case with a core field
1. are not required for many Keystone projects
1. connect with a third-party service or API
1. include a third-party library, that will impact the core fields bundle

It may be open to some interpretation, but the above guidelines help when deciding which fields belong with `@keystonejs/fields` package, and which don't.

## The future of field types

After reviewing existing fields and applying the above decision making process retrospectively, it highlights a few places we got this wrong in the past.

We've realised the following field types are non-core field types:

- `CloudinaryImage`
- `OEmbed`
- `UnSplash`
- `Location`

These will be moved out of the core fields package.

We've also realised that the `AuthedRelationship` is not conceptually different to the standard `Relationship` field. It doesn't store or handle data differently. It provides a shortcut for a common use-case of setting the value of the of a `Relationship` field to the currently authenticated user is a common use-case.

This functionality can be achieved with hooks and config on the existing `Relationship` field. We plan to document how to achieve common use-cases such as this before changing the `AuthedRelationship` field.

The `@keystonejs/fields-date-utc` package should be moved into the core fields package. It's a primitive data type used in a wide range of projects.

Both `Color` and `Url` are interesting. They currently both store values in the same way as the `Text` field and do nothing more than change the view.

The `Url` field only sets the HTML `type` attribute on the input element. You could add an option like is `isURL`, similar to the `isMultiline` and the same argument could be made for an option that allows setting the `type` attribute to "email".

An option should be added to the `Text` field that allows setting the HTML `type` attribute to either `url`, `email` or `text` (default).

However, much like `Markdown`, `URL` and `Email` are conceptually different fields for many users. It makes sense to expand the configuration options for `Text`, but there is also an argument for a unique field type that uses knowledge of the structure of URLs and emails to implement specific features. Examples might include server-side validation, domain based filtering, case-insensitive unique restrictions.

We won't deprecate or move the `URL` field for now but will look to improve it's implementation over time.

The `Location` and `Color` fields bundles a third-party libraries and are not a common requirement for many projects. Both should be moved out of the core packages.

Expect to see fields move between the core and non-core packages over the next few weeks. In the longer term hope to improve functionality of existing field in some of the ways mentioned here. We also hope this provides clarity around the choices we have made with field types.

If you want to continue the discussion head over to our [community Slack channel](https://community.keystonejs.com/) and ask us about field types. You can tweet at us [@KeystoneJS on Twitter](https://twitter.com/KeystoneJS).

Finally if you have a custom field type, please share it with us! We might include it in the Keystone or one of our contributors, Gautam Singh, maintains the `@keystonejs-contrib` namespace for any other community contributions.
4 changes: 0 additions & 4 deletions docs/guides/mutation-lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,6 @@ Each of these mutations is implemented within Keystone by a corresponding resolv
| `updateUsers` || `updateManyMutation` |
| `deleteUsers` || `deleteManyMutation` |

<!-- Dead links
Please refer to the [API documentation](LINK_TODO)) for full details on how to call these mutations either from [GraphQL](LINK_TODO)) or directly from [Keystone](LINK_TODO)).
-->

Keystone provides [access control](/docs/guides/access-control.md) mechanisms and a [hook system](/docs/guides/hooks.md) which allows the developer to customise the behaviour of each of these mutations.

This document details the lifecycle of each mutation, and how the different access control mechanisms and hooks interact.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ module.exports = async keystone => {
// Count existing users
const {
data: {
_allUsersMeta: { count },
_allUsersMeta: { count = 0 },
},
} = await keystone.executeGraphQL({
context: keystone.createContext({ skipAccessControl: true }),
Expand Down
91 changes: 77 additions & 14 deletions website/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const visit = require('unist-util-visit');
const rawMDX = require('@mdx-js/mdx');
const matter = require('gray-matter');
const mdastToString = require('mdast-util-to-string');
const createPaginatedPages = require('gatsby-paginate');

const generateUrl = require('./generateUrl');

Expand All @@ -19,6 +20,7 @@ const PROJECT_ROOT = path.resolve('..');
const GROUPS = [
'',
'quick-start',
'blog',
'tutorials',
'guides',
'discussions',
Expand All @@ -37,15 +39,10 @@ const SUB_GROUPS = [
'utilities',
];

exports.createPages = ({ actions, graphql }) => {
const { createPage } = actions;

const template = path.resolve(`src/templates/docs.js`);

// The 'fields' values are injected during the `onCreateNode` call below
return graphql(`
const createDocsPages = async ({ createPage, graphql }) =>
graphql(`
{
allMdx {
allMdx(filter: { fields: { navGroup: { ne: "blog" } } }) {
edges {
node {
id
Expand All @@ -71,10 +68,60 @@ exports.createPages = ({ actions, graphql }) => {
return Promise.reject(result.errors);
}

/*
If you end up with multiple ways to generate a markdown page, you will
need to split out to new templates, with their own graphql queries
*/
const pages = result.data.allMdx.edges.filter(page => {
const {
node: {
fields: { draft },
},
} = page;

return Boolean(!draft);
});

pages.forEach(({ node: { id, fields } }) => {
createPage({
path: `${fields.slug}`,
component: path.resolve(`src/templates/docs.js`),
context: {
mdPageId: id,
...fields,
}, // additional data can be passed via context
});
});
});

const createBlogPages = async ({ createPage, graphql }) =>
graphql(`
{
allMdx(filter: { fields: { navGroup: { eq: "blog" } } }) {
edges {
node {
id
fields {
slug
pageTitle
description
draft
heading
author
date
navGroup
navSubGroup
workspaceSlug
sortOrder
sortSubOrder
order
isPackageIndex
isIndex
}
}
}
}
}
`).then(result => {
if (result.errors) {
return Promise.reject(result.errors);
}

const pages = result.data.allMdx.edges.filter(page => {
const {
Expand All @@ -86,17 +133,31 @@ exports.createPages = ({ actions, graphql }) => {
return Boolean(!draft);
});

createPaginatedPages({
edges: pages,
createPage: createPage,
pageTemplate: 'src/templates/blogList.js',
pathPrefix: 'blog', // This is optional and defaults to an empty string if not used
});

pages.forEach(({ node: { id, fields } }) => {
createPage({
path: `${fields.slug}`,
component: template,
component: path.resolve(`src/templates/blogPost.js`),
context: {
mdPageId: id,
...fields,
}, // additional data can be passed via context
});
});
});

exports.createPages = ({ actions, graphql }) => {
const { createPage } = actions;
return Promise.all([
createDocsPages({ createPage, graphql }),
createBlogPages({ createPage, graphql }),
]);
};

const getEditUrl = absPath =>
Expand All @@ -114,7 +175,7 @@ exports.onCreateNode = async ({ node, actions, getNode }) => {
const isPackage = !GROUPS.includes(sourceInstanceName);
let { data, content } = matter(node.rawBody, { delimiters: ['<!--[meta]', '[meta]-->'] });

const navGroup = data.section;
const navGroup = data.section === 'api' ? 'API' : data.section;
const navSubGroup = data.subSection;
const order = data.order || 99999999999;
let pageTitle = data.title || '';
Expand Down Expand Up @@ -156,6 +217,8 @@ exports.onCreateNode = async ({ node, actions, getNode }) => {
isPackageIndex: isPackage && relativePath === 'README.md',
isIndex: !isPackage && relativePath === 'index.md',
pageTitle: pageTitle,
author: data.author,
date: new Date(data.date).toDateString(),
draft: Boolean(data.draft),
description,
heading,
Expand Down
1 change: 1 addition & 0 deletions website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@sindresorhus/slugify": "^0.11.0",
"facepaint": "^1.2.1",
"gatsby": "^2.13.25",
"gatsby-paginate": "^1.1.1",
"gatsby-plugin-google-analytics": "^2.1.4",
"gatsby-plugin-manifest": "^2.2.41",
"gatsby-plugin-mdx": "^1.0.64",
Expand Down
4 changes: 2 additions & 2 deletions website/src/components/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { media, mediaMax, mq } from '../utils/media';

export const HEADER_HEIGHT = 60;

export const Header = forwardRef(({ toggleMenu, ...props }, ref) => (
export const Header = forwardRef(({ toggleMenu, showSearch = true, ...props }, ref) => (
<header
ref={ref}
css={{
Expand Down Expand Up @@ -78,7 +78,7 @@ export const Header = forwardRef(({ toggleMenu, ...props }, ref) => (
},
}}
>
<Search />
{showSearch && <Search />}
</div>
<div
css={{
Expand Down
62 changes: 30 additions & 32 deletions website/src/components/Sidebar.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,33 @@ let scrollOffset = 0;

export const SIDEBAR_WIDTH = 280;

export const navStyles = ({ isVisible, mobileOnly }) => ({
boxSizing: 'border-box',
flexShrink: 0,
height: 'calc(100vh - 60px)',
overflowY: 'auto',
padding: `${gridSize * 4}px ${gridSize * 3}px`,
position: 'sticky',
top: 60,
WebkitOverflowScrolling: 'touch',
width: SIDEBAR_WIDTH,

[mediaMax.md]: {
background: 'white',
boxShadow: isVisible ? 'rgba(0, 0, 0, 0.25) 0px 0px 48px' : 'none',
height: '100vh',
opacity: isVisible ? 1 : 0,
position: 'fixed',
top: 0,
transform: isVisible ? 'translateX(0px)' : `translateX(-${SIDEBAR_WIDTH}px)`,
transition: 'all 150ms',
zIndex: 2,
},
[media.md]: {
display: mobileOnly ? 'none' : 'block',
},
});

export const Sidebar = ({ isVisible, toggleSidebar, mobileOnly }) => {
const asideRef = useRef();

Expand All @@ -36,36 +63,7 @@ export const Sidebar = ({ isVisible, toggleSidebar, mobileOnly }) => {
}, []);

return (
<aside
key="sidebar"
ref={asideRef}
css={{
boxSizing: 'border-box',
flexShrink: 0,
height: 'calc(100vh - 60px)',
overflowY: 'auto',
padding: `${gridSize * 4}px ${gridSize * 3}px`,
position: 'sticky',
top: 60,
WebkitOverflowScrolling: 'touch',
width: SIDEBAR_WIDTH,

[mediaMax.md]: {
background: 'white',
boxShadow: isVisible ? 'rgba(0, 0, 0, 0.25) 0px 0px 48px' : 'none',
height: '100vh',
opacity: isVisible ? 1 : 0,
position: 'fixed',
top: 0,
transform: isVisible ? 'translateX(0px)' : `translateX(-${SIDEBAR_WIDTH}px)`,
transition: 'all 150ms',
zIndex: 2,
},
[media.md]: {
display: mobileOnly ? 'none' : 'block',
},
}}
>
<aside key="sidebar" ref={asideRef} css={navStyles({ isVisible, mobileOnly })}>
<SocialIconsNav
css={{
marginBottom: '2.4em',
Expand Down Expand Up @@ -113,7 +111,7 @@ export const SidebarNav = () => {
);
};

const NavGroup = ({ index, navGroup, pathname }) => {
export const NavGroup = ({ index, navGroup, pathname }) => {
const sectionId = `docs-menu-${navGroup.navTitle}`;

const isPageInGroupActive = useMemo(() => {
Expand Down Expand Up @@ -257,7 +255,7 @@ export const Footer = () => (
marginBottom: '2rem',
}}
>
Made with ❤️ by{' '}
Made with ❤️&nbsp; by{' '}
<FooterAnchor href="https://www.thinkmill.com.au" target="_blank">
Thinkmill
</FooterAnchor>{' '}
Expand Down
Loading

0 comments on commit 234627a

Please sign in to comment.