Moved home page example code to /content/home

Now examples are trasnformed to GraphQL during build and assembled by the index template. This makes them easier to edit and tie in with their associated markdown description.
This commit is contained in:
Brian Vaughn
2017-11-06 13:01:13 +00:00
parent 65f1ced297
commit f5aaf4c1b4
13 changed files with 240 additions and 195 deletions

View File

@@ -0,0 +1,35 @@
class MarkdownEditor extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = { value: 'Type some *markdown* here!' };
}
handleChange(e) {
this.setState({ value: e.target.value });
}
getRawMarkup() {
const md = new Remarkable();
return { __html: md.render(this.state.value) };
}
render() {
return (
<div className="MarkdownEditor">
<h3>Input</h3>
<textarea
onChange={this.handleChange}
defaultValue={this.state.value}
/>
<h3>Output</h3>
<div
className="content"
dangerouslySetInnerHTML={this.getRawMarkup()}
/>
</div>
);
}
}
ReactDOM.render(<MarkdownEditor />, mountNode);

View File

@@ -1,7 +1,6 @@
---
title: A Component Using External Plugins
order: 3
example_name: markdownExample
---
React is flexible and provides hooks that allow you to interface with other libraries and frameworks. This example uses **remarkable**, an external Markdown library, to convert the `<textarea>`'s value in real time.

View File

@@ -0,0 +1,14 @@
class HelloMessage extends React.Component {
render() {
return (
<div>
Hello {this.props.name}
</div>
);
}
}
ReactDOM.render(
<HelloMessage name="Taylor" />,
mountNode
);

View File

@@ -1,9 +1,8 @@
---
title: A Simple Component
order: 0
example_name: helloExample
---
React components implement a `render()` method that takes input data and returns what to display. This example uses an XML-like syntax called JSX. Input data that is passed into the component can be accessed by `render()` via `this.props`.
**JSX is optional and not required to use React.** Try the [Babel REPL](http://babeljs.io/repl#?babili=false&browsers=&build=&builtIns=false&code_lz=MYGwhgzhAEASCmIQHsCy8pgOb2vAHgC7wB2AJjAErxjCEB0AwsgLYAOyJph0A3gFABIAE6ky8YQAoAlHyEj4hAK7CS0ADxkAlgDcAfAiTI-hABZaI9NsORtLJMC3gBfdQHpt-gNxDn_P_zUtIQAIgDyqPSi5BKS6oYo6Jg40A5OALwARCHwOlokmdBuegA00CzISiSEAHLI4tJeQA&debug=false&circleciRepo=&evaluate=false&lineWrap=false&presets=react&prettier=true&targets=&version=6.26.0) to see the raw JavaScript code produced by the JSX compilation step.
**JSX is optional and not required to use React.** Try the [Babel REPL](http://babeljs.io/repl#?babili=false&browsers=&build=&builtIns=false&code_lz=MYGwhgzhAEASCmIQHsCy8pgOb2vAHgC7wB2AJjAErxjCEB0AwsgLYAOyJph0A3gFDRoAJ1Jl4wgBQBKPoKEj4hAK7CS0SfIXQAPGQCWANwB8W7XEQo-hABb6I9NsORsHJMC3gBfM0J0B6AxMzaQBueR8ffmpaQgARAHlUelFyCU0_BCQ0DAhsXHdPAF4AIgAVMABPFGES6H9jABp5FmRlEkIAOWRxfjCgA&debug=false&circleciRepo=&evaluate=false&lineWrap=false&presets=react&targets=&version=6.26.0) to see the raw JavaScript code produced by the JSX compilation step.

View File

@@ -0,0 +1,30 @@
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
tick() {
this.setState(prevState => ({
seconds: prevState.seconds + 1
}));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
Seconds: {this.state.seconds}
</div>
);
}
}
ReactDOM.render(<Timer />, mountNode);

View File

@@ -1,7 +1,6 @@
---
title: A Stateful Component
order: 1
example_name: timerExample
---
In addition to taking input data (accessed via `this.props`), a component can maintain internal state data (accessed via `this.state`). When a component's state data changes, the rendered markup will be updated by re-invoking `render()`.

View File

@@ -0,0 +1,59 @@
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = { items: [], text: '' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<input
onChange={this.handleChange}
value={this.state.text}
/>
<button>
Add #{this.state.items.length + 1}
</button>
</form>
</div>
);
}
handleChange(e) {
this.setState({ text: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
if (!this.state.text.length) {
return;
}
const newItem = {
text: this.state.text,
id: Date.now()
};
this.setState(prevState => ({
items: prevState.items.concat(newItem),
text: ''
}));
}
}
class TodoList extends React.Component {
render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>{item.text}</li>
))}
</ul>
);
}
}
ReactDOM.render(<TodoApp />, mountNode);

View File

@@ -1,7 +1,6 @@
---
title: An Application
order: 2
example_name: todoExample
---
Using `props` and `state`, we can put together a small Todo application. This example uses `state` to track the current list of items as well as the text that the user has entered. Although event handlers appear to be rendered inline, they will be collected and implemented using event delegation.

View File

@@ -19,6 +19,7 @@ module.exports = {
plugins: [
'gatsby-source-react-error-codes',
'gatsby-transformer-authors-yaml',
'gatsby-transformer-home-example-code',
'gatsby-plugin-netlify',
'gatsby-plugin-glamor',
'gatsby-plugin-react-next',

View File

@@ -208,7 +208,7 @@ exports.onCreateNode = ({node, boundActionCreators, getNode}) => {
if (!slug) {
slug = `/${relativePath.replace('.md', '.html')}`;
// This should (probably) only happen for the index.md,
// This should only happen for the partials in /content/home,
// But let's log it in case it happens for other files also.
console.warn(
`Warning: No slug found for "${relativePath}". Falling back to default "${slug}".`,

View File

@@ -0,0 +1,28 @@
const {readdirSync, readFileSync} = require('fs');
const {join, resolve} = require('path');
// Store code snippets in GraphQL for the home page examples.
// Snippets will be matched with markdown templates of the same name.
exports.sourceNodes = ({graphql, boundActionCreators}) => {
const {createNode} = boundActionCreators;
const path = resolve(__dirname, '../../content/home/examples');
const files = readdirSync(path);
files.forEach(file => {
if (file.match(/\.js$/)) {
const code = readFileSync(join(path, file), 'utf8');
const id = file.replace(/\.js$/, '');
createNode({
id,
children: [],
parent: 'EXAMPLES',
internal: {
type: 'ExampleCode',
contentDigest: JSON.stringify(code),
},
});
}
});
};

View File

@@ -0,0 +1,4 @@
{
"name": "gatsby-transformer-home-example-code",
"version": "0.0.1"
}

View File

@@ -20,17 +20,46 @@ import {babelURL} from 'site-constants';
import ReactDOM from 'react-dom';
class Home extends Component {
constructor(props, context) {
super(props, context);
const {data} = props;
const code = data.code.edges.reduce((map, {node}) => {
map[node.id] = JSON.parse(node.internal.contentDigest);
return map;
}, {});
const examples = data.examples.edges.map(({node}) => ({
content: node.html,
id: node.fields.slug.replace(/^.+\//, '').replace('.html', ''),
title: node.frontmatter.title,
}));
const marketing = data.marketing.edges.map(({node}) => ({
title: node.frontmatter.title,
content: node.html,
}));
this.state = {
code,
examples,
marketing,
};
}
componentDidMount() {
renderExamplePlaceholder('helloExample');
renderExamplePlaceholder('timerExample');
renderExamplePlaceholder('todoExample');
renderExamplePlaceholder('markdownExample');
const {code, examples} = this.state;
examples.forEach(({id}) => {
renderExamplePlaceholder(id);
});
function mountCodeExamples() {
mountCodeExample('helloExample', HELLO_COMPONENT);
mountCodeExample('timerExample', TIMER_COMPONENT);
mountCodeExample('todoExample', TODO_COMPONENT);
mountCodeExample('markdownExample', MARKDOWN_COMPONENT);
examples.forEach(({id}) => {
mountCodeExample(id, code[id]);
});
}
loadScript(babelURL).then(mountCodeExamples, error => {
@@ -41,21 +70,14 @@ class Home extends Component {
}
render() {
const {data} = this.props;
const title = 'React - A JavaScript library for building user interfaces';
const marketingContent = data.marketing.edges.map(edge => ({
title: edge.node.frontmatter.title,
content: edge.node.html,
}));
const examplesContent = data.examples.edges.map(edge => ({
title: edge.node.frontmatter.title,
name: edge.node.frontmatter.example_name,
content: edge.node.html,
}));
const {examples, marketing} = this.state;
return (
<div css={{width: '100%'}}>
<TitleAndMetaTags title={title} ogUrl={createOgUrl('index.html')} />
<TitleAndMetaTags
title="React - A JavaScript library for building user interfaces"
ogUrl={createOgUrl('index.html')}
/>
<header
css={{
backgroundColor: colors.dark,
@@ -174,7 +196,7 @@ class Home extends Component {
whiteSpace: 'nowrap',
},
}}>
{marketingContent.map((column, index) => (
{marketing.map((column, index) => (
<div
key={index}
css={{
@@ -240,7 +262,7 @@ class Home extends Component {
/>
<section css={sectionStyles}>
<div id="examples">
{examplesContent.map((example, index) => (
{examples.map((example, index) => (
<div
key={index}
css={{
@@ -256,7 +278,7 @@ class Home extends Component {
}}>
<h3 css={headingStyles}>{example.title}</h3>
<div dangerouslySetInnerHTML={{__html: example.content}} />
<div id={example.name} />
<div id={example.id} />
</div>
))}
</div>
@@ -293,15 +315,13 @@ class Home extends Component {
Home.propTypes = {
data: PropTypes.shape({
marketing: PropTypes.object.isRequired,
code: PropTypes.object.isRequired,
examples: PropTypes.object.isRequired,
marketing: PropTypes.object.isRequired,
}).isRequired,
location: PropTypes.object.isRequired,
};
// TODO Improve this temporarily placeholder as part of
// converting the home page from markdown template to a Gatsby
// page (see issue #2)
function renderExamplePlaceholder(containerId) {
ReactDOM.render(
<h4>Loading code example...</h4>,
@@ -340,28 +360,40 @@ const CtaItem = ({children, primary = false}) => (
// eslint-disable-next-line no-undef
export const pageQuery = graphql`
query IndexMarkdown {
marketing: allMarkdownRemark(
filter: {id: {regex: "//home/marketing//"}}
sort: {fields: [frontmatter___order], order: ASC}
) {
code: allExampleCode {
edges {
node {
frontmatter {
title
id
internal {
contentDigest
}
html
}
}
}
examples: allMarkdownRemark(
filter: {id: {regex: "//home/examples//"}}
sort: {fields: [frontmatter___order], order: ASC}
) {
edges {
node {
fields {
slug
}
frontmatter {
title
}
html
}
}
}
marketing: allMarkdownRemark(
filter: {id: {regex: "//home/marketing//"}}
sort: {fields: [frontmatter___order], order: ASC}
) {
edges {
node {
frontmatter {
title
example_name
}
html
}
@@ -387,157 +419,3 @@ const headingStyles = {
marginBottom: 20,
},
};
// TODO Move these hard-coded examples into example files and out of the template?
// Alternately, move them into the markdown and transform them during build?
// This could be done via a new Gatsby transform plug-in that auto-converts to runnable REPLs?
const name = Math.random() > 0.5 ? 'John' : 'Jane';
const HELLO_COMPONENT = `
class HelloMessage extends React.Component {
render() {
return (
<div>
Hello {this.props.name}
</div>
);
}
}
ReactDOM.render(
<HelloMessage name="${name}" />,
mountNode
);
`.trim();
const TIMER_COMPONENT = `
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
tick() {
this.setState(prevState => ({
seconds: prevState.seconds + 1
}));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
Seconds: {this.state.seconds}
</div>
);
}
}
ReactDOM.render(<Timer />, mountNode);
`.trim();
var TODO_COMPONENT = `
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = { items: [], text: '' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<input
onChange={this.handleChange}
value={this.state.text}
/>
<button>
Add #{this.state.items.length + 1}
</button>
</form>
</div>
);
}
handleChange(e) {
this.setState({ text: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
if (!this.state.text.length) {
return;
}
const newItem = {
text: this.state.text,
id: Date.now()
};
this.setState(prevState => ({
items: prevState.items.concat(newItem),
text: ''
}));
}
}
class TodoList extends React.Component {
render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>{item.text}</li>
))}
</ul>
);
}
}
ReactDOM.render(<TodoApp />, mountNode);
`.trim();
var MARKDOWN_COMPONENT = `
class MarkdownEditor extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = { value: 'Type some *markdown* here!' };
}
handleChange(e) {
this.setState({ value: e.target.value });
}
getRawMarkup() {
const md = new Remarkable();
return { __html: md.render(this.state.value) };
}
render() {
return (
<div className="MarkdownEditor">
<h3>Input</h3>
<textarea
onChange={this.handleChange}
defaultValue={this.state.value}
/>
<h3>Output</h3>
<div
className="content"
dangerouslySetInnerHTML={this.getRawMarkup()}
/>
</div>
);
}
}
ReactDOM.render(<MarkdownEditor />, mountNode);
`.trim();