Skip to content

Commit

Permalink
Merge branch 'master' into seed-data-readme
Browse files Browse the repository at this point in the history
  • Loading branch information
raveling authored Aug 27, 2021
2 parents 1e26bd1 + 9c5991f commit 85b398f
Show file tree
Hide file tree
Showing 29 changed files with 446 additions and 286 deletions.
5 changes: 5 additions & 0 deletions .changeset/dry-dolls-jog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@keystone-next/keystone': patch
---

Made cosmetic changes to the Admin UI code. No functional changes.
6 changes: 6 additions & 0 deletions .changeset/tiny-guests-sin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@keystone-next/example-blog': patch
'@keystone-next/example-task-manager': patch
---

Adds ability to seed data for `blog` and `task-manager` examples. Use `yarn seed-data` in either examples folder to create a set of example data.
53 changes: 46 additions & 7 deletions docs/components/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
/** @jsx jsx */
import { createContext, useContext, useEffect, useState, useRef, ReactNode } from 'react';
import {
createContext,
useContext,
useCallback,
useEffect,
useState,
useRef,
ReactNode,
} from 'react';
import { useRouter } from 'next/router';
import { jsx } from '@emotion/react';
import Link from 'next/link';
import debounce from 'lodash.debounce';

import { useCallback } from 'react';
import { BREAK_POINTS } from '../lib/media';
import { useMediaQuery } from '../lib/media';

import { SearchField } from './primitives/SearchField';
import { Highlight } from './primitives/Highlight';
import { Wrapper } from './primitives/Wrapper';
Expand All @@ -20,8 +28,11 @@ import { GitHub } from './icons/GitHub';
// TODO: Add in search for mobile via this button
// import { Search } from './icons/Search';

type HeaderContextType = { mobileNavIsOpen: boolean };
const HeaderContext = createContext<HeaderContextType>({ mobileNavIsOpen: false });
type HeaderContextType = { mobileNavIsOpen: boolean; desktopOpenState: number };
const HeaderContext = createContext<HeaderContextType>({
mobileNavIsOpen: false,
desktopOpenState: -1,
});
export const useHeaderContext = () => useContext(HeaderContext);

function Logo() {
Expand Down Expand Up @@ -94,6 +105,7 @@ function LinkItem({ children, href }: { children: ReactNode; href: string }) {
<span css={mq({ display: ['none', 'inline'], fontWeight: 600 })}>
<NavItem
isActive={isActive}
alwaysVisible
href={href}
css={{
padding: '0 !important',
Expand All @@ -108,10 +120,37 @@ function LinkItem({ children, href }: { children: ReactNode; href: string }) {
export function Header() {
const mq = useMediaQuery();
const router = useRouter();
const [mobileNavIsOpen, setMobileNavIsOpen] = useState(false);

const menuRef = useRef<HTMLDivElement>(null);
const headerRef = useRef<HTMLElement>(null);

const [mobileNavIsOpen, setMobileNavIsOpen] = useState(false);
const [desktopOpenState, setDesktopOpenState] = useState(-1);

useEffect(() => {
const listener = () => {
setMobileNavIsOpen(false);
setDesktopOpenState(-1);
const width = Math.max(
document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth
);
if (width > BREAK_POINTS.sm) {
setDesktopOpenState(-1);
} else {
setDesktopOpenState(-1);
}
};
window.addEventListener('resize', debounce(listener, 130));

return () => {
window.removeEventListener('resize', debounce(listener, 130));
};
}, [setDesktopOpenState]);

useEffect(() => {
document.body.style.overflow = 'auto';
// search - init field
Expand Down Expand Up @@ -270,7 +309,7 @@ export function Header() {
>
<GitHub css={{ height: '1.5em' }} />
</a>
<HeaderContext.Provider value={{ mobileNavIsOpen }}>
<HeaderContext.Provider value={{ mobileNavIsOpen, desktopOpenState }}>
<div
ref={menuRef}
css={mq({
Expand Down
23 changes: 16 additions & 7 deletions docs/components/docs/Navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,27 @@ type NavItemProps = {
href: string;
isActive?: boolean;
isPlaceholder?: boolean;
alwaysVisible?: boolean;
} & AnchorHTMLAttributes<HTMLAnchorElement>;

export function NavItem({ href, isActive: _isActive, isPlaceholder, ...props }: NavItemProps) {
export function NavItem({
href,
isActive: _isActive,
isPlaceholder,
alwaysVisible,
...props
}: NavItemProps) {
const { pathname } = useRouter();
const mq = useMediaQuery();
let isActive = _isActive || pathname === href;
const isActive = _isActive || pathname === href;
const ctx = useHeaderContext();
const isOpen = ctx ? ctx.mobileNavIsOpen : true;
const isMobileNavOpen = ctx ? ctx.mobileNavIsOpen : true;
const desktopOpenState = ctx ? ctx.desktopOpenState : -1;

return (
<Link href={href} passHref>
<a
tabIndex={isOpen ? 0 : -1}
{...(alwaysVisible ? {} : { tabIndex: isMobileNavOpen ? 0 : desktopOpenState })}
css={mq({
display: 'block',
textDecoration: 'none',
Expand Down Expand Up @@ -84,14 +92,15 @@ type PrimaryNavItemProps = {

export function PrimaryNavItem({ href, children }: PrimaryNavItemProps) {
const { pathname } = useRouter();
let isActive = pathname === href;
const isActive = pathname === href;
const ctx = useHeaderContext();
const isOpen = ctx ? ctx.mobileNavIsOpen : true;
const isMobileNavOpen = ctx ? ctx.mobileNavIsOpen : true;
const desktopOpenState = ctx ? ctx.desktopOpenState : -1;

return (
<Link href={href} passHref>
<a
tabIndex={isOpen ? 0 : -1}
tabIndex={isMobileNavOpen ? 0 : desktopOpenState}
css={{
display: 'block',
fontSize: '1rem',
Expand Down
2 changes: 2 additions & 0 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"cypress": "^5.6.0",
"date-fns": "^2.23.0",
"facepaint": "^1.2.1",
"lodash.debounce": "^4.0.8",
"next": "npm:next@^11.1.0",
"next-compose-plugins": "^2.2.1",
"prism-react-renderer": "^1.2.1",
Expand All @@ -45,6 +46,7 @@
"remark-hint": "^1.0.10"
},
"devDependencies": {
"@types/lodash.debounce": "^4.0.6",
"next-sitemap": "^1.6.164",
"start-server-and-test": "^1.13.1",
"typescript": "^4.3.5"
Expand Down
6 changes: 4 additions & 2 deletions docs/pages/404.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@ function ConstructionIllustration() {
);
}

// Modifying this code may have security implications
// See.. https://github.com/keystonejs/keystone/pull/6411#issuecomment-906085389
const v5PathList = ['/tutorials', '/guides', '/keystonejs', '/api', '/discussions'];

export default function NotFoundPage() {
const { asPath } = useRouter();
const tryV5Link = v5PathList.some(i => asPath.startsWith(i));
const tryV5Link = asPath.startsWith('/') && v5PathList.some(i => asPath.startsWith(i));
return (
<Page title={'Page Not Found (404)'} description={'Page Not Found (404)'}>
<div
Expand All @@ -53,7 +55,7 @@ export default function NotFoundPage() {
{tryV5Link ? (
<Type as="p" look="body18bold" margin="2rem 0 0">
If you were looking for a page in the Keystone 5 docs, try{' '}
<a href="https://v5.keystonejs.com">v5.keystonejs.com{asPath}</a>.
<a href={'https://v5.keystonejs.com' + asPath}>https://v5.keystonejs.com{asPath}</a>.
</Type>
) : null}
<ConstructionIllustration />
Expand Down
6 changes: 6 additions & 0 deletions examples/blog/keystone.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { config } from '@keystone-next/keystone';
import { lists } from './schema';
import { insertSeedData } from './seed-data';

export default config({
db: {
provider: 'sqlite',
url: process.env.DATABASE_URL || 'file:./keystone-example.db',
async onConnect(context) {
if (process.argv.includes('--seed-data')) {
await insertSeedData(context);
}
},
},
lists,
});
3 changes: 2 additions & 1 deletion examples/blog/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"scripts": {
"dev": "keystone-next dev",
"start": "keystone-next start",
"build": "keystone-next build"
"build": "keystone-next build",
"seed-data": "keystone-next --seed-data"
},
"dependencies": {
"@keystone-next/keystone": "^24.0.0"
Expand Down
77 changes: 77 additions & 0 deletions examples/blog/seed-data/data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
export const authors = [
{ name: 'Arthur Conan Doyle', email: '[email protected]' },
{ name: 'Emily Brontë', email: '[email protected]' },
{ name: 'Jane Austen', email: '[email protected]' },
{ name: 'Daren Shipley', email: '[email protected]' },
{ name: 'Lewis Carroll', email: '[email protected]' },
{ name: 'Lewis Carroll', email: '[email protected]' },
{ name: 'George Eliot', email: '[email protected]' },
{ name: 'L. Frank Baum', email: '[email protected]' },
];

export const posts = [
{
title: 'The Adventures of Sherlock Holmes',
status: 'draft',
publishDate: '2021-08-19T02:30:00.000Z',
author: 'Arthur Conan Doyle',
content:
'One night—it was on the twentieth of March, 1888—I was returning from a journey to a patient (for I had now returned to civil practice), when my way led me through Baker Street. As I passed the well-remembered door, which must always be associated in my mind with my wooing, and with the dark incidents of the Study in Scarlet, I was seized with a keen desire to see Holmes again, and to know how he was employing his extraordinary powers. His rooms were brilliantly lit, and, even as I looked up, I saw his tall, spare figure pass twice in a dark silhouette against the blind. He was pacing the room swiftly, eagerly, with his head sunk upon his chest and his hands clasped behind him. To me, who knew his every mood and habit, his attitude and manner told their own story. He was at work again. He had risen out of his drug-created dreams and was hot upon the scent of some new problem. I rang the bell and was shown up to the chamber which had formerly been in part my own. ',
},
{
title: 'Wuthering Heights',
status: 'published',
publishDate: '2021-04-22T05:43:51.000Z',
author: 'Emily Brontë',
content:
'I have just returned from a visit to my landlord—the solitary neighbour that I shall be troubled with. This is certainly a beautiful country! In all England, I do not believe that I could have fixed on a situation so completely removed from the stir of society. A perfect misanthropist’s Heaven—and Mr. Heathcliff and I are such a suitable pair to divide the desolation between us. A capital fellow! He little imagined how my heart warmed towards him when I beheld his black eyes withdraw so suspiciously under their brows, as I rode up, and when his fingers sheltered themselves, with a jealous resolution, still further in his waistcoat, as I announced my name.',
},
{
title: 'Emma',
status: 'draft',
publishDate: '2021-02-02T20:02:37.000Z',
author: 'Jane Austen',
content:
'Emma Woodhouse, handsome, clever, and rich, with a comfortable home and happy disposition, seemed to unite some of the best blessings of existence; and had lived nearly twenty-one years in the world with very little to distress or vex her. She was the youngest of the two daughters of a most affectionate, indulgent father; and had, in consequence of her sister’s marriage, been mistress of his house from a very early period. Her mother had died too long ago for her to have more than an indistinct remembrance of her caresses; and her place had been supplied by an excellent woman as governess, who had fallen little short of a mother in affection.',
},
{
title: 'Sense and Sensibility',
status: 'published',
publishDate: '2021-05-07T22:17:07.000Z',
author: 'Jane Austen',
content:
'The family of Dashwood had long been settled in Sussex. Their estate was large, and their residence was at Norland Park, in the centre of their property, where, for many generations, they had lived in so respectable a manner as to engage the general good opinion of their surrounding acquaintance. The late owner of this estate was a single man, who lived to a very advanced age, and who for many years of his life, had a constant companion and housekeeper in his sister. But her death, which happened ten years before his own, produced a great alteration in his home; for to supply her loss, he invited and received into his house the family of his nephew Mr. Henry Dashwood, the legal inheritor of the Norland estate, and the person to whom he intended to bequeath it. In the society of his nephew and niece, and their children, the old Gentleman’s days were comfortably spent. His attachment to them all increased. The constant attention of Mr. and Mrs. Henry Dashwood to his wishes, which proceeded not merely from interest, but from goodness of heart, gave him every degree of solid comfort which his age could receive; and the cheerfulness of the children added a relish to his existence.',
},
{
title: 'Through the Looking-Glass',
status: 'draft',
publishDate: '2021-03-09T05:41:37.000Z',
author: 'Lewis Carroll',
content:
'One thing was certain, that the white kitten had had nothing to do with it: it was the black kitten’s fault entirely. For the white kitten had been having its face washed by the old cat for the last quarter of an hour (and bearing it pretty well, considering); so you see that it couldn’t have had any hand in the mischief. ',
},
{
title: 'Jabberwocky',
status: 'published',
publishDate: '2021-07-27T00:12:02.000Z',
author: 'Lewis Carroll',
content:
'"’Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe. “Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch!”" ',
},
{
title: 'Middlemarch',
status: 'draft',
publishDate: '2021-08-07T05:50:57.000Z',
author: 'George Eliot',
content:
'Who that cares much to know the history of man, and how the mysterious mixture behaves under the varying experiments of Time, has not dwelt, at least briefly, on the life of Saint Theresa, has not smiled with some gentleness at the thought of the little girl walking forth one morning hand-in-hand with her still smaller brother, to go and seek martyrdom in the country of the Moors? Out they toddled from rugged Avila, wide-eyed and helpless-looking as two fawns, but with human hearts, already beating to a national idea; until domestic reality met them in the shape of uncles, and turned them back from their great resolve. That child-pilgrimage was a fit beginning. Theresa’s passionate, ideal nature demanded an epic life: what were many-volumed romances of chivalry and the social conquests of a brilliant girl to her? Her flame quickly burned up that light fuel; and, fed from within, soared after some illimitable satisfaction, some object which would never justify weariness, which would reconcile self-despair with the rapturous consciousness of life beyond self. She found her epos in the reform of a religious order. ',
},
{
title: 'The Wonderful Wizard of Oz',
status: 'published',
publishDate: '2021-03-01T06:41:57.000Z',
author: 'L. Frank Baum',
content:
'Dorothy lived in the midst of the great Kansas prairies, with Uncle Henry, who was a farmer, and Aunt Em, who was the farmer’s wife. Their house was small, for the lumber to build it had to be carried by wagon many miles. There were four walls, a floor and a roof, which made one room; and this room contained a rusty looking cookstove, a cupboard for the dishes, a table, three or four chairs, and the beds. Uncle Henry and Aunt Em had a big bed in one corner, and Dorothy a little bed in another corner. There was no garret at all, and no cellar—except a small hole dug in the ground, called a cyclone cellar, where the family could go in case one of those great whirlwinds arose, mighty enough to crush any building in its path. It was reached by a trap door in the middle of the floor, from which a ladder led down into the small, dark hole.',
},
];
67 changes: 67 additions & 0 deletions examples/blog/seed-data/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { KeystoneContext } from '@keystone-next/keystone/types';
import { authors, posts } from './data';

type AuthorProps = {
name: string;
email: string;
};

type PostProps = {
title: string;
status: string;
publishDate: string;
author: Object;
content: string;
};

export async function insertSeedData(context: KeystoneContext) {
console.log(`🌱 Inserting seed data`);

const createAuthor = async (authorData: AuthorProps) => {
let author = null;
try {
author = await context.lists.Author.findOne({
where: { email: authorData.email },
query: 'id',
});
} catch (e) {}
if (!author) {
author = await context.lists.Author.createOne({
data: authorData,
query: 'id',
});
}
return author;
};

const createPost = async (postData: PostProps) => {
let authors;
try {
authors = await context.lists.Author.findMany({
where: { name: { equals: postData.author } },
query: 'id',
});
} catch (e) {
authors = [];
}
postData.author = { connect: { id: authors[0].id } };
const post = await context.lists.Post.createOne({
data: postData,
query: 'id',
});
return post;
};

for (const author of authors) {
console.log(`👩 Adding author: ${author.name}`);
await createAuthor(author);
}
for (const post of posts) {
console.log(`📝 Adding post: ${post.title}`);
await createPost(post);
}

console.log(`✅ Seed data inserted`);
console.log(`👋 Please start the process with \`yarn dev\` or \`npm run dev\``);
process.exit();
}
6 changes: 6 additions & 0 deletions examples/task-manager/keystone.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { config } from '@keystone-next/keystone';
import { lists } from './schema';
import { insertSeedData } from './seed-data';

export default config({
db: {
provider: 'sqlite',
url: process.env.DATABASE_URL || 'file:./keystone-example.db',
async onConnect(context) {
if (process.argv.includes('--seed-data')) {
await insertSeedData(context);
}
},
},
lists,
});
3 changes: 2 additions & 1 deletion examples/task-manager/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"scripts": {
"dev": "keystone-next dev",
"start": "keystone-next start",
"build": "keystone-next build"
"build": "keystone-next build",
"seed-data": "keystone-next --seed-data"
},
"dependencies": {
"@keystone-next/keystone": "^24.0.0"
Expand Down
Loading

0 comments on commit 85b398f

Please sign in to comment.