Browse Source

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.
main
Brian Vaughn 7 years ago
parent
commit
f5aaf4c1b4
  1. 35
      content/home/examples/a-component-using-external-plugins.js
  2. 1
      content/home/examples/a-component-using-external-plugins.md
  3. 14
      content/home/examples/a-simple-component.js
  4. 3
      content/home/examples/a-simple-component.md
  5. 30
      content/home/examples/a-stateful-component.js
  6. 1
      content/home/examples/a-stateful-component.md
  7. 59
      content/home/examples/an-application.js
  8. 1
      content/home/examples/an-application.md
  9. 1
      gatsby-config.js
  10. 2
      gatsby-node.js
  11. 28
      plugins/gatsby-transformer-home-example-code/gatsby-node.js
  12. 4
      plugins/gatsby-transformer-home-example-code/package.json
  13. 250
      src/pages/index.js

35
content/home/examples/a-component-using-external-plugins.js

@ -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);

1
content/home/examples/a-component-using-external-plugins.md

@ -1,7 +1,6 @@
--- ---
title: A Component Using External Plugins title: A Component Using External Plugins
order: 3 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. 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.

14
content/home/examples/a-simple-component.js

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

3
content/home/examples/a-simple-component.md

@ -1,9 +1,8 @@
--- ---
title: A Simple Component title: A Simple Component
order: 0 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`. 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.

30
content/home/examples/a-stateful-component.js

@ -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);

1
content/home/examples/a-stateful-component.md

@ -1,7 +1,6 @@
--- ---
title: A Stateful Component title: A Stateful Component
order: 1 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()`. 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()`.

59
content/home/examples/an-application.js

@ -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);

1
content/home/examples/an-application.md

@ -1,7 +1,6 @@
--- ---
title: An Application title: An Application
order: 2 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. 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.

1
gatsby-config.js

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

2
gatsby-node.js

@ -208,7 +208,7 @@ exports.onCreateNode = ({node, boundActionCreators, getNode}) => {
if (!slug) { if (!slug) {
slug = `/${relativePath.replace('.md', '.html')}`; 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. // But let's log it in case it happens for other files also.
console.warn( console.warn(
`Warning: No slug found for "${relativePath}". Falling back to default "${slug}".`, `Warning: No slug found for "${relativePath}". Falling back to default "${slug}".`,

28
plugins/gatsby-transformer-home-example-code/gatsby-node.js

@ -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),
},
});
}
});
};

4
plugins/gatsby-transformer-home-example-code/package.json

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

250
src/pages/index.js

@ -20,17 +20,46 @@ import {babelURL} from 'site-constants';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
class Home extends Component { 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() { componentDidMount() {
renderExamplePlaceholder('helloExample'); const {code, examples} = this.state;
renderExamplePlaceholder('timerExample');
renderExamplePlaceholder('todoExample'); examples.forEach(({id}) => {
renderExamplePlaceholder('markdownExample'); renderExamplePlaceholder(id);
});
function mountCodeExamples() { function mountCodeExamples() {
mountCodeExample('helloExample', HELLO_COMPONENT); examples.forEach(({id}) => {
mountCodeExample('timerExample', TIMER_COMPONENT); mountCodeExample(id, code[id]);
mountCodeExample('todoExample', TODO_COMPONENT); });
mountCodeExample('markdownExample', MARKDOWN_COMPONENT);
} }
loadScript(babelURL).then(mountCodeExamples, error => { loadScript(babelURL).then(mountCodeExamples, error => {
@ -41,21 +70,14 @@ class Home extends Component {
} }
render() { render() {
const {data} = this.props; const {examples, marketing} = this.state;
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,
}));
return ( return (
<div css={{width: '100%'}}> <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 <header
css={{ css={{
backgroundColor: colors.dark, backgroundColor: colors.dark,
@ -174,7 +196,7 @@ class Home extends Component {
whiteSpace: 'nowrap', whiteSpace: 'nowrap',
}, },
}}> }}>
{marketingContent.map((column, index) => ( {marketing.map((column, index) => (
<div <div
key={index} key={index}
css={{ css={{
@ -240,7 +262,7 @@ class Home extends Component {
/> />
<section css={sectionStyles}> <section css={sectionStyles}>
<div id="examples"> <div id="examples">
{examplesContent.map((example, index) => ( {examples.map((example, index) => (
<div <div
key={index} key={index}
css={{ css={{
@ -256,7 +278,7 @@ class Home extends Component {
}}> }}>
<h3 css={headingStyles}>{example.title}</h3> <h3 css={headingStyles}>{example.title}</h3>
<div dangerouslySetInnerHTML={{__html: example.content}} /> <div dangerouslySetInnerHTML={{__html: example.content}} />
<div id={example.name} /> <div id={example.id} />
</div> </div>
))} ))}
</div> </div>
@ -293,15 +315,13 @@ class Home extends Component {
Home.propTypes = { Home.propTypes = {
data: PropTypes.shape({ data: PropTypes.shape({
marketing: PropTypes.object.isRequired, code: PropTypes.object.isRequired,
examples: PropTypes.object.isRequired, examples: PropTypes.object.isRequired,
marketing: PropTypes.object.isRequired,
}).isRequired, }).isRequired,
location: PropTypes.object.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) { function renderExamplePlaceholder(containerId) {
ReactDOM.render( ReactDOM.render(
<h4>Loading code example...</h4>, <h4>Loading code example...</h4>,
@ -340,12 +360,25 @@ const CtaItem = ({children, primary = false}) => (
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
export const pageQuery = graphql` export const pageQuery = graphql`
query IndexMarkdown { query IndexMarkdown {
marketing: allMarkdownRemark( code: allExampleCode {
filter: {id: {regex: "//home/marketing//"}} edges {
node {
id
internal {
contentDigest
}
}
}
}
examples: allMarkdownRemark(
filter: {id: {regex: "//home/examples//"}}
sort: {fields: [frontmatter___order], order: ASC} sort: {fields: [frontmatter___order], order: ASC}
) { ) {
edges { edges {
node { node {
fields {
slug
}
frontmatter { frontmatter {
title title
} }
@ -353,15 +386,14 @@ export const pageQuery = graphql`
} }
} }
} }
examples: allMarkdownRemark( marketing: allMarkdownRemark(
filter: {id: {regex: "//home/examples//"}} filter: {id: {regex: "//home/marketing//"}}
sort: {fields: [frontmatter___order], order: ASC} sort: {fields: [frontmatter___order], order: ASC}
) { ) {
edges { edges {
node { node {
frontmatter { frontmatter {
title title
example_name
} }
html html
} }
@ -387,157 +419,3 @@ const headingStyles = {
marginBottom: 20, 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();

Loading…
Cancel
Save