├── .editorconfig ├── .gitignore ├── .travis.yml ├── LICENSE.md ├── README.md ├── koa2-simplified-todo ├── .babelrc ├── .eslintrc.json ├── .gitignore ├── README.md ├── build │ └── babelRelayPlugin.js ├── data │ ├── database.js │ ├── schema.js │ └── schema.json ├── js │ ├── app.js │ ├── components │ │ ├── Todo.js │ │ ├── TodoApp.js │ │ ├── TodoList.js │ │ ├── TodoListFooter.js │ │ └── TodoTextInput.js │ ├── mutations │ │ ├── AddTodoMutation.js │ │ ├── ChangeTodoStatusMutation.js │ │ └── RemoveTodoMutation.js │ └── routes │ │ └── AppHomeRoute.js ├── package.json ├── public │ ├── base.css │ ├── index.css │ ├── index.html │ └── learn.json ├── scripts │ └── updateSchema.js └── server.js ├── koa2-todo ├── .babelrc ├── .eslintrc ├── .gitignore ├── README.md ├── build │ └── babelRelayPlugin.js ├── data │ ├── database.js │ ├── schema.js │ └── schema.json ├── js │ ├── app.js │ ├── components │ │ ├── Todo.js │ │ ├── TodoApp.js │ │ ├── TodoList.js │ │ ├── TodoListFooter.js │ │ └── TodoTextInput.js │ ├── mutations │ │ ├── AddTodoMutation.js │ │ ├── ChangeTodoStatusMutation.js │ │ ├── MarkAllTodosMutation.js │ │ ├── RemoveCompletedTodosMutation.js │ │ ├── RemoveTodoMutation.js │ │ └── RenameTodoMutation.js │ └── queries │ │ └── ViewerQueries.js ├── package.json ├── public │ ├── base.css │ ├── index.css │ ├── index.html │ └── learn.json ├── scripts │ └── updateSchema.js └── server.js ├── react-native-TodoMVC ├── .babelrc ├── .eslintrc ├── .flowconfig ├── .gitignore ├── .watchmanconfig ├── README.md ├── android │ ├── app │ │ ├── build.gradle │ │ ├── proguard-rules.pro │ │ ├── react.gradle │ │ └── src │ │ │ └── main │ │ │ ├── AndroidManifest.xml │ │ │ ├── java │ │ │ └── com │ │ │ │ └── todomvc │ │ │ │ └── MainActivity.java │ │ │ └── res │ │ │ ├── mipmap-hdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ └── ic_launcher.png │ │ │ └── values │ │ │ ├── strings.xml │ │ │ └── styles.xml │ ├── build.gradle │ ├── gradle.properties │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ └── settings.gradle ├── app.js ├── components │ ├── StatusButton.js │ ├── Todo.js │ ├── TodoApp.js │ ├── TodoList.js │ ├── TodoListFooter.js │ └── TodoTextInput.js ├── data │ ├── database.js │ ├── schema.graphql │ ├── schema.js │ └── schema.json ├── images │ ├── todo_checkbox-active.png │ ├── todo_checkbox-active@2x.png │ ├── todo_checkbox.png │ └── todo_checkbox@2x.png ├── index.android.js ├── index.ios.js ├── ios │ ├── TodoMVC.xcodeproj │ │ ├── project.pbxproj │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ └── TodoMVC.xcscheme │ ├── TodoMVC │ │ ├── AppDelegate.h │ │ ├── AppDelegate.m │ │ ├── Base.lproj │ │ │ └── LaunchScreen.xib │ │ ├── Images.xcassets │ │ │ └── AppIcon.appiconset │ │ │ │ └── Contents.json │ │ ├── Info.plist │ │ └── main.m │ └── TodoMVCTests │ │ ├── Info.plist │ │ └── TodoMVCTests.m ├── mutations │ ├── AddTodoMutation.js │ ├── ChangeTodoStatusMutation.js │ ├── MarkAllTodosMutation.js │ ├── RemoveCompletedTodosMutation.js │ ├── RemoveTodoMutation.js │ └── RenameTodoMutation.js ├── package.json ├── plugins │ └── babelRelayPlugin.js ├── routes │ └── TodoAppRoute.js ├── scripts │ └── updateSchema.js └── server.js ├── relay-treasurehunt ├── .babelrc ├── .eslintrc ├── .gitignore ├── README.md ├── build │ └── babelRelayPlugin.js ├── data │ ├── database.js │ ├── schema.js │ └── schema.json ├── js │ ├── app.js │ ├── components │ │ └── App.js │ ├── mutations │ │ └── CheckHidingSpotForTreasureMutation.js │ └── routes │ │ └── AppHomeRoute.js ├── package.json ├── public │ └── index.html ├── scripts │ └── updateSchema.js └── server.js ├── star-wars ├── .babelrc ├── .eslintrc ├── .gitignore ├── README.md ├── build │ └── babelRelayPlugin.js ├── data │ ├── database.js │ ├── schema.js │ └── schema.json ├── js │ ├── app.js │ ├── components │ │ ├── StarWarsApp.js │ │ └── StarWarsShip.js │ ├── mutation │ │ └── AddShipMutation.js │ └── routes │ │ └── StarWarsAppHomeRoute.js ├── package.json ├── public │ └── index.html ├── scripts │ └── updateSchema.js └── server.js └── todo ├── .babelrc ├── .eslintrc ├── .gitignore ├── README.md ├── build └── babelRelayPlugin.js ├── data ├── database.js ├── schema.js └── schema.json ├── js ├── app.js ├── components │ ├── Todo.js │ ├── TodoApp.js │ ├── TodoList.js │ ├── TodoListFooter.js │ └── TodoTextInput.js ├── mutations │ ├── AddTodoMutation.js │ ├── ChangeTodoStatusMutation.js │ ├── MarkAllTodosMutation.js │ ├── RemoveCompletedTodosMutation.js │ ├── RemoveTodoMutation.js │ └── RenameTodoMutation.js └── queries │ └── ViewerQueries.js ├── package.json ├── public ├── base.css ├── index.css ├── index.html └── learn.json ├── scripts └── updateSchema.js └── server.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.{json,js,html,css}] 11 | indent_style = space 12 | indent_size = 2 13 | 14 | [.eslintrc] 15 | indent_style = space 16 | indent_size = 2 17 | 18 | [*.md] 19 | trim_trailing_whitespace = false 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea 3 | .nvmrc 4 | /dist/ 5 | /lib/ 6 | node_modules 7 | npm-debug.log 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - '4' 4 | - '5' 5 | - '6' 6 | - '7' 7 | install: true 8 | env: 9 | - EXAMPLE_PATH=./relay-treasurehunt 10 | - EXAMPLE_PATH=./star-wars 11 | - EXAMPLE_PATH=./todo 12 | - EXAMPLE_PATH=./react-native-TodoMVC 13 | - EXAMPLE_PATH=./koa2-simplified-todo 14 | - EXAMPLE_PATH=./koa2-todo 15 | script: 16 | cd $EXAMPLE_PATH && npm install && npm run update-schema 17 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016-present, Facebook, Inc. All rights reserved. 2 | 3 | The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 4 | 5 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # koa-graphql-relay-example 2 | 3 | ## Examples 4 | 5 | - todo 6 | - relay-treasurehunt 7 | - star-wars 8 | - react-native-TodoMVC (React Native) 9 | - koa2-todo (koa v2) 10 | 11 | ## Setup 12 | 13 | ```sh 14 | npm i 15 | npm start 16 | ``` 17 | -------------------------------------------------------------------------------- /koa2-simplified-todo/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "./build/babelRelayPlugin" 4 | ], 5 | "presets": [ 6 | "react", 7 | "es2015", 8 | "stage-2" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /koa2-simplified-todo/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb", 3 | "parser": "babel-eslint", 4 | "env": { 5 | "browser": true, 6 | "node": true 7 | }, 8 | "rules": { 9 | "class-methods-use-this": "off", 10 | "no-use-before-define": "off", 11 | "react/jsx-filename-extension": ["error", { 12 | "extensions": [".js"] 13 | }], 14 | "react/prop-types": "off" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /koa2-simplified-todo/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | npm-debug.log 4 | data/schema.graphql 5 | -------------------------------------------------------------------------------- /koa2-simplified-todo/README.md: -------------------------------------------------------------------------------- 1 | # Relay TodoMVC 2 | 3 | ## Installation 4 | 5 | ``` 6 | npm install 7 | ``` 8 | 9 | ## Running 10 | 11 | Start a local server: 12 | 13 | ``` 14 | npm start 15 | ``` 16 | 17 | ## Developing 18 | 19 | Any changes you make to files in the `js/` directory will cause the server to 20 | automatically rebuild the app and refresh your browser. 21 | 22 | If at any time you make changes to `data/schema.js`, stop the server, 23 | regenerate `data/schema.json`, and restart the server: 24 | 25 | ``` 26 | npm run update-schema 27 | npm start 28 | ``` 29 | 30 | ## License 31 | 32 | This file provided by Facebook is for non-commercial testing and evaluation 33 | purposes only. Facebook reserves all rights not expressly granted. 34 | 35 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 36 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 37 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 38 | FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 39 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 40 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 41 | -------------------------------------------------------------------------------- /koa2-simplified-todo/build/babelRelayPlugin.js: -------------------------------------------------------------------------------- 1 | import getBabelRelayPlugin from 'babel-relay-plugin'; 2 | import schema from '../data/schema.json'; 3 | 4 | export default getBabelRelayPlugin(schema.data); 5 | -------------------------------------------------------------------------------- /koa2-simplified-todo/data/database.js: -------------------------------------------------------------------------------- 1 | export class Todo {} 2 | export class User {} 3 | 4 | // Mock authenticated ID 5 | const VIEWER_ID = 'me'; 6 | 7 | // Mock user data 8 | const viewer = new User(); 9 | 10 | viewer.id = VIEWER_ID; 11 | 12 | const usersById = { 13 | [VIEWER_ID]: viewer, 14 | }; 15 | 16 | // Mock todo data 17 | const todosById = {}; 18 | 19 | const todoIdsByUser = { 20 | [VIEWER_ID]: [], 21 | }; 22 | 23 | let nextTodoId = 0; 24 | 25 | addTodo('Taste JavaScript', true); 26 | addTodo('Buy a unicorn', false); 27 | 28 | export function addTodo(text, complete) { 29 | const todo = new Todo(); 30 | todo.complete = !!complete; 31 | todo.id = `${nextTodoId++}`; 32 | todo.text = text; 33 | todosById[todo.id] = todo; 34 | todoIdsByUser[VIEWER_ID].push(todo.id); 35 | return todo.id; 36 | } 37 | 38 | export function changeTodoStatus(id, complete) { 39 | const todo = getTodo(id); 40 | todo.complete = complete; 41 | } 42 | 43 | export function getTodo(id) { 44 | return todosById[id]; 45 | } 46 | 47 | export function getTodos(status = 'any') { 48 | const todos = todoIdsByUser[VIEWER_ID].map(id => todosById[id]); 49 | if (status === 'any') { 50 | return todos; 51 | } 52 | return todos.filter(todo => todo.complete === (status === 'completed')); 53 | } 54 | 55 | export function getUser(id) { 56 | return usersById[id]; 57 | } 58 | 59 | export function getViewer() { 60 | return getUser(VIEWER_ID); 61 | } 62 | 63 | export function removeTodo(id) { 64 | const todoIndex = todoIdsByUser[VIEWER_ID].indexOf(id); 65 | if (todoIndex !== -1) { 66 | todoIdsByUser[VIEWER_ID].splice(todoIndex, 1); 67 | } 68 | delete todosById[id]; 69 | } 70 | -------------------------------------------------------------------------------- /koa2-simplified-todo/js/app.js: -------------------------------------------------------------------------------- 1 | import 'babel-polyfill'; 2 | import 'todomvc-common'; 3 | 4 | import React from 'react'; 5 | import { render } from 'react-dom'; 6 | import { RootContainer } from 'react-relay'; 7 | import TodoApp from './components/TodoApp'; 8 | import AppHomeRoute from './routes/AppHomeRoute'; 9 | 10 | render( 11 | , 15 | document.getElementById('root'), 16 | ); 17 | -------------------------------------------------------------------------------- /koa2-simplified-todo/js/components/Todo.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import Relay from 'react-relay'; 3 | import classnames from 'classnames'; 4 | 5 | import ChangeTodoStatusMutation from '../mutations/ChangeTodoStatusMutation'; 6 | import RemoveTodoMutation from '../mutations/RemoveTodoMutation'; 7 | 8 | class Todo extends React.Component { 9 | handleCompleteChange = (e) => { 10 | const complete = e.target.checked; 11 | this.props.relay.commitUpdate( 12 | new ChangeTodoStatusMutation({ 13 | complete, 14 | todo: this.props.todo, 15 | viewer: this.props.viewer, 16 | }), 17 | ); 18 | }; 19 | 20 | handleDestroyClick = () => { 21 | this.removeTodo(); 22 | }; 23 | 24 | removeTodo() { 25 | this.props.relay.commitUpdate( 26 | new RemoveTodoMutation({ todo: this.props.todo, viewer: this.props.viewer }) 27 | ); 28 | } 29 | 30 | render() { 31 | return ( 32 |
  • 37 |
    38 | 44 | 45 |
    50 |
  • 51 | ); 52 | } 53 | } 54 | 55 | export default Relay.createContainer(Todo, { 56 | fragments: { 57 | todo: () => Relay.QL` 58 | fragment on Todo { 59 | complete, 60 | id, 61 | text, 62 | ${ChangeTodoStatusMutation.getFragment('todo')}, 63 | ${RemoveTodoMutation.getFragment('todo')}, 64 | } 65 | `, 66 | viewer: () => Relay.QL` 67 | fragment on User { 68 | ${ChangeTodoStatusMutation.getFragment('viewer')}, 69 | ${RemoveTodoMutation.getFragment('viewer')}, 70 | } 71 | `, 72 | }, 73 | }); 74 | -------------------------------------------------------------------------------- /koa2-simplified-todo/js/components/TodoApp.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import Relay from 'react-relay'; 3 | 4 | import AddTodoMutation from '../mutations/AddTodoMutation'; 5 | import TodoList from './TodoList'; 6 | import TodoListFooter from './TodoListFooter'; 7 | import TodoTextInput from './TodoTextInput'; 8 | 9 | class TodoApp extends React.Component { 10 | handleTextInputSave = (text) => { 11 | this.props.relay.commitUpdate( 12 | new AddTodoMutation({ text, viewer: this.props.viewer }) 13 | ); 14 | }; 15 | 16 | render() { 17 | const hasTodos = this.props.viewer.totalCount > 0; 18 | return ( 19 |
    20 |
    21 |
    22 |

    23 | todos 24 |

    25 | 31 |
    32 | 33 | 34 | 35 | {hasTodos && 36 | 40 | } 41 |
    42 |
    43 |

    44 | Part of TodoMVC 45 |

    46 |
    47 |
    48 | ); 49 | } 50 | } 51 | 52 | export default Relay.createContainer(TodoApp, { 53 | fragments: { 54 | viewer: () => Relay.QL` 55 | fragment on User { 56 | totalCount, 57 | ${TodoList.getFragment('viewer')}, 58 | ${TodoListFooter.getFragment('viewer')}, 59 | ${AddTodoMutation.getFragment('viewer')}, 60 | } 61 | `, 62 | }, 63 | }); 64 | -------------------------------------------------------------------------------- /koa2-simplified-todo/js/components/TodoList.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import Relay from 'react-relay'; 3 | 4 | import Todo from './Todo'; 5 | 6 | class TodoList extends React.Component { 7 | renderTodos() { 8 | return this.props.viewer.todos.edges.map(edge => 9 | , 14 | ); 15 | } 16 | 17 | render() { 18 | return ( 19 |
    20 |
      21 | {this.renderTodos()} 22 |
    23 |
    24 | ); 25 | } 26 | } 27 | 28 | export default Relay.createContainer(TodoList, { 29 | fragments: { 30 | viewer: () => Relay.QL` 31 | fragment on User { 32 | todos( 33 | first: 2147483647 # max GraphQLInt 34 | ) { 35 | edges { 36 | node { 37 | id, 38 | ${Todo.getFragment('todo')}, 39 | }, 40 | }, 41 | }, 42 | ${Todo.getFragment('viewer')}, 43 | } 44 | `, 45 | }, 46 | }); 47 | -------------------------------------------------------------------------------- /koa2-simplified-todo/js/components/TodoListFooter.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import Relay from 'react-relay'; 3 | 4 | class TodoListFooter extends Component { 5 | render() { 6 | const numCompletedTodos = this.props.viewer.completedCount; 7 | const numRemainingTodos = this.props.viewer.totalCount - numCompletedTodos; 8 | return ( 9 |
    10 | 11 | {numRemainingTodos} item{numRemainingTodos === 1 ? '' : 's'} left 12 | 13 |
    14 | ); 15 | } 16 | } 17 | 18 | export default Relay.createContainer(TodoListFooter, { 19 | fragments: { 20 | viewer: () => Relay.QL` 21 | fragment on User { 22 | completedCount, 23 | totalCount, 24 | } 25 | `, 26 | }, 27 | }); 28 | -------------------------------------------------------------------------------- /koa2-simplified-todo/js/components/TodoTextInput.js: -------------------------------------------------------------------------------- 1 | import React, { PropTypes } from 'react'; 2 | import { findDOMNode } from 'react-dom'; 3 | 4 | const ENTER_KEY_CODE = 13; 5 | 6 | export default class TodoTextInput extends React.Component { 7 | static propTypes = { 8 | className: PropTypes.string, 9 | onSave: PropTypes.func.isRequired, 10 | placeholder: PropTypes.string, 11 | }; 12 | 13 | state = { 14 | text: '', 15 | }; 16 | 17 | componentDidMount() { 18 | findDOMNode(this).focus(); // eslint-disable-line react/no-find-dom-node 19 | } 20 | 21 | commitChanges = () => { 22 | const newText = this.state.text.trim(); 23 | if (newText !== '') { 24 | this.props.onSave(newText); 25 | this.setState({ text: '' }); 26 | } 27 | }; 28 | 29 | handleChange = (e) => { 30 | this.setState({ text: e.target.value }); 31 | }; 32 | 33 | handleKeyDown = (e) => { 34 | if (e.keyCode === ENTER_KEY_CODE) { 35 | this.commitChanges(); 36 | } 37 | }; 38 | 39 | render() { 40 | return ( 41 | 48 | ); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /koa2-simplified-todo/js/mutations/AddTodoMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class AddTodoMutation extends Relay.Mutation { 4 | static fragments = { 5 | viewer: () => Relay.QL` 6 | fragment on User { 7 | id 8 | totalCount 9 | } 10 | `, 11 | }; 12 | 13 | getMutation() { 14 | return Relay.QL`mutation { addTodo }`; 15 | } 16 | 17 | getFatQuery() { 18 | return Relay.QL` 19 | fragment on AddTodoPayload @relay(pattern: true) { 20 | todoEdge 21 | viewer { 22 | todos 23 | totalCount 24 | } 25 | } 26 | `; 27 | } 28 | 29 | getConfigs() { 30 | return [{ 31 | type: 'RANGE_ADD', 32 | parentName: 'viewer', 33 | parentID: this.props.viewer.id, 34 | connectionName: 'todos', 35 | edgeName: 'todoEdge', 36 | rangeBehaviors: () => 'append', 37 | }]; 38 | } 39 | 40 | getVariables() { 41 | return { 42 | text: this.props.text, 43 | }; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /koa2-simplified-todo/js/mutations/ChangeTodoStatusMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class ChangeTodoStatusMutation extends Relay.Mutation { 4 | static fragments = { 5 | todo: () => Relay.QL` 6 | fragment on Todo { 7 | id 8 | } 9 | `, 10 | // TODO: Mark completedCount optional 11 | viewer: () => Relay.QL` 12 | fragment on User { 13 | id 14 | completedCount 15 | } 16 | `, 17 | }; 18 | 19 | getMutation() { 20 | return Relay.QL`mutation { changeTodoStatus }`; 21 | } 22 | 23 | getFatQuery() { 24 | return Relay.QL` 25 | fragment on ChangeTodoStatusPayload @relay(pattern: true) { 26 | todo { 27 | complete 28 | } 29 | viewer { 30 | completedCount 31 | todos 32 | } 33 | } 34 | `; 35 | } 36 | 37 | getConfigs() { 38 | return [{ 39 | type: 'FIELDS_CHANGE', 40 | fieldIDs: { 41 | todo: this.props.todo.id, 42 | viewer: this.props.viewer.id, 43 | }, 44 | }]; 45 | } 46 | 47 | getVariables() { 48 | return { 49 | complete: this.props.complete, 50 | id: this.props.todo.id, 51 | }; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /koa2-simplified-todo/js/mutations/RemoveTodoMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class RemoveTodoMutation extends Relay.Mutation { 4 | static fragments = { 5 | // TODO: Mark complete as optional 6 | todo: () => Relay.QL` 7 | fragment on Todo { 8 | complete 9 | id 10 | } 11 | `, 12 | // TODO: Mark completedCount and totalCount as optional 13 | viewer: () => Relay.QL` 14 | fragment on User { 15 | completedCount 16 | id 17 | totalCount 18 | } 19 | `, 20 | }; 21 | 22 | getMutation() { 23 | return Relay.QL`mutation { removeTodo }`; 24 | } 25 | 26 | getFatQuery() { 27 | return Relay.QL` 28 | fragment on RemoveTodoPayload @relay(pattern: true) { 29 | deletedTodoId 30 | viewer { 31 | completedCount 32 | totalCount 33 | } 34 | } 35 | `; 36 | } 37 | 38 | getConfigs() { 39 | return [{ 40 | type: 'NODE_DELETE', 41 | parentName: 'viewer', 42 | parentID: this.props.viewer.id, 43 | connectionName: 'todos', 44 | deletedIDFieldName: 'deletedTodoId', 45 | }]; 46 | } 47 | 48 | getVariables() { 49 | return { 50 | id: this.props.todo.id, 51 | }; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /koa2-simplified-todo/js/routes/AppHomeRoute.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class extends Relay.Route { 4 | static queries = { 5 | viewer: () => Relay.QL`query { viewer }`, 6 | }; 7 | 8 | static routeName = 'AppHomeRoute'; 9 | } 10 | -------------------------------------------------------------------------------- /koa2-simplified-todo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "start": "babel-node ./server.js", 5 | "update-schema": "babel-node ./scripts/updateSchema.js", 6 | "lint": "./node_modules/.bin/eslint ." 7 | }, 8 | "dependencies": { 9 | "babel-core": "^6.18.2", 10 | "babel-loader": "^6.2.8", 11 | "babel-polyfill": "^6.16.0", 12 | "babel-preset-es2015": "^6.18.0", 13 | "babel-preset-react": "^6.16.0", 14 | "babel-preset-stage-2": "^6.18.0", 15 | "babel-relay-plugin": "^0.9.3", 16 | "classnames": "^2.2.5", 17 | "express": "^4.14.0", 18 | "graphql": "^0.8.2", 19 | "graphql-relay": "^0.4.4", 20 | "koa": "^2.0.0", 21 | "koa-convert": "^1.2.0", 22 | "koa-graphql": "^0.6.0", 23 | "koa-mount": "^2.0.0", 24 | "react": "^15.4.0", 25 | "react-dom": "^15.4.0", 26 | "react-relay": "^0.9.3", 27 | "todomvc-app-css": "^2.0.6", 28 | "todomvc-common": "^1.0.3", 29 | "webpack": "^1.13.3", 30 | "webpack-dev-server": "^1.16.2" 31 | }, 32 | "devDependencies": { 33 | "babel-cli": "^6.18.0", 34 | "babel-eslint": "^7.1.1", 35 | "eslint": "^3.10.2", 36 | "eslint-config-airbnb": "^13.0.0", 37 | "eslint-plugin-import": "^2.2.0", 38 | "eslint-plugin-jsx-a11y": "^2.2.3", 39 | "eslint-plugin-react": "^6.7.1" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /koa2-simplified-todo/public/base.css: -------------------------------------------------------------------------------- 1 | ../node_modules/todomvc-common/base.css -------------------------------------------------------------------------------- /koa2-simplified-todo/public/index.css: -------------------------------------------------------------------------------- 1 | ../node_modules/todomvc-app-css/index.css -------------------------------------------------------------------------------- /koa2-simplified-todo/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Relay • TodoMVC 7 | 8 | 9 | 10 | 11 |
    12 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /koa2-simplified-todo/public/learn.json: -------------------------------------------------------------------------------- 1 | { 2 | "relay": { 3 | "name": "Koa GraphQL", 4 | "description": "Create a GraphQL HTTP server with Koa. ", 5 | "homepage": "https://github.com/chentsulin/koa-graphql", 6 | "examples": [{ 7 | "name": "koa-graphql + relay Example", 8 | "url": "", 9 | "source_url": "https://github.com/chentsulin/koa-graphql-relay-example", 10 | "type": "backend" 11 | }], 12 | "link_groups": [{ 13 | "heading": "Resources", 14 | "links": [{ 15 | "name": "Relay Documentation", 16 | "url": "https://facebook.github.io/relay/docs/getting-started.html" 17 | }, { 18 | "name": "Relay API Reference", 19 | "url": "https://facebook.github.io/relay/docs/api-reference-relay.html" 20 | }, { 21 | "name": "Koa GraphQL on GitHub", 22 | "url": "https://github.com/chentsulin/koa-graphql" 23 | }] 24 | }, { 25 | "heading": "Issue Tracker", 26 | "links": [{ 27 | "name": "Open a new issue on GitHub", 28 | "url": "https://github.com/chentsulin/koa-graphql-relay-example/issues/new" 29 | }] 30 | }] 31 | }, 32 | "templates": { 33 | "todomvc": "

    <%= name %>

    <% if (typeof examples !== 'undefined') { %> <% examples.forEach(function (example) { %>
    <%= example.name %>
    <% if (!location.href.match(example.url + '/')) { %> \" href=\"<%= example.url %>\">Demo, <% } if (example.type === 'backend') { %>\"><% } else { %>\"><% } %>Source <% }); %> <% } %>

    <%= description %>

    <% if (typeof link_groups !== 'undefined') { %>
    <% link_groups.forEach(function (link_group) { %>

    <%= link_group.heading %>

    <% }); %> <% } %>

    If you have other helpful links to share, or find any of the links above no longer work, please let us know.
    " 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /koa2-simplified-todo/scripts/updateSchema.js: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | import { graphql } from 'graphql'; 4 | import { introspectionQuery, printSchema } from 'graphql/utilities'; 5 | 6 | import schema from '../data/schema'; 7 | 8 | // Save JSON of full schema introspection for Babel Relay Plugin to use 9 | (async () => { 10 | const result = await (graphql(schema, introspectionQuery)); 11 | if (result.errors) { 12 | console.error( 13 | 'ERROR introspecting schema: ', 14 | JSON.stringify(result.errors, null, 2), 15 | ); 16 | } else { 17 | fs.writeFileSync( 18 | path.join(__dirname, '../data/schema.json'), 19 | JSON.stringify(result, null, 2), 20 | ); 21 | } 22 | })(); 23 | 24 | // Save user readable type system shorthand of schema 25 | fs.writeFileSync( 26 | path.join(__dirname, '../data/schema.graphql'), 27 | printSchema(schema) 28 | ); 29 | -------------------------------------------------------------------------------- /koa2-simplified-todo/server.js: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import Koa from 'koa'; 3 | import graphQLHTTP from 'koa-graphql'; 4 | import mount from 'koa-mount'; 5 | import convert from 'koa-convert'; 6 | import path from 'path'; 7 | import webpack from 'webpack'; 8 | import WebpackDevServer from 'webpack-dev-server'; 9 | import schema from './data/schema'; 10 | 11 | const APP_PORT = 3000; 12 | const GRAPHQL_PORT = 8080; 13 | 14 | // Expose a GraphQL endpoint 15 | const graphQLServer = new Koa(); 16 | 17 | graphQLServer.use(mount('/', convert(graphQLHTTP({ 18 | schema, 19 | pretty: true, 20 | graphiql: true, 21 | })))); 22 | 23 | graphQLServer.listen(GRAPHQL_PORT, () => console.log( 24 | `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}` 25 | )); 26 | 27 | // Serve the Relay app 28 | const compiler = webpack({ 29 | devtool: 'cheap-module-eval-source-map', 30 | entry: path.resolve(__dirname, 'js', 'app.js'), 31 | module: { 32 | loaders: [ 33 | { 34 | exclude: /node_modules/, 35 | loader: 'babel', 36 | test: /\.js$/, 37 | }, 38 | ], 39 | }, 40 | output: { filename: 'app.js', path: '/' }, 41 | }); 42 | 43 | const app = new WebpackDevServer(compiler, { 44 | contentBase: '/public/', 45 | proxy: { '/graphql': `http://localhost:${GRAPHQL_PORT}` }, 46 | publicPath: '/js/', 47 | stats: { colors: true }, 48 | }); 49 | 50 | // Serve static resources 51 | app.use('/', express.static(path.resolve(__dirname, 'public'))); 52 | 53 | app.listen(APP_PORT, () => { 54 | console.log(`App is now running on http://localhost:${APP_PORT}`); 55 | }); 56 | -------------------------------------------------------------------------------- /koa2-todo/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "passPerPreset": true, 3 | "presets": [ 4 | { 5 | "plugins": [ 6 | "./build/babelRelayPlugin" 7 | ] 8 | }, 9 | "react", 10 | "es2015", 11 | "stage-0" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /koa2-todo/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb", 3 | "parser": "babel-eslint", 4 | "env": { 5 | "browser": true, 6 | "node": true 7 | }, 8 | "rules": { 9 | "eqeqeq": 0, 10 | "no-console": 0, 11 | "no-use-before-define": 0, 12 | "react/prop-types": 0, 13 | "react/jsx-closing-bracket-location": 0 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /koa2-todo/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | npm-debug.log 4 | data/schema.graphql 5 | -------------------------------------------------------------------------------- /koa2-todo/README.md: -------------------------------------------------------------------------------- 1 | # Relay TodoMVC 2 | 3 | ## Installation 4 | 5 | ``` 6 | npm install 7 | ``` 8 | 9 | ## Running 10 | 11 | Start a local server: 12 | 13 | ``` 14 | npm start 15 | ``` 16 | 17 | ## Developing 18 | 19 | Any changes you make to files in the `js/` directory will cause the server to 20 | automatically rebuild the app and refresh your browser. 21 | 22 | If at any time you make changes to `data/schema.js`, stop the server, 23 | regenerate `data/schema.json`, and restart the server: 24 | 25 | ``` 26 | npm run update-schema 27 | npm start 28 | ``` 29 | 30 | ## License 31 | 32 | This file provided by Facebook is for non-commercial testing and evaluation 33 | purposes only. Facebook reserves all rights not expressly granted. 34 | 35 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 36 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 37 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 38 | FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 39 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 40 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 41 | -------------------------------------------------------------------------------- /koa2-todo/build/babelRelayPlugin.js: -------------------------------------------------------------------------------- 1 | import getBabelRelayPlugin from 'babel-relay-plugin'; 2 | import schema from '../data/schema.json'; 3 | 4 | export default getBabelRelayPlugin(schema.data); 5 | -------------------------------------------------------------------------------- /koa2-todo/data/database.js: -------------------------------------------------------------------------------- 1 | export class Todo {} 2 | export class User {} 3 | 4 | // Mock authenticated ID 5 | const VIEWER_ID = 'me'; 6 | 7 | // Mock user data 8 | const viewer = new User(); 9 | viewer.id = VIEWER_ID; 10 | const usersById = { 11 | [VIEWER_ID]: viewer, 12 | }; 13 | 14 | // Mock todo data 15 | const todosById = {}; 16 | const todoIdsByUser = { 17 | [VIEWER_ID]: [], 18 | }; 19 | let nextTodoId = 0; 20 | addTodo('Taste JavaScript', true); 21 | addTodo('Buy a unicorn', false); 22 | 23 | export function addTodo(text, complete) { 24 | const todo = new Todo(); 25 | todo.complete = !!complete; 26 | todo.id = `${nextTodoId++}`; 27 | todo.text = text; 28 | todosById[todo.id] = todo; 29 | todoIdsByUser[VIEWER_ID].push(todo.id); 30 | return todo.id; 31 | } 32 | 33 | export function changeTodoStatus(id, complete) { 34 | const todo = getTodo(id); 35 | todo.complete = complete; 36 | } 37 | 38 | export function getTodo(id) { 39 | return todosById[id]; 40 | } 41 | 42 | export function getTodos(status = 'any') { 43 | const todos = todoIdsByUser[VIEWER_ID].map(id => todosById[id]); 44 | if (status === 'any') { 45 | return todos; 46 | } 47 | return todos.filter(todo => todo.complete === (status === 'completed')); 48 | } 49 | 50 | export function getUser(id) { 51 | return usersById[id]; 52 | } 53 | 54 | export function getViewer() { 55 | return getUser(VIEWER_ID); 56 | } 57 | 58 | export function markAllTodos(complete) { 59 | const changedTodos = []; 60 | getTodos().forEach(todo => { 61 | if (todo.complete !== complete) { 62 | todo.complete = complete; // eslint-disable-line no-param-reassign 63 | changedTodos.push(todo); 64 | } 65 | }); 66 | return changedTodos.map(todo => todo.id); 67 | } 68 | 69 | export function removeTodo(id) { 70 | const todoIndex = todoIdsByUser[VIEWER_ID].indexOf(id); 71 | if (todoIndex !== -1) { 72 | todoIdsByUser[VIEWER_ID].splice(todoIndex, 1); 73 | } 74 | delete todosById[id]; 75 | } 76 | 77 | export function removeCompletedTodos() { 78 | const todosToRemove = getTodos().filter(todo => todo.complete); 79 | todosToRemove.forEach(todo => removeTodo(todo.id)); 80 | return todosToRemove.map(todo => todo.id); 81 | } 82 | 83 | export function renameTodo(id, text) { 84 | const todo = getTodo(id); 85 | todo.text = text; 86 | } 87 | -------------------------------------------------------------------------------- /koa2-todo/js/app.js: -------------------------------------------------------------------------------- 1 | import 'babel-polyfill'; 2 | import 'todomvc-common'; 3 | 4 | import React from 'react'; 5 | import { render } from 'react-dom'; 6 | import Relay from 'react-relay'; 7 | import { createHashHistory } from 'history'; 8 | import { IndexRoute, Route, Router, applyRouterMiddleware, useRouterHistory } from 'react-router'; 9 | import useRelay from 'react-router-relay'; 10 | import TodoApp from './components/TodoApp'; 11 | import TodoList from './components/TodoList'; 12 | import ViewerQueries from './queries/ViewerQueries'; 13 | 14 | const history = useRouterHistory(createHashHistory)({ queryKey: false }); 15 | const mountNode = document.getElementById('root'); 16 | 17 | render( 18 | 22 | 25 | ({ status: 'any' })} 29 | /> 30 | 34 | 35 | , 36 | mountNode 37 | ); 38 | -------------------------------------------------------------------------------- /koa2-todo/js/components/Todo.js: -------------------------------------------------------------------------------- 1 | import ChangeTodoStatusMutation from '../mutations/ChangeTodoStatusMutation'; 2 | import RemoveTodoMutation from '../mutations/RemoveTodoMutation'; 3 | import RenameTodoMutation from '../mutations/RenameTodoMutation'; 4 | import TodoTextInput from './TodoTextInput'; 5 | 6 | import React from 'react'; 7 | import Relay from 'react-relay'; 8 | import classnames from 'classnames'; 9 | 10 | class Todo extends React.Component { 11 | state = { 12 | isEditing: false, 13 | }; 14 | _handleCompleteChange = (e) => { 15 | const complete = e.target.checked; 16 | this.props.relay.commitUpdate( 17 | new ChangeTodoStatusMutation({ 18 | complete, 19 | todo: this.props.todo, 20 | viewer: this.props.viewer, 21 | }) 22 | ); 23 | }; 24 | _handleDestroyClick = () => { 25 | this._removeTodo(); 26 | }; 27 | _handleLabelDoubleClick = () => { 28 | this._setEditMode(true); 29 | }; 30 | _handleTextInputCancel = () => { 31 | this._setEditMode(false); 32 | }; 33 | _handleTextInputDelete = () => { 34 | this._setEditMode(false); 35 | this._removeTodo(); 36 | }; 37 | _handleTextInputSave = (text) => { 38 | this._setEditMode(false); 39 | this.props.relay.commitUpdate( 40 | new RenameTodoMutation({ todo: this.props.todo, text }) 41 | ); 42 | }; 43 | _removeTodo() { 44 | this.props.relay.commitUpdate( 45 | new RemoveTodoMutation({ todo: this.props.todo, viewer: this.props.viewer }) 46 | ); 47 | } 48 | _setEditMode = (shouldEdit) => { 49 | this.setState({ isEditing: shouldEdit }); 50 | }; 51 | renderTextInput() { 52 | return ( 53 | 61 | ); 62 | } 63 | render() { 64 | return ( 65 |
  • 70 |
    71 | 77 | 80 |
    85 | {this.state.isEditing && this.renderTextInput()} 86 |
  • 87 | ); 88 | } 89 | } 90 | 91 | export default Relay.createContainer(Todo, { 92 | fragments: { 93 | todo: () => Relay.QL` 94 | fragment on Todo { 95 | complete, 96 | id, 97 | text, 98 | ${ChangeTodoStatusMutation.getFragment('todo')}, 99 | ${RemoveTodoMutation.getFragment('todo')}, 100 | ${RenameTodoMutation.getFragment('todo')}, 101 | } 102 | `, 103 | viewer: () => Relay.QL` 104 | fragment on User { 105 | ${ChangeTodoStatusMutation.getFragment('viewer')}, 106 | ${RemoveTodoMutation.getFragment('viewer')}, 107 | } 108 | `, 109 | }, 110 | }); 111 | -------------------------------------------------------------------------------- /koa2-todo/js/components/TodoApp.js: -------------------------------------------------------------------------------- 1 | import AddTodoMutation from '../mutations/AddTodoMutation'; 2 | import TodoListFooter from './TodoListFooter'; 3 | import TodoTextInput from './TodoTextInput'; 4 | 5 | import React from 'react'; 6 | import Relay from 'react-relay'; 7 | 8 | class TodoApp extends React.Component { 9 | _handleTextInputSave = (text) => { 10 | this.props.relay.commitUpdate( 11 | new AddTodoMutation({ text, viewer: this.props.viewer }) 12 | ); 13 | }; 14 | render() { 15 | const hasTodos = this.props.viewer.totalCount > 0; 16 | return ( 17 |
    18 |
    19 |
    20 |

    21 | todos 22 |

    23 | 29 |
    30 | 31 | {this.props.children} 32 | 33 | {hasTodos && 34 | 38 | } 39 |
    40 | 53 |
    54 | ); 55 | } 56 | } 57 | 58 | export default Relay.createContainer(TodoApp, { 59 | fragments: { 60 | viewer: () => Relay.QL` 61 | fragment on User { 62 | totalCount, 63 | ${AddTodoMutation.getFragment('viewer')}, 64 | ${TodoListFooter.getFragment('viewer')}, 65 | } 66 | `, 67 | }, 68 | }); 69 | -------------------------------------------------------------------------------- /koa2-todo/js/components/TodoList.js: -------------------------------------------------------------------------------- 1 | import MarkAllTodosMutation from '../mutations/MarkAllTodosMutation'; 2 | import Todo from './Todo'; 3 | 4 | import React from 'react'; 5 | import Relay from 'react-relay'; 6 | 7 | class TodoList extends React.Component { 8 | _handleMarkAllChange = (e) => { 9 | const complete = e.target.checked; 10 | this.props.relay.commitUpdate( 11 | new MarkAllTodosMutation({ 12 | complete, 13 | todos: this.props.viewer.todos, 14 | viewer: this.props.viewer, 15 | }) 16 | ); 17 | }; 18 | renderTodos() { 19 | return this.props.viewer.todos.edges.map(edge => 20 | 25 | ); 26 | } 27 | render() { 28 | const numTodos = this.props.viewer.totalCount; 29 | const numCompletedTodos = this.props.viewer.completedCount; 30 | return ( 31 |
    32 | 38 | 41 |
      42 | {this.renderTodos()} 43 |
    44 |
    45 | ); 46 | } 47 | } 48 | 49 | export default Relay.createContainer(TodoList, { 50 | initialVariables: { 51 | status: null, 52 | }, 53 | 54 | prepareVariables({ status }) { 55 | let nextStatus; 56 | if (status === 'active' || status === 'completed') { 57 | nextStatus = status; 58 | } else { 59 | // This matches the Backbone example, which displays all todos on an 60 | // invalid route. 61 | nextStatus = 'any'; 62 | } 63 | return { 64 | status: nextStatus, 65 | }; 66 | }, 67 | 68 | fragments: { 69 | viewer: () => Relay.QL` 70 | fragment on User { 71 | completedCount, 72 | todos( 73 | status: $status, 74 | first: 2147483647 # max GraphQLInt 75 | ) { 76 | edges { 77 | node { 78 | id, 79 | ${Todo.getFragment('todo')}, 80 | }, 81 | }, 82 | ${MarkAllTodosMutation.getFragment('todos')}, 83 | }, 84 | totalCount, 85 | ${MarkAllTodosMutation.getFragment('viewer')}, 86 | ${Todo.getFragment('viewer')}, 87 | } 88 | `, 89 | }, 90 | }); 91 | -------------------------------------------------------------------------------- /koa2-todo/js/components/TodoListFooter.js: -------------------------------------------------------------------------------- 1 | import { IndexLink, Link } from 'react-router'; 2 | import RemoveCompletedTodosMutation from '../mutations/RemoveCompletedTodosMutation'; 3 | 4 | import React from 'react'; 5 | import Relay from 'react-relay'; 6 | 7 | class TodoListFooter extends React.Component { 8 | _handleRemoveCompletedTodosClick = () => { 9 | this.props.relay.commitUpdate( 10 | new RemoveCompletedTodosMutation({ 11 | todos: this.props.viewer.todos, 12 | viewer: this.props.viewer, 13 | }) 14 | ); 15 | }; 16 | render() { 17 | const numCompletedTodos = this.props.viewer.completedCount; 18 | const numRemainingTodos = this.props.viewer.totalCount - numCompletedTodos; 19 | return ( 20 |
    21 | 22 | {numRemainingTodos} item{numRemainingTodos === 1 ? '' : 's'} left 23 | 24 |
      25 |
    • 26 | All 27 |
    • 28 |
    • 29 | Active 30 |
    • 31 |
    • 32 | Completed 33 |
    • 34 |
    35 | {numCompletedTodos > 0 && 36 | 41 | } 42 |
    43 | ); 44 | } 45 | } 46 | 47 | export default Relay.createContainer(TodoListFooter, { 48 | fragments: { 49 | viewer: () => Relay.QL` 50 | fragment on User { 51 | completedCount, 52 | todos( 53 | status: "completed", 54 | first: 2147483647 # max GraphQLInt 55 | ) { 56 | ${RemoveCompletedTodosMutation.getFragment('todos')}, 57 | }, 58 | totalCount, 59 | ${RemoveCompletedTodosMutation.getFragment('viewer')}, 60 | } 61 | `, 62 | }, 63 | }); 64 | -------------------------------------------------------------------------------- /koa2-todo/js/components/TodoTextInput.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | 4 | const { PropTypes } = React; 5 | 6 | const ENTER_KEY_CODE = 13; 7 | const ESC_KEY_CODE = 27; 8 | 9 | export default class TodoTextInput extends React.Component { 10 | static propTypes = { 11 | className: PropTypes.string, 12 | commitOnBlur: PropTypes.bool.isRequired, 13 | initialValue: PropTypes.string, 14 | onCancel: PropTypes.func, 15 | onDelete: PropTypes.func, 16 | onSave: PropTypes.func.isRequired, 17 | placeholder: PropTypes.string, 18 | }; 19 | static defaultProps = { 20 | commitOnBlur: false, 21 | }; 22 | state = { 23 | isEditing: false, 24 | text: this.props.initialValue || '', 25 | }; 26 | componentDidMount() { 27 | ReactDOM.findDOMNode(this).focus(); 28 | } 29 | _commitChanges = () => { 30 | const newText = this.state.text.trim(); 31 | if (this.props.onDelete && newText === '') { 32 | this.props.onDelete(); 33 | } else if (this.props.onCancel && newText === this.props.initialValue) { 34 | this.props.onCancel(); 35 | } else if (newText !== '') { 36 | this.props.onSave(newText); 37 | this.setState({ text: '' }); 38 | } 39 | }; 40 | _handleBlur = () => { 41 | if (this.props.commitOnBlur) { 42 | this._commitChanges(); 43 | } 44 | }; 45 | _handleChange = (e) => { 46 | this.setState({ text: e.target.value }); 47 | }; 48 | _handleKeyDown = (e) => { 49 | if (this.props.onCancel && e.keyCode === ESC_KEY_CODE) { 50 | this.props.onCancel(); 51 | } else if (e.keyCode === ENTER_KEY_CODE) { 52 | this._commitChanges(); 53 | } 54 | }; 55 | render() { 56 | return ( 57 | 65 | ); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /koa2-todo/js/mutations/AddTodoMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class AddTodoMutation extends Relay.Mutation { 4 | static fragments = { 5 | viewer: () => Relay.QL` 6 | fragment on User { 7 | id, 8 | totalCount, 9 | } 10 | `, 11 | }; 12 | getMutation() { 13 | return Relay.QL`mutation{addTodo}`; 14 | } 15 | getFatQuery() { 16 | return Relay.QL` 17 | fragment on AddTodoPayload @relay(pattern: true) { 18 | todoEdge, 19 | viewer { 20 | todos, 21 | totalCount, 22 | }, 23 | } 24 | `; 25 | } 26 | getConfigs() { 27 | return [{ 28 | type: 'RANGE_ADD', 29 | parentName: 'viewer', 30 | parentID: this.props.viewer.id, 31 | connectionName: 'todos', 32 | edgeName: 'todoEdge', 33 | rangeBehaviors: ({ status }) => { 34 | if (status === 'completed') { 35 | return 'ignore'; 36 | } 37 | return 'append'; 38 | }, 39 | }]; 40 | } 41 | getVariables() { 42 | return { 43 | text: this.props.text, 44 | }; 45 | } 46 | getOptimisticResponse() { 47 | return { 48 | // FIXME: totalCount gets updated optimistically, but this edge does not 49 | // get added until the server responds 50 | todoEdge: { 51 | node: { 52 | complete: false, 53 | text: this.props.text, 54 | }, 55 | }, 56 | viewer: { 57 | id: this.props.viewer.id, 58 | totalCount: this.props.viewer.totalCount + 1, 59 | }, 60 | }; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /koa2-todo/js/mutations/ChangeTodoStatusMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class ChangeTodoStatusMutation extends Relay.Mutation { 4 | static fragments = { 5 | todo: () => Relay.QL` 6 | fragment on Todo { 7 | id, 8 | } 9 | `, 10 | // TODO: Mark completedCount optional 11 | viewer: () => Relay.QL` 12 | fragment on User { 13 | id, 14 | completedCount, 15 | } 16 | `, 17 | }; 18 | getMutation() { 19 | return Relay.QL`mutation{changeTodoStatus}`; 20 | } 21 | getFatQuery() { 22 | return Relay.QL` 23 | fragment on ChangeTodoStatusPayload @relay(pattern: true) { 24 | todo { 25 | complete, 26 | }, 27 | viewer { 28 | completedCount, 29 | todos, 30 | }, 31 | } 32 | `; 33 | } 34 | getConfigs() { 35 | return [{ 36 | type: 'FIELDS_CHANGE', 37 | fieldIDs: { 38 | todo: this.props.todo.id, 39 | viewer: this.props.viewer.id, 40 | }, 41 | }]; 42 | } 43 | getVariables() { 44 | return { 45 | complete: this.props.complete, 46 | id: this.props.todo.id, 47 | }; 48 | } 49 | getOptimisticResponse() { 50 | const viewerPayload = { id: this.props.viewer.id }; 51 | if (this.props.viewer.completedCount != null) { 52 | viewerPayload.completedCount = this.props.complete ? 53 | this.props.viewer.completedCount + 1 : 54 | this.props.viewer.completedCount - 1; 55 | } 56 | return { 57 | todo: { 58 | complete: this.props.complete, 59 | id: this.props.todo.id, 60 | }, 61 | viewer: viewerPayload, 62 | }; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /koa2-todo/js/mutations/MarkAllTodosMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class MarkAllTodosMutation extends Relay.Mutation { 4 | static fragments = { 5 | // TODO: Mark edges and totalCount optional 6 | todos: () => Relay.QL` 7 | fragment on TodoConnection { 8 | edges { 9 | node { 10 | complete, 11 | id, 12 | }, 13 | }, 14 | } 15 | `, 16 | viewer: () => Relay.QL` 17 | fragment on User { 18 | id, 19 | totalCount, 20 | } 21 | `, 22 | }; 23 | getMutation() { 24 | return Relay.QL`mutation{markAllTodos}`; 25 | } 26 | getFatQuery() { 27 | return Relay.QL` 28 | fragment on MarkAllTodosPayload @relay(pattern: true) { 29 | viewer { 30 | completedCount, 31 | todos, 32 | }, 33 | } 34 | `; 35 | } 36 | getConfigs() { 37 | return [{ 38 | type: 'FIELDS_CHANGE', 39 | fieldIDs: { 40 | viewer: this.props.viewer.id, 41 | }, 42 | }]; 43 | } 44 | getVariables() { 45 | return { 46 | complete: this.props.complete, 47 | }; 48 | } 49 | getOptimisticResponse() { 50 | const viewerPayload = { id: this.props.viewer.id }; 51 | if (this.props.todos && this.props.todos.edges) { 52 | viewerPayload.todos = { 53 | edges: this.props.todos.edges 54 | .filter(edge => edge.node.complete !== this.props.complete) 55 | .map(edge => ({ 56 | node: { 57 | complete: this.props.complete, 58 | id: edge.node.id, 59 | }, 60 | })), 61 | }; 62 | } 63 | if (this.props.viewer.totalCount != null) { 64 | viewerPayload.completedCount = this.props.complete ? 65 | this.props.viewer.totalCount : 66 | 0; 67 | } 68 | return { 69 | viewer: viewerPayload, 70 | }; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /koa2-todo/js/mutations/RemoveCompletedTodosMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class RemoveCompletedTodosMutation extends Relay.Mutation { 4 | static fragments = { 5 | // TODO: Make completedCount, edges, and totalCount optional 6 | todos: () => Relay.QL` 7 | fragment on TodoConnection { 8 | edges { 9 | node { 10 | complete, 11 | id, 12 | }, 13 | }, 14 | } 15 | `, 16 | viewer: () => Relay.QL` 17 | fragment on User { 18 | completedCount, 19 | id, 20 | totalCount, 21 | } 22 | `, 23 | }; 24 | getMutation() { 25 | return Relay.QL`mutation{removeCompletedTodos}`; 26 | } 27 | getFatQuery() { 28 | return Relay.QL` 29 | fragment on RemoveCompletedTodosPayload @relay(pattern: true) { 30 | deletedTodoIds, 31 | viewer { 32 | completedCount, 33 | totalCount, 34 | }, 35 | } 36 | `; 37 | } 38 | getConfigs() { 39 | return [{ 40 | type: 'NODE_DELETE', 41 | parentName: 'viewer', 42 | parentID: this.props.viewer.id, 43 | connectionName: 'todos', 44 | deletedIDFieldName: 'deletedTodoIds', 45 | }]; 46 | } 47 | getVariables() { 48 | return {}; 49 | } 50 | getOptimisticResponse() { 51 | let deletedTodoIds; 52 | let newTotalCount; 53 | if (this.props.todos && this.props.todos.edges) { 54 | deletedTodoIds = this.props.todos.edges 55 | .filter(edge => edge.node.complete) 56 | .map(edge => edge.node.id); 57 | } 58 | const { completedCount, totalCount } = this.props.viewer; 59 | if (completedCount != null && totalCount != null) { 60 | newTotalCount = totalCount - completedCount; 61 | } 62 | return { 63 | deletedTodoIds, 64 | viewer: { 65 | completedCount: 0, 66 | id: this.props.viewer.id, 67 | totalCount: newTotalCount, 68 | }, 69 | }; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /koa2-todo/js/mutations/RemoveTodoMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class RemoveTodoMutation extends Relay.Mutation { 4 | static fragments = { 5 | // TODO: Mark complete as optional 6 | todo: () => Relay.QL` 7 | fragment on Todo { 8 | complete, 9 | id, 10 | } 11 | `, 12 | // TODO: Mark completedCount and totalCount as optional 13 | viewer: () => Relay.QL` 14 | fragment on User { 15 | completedCount, 16 | id, 17 | totalCount, 18 | } 19 | `, 20 | }; 21 | getMutation() { 22 | return Relay.QL`mutation{removeTodo}`; 23 | } 24 | getFatQuery() { 25 | return Relay.QL` 26 | fragment on RemoveTodoPayload @relay(pattern: true) { 27 | deletedTodoId, 28 | viewer { 29 | completedCount, 30 | totalCount, 31 | }, 32 | } 33 | `; 34 | } 35 | getConfigs() { 36 | return [{ 37 | type: 'NODE_DELETE', 38 | parentName: 'viewer', 39 | parentID: this.props.viewer.id, 40 | connectionName: 'todos', 41 | deletedIDFieldName: 'deletedTodoId', 42 | }]; 43 | } 44 | getVariables() { 45 | return { 46 | id: this.props.todo.id, 47 | }; 48 | } 49 | getOptimisticResponse() { 50 | const viewerPayload = { id: this.props.viewer.id }; 51 | if (this.props.viewer.completedCount != null) { 52 | viewerPayload.completedCount = this.props.todo.complete === true ? 53 | this.props.viewer.completedCount - 1 : 54 | this.props.viewer.completedCount; 55 | } 56 | if (this.props.viewer.totalCount != null) { 57 | viewerPayload.totalCount = this.props.viewer.totalCount - 1; 58 | } 59 | return { 60 | deletedTodoId: this.props.todo.id, 61 | viewer: viewerPayload, 62 | }; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /koa2-todo/js/mutations/RenameTodoMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class RenameTodoMutation extends Relay.Mutation { 4 | static fragments = { 5 | todo: () => Relay.QL` 6 | fragment on Todo { 7 | id, 8 | } 9 | `, 10 | }; 11 | getMutation() { 12 | return Relay.QL`mutation{renameTodo}`; 13 | } 14 | getFatQuery() { 15 | return Relay.QL` 16 | fragment on RenameTodoPayload @relay(pattern: true) { 17 | todo { 18 | text, 19 | } 20 | } 21 | `; 22 | } 23 | getConfigs() { 24 | return [{ 25 | type: 'FIELDS_CHANGE', 26 | fieldIDs: { 27 | todo: this.props.todo.id, 28 | }, 29 | }]; 30 | } 31 | getVariables() { 32 | return { 33 | id: this.props.todo.id, 34 | text: this.props.text, 35 | }; 36 | } 37 | getOptimisticResponse() { 38 | return { 39 | todo: { 40 | id: this.props.todo.id, 41 | text: this.props.text, 42 | }, 43 | }; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /koa2-todo/js/queries/ViewerQueries.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default { 4 | viewer: () => Relay.QL`query { viewer }`, 5 | }; 6 | -------------------------------------------------------------------------------- /koa2-todo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "start": "babel-node ./server.js", 5 | "update-schema": "babel-node ./scripts/updateSchema.js", 6 | "lint": "./node_modules/.bin/eslint ." 7 | }, 8 | "dependencies": { 9 | "babel-core": "^6.5.2", 10 | "babel-loader": "^6.2.4", 11 | "babel-polyfill": "^6.9.0", 12 | "babel-preset-es2015": "^6.9.0", 13 | "babel-preset-react": "^6.5.0", 14 | "babel-preset-stage-0": "^6.5.0", 15 | "babel-relay-plugin": "^0.9.0", 16 | "classnames": "^2.2.5", 17 | "express": "^4.13.4", 18 | "graphql": "^0.5.0", 19 | "graphql-relay": "^0.4.1", 20 | "history": "^2.1.1", 21 | "koa": "^2.0.0", 22 | "koa-convert": "^1.2.0", 23 | "koa-graphql": "^0.5.1", 24 | "koa-mount": "^2.0.0", 25 | "react": "^15.0.2", 26 | "react-dom": "^15.0.2", 27 | "react-relay": "^0.9.0", 28 | "react-router": "^2.4.1", 29 | "react-router-relay": "^0.13.2", 30 | "todomvc-app-css": "^2.0.6", 31 | "todomvc-common": "^1.0.2", 32 | "webpack": "^1.13.1", 33 | "webpack-dev-server": "^1.14.1" 34 | }, 35 | "devDependencies": { 36 | "babel-cli": "^6.9.0", 37 | "babel-eslint": "^6.0.3", 38 | "eslint": "^2.8.0", 39 | "eslint-config-airbnb": "^7.0.0", 40 | "eslint-plugin-jsx-a11y": "^0.6.2", 41 | "eslint-plugin-react": "^4.3.0" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /koa2-todo/public/base.css: -------------------------------------------------------------------------------- 1 | ../node_modules/todomvc-common/base.css -------------------------------------------------------------------------------- /koa2-todo/public/index.css: -------------------------------------------------------------------------------- 1 | ../node_modules/todomvc-app-css/index.css -------------------------------------------------------------------------------- /koa2-todo/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Relay • TodoMVC 7 | 8 | 9 | 10 | 11 |
    12 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /koa2-todo/public/learn.json: -------------------------------------------------------------------------------- 1 | { 2 | "relay": { 3 | "name": "Koa GraphQL", 4 | "description": "Create a GraphQL HTTP server with Koa. ", 5 | "homepage": "https://github.com/chentsulin/koa-graphql", 6 | "examples": [{ 7 | "name": "koa-graphql + relay Example", 8 | "url": "", 9 | "source_url": "https://github.com/chentsulin/koa-graphql-relay-example", 10 | "type": "backend" 11 | }], 12 | "link_groups": [{ 13 | "heading": "Resources", 14 | "links": [{ 15 | "name": "Relay Documentation", 16 | "url": "https://facebook.github.io/relay/docs/getting-started.html" 17 | }, { 18 | "name": "Relay API Reference", 19 | "url": "https://facebook.github.io/relay/docs/api-reference-relay.html" 20 | }, { 21 | "name": "Koa GraphQL on GitHub", 22 | "url": "https://github.com/chentsulin/koa-graphql" 23 | }] 24 | }, { 25 | "heading": "Issue Tracker", 26 | "links": [{ 27 | "name": "Open a new issue on GitHub", 28 | "url": "https://github.com/chentsulin/koa-graphql-relay-example/issues/new" 29 | }] 30 | }] 31 | }, 32 | "templates": { 33 | "todomvc": "

    <%= name %>

    <% if (typeof examples !== 'undefined') { %> <% examples.forEach(function (example) { %>
    <%= example.name %>
    <% if (!location.href.match(example.url + '/')) { %> \" href=\"<%= example.url %>\">Demo, <% } if (example.type === 'backend') { %>\"><% } else { %>\"><% } %>Source <% }); %> <% } %>

    <%= description %>

    <% if (typeof link_groups !== 'undefined') { %>
    <% link_groups.forEach(function (link_group) { %>

    <%= link_group.heading %>

    <% }); %> <% } %>

    If you have other helpful links to share, or find any of the links above no longer work, please let us know.
    " 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /koa2-todo/scripts/updateSchema.js: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | import { schema } from '../data/schema'; 4 | import { graphql } from 'graphql'; 5 | import { introspectionQuery, printSchema } from 'graphql/utilities'; 6 | 7 | // Save JSON of full schema introspection for Babel Relay Plugin to use 8 | (async () => { 9 | const result = await (graphql(schema, introspectionQuery)); 10 | if (result.errors) { 11 | console.error( 12 | 'ERROR introspecting schema: ', 13 | JSON.stringify(result.errors, null, 2) 14 | ); 15 | } else { 16 | fs.writeFileSync( 17 | path.join(__dirname, '../data/schema.json'), 18 | JSON.stringify(result, null, 2) 19 | ); 20 | } 21 | })(); 22 | 23 | // Save user readable type system shorthand of schema 24 | fs.writeFileSync( 25 | path.join(__dirname, '../data/schema.graphql'), 26 | printSchema(schema) 27 | ); 28 | -------------------------------------------------------------------------------- /koa2-todo/server.js: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import Koa from 'koa'; 3 | import graphQLHTTP from 'koa-graphql'; 4 | import mount from 'koa-mount'; 5 | import convert from 'koa-convert'; 6 | import path from 'path'; 7 | import webpack from 'webpack'; 8 | import WebpackDevServer from 'webpack-dev-server'; 9 | import { schema } from './data/schema'; 10 | 11 | const APP_PORT = 3000; 12 | const GRAPHQL_PORT = 8080; 13 | 14 | // Expose a GraphQL endpoint 15 | const graphQLServer = new Koa(); 16 | 17 | graphQLServer.use(mount('/', convert(graphQLHTTP({ schema, pretty: true })))); 18 | 19 | graphQLServer.listen(GRAPHQL_PORT, () => console.log( 20 | `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}` 21 | )); 22 | 23 | // Serve the Relay app 24 | const compiler = webpack({ 25 | devtool: 'cheap-module-eval-source-map', 26 | entry: path.resolve(__dirname, 'js', 'app.js'), 27 | module: { 28 | loaders: [ 29 | { 30 | exclude: /node_modules/, 31 | loader: 'babel', 32 | test: /\.js$/, 33 | }, 34 | ], 35 | }, 36 | output: { filename: 'app.js', path: '/' }, 37 | }); 38 | 39 | const app = new WebpackDevServer(compiler, { 40 | contentBase: '/public/', 41 | proxy: { '/graphql': `http://localhost:${GRAPHQL_PORT}` }, 42 | publicPath: '/js/', 43 | stats: { colors: true }, 44 | }); 45 | 46 | // Serve static resources 47 | app.use('/', express.static(path.resolve(__dirname, 'public'))); 48 | 49 | app.listen(APP_PORT, () => { 50 | console.log(`App is now running on http://localhost:${APP_PORT}`); 51 | }); 52 | -------------------------------------------------------------------------------- /react-native-TodoMVC/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "development": { 4 | "passPerPreset": true, 5 | "presets": [ 6 | { 7 | "plugins": [ 8 | "./plugins/babelRelayPlugin" 9 | ] 10 | }, 11 | "react-native" 12 | ] 13 | }, 14 | "production": { 15 | "passPerPreset": true, 16 | "presets": [ 17 | { 18 | "plugins": [ 19 | "./plugins/babelRelayPlugin" 20 | ] 21 | }, 22 | "react-native" 23 | ] 24 | }, 25 | "server": { 26 | "plugins": [ 27 | "./plugins/babelRelayPlugin" 28 | ], 29 | "presets": [ 30 | "es2015", 31 | "stage-0" 32 | ] 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /react-native-TodoMVC/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb", 3 | "parser": "babel-eslint", 4 | "env": { 5 | "node": true 6 | }, 7 | "rules": { 8 | "eqeqeq": 0, 9 | "no-console": 0, 10 | "no-use-before-define": 0, 11 | "react/prop-types": 0, 12 | "react/jsx-closing-bracket-location": 0, 13 | "react/prefer-stateless-function": 0, 14 | "react/jsx-no-bind": 0, 15 | "react/jsx-boolean-value": 0, 16 | "react/sort-comp": 0 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /react-native-TodoMVC/.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | 3 | # We fork some components by platform. 4 | .*/*.web.js 5 | .*/*.android.js 6 | 7 | # Some modules have their own node_modules with overlap 8 | .*/node_modules/node-haste/.* 9 | 10 | # Ugh 11 | .*/node_modules/babel.* 12 | .*/node_modules/babylon.* 13 | .*/node_modules/invariant.* 14 | 15 | # Ignore react and fbjs where there are overlaps, but don't ignore 16 | # anything that react-native relies on 17 | .*/node_modules/fbjs/lib/Map.js 18 | .*/node_modules/fbjs/lib/Promise.js 19 | .*/node_modules/fbjs/lib/fetch.js 20 | .*/node_modules/fbjs/lib/ExecutionEnvironment.js 21 | .*/node_modules/fbjs/lib/isEmpty.js 22 | .*/node_modules/fbjs/lib/crc32.js 23 | .*/node_modules/fbjs/lib/ErrorUtils.js 24 | 25 | # Flow has a built-in definition for the 'react' module which we prefer to use 26 | # over the currently-untyped source 27 | .*/node_modules/react/react.js 28 | .*/node_modules/react/lib/React.js 29 | .*/node_modules/react/lib/ReactDOM.js 30 | 31 | # Ignore commoner tests 32 | .*/node_modules/commoner/test/.* 33 | 34 | # See https://github.com/facebook/flow/issues/442 35 | .*/react-tools/node_modules/commoner/lib/reader.js 36 | 37 | # Ignore jest 38 | .*/node_modules/jest-cli/.* 39 | 40 | # Ignore Website 41 | .*/website/.* 42 | 43 | [include] 44 | 45 | [libs] 46 | node_modules/react-native/Libraries/react-native/react-native-interface.js 47 | 48 | [options] 49 | module.system=haste 50 | 51 | munge_underscores=true 52 | 53 | module.name_mapper='^image![a-zA-Z0-9$_-]+$' -> 'GlobalImageStub' 54 | module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\)$' -> 'RelativeImageStub' 55 | 56 | suppress_type=$FlowIssue 57 | suppress_type=$FlowFixMe 58 | suppress_type=$FixMe 59 | 60 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(2[0-1]\\|1[0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\) 61 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(2[0-1]\\|1[0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+ 62 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy 63 | 64 | [version] 65 | 0.24.2 66 | -------------------------------------------------------------------------------- /react-native-TodoMVC/.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # Xcode 6 | # 7 | build/ 8 | *.pbxuser 9 | !default.pbxuser 10 | *.mode1v3 11 | !default.mode1v3 12 | *.mode2v3 13 | !default.mode2v3 14 | *.perspectivev3 15 | !default.perspectivev3 16 | xcuserdata 17 | *.xccheckout 18 | *.moved-aside 19 | DerivedData 20 | *.hmap 21 | *.ipa 22 | *.xcuserstate 23 | project.xcworkspace 24 | 25 | # Android/IJ 26 | # 27 | .idea 28 | .gradle 29 | local.properties 30 | 31 | # node.js 32 | # 33 | node_modules/ 34 | npm-debug.log 35 | -------------------------------------------------------------------------------- /react-native-TodoMVC/.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /react-native-TodoMVC/README.md: -------------------------------------------------------------------------------- 1 | # React Native / Relay TodoMVC 2 | 3 | ## Installation 4 | 5 | ``` 6 | npm install -g react-native-cli && npm install 7 | ``` 8 | 9 | ## Running 10 | 11 | ### Start the GraphQL server: 12 | 13 | ``` 14 | npm start 15 | ``` 16 | 17 | ### Ensure you can connect to the development server: 18 | 19 | #### iOS 20 | 21 | Ensure that you are on the same WiFi network as your computer. If you're using a 22 | cell data plan, your phone can't access your computer's local IP address. 23 | 24 | #### Android 25 | 26 | You need to run `adb reverse tcp:8080 tcp:8080` to forward requests from the 27 | device to your computer. This works only on Android 5.0 and newer. 28 | 29 | #### If all else fails 30 | 31 | Open `app.js` and change `localhost:8080` to an IP/port that your device can 32 | access. 33 | 34 | ### Run on your device of choice: 35 | 36 | ``` 37 | react-native run-ios # or... 38 | react-native run-android 39 | ``` 40 | 41 | ## Developing 42 | 43 | If at any time you make changes to `data/schema.js`, stop the server, 44 | regenerate `data/schema.json`, and restart the server: 45 | 46 | ``` 47 | npm run update-schema 48 | npm start 49 | ``` 50 | 51 | ## License 52 | 53 | This file provided by Facebook is for non-commercial testing and evaluation 54 | purposes only. Facebook reserves all rights not expressly granted. 55 | 56 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 57 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 58 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 59 | FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 60 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 61 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 62 | -------------------------------------------------------------------------------- /react-native-TodoMVC/android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Disabling obfuscation is useful if you collect stack traces from production crashes 20 | # (unless you are using a system that supports de-obfuscate the stack traces). 21 | -dontobfuscate 22 | 23 | # React Native 24 | 25 | # Keep our interfaces so they can be used by other ProGuard rules. 26 | # See http://sourceforge.net/p/proguard/bugs/466/ 27 | -keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip 28 | -keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters 29 | 30 | # Do not strip any method/class that is annotated with @DoNotStrip 31 | -keep @com.facebook.proguard.annotations.DoNotStrip class * 32 | -keepclassmembers class * { 33 | @com.facebook.proguard.annotations.DoNotStrip *; 34 | } 35 | 36 | -keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * { 37 | void set*(***); 38 | *** get*(); 39 | } 40 | 41 | -keep class * extends com.facebook.react.bridge.JavaScriptModule { *; } 42 | -keep class * extends com.facebook.react.bridge.NativeModule { *; } 43 | -keepclassmembers,includedescriptorclasses class * { native ; } 44 | -keepclassmembers class * { @com.facebook.react.uimanager.UIProp ; } 45 | -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp ; } 46 | -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup ; } 47 | 48 | -dontwarn com.facebook.react.** 49 | 50 | # okhttp 51 | 52 | -keepattributes Signature 53 | -keepattributes *Annotation* 54 | -keep class com.squareup.okhttp.** { *; } 55 | -keep interface com.squareup.okhttp.** { *; } 56 | -dontwarn com.squareup.okhttp.** 57 | 58 | # okio 59 | 60 | -keep class sun.misc.Unsafe { *; } 61 | -dontwarn java.nio.file.* 62 | -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement 63 | -dontwarn okio.** 64 | 65 | # stetho 66 | 67 | -dontwarn com.facebook.stetho.** 68 | -------------------------------------------------------------------------------- /react-native-TodoMVC/android/app/react.gradle: -------------------------------------------------------------------------------- 1 | import org.apache.tools.ant.taskdefs.condition.Os 2 | 3 | def config = project.hasProperty("react") ? project.react : []; 4 | 5 | def bundleAssetName = config.bundleAssetName ?: "index.android.bundle" 6 | def entryFile = config.entryFile ?: "index.android.js" 7 | 8 | // because elvis operator 9 | def elvisFile(thing) { 10 | return thing ? file(thing) : null; 11 | } 12 | 13 | def reactRoot = elvisFile(config.root) ?: file("../../") 14 | def inputExcludes = config.inputExcludes ?: ["android/**", "ios/**"] 15 | 16 | void runBefore(String dependentTaskName, Task task) { 17 | Task dependentTask = tasks.findByPath(dependentTaskName); 18 | if (dependentTask != null) { 19 | dependentTask.dependsOn task 20 | } 21 | } 22 | 23 | gradle.projectsEvaluated { 24 | // Grab all build types and product flavors 25 | def buildTypes = android.buildTypes.collect { type -> type.name } 26 | def productFlavors = android.productFlavors.collect { flavor -> flavor.name } 27 | 28 | // When no product flavors defined, use empty 29 | if (!productFlavors) productFlavors.add('') 30 | 31 | productFlavors.each { productFlavorName -> 32 | buildTypes.each { buildTypeName -> 33 | // Create variant and target names 34 | def targetName = "${productFlavorName.capitalize()}${buildTypeName.capitalize()}" 35 | def targetPath = productFlavorName ? 36 | "${productFlavorName}/${buildTypeName}" : 37 | "${buildTypeName}" 38 | 39 | // React js bundle directories 40 | def jsBundleDirConfigName = "jsBundleDir${targetName}" 41 | def jsBundleDir = elvisFile(config."$jsBundleDirConfigName") ?: 42 | file("$buildDir/intermediates/assets/${targetPath}") 43 | 44 | def resourcesDirConfigName = "jsBundleDir${targetName}" 45 | def resourcesDir = elvisFile(config."${resourcesDirConfigName}") ?: 46 | file("$buildDir/intermediates/res/merged/${targetPath}") 47 | def jsBundleFile = file("$jsBundleDir/$bundleAssetName") 48 | 49 | // Bundle task name for variant 50 | def bundleJsAndAssetsTaskName = "bundle${targetName}JsAndAssets" 51 | 52 | def currentBundleTask = tasks.create( 53 | name: bundleJsAndAssetsTaskName, 54 | type: Exec) { 55 | group = "react" 56 | description = "bundle JS and assets for ${targetName}." 57 | 58 | // Create dirs if they are not there (e.g. the "clean" task just ran) 59 | doFirst { 60 | jsBundleDir.mkdirs() 61 | resourcesDir.mkdirs() 62 | } 63 | 64 | // Set up inputs and outputs so gradle can cache the result 65 | inputs.files fileTree(dir: reactRoot, excludes: inputExcludes) 66 | outputs.dir jsBundleDir 67 | outputs.dir resourcesDir 68 | 69 | // Set up the call to the react-native cli 70 | workingDir reactRoot 71 | 72 | // Set up dev mode 73 | def devEnabled = !targetName.toLowerCase().contains("release") 74 | if (Os.isFamily(Os.FAMILY_WINDOWS)) { 75 | commandLine "cmd", "/c", "react-native", "bundle", "--platform", "android", "--dev", "${devEnabled}", 76 | "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir 77 | } else { 78 | commandLine "react-native", "bundle", "--platform", "android", "--dev", "${devEnabled}", 79 | "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir 80 | } 81 | 82 | enabled config."bundleIn${targetName}" || 83 | config."bundleIn${buildTypeName.capitalize()}" ?: 84 | targetName.toLowerCase().contains("release") 85 | } 86 | 87 | // Hook bundle${productFlavor}${buildType}JsAndAssets into the android build process 88 | currentBundleTask.dependsOn("merge${targetName}Resources") 89 | currentBundleTask.dependsOn("merge${targetName}Assets") 90 | 91 | runBefore("processArmeabi-v7a${targetName}Resources", currentBundleTask) 92 | runBefore("processX86${targetName}Resources", currentBundleTask) 93 | runBefore("processUniversal${targetName}Resources", currentBundleTask) 94 | runBefore("process${targetName}Resources", currentBundleTask) 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /react-native-TodoMVC/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 11 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /react-native-TodoMVC/android/app/src/main/java/com/todomvc/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.todomvc; 2 | 3 | import com.facebook.react.ReactActivity; 4 | import com.facebook.react.ReactPackage; 5 | import com.facebook.react.shell.MainReactPackage; 6 | 7 | import java.util.Arrays; 8 | import java.util.List; 9 | 10 | public class MainActivity extends ReactActivity { 11 | 12 | /** 13 | * Returns the name of the main component registered from JavaScript. 14 | * This is used to schedule rendering of the component. 15 | */ 16 | @Override 17 | protected String getMainComponentName() { 18 | return "TodoMVC"; 19 | } 20 | 21 | /** 22 | * Returns whether dev mode should be enabled. 23 | * This enables e.g. the dev menu. 24 | */ 25 | @Override 26 | protected boolean getUseDeveloperSupport() { 27 | return BuildConfig.DEBUG; 28 | } 29 | 30 | /** 31 | * A list of packages used by the app. If the app uses additional views 32 | * or modules besides the default ones, add more packages here. 33 | */ 34 | @Override 35 | protected List getPackages() { 36 | return Arrays.asList( 37 | new MainReactPackage() 38 | ); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /react-native-TodoMVC/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chentsulin/koa-graphql-relay-example/3cba433d190f141d8398c76dc5a0860c8317d5a0/react-native-TodoMVC/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /react-native-TodoMVC/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chentsulin/koa-graphql-relay-example/3cba433d190f141d8398c76dc5a0860c8317d5a0/react-native-TodoMVC/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /react-native-TodoMVC/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chentsulin/koa-graphql-relay-example/3cba433d190f141d8398c76dc5a0860c8317d5a0/react-native-TodoMVC/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /react-native-TodoMVC/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chentsulin/koa-graphql-relay-example/3cba433d190f141d8398c76dc5a0860c8317d5a0/react-native-TodoMVC/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /react-native-TodoMVC/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | TodoMVC 3 | 4 | -------------------------------------------------------------------------------- /react-native-TodoMVC/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /react-native-TodoMVC/android/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:1.3.1' 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | mavenLocal() 18 | jcenter() 19 | maven { 20 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm 21 | url "$projectDir/../../node_modules/react-native/android" 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /react-native-TodoMVC/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | android.useDeprecatedNdk=true 21 | -------------------------------------------------------------------------------- /react-native-TodoMVC/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chentsulin/koa-graphql-relay-example/3cba433d190f141d8398c76dc5a0860c8317d5a0/react-native-TodoMVC/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /react-native-TodoMVC/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip 6 | -------------------------------------------------------------------------------- /react-native-TodoMVC/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /react-native-TodoMVC/android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'TodoMVC' 2 | 3 | include ':app' 4 | -------------------------------------------------------------------------------- /react-native-TodoMVC/app.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import TodoApp from './components/TodoApp'; 14 | import TodoAppRoute from './routes/TodoAppRoute'; 15 | import React, { 16 | Component, 17 | } from 'react-native'; 18 | import Relay, { 19 | DefaultNetworkLayer, 20 | RootContainer, 21 | } from 'react-relay'; 22 | 23 | Relay.injectNetworkLayer( 24 | new DefaultNetworkLayer('http://localhost:8080') 25 | ); 26 | 27 | export default class TodoMVC extends Component { 28 | render(): void { 29 | return ( 30 | 34 | ); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /react-native-TodoMVC/components/StatusButton.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import React, { 14 | Component, 15 | PropTypes, 16 | StyleSheet, 17 | Text, 18 | TouchableHighlight, 19 | } from 'react-native'; 20 | 21 | export default class StatusButton extends Component { 22 | static propTypes = { 23 | active: PropTypes.bool.isRequired, 24 | children: PropTypes.oneOfType([ 25 | PropTypes.arrayOf(PropTypes.node), 26 | PropTypes.node, 27 | ]).isRequired, 28 | onPress: PropTypes.func.isRequired, 29 | style: Text.propTypes.style, 30 | }; 31 | render() { 32 | return ( 33 | 40 | 41 | {this.props.children} 42 | 43 | 44 | ); 45 | } 46 | } 47 | 48 | const styles = StyleSheet.create({ 49 | activeButton: { 50 | borderColor: 'rgba(175, 47, 47, 0.2)', 51 | borderRadius: 6, 52 | }, 53 | baseButton: { 54 | borderColor: 'transparent', 55 | borderWidth: 1, 56 | paddingHorizontal: 14, 57 | paddingVertical: 6, 58 | top: 1, 59 | }, 60 | buttonText: { 61 | fontSize: 16, 62 | }, 63 | }); 64 | -------------------------------------------------------------------------------- /react-native-TodoMVC/components/TodoApp.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import Relay from 'react-relay'; 14 | import StatusButton from './StatusButton'; 15 | import TodoList from './TodoList'; 16 | import TodoListFooter from './TodoListFooter'; 17 | import React, { 18 | Component, 19 | Platform, 20 | StyleSheet, 21 | Text, 22 | View, 23 | } from 'react-native'; 24 | 25 | class TodoApp extends Component { 26 | constructor(props, context) { 27 | super(props, context); 28 | this._handleStatusChange = this._handleStatusChange.bind(this); 29 | } 30 | _handleStatusChange(status) { 31 | this.props.relay.setVariables({ status }); 32 | } 33 | render() { 34 | return ( 35 | 36 | todos 37 | 38 | 41 | All 42 | 43 | 46 | Active 47 | 48 | 51 | Completed 52 | 53 | 54 | 59 | 64 | 65 | ); 66 | } 67 | } 68 | 69 | export default Relay.createContainer(TodoApp, { 70 | initialVariables: { 71 | status: 'any', 72 | }, 73 | fragments: { 74 | viewer: variables => Relay.QL` 75 | fragment on User { 76 | totalCount 77 | ${TodoList.getFragment('viewer', { status: variables.status })} 78 | ${TodoListFooter.getFragment('viewer', { status: variables.status })} 79 | } 80 | `, 81 | }, 82 | }); 83 | 84 | const styles = StyleSheet.create({ 85 | actionList: { 86 | alignItems: 'center', 87 | flexDirection: 'row', 88 | justifyContent: 'center', 89 | marginBottom: 15, 90 | }, 91 | container: { 92 | backgroundColor: '#F5F5F5', 93 | flex: 1, 94 | paddingTop: Platform.OS === 'android' ? undefined : 20, 95 | }, 96 | footer: { 97 | height: 10, 98 | paddingHorizontal: 15, 99 | }, 100 | header: { 101 | alignSelf: 'center', 102 | color: 'rgba(175, 47, 47, 0.15)', 103 | fontFamily: Platform.OS === 'android' ? 'sans-serif-light' : undefined, 104 | fontSize: 100, 105 | fontWeight: '100', 106 | }, 107 | list: { 108 | borderTopColor: 'rgba(0,0,0,0.1)', 109 | borderTopWidth: 1, 110 | flex: 1, 111 | shadowColor: 'black', 112 | shadowOffset: { 113 | height: -2, 114 | }, 115 | shadowOpacity: 0.03, 116 | shadowRadius: 1, 117 | }, 118 | }); 119 | -------------------------------------------------------------------------------- /react-native-TodoMVC/components/TodoListFooter.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import Relay from 'react-relay'; 14 | import RemoveCompletedTodosMutation from '../mutations/RemoveCompletedTodosMutation'; 15 | import React, { 16 | Component, 17 | PropTypes, 18 | StyleSheet, 19 | Text, 20 | TouchableHighlight, 21 | View, 22 | } from 'react-native'; 23 | 24 | class TodoListFooter extends Component { 25 | static propTypes = { 26 | status: PropTypes.oneOf(['active', 'any', 'completed']).isRequired, 27 | style: View.propTypes.style, 28 | }; 29 | constructor(props, context) { 30 | super(props, context); 31 | this._handleRemoveCompletedTodosPress = 32 | this._handleRemoveCompletedTodosPress.bind(this); 33 | } 34 | _handleRemoveCompletedTodosPress() { 35 | this.props.relay.commitUpdate( 36 | new RemoveCompletedTodosMutation({ 37 | todos: this.props.viewer.todos, 38 | viewer: this.props.viewer, 39 | }) 40 | ); 41 | } 42 | render() { 43 | const numCompletedTodos = this.props.viewer.completedCount; 44 | const numRemainingTodos = this.props.viewer.totalCount - numCompletedTodos; 45 | return ( 46 | 47 | 48 | 49 | {numRemainingTodos} 50 | item{numRemainingTodos === 1 ? '' : 's'} left 51 | 52 | {numCompletedTodos > 0 && 53 | 54 | Clear completed 55 | 56 | } 57 | 58 | ); 59 | } 60 | } 61 | 62 | export default Relay.createContainer(TodoListFooter, { 63 | initialVariables: { 64 | status: 'any', 65 | }, 66 | prepareVariables(prevVars) { 67 | return { 68 | ...prevVars, 69 | limit: 2147483647, // GraphQLInt 70 | }; 71 | }, 72 | fragments: { 73 | viewer: () => Relay.QL` 74 | fragment on User { 75 | completedCount 76 | todos(status: $status, first: $limit) { 77 | ${RemoveCompletedTodosMutation.getFragment('todos')} 78 | } 79 | totalCount 80 | ${RemoveCompletedTodosMutation.getFragment('viewer')} 81 | } 82 | `, 83 | }, 84 | }); 85 | 86 | const styles = StyleSheet.create({ 87 | container: { 88 | alignItems: 'center', 89 | flexDirection: 'row', 90 | height: 40, 91 | justifyContent: 'space-between', 92 | }, 93 | strong: { 94 | fontWeight: 'bold', 95 | }, 96 | }); 97 | -------------------------------------------------------------------------------- /react-native-TodoMVC/components/TodoTextInput.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import React, { 14 | Component, 15 | PropTypes, 16 | TextInput, 17 | } from 'react-native'; 18 | 19 | export default class TodoTextInput extends Component { 20 | static defaultProps = { 21 | commitOnBlur: false, 22 | }; 23 | static propTypes = { 24 | autoFocus: TextInput.propTypes.autoFocus, 25 | clearButtonMode: TextInput.propTypes.clearButtonMode, 26 | commitOnBlur: PropTypes.bool.isRequired, 27 | onCancel: PropTypes.func, 28 | onDelete: PropTypes.func, 29 | onSave: PropTypes.func.isRequired, 30 | placeholder: TextInput.propTypes.placeholder, 31 | style: TextInput.propTypes.style, 32 | value: TextInput.propTypes.value, 33 | }; 34 | state = { 35 | text: this.props.initialValue || '', 36 | }; 37 | constructor(props, context) { 38 | super(props, context); 39 | this._commitChanges = this._commitChanges.bind(this); 40 | this._handleBlur = this._handleBlur.bind(this); 41 | this._handleChangeText = this._handleChangeText.bind(this); 42 | this._handleSubmitEditing = this._handleSubmitEditing.bind(this); 43 | } 44 | _commitChanges() { 45 | const newText = this.state.text.trim(); 46 | if (this.props.onDelete && newText === '') { 47 | this.props.onDelete(); 48 | } else if (this.props.onCancel && newText === this.props.initialValue) { 49 | this.props.onCancel(); 50 | } else if (newText !== '') { 51 | this.props.onSave(newText); 52 | if (this._mounted !== false) { 53 | this.setState({ text: '' }); 54 | } 55 | } 56 | } 57 | _handleBlur() { 58 | if (this.props.commitOnBlur) { 59 | this._commitChanges(); 60 | } 61 | } 62 | _handleChangeText(text) { 63 | if (this._mounted !== false) { 64 | this.setState({ text }); 65 | } 66 | } 67 | _handleSubmitEditing() { 68 | this._commitChanges(); 69 | } 70 | componentWillUnmount() { 71 | this._mounted = false; 72 | } 73 | render() { 74 | return ( 75 | 86 | ); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /react-native-TodoMVC/data/database.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | export class Todo {} 14 | export class User {} 15 | 16 | // Mock authenticated ID 17 | const VIEWER_ID = 'me'; 18 | 19 | // Mock user data 20 | const viewer = new User(); 21 | viewer.id = VIEWER_ID; 22 | const usersById = { 23 | [VIEWER_ID]: viewer, 24 | }; 25 | 26 | // Mock todo data 27 | const todosById = {}; 28 | const todoIdsByUser = { 29 | [VIEWER_ID]: [], 30 | }; 31 | let nextTodoId = 0; 32 | addTodo('Taste JavaScript', true); 33 | addTodo('Buy a unicorn', false); 34 | 35 | export function addTodo(text, complete) { 36 | const todo = new Todo(); 37 | todo.complete = !!complete; 38 | todo.id = `${nextTodoId++}`; 39 | todo.text = text; 40 | todosById[todo.id] = todo; 41 | todoIdsByUser[VIEWER_ID].push(todo.id); 42 | return todo.id; 43 | } 44 | 45 | export function changeTodoStatus(id, complete) { 46 | const todo = getTodo(id); 47 | todo.complete = complete; 48 | } 49 | 50 | export function getTodo(id) { 51 | return todosById[id]; 52 | } 53 | 54 | export function getTodos(status = 'any') { 55 | const todos = todoIdsByUser[VIEWER_ID].map(id => todosById[id]); 56 | if (status === 'any') { 57 | return todos; 58 | } 59 | return todos.filter(todo => todo.complete === (status === 'completed')); 60 | } 61 | 62 | export function getUser(id) { 63 | return usersById[id]; 64 | } 65 | 66 | export function getViewer() { 67 | return getUser(VIEWER_ID); 68 | } 69 | 70 | export function markAllTodos(complete) { 71 | const changedTodos = []; 72 | getTodos().forEach(todo => { 73 | if (todo.complete !== complete) { 74 | todo.complete = complete; // eslint-disable-line no-param-reassign 75 | changedTodos.push(todo); 76 | } 77 | }); 78 | return changedTodos.map(todo => todo.id); 79 | } 80 | 81 | export function removeTodo(id) { 82 | const todoIndex = todoIdsByUser[VIEWER_ID].indexOf(id); 83 | if (todoIndex !== -1) { 84 | todoIdsByUser[VIEWER_ID].splice(todoIndex, 1); 85 | } 86 | delete todosById[id]; 87 | } 88 | 89 | export function removeCompletedTodos() { 90 | const todosToRemove = getTodos().filter(todo => todo.complete); 91 | todosToRemove.forEach(todo => removeTodo(todo.id)); 92 | return todosToRemove.map(todo => todo.id); 93 | } 94 | 95 | export function renameTodo(id, text) { 96 | const todo = getTodo(id); 97 | todo.text = text; 98 | } 99 | -------------------------------------------------------------------------------- /react-native-TodoMVC/data/schema.graphql: -------------------------------------------------------------------------------- 1 | input AddTodoInput { 2 | text: String! 3 | clientMutationId: String! 4 | } 5 | 6 | type AddTodoPayload { 7 | todoEdge: TodoEdge 8 | viewer: User 9 | clientMutationId: String! 10 | } 11 | 12 | input ChangeTodoStatusInput { 13 | complete: Boolean! 14 | id: ID! 15 | clientMutationId: String! 16 | } 17 | 18 | type ChangeTodoStatusPayload { 19 | todo: Todo 20 | viewer: User 21 | clientMutationId: String! 22 | } 23 | 24 | input MarkAllTodosInput { 25 | complete: Boolean! 26 | clientMutationId: String! 27 | } 28 | 29 | type MarkAllTodosPayload { 30 | changedTodos: [Todo] 31 | viewer: User 32 | clientMutationId: String! 33 | } 34 | 35 | type Mutation { 36 | addTodo(input: AddTodoInput!): AddTodoPayload 37 | changeTodoStatus(input: ChangeTodoStatusInput!): ChangeTodoStatusPayload 38 | markAllTodos(input: MarkAllTodosInput!): MarkAllTodosPayload 39 | removeCompletedTodos(input: RemoveCompletedTodosInput!): RemoveCompletedTodosPayload 40 | removeTodo(input: RemoveTodoInput!): RemoveTodoPayload 41 | renameTodo(input: RenameTodoInput!): RenameTodoPayload 42 | } 43 | 44 | interface Node { 45 | id: ID! 46 | } 47 | 48 | type PageInfo { 49 | hasNextPage: Boolean! 50 | hasPreviousPage: Boolean! 51 | startCursor: String 52 | endCursor: String 53 | } 54 | 55 | input RemoveCompletedTodosInput { 56 | clientMutationId: String! 57 | } 58 | 59 | type RemoveCompletedTodosPayload { 60 | deletedTodoIds: [String] 61 | viewer: User 62 | clientMutationId: String! 63 | } 64 | 65 | input RemoveTodoInput { 66 | id: ID! 67 | clientMutationId: String! 68 | } 69 | 70 | type RemoveTodoPayload { 71 | deletedTodoId: ID 72 | viewer: User 73 | clientMutationId: String! 74 | } 75 | 76 | input RenameTodoInput { 77 | id: ID! 78 | text: String! 79 | clientMutationId: String! 80 | } 81 | 82 | type RenameTodoPayload { 83 | todo: Todo 84 | clientMutationId: String! 85 | } 86 | 87 | type Root { 88 | viewer: User 89 | node(id: ID!): Node 90 | } 91 | 92 | type Todo implements Node { 93 | id: ID! 94 | text: String 95 | complete: Boolean 96 | } 97 | 98 | type TodoConnection { 99 | pageInfo: PageInfo! 100 | edges: [TodoEdge] 101 | } 102 | 103 | type TodoEdge { 104 | node: Todo 105 | cursor: String! 106 | } 107 | 108 | type User implements Node { 109 | id: ID! 110 | todos(status: String = "any", after: String, first: Int, before: String, last: Int): TodoConnection 111 | totalCount: Int 112 | completedCount: Int 113 | } 114 | -------------------------------------------------------------------------------- /react-native-TodoMVC/images/todo_checkbox-active.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chentsulin/koa-graphql-relay-example/3cba433d190f141d8398c76dc5a0860c8317d5a0/react-native-TodoMVC/images/todo_checkbox-active.png -------------------------------------------------------------------------------- /react-native-TodoMVC/images/todo_checkbox-active@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chentsulin/koa-graphql-relay-example/3cba433d190f141d8398c76dc5a0860c8317d5a0/react-native-TodoMVC/images/todo_checkbox-active@2x.png -------------------------------------------------------------------------------- /react-native-TodoMVC/images/todo_checkbox.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chentsulin/koa-graphql-relay-example/3cba433d190f141d8398c76dc5a0860c8317d5a0/react-native-TodoMVC/images/todo_checkbox.png -------------------------------------------------------------------------------- /react-native-TodoMVC/images/todo_checkbox@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chentsulin/koa-graphql-relay-example/3cba433d190f141d8398c76dc5a0860c8317d5a0/react-native-TodoMVC/images/todo_checkbox@2x.png -------------------------------------------------------------------------------- /react-native-TodoMVC/index.android.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import { 14 | AppRegistry, 15 | } from 'react-native'; 16 | import TodoMVC from './app'; 17 | 18 | AppRegistry.registerComponent('TodoMVC', () => TodoMVC); 19 | -------------------------------------------------------------------------------- /react-native-TodoMVC/index.ios.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import { 14 | AppRegistry, 15 | } from 'react-native'; 16 | import TodoMVC from './app'; 17 | 18 | console.ignoredYellowBox = [ 19 | // FIXME: https://github.com/facebook/react-native/issues/1501 20 | 'Warning: ScrollView doesn\'t take rejection well - scrolls anyway', 21 | ]; 22 | 23 | AppRegistry.registerComponent('TodoMVC', () => TodoMVC); 24 | -------------------------------------------------------------------------------- /react-native-TodoMVC/ios/TodoMVC.xcodeproj/xcshareddata/xcschemes/TodoMVC.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 38 | 39 | 44 | 45 | 47 | 53 | 54 | 55 | 56 | 57 | 63 | 64 | 65 | 66 | 75 | 77 | 83 | 84 | 85 | 86 | 87 | 88 | 94 | 96 | 102 | 103 | 104 | 105 | 107 | 108 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /react-native-TodoMVC/ios/TodoMVC/AppDelegate.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | */ 9 | 10 | #import 11 | 12 | @interface AppDelegate : UIResponder 13 | 14 | @property (nonatomic, strong) UIWindow *window; 15 | 16 | @end 17 | -------------------------------------------------------------------------------- /react-native-TodoMVC/ios/TodoMVC/AppDelegate.m: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | */ 9 | 10 | #import "AppDelegate.h" 11 | 12 | #import "RCTRootView.h" 13 | 14 | @implementation AppDelegate 15 | 16 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 17 | { 18 | NSURL *jsCodeLocation; 19 | 20 | /** 21 | * Loading JavaScript code - uncomment the one you want. 22 | * 23 | * OPTION 1 24 | * Load from development server. Start the server from the repository root: 25 | * 26 | * $ npm start 27 | * 28 | * To run on device, change `localhost` to the IP address of your computer 29 | * (you can get this by typing `ifconfig` into the terminal and selecting the 30 | * `inet` value under `en0:`) and make sure your computer and iOS device are 31 | * on the same Wi-Fi network. 32 | */ 33 | 34 | jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"]; 35 | 36 | /** 37 | * OPTION 2 38 | * Load from pre-bundled file on disk. The static bundle is automatically 39 | * generated by "Bundle React Native code and images" build step. 40 | */ 41 | 42 | // jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; 43 | 44 | RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation 45 | moduleName:@"TodoMVC" 46 | initialProperties:nil 47 | launchOptions:launchOptions]; 48 | 49 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; 50 | UIViewController *rootViewController = [UIViewController new]; 51 | rootViewController.view = rootView; 52 | self.window.rootViewController = rootViewController; 53 | [self.window makeKeyAndVisible]; 54 | return YES; 55 | } 56 | 57 | @end 58 | -------------------------------------------------------------------------------- /react-native-TodoMVC/ios/TodoMVC/Base.lproj/LaunchScreen.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 21 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /react-native-TodoMVC/ios/TodoMVC/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | } 33 | ], 34 | "info" : { 35 | "version" : 1, 36 | "author" : "xcode" 37 | } 38 | } -------------------------------------------------------------------------------- /react-native-TodoMVC/ios/TodoMVC/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | NSAppTransportSecurity 26 | 27 | NSAllowsArbitraryLoads 28 | 29 | 30 | NSLocationWhenInUseUsageDescription 31 | 32 | UILaunchStoryboardName 33 | LaunchScreen 34 | UIRequiredDeviceCapabilities 35 | 36 | armv7 37 | 38 | UISupportedInterfaceOrientations 39 | 40 | UIInterfaceOrientationPortrait 41 | UIInterfaceOrientationLandscapeLeft 42 | UIInterfaceOrientationLandscapeRight 43 | 44 | UIViewControllerBasedStatusBarAppearance 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /react-native-TodoMVC/ios/TodoMVC/main.m: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | */ 9 | 10 | #import 11 | 12 | #import "AppDelegate.h" 13 | 14 | int main(int argc, char * argv[]) { 15 | @autoreleasepool { 16 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /react-native-TodoMVC/ios/TodoMVCTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /react-native-TodoMVC/ios/TodoMVCTests/TodoMVCTests.m: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | */ 9 | 10 | #import 11 | #import 12 | 13 | #import "RCTLog.h" 14 | #import "RCTRootView.h" 15 | 16 | #define TIMEOUT_SECONDS 240 17 | #define TEXT_TO_LOOK_FOR @"Welcome to React Native!" 18 | 19 | @interface TodoMVCTests : XCTestCase 20 | 21 | @end 22 | 23 | @implementation TodoMVCTests 24 | 25 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test 26 | { 27 | if (test(view)) { 28 | return YES; 29 | } 30 | for (UIView *subview in [view subviews]) { 31 | if ([self findSubviewInView:subview matching:test]) { 32 | return YES; 33 | } 34 | } 35 | return NO; 36 | } 37 | 38 | - (void)testRendersWelcomeScreen 39 | { 40 | UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController]; 41 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; 42 | BOOL foundElement = NO; 43 | 44 | __block NSString *redboxError = nil; 45 | RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { 46 | if (level >= RCTLogLevelError) { 47 | redboxError = message; 48 | } 49 | }); 50 | 51 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { 52 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 53 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 54 | 55 | foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) { 56 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { 57 | return YES; 58 | } 59 | return NO; 60 | }]; 61 | } 62 | 63 | RCTSetLogFunction(RCTDefaultLogFunction); 64 | 65 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); 66 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); 67 | } 68 | 69 | 70 | @end 71 | -------------------------------------------------------------------------------- /react-native-TodoMVC/mutations/AddTodoMutation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import Relay from 'react-relay'; 14 | 15 | export default class AddTodoMutation extends Relay.Mutation { 16 | static fragments = { 17 | viewer: () => Relay.QL` 18 | fragment on User { 19 | id, 20 | totalCount, 21 | } 22 | `, 23 | }; 24 | getMutation() { 25 | return Relay.QL`mutation{addTodo}`; 26 | } 27 | getFatQuery() { 28 | return Relay.QL` 29 | fragment on AddTodoPayload { 30 | todoEdge, 31 | viewer { 32 | todos, 33 | totalCount, 34 | }, 35 | } 36 | `; 37 | } 38 | getConfigs() { 39 | return [{ 40 | type: 'RANGE_ADD', 41 | parentName: 'viewer', 42 | parentID: this.props.viewer.id, 43 | connectionName: 'todos', 44 | edgeName: 'todoEdge', 45 | rangeBehaviors: { 46 | '': 'append', 47 | 'status(any)': 'append', 48 | 'status(active)': 'append', 49 | 'status(completed)': 'ignore', 50 | }, 51 | }]; 52 | } 53 | getVariables() { 54 | return { 55 | text: this.props.text, 56 | }; 57 | } 58 | getOptimisticResponse() { 59 | return { 60 | // FIXME: totalCount gets updated optimistically, but this edge does not 61 | // get added until the server responds 62 | todoEdge: { 63 | node: { 64 | complete: false, 65 | text: this.props.text, 66 | }, 67 | }, 68 | viewer: { 69 | id: this.props.viewer.id, 70 | totalCount: this.props.viewer.totalCount + 1, 71 | }, 72 | }; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /react-native-TodoMVC/mutations/ChangeTodoStatusMutation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import Relay from 'react-relay'; 14 | 15 | export default class ChangeTodoStatusMutation extends Relay.Mutation { 16 | static fragments = { 17 | todo: () => Relay.QL` 18 | fragment on Todo { 19 | id, 20 | } 21 | `, 22 | // TODO: Mark completedCount optional 23 | viewer: () => Relay.QL` 24 | fragment on User { 25 | id, 26 | completedCount, 27 | } 28 | `, 29 | }; 30 | getMutation() { 31 | return Relay.QL`mutation{changeTodoStatus}`; 32 | } 33 | getFatQuery() { 34 | return Relay.QL` 35 | fragment on ChangeTodoStatusPayload { 36 | todo { 37 | complete, 38 | }, 39 | viewer { 40 | completedCount, 41 | todos, 42 | }, 43 | } 44 | `; 45 | } 46 | getConfigs() { 47 | return [{ 48 | type: 'FIELDS_CHANGE', 49 | fieldIDs: { 50 | todo: this.props.todo.id, 51 | viewer: this.props.viewer.id, 52 | }, 53 | }]; 54 | } 55 | getVariables() { 56 | return { 57 | complete: this.props.complete, 58 | id: this.props.todo.id, 59 | }; 60 | } 61 | getOptimisticResponse() { 62 | const viewerPayload = { id: this.props.viewer.id }; 63 | if (this.props.viewer.completedCount != null) { 64 | viewerPayload.completedCount = this.props.complete ? 65 | this.props.viewer.completedCount + 1 : 66 | this.props.viewer.completedCount - 1; 67 | } 68 | return { 69 | todo: { 70 | complete: this.props.complete, 71 | id: this.props.todo.id, 72 | }, 73 | viewer: viewerPayload, 74 | }; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /react-native-TodoMVC/mutations/MarkAllTodosMutation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import Relay from 'react-relay'; 14 | 15 | export default class MarkAllTodosMutation extends Relay.Mutation { 16 | static fragments = { 17 | // TODO: Mark edges and totalCount optional 18 | todos: () => Relay.QL` 19 | fragment on TodoConnection { 20 | edges { 21 | node { 22 | complete, 23 | id, 24 | }, 25 | }, 26 | } 27 | `, 28 | viewer: () => Relay.QL` 29 | fragment on User { 30 | id, 31 | totalCount, 32 | } 33 | `, 34 | }; 35 | getMutation() { 36 | return Relay.QL`mutation{markAllTodos}`; 37 | } 38 | getFatQuery() { 39 | return Relay.QL` 40 | fragment on MarkAllTodosPayload { 41 | viewer { 42 | completedCount, 43 | todos, 44 | }, 45 | } 46 | `; 47 | } 48 | getConfigs() { 49 | return [{ 50 | type: 'FIELDS_CHANGE', 51 | fieldIDs: { 52 | viewer: this.props.viewer.id, 53 | }, 54 | }]; 55 | } 56 | getVariables() { 57 | return { 58 | complete: this.props.complete, 59 | }; 60 | } 61 | getOptimisticResponse() { 62 | const viewerPayload = { id: this.props.viewer.id }; 63 | if (this.props.todos && this.props.todos.edges) { 64 | viewerPayload.todos = { 65 | edges: this.props.todos.edges 66 | .filter(edge => edge.node.complete !== this.props.complete) 67 | .map(edge => ({ 68 | node: { 69 | complete: this.props.complete, 70 | id: edge.node.id, 71 | }, 72 | })), 73 | }; 74 | } 75 | if (this.props.viewer.totalCount != null) { 76 | viewerPayload.completedCount = this.props.complete ? 77 | this.props.viewer.totalCount : 78 | 0; 79 | } 80 | return { 81 | viewer: viewerPayload, 82 | }; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /react-native-TodoMVC/mutations/RemoveCompletedTodosMutation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import Relay from 'react-relay'; 14 | 15 | export default class RemoveCompletedTodosMutation extends Relay.Mutation { 16 | static fragments = { 17 | // TODO: Make completedCount, edges, and totalCount optional 18 | todos: () => Relay.QL` 19 | fragment on TodoConnection { 20 | edges { 21 | node { 22 | complete, 23 | id, 24 | }, 25 | }, 26 | } 27 | `, 28 | viewer: () => Relay.QL` 29 | fragment on User { 30 | completedCount, 31 | id, 32 | totalCount, 33 | } 34 | `, 35 | }; 36 | getMutation() { 37 | return Relay.QL`mutation{removeCompletedTodos}`; 38 | } 39 | getFatQuery() { 40 | return Relay.QL` 41 | fragment on RemoveCompletedTodosPayload { 42 | deletedTodoIds, 43 | viewer { 44 | completedCount, 45 | totalCount, 46 | }, 47 | } 48 | `; 49 | } 50 | getConfigs() { 51 | return [{ 52 | type: 'NODE_DELETE', 53 | parentName: 'viewer', 54 | parentID: this.props.viewer.id, 55 | connectionName: 'todos', 56 | deletedIDFieldName: 'deletedTodoIds', 57 | }]; 58 | } 59 | getVariables() { 60 | return {}; 61 | } 62 | getOptimisticResponse() { 63 | let deletedTodoIds; 64 | let newTotalCount; 65 | if (this.props.todos && this.props.todos.edges) { 66 | deletedTodoIds = this.props.todos.edges 67 | .filter(edge => edge.node.complete) 68 | .map(edge => edge.node.id); 69 | } 70 | const { completedCount, totalCount } = this.props.viewer; 71 | if (completedCount != null && totalCount != null) { 72 | newTotalCount = totalCount - completedCount; 73 | } 74 | return { 75 | deletedTodoIds, 76 | viewer: { 77 | completedCount: 0, 78 | id: this.props.viewer.id, 79 | totalCount: newTotalCount, 80 | }, 81 | }; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /react-native-TodoMVC/mutations/RemoveTodoMutation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import Relay from 'react-relay'; 14 | 15 | export default class RemoveTodoMutation extends Relay.Mutation { 16 | static fragments = { 17 | // TODO: Mark complete as optional 18 | todo: () => Relay.QL` 19 | fragment on Todo { 20 | complete, 21 | id, 22 | } 23 | `, 24 | // TODO: Mark completedCount and totalCount as optional 25 | viewer: () => Relay.QL` 26 | fragment on User { 27 | completedCount, 28 | id, 29 | totalCount, 30 | } 31 | `, 32 | }; 33 | getMutation() { 34 | return Relay.QL`mutation{removeTodo}`; 35 | } 36 | getFatQuery() { 37 | return Relay.QL` 38 | fragment on RemoveTodoPayload { 39 | deletedTodoId, 40 | viewer { 41 | completedCount, 42 | totalCount, 43 | }, 44 | } 45 | `; 46 | } 47 | getConfigs() { 48 | return [{ 49 | type: 'NODE_DELETE', 50 | parentName: 'viewer', 51 | parentID: this.props.viewer.id, 52 | connectionName: 'todos', 53 | deletedIDFieldName: 'deletedTodoId', 54 | }]; 55 | } 56 | getVariables() { 57 | return { 58 | id: this.props.todo.id, 59 | }; 60 | } 61 | getOptimisticResponse() { 62 | const viewerPayload = { id: this.props.viewer.id }; 63 | if (this.props.viewer.completedCount != null) { 64 | viewerPayload.completedCount = this.props.todo.complete === true ? 65 | this.props.viewer.completedCount - 1 : 66 | this.props.viewer.completedCount; 67 | } 68 | if (this.props.viewer.totalCount != null) { 69 | viewerPayload.totalCount = this.props.viewer.totalCount - 1; 70 | } 71 | return { 72 | deletedTodoId: this.props.todo.id, 73 | viewer: viewerPayload, 74 | }; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /react-native-TodoMVC/mutations/RenameTodoMutation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import Relay from 'react-relay'; 14 | 15 | export default class RenameTodoMutation extends Relay.Mutation { 16 | static fragments = { 17 | todo: () => Relay.QL` 18 | fragment on Todo { 19 | id, 20 | } 21 | `, 22 | }; 23 | getMutation() { 24 | return Relay.QL`mutation{renameTodo}`; 25 | } 26 | getFatQuery() { 27 | return Relay.QL` 28 | fragment on RenameTodoPayload { 29 | todo { 30 | text, 31 | } 32 | } 33 | `; 34 | } 35 | getConfigs() { 36 | return [{ 37 | type: 'FIELDS_CHANGE', 38 | fieldIDs: { 39 | todo: this.props.todo.id, 40 | }, 41 | }]; 42 | } 43 | getVariables() { 44 | return { 45 | id: this.props.todo.id, 46 | text: this.props.text, 47 | }; 48 | } 49 | getOptimisticResponse() { 50 | return { 51 | todo: { 52 | id: this.props.todo.id, 53 | text: this.props.text, 54 | }, 55 | }; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /react-native-TodoMVC/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "TodoMVC", 3 | "version": "0.0.1", 4 | "private": true, 5 | "scripts": { 6 | "start": "BABEL_ENV=server babel-node ./server.js", 7 | "update-schema": "babel-node ./scripts/updateSchema.js", 8 | "lint": "./node_modules/.bin/eslint ." 9 | }, 10 | "dependencies": { 11 | "babel-preset-es2015": "^6.5.0", 12 | "babel-preset-react-native": "^1.5.1", 13 | "babel-preset-stage-0": "^6.5.0", 14 | "babel-relay-plugin": "^0.9.0", 15 | "graphql": "^0.4.17", 16 | "graphql-relay": "^0.3.6", 17 | "koa": "^1.1.2", 18 | "koa-graphql": "^0.4.4", 19 | "koa-mount": "^1.3.0", 20 | "react": "^0.14.5", 21 | "react-native": "^0.22.0", 22 | "react-native-listitem": "^1.0.5", 23 | "react-native-swipeout": "^2.0.12", 24 | "react-relay": "^0.9.0" 25 | }, 26 | "devDependencies": { 27 | "babel-cli": "^6.6.4", 28 | "babel-eslint": "^6.0.3", 29 | "eslint": "^2.8.0", 30 | "eslint-config-airbnb": "^7.0.0", 31 | "eslint-plugin-jsx-a11y": "^0.6.2", 32 | "eslint-plugin-react": "^4.3.0" 33 | }, 34 | "engines": { 35 | "npm": ">=3" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /react-native-TodoMVC/plugins/babelRelayPlugin.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | const getBabelRelayPlugin = require('babel-relay-plugin'); 14 | const schema = require('../data/schema.json'); 15 | 16 | module.exports = getBabelRelayPlugin(schema.data); 17 | -------------------------------------------------------------------------------- /react-native-TodoMVC/routes/TodoAppRoute.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import Relay, { 14 | Route, 15 | } from 'react-relay'; 16 | 17 | export default class TodoAppRoute extends Route { 18 | static paramDefinitions = { 19 | status: { required: false }, 20 | }; 21 | static queries = { 22 | viewer: () => Relay.QL`query { viewer }`, 23 | }; 24 | static routeName = 'TodoAppRoute'; 25 | } 26 | -------------------------------------------------------------------------------- /react-native-TodoMVC/scripts/updateSchema.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env babel-node --optional es7.asyncFunctions 2 | /** 3 | * This file provided by Facebook is for non-commercial testing and evaluation 4 | * purposes only. Facebook reserves all rights not expressly granted. 5 | * 6 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 7 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 8 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 9 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 10 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 11 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 12 | */ 13 | 14 | import fs from 'fs'; 15 | import path from 'path'; 16 | import { schema } from '../data/schema'; 17 | import { graphql } from 'graphql'; 18 | import { introspectionQuery, printSchema } from 'graphql/utilities'; 19 | 20 | // Save JSON of full schema introspection for Babel Relay Plugin to use 21 | (async () => { 22 | const result = await (graphql(schema, introspectionQuery)); 23 | if (result.errors) { 24 | console.error( 25 | 'ERROR introspecting schema: ', 26 | JSON.stringify(result.errors, null, 2) 27 | ); 28 | } else { 29 | fs.writeFileSync( 30 | path.join(__dirname, '../data/schema.json'), 31 | JSON.stringify(result, null, 2) 32 | ); 33 | } 34 | })(); 35 | 36 | // Save user readable type system shorthand of schema 37 | fs.writeFileSync( 38 | path.join(__dirname, '../data/schema.graphql'), 39 | printSchema(schema) 40 | ); 41 | -------------------------------------------------------------------------------- /react-native-TodoMVC/server.js: -------------------------------------------------------------------------------- 1 | import koa from 'koa'; 2 | import graphQLHTTP from 'koa-graphql'; 3 | import mount from 'koa-mount'; 4 | import { schema } from './data/schema'; 5 | 6 | const GRAPHQL_PORT = 8080; 7 | 8 | // Expose a GraphQL endpoint 9 | const graphQLServer = koa(); 10 | 11 | graphQLServer.use(mount('/', graphQLHTTP({ schema, pretty: true }))); 12 | 13 | graphQLServer.listen(GRAPHQL_PORT, () => console.log( 14 | `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}` 15 | )); 16 | -------------------------------------------------------------------------------- /relay-treasurehunt/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "passPerPreset": true, 3 | "presets": [ 4 | { 5 | "plugins": [ 6 | "./build/babelRelayPlugin" 7 | ] 8 | }, 9 | "react", 10 | "es2015", 11 | "stage-0" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /relay-treasurehunt/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb", 3 | "parser": "babel-eslint", 4 | "env": { 5 | "browser": true, 6 | "node": true 7 | }, 8 | "rules": { 9 | "eqeqeq": 0, 10 | "no-console": 0, 11 | "no-use-before-define": 0, 12 | "no-else-return": 0, 13 | "react/prop-types": 0, 14 | "react/jsx-closing-bracket-location": 0, 15 | "react/jsx-no-bind": 0 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /relay-treasurehunt/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | npm-debug.log 4 | data/schema.graphql 5 | -------------------------------------------------------------------------------- /relay-treasurehunt/README.md: -------------------------------------------------------------------------------- 1 | # Relay Treasure Hunt 2 | 3 | ## Installation 4 | 5 | ``` 6 | npm install 7 | ``` 8 | 9 | ## Running 10 | 11 | Start a local server: 12 | 13 | ``` 14 | npm start 15 | ``` 16 | 17 | ## Developing 18 | 19 | Any changes you make to files in the `js/` directory will cause the server to 20 | automatically rebuild the app and refresh your browser. 21 | 22 | If at any time you make changes to `data/schema.js`, stop the server, 23 | regenerate `data/schema.json`, and restart the server: 24 | 25 | ``` 26 | npm run update-schema 27 | npm start 28 | ``` 29 | 30 | ## License 31 | 32 | This file provided by Facebook is for non-commercial testing and evaluation 33 | purposes only. Facebook reserves all rights not expressly granted. 34 | 35 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 36 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 37 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 38 | FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 39 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 40 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 41 | -------------------------------------------------------------------------------- /relay-treasurehunt/build/babelRelayPlugin.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | const getBabelRelayPlugin = require('babel-relay-plugin'); 14 | const schema = require('../data/schema.json'); 15 | 16 | module.exports = getBabelRelayPlugin(schema.data); 17 | -------------------------------------------------------------------------------- /relay-treasurehunt/data/database.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | // Model types 14 | export class Game {} 15 | export class HidingSpot {} 16 | 17 | // Mock data 18 | const game = new Game(); 19 | game.id = '1'; 20 | 21 | const hidingSpots = []; 22 | (function () { // eslint-disable-line 23 | let hidingSpot; 24 | const indexOfSpotWithTreasure = Math.floor(Math.random() * 9); 25 | for (let i = 0; i < 9; i++) { 26 | hidingSpot = new HidingSpot(); 27 | hidingSpot.id = `${i}`; 28 | hidingSpot.hasTreasure = (i === indexOfSpotWithTreasure); 29 | hidingSpot.hasBeenChecked = false; 30 | hidingSpots.push(hidingSpot); 31 | } 32 | })(); 33 | 34 | let turnsRemaining = 3; 35 | 36 | export function checkHidingSpotForTreasure(id) { 37 | if (hidingSpots.some(hs => hs.hasTreasure && hs.hasBeenChecked)) { 38 | return; 39 | } 40 | turnsRemaining--; 41 | const hidingSpot = getHidingSpot(id); 42 | hidingSpot.hasBeenChecked = true; 43 | } 44 | export function getHidingSpot(id) { 45 | return hidingSpots.find(hs => hs.id === id); 46 | } 47 | export function getGame() { return game; } 48 | export function getHidingSpots() { return hidingSpots; } 49 | export function getTurnsRemaining() { return turnsRemaining; } 50 | -------------------------------------------------------------------------------- /relay-treasurehunt/js/app.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import 'babel-polyfill'; 14 | import App from './components/App'; 15 | import AppHomeRoute from './routes/AppHomeRoute'; 16 | import React from 'react'; 17 | import ReactDOM from 'react-dom'; 18 | import Relay from 'react-relay'; 19 | 20 | ReactDOM.render( 21 | , 25 | document.getElementById('root') 26 | ); 27 | -------------------------------------------------------------------------------- /relay-treasurehunt/js/components/App.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import CheckHidingSpotForTreasureMutation from '../mutations/CheckHidingSpotForTreasureMutation'; 14 | import React from 'react'; 15 | import Relay from 'react-relay'; 16 | 17 | class App extends React.Component { 18 | _getHidingSpotStyle(hidingSpot) { 19 | let color; 20 | if (this.props.relay.hasOptimisticUpdate(hidingSpot)) { 21 | color = 'lightGrey'; 22 | } else if (hidingSpot.hasBeenChecked) { 23 | if (hidingSpot.hasTreasure) { 24 | color = 'blue'; 25 | } else { 26 | color = 'red'; 27 | } 28 | } else { 29 | color = 'black'; 30 | } 31 | return { 32 | backgroundColor: color, 33 | cursor: this._isGameOver() ? null : 'pointer', 34 | display: 'inline-block', 35 | height: 100, 36 | marginRight: 10, 37 | width: 100, 38 | }; 39 | } 40 | _handleHidingSpotClick(hidingSpot) { 41 | if (this._isGameOver()) { 42 | return; 43 | } 44 | this.props.relay.commitUpdate( 45 | new CheckHidingSpotForTreasureMutation({ 46 | game: this.props.game, 47 | hidingSpot, 48 | }) 49 | ); 50 | } 51 | _hasFoundTreasure() { 52 | return ( 53 | this.props.game.hidingSpots.edges.some(edge => edge.node.hasTreasure) 54 | ); 55 | } 56 | _isGameOver() { 57 | return !this.props.game.turnsRemaining || this._hasFoundTreasure(); 58 | } 59 | renderGameBoard() { 60 | return this.props.game.hidingSpots.edges.map(edge => 61 |
    66 | ); 67 | } 68 | render() { 69 | let headerText; 70 | if (this.props.relay.getPendingTransactions(this.props.game)) { 71 | headerText = '\u2026'; 72 | } else if (this._hasFoundTreasure()) { 73 | headerText = 'You win!'; 74 | } else if (this._isGameOver()) { 75 | headerText = 'Game over!'; 76 | } else { 77 | headerText = 'Find the treasure!'; 78 | } 79 | return ( 80 |
    81 |

    {headerText}

    82 | {this.renderGameBoard()} 83 |

    Turns remaining: {this.props.game.turnsRemaining}

    84 |
    85 | ); 86 | } 87 | } 88 | 89 | export default Relay.createContainer(App, { 90 | fragments: { 91 | game: () => Relay.QL` 92 | fragment on Game { 93 | turnsRemaining, 94 | hidingSpots(first: 9) { 95 | edges { 96 | node { 97 | hasBeenChecked, 98 | hasTreasure, 99 | id, 100 | ${CheckHidingSpotForTreasureMutation.getFragment('hidingSpot')}, 101 | } 102 | } 103 | }, 104 | ${CheckHidingSpotForTreasureMutation.getFragment('game')}, 105 | } 106 | `, 107 | }, 108 | }); 109 | -------------------------------------------------------------------------------- /relay-treasurehunt/js/mutations/CheckHidingSpotForTreasureMutation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import Relay from 'react-relay'; 14 | 15 | export default class CheckHidingSpotForTreasureMutation extends Relay.Mutation { 16 | static fragments = { 17 | game: () => Relay.QL` 18 | fragment on Game { 19 | id, 20 | turnsRemaining, 21 | } 22 | `, 23 | hidingSpot: () => Relay.QL` 24 | fragment on HidingSpot { 25 | id, 26 | } 27 | `, 28 | }; 29 | getMutation() { 30 | return Relay.QL`mutation{checkHidingSpotForTreasure}`; 31 | } 32 | getCollisionKey() { 33 | return `check_${this.props.game.id}`; 34 | } 35 | getFatQuery() { 36 | return Relay.QL` 37 | fragment on CheckHidingSpotForTreasurePayload @relay(pattern: true) { 38 | hidingSpot { 39 | hasBeenChecked, 40 | hasTreasure, 41 | }, 42 | game { 43 | turnsRemaining, 44 | }, 45 | } 46 | `; 47 | } 48 | getConfigs() { 49 | return [{ 50 | type: 'FIELDS_CHANGE', 51 | fieldIDs: { 52 | hidingSpot: this.props.hidingSpot.id, 53 | game: this.props.game.id, 54 | }, 55 | }]; 56 | } 57 | getVariables() { 58 | return { 59 | id: this.props.hidingSpot.id, 60 | }; 61 | } 62 | getOptimisticResponse() { 63 | return { 64 | game: { 65 | turnsRemaining: this.props.game.turnsRemaining - 1, 66 | }, 67 | hidingSpot: { 68 | id: this.props.hidingSpot.id, 69 | hasBeenChecked: true, 70 | }, 71 | }; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /relay-treasurehunt/js/routes/AppHomeRoute.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import Relay from 'react-relay'; 14 | 15 | export default class extends Relay.Route { 16 | static queries = { 17 | game: () => Relay.QL`query { game }`, 18 | }; 19 | static routeName = 'AppHomeRoute'; 20 | } 21 | -------------------------------------------------------------------------------- /relay-treasurehunt/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "start": "babel-node ./server.js", 5 | "update-schema": "babel-node ./scripts/updateSchema.js", 6 | "lint": "./node_modules/.bin/eslint ." 7 | }, 8 | "dependencies": { 9 | "babel-core": "^6.5.2", 10 | "babel-loader": "^6.2.2", 11 | "babel-polyfill": "^6.5.0", 12 | "babel-preset-es2015": "^6.5.0", 13 | "babel-preset-react": "^6.5.0", 14 | "babel-preset-stage-0": "^6.5.0", 15 | "babel-relay-plugin": "^0.9.0", 16 | "classnames": "^2.2.3", 17 | "express": "^4.13.4", 18 | "graphql": "^0.4.17", 19 | "graphql-relay": "^0.3.6", 20 | "history": "^1.17.0", 21 | "koa": "^1.1.2", 22 | "koa-graphql": "^0.4.4", 23 | "koa-mount": "^1.3.0", 24 | "react": "^0.14.7", 25 | "react-dom": "^0.14.7", 26 | "react-relay": "^0.9.0", 27 | "webpack": "^1.12.13", 28 | "webpack-dev-server": "^1.14.1" 29 | }, 30 | "devDependencies": { 31 | "babel-cli": "^6.5.1", 32 | "babel-eslint": "^6.0.3", 33 | "eslint": "^2.8.0", 34 | "eslint-config-airbnb": "^7.0.0", 35 | "eslint-plugin-jsx-a11y": "^0.6.2", 36 | "eslint-plugin-react": "^4.3.0" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /relay-treasurehunt/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Relay • Treasure Hunt 7 | 8 | 9 |
    10 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /relay-treasurehunt/scripts/updateSchema.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env babel-node --optional es7.asyncFunctions 2 | /** 3 | * This file provided by Facebook is for non-commercial testing and evaluation 4 | * purposes only. Facebook reserves all rights not expressly granted. 5 | * 6 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 7 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 8 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 9 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 10 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 11 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 12 | */ 13 | 14 | import fs from 'fs'; 15 | import path from 'path'; 16 | import { schema } from '../data/schema'; 17 | import { graphql } from 'graphql'; 18 | import { introspectionQuery, printSchema } from 'graphql/utilities'; 19 | 20 | // Save JSON of full schema introspection for Babel Relay Plugin to use 21 | (async () => { 22 | const result = await (graphql(schema, introspectionQuery)); 23 | if (result.errors) { 24 | console.error( 25 | 'ERROR introspecting schema: ', 26 | JSON.stringify(result.errors, null, 2) 27 | ); 28 | } else { 29 | fs.writeFileSync( 30 | path.join(__dirname, '../data/schema.json'), 31 | JSON.stringify(result, null, 2) 32 | ); 33 | } 34 | })(); 35 | 36 | // Save user readable type system shorthand of schema 37 | fs.writeFileSync( 38 | path.join(__dirname, '../data/schema.graphql'), 39 | printSchema(schema) 40 | ); 41 | -------------------------------------------------------------------------------- /relay-treasurehunt/server.js: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import koa from 'koa'; 3 | import graphQLHTTP from 'koa-graphql'; 4 | import mount from 'koa-mount'; 5 | import path from 'path'; 6 | import webpack from 'webpack'; 7 | import WebpackDevServer from 'webpack-dev-server'; 8 | import { schema } from './data/schema'; 9 | 10 | const APP_PORT = 3000; 11 | const GRAPHQL_PORT = 8080; 12 | 13 | // Expose a GraphQL endpoint 14 | const graphQLServer = koa(); 15 | 16 | graphQLServer.use(mount('/', graphQLHTTP({ schema, pretty: true }))); 17 | 18 | graphQLServer.listen(GRAPHQL_PORT, () => console.log( 19 | `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}` 20 | )); 21 | 22 | // Serve the Relay app 23 | const compiler = webpack({ 24 | entry: path.resolve(__dirname, 'js', 'app.js'), 25 | module: { 26 | loaders: [ 27 | { 28 | exclude: /node_modules/, 29 | loader: 'babel', 30 | test: /\.js$/, 31 | }, 32 | ], 33 | }, 34 | output: { filename: 'app.js', path: '/' }, 35 | }); 36 | 37 | const app = new WebpackDevServer(compiler, { 38 | contentBase: '/public/', 39 | proxy: { '/graphql': `http://localhost:${GRAPHQL_PORT}` }, 40 | publicPath: '/js/', 41 | stats: { colors: true }, 42 | }); 43 | 44 | // Serve static resources 45 | app.use('/', express.static(path.resolve(__dirname, 'public'))); 46 | 47 | app.listen(APP_PORT, () => { 48 | console.log(`App is now running on http://localhost:${APP_PORT}`); 49 | }); 50 | -------------------------------------------------------------------------------- /star-wars/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "passPerPreset": true, 3 | "presets": [ 4 | { 5 | "plugins": [ 6 | "./build/babelRelayPlugin" 7 | ] 8 | }, 9 | "react", 10 | "es2015", 11 | "stage-0" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /star-wars/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb", 3 | "parser": "babel-eslint", 4 | "env": { 5 | "browser": true, 6 | "node": true 7 | }, 8 | "rules": { 9 | "eqeqeq": 0, 10 | "no-console": 0, 11 | "no-use-before-define": 0, 12 | "no-else-return": 0, 13 | "react/prop-types": 0, 14 | "react/jsx-closing-bracket-location": 0, 15 | "react/jsx-no-bind": 0, 16 | "react/prefer-stateless-function": 0 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /star-wars/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | npm-debug.log 4 | data/schema.graphql 5 | -------------------------------------------------------------------------------- /star-wars/README.md: -------------------------------------------------------------------------------- 1 | # Relay Star Wars 2 | 3 | ## Installation 4 | 5 | ``` 6 | npm install 7 | ``` 8 | 9 | ## Running 10 | 11 | Start a local server: 12 | 13 | ``` 14 | npm start 15 | ``` 16 | 17 | ## Developing 18 | 19 | Any changes you make to files in the `js/` directory will cause the server to 20 | automatically rebuild the app and refresh your browser. 21 | 22 | If at any time you make changes to `data/schema.js`, stop the server, 23 | regenerate `data/schema.json`, and restart the server: 24 | 25 | ``` 26 | npm run update-schema 27 | npm start 28 | ``` 29 | 30 | ## License 31 | 32 | This file provided by Facebook is for non-commercial testing and evaluation 33 | purposes only. Facebook reserves all rights not expressly granted. 34 | 35 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 36 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 37 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 38 | FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 39 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 40 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 41 | -------------------------------------------------------------------------------- /star-wars/build/babelRelayPlugin.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | const getBabelRelayPlugin = require('babel-relay-plugin'); 14 | const schema = require('../data/schema.json'); 15 | 16 | module.exports = getBabelRelayPlugin(schema.data); 17 | -------------------------------------------------------------------------------- /star-wars/data/database.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | /** 14 | * This defines a basic set of data for our Star Wars Schema. 15 | * 16 | * This data is hard coded for the sake of the demo, but you could imagine 17 | * fetching this data from a backend service rather than from hardcoded 18 | * JSON objects in a more complex demo. 19 | */ 20 | 21 | const xwing = { 22 | id: '1', 23 | name: 'X-Wing', 24 | }; 25 | 26 | const ywing = { 27 | id: '2', 28 | name: 'Y-Wing', 29 | }; 30 | 31 | const awing = { 32 | id: '3', 33 | name: 'A-Wing', 34 | }; 35 | 36 | // Yeah, technically it's Corellian. But it flew in the service of the rebels, 37 | // so for the purposes of this demo it's a rebel ship. 38 | const falcon = { 39 | id: '4', 40 | name: 'Millenium Falcon', 41 | }; 42 | 43 | const homeOne = { 44 | id: '5', 45 | name: 'Home One', 46 | }; 47 | 48 | const tieFighter = { 49 | id: '6', 50 | name: 'TIE Fighter', 51 | }; 52 | 53 | const tieInterceptor = { 54 | id: '7', 55 | name: 'TIE Interceptor', 56 | }; 57 | 58 | const executor = { 59 | id: '8', 60 | name: 'Executor', 61 | }; 62 | 63 | const rebels = { 64 | id: '1', 65 | name: 'Alliance to Restore the Republic', 66 | ships: ['1', '2', '3', '4', '5'], 67 | }; 68 | 69 | const empire = { 70 | id: '2', 71 | name: 'Galactic Empire', 72 | ships: ['6', '7', '8'], 73 | }; 74 | 75 | const data = { 76 | Faction: { 77 | 1: rebels, 78 | 2: empire, 79 | }, 80 | Ship: { 81 | 1: xwing, 82 | 2: ywing, 83 | 3: awing, 84 | 4: falcon, 85 | 5: homeOne, 86 | 6: tieFighter, 87 | 7: tieInterceptor, 88 | 8: executor, 89 | }, 90 | }; 91 | 92 | let nextShip = 9; 93 | export function createShip(shipName, factionId) { 94 | const newShip = { 95 | id: `${nextShip++}`, 96 | name: shipName, 97 | }; 98 | data.Ship[newShip.id] = newShip; 99 | data.Faction[factionId].ships.push(newShip.id); 100 | return newShip; 101 | } 102 | 103 | export function getShip(id) { 104 | return data.Ship[id]; 105 | } 106 | 107 | export function getShips(id) { 108 | return data.Faction[id].ships.map(shipId => data.Ship[shipId]); 109 | } 110 | 111 | export function getFaction(id) { 112 | return data.Faction[id]; 113 | } 114 | 115 | export function getFactions(names) { 116 | return names.map(name => { 117 | if (name === 'empire') { 118 | return empire; 119 | } 120 | if (name === 'rebels') { 121 | return rebels; 122 | } 123 | return null; 124 | }); 125 | } 126 | -------------------------------------------------------------------------------- /star-wars/js/app.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import 'babel-polyfill'; 14 | import React from 'react'; 15 | import ReactDOM from 'react-dom'; 16 | import Relay from 'react-relay'; 17 | import StarWarsApp from './components/StarWarsApp'; 18 | import StarWarsAppHomeRoute from './routes/StarWarsAppHomeRoute'; 19 | 20 | ReactDOM.render( 21 | , 27 | document.getElementById('root') 28 | ); 29 | -------------------------------------------------------------------------------- /star-wars/js/components/StarWarsApp.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import React from 'react'; 14 | import Relay from 'react-relay'; 15 | import StarWarsShip from './StarWarsShip'; 16 | import AddShipMutation from '../mutation/AddShipMutation'; 17 | 18 | class StarWarsApp extends React.Component { 19 | constructor() { 20 | super(); 21 | this.state = { 22 | factionId: 1, 23 | shipName: '', 24 | }; 25 | } 26 | 27 | handleAddShip() { 28 | const name = this.state.shipName; 29 | this.props.relay.commitUpdate( 30 | new AddShipMutation({ 31 | name, 32 | faction: this.props.factions[this.state.factionId], 33 | }) 34 | ); 35 | this.setState({ shipName: '' }); 36 | } 37 | 38 | handleInputChange(e) { 39 | this.setState({ 40 | shipName: e.target.value, 41 | }); 42 | } 43 | 44 | handleSelectionChange(e) { 45 | this.setState({ 46 | factionId: e.target.value, 47 | }); 48 | } 49 | 50 | render() { 51 | const { factions } = this.props; 52 | return ( 53 |
    54 |
      55 | {factions.map(faction => ( 56 |
    1. 57 |

      {faction.name}

      58 |
        59 | {faction.ships.edges.map(({ node }) => ( 60 |
      1. 61 | ))} 62 |
      63 |
    2. 64 | ))} 65 |
    3. 66 |

      Introduce Ship

      67 |
        68 |
      1. 69 | Name: 70 | 75 |
      2. 76 |
      3. 77 | Faction: 78 | 84 |
      4. 85 |
      5. 86 | 87 |
      6. 88 |
      89 |
    4. 90 |
    91 |
    92 | ); 93 | } 94 | } 95 | 96 | export default Relay.createContainer(StarWarsApp, { 97 | fragments: { 98 | factions: () => Relay.QL` 99 | fragment on Faction @relay(plural: true) { 100 | id, 101 | factionId, 102 | name, 103 | ships(first: 10) { 104 | edges { 105 | node { 106 | id 107 | ${StarWarsShip.getFragment('ship')} 108 | } 109 | } 110 | } 111 | ${AddShipMutation.getFragment('faction')}, 112 | } 113 | `, 114 | }, 115 | }); 116 | -------------------------------------------------------------------------------- /star-wars/js/components/StarWarsShip.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import React from 'react'; 14 | import Relay from 'react-relay'; 15 | 16 | class StarWarsShip extends React.Component { 17 | render() { 18 | const { ship } = this.props; 19 | return
    {ship.name}
    ; 20 | } 21 | } 22 | 23 | export default Relay.createContainer(StarWarsShip, { 24 | fragments: { 25 | ship: () => Relay.QL` 26 | fragment on Ship { 27 | id, 28 | name 29 | } 30 | `, 31 | }, 32 | }); 33 | -------------------------------------------------------------------------------- /star-wars/js/mutation/AddShipMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class AddShipMutation extends Relay.Mutation { 4 | 5 | static fragments = { 6 | faction: () => Relay.QL` 7 | fragment on Faction { 8 | id, 9 | factionId 10 | } 11 | `, 12 | }; 13 | 14 | getMutation() { 15 | return Relay.QL`mutation { introduceShip }`; 16 | } 17 | 18 | getVariables() { 19 | return { 20 | shipName: this.props.name, 21 | factionId: this.props.faction.factionId, 22 | }; 23 | } 24 | 25 | getFatQuery() { 26 | return Relay.QL` 27 | fragment on IntroduceShipPayload @relay(pattern: true) { 28 | faction { 29 | name 30 | ships { 31 | edges { 32 | node { 33 | name 34 | } 35 | } 36 | } 37 | } 38 | newShipEdge 39 | } 40 | `; 41 | } 42 | 43 | getConfigs() { 44 | return [{ 45 | type: 'RANGE_ADD', 46 | parentName: 'faction', 47 | parentID: this.props.faction.id, 48 | connectionName: 'ships', 49 | edgeName: 'newShipEdge', 50 | rangeBehaviors: { 51 | '': 'append', 52 | 'orderby(oldest)': 'prepend', 53 | }, 54 | }]; 55 | } 56 | 57 | getOptimisticResponse() { 58 | return { 59 | newShipEdge: { 60 | node: { 61 | name: this.props.name, 62 | }, 63 | }, 64 | faction: { 65 | id: this.props.faction.id, 66 | }, 67 | }; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /star-wars/js/routes/StarWarsAppHomeRoute.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file provided by Facebook is for non-commercial testing and evaluation 3 | * purposes only. Facebook reserves all rights not expressly granted. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 8 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 9 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | 13 | import Relay from 'react-relay'; 14 | 15 | export default class extends Relay.Route { 16 | static queries = { 17 | factions: () => Relay.QL`query { factions(names: $factionNames) }`, 18 | }; 19 | static routeName = 'StarWarsAppHomeRoute'; 20 | } 21 | -------------------------------------------------------------------------------- /star-wars/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "start": "babel-node ./server.js", 5 | "update-schema": "babel-node ./scripts/updateSchema.js", 6 | "lint": "./node_modules/.bin/eslint ." 7 | }, 8 | "dependencies": { 9 | "babel-core": "^6.5.2", 10 | "babel-loader": "^6.2.2", 11 | "babel-polyfill": "^6.5.0", 12 | "babel-preset-es2015": "^6.5.0", 13 | "babel-preset-react": "^6.5.0", 14 | "babel-preset-stage-0": "^6.5.0", 15 | "babel-relay-plugin": "^0.9.0", 16 | "classnames": "^2.2.3", 17 | "express": "^4.13.4", 18 | "graphql": "^0.4.17", 19 | "graphql-relay": "^0.3.6", 20 | "history": "^1.17.0", 21 | "koa": "^1.1.2", 22 | "koa-graphql": "^0.4.4", 23 | "koa-mount": "^1.3.0", 24 | "react": "^0.14.7", 25 | "react-dom": "^0.14.7", 26 | "react-relay": "^0.9.0", 27 | "webpack": "^1.12.13", 28 | "webpack-dev-server": "^1.14.1" 29 | }, 30 | "devDependencies": { 31 | "babel-cli": "^6.5.1", 32 | "babel-eslint": "^6.0.3", 33 | "eslint": "^2.8.0", 34 | "eslint-config-airbnb": "^7.0.0", 35 | "eslint-plugin-jsx-a11y": "^0.6.2", 36 | "eslint-plugin-react": "^4.3.0" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /star-wars/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Relay • Star Wars 7 | 8 | 9 |
    10 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /star-wars/scripts/updateSchema.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env babel-node --optional es7.asyncFunctions 2 | /** 3 | * This file provided by Facebook is for non-commercial testing and evaluation 4 | * purposes only. Facebook reserves all rights not expressly granted. 5 | * 6 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 7 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 8 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 9 | * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 10 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 11 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 12 | */ 13 | 14 | import fs from 'fs'; 15 | import path from 'path'; 16 | import { schema } from '../data/schema'; 17 | import { graphql } from 'graphql'; 18 | import { introspectionQuery, printSchema } from 'graphql/utilities'; 19 | 20 | // Save JSON of full schema introspection for Babel Relay Plugin to use 21 | (async () => { 22 | const result = await (graphql(schema, introspectionQuery)); 23 | if (result.errors) { 24 | console.error( 25 | 'ERROR introspecting schema: ', 26 | JSON.stringify(result.errors, null, 2) 27 | ); 28 | } else { 29 | fs.writeFileSync( 30 | path.join(__dirname, '../data/schema.json'), 31 | JSON.stringify(result, null, 2) 32 | ); 33 | } 34 | })(); 35 | 36 | // Save user readable type system shorthand of schema 37 | fs.writeFileSync( 38 | path.join(__dirname, '../data/schema.graphql'), 39 | printSchema(schema) 40 | ); 41 | -------------------------------------------------------------------------------- /star-wars/server.js: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import koa from 'koa'; 3 | import graphQLHTTP from 'koa-graphql'; 4 | import mount from 'koa-mount'; 5 | import path from 'path'; 6 | import webpack from 'webpack'; 7 | import WebpackDevServer from 'webpack-dev-server'; 8 | import { schema } from './data/schema'; 9 | 10 | const APP_PORT = 3000; 11 | const GRAPHQL_PORT = 8080; 12 | 13 | // Expose a GraphQL endpoint 14 | const graphQLServer = koa(); 15 | 16 | graphQLServer.use(mount('/', graphQLHTTP({ schema, pretty: true }))); 17 | 18 | graphQLServer.listen(GRAPHQL_PORT, () => console.log( 19 | `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}` 20 | )); 21 | 22 | // Serve the Relay app 23 | const compiler = webpack({ 24 | entry: path.resolve(__dirname, 'js', 'app.js'), 25 | module: { 26 | loaders: [ 27 | { 28 | exclude: /node_modules/, 29 | loader: 'babel', 30 | test: /\.js$/, 31 | }, 32 | ], 33 | }, 34 | output: { filename: 'app.js', path: '/' }, 35 | }); 36 | 37 | const app = new WebpackDevServer(compiler, { 38 | contentBase: '/public/', 39 | proxy: { '/graphql': `http://localhost:${GRAPHQL_PORT}` }, 40 | publicPath: '/js/', 41 | stats: { colors: true }, 42 | }); 43 | 44 | // Serve static resources 45 | app.use('/', express.static(path.resolve(__dirname, 'public'))); 46 | 47 | app.listen(APP_PORT, () => { 48 | console.log(`App is now running on http://localhost:${APP_PORT}`); 49 | }); 50 | -------------------------------------------------------------------------------- /todo/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "passPerPreset": true, 3 | "presets": [ 4 | { 5 | "plugins": [ 6 | "./build/babelRelayPlugin" 7 | ] 8 | }, 9 | "react", 10 | "es2015", 11 | "stage-0" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /todo/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb", 3 | "parser": "babel-eslint", 4 | "env": { 5 | "browser": true, 6 | "node": true 7 | }, 8 | "rules": { 9 | "eqeqeq": 0, 10 | "no-console": 0, 11 | "no-use-before-define": 0, 12 | "react/prop-types": 0, 13 | "react/jsx-closing-bracket-location": 0 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /todo/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | npm-debug.log 4 | data/schema.graphql 5 | -------------------------------------------------------------------------------- /todo/README.md: -------------------------------------------------------------------------------- 1 | # Relay TodoMVC 2 | 3 | ## Installation 4 | 5 | ``` 6 | npm install 7 | ``` 8 | 9 | ## Running 10 | 11 | Start a local server: 12 | 13 | ``` 14 | npm start 15 | ``` 16 | 17 | ## Developing 18 | 19 | Any changes you make to files in the `js/` directory will cause the server to 20 | automatically rebuild the app and refresh your browser. 21 | 22 | If at any time you make changes to `data/schema.js`, stop the server, 23 | regenerate `data/schema.json`, and restart the server: 24 | 25 | ``` 26 | npm run update-schema 27 | npm start 28 | ``` 29 | 30 | ## License 31 | 32 | This file provided by Facebook is for non-commercial testing and evaluation 33 | purposes only. Facebook reserves all rights not expressly granted. 34 | 35 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 36 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 37 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 38 | FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 39 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 40 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 41 | -------------------------------------------------------------------------------- /todo/build/babelRelayPlugin.js: -------------------------------------------------------------------------------- 1 | import getBabelRelayPlugin from 'babel-relay-plugin'; 2 | import schema from '../data/schema.json'; 3 | 4 | export default getBabelRelayPlugin(schema.data); 5 | -------------------------------------------------------------------------------- /todo/data/database.js: -------------------------------------------------------------------------------- 1 | export class Todo {} 2 | export class User {} 3 | 4 | // Mock authenticated ID 5 | const VIEWER_ID = 'me'; 6 | 7 | // Mock user data 8 | const viewer = new User(); 9 | viewer.id = VIEWER_ID; 10 | const usersById = { 11 | [VIEWER_ID]: viewer, 12 | }; 13 | 14 | // Mock todo data 15 | const todosById = {}; 16 | const todoIdsByUser = { 17 | [VIEWER_ID]: [], 18 | }; 19 | let nextTodoId = 0; 20 | addTodo('Taste JavaScript', true); 21 | addTodo('Buy a unicorn', false); 22 | 23 | export function addTodo(text, complete) { 24 | const todo = new Todo(); 25 | todo.complete = !!complete; 26 | todo.id = `${nextTodoId++}`; 27 | todo.text = text; 28 | todosById[todo.id] = todo; 29 | todoIdsByUser[VIEWER_ID].push(todo.id); 30 | return todo.id; 31 | } 32 | 33 | export function changeTodoStatus(id, complete) { 34 | const todo = getTodo(id); 35 | todo.complete = complete; 36 | } 37 | 38 | export function getTodo(id) { 39 | return todosById[id]; 40 | } 41 | 42 | export function getTodos(status = 'any') { 43 | const todos = todoIdsByUser[VIEWER_ID].map(id => todosById[id]); 44 | if (status === 'any') { 45 | return todos; 46 | } 47 | return todos.filter(todo => todo.complete === (status === 'completed')); 48 | } 49 | 50 | export function getUser(id) { 51 | return usersById[id]; 52 | } 53 | 54 | export function getViewer() { 55 | return getUser(VIEWER_ID); 56 | } 57 | 58 | export function markAllTodos(complete) { 59 | const changedTodos = []; 60 | getTodos().forEach(todo => { 61 | if (todo.complete !== complete) { 62 | todo.complete = complete; // eslint-disable-line no-param-reassign 63 | changedTodos.push(todo); 64 | } 65 | }); 66 | return changedTodos.map(todo => todo.id); 67 | } 68 | 69 | export function removeTodo(id) { 70 | const todoIndex = todoIdsByUser[VIEWER_ID].indexOf(id); 71 | if (todoIndex !== -1) { 72 | todoIdsByUser[VIEWER_ID].splice(todoIndex, 1); 73 | } 74 | delete todosById[id]; 75 | } 76 | 77 | export function removeCompletedTodos() { 78 | const todosToRemove = getTodos().filter(todo => todo.complete); 79 | todosToRemove.forEach(todo => removeTodo(todo.id)); 80 | return todosToRemove.map(todo => todo.id); 81 | } 82 | 83 | export function renameTodo(id, text) { 84 | const todo = getTodo(id); 85 | todo.text = text; 86 | } 87 | -------------------------------------------------------------------------------- /todo/js/app.js: -------------------------------------------------------------------------------- 1 | import 'babel-polyfill'; 2 | import 'todomvc-common'; 3 | 4 | import React from 'react'; 5 | import { render } from 'react-dom'; 6 | import Relay from 'react-relay'; 7 | import { createHashHistory } from 'history'; 8 | import { IndexRoute, Route, Router, applyRouterMiddleware, useRouterHistory } from 'react-router'; 9 | import useRelay from 'react-router-relay'; 10 | import TodoApp from './components/TodoApp'; 11 | import TodoList from './components/TodoList'; 12 | import ViewerQueries from './queries/ViewerQueries'; 13 | 14 | const history = useRouterHistory(createHashHistory)({ queryKey: false }); 15 | const mountNode = document.getElementById('root'); 16 | 17 | render( 18 | 22 | 25 | ({ status: 'any' })} 29 | /> 30 | 34 | 35 | , 36 | mountNode 37 | ); 38 | -------------------------------------------------------------------------------- /todo/js/components/Todo.js: -------------------------------------------------------------------------------- 1 | import ChangeTodoStatusMutation from '../mutations/ChangeTodoStatusMutation'; 2 | import RemoveTodoMutation from '../mutations/RemoveTodoMutation'; 3 | import RenameTodoMutation from '../mutations/RenameTodoMutation'; 4 | import TodoTextInput from './TodoTextInput'; 5 | 6 | import React from 'react'; 7 | import Relay from 'react-relay'; 8 | import classnames from 'classnames'; 9 | 10 | class Todo extends React.Component { 11 | state = { 12 | isEditing: false, 13 | }; 14 | _handleCompleteChange = (e) => { 15 | const complete = e.target.checked; 16 | this.props.relay.commitUpdate( 17 | new ChangeTodoStatusMutation({ 18 | complete, 19 | todo: this.props.todo, 20 | viewer: this.props.viewer, 21 | }) 22 | ); 23 | }; 24 | _handleDestroyClick = () => { 25 | this._removeTodo(); 26 | }; 27 | _handleLabelDoubleClick = () => { 28 | this._setEditMode(true); 29 | }; 30 | _handleTextInputCancel = () => { 31 | this._setEditMode(false); 32 | }; 33 | _handleTextInputDelete = () => { 34 | this._setEditMode(false); 35 | this._removeTodo(); 36 | }; 37 | _handleTextInputSave = (text) => { 38 | this._setEditMode(false); 39 | this.props.relay.commitUpdate( 40 | new RenameTodoMutation({ todo: this.props.todo, text }) 41 | ); 42 | }; 43 | _removeTodo() { 44 | this.props.relay.commitUpdate( 45 | new RemoveTodoMutation({ todo: this.props.todo, viewer: this.props.viewer }) 46 | ); 47 | } 48 | _setEditMode = (shouldEdit) => { 49 | this.setState({ isEditing: shouldEdit }); 50 | }; 51 | renderTextInput() { 52 | return ( 53 | 61 | ); 62 | } 63 | render() { 64 | return ( 65 |
  • 70 |
    71 | 77 | 80 |
    85 | {this.state.isEditing && this.renderTextInput()} 86 |
  • 87 | ); 88 | } 89 | } 90 | 91 | export default Relay.createContainer(Todo, { 92 | fragments: { 93 | todo: () => Relay.QL` 94 | fragment on Todo { 95 | complete, 96 | id, 97 | text, 98 | ${ChangeTodoStatusMutation.getFragment('todo')}, 99 | ${RemoveTodoMutation.getFragment('todo')}, 100 | ${RenameTodoMutation.getFragment('todo')}, 101 | } 102 | `, 103 | viewer: () => Relay.QL` 104 | fragment on User { 105 | ${ChangeTodoStatusMutation.getFragment('viewer')}, 106 | ${RemoveTodoMutation.getFragment('viewer')}, 107 | } 108 | `, 109 | }, 110 | }); 111 | -------------------------------------------------------------------------------- /todo/js/components/TodoApp.js: -------------------------------------------------------------------------------- 1 | import AddTodoMutation from '../mutations/AddTodoMutation'; 2 | import TodoListFooter from './TodoListFooter'; 3 | import TodoTextInput from './TodoTextInput'; 4 | 5 | import React from 'react'; 6 | import Relay from 'react-relay'; 7 | 8 | class TodoApp extends React.Component { 9 | _handleTextInputSave = (text) => { 10 | this.props.relay.commitUpdate( 11 | new AddTodoMutation({ text, viewer: this.props.viewer }) 12 | ); 13 | }; 14 | render() { 15 | const hasTodos = this.props.viewer.totalCount > 0; 16 | return ( 17 |
    18 |
    19 |
    20 |

    21 | todos 22 |

    23 | 29 |
    30 | 31 | {this.props.children} 32 | 33 | {hasTodos && 34 | 38 | } 39 |
    40 | 53 |
    54 | ); 55 | } 56 | } 57 | 58 | export default Relay.createContainer(TodoApp, { 59 | fragments: { 60 | viewer: () => Relay.QL` 61 | fragment on User { 62 | totalCount, 63 | ${AddTodoMutation.getFragment('viewer')}, 64 | ${TodoListFooter.getFragment('viewer')}, 65 | } 66 | `, 67 | }, 68 | }); 69 | -------------------------------------------------------------------------------- /todo/js/components/TodoList.js: -------------------------------------------------------------------------------- 1 | import MarkAllTodosMutation from '../mutations/MarkAllTodosMutation'; 2 | import Todo from './Todo'; 3 | 4 | import React from 'react'; 5 | import Relay from 'react-relay'; 6 | 7 | class TodoList extends React.Component { 8 | _handleMarkAllChange = (e) => { 9 | const complete = e.target.checked; 10 | this.props.relay.commitUpdate( 11 | new MarkAllTodosMutation({ 12 | complete, 13 | todos: this.props.viewer.todos, 14 | viewer: this.props.viewer, 15 | }) 16 | ); 17 | }; 18 | renderTodos() { 19 | return this.props.viewer.todos.edges.map(edge => 20 | 25 | ); 26 | } 27 | render() { 28 | const numTodos = this.props.viewer.totalCount; 29 | const numCompletedTodos = this.props.viewer.completedCount; 30 | return ( 31 |
    32 | 38 | 41 |
      42 | {this.renderTodos()} 43 |
    44 |
    45 | ); 46 | } 47 | } 48 | 49 | export default Relay.createContainer(TodoList, { 50 | initialVariables: { 51 | status: null, 52 | }, 53 | 54 | prepareVariables({ status }) { 55 | let nextStatus; 56 | if (status === 'active' || status === 'completed') { 57 | nextStatus = status; 58 | } else { 59 | // This matches the Backbone example, which displays all todos on an 60 | // invalid route. 61 | nextStatus = 'any'; 62 | } 63 | return { 64 | status: nextStatus, 65 | }; 66 | }, 67 | 68 | fragments: { 69 | viewer: () => Relay.QL` 70 | fragment on User { 71 | completedCount, 72 | todos( 73 | status: $status, 74 | first: 2147483647 # max GraphQLInt 75 | ) { 76 | edges { 77 | node { 78 | id, 79 | ${Todo.getFragment('todo')}, 80 | }, 81 | }, 82 | ${MarkAllTodosMutation.getFragment('todos')}, 83 | }, 84 | totalCount, 85 | ${MarkAllTodosMutation.getFragment('viewer')}, 86 | ${Todo.getFragment('viewer')}, 87 | } 88 | `, 89 | }, 90 | }); 91 | -------------------------------------------------------------------------------- /todo/js/components/TodoListFooter.js: -------------------------------------------------------------------------------- 1 | import { IndexLink, Link } from 'react-router'; 2 | import RemoveCompletedTodosMutation from '../mutations/RemoveCompletedTodosMutation'; 3 | 4 | import React from 'react'; 5 | import Relay from 'react-relay'; 6 | 7 | class TodoListFooter extends React.Component { 8 | _handleRemoveCompletedTodosClick = () => { 9 | this.props.relay.commitUpdate( 10 | new RemoveCompletedTodosMutation({ 11 | todos: this.props.viewer.todos, 12 | viewer: this.props.viewer, 13 | }) 14 | ); 15 | }; 16 | render() { 17 | const numCompletedTodos = this.props.viewer.completedCount; 18 | const numRemainingTodos = this.props.viewer.totalCount - numCompletedTodos; 19 | return ( 20 |
    21 | 22 | {numRemainingTodos} item{numRemainingTodos === 1 ? '' : 's'} left 23 | 24 |
      25 |
    • 26 | All 27 |
    • 28 |
    • 29 | Active 30 |
    • 31 |
    • 32 | Completed 33 |
    • 34 |
    35 | {numCompletedTodos > 0 && 36 | 41 | } 42 |
    43 | ); 44 | } 45 | } 46 | 47 | export default Relay.createContainer(TodoListFooter, { 48 | fragments: { 49 | viewer: () => Relay.QL` 50 | fragment on User { 51 | completedCount, 52 | todos( 53 | status: "completed", 54 | first: 2147483647 # max GraphQLInt 55 | ) { 56 | ${RemoveCompletedTodosMutation.getFragment('todos')}, 57 | }, 58 | totalCount, 59 | ${RemoveCompletedTodosMutation.getFragment('viewer')}, 60 | } 61 | `, 62 | }, 63 | }); 64 | -------------------------------------------------------------------------------- /todo/js/components/TodoTextInput.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | 4 | const { PropTypes } = React; 5 | 6 | const ENTER_KEY_CODE = 13; 7 | const ESC_KEY_CODE = 27; 8 | 9 | export default class TodoTextInput extends React.Component { 10 | static propTypes = { 11 | className: PropTypes.string, 12 | commitOnBlur: PropTypes.bool.isRequired, 13 | initialValue: PropTypes.string, 14 | onCancel: PropTypes.func, 15 | onDelete: PropTypes.func, 16 | onSave: PropTypes.func.isRequired, 17 | placeholder: PropTypes.string, 18 | }; 19 | static defaultProps = { 20 | commitOnBlur: false, 21 | }; 22 | state = { 23 | isEditing: false, 24 | text: this.props.initialValue || '', 25 | }; 26 | componentDidMount() { 27 | ReactDOM.findDOMNode(this).focus(); 28 | } 29 | _commitChanges = () => { 30 | const newText = this.state.text.trim(); 31 | if (this.props.onDelete && newText === '') { 32 | this.props.onDelete(); 33 | } else if (this.props.onCancel && newText === this.props.initialValue) { 34 | this.props.onCancel(); 35 | } else if (newText !== '') { 36 | this.props.onSave(newText); 37 | this.setState({ text: '' }); 38 | } 39 | }; 40 | _handleBlur = () => { 41 | if (this.props.commitOnBlur) { 42 | this._commitChanges(); 43 | } 44 | }; 45 | _handleChange = (e) => { 46 | this.setState({ text: e.target.value }); 47 | }; 48 | _handleKeyDown = (e) => { 49 | if (this.props.onCancel && e.keyCode === ESC_KEY_CODE) { 50 | this.props.onCancel(); 51 | } else if (e.keyCode === ENTER_KEY_CODE) { 52 | this._commitChanges(); 53 | } 54 | }; 55 | render() { 56 | return ( 57 | 65 | ); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /todo/js/mutations/AddTodoMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class AddTodoMutation extends Relay.Mutation { 4 | static fragments = { 5 | viewer: () => Relay.QL` 6 | fragment on User { 7 | id, 8 | totalCount, 9 | } 10 | `, 11 | }; 12 | getMutation() { 13 | return Relay.QL`mutation{addTodo}`; 14 | } 15 | getFatQuery() { 16 | return Relay.QL` 17 | fragment on AddTodoPayload @relay(pattern: true) { 18 | todoEdge, 19 | viewer { 20 | todos, 21 | totalCount, 22 | }, 23 | } 24 | `; 25 | } 26 | getConfigs() { 27 | return [{ 28 | type: 'RANGE_ADD', 29 | parentName: 'viewer', 30 | parentID: this.props.viewer.id, 31 | connectionName: 'todos', 32 | edgeName: 'todoEdge', 33 | rangeBehaviors: ({ status }) => { 34 | if (status === 'completed') { 35 | return 'ignore'; 36 | } 37 | return 'append'; 38 | }, 39 | }]; 40 | } 41 | getVariables() { 42 | return { 43 | text: this.props.text, 44 | }; 45 | } 46 | getOptimisticResponse() { 47 | return { 48 | // FIXME: totalCount gets updated optimistically, but this edge does not 49 | // get added until the server responds 50 | todoEdge: { 51 | node: { 52 | complete: false, 53 | text: this.props.text, 54 | }, 55 | }, 56 | viewer: { 57 | id: this.props.viewer.id, 58 | totalCount: this.props.viewer.totalCount + 1, 59 | }, 60 | }; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /todo/js/mutations/ChangeTodoStatusMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class ChangeTodoStatusMutation extends Relay.Mutation { 4 | static fragments = { 5 | todo: () => Relay.QL` 6 | fragment on Todo { 7 | id, 8 | } 9 | `, 10 | // TODO: Mark completedCount optional 11 | viewer: () => Relay.QL` 12 | fragment on User { 13 | id, 14 | completedCount, 15 | } 16 | `, 17 | }; 18 | getMutation() { 19 | return Relay.QL`mutation{changeTodoStatus}`; 20 | } 21 | getFatQuery() { 22 | return Relay.QL` 23 | fragment on ChangeTodoStatusPayload @relay(pattern: true) { 24 | todo { 25 | complete, 26 | }, 27 | viewer { 28 | completedCount, 29 | todos, 30 | }, 31 | } 32 | `; 33 | } 34 | getConfigs() { 35 | return [{ 36 | type: 'FIELDS_CHANGE', 37 | fieldIDs: { 38 | todo: this.props.todo.id, 39 | viewer: this.props.viewer.id, 40 | }, 41 | }]; 42 | } 43 | getVariables() { 44 | return { 45 | complete: this.props.complete, 46 | id: this.props.todo.id, 47 | }; 48 | } 49 | getOptimisticResponse() { 50 | const viewerPayload = { id: this.props.viewer.id }; 51 | if (this.props.viewer.completedCount != null) { 52 | viewerPayload.completedCount = this.props.complete ? 53 | this.props.viewer.completedCount + 1 : 54 | this.props.viewer.completedCount - 1; 55 | } 56 | return { 57 | todo: { 58 | complete: this.props.complete, 59 | id: this.props.todo.id, 60 | }, 61 | viewer: viewerPayload, 62 | }; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /todo/js/mutations/MarkAllTodosMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class MarkAllTodosMutation extends Relay.Mutation { 4 | static fragments = { 5 | // TODO: Mark edges and totalCount optional 6 | todos: () => Relay.QL` 7 | fragment on TodoConnection { 8 | edges { 9 | node { 10 | complete, 11 | id, 12 | }, 13 | }, 14 | } 15 | `, 16 | viewer: () => Relay.QL` 17 | fragment on User { 18 | id, 19 | totalCount, 20 | } 21 | `, 22 | }; 23 | getMutation() { 24 | return Relay.QL`mutation{markAllTodos}`; 25 | } 26 | getFatQuery() { 27 | return Relay.QL` 28 | fragment on MarkAllTodosPayload @relay(pattern: true) { 29 | viewer { 30 | completedCount, 31 | todos, 32 | }, 33 | } 34 | `; 35 | } 36 | getConfigs() { 37 | return [{ 38 | type: 'FIELDS_CHANGE', 39 | fieldIDs: { 40 | viewer: this.props.viewer.id, 41 | }, 42 | }]; 43 | } 44 | getVariables() { 45 | return { 46 | complete: this.props.complete, 47 | }; 48 | } 49 | getOptimisticResponse() { 50 | const viewerPayload = { id: this.props.viewer.id }; 51 | if (this.props.todos && this.props.todos.edges) { 52 | viewerPayload.todos = { 53 | edges: this.props.todos.edges 54 | .filter(edge => edge.node.complete !== this.props.complete) 55 | .map(edge => ({ 56 | node: { 57 | complete: this.props.complete, 58 | id: edge.node.id, 59 | }, 60 | })), 61 | }; 62 | } 63 | if (this.props.viewer.totalCount != null) { 64 | viewerPayload.completedCount = this.props.complete ? 65 | this.props.viewer.totalCount : 66 | 0; 67 | } 68 | return { 69 | viewer: viewerPayload, 70 | }; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /todo/js/mutations/RemoveCompletedTodosMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class RemoveCompletedTodosMutation extends Relay.Mutation { 4 | static fragments = { 5 | // TODO: Make completedCount, edges, and totalCount optional 6 | todos: () => Relay.QL` 7 | fragment on TodoConnection { 8 | edges { 9 | node { 10 | complete, 11 | id, 12 | }, 13 | }, 14 | } 15 | `, 16 | viewer: () => Relay.QL` 17 | fragment on User { 18 | completedCount, 19 | id, 20 | totalCount, 21 | } 22 | `, 23 | }; 24 | getMutation() { 25 | return Relay.QL`mutation{removeCompletedTodos}`; 26 | } 27 | getFatQuery() { 28 | return Relay.QL` 29 | fragment on RemoveCompletedTodosPayload @relay(pattern: true) { 30 | deletedTodoIds, 31 | viewer { 32 | completedCount, 33 | totalCount, 34 | }, 35 | } 36 | `; 37 | } 38 | getConfigs() { 39 | return [{ 40 | type: 'NODE_DELETE', 41 | parentName: 'viewer', 42 | parentID: this.props.viewer.id, 43 | connectionName: 'todos', 44 | deletedIDFieldName: 'deletedTodoIds', 45 | }]; 46 | } 47 | getVariables() { 48 | return {}; 49 | } 50 | getOptimisticResponse() { 51 | let deletedTodoIds; 52 | let newTotalCount; 53 | if (this.props.todos && this.props.todos.edges) { 54 | deletedTodoIds = this.props.todos.edges 55 | .filter(edge => edge.node.complete) 56 | .map(edge => edge.node.id); 57 | } 58 | const { completedCount, totalCount } = this.props.viewer; 59 | if (completedCount != null && totalCount != null) { 60 | newTotalCount = totalCount - completedCount; 61 | } 62 | return { 63 | deletedTodoIds, 64 | viewer: { 65 | completedCount: 0, 66 | id: this.props.viewer.id, 67 | totalCount: newTotalCount, 68 | }, 69 | }; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /todo/js/mutations/RemoveTodoMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class RemoveTodoMutation extends Relay.Mutation { 4 | static fragments = { 5 | // TODO: Mark complete as optional 6 | todo: () => Relay.QL` 7 | fragment on Todo { 8 | complete, 9 | id, 10 | } 11 | `, 12 | // TODO: Mark completedCount and totalCount as optional 13 | viewer: () => Relay.QL` 14 | fragment on User { 15 | completedCount, 16 | id, 17 | totalCount, 18 | } 19 | `, 20 | }; 21 | getMutation() { 22 | return Relay.QL`mutation{removeTodo}`; 23 | } 24 | getFatQuery() { 25 | return Relay.QL` 26 | fragment on RemoveTodoPayload @relay(pattern: true) { 27 | deletedTodoId, 28 | viewer { 29 | completedCount, 30 | totalCount, 31 | }, 32 | } 33 | `; 34 | } 35 | getConfigs() { 36 | return [{ 37 | type: 'NODE_DELETE', 38 | parentName: 'viewer', 39 | parentID: this.props.viewer.id, 40 | connectionName: 'todos', 41 | deletedIDFieldName: 'deletedTodoId', 42 | }]; 43 | } 44 | getVariables() { 45 | return { 46 | id: this.props.todo.id, 47 | }; 48 | } 49 | getOptimisticResponse() { 50 | const viewerPayload = { id: this.props.viewer.id }; 51 | if (this.props.viewer.completedCount != null) { 52 | viewerPayload.completedCount = this.props.todo.complete === true ? 53 | this.props.viewer.completedCount - 1 : 54 | this.props.viewer.completedCount; 55 | } 56 | if (this.props.viewer.totalCount != null) { 57 | viewerPayload.totalCount = this.props.viewer.totalCount - 1; 58 | } 59 | return { 60 | deletedTodoId: this.props.todo.id, 61 | viewer: viewerPayload, 62 | }; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /todo/js/mutations/RenameTodoMutation.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default class RenameTodoMutation extends Relay.Mutation { 4 | static fragments = { 5 | todo: () => Relay.QL` 6 | fragment on Todo { 7 | id, 8 | } 9 | `, 10 | }; 11 | getMutation() { 12 | return Relay.QL`mutation{renameTodo}`; 13 | } 14 | getFatQuery() { 15 | return Relay.QL` 16 | fragment on RenameTodoPayload @relay(pattern: true) { 17 | todo { 18 | text, 19 | } 20 | } 21 | `; 22 | } 23 | getConfigs() { 24 | return [{ 25 | type: 'FIELDS_CHANGE', 26 | fieldIDs: { 27 | todo: this.props.todo.id, 28 | }, 29 | }]; 30 | } 31 | getVariables() { 32 | return { 33 | id: this.props.todo.id, 34 | text: this.props.text, 35 | }; 36 | } 37 | getOptimisticResponse() { 38 | return { 39 | todo: { 40 | id: this.props.todo.id, 41 | text: this.props.text, 42 | }, 43 | }; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /todo/js/queries/ViewerQueries.js: -------------------------------------------------------------------------------- 1 | import Relay from 'react-relay'; 2 | 3 | export default { 4 | viewer: () => Relay.QL`query { viewer }`, 5 | }; 6 | -------------------------------------------------------------------------------- /todo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "start": "babel-node ./server.js", 5 | "update-schema": "babel-node ./scripts/updateSchema.js", 6 | "lint": "./node_modules/.bin/eslint ." 7 | }, 8 | "dependencies": { 9 | "babel-core": "^6.5.2", 10 | "babel-loader": "^6.2.4", 11 | "babel-polyfill": "^6.9.0", 12 | "babel-preset-es2015": "^6.9.0", 13 | "babel-preset-react": "^6.5.0", 14 | "babel-preset-stage-0": "^6.5.0", 15 | "babel-relay-plugin": "^0.9.0", 16 | "classnames": "^2.2.5", 17 | "express": "^4.13.4", 18 | "graphql": "^0.5.0", 19 | "graphql-relay": "^0.4.1", 20 | "history": "^2.1.1", 21 | "koa": "^1.1.2", 22 | "koa-graphql": "^0.5.1", 23 | "koa-mount": "^1.3.0", 24 | "react": "^15.0.2", 25 | "react-dom": "^15.0.2", 26 | "react-relay": "^0.9.0", 27 | "react-router": "^2.4.1", 28 | "react-router-relay": "^0.13.2", 29 | "todomvc-app-css": "^2.0.6", 30 | "todomvc-common": "^1.0.2", 31 | "webpack": "^1.13.1", 32 | "webpack-dev-server": "^1.14.1" 33 | }, 34 | "devDependencies": { 35 | "babel-cli": "^6.9.0", 36 | "babel-eslint": "^6.0.3", 37 | "eslint": "^2.8.0", 38 | "eslint-config-airbnb": "^7.0.0", 39 | "eslint-plugin-jsx-a11y": "^0.6.2", 40 | "eslint-plugin-react": "^4.3.0" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /todo/public/base.css: -------------------------------------------------------------------------------- 1 | ../node_modules/todomvc-common/base.css -------------------------------------------------------------------------------- /todo/public/index.css: -------------------------------------------------------------------------------- 1 | ../node_modules/todomvc-app-css/index.css -------------------------------------------------------------------------------- /todo/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Relay • TodoMVC 7 | 8 | 9 | 10 | 11 |
    12 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /todo/public/learn.json: -------------------------------------------------------------------------------- 1 | { 2 | "relay": { 3 | "name": "Koa GraphQL", 4 | "description": "Create a GraphQL HTTP server with Koa. ", 5 | "homepage": "https://github.com/chentsulin/koa-graphql", 6 | "examples": [{ 7 | "name": "koa-graphql + relay Example", 8 | "url": "", 9 | "source_url": "https://github.com/chentsulin/koa-graphql-relay-example", 10 | "type": "backend" 11 | }], 12 | "link_groups": [{ 13 | "heading": "Resources", 14 | "links": [{ 15 | "name": "Relay Documentation", 16 | "url": "https://facebook.github.io/relay/docs/getting-started.html" 17 | }, { 18 | "name": "Relay API Reference", 19 | "url": "https://facebook.github.io/relay/docs/api-reference-relay.html" 20 | }, { 21 | "name": "Koa GraphQL on GitHub", 22 | "url": "https://github.com/chentsulin/koa-graphql" 23 | }] 24 | }, { 25 | "heading": "Issue Tracker", 26 | "links": [{ 27 | "name": "Open a new issue on GitHub", 28 | "url": "https://github.com/chentsulin/koa-graphql-relay-example/issues/new" 29 | }] 30 | }] 31 | }, 32 | "templates": { 33 | "todomvc": "

    <%= name %>

    <% if (typeof examples !== 'undefined') { %> <% examples.forEach(function (example) { %>
    <%= example.name %>
    <% if (!location.href.match(example.url + '/')) { %> \" href=\"<%= example.url %>\">Demo, <% } if (example.type === 'backend') { %>\"><% } else { %>\"><% } %>Source <% }); %> <% } %>

    <%= description %>

    <% if (typeof link_groups !== 'undefined') { %>
    <% link_groups.forEach(function (link_group) { %>

    <%= link_group.heading %>

    <% }); %> <% } %> " 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /todo/scripts/updateSchema.js: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | import { schema } from '../data/schema'; 4 | import { graphql } from 'graphql'; 5 | import { introspectionQuery, printSchema } from 'graphql/utilities'; 6 | 7 | // Save JSON of full schema introspection for Babel Relay Plugin to use 8 | (async () => { 9 | const result = await (graphql(schema, introspectionQuery)); 10 | if (result.errors) { 11 | console.error( 12 | 'ERROR introspecting schema: ', 13 | JSON.stringify(result.errors, null, 2) 14 | ); 15 | } else { 16 | fs.writeFileSync( 17 | path.join(__dirname, '../data/schema.json'), 18 | JSON.stringify(result, null, 2) 19 | ); 20 | } 21 | })(); 22 | 23 | // Save user readable type system shorthand of schema 24 | fs.writeFileSync( 25 | path.join(__dirname, '../data/schema.graphql'), 26 | printSchema(schema) 27 | ); 28 | -------------------------------------------------------------------------------- /todo/server.js: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import koa from 'koa'; 3 | import graphQLHTTP from 'koa-graphql'; 4 | import mount from 'koa-mount'; 5 | import path from 'path'; 6 | import webpack from 'webpack'; 7 | import WebpackDevServer from 'webpack-dev-server'; 8 | import { schema } from './data/schema'; 9 | 10 | const APP_PORT = 3000; 11 | const GRAPHQL_PORT = 8080; 12 | 13 | // Expose a GraphQL endpoint 14 | const graphQLServer = koa(); 15 | 16 | graphQLServer.use(mount('/', graphQLHTTP({ schema, pretty: true }))); 17 | 18 | graphQLServer.listen(GRAPHQL_PORT, () => console.log( 19 | `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}` 20 | )); 21 | 22 | // Serve the Relay app 23 | const compiler = webpack({ 24 | devtool: 'cheap-module-eval-source-map', 25 | entry: path.resolve(__dirname, 'js', 'app.js'), 26 | module: { 27 | loaders: [ 28 | { 29 | exclude: /node_modules/, 30 | loader: 'babel', 31 | test: /\.js$/, 32 | }, 33 | ], 34 | }, 35 | output: { filename: 'app.js', path: '/' }, 36 | }); 37 | 38 | const app = new WebpackDevServer(compiler, { 39 | contentBase: '/public/', 40 | proxy: { '/graphql': `http://localhost:${GRAPHQL_PORT}` }, 41 | publicPath: '/js/', 42 | stats: { colors: true }, 43 | }); 44 | 45 | // Serve static resources 46 | app.use('/', express.static(path.resolve(__dirname, 'public'))); 47 | 48 | app.listen(APP_PORT, () => { 49 | console.log(`App is now running on http://localhost:${APP_PORT}`); 50 | }); 51 | --------------------------------------------------------------------------------