path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
public/7.blog.js
|
christianalfoni/EmptyBox
|
webpackJsonp([7],{341:function(e,t){e.exports="# Handling complex state with Baobab\n\nSo Baobab is here in version 1.0. Let us quickly recap why Baobab is such a great tool for your application and then we will see what version 1.0 addresses in regards of complex state handling. I encourage you to read the [initial article on Baobab](http://christianalfoni.com/articles/2015_02_06_Plant-a-Baobab-tree-in-your-flux-application) first as it introduces why you would consider Baobab at all.\n\n## A recap\nBaobab gives you the same \"one way flow\" of state in FLUX, only it reduces a lot of the complexity. A simple view on this \"one way flow\" is:\n\n```javascript\n\nArchitecture using Baobab\n \n |------------|\n |-> | State tree | --| \n | |------------| |\n | v\n |---------| |------------|\n | Actions | <------ | Components |\n |---------| |------------|\n\n```\n\nNote that the **Actions** layer is whatever you want it to be. Personally I just expose a module with methods that operates on the state tree. The point is that your components never mutate the tree and the actions never return state from the tree. Any change to state is done through an action which changes the tree, which notifies about the change to any components listening to that part of the tree. Baobab handles this very well and it integrates very well with React.\n\n## What is complex state?\nFirst of all we have to get a notion of what we are trying to solve. Even though Baobab up until version 1.0 gave us a great concept for handling state it was challenging to handle \"shared data\". Let me explain.\n\n### Direct reference\n```javascript\n\nlet tree = new Baobab({\n\n projects: [{\n id: 0, \n title: 'foo'\n }, {\n id: 1, \n title: 'bar'\n }],\n\n selectedProject: null\n\n});\n```\n\nLet us imagine we have a list of projects. They are displayed in a table. When the user clicks one of the projects a modal should appear with the possibility to change the data of the project. So let us imagine that now. The user clicks the first project and triggers an action:\n\n```javascript\n\nimport tree from './tree.js';\n\nlet actions = {\n selectProject(index) {\n tree.set('selectedProject', tree.get('projects')[index]);\n }\n};\n\nexport default actions;\n```\n\nThe problem we face here is that we reference the first project in the projects array. This will get us into trouble. The technical reason you get into trouble is because any change to an object or array in a Baobab tree will effectively change its reference. Baobab does this is so that you can easily do a `prevObj === newObj` to know if something changed. You do not have to go into objects and arrays, traversing them to figure out if anything changed. Especially React takes advantage of this to determine the need to render a component.\n\nAnother part of this story is that \"shared state is the root of all evil\". If a change in one part of your state tree would uncontrollably affect other parts it would be difficult both for you as a developer and Baobab to keep track of those changes. It needs to behave in a predictable manner.\n\nSo the only way to really fix this is to create a clone.\n\n```javascript\n\nlet tree = new Baobab({\n\n projects: [{\n id: 0, \n title: 'foo'\n }, {\n id: 1, \n title: 'bar'\n }],\n\n selectedProject: {\n id: 0, \n title: 'foo' \n }\n\n});\n```\n\nBut now we have two instances of the same project. One on **selectedProject** and one inside **projects**. So if we change the selected project it will not be reflected in the projects list and vice versa. We would have to create pretty complex logic to make sure everything is up to date in our tree.\n\n\n### Referencing in a list\nIn the example above we selected one single project. But what if you downloaded 1000 projects to the client and just wanted to show 10 of them in a table? We need to clone multiple of the projects.\n\n```javascript\n\nlet tree = new Baobab({\n\n projects: [{\n id: 0, \n title: 'foo'\n }, {\n id: 1, \n title: 'bar'\n }...1000],\n\n projectRows: [{\n id: 0, \n title: 'foo'\n }, {\n id: 1, \n title: 'bar'\n }...10]\n\n});\n```\n\nAnd we run into the exact same problem as above, though it requires even more logic to keep in sync.\n\n### Reference within reference\nVery typically in relational databases everything is referenced with an ID. So let us imagine our projects can have comments. These comments are referenced by ID. Let us add that to the state tree:\n\n```javascript\n\nlet tree = new Baobab({\n\n comments: [{\n id: 0, \n comment: 'foo'\n }, {\n id: 1, \n comment: 'bar'\n }],\n\n projects: [{\n id: 0, \n title: 'foo', \n comments: [0]\n }, {\n id: 1, \n title: 'bar', \n comments: [1]\n }...1000],\n\n projectRows: [{\n id: 0, \n title: 'foo',\n comments: [{\n id: 0, \n comment: 'foo'\n }]\n }, {\n id: 1, \n title: 'bar',\n comments: [{\n id: 1, \n comment: 'bar'\n }]\n }...10]\n\n});\n```\n\nNow we need even more complex logic, because we do not really want just the ID of the comments, we want the comments themselves. We have to handle that while cloning. But what if a comment is deleted? We have to traverse all projectRows, check the project comments if it exists there and remove it also. But even worse, what if we did not have the data for the comment yet? We have to grab it from the server. How would we handle that?\n\n## Baobab-react\nOne clever change in the v1.0 of Baobab is that the React parts of the library is moved into its own repo. The reason is that there are many different ways you might want to handle moving state into your components. Baobab allows for different strategies, even ES7 decorators, which we are going to look at shortly.\n\nAnother thing to notice is that Baobab now uses the context to pass state into your components. This is a less intrusive and more isomorphic friendly way of doing it. In practice it means that none of your components will depend on the state tree itself, it is injected in your top component and you use mixins to extract the state. Let us have a look at that first to get used to the syntax:\n\n*main.js*\n```javascript\n\nimport tree from './tree.js';\nimport {root, branch} from 'baobab-react/mixins';\n\n/* We first set up our top component. This component will need\n the \"root\" mixin. The root mixin exposes the state tree on\n the context */\n\nlet App = React.createClass({\n mixins: [root],\n render() {\n return (\n <div>\n <Header/>\n </div>\n );\n }\n});\n\n/* Any child component in the application can attach the\n branch mixin. This mixin allows you to attach cursors\n that will extract state from the tree and attach it to\n the state object of the component */\n\nlet Header = React.createClass({\n mixins: [branch],\n cursors: {\n foo: ['bar']\n },\n render() {\n return (\n <div>{this.state.foo}</div>\n );\n }\n});\n\n\n/* When we render the application we attach a \"tree\" prop to it\n and pass our tree. Now you see how well this works on the server,\n where you would probably pass down different trees based on the user\n requesting a resource */\n\nReact.render(<App tree={tree}/>, document.getElementById('app'));\n```\n\nBut now, let us look at the one major API addition to Baobab.\n\n## Facets\nSo the new term is **Facets**. If you think about how components are able to use cursors to compose a UI description in the example above, think of Facets using cursors to compose state. Nothing explains this better than an example though, so let us head straight to our first challenge and solve that.\n\n### Solving direct reference\n\n*tree.js*\n```javascript\n\nimport Baobab from 'baobab';\n\n/* We define a Facet simply as an object with two special properties, \n \"cursors\" and \"get\" */\n\nlet selectedProject = {\n cursors: {\n id: ['selectedProjectId'],\n projects: ['projects']\n },\n get: function (state) {\n return state.projects[state.id];\n }\n};\n\n/* We define our tree with some initial data and attach the facet */\n\nlet tree = new Baobab({\n projects: {\n '0': {\n title: 'foo'\n },\n '1': {\n title: 'bar'\n }\n },\n selectedProjectId: '0'\n}, {\n facets: {\n selectedProject: selectedProject\n }\n});\n\nexport default tree;\n```\nSo this is quite self explainatory I think. We first define our facet. It is just an object with two properties. The **cursors** property brings in the state you need to create a new state output. In this case we want to know about **selectedProjectId** and **projects**. This also ensures any changes to these two cursors will update the facet. The **get** method is the second property and that is where you produce the state you want this facet to return. In this case we just want to grab the project from the projects map by using the ID in **selectedProjectId**. In the previous examples the projects were an array, but by using a map lookups are a lot easier and more performant.\n\nLets make use of our facet:\n\n*Project.js*\n```javascript\n\nimport React from 'react';\nimport {branch} from 'baobab-react/mixins';\n\nlet Project = React.createClass({\n mixins: [branch],\n facets: {\n project: 'selectedProject'\n },\n render() {\n if (this.state.project) {\n return (\n <div>{this.state.project.title}</div>\n );\n } else {\n return null;\n }\n } \n});\n\nexport default Project;\n```\nAs we can see a **facets** property is also available to our components using the mixin. It behaves exactly the same as a cursor. It grabs the value produced by the facet whenever any of its cursors update.\n\nSo if any component triggered an action defined something like this:\n\n*actions.js*\n```javascript\n\nimport tree from './tree.js';\n\nlet actions = {\n selectProject(projectId) {\n tree.set('selectedProjectId', projectId);\n }\n};\n\nexport default actions;\n```\n\nThe facet would first react and in turn notify the Project component which would then grab the new state from the facet. So this is quite nice. We have now solved the challenge with referencing data in the tree, but this was the least troublesome challenge we had. Let us move on to more complex state handling.\n\n### Solving referencing in a list\nInstead of displaying a single project, lets us imagine displaying a list of projects in a table. We actually use the exact same approach here, but I think it is worth looking at.\n\n*tree.js*\n```javascript\n\nimport Baobab from 'baobab';\n\nlet projectsList = {\n cursors: {\n ids: ['projectsListIds'],\n projects: ['projects']\n },\n get: function (state) {\n return state.ids.map(function (id) {\n return state.projects[id];\n });\n }\n};\n\nlet tree = new Baobab({\n projects: {\n '0': {\n title: 'foo'\n },\n '1': {\n title: 'bar'\n }\n },\n projectsListIds: []\n}, {\n facets: {\n projectsList: projectsList\n }\n});\n\nexport default tree;\n```\n\nAnd our component could use the facet something like this:\n\n*ProjectsList.js*\n```javascript\n\nimport React from 'react';\nimport {branch} from 'baobab-react/mixins';\n\nlet ProjectsList = React.createClass({\n mixins: [branch],\n facets: {\n projects: 'projectsList'\n },\n renderRow(project) {\n return (\n <tr key={project.id}>\n <td>{project.title}</td>\n </tr>\n );\n },\n render() {\n return (\n <table>\n <tbody>\n {this.state.projects.map(this.renderRow)}\n </tbody>\n </table>\n );\n } \n});\n\nexport default ProjectsList;\n```\n\nAnd finally an action could look something like this:\n\n*actions.js*\n```javascript\n\nimport tree from './tree.js';\n\nlet actions = {\n displayProjects(projectIds) {\n tree.set('projectsListIds', projectIds);\n }\n};\n\nexport default actions;\n```\nAnd that's it. We now have pretty complex state handling and everything will just update automatically when anything changes. Either it being in the state defining what to display in the UI or the state containing the source data.\n\nWe are starting to see a pattern emerge here. We start to see a more clear separation of state. Our **projects** state is more a data source than state used in the UI. It is very typical that you want to keep downloaded data in the client for optimization reason. That way the next time you want to use the data you do not need a roundtrip to the server.\n\n### Solving reference within reference\nIn this last example I will just show the code for the tree, as I hope you are getting the feel for how it is used in a component and changed using an action. Lets imagine our projects are created by users. The projects only store the ID of the user on an **authorId** property.\n\n*tree.js*\n```javascript\n\nimport Baobab from 'baobab';\n\nlet projectsList = {\n cursors: {\n ids: ['projectsListIds'],\n projects: ['projects'],\n users: ['users']\n },\n get(state) {\n return state.ids.map(function (id) {\n\n /* We are going to add a new property to the project. The \"author\"\n property will contain the user from the users map. We do not want\n to mutate the project object inside the tree, so we create a new\n object and hook the project object as a prototype to it. Any\n properties added will be part of the new object, not the actual\n project inside the tree, but we can still reference any property\n from the original project object */\n\n let project = Object.create(state.projects[id]);\n project.author = state.users[project.authorId];\n return project;\n });\n }\n};\n\nlet tree = new Baobab({\n projects: {},\n users: {},\n projectsListIds: []\n}, {\n facets: {\n projectsList: projectsList\n }\n});\n\nexport default tree;\n```\nLets us go through this step by step.\n\n1. I added a users cursor to the facet as we need access to those users as a lookup with the **authorId**\n2. I decide to add an **author** property to the project based on the **authorId**. This will be the actual user. To make sure that the project object in the tree does not mutate I simply create a new object with the project object in the tree as a prototype\n3. When I now add a new author property to the project it does not affect the object in the tree, but I can still reference all the properties from the original project object\n\nThe really important point to get here is that if any of the cursors of the facet updates, so will the facet. So if something from the server or other parts of the UI would cause a project or a user to update, the facet would update itself. This is an extremely important and powerful concept. If you have worked with Ember \"computed properties\" might come to mind. This is very much the same concept, but it is more about solving the challenge of referencing data in the tree, not computing counters etc. as that can more easily be done when an action changes state in the tree.\n\nNow, you might say. What if I have 500 users that quite often updates, but the facet only shows 10 projects. Would it not update unnecessarily quite often? Yeah, you are perfectly right. But this is actually the same core concept that makes React work so well. You recalculate on changes. Be sure you also note that you will not go through the 500 users when something updates, just the 10 project ids you are currently displaying in the UI. So it is very efficient nevertheless.\n\n## Bring state handling to a whole new level\nThe really good thing about facets is that it keeps state handling away from your components. Components should just get data and produce UI. They should ideally not have any logic related to computing state. But this is not all to facets. They open up for something completely new and that is reacting to missing data.\n\nIn our example with **projectsListIds** and the projects themselves pointing to **authorId** you will quickly get into situations where some of this data is missing and you need to get it from the server. What if this could happen completely automatically?\n\nFacebook has introduced their [Relay and GraphQL](https://facebook.github.io/react/blog/2015/02/20/introducing-relay-and-graphql.html) concept which is really exciting. The challenge with that solution though is that you have to refactor your backend to support a single endpoint and it does not seem to address relational data like in the examples above. A lot of solutions out there today has this relational data structure and it would be great to have a flexible enough concept to handle that in a way that makes sense for each application.\n\nI am going to show you an example of how you can create this automatic loading of data by using facets and something I just call **loaders**. Loaders are just like **actions** in the way that they are a concept, not a specific part of Baobab or React, but they do have a specific purpose. \n\n```javascript\n\nFacets and loaders\n \n |------------|\n |-> | State tree | ------------- \n | |------------| | |\n | ^ | |\n | | | |\n | |---------| |--------| |\n | | Loaders | <-| Facets | |\n | |---------| |--------| |\n | | |\n | v v\n |---------| |-------------------|\n | Actions | <------ | Components |\n |---------| |-------------------|\n\n```\n\nLike actions are methods that have access to the state tree, so are loaders. But unlike actions that are typically called from components, loaders are only called from facets. This keeps the one way flow that we need to keep our minds sane. I just want to point out again that this is not an official Baobab concept, it is an example to inspire use of facets. So let us see this concept in action.\n\n### The challenge\nYou have probably experienced the need for client specific state related to server specific state, or data if you will. What I mean is that when you load, create, optimistically create, update or have errors on some data you want to easily display that in the UI. An other thing is that you want to easily grab any data that is missing. An example of this is loading a project where the **authorId** is not currently available, you have to get it from the server, and you want to indicate that somehow.\n\n### The solution\nWe are now going to keep working on our **projects** example and create a solution for handling the challenges explained. Let us imagine we have no data at all in the client, but we have hardcoded some project ids we want to load. Maybe these ids came from localstorage or something. I am not going to create a crazy magic abstraction, but rather create a readable example to show you how this can be solved. That way you are totally free to create an abstraction for your project the suits the needs.\n\n*tree.js*\n```javascript\n\nimport Baobab from 'baobab';\nimport ProjectsListFacet from './facets/ProjectsList';\n\nlet tree = new Baobab({\n projects: {},\n users: {}\n projectsListIds: ['123', '456', '789']\n}, {\n facets: {\n projectsList: ProjectsListFacet\n }\n});\n\nexport default tree;\n```\n\nAnd let us define the facet:\n\n*facets/ProjectsList.js*\n```javascript\n\nimport projectLoader from './../loaders/project.js';\nimport userLoader from './../loaders/user.js';\n\nlet ProjectsList = {\n cursors: {\n ids: ['projectsListIds'],\n projects: ['projects'],\n users: ['users']\n },\n get(state) {\n return state.ids.map(function (id) {\n\n let project = state.projects[id];\n if (project) {\n project = Object.create(project);\n } else {\n return projectLoader(id, this);\n }\n\n let author = state.users[project.authorId];\n if (author) {\n project.author = author; \n } else {\n project.author = userLoader(project.author, this);\n }\n\n return project;\n }); \n }\n};\n\nexport default ProjectsList;\n```\nOkay, so what are we doing here? Lets go through that step by step before looking at the loaders:\n\n1. First we try to get the project from our **projects** map\n2. If the project exists we hook it as a prototype on a new object to avoid mutation. If it does not exist we pass the id to a loader. The **get** method runs in the context of the tree, so we pass the tree also to the loader. This allows the facet to be reused on different trees. Then we return what the loader returns\n3. If the project exists we try to grab the author from the **users** map, but if it does not exist we pass the author id to a user loader and put whatever it returns as the author\n\nSo what are these loaders actually doing? Lets look at an example:\n\n*loaders/project.js*\n```javascript\n\nimport ajax from 'ajax'; // Some ajax lib\nimport batchCalls from 'batchcalls';\n\n/* We are using the tiny \"batchcalls\" lib which just accumulates\n synchronous calls done to the function. So for example a list\n of 10 projects would cause one request for those 10 projects.\n Note that also Baobab batches changes to the tree so we are only\n causing one request to the server and one update to the facet */\n\nlet getAndSetProject = batchCalls(function (ids, paths, tree) {\n\n ajax.get('/projects/?ids=' + ids.join(','))\n .success(function (projects) {\n ids.forEach(function (id, index) {\n tree.set(paths[index], projects[id]);\n });\n })\n .error(function (error) {\n ids.forEach(function (id, index) {\n tree.set(paths[index], {\n id: id,\n $error: error\n });\n });\n });\n\n});\n\nexport default function (id, tree) {\n\n /* First we define at what path in our state tree the project should\n be available. Then we check if there is some data there already \n or prepare a new object */\n\n let path = ['projects', id];\n let project = tree.get(path) || {};\n\n /* We now attach the id and a UI property we call $isLoading. It is\n prefixed with $ to indicate that this is only a client property.\n We do not insert this into the state tree as it is temporary facet\n data */\n\n project.id = id;\n project.$isLoading = true;\n\n /* Now we try to grab the project from the server and update the\n project in the state tree on either success or error response */\n\n getAndSetProject(project.id, path, tree);\n\n /* We also return the temporary representation of the project that\n the facet can use to indicate that it is loading */\n\n return project;\n \n};\n```\n\nSo what does this give us? Well, lets first create a component using the facet and then we will summarize.\n\n*Projects.js*\n```javascript\n\nimport React from 'react';\nimport {branch} from 'baobab-react/mixins';\n\nlet Projects = React.createClass({\n mixins: [branch],\n facets: {\n projects: 'projectsList'\n },\n\n /* When we render a project we can now use our UI states to display what \n is happening to the data. Is it being loaded, was there an error etc.\n You may also expand on these states with $notFound, $noAccess etc. */\n\n renderProject(project) {\n if (project.$error) {\n return (\n <li key={project.id}>\n Could not load project - {project.$error}\n </li>\n );\n } else if (project.$isLoading) {\n return (\n <li key={project.id}>Loading project...</li>\n );\n } else {\n return (\n <li key={project.id}>\n {project.id + ' - ' + project.title}\n {this.renderAuthor(project.author)}\n </li>\n );\n }\n },\n\n /* And we use the exact same approach with the author */\n\n renderAuthor(author) {\n if (author.$error) {\n return (\n <small>Could not load author - {author.$error}</small>\n );\n } else if (author.$isLoading) {\n return (\n <small>Loading author...</small>\n );\n } else {\n return (\n <small>{author.name}</small>\n );\n }\n },\n render() {\n return (\n <ul>\n {this.state.projects.map(this.renderProject)}\n </ul>\n );\n }\n});\n\nexport default Projects;\n```\n\n### Summarizing\n\nSo this is whats happening:\n\n1. Our **ProjectsList** component tries to get some state using the **projectsList** facet\n2. There are no data on the projects map and the facet uses a **project loader** to grab that data. The loader returns and object with the ID of the project and a UI state called **$isLoading**\n3. When the ajax request reponds we insert either a project or an object indicating error with a project in the tree. This causes the **projects** cursor to update and the facet will run again\n4. In a situation where a project was successfully responded the facet will now attach an **author** property to the project using the **user loader**. The exact same thing happens again\n5. On every update of the facet the component will also update, displaying in detail what is happening to the data being loaded\n\nThis is really some of the most complex state handling you meet in applications, especially where the data is in a relational database. I think facets gives you that perfect balance of freedom to compose the state exactly how you need it, but still has a very strong concept of where to put it. I think we have to realize that handling state is not about creating one simple abstraction like \"Models\" and \"Collections\". We need something a lot more flexible and lower level so that we can create a custom abstraction that suits the project. Facets does exactly that.\n\n## Going ES6 and ES7\nOne last thing I want to share with you is how the **baobab-react** project allows you to use ES6 classes and ES7 decorators to allow your components to grab state. You of course need to use a transpiler for this, where I highly recommend [Babel](https://babeljs.io/). React, Babel and Webpack are close friends. You can read more about setting that up in my previous article [The ultimate webpack setup](http://christianalfoni.com/articles/2015_04_19_The-ultimate-webpack-setup).\n\nNote that with classes and decorators the state is not exposed on the components **state** object, but the **props** object. This is due to implementation details. Personally I think it is better as it indicates external state, not internal component state.\n\n### ES6 classes\n*App.js*\n```javascript\n\nimport {Component} from 'react';\nimport tree from './tree.js';\nimport Projects from './Projects.js';\nimport {root} from 'baobab-react/higher-order';\n\nclass Application extends Component {\n render() {\n return (\n <div>\n <Projects/>\n </div>\n );\n }\n}\n\nexport default root(Application, tree);\n```\n\n*Projects.js*\n```javascript\n\nimport {Component} from 'react';\nimport {branch} from 'baobab-react/higher-order';\n\nclass Projects extends Component {\n renderProject(project) {\n return (\n <li key={project.id}>{project.title}</li>\n );\n }\n render() {\n return (\n <ul>\n {this.props.projects.map(this.renderProject)}\n </ul>\n );\n }\n}\n\nexport default branch(Projects, {\n facets: {\n projects: 'projectsList'\n }\n});\n```\n\n### ES7 decorators\n*App.js*\n```javascript\n\nimport {Component} from 'react';\nimport tree from './tree.js';\nimport Projects from './Projects.js';\nimport {root} from 'baobab-react/decorators';\n\n@root(tree)\nclass Application extends Component {\n render() {\n return (\n <div>\n <Projects/>\n </div>\n );\n }\n}\n\nexport default Application;\n```\n\n*Projects.js*\n```javascript\n\nimport {Component} from 'react';\nimport {branch} from 'baobab-react/decorators';\n\n@branch({\n facets: {\n projects: 'projectsList'\n }\n})\nclass Projects extends Component {\n renderProject(project) {\n return (\n <li key={project.id}>{project.title}</li>\n );\n }\n render() {\n return (\n <ul>\n {this.props.projects.map(this.renderProject)}\n </ul>\n );\n }\n}\n\nexport default Projects;\n```\n\n## Summary\nI hope this gave you some good insight into how Baobab keeps evolving to handle application state. What makes Baobab really great is that it is \"low level\" compared to other solutions. It does not create abstractions that assumes anything about how you want to structure your state or how your data is structured on the server. This is something you need to create an abstraction for yourself as it differs just as much as user interfaces.\n\nFacets is a brand new thing and there will probably be many strategies taking advantage of it. I just wanted show you my thoughts on how you can use them.\n\n[Baobab](https://github.com/Yomguithereal/baobab) v1.0 is relased and [Baobab-React](https://github.com/Yomguithereal/baobab-react) is also released. Please check out the repo for more information and please share your ideas and thoughts on using facets to handle the state complexity of your application.\n"}});
//# sourceMappingURL=7.blog.js.map
|
src/svg-icons/maps/map.js
|
ruifortes/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsMap = (props) => (
<SvgIcon {...props}>
<path d="M20.5 3l-.16.03L15 5.1 9 3 3.36 4.9c-.21.07-.36.25-.36.48V20.5c0 .28.22.5.5.5l.16-.03L9 18.9l6 2.1 5.64-1.9c.21-.07.36-.25.36-.48V3.5c0-.28-.22-.5-.5-.5zM15 19l-6-2.11V5l6 2.11V19z"/>
</SvgIcon>
);
MapsMap = pure(MapsMap);
MapsMap.displayName = 'MapsMap';
MapsMap.muiName = 'SvgIcon';
export default MapsMap;
|
__tests__/components/NumberInput-test.js
|
kylebyerly-hp/grommet
|
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React from 'react';
import renderer from 'react-test-renderer';
import NumberInput from '../../src/js/components/NumberInput';
// needed because this:
// https://github.com/facebook/jest/issues/1353
jest.mock('react-dom');
describe('NumberInput', () => {
it('has correct default options', () => {
const component = renderer.create(
<NumberInput id="item2" name="item2" value={10} />
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
|
test/js/AR/release_test/ARPlaneTest.js
|
viromedia/viro
|
/**
* Copyright (c) 2017-present, Viro Media, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import {
ViroARScene,
ViroARPlane,
ViroMaterials,
ViroImage,
ViroARPlaneSelector,
ViroQuad,
ViroConstants,
ViroVideo,
ViroText,
ViroUtils
} from 'react-viro';
var createReactClass = require('create-react-class');
let polarToCartesian = ViroUtils.polarToCartesian;
var testARScene = createReactClass({
getInitialState: function() {
return {
pauseUpdates: false,
addPlane : true,
useFirstPlane : true,
updateMap : {width:0, height:0, position:[0,0,0]}, // used to update render props
displayMap : {width:0, height:0, position:[0,0,0]}, // used to display info
minValue : 0,
detectType : 0,
}
},
render: function() {
return (
<ViroARScene position={[0,0,0]} reticleEnabled={false} anchorDetectionTypes={this._getDetectType()} >
{this._getPlane()}
<ViroText position={polarToCartesian([6, 30, 10])} text={!this.state.addPlane ? "Add Plane" : "Remove Plane"}
style={styles.instructionText} transformBehaviors={["billboard"]} onClick={this._addRemovePlane}/>
<ViroText position={polarToCartesian([6, 30, 0])} text={"Switch Plane"}
style={styles.instructionText} transformBehaviors={["billboard"]} onClick={this._switchPlane}/>
<ViroText position={polarToCartesian([6, 30, -10])} text={"Min Width/Height: " + this.state.minValue}
style={styles.instructionText} transformBehaviors={["billboard"]} onClick={this._increaseMinValue}/>
<ViroText position={polarToCartesian([6, 30, -20])} text={this.state.pauseUpdates ? "Resume Updates" : "Pause Updates"}
style={styles.instructionText} transformBehaviors={["billboard"]}
onClick={()=>{this.setState({pauseUpdates : !this.state.pauseUpdates})}}/>
<ViroText position={polarToCartesian([6, 30, -30])} text={"Detect Type: " + this._getDetectType()}
style={styles.instructionText} transformBehaviors={["billboard"]}
onClick={this._changeDetectType}/>
<ViroText position={polarToCartesian([6, 0, 10])} text={this._getFoundText()}
style={styles.instructionText} transformBehaviors={["billboard"]}/>
<ViroText position={polarToCartesian([6, 0, 0])} text={this._getUpdatedText()}
style={styles.instructionText} transformBehaviors={["billboard"]}/>
<ViroText position={polarToCartesian([6, 0, -10])} text={this._getRemovedText()}
style={styles.instructionText} transformBehaviors={["billboard"]}/>
<ViroText position={polarToCartesian([6, 0, -20])} text={"No Callback"}
style={styles.instructionText} transformBehaviors={["billboard"]}
ref={component=>{this._callbackText = component}}/>
{/* Release Menu */}
<ViroText position={polarToCartesian([6, -30, 0])} text={"Next test"}
style={styles.instructionText} onClick={this._goToNextTest} transformBehaviors={["billboard"]}/>
<ViroText position={polarToCartesian([6, -30, -15])} text={"Release Menu"}
style={styles.instructionText} onClick={()=>{this.props.arSceneNavigator.replace("ARReleaseMenu", {scene: require("./ARReleaseMenu")})}}
transformBehaviors={["billboard"]}/>
</ViroARScene>
);
},
_changeDetectType() {
this.setState({
detectType : (this.state.detectType == 2) ? 0 : this.state.detectType + 1
})
},
_getDetectType() {
if (this.state.detectType == 0) {
return "PlanesHorizontal"
} else if (this.state.detectType == 1) {
return "PlanesVertical"
} else {
return "None"
}
},
_getPlane() {
let planes = []
if(this.state.addPlane) {
planes.push((
<ViroARPlane
minHeight={this.state.minValue}
minWidth={this.state.minValue}
alignment={this.state.detectType == 1 ? "Vertical" : "Horizontal"}
pauseUpdates={this.state.pauseUpdates}
key={this.state.useFirstPlane ? "firstPlane" : "secondPlane"}
onClick={this._setTextNatively("onClick")}
onHover={this._setTextNatively("onHover")}
onDrag={this._setTextNatively("onDrag")}
onPinch={this._setTextNatively("onPinch")}
onRotate={this._setTextNatively("onRotate")}
onAnchorFound={this._onAnchorFound}
onAnchorUpdated={this._onAnchorUpdated}
onAnchorRemoved={this._onAnchorRemoved} >
<ViroQuad
position={this.state.updateMap.center}
rotation={[-90, 0, 0]}
scale={[this.state.updateMap.width, this.state.updateMap.height, 1]}
materials={this.state.useFirstPlane ? "blue_plane" : "red_plane"}/>
</ViroARPlane>));
}
return planes;
},
_increaseMinValue() {
this.setState({
minValue : (this.state.minValue >= 3 ? 0 : this.state.minValue + .3),
})
},
_onAnchorFound() {
this.setState({
found : true,
});
},
_onAnchorUpdated(updateMap) {
let newState = {};
newState["displayMap"] = updateMap;
if (!this.state.pauseUpdates) {
newState["updateMap"] = updateMap;
}
this.setState(newState);
},
_onAnchorRemoved() {
this.setState({
removed : true,
})
},
_getFoundText() {
return "Plane Found: " + (this.state.found ? "true" : "false");
},
_getUpdatedText() {
return this.state.displayMap ? ("Width: " + this.state.displayMap.width + ", Height: " + this.state.displayMap.height) : "No Updates";
},
_getRemovedText() {
return "Plane Removed: " + (this.state.removed ? "true" : "false");
},
/*
We set text natively because some events update very quickly
*/
_setTextNatively(callbackType) {
return ()=> {
this._callbackText.setNativeProps({"text" : "Callback: " + callbackType})
}
},
_addRemovePlane() {
this.setState({
addPlane : !this.state.addPlane
});
},
_switchPlane() {
this.setState({
useFirstPlane : !this.state.useFirstPlane
})
},
_goToNextTest() {
this.props.arSceneNavigator.replace("ARPlaneManualTest", {scene:require("./ARPlaneManualTest")})
},
});
var styles = StyleSheet.create({
instructionText: {
fontFamily: 'Arial',
fontSize: 25,
width: 2,
color: '#cccccc',
flex: 1,
textAlignVertical: 'center',
textAlign: 'center',
},
});
ViroMaterials.createMaterials({
blue_plane: {
lightingModel: "Constant",
diffuseColor: "#0000ff50"
},
red_plane: {
lightingModel: "Constant",
diffuseColor: "#ff000050"
},
});
module.exports = testARScene;
|
frontend/src/components/post-changelog/toolbar.js
|
1905410/Misago
|
// jshint ignore:start
import React from 'react';
import Button from 'misago/components/button';
import escapeHtml from 'misago/utils/escape-html';
const DATE_ABBR = '<abbr title="%(absolute)s">%(relative)s</abbr>';
const USER_SPAN = '<span class="item-title">%(user)s</span>';
const USER_URL = '<a href="%(url)s" class="item-title">%(user)s</a>';
export default class extends React.Component {
goLast = () => {
this.props.goToEdit();
};
goForward = () => {
this.props.goToEdit(this.props.edit.next);
};
goBack = () => {
this.props.goToEdit(this.props.edit.previous);
};
revertEdit = () => {
this.props.revertEdit(this.props.edit.id);
}
render() {
return (
<div className="modal-toolbar">
<GoBackBtn
disabled={this.props.disabled}
edit={this.props.edit}
onClick={this.goBack}
/>
<GoForwardBtn
disabled={this.props.disabled}
edit={this.props.edit}
onClick={this.goForward}
/>
<GoLastBtn
disabled={this.props.disabled}
edit={this.props.edit}
onClick={this.goLast}
/>
<Label edit={this.props.edit} />
<RevertBtn
canRevert={this.props.canRevert}
disabled={this.props.disabled}
onClick={this.revertEdit}
/>
</div>
);
}
}
export function GoBackBtn(props) {
return (
<Button
className="btn-default btn-icon btn-sm pull-left"
disabled={props.disabled || !props.edit.previous}
onClick={props.onClick}
title={gettext("See previous change")}
>
<span className="material-icon">
chevron_left
</span>
</Button>
)
}
export function GoForwardBtn(props) {
return (
<Button
className="btn-default btn-icon btn-sm pull-left"
disabled={props.disabled || !props.edit.next}
onClick={props.onClick}
title={gettext("See previous change")}
>
<span className="material-icon">
chevron_right
</span>
</Button>
)
}
export function GoLastBtn(props) {
return (
<Button
className="btn-default btn-icon btn-sm pull-left"
disabled={props.disabled || !props.edit.next}
onClick={props.onClick}
title={gettext("See previous change")}
>
<span className="material-icon">
last_page
</span>
</Button>
)
}
export function RevertBtn(props) {
if (!props.canRevert) return null;
return (
<Button
className="btn-default btn-sm pull-right"
disabled={props.disabled}
onClick={props.onClick}
title={gettext("Revert post to state from before this edit.")}
>
{gettext("Revert")}
</Button>
)
}
export function Label(props) {
let user = null;
if (props.edit.url.editor) {
user = interpolate(USER_URL, {
url: escapeHtml(props.edit.url.editor),
user: escapeHtml(props.edit.editor_name)
}, true);
} else {
user = interpolate(USER_SPAN, {
user: escapeHtml(props.edit.editor_name)
}, true);
}
const date = interpolate(DATE_ABBR, {
absolute: escapeHtml(props.edit.edited_on.format('LLL')),
relative: escapeHtml(props.edit.edited_on.fromNow())
}, true);
const message = interpolate(escapeHtml(gettext("By %(edited_by)s %(edited_on)s.")), {
edited_by: user,
edited_on: date
}, true);
return (
<p
className="pull-left"
dangerouslySetInnerHTML={{__html: message}}
/>
);
}
|
src/components/WikipediaUI/WikipediaUI.js
|
Vargentum/react-redux-apps
|
import React from 'react'
import SearchBar from '../common/SearchBar'
import SearchResults from "../common/SearchResults"
import WikiArticlePreview from './WikiArticlePreview'
import ErrorArea from '../common/ErrorArea'
import {WIKI_RANDOM_ARTICLE_URL} from '../../redux/modules/Wikipedia'
type Props = {
results: PropTypes.array.isRequired,
error: ProptTypes.object,
loaded: PropTypes.bool,
loading: PropTypes.bool,
searchWiki: PropTypes.func
};
export class WikipediaUI extends React.Component {
props: Props;
render () {
const {
loading,
loaded,
searchWiki,
results,
error
} = this.props
return (
<div>
<SearchBar searchByToken={searchWiki}
randomResultUrl={WIKI_RANDOM_ARTICLE_URL} />
{loading ?
<h3 className="f-box f-align--1-2">Loading...</h3>
:
error ?
<ErrorArea error={error} />
:
loaded && !results.length ?
<h3 className="f-box f-align--1-2">Sorry, no results. Try another search.</h3>
:
<SearchResults data={results} Item={WikiArticlePreview} />
}
</div>
)
}
}
export default WikipediaUI
|
node_modules/@material-ui/styles/es/ServerStyleSheets/ServerStyleSheets.js
|
pcclarke/civ-techs
|
import _extends from "@babel/runtime/helpers/extends";
import React from 'react';
import { SheetsRegistry } from 'jss';
import StylesProvider from '../StylesProvider';
import createGenerateClassName from '../createGenerateClassName';
class ServerStyleSheets {
constructor(options = {}) {
this.options = options;
}
collect(children) {
// This is needed in order to deduplicate the injection of CSS in the page.
const sheetsManager = new Map(); // This is needed in order to inject the critical CSS.
this.sheetsRegistry = new SheetsRegistry(); // A new class name generator
const generateClassName = createGenerateClassName();
return React.createElement(StylesProvider, _extends({
sheetsManager: sheetsManager,
serverGenerateClassName: generateClassName,
sheetsRegistry: this.sheetsRegistry
}, this.options), children);
}
toString() {
return this.sheetsRegistry ? this.sheetsRegistry.toString() : '';
}
getStyleElement(props) {
return React.createElement('style', Object.assign({
id: 'jss-server-side',
key: 'jss-server-side',
dangerouslySetInnerHTML: {
__html: this.toString()
}
}, props));
}
}
export default ServerStyleSheets;
|
src/components/Feedback/Feedback.js
|
mcfa77y/isla_de_pescua
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Feedback.scss';
function Feedback() {
return (
<div className={s.root}>
<div className={s.container}>
<a
className={s.link}
href="https://gitter.im/kriasoft/react-starter-kit"
>Ask a question</a>
<span className={s.spacer}>|</span>
<a
className={s.link}
href="https://github.com/kriasoft/react-starter-kit/issues/new"
>Report an issue</a>
</div>
</div>
);
}
export default withStyles(Feedback, s);
|
client2/src/components/react-burger-menu/test/stack.spec.js
|
frolicking-ampersand/Board
|
'use strict';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { expect } from 'chai';
import createShallowComponent from './utils/createShallowComponent';
import BurgerMenu from '../lib/BurgerMenu';
const Menu = BurgerMenu.stack;
describe('stack', () => {
let component, menuWrap, menu, itemList, firstItem;
beforeEach(() => {
component = createShallowComponent(<Menu><div>An item</div></Menu>);
menuWrap = component.props.children[1];
});
it('has correct menuWrap styles', () => {
expect(menuWrap.props.style.position).to.equal('fixed');
expect(menuWrap.props.style.zIndex).to.equal(2);
expect(menuWrap.props.style.width).to.equal(300);
expect(menuWrap.props.style.height).to.equal('100%');
});
it('has correct menu styles', () => {
component = TestUtils.renderIntoDocument(<Menu><div>An item</div></Menu>);
menu = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-menu');
expect(menu.style.height).to.equal('100%');
expect(menu.style.boxSizing).to.equal('border-box');
});
it('has correct itemList styles', () => {
component = TestUtils.renderIntoDocument(<Menu pageWrapId={ 'page-wrap' } outerContainerId={ 'outer-container' }><div>An item</div></Menu>);
itemList = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-item-list');
expect(itemList.style.height).to.equal('100%');
});
it('has correct item styles', () => {
component = TestUtils.renderIntoDocument(<Menu><div>An item</div></Menu>);
firstItem = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-item-list').children[0];
expect(firstItem.style.display).to.equal('block');
expect(firstItem.style.outline).to.equal('none');
});
it('can be positioned on the right', () => {
component = TestUtils.renderIntoDocument(<Menu right><div>An item</div></Menu>);
menuWrap = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-menu-wrap');
expect(menuWrap.style.right).to.equal('0px');
});
});
|
components/Footer/Footer.js
|
BelwoodBakeryCafe/belwoodbakerycafe
|
/**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Link from '../Link';
function Footer() {
return (
<footer className="mdl-mini-footer">
<div className="mdl-mini-footer__left-section">
<div className="mdl-logo">© Company Name</div>
<ul className="mdl-mini-footer__link-list">
<li><Link to="/privacy">Privacy & Terms</Link></li>
<li><Link to="/not-found">Not Found</Link></li>
</ul>
</div>
<div className="mdl-mini-footer__right-section">
<ul className="mdl-mini-footer__link-list">
<li className="mdl-mini-footer--social-btn" style={{ backgroundColor: 'transparent' }}>
<a href="https://github.com/kriasoft/react-static-boilerplate" role="button" title="GitHub">
<svg width="36" height="36" viewBox="0 0 24 24">
<path
fill="#fff" d="M12,2A10,10 0 0,0 2,12C2,16.42 4.87,20.17 8.84,21.5C9.34,21.58
9.5,21.27 9.5,21C9.5,20.77 9.5,20.14 9.5,19.31C6.73,19.91 6.14,17.97 6.14,
17.97C5.68,16.81 5.03,16.5 5.03,16.5C4.12,15.88 5.1,15.9 5.1,15.9C6.1,15.97 6.63,
16.93 6.63,16.93C7.5,18.45 8.97,18 9.54,17.76C9.63,17.11 9.89,16.67 10.17,
16.42C7.95,16.17 5.62,15.31 5.62,11.5C5.62,10.39 6,9.5 6.65,8.79C6.55,8.54 6.2,
7.5 6.75,6.15C6.75,6.15 7.59,5.88 9.5,7.17C10.29,6.95 11.15,6.84 12,6.84C12.85,
6.84 13.71,6.95 14.5,7.17C16.41,5.88 17.25,6.15 17.25,6.15C17.8,7.5 17.45,8.54
17.35,8.79C18,9.5 18.38,10.39 18.38,11.5C18.38,15.32 16.04,16.16 13.81,
16.41C14.17,16.72 14.5,17.33 14.5,18.26C14.5,19.6 14.5,20.68 14.5,21C14.5,21.27
14.66,21.59 15.17,21.5C19.14,20.16 22,16.42 22,12A10,10 0 0,0 12,2Z"
/>
</svg>
</a>
</li>
<li className="mdl-mini-footer--social-btn" style={{ backgroundColor: 'transparent' }}>
<a href="https://twitter.com/ReactStatic" role="button" title="Twitter">
<svg width="36" height="36" viewBox="0 0 24 24">
<path
fill="#fff" d="M17.71,9.33C18.19,8.93 18.75,8.45 19,7.92C18.59,8.13 18.1,8.26
17.56,8.33C18.06,7.97 18.47,7.5 18.68,6.86C18.16,7.14 17.63,7.38 16.97,
7.5C15.42,5.63 11.71,7.15 12.37,9.95C9.76,9.79 8.17,8.61 6.85,7.16C6.1,8.38
6.75,10.23 7.64,10.74C7.18,10.71 6.83,10.57 6.5,10.41C6.54,11.95 7.39,12.69
8.58,13.09C8.22,13.16 7.82,13.18 7.44,13.12C7.81,14.19 8.58,14.86 9.9,15C9,15.76
7.34,16.29 6,16.08C7.15,16.81 8.46,17.39 10.28,17.31C14.69,17.11 17.64,13.95
17.71,9.33M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1
12,2Z"
/>
</svg>
</a>
</li>
</ul>
</div>
</footer>
);
}
export default Footer;
|
docs/build.js
|
nickuraltsev/react-bootstrap
|
/* eslint no-console: 0 */
import React from 'react';
import path from 'path';
import Router from 'react-router';
import routes from './src/Routes';
import Root from './src/Root';
import fsp from 'fs-promise';
import { copy } from '../tools/fs-utils';
import { exec } from '../tools/exec';
import metadata from './generate-metadata';
const repoRoot = path.resolve(__dirname, '../');
const docsBuilt = path.join(repoRoot, 'docs-built');
const license = path.join(repoRoot, 'LICENSE');
const readmeSrc = path.join(__dirname, 'README.docs.md');
const readmeDest = path.join(docsBuilt, 'README.md');
/**
* Generates HTML code for `fileName` page.
*
* @param {string} fileName Path for Router.Route
* @return {Promise} promise
* @internal
*/
function generateHTML(fileName, propData) {
return new Promise( resolve => {
const urlSlug = fileName === 'index.html' ? '/' : `/${fileName}`;
Router.run(routes, urlSlug, Handler => {
let html = React.renderToString(React.createElement(Handler, { propData }));
html = '<!doctype html>' + html;
let write = fsp.writeFile(path.join(docsBuilt, fileName), html);
resolve(write);
});
});
}
export default function BuildDocs({dev}) {
console.log('Building: '.cyan + 'docs'.green + (dev ? ' [DEV]'.grey : ''));
const devOption = dev ? '' : '-p';
return exec(`rimraf ${docsBuilt}`)
.then(() => fsp.mkdir(docsBuilt))
.then(metadata)
.then(propData => {
let pagesGenerators = Root.getPages().map( page => generateHTML(page, propData));
return Promise.all(pagesGenerators.concat([
exec(`webpack --config webpack.docs.js --bail ${devOption}`),
copy(license, docsBuilt),
copy(readmeSrc, readmeDest)
]));
})
.then(() => console.log('Built: '.cyan + 'docs'.green + (dev ? ' [DEV]'.grey : '')));
}
|
test/mochaTestHelper.js
|
mirimCZ/fifth
|
import Bluebird from 'bluebird';
import chai, {assert, expect} from 'chai';
import React from 'react';
import sinon from 'sinon';
import sinonAsPromised from 'sinon-as-promised';
import sinonChai from 'sinon-chai';
import TestUtils from 'react-addons-test-utils';
chai.should();
chai.use(sinonChai);
// Use Bluebird Promises inside of sinon stubs.
// Bluebird has better error reporting for unhandled Promises.
sinonAsPromised(Bluebird);
export {
assert,
chai,
expect,
React,
sinon,
sinonChai,
TestUtils
};
|
src/client.js
|
konstantin24121/replat
|
/* eslint react/jsx-filename-extension: "off" */
import 'babel-polyfill';
import 'config/logger';
import React from 'react';
import ReactDOM from 'react-dom';
import createStore from 'config/store';
import { AppContainer } from 'react-hot-loader';
import { browserHistory } from 'react-router';
import Root from './Root';
const dest = document.getElementById('app');
const store = createStore();
ReactDOM.render(
<AppContainer>
<Root store={store} history={browserHistory} />
</AppContainer>, dest
);
if (module.hot) {
module.hot.accept('./Root', () => {
// If you use Webpack 2 in ES modules mode, you can
// use <App /> here rather than require() a <NextApp />.
const NextApp = require('./Root').default;
ReactDOM.render(
<AppContainer>
<NextApp store={store} history={browserHistory} />
</AppContainer>,
dest
);
});
}
|
__tests__/common/util.spec.js
|
romagny13/react-form-validation
|
import React from 'react';
import { jsdom } from 'jsdom';
import { hasClassName, addClassName, removeClassName } from '../../src/common/util';
describe('util', () => {
it('check has class name', () => {
expect(hasClassName('', 'form-group')).toBeFalsy();
expect(hasClassName('form-group', 'form-group')).toBeTruthy();
expect(hasClassName('my-form form-group', 'form-group')).toBeTruthy();
});
it('should add class name', () => {
expect(addClassName('', 'form-group')).toEqual('form-group');
expect(addClassName('my-form', 'form-group')).toEqual('my-form form-group');
});
it('should remove class name', () => {
expect(removeClassName('form-group','form-group')).toEqual('');
expect(removeClassName('my-form form-group', 'form-group')).toEqual('my-form');
});
});
|
src/index.js
|
ssorallen/react-reddit-client
|
/* @flow */
import App from './App';
import React from 'react';
import ReactDOM from 'react-dom';
const root = document.getElementById('root');
if (root == null) throw new Error('Missing #root element in the DOM');
ReactDOM.render(<App />, root);
|
public/src/containers/selectArea/selectArea.js
|
white87332/react-redux-sample
|
import React from 'react';
import { findDOMNode } from 'react-dom';
import { forIn } from 'lodash';
import PropTypes from 'prop-types';
import { addEventListener, removeEventListener } from '../../utils/event';
// import Drag from '../drag/drag';
import createSelectable from './createSelectable';
class SelectArea extends React.Component
{
constructor(props, context)
{
super(props, context);
this.state = {
style: {
display: "none"
}
};
this.selectableItems = [];
this.act = null;
}
getChildContext()
{
// context可以將資料做父子間的上或下傳遞
return {
selectable: {
register: (key, domNode) => {
this.selectableItems.push(
{
key,
domNode
});
},
unregister: (key) => {
this.selectableItems = this.selectableItems.filter(data => data.key !== key);
}
}
};
}
componentDidMount()
{
addEventListener(this.refs.selectArea, 'mousedown', this.mouseDown.bind(this));
addEventListener(this.refs.selectArea, 'mousemove', this.mouseMove.bind(this));
addEventListener(this.refs.selectArea, 'mouseup', this.mouseUp.bind(this));
}
componentWillUnMount()
{
removeEventListener(this.refs.selectArea, 'mousedown', this.mouseDown.bind(this));
removeEventListener(this.refs.selectArea, 'mousemove', this.mouseMove.bind(this));
removeEventListener(this.refs.selectArea, 'mouseup', this.mouseUp.bind(this));
}
mouseDown(e)
{
e.stopPropagation();
this.act = "mouseDown";
this.initX = e.pageX || e.clientX;
this.initY = e.pageY || e.clientY;
}
mouseMove(e)
{
e.stopPropagation();
if(this.initX !== undefined && this.initY !== undefined)
{
this.act = "mouseMove";
let mousePosX = e.pageX || e.clientX;
let mousePosY = e.pageY || e.clientY;
// 邊距多遠
let left = Math.min(this.initX, mousePosX);
let top = Math.min(this.initY, mousePosY);
// 左或右邊的最大值
let tmpWidth = Math.max(this.initX, mousePosX);
let tmpHeight = Math.max(this.initY, mousePosY);
// 實際大小
let width = tmpWidth - left;
let height = tmpHeight - top;
this.setState({
style: {
position: 'absolute',
zIndex: 1,
display: "block",
border: "1px solid #999",
backgroundColor: "rgba(178, 178, 178, 0.3)",
left,
top,
width,
height
}
});
}
}
mouseUp(e)
{
e.stopPropagation();
this.initX = this.initY = undefined;
if(this.act === "mouseMove")
{
this.selectElements();
this.setState({
style: {
display: "none"
}
});
this.act = "mouseUp";
}
}
selectElements()
{
let selectedItems = [];
let selectDiv = findDOMNode(this.refs.selectDiv);
forIn(this.selectableItems, (dataObj) =>
{
// 判斷是否在圈選範圍內
if(this.collide(this.refs.selectDiv, dataObj.domNode))
{
selectedItems.push(dataObj.key);
}
});
this.props.onHandled(selectedItems);
}
collide(selectDiv, domNode)
{
return !(
((selectDiv.offsetTop + selectDiv.offsetHeight) < domNode.offsetTop) ||
((selectDiv.offsetTop) > (domNode.offsetTop + domNode.offsetHeight)) ||
((selectDiv.offsetLeft + selectDiv.offsetWidth) < domNode.offsetLeft) ||
((selectDiv.offsetLeft) > (domNode.offsetLeft + domNode.offsetWidth))
);
}
render()
{
return (
<div ref="selectArea">
<div ref="selectDiv" style={this.state.style} />
{this.props.children}
</div>
);
}
}
SelectArea.defaultProps = {};
SelectArea.propTypes = {
onHandled: PropTypes.func.isRequired
};
SelectArea.childContextTypes = {
selectable: PropTypes.object
};
export { SelectArea, createSelectable };
|
examples/1_router_route/index.js
|
losogudok/losogudok.github.io
|
import React from 'react'
import ReactDOM from 'react-dom'
import {Router, Route} from 'react-router'
import createHistory from 'history/createHashHistory'
const history = createHistory()
const App = () => (
<Router history={history}>
<div>
<Route path='/recipes' component={RecipesList} />
<Route path='/new' component={NewRecipe} />
</div>
</Router>
)
const RecipesList = () => (
<div>
<h1>
Рецепты
</h1>
<ul>
<li>Борщ</li>
<li>Утка по-пекински</li>
<li>Рыбы Фуга</li>
</ul>
</div>
)
const NewRecipe = () => (
<div>
<div>Новый рецепт</div>
<textarea name='recipe' id='recipe' cols="30" rows="10" placeholder='Напиши свой рецепт'></textarea>
</div>
)
ReactDOM.render(
<App/>,
document.getElementById('app')
)
|
src/frontend/components/CreateNewRoom.js
|
sauvala/chatterbox
|
import React, { Component } from 'react';
import { FormGroup, FormControl, InputGroup, Button } from 'react-bootstrap';
import '../styles/CreateNewRoom.css';
class CreateNewRoom extends Component {
constructor(props) {
super(props);
this.state = { newChannelName: '' };
this.onUpdateNewChannelName = this.onUpdateNewChannelName.bind(this);
this.onCreateNewChannel = this.onCreateNewChannel.bind(this);
}
onUpdateNewChannelName(event) {
this.setState({ newChannelName: event.target.value });
}
onCreateNewChannel() {
this.props.onCreateNewChannel(this.state.newChannelName);
this.setState({ newChannelName: '' });
}
render() {
const newChannelNameField = <FormControl type="text"
onChange={this.onUpdateNewChannelName}
onKeyPress={this.onKeyPressed}
value={this.state.newChannelName}
placeholder="New room name..." />;
const createNewChatRoomButton = <InputGroup.Button
onClick={this.onCreateNewChannel}>
<Button>Create</Button>
</InputGroup.Button>;
return (
<div>
<FormGroup className="create-new-room"
onSubmit={event => event.preventDefault()}>
<InputGroup>
{newChannelNameField}
{createNewChatRoomButton}
</InputGroup>
</FormGroup>
</div>
);
}
}
export default CreateNewRoom;
|
src/components/Layout/index.js
|
redux-saga/redux-saga-devtools
|
import React from 'react'
import styled from 'styled-components'
export const Row = styled.div`
margin: 0;
padding: 0;
white-space: nowrap;
width: 100%;
height: 100%;
`
export const Cell = styled.div`
display: inline-block;
vertical-align: top;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin: 0;
padding: 0;
`
|
examples/todomvc/src/components/TodoTextInput.spec.js
|
lifeiscontent/redux
|
import React from 'react'
import { createRenderer } from 'react-test-renderer/shallow';
import TodoTextInput from './TodoTextInput'
const setup = propOverrides => {
const props = Object.assign({
onSave: jest.fn(),
text: 'Use Redux',
placeholder: 'What needs to be done?',
editing: false,
newTodo: false
}, propOverrides)
const renderer = createRenderer()
renderer.render(
<TodoTextInput {...props} />
)
const output = renderer.getRenderOutput()
return {
props: props,
output: output,
renderer: renderer
}
}
describe('components', () => {
describe('TodoTextInput', () => {
it('should render correctly', () => {
const { output } = setup()
expect(output.props.placeholder).toEqual('What needs to be done?')
expect(output.props.value).toEqual('Use Redux')
expect(output.props.className).toEqual('')
})
it('should render correctly when editing=true', () => {
const { output } = setup({ editing: true })
expect(output.props.className).toEqual('edit')
})
it('should render correctly when newTodo=true', () => {
const { output } = setup({ newTodo: true })
expect(output.props.className).toEqual('new-todo')
})
it('should update value on change', () => {
const { output, renderer } = setup()
output.props.onChange({ target: { value: 'Use Radox' } })
const updated = renderer.getRenderOutput()
expect(updated.props.value).toEqual('Use Radox')
})
it('should call onSave on return key press', () => {
const { output, props } = setup()
output.props.onKeyDown({ which: 13, target: { value: 'Use Redux' } })
expect(props.onSave).toBeCalledWith('Use Redux')
})
it('should reset state on return key press if newTodo', () => {
const { output, renderer } = setup({ newTodo: true })
output.props.onKeyDown({ which: 13, target: { value: 'Use Redux' } })
const updated = renderer.getRenderOutput()
expect(updated.props.value).toEqual('')
})
it('should call onSave on blur', () => {
const { output, props } = setup()
output.props.onBlur({ target: { value: 'Use Redux' } })
expect(props.onSave).toBeCalledWith('Use Redux')
})
it('shouldnt call onSave on blur if newTodo', () => {
const { output, props } = setup({ newTodo: true })
output.props.onBlur({ target: { value: 'Use Redux' } })
expect(props.onSave).not.toBeCalled()
})
})
})
|
.storybook/Video.stories.js
|
constelation/monorepo
|
import React from 'react'
import { storiesOf, action } from '@kadira/storybook'
import Video from '../packages/Video/index.js'
// import Text from '../packages/Text/dist/Text.native.js'
storiesOf('Video', module)
.addWithInfo('plays a video', () => (
<Video src='http://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4' />
))
.addWithInfo('source child', () => (
<Video muted >
<source src='http://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4' type='video/mp4' />
</Video>
))
.addWithInfo('has controls and muted', () => (
<Video src='http://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4' controls muted />
))
.addWithInfo('repeat', () => (
<Video src='http://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4' controls muted repeat />
))
.add('pauses', () => {
class PlaysAndPauses extends React.Component {
state = {
paused: false
}
componentWillMount() {
setTimeout(() => this.setState( {paused: true} ), 3000)
}
render() {
return (
<Video
src='http://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4'
paused={this.state.paused}
controls
muted
/>
)
}
}
return (
<PlaysAndPauses />
)
})
|
ui/components/Loading.js
|
nlhuykhang/apollo-react-quotes-client
|
import React from 'react';
export default () => (
<div>Loading...</div>
);
|
src/index.js
|
vsmode/pixels
|
import React from 'react';
import { render } from 'react-dom';
import { createStore } from 'redux';
import { injectGlobal } from 'styled-components';
import fastclick from 'react-fastclick';
import reducer from './reducers';
import initKeyboard from './keyboard';
import createInitialState from './store/state';
import App from './components/App';
const store = createStore(
reducer,
createInitialState({
width: 8,
height: 8,
frameCount: 4
}),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
const init = () => {
fastclick(); // make mobile safari responsive to touch events
window.addEventListener('contextmenu', e => e.preventDefault());
initKeyboard(store);
injectGlobal`
* {
box-sizing: border-box;
user-select: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-overflow-scrolling: touch;
touch-action: manipulation;
}
html, body {
position: fixed;
overflow: hidden;
height: 100vh;
margin: 0;
font-family: 'Source Sans Pro', Helvetica, sans-serif;
}
main {
width: 100vw;
height: 100vh;
overflow-y: scroll;
}
`;
};
const run = update => {
store.subscribe(update);
update();
};
/**
* Let the pixel editing begin!
*/
init();
run(() => {
render(
<App {...store.getState()} dispatch={store.dispatch} />,
document.getElementById('root')
);
});
if (module.hot) module.hot.accept(run);
|
src/dumb/common/Floated.js
|
jeckhummer/wf-constructor
|
import React from 'react';
export const Floated = ({right, children, style}) => {
const direction = right !== undefined ? 'right' : 'left';
return (
<div style={{float: direction, ...style}}>
{children}
</div>
);
};
|
src/client/routes/Home/components/HomeView.js
|
jaimerosales/visual-reports-bim360dc
|
import { IndexLink, Link } from 'react-router'
import React from 'react'
import './HomeView.scss'
class HomeView extends React.Component {
/////////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////////
constructor() {
super()
this.state = {
models: [
{
thumbnail: 'resources/img/Office.png',
// PRODUCTION
//urn: 'dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6YWVjbW9kZWxzLXZpc3VhbHJlcG9ydHMtcHJvZGtlcGg5eHZ3a3BvbDJrZm9memd2ZHUwZ3hpa2RqdWc4L1VyYmFuSG91c2UtMjAxNS5ydnQ',
// DEVELOPMENT
urn: 'dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6amFpbWV2aXN1YWxyZXBzYmltMzYwZG9jczFnc2Jtb3NlYnp4a2cyY3RhNW0wZWtsMDNubXN6dzF0L1VyYmFuSG91c2UtMjAxNS5ydnQ',
thumbnailClass: 'office-thumbnail',
name: 'Office'
}
]
}
}
/////////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////////
render() {
return (
<div className="home">
<img className='logo-hero'/>
<div className="models">
<div className="title">
Choose Model
</div>
<div className="content responsive-grid">
{
this.state.models.map((model, idx) => {
return (
<Link key={idx} to={`/viewer?urn=${model.urn}`}>
<figure>
<figcaption>
{model.name}
</figcaption>
<img className={model.thumbnailClass || 'default-thumbnail'}
src={model.thumbnail || ''}/>
</figure>
</Link>)
})
}
</div>
</div>
</div>
)
}
}
export default HomeView
|
src/js/Papers/__tests__/Paper.js
|
lwhitlock/grow-tracker
|
/* eslint-env jest */
jest.unmock('../Paper');
import React from 'react';
import { findDOMNode } from 'react-dom';
import {
renderIntoDocument,
} from 'react-dom/test-utils';
import Paper from '../Paper';
describe('Paper', () => {
it('merges className and style', () => {
const props = {
style: { background: 'black' },
className: 'test',
};
const paper = renderIntoDocument(<Paper {...props} />);
const paperNode = findDOMNode(paper);
expect(paperNode.style.background).toBe(props.style.background);
expect(paperNode.className).toContain(props.className);
});
});
|
app/sidebar/components/Controls.js
|
Raymond-Zhu/music-video-app
|
import React, { Component } from 'react';
export default class Controls extends Component {
constructor(props) {
super(props);
this.state = {paused: true};
this.handleTouch = this.handleTouch.bind(this);
}
handleTouch() {
if(this.state.paused) {
this.setState({paused: false});
} else {
this.setState({paused: true});
}
}
render() {
return (
<div>
<div onTouchTap={this.handleTouch}>
{this.state.paused ? "Play" : "Pause"}
</div>
<div onTouchTap={this.props.removeFromQueue}>Next</div>
</div>
)
}
}
|
public/ind.js
|
viktorkh/elastickit_express
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './search_react';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
blueocean-material-icons/src/js/components/svg-icons/av/repeat-one.js
|
kzantow/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const AvRepeatOne = (props) => (
<SvgIcon {...props}>
<path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4zm-4-2V9h-1l-2 1v1h1.5v4H13z"/>
</SvgIcon>
);
AvRepeatOne.displayName = 'AvRepeatOne';
AvRepeatOne.muiName = 'SvgIcon';
export default AvRepeatOne;
|
src/components/AdminProxy/index.js
|
u-wave/web
|
import React from 'react';
import PropTypes from 'prop-types';
import CircularProgress from '@mui/material/CircularProgress';
import Overlay from '../Overlay';
import OverlayHeader from '../Overlay/Header';
const { lazy, Suspense } = React;
const AdminComponent = lazy(() => (
import('../../admin/containers/AdminApp')
));
const Fallback = () => <CircularProgress size="100%" />;
const AdminProxy = ({ onCloseOverlay }) => (
<Overlay className="AppColumn AppColumn--full" direction="top">
<OverlayHeader
title="Administration"
onCloseOverlay={onCloseOverlay}
direction="top"
/>
<div className="AdminPanel">
<Suspense fallback={<Fallback />}>
<AdminComponent />
</Suspense>
</div>
</Overlay>
);
AdminProxy.propTypes = {
onCloseOverlay: PropTypes.func.isRequired,
};
export default AdminProxy;
|
docs/src/app/components/pages/components/AppBar/ExampleIcon.js
|
ArcanisCz/material-ui
|
import React from 'react';
import AppBar from 'material-ui/AppBar';
/**
* A simple example of `AppBar` with an icon on the right.
* By default, the left icon is a navigation-menu.
*/
const AppBarExampleIcon = () => (
<AppBar
title="Title"
iconClassNameRight="muidocs-icon-navigation-expand-more"
/>
);
export default AppBarExampleIcon;
|
imports/ui/components/categories/timeline-categories-list-items.js
|
irvinlim/free4all
|
import React from 'react';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import ArrowDropRight from 'material-ui/svg-icons/navigation-arrow-drop-right';
import * as IconsHelper from '../../../util/icons';
import * as CategoriesHelper from '../../../util/categories';
const ListItem = (category, isChild) => (
<MenuItem
key={ category._id }
value={ category._id }
primaryText={ category.name }
insetChildren={ isChild }
/>
);
export const TimelineCategoriesListItems = ({ itemsFilter }) => {
let cats = CategoriesHelper.getOrderedParentCategories();
if (itemsFilter)
cats = itemsFilter(cats);
const items = [];
cats.forEach(cat => {
items.push(cat);
CategoriesHelper.getOrderedChildCategoriesOf(cat).forEach(child => items.push(child));
});
return items.map(cat => ListItem(cat, !!cat.parent));
};
|
client/src/components/Toolbar/Toolbar.js
|
silverstripe/silverstripe-admin
|
import React from 'react';
import PropTypes from 'prop-types';
import BackButton from 'components/Button/BackButton';
/**
* Display a toolbar with some children, usually a breadcrumb or some actions.
*/
const Toolbar = ({ showBackButton, children, onBackButtonClick }) => {
const onClick = (e) => {
e.preventDefault();
if (typeof onBackButtonClick === 'function') {
onBackButtonClick(e);
}
};
return (
<div className="toolbar toolbar--north">
<div className="toolbar__navigation fill-width">
{showBackButton && <BackButton onClick={onClick} className="toolbar__back-button" />}
{children}
</div>
</div>
);
};
Toolbar.propTypes = {
onBackButtonClick: PropTypes.func,
showBackButton: PropTypes.bool
};
Toolbar.defaultProps = {
showBackButton: false,
};
export default Toolbar;
|
examples/forms-bootstrap/src/components/Layout.js
|
lore/lore-forms
|
/**
* This component is intended to reflect the high level structure of your application,
* and render any components that are common across all views, such as the header or
* top-level navigation. All other components should be rendered by route handlers.
**/
import React from 'react';
import createReactClass from 'create-react-class';
import Navigation from './Navigation';
export default createReactClass({
displayName: 'Layout',
render: function() {
return (
<div>
<nav className="navbar navbar-default navbar-static-top header">
<div className="container">
<div className="navbar-header">
<a className="navbar-brand" href="/">Lore Example: Bootstrap Forms & Dialogs</a>
</div>
</div>
</nav>
<div className="container">
<div className="row">
<div className="col-md-2">
<Navigation/>
</div>
<div className="col-md-10">
{React.cloneElement(this.props.children)}
</div>
</div>
</div>
</div>
);
}
});
|
examples/src/components/ValuesAsNumbersField.js
|
webcoding/react-select
|
import React from 'react';
import Select from 'react-select';
function logChange() {
console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments)));
}
var ValuesAsNumbersField = React.createClass({
displayName: 'ValuesAsNumbersField',
propTypes: {
label: React.PropTypes.string
},
getInitialState () {
return {
options: [
{ value: 10, label: 'Ten' },
{ value: 11, label: 'Eleven' },
{ value: 12, label: 'Twelve' },
{ value: 23, label: 'Twenty-three' },
{ value: 24, label: 'Twenty-four' }
],
matchPos: 'any',
matchValue: true,
matchLabel: true,
value: null,
multi: false
};
},
onChangeMatchStart(event) {
this.setState({
matchPos: event.target.checked ? 'start' : 'any'
});
},
onChangeMatchValue(event) {
this.setState({
matchValue: event.target.checked
});
},
onChangeMatchLabel(event) {
this.setState({
matchLabel: event.target.checked
});
},
onChange(value, values) {
this.setState({
value: value
});
logChange(value, values);
},
onChangeMulti(event) {
this.setState({
multi: event.target.checked
});
},
render () {
var matchProp = 'any';
if (this.state.matchLabel && !this.state.matchValue) {
matchProp = 'label';
}
if (!this.state.matchLabel && this.state.matchValue) {
matchProp = 'value';
}
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select
searchable={true}
matchProp={matchProp}
matchPos={this.state.matchPos}
options={this.state.options}
onChange={this.onChange}
value={this.state.value}
multi={this.state.multi}
/>
<div className="checkbox-list">
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.multi} onChange={this.onChangeMulti} />
<span className="checkbox-label">Multi-Select</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchValue} onChange={this.onChangeMatchValue} />
<span className="checkbox-label">Match value only</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchLabel} onChange={this.onChangeMatchLabel} />
<span className="checkbox-label">Match label only</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchPos === 'start'} onChange={this.onChangeMatchStart} />
<span className="checkbox-label">Only include matches from the start of the string</span>
</label>
</div>
</div>
);
}
});
module.exports = ValuesAsNumbersField;
|
src/helpers/react-widgets/DropdownList/component_renderers.js
|
dannyrdalton/example_signup_flow
|
import React from 'react'
export const imageAndText = (props) => (
<span>
<span>{props.item.value}</span><img src={props.item.imgSrc} style={{ height: '100px', paddingLeft: '20px' }}/>
</span>
)
export const REACT_WIDGETS_DROPDOWN_LIST_COMPONENT_RENDERERS = {
imageAndText
}
export default REACT_WIDGETS_DROPDOWN_LIST_COMPONENT_RENDERERS
|
examples/universal/server/server.js
|
joaomilho/redux
|
/* eslint-disable no-console, no-use-before-define */
import path from 'path'
import Express from 'express'
import qs from 'qs'
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import webpackConfig from '../webpack.config'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'
import configureStore from '../common/store/configureStore'
import App from '../common/containers/App'
import { fetchCounter } from '../common/api/counter'
const app = new Express()
const port = 3000
// Use this middleware to set up hot module reloading via webpack.
const compiler = webpack(webpackConfig)
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath }))
app.use(webpackHotMiddleware(compiler))
// This is fired every time the server side receives a request
app.use(handleRender)
function handleRender(req, res) {
// Query our mock API asynchronously
fetchCounter(apiResult => {
// Read the counter from the request, if provided
const params = qs.parse(req.query)
const counter = parseInt(params.counter, 10) || apiResult || 0
// Compile an initial state
const initialState = { counter }
// Create a new Redux store instance
const store = configureStore(initialState)
// Render the component to a string
const html = renderToString(
<Provider store={store}>
<App />
</Provider>
)
// Grab the initial state from our Redux store
const finalState = store.getState()
// Send the rendered page back to the client
res.send(renderFullPage(html, finalState))
})
}
function renderFullPage(html, initialState) {
return `
<!doctype html>
<html>
<head>
<title>Redux Universal Example</title>
</head>
<body>
<div id="app">${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}
</script>
<script src="/static/bundle.js"></script>
</body>
</html>
`
}
app.listen(port, (error) => {
if (error) {
console.error(error)
} else {
console.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`)
}
})
|
app/components/dashboardproject/manageKeys.js
|
ritishgumber/dashboard-ui
|
'use strict';
import React from 'react';
import {connect} from 'react-redux';
import OptionsModal from './optionsModal';
import PersonAdd from 'material-ui/svg-icons/social/person-add';
import {Modal, Button} from 'react-bootstrap';
class DeleteApp extends React.Component {
constructor(props) {
super(props);
this.state = {
buttonState: false
};
}
handleKeyChange(e) {
if (e.keyCode === 13 && !this.props.deleteButtonState)
this.props.onDelete(this.props.appId)
}
render() {
return (
<Modal show={this.props.show} dialogClassName='developers-modal' onHide={this.props.close}>
<Modal.Header style={{
paddingTop: 10
}} className="modal-header-style">
<Modal.Title>
<span className="modal-title-style">
App Keys
</span>
<img className="key-modal-icon-style pull-right"></img>
<div className="modal-title-inner-text">Use these keys to initialize your app.
</div>
</Modal.Title>
</Modal.Header>
<Modal.Body>
<OptionsModal loading={this.props.loading} id={this.props.id} appId={this.props.appId} masterKey={this.props.masterKey} clientKey={this.props.clientKey} planId={this.props.planId} developers={this.props.developers} invited={this.props.invited} selectedTab={this.props.selectedTab}/>
</Modal.Body>
</Modal>
);
}
}
const mapStateToProps = (state) => {
return {};
};
const mapDispatchToProps = (dispatch) => {
return {};
};
export default connect(mapStateToProps, mapDispatchToProps)(DeleteApp);
|
Client/src/components/App.js
|
MarcosBessega/vootodo
|
import React from 'react'
import {Provider} from 'react-redux'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import ToolBar from './toolbar'
const Root = ({store}) => (
<Provider store={store}>
<MuiThemeProvider>
<ToolBar />
</MuiThemeProvider>
</Provider>
)
export default Root
|
app/components/Footer/index.js
|
rajeshbhatt/shopping-cart-redux
|
import React from 'react';
import { FormattedMessage } from 'react-intl';
import A from 'components/A';
import LocaleToggle from 'containers/LocaleToggle';
import Wrapper from './Wrapper';
import messages from './messages';
function Footer() {
return (
<Wrapper>
<section>
<FormattedMessage {...messages.licenseMessage} />
</section>
<section>
<LocaleToggle />
</section>
<section>
<FormattedMessage
{...messages.authorMessage}
values={{
author: <A href="https://twitter.com/mxstbr">Max Stoiber</A>,
}}
/>
</section>
</Wrapper>
);
}
export default Footer;
|
src/svg-icons/maps/directions-run.js
|
ruifortes/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsDirectionsRun = (props) => (
<SvgIcon {...props}>
<path d="M13.49 5.48c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-3.6 13.9l1-4.4 2.1 2v6h2v-7.5l-2.1-2 .6-3c1.3 1.5 3.3 2.5 5.5 2.5v-2c-1.9 0-3.5-1-4.3-2.4l-1-1.6c-.4-.6-1-1-1.7-1-.3 0-.5.1-.8.1l-5.2 2.2v4.7h2v-3.4l1.8-.7-1.6 8.1-4.9-1-.4 2 7 1.4z"/>
</SvgIcon>
);
MapsDirectionsRun = pure(MapsDirectionsRun);
MapsDirectionsRun.displayName = 'MapsDirectionsRun';
MapsDirectionsRun.muiName = 'SvgIcon';
export default MapsDirectionsRun;
|
src/Root.js
|
Syncano/syncano-dashboard
|
import React from 'react';
import { Router, useRouterHistory } from 'react-router';
import createHistory from 'history/lib/createHashHistory';
import routes from './routes';
import useNamedRoutes from 'use-named-routes';
const history = useNamedRoutes(useRouterHistory(createHistory))({ routes });
const Root = () => (
<Router history={history} routes={routes} />
);
export default Root;
|
app/containers/Minna/layout/footer.js
|
oliverox/react99
|
import React from 'react';
import { Link } from 'react-router';
import moment from 'moment';
/**
* Layout: Footer
*
* Display a the site's footer
*/
export default class Footer extends React.Component { // eslint-disable-line
render() {
return (
<footer id="main-footer">
© {moment().format('YYYY')} <Link to="dashboard">Minna Theme</Link> | <Link to="privacy-policy">Privacy Policy</Link>
</footer>
);
}
}
|
src/components/Success.js
|
ericyd/gdrive-copy
|
/**
* Success message container
*/
'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import Alert from './Alert';
import Checkmark from './icons/Checkmark';
import Star from './icons/Star';
export default function Success(props) {
return (
<Alert
label={'Success! ' + props.msg}
className="alert--success"
icon={<Checkmark />}
>
{props.children}
</Alert>
);
}
Success.propTypes = {
msg: PropTypes.string
};
|
src/components/FabButton/index.js
|
RodolfoSilva/DeVryCalc
|
import React from 'react'
import IconButton from '../IconButton'
import styles from './styles'
let FabButton = ({ name, style, ...props }) => (
<IconButton name={name} style={[styles.container, style]} {...props} />
)
FabButton.propTypes = {
...IconButton.propTypes
}
export default FabButton
|
src/components/MainPage/AboutPattern.js
|
cindyqian/BoardGames
|
import React from 'react';
import {connect} from 'react-redux'
import cs from '../../services/CommunicationService'
import RemoteService from '../../services/RemoteService'
import Footer from './Footer';
/**
*
*/
class _AboutPattern extends React.Component{
componentDidMount(tabId) {
let self = this;
RemoteService.fatchThroughProxy("https://raw.githubusercontent.com/coolshare/ReactReduxPattern/master/README.md", {"callback":function(data) {
self.refs.aboutPattern.innerHTML = data;
}})
}
/**
* render
* @return {ReactElement} markup
*/
render(){
return (
<div style={{"height":"500px", "overflow":"auto"}}>
<pre ref="aboutPattern">
{this.props.aboutPattern===undefined?"":this.props.aboutPattern}
</pre>
</div>
)
}
}
const AboutPattern = connect(
store => {
return {
aboutPattern: store.MainContainerReducer.aboutPattern
};
}
)(_AboutPattern);
export default AboutPattern
|
test/utils/CustomPropTypesSpec.js
|
bvasko/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import CustomPropTypes from '../../src/utils/CustomPropTypes';
import {shouldWarn} from '../helpers';
function isChainableAndUndefinedOK(validatorUnderTest) {
it('Should validate OK with undefined or null values', () => {
assert.isUndefined(validatorUnderTest({}, 'p', 'Component'));
assert.isUndefined(validatorUnderTest({p: null}, 'p', 'Component'));
});
it('Should be able to chain', () => {
let err = validatorUnderTest.isRequired({}, 'p', 'Component');
assert.instanceOf(err, Error);
assert.include(err.message, 'Required prop');
assert.include(err.message, 'was not specified in');
});
}
describe('CustomPropTypes', () => {
describe('mountable', () => {
function validate(prop) {
return CustomPropTypes.mountable({p: prop}, 'p', 'Component');
}
isChainableAndUndefinedOK(CustomPropTypes.mountable);
it('Should return error with non mountable values', () => {
let err = validate({});
assert.instanceOf(err, Error);
assert.include(err.message, 'expected a DOM element or an object that has a `render` method');
});
it('Should return undefined with mountable values', () => {
assert.isUndefined(validate(document.createElement('div')));
assert.isUndefined(validate(document.body));
assert.isUndefined(validate(ReactTestUtils.renderIntoDocument(<div />)));
});
});
describe('elementType', () => {
function validate(prop) {
return CustomPropTypes.elementType({p: prop}, 'p', 'TestComponent');
}
isChainableAndUndefinedOK(CustomPropTypes.elementType);
it('Should validate OK with elementType values', () => {
assert.isUndefined(validate('span'));
assert.isUndefined(validate(() => {}));
});
it('Should return error with not a string or function values', () => {
let err = validate({});
assert.instanceOf(err, Error);
assert.include(err.message, 'Expected an Element `type` such as a tag name or return value of React.createClass(...)');
});
it('Should return error with react element', () => {
let err = validate(React.createElement('span'));
assert.instanceOf(err, Error);
assert.include(err.message, 'Expected an Element `type`, not an actual Element');
});
});
describe('keyOf', () => {
let obj = {'foo': 1};
function validate(prop) {
return CustomPropTypes.keyOf(obj)({p: prop}, 'p', 'Component');
}
isChainableAndUndefinedOK(CustomPropTypes.keyOf(obj));
it('Should return error with non-key values', () => {
let err = validate('bar');
assert.instanceOf(err, Error);
assert.include(err.message, 'expected one of ["foo"]');
});
it('Should validate OK with key values', () => {
assert.isUndefined(validate('foo'));
obj.bar = 2;
assert.isUndefined(validate('bar'));
});
});
describe('singlePropFrom', () => {
function validate(testProps) {
const propList = ['children', 'value'];
return CustomPropTypes.singlePropFrom(propList)(testProps, 'value', 'Component');
}
it('Should validate OK if only one listed prop in used', () => {
const testProps = {value: 5};
assert.isUndefined(validate(testProps));
});
it('Should return error if multiple of the listed properties have values', () => {
let err = validate({value: 5, children: 5});
assert.instanceOf(err, Error);
assert.include(err.message, 'only one of the following may be provided: value and children');
});
});
describe('all', () => {
let validators;
const props = {
key: 'value'
};
const propName = 'key';
const componentName = 'TestComponent';
beforeEach(() => {
validators = [
sinon.stub(),
sinon.stub(),
sinon.stub()
];
});
it('with no arguments provided', () => {
expect(() => {
CustomPropTypes.all();
}).to.throw(Error, /No validations provided/);
});
it('with no validations provided', () => {
expect(() => {
CustomPropTypes.all([]);
}).to.throw(Error, /No validations provided/);
});
it('with invalid arguments provided', () => {
expect(() => {
CustomPropTypes.all(1);
}).to.throw(Error, /Invalid argument must be an array/);
});
it('validates each validation', () => {
const all = CustomPropTypes.all(validators);
let result = all(props, propName, componentName);
expect(result).to.equal(undefined);
validators.forEach(x => {
x.should.have.been.calledOnce
.and.calledWith(props, propName, componentName);
});
});
it('returns first validation failure', () => {
let err = new Error('Failure');
validators[1].returns(err);
const all = CustomPropTypes.all(validators);
let result = all(props, propName, componentName);
expect(result).to.equal(err);
validators[0].should.have.been.calledOnce
.and.calledWith(props, propName, componentName);
validators[1].should.have.been.calledOnce
.and.calledWith(props, propName, componentName);
validators[2].should.not.have.been.called;
});
});
describe('isRequiredForA11y', () => {
function validate(prop) {
return CustomPropTypes.isRequiredForA11y(React.PropTypes.string)({p: prop}, 'p', 'Component');
}
it('Should validate OK when property is provided', () => {
let err = validate('aria-tag');
assert.notInstanceOf(err, Error);
});
it('Should return custom error message when property is not provided', () => {
let err = validate(null);
assert.instanceOf(err, Error);
assert.include(err.message, 'accessible for users using assistive technologies such as screen readers');
});
});
describe('deprecated', () => {
function validate(prop) {
return CustomPropTypes.deprecated(React.PropTypes.string, 'Read more at link')({pName: prop}, 'pName', 'ComponentName');
}
it('Should warn about deprecation and validate OK', () => {
let err = validate('value');
shouldWarn('"pName" property of "ComponentName" has been deprecated.\nRead more at link');
assert.notInstanceOf(err, Error);
});
it('Should warn about deprecation and throw validation error when property value is not OK', () => {
let err = validate({});
shouldWarn('"pName" property of "ComponentName" has been deprecated.\nRead more at link');
assert.instanceOf(err, Error);
assert.include(err.message, 'Invalid undefined `pName` of type `object` supplied to `ComponentName`');
});
});
});
|
packages/es-components/src/components/containers/notification/Notification.js
|
jrios/es-components
|
import React from 'react';
import PropTypes from 'prop-types';
import { noop } from 'lodash';
import { useNotification } from './useNotification';
const DefaultNotification = useNotification();
function Notification(props) {
return <DefaultNotification {...props} />;
}
Notification.propTypes = {
/* The type of notification to render */
type: PropTypes.oneOf(['success', 'info', 'warning', 'danger', 'advisor'])
.isRequired,
/* Display an icon in the notification on a screen >= 768px */
includeIcon: PropTypes.bool,
/* Display a dismiss button that will close the notification */
isDismissable: PropTypes.bool,
role: PropTypes.oneOf(['dialog', 'alert']),
/* Function to execute when the dialog is closed */
onDismiss: PropTypes.func,
children: PropTypes.node
};
Notification.defaultProps = {
includeIcon: false,
isDismissable: false,
children: null,
role: 'dialog',
onDismiss: noop
};
export default Notification;
|
src/index.js
|
zfanta/react-sequence-diagram
|
import React, { Component } from 'react';
import Diagram from './sequence-diagram-2.0.1';
class SequenceDiagram extends Component {
componentDidUpdate() {
if (!this.div) return;
const { input, options } = this.props;
if (this.div.children[0]){
this.div.removeChild(this.div.children[0]);
}
try {
const diagram = Diagram.parse(input);
diagram.drawSVG(this.div, options);
} catch(err) {
this.processError(err);
}
}
componentDidMount() {
const { input, options } = this.props;
try {
const diagram = Diagram.parse(input);
if (this.div) {
diagram.drawSVG(this.div, options)
}
} catch(err) {
this.processError(err);
}
}
processError(err) {
//use same annotation object as https://bramp.github.io/js-sequence-diagrams/
var annotation = {
type: "error", // also warning and information
column: 0,
row: 0,
text: err.message
};
if (err instanceof Diagram.ParseError) {
annotation.row = err.loc.first_line - 1;
annotation.column = err.loc.first_column;
}
if (typeof this.props.onError === 'function') {
this.props.onError(annotation);
}
}
render() {
return <div className={this.props.className} ref={div => { this.div = div }} />
}
}
export default SequenceDiagram;
|
src/routes.js
|
justboris/isomorphic-react-redux-app
|
/* eslint react/jsx-filename-extension: 0 */
import React from 'react';
import { IndexRoute, Route } from 'react-router';
import {
App,
Home,
About,
Testing,
NotFound,
} from './containers';
export default (store) => { // eslint-disable-line
return (
<Route path="/" component={App}>
{ /* Home (main) route */ }
<IndexRoute component={Home} />
<Route path="/about" component={About} />
<Route path="/testing" component={Testing} />
{ /* Catch all route */ }
<Route path="*" component={NotFound} status={404} />
</Route>
);
};
|
packages/react/src/components/FormatJson.js
|
wq/wq.app
|
import React from 'react';
import PropTypes from 'prop-types';
export default function FormatJson({ json }) {
return (
<pre>
<code>{JSON.stringify(json, null, 4)}</code>
</pre>
);
}
FormatJson.propTypes = {
json: PropTypes.object
};
|
src/components/ProfessionalPage.js
|
W01fw00d/w01fw00d_portfolio
|
import React, { Component } from 'react';
import '../stylesheets/ProfessionalPage.css';
import Gallery from './Gallery';
import edreams_gif1 from '../assets/gallery/edreams1.gif';
import edreams_gif2 from '../assets/gallery/edreams2.gif';
import esbaluard_gif1 from '../assets/gallery/esbaluard1.gif';
import esbaluard_gif2 from '../assets/gallery/esbaluard2.gif';
const galleries = {
edreams: {
modalTitle: 'eDreams',
paragraphs: [
'This is the flights ecommerce eDreams site. I worked in this project for a year, ' +
'as a Full-Stack Web Developer in “Brújula Tecnologías de la Información”, ' +
'working remotely full-time with only one client: “eDreams Odigeo”, ' +
'integrated in one of its Front-end development teams.',
'We used Kanban as an Agile Methodology, and Mercurial for version control. ' +
'I performed maintenance and development of new ' +
'products for the eDreams site, in a fast iterative process with A/B tests. ' +
'I worked with Javascript (Backbone framework) in the Front-End and ' +
'with Java in order to receive the data from the API, in desktop as well as mobile versions of eDreams. ' +
'I developed and fixed automatic tests with Cucumber (as well as unit tests with Java), ' +
'that covered the web functionality. I improved its efficiency too, refactoring legacy code.'
],
links: [
{
label: 'Visit eDreams',
url: 'https://www.edreams.com/'
},
{
label: 'Visit Brújula',
url: 'http://www.brujula.es/'
}
],
images: [
edreams_gif1,
edreams_gif2
]
},
esbaluard: {
modalTitle: 'Es Baluard',
description: 'This is the official site of the "Es Baluard" museum. I worked in this project while training as a web developer in Kamalyon.',
paragraphs: [
'I developed a PHP web, using a Wordpress template that I modified in order to implement ' +
'a Masonry gallery, sliders, filters, Google Maps pluggin, Twitter… ' +
'I created custom postypes to adapt the web content to the client needs, ' +
'so that way all content would be dynamic and the client would be able to modify them themselves.',
'The web includes an interactive museum map which markers that link to anchors on each section of the post.'
],
links: [
{
label: 'Visit Es Baluard',
url: 'http://www.esbaluard.org/'
},
{
label: 'Visit Kamalyon',
url: 'http://kamalyon.com/'
}
],
images: [
esbaluard_gif1,
esbaluard_gif2
]
}
},
email = 'romay.gabriel@gmail.com'; ;
class ProfessionalPage extends Component {
render() {
return (
<div className="ProfessionalPage">
<h3 className="margin-top"> Professional Projects </h3>
<div className="margin-top">
<Gallery
url={galleries.edreams.url}
images={galleries.edreams.images}
modalTitle={galleries.edreams.modalTitle}
paragraphs={galleries.edreams.paragraphs}
links={galleries.edreams.links}
/>
</div>
<div className="margin-top">
<Gallery
url={galleries.esbaluard.url}
images={galleries.esbaluard.images}
modalTitle={galleries.esbaluard.modalTitle}
paragraphs={galleries.esbaluard.paragraphs}
links={galleries.esbaluard.links}
/>
</div>
<h3 className="margin-top"> Contact: {email}</h3>
<br/>
</div>
);
}
}
export default ProfessionalPage;
|
definitions/npm/react-css-modules_v3.x.x/flow_v0.53.x-/test_react-css-modules-v3.js
|
echenley/flow-typed
|
// @flow
import React, { Component } from 'react';
import CSSModules from 'react-css-modules';
const styles = { test: '123' };
class ExampleModule extends Component<{
foo: string,
styles: typeof styles,
}> {
render() {
return <div className={this.props.styles}>{this.props.foo}</div>;
}
}
const ExampleCSSModules = CSSModules(ExampleModule, styles);
const ExampleCSSModules2 = CSSModules(ExampleModule, styles, { allowMultiple: true });
// $ExpectError invalid module option.
const BustedCSSModule = CSSModules(ExampleModule, styles, { wubbaLubba: 'dub-dub' });
1
class Failure1 extends Component<{}> {
render() {
// $ExpectError Missing prop `foo` will be caught.
return <ExampleCSSModules />;
}
}
class Failure2 extends Component<{}> {
render() {
// $ExpectError Unwrapped component won't be passed `styles`.
return <ExampleModule foo="bar" />;
}
}
class Working extends Component<{}> {
render() {
return <ExampleCSSModules foo="bar" />;
}
}
|
system/src/routes/Document/containers/EditDocumentViewContainer/index.js
|
axmatthew/react
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import documentModule from '../../../../modules/documents';
import EditDocumentView from '../../components/EditDocumentView';
import { baseMapStateToProps } from '../../../../common/container-helpers';
class EditDocumentViewContainer extends Component {
static propTypes = Object.assign({}, EditDocumentView.propTypes, {
params: React.PropTypes.object.isRequired,
fetch: React.PropTypes.func.isRequired
});
componentDidMount() {
this.props.fetch(this.props.params._id);
}
render() {
return React.createElement(
EditDocumentView,
Object.assign({}, this.props, { params: undefined, fetch: undefined })
);
}
}
export default connect(baseMapStateToProps.bind(null, documentModule.entityUrl, 'editView'), {
fetch: documentModule.fetch,
// Transfer to presentation component
update: documentModule.update
})(EditDocumentViewContainer);
|
docs/src/app/components/pages/components/Toggle/Page.js
|
pradel/material-ui
|
import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import toggleReadmeText from './README';
import ToggleExampleSimple from './ExampleSimple';
import toggleExampleSimpleCode from '!raw!./ExampleSimple';
import toggleCode from '!raw!material-ui/lib/Toggle/Toggle';
const description = 'The second example is selected by default using the `defaultToggled` property. The third ' +
'example is disabled using the `disabled` property. The final example uses the `labelPosition` property to ' +
'position the label on the right.';
const TogglePage = () => (
<div>
<Title render={(previousTitle) => `Toggle - ${previousTitle}`} />
<MarkdownElement text={toggleReadmeText} />
<CodeExample
title="Examples"
description={description}
code={toggleExampleSimpleCode}
>
<ToggleExampleSimple />
</CodeExample>
<PropTypeDescription code={toggleCode} />
</div>
);
export default TogglePage;
|
blueprints/view/files/__test__/views/__name__View.spec.js
|
pawelniewie/zen
|
import React from 'react'
describe('(View) <%= pascalEntityName %>', () => {
it('should exist', () => {
})
})
|
src/docs/examples/TextInputCSSModules/ExampleError.js
|
abhiisheek/ps-react-abhiisheek
|
import React from 'react';
import TextInputCSSModules from 'ps-react-abhiisheek/TextInputCSSModules';
/** Required TextBox with error */
export default class ExampleError extends React.Component {
render() {
return (
<TextInputCSSModules
htmlId="example-optional"
label="First Name"
name="firstname"
onChange={() => {}}
required
error="First name is required."
/>
);
}
}
|
js/App.js
|
giladl82/complete-intro-to-react
|
import React from 'react'
import { Route } from 'react-router-dom'
import { Provider } from 'react-redux'
import store from './store'
// import Landing from './Landing'
// import Search from './Search'
// import Details from './Details'
import AsycRoute from './AsyncRoute'
import preload from '../public/data.json'
// import '../public/normalize.css'
// import '../public/style.css'
if (global) {
global.System = {
import () { }
}
}
const AsyncDetailsComponent = (props) => {
const shows = preload.shows.filter((show) => {
return props.match.params.id === show.imdbID
})
return (
<AsycRoute
props={Object.assign({ show: shows[ 0 ] }, props)}
loadingPromise={System.import('./Details')} />
)
}
AsyncDetailsComponent.propTypes = {
match: React.PropTypes.object
}
const App = () => {
return (
<Provider store={store}>
<div className='app'>
{/* <Route exact path='/' component={Landing} /> */}
<Route exact path='/'
component={(props) => <AsycRoute props={props}
loadingPromise={System.import('./Landing')} />}
/>
{/* <Route path='/search'
component={(props) => <Search shows={preload.shows} {...props} />} /> */}
<Route path='/search'
component={(props) => {
return (<AsycRoute
props={Object.assign({ shows: preload.shows }, props)}
loadingPromise={System.import('./Search')} />)
}} />
{/* <Route path='/details/:id'
component={(props) => {
const shows = preload.shows.filter((show) => {
return props.match.params.id === show.imdbID
})
return <Details show={shows[ 0 ]} {...props} />
}} /> */}
<Route path='/details/:id'
component={AsyncDetailsComponent} />
</div>
</Provider>
)
}
export default App
|
rojak-ui-web/src/Routes.js
|
reinarduswindy/rojak
|
import { Route, IndexRoute } from 'react-router';
import React from 'react';
import Container from './app/utils/Container';
import HomePage from './app/home/HomePage';
export default (
<Route component={Container}>
<Route path="/(search/:keyword)" component={HomePage} />
</Route>
)
|
webserver/src/components/AppRoutes.js
|
lukedoolittle/moviematch
|
'use strict';
import React from 'react';
import { Router, browserHistory } from 'react-router';
import routes from '../routes';
export default class AppRoutes extends React.Component {
render() {
return (
<Router history={browserHistory} routes={routes} onUpdate={() => window.scrollTo(0, 0)}/>
);
}
}
|
src/containers/Root.prod.js
|
vojtechsoban/mortgage-calc
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Provider } from 'react-redux';
import App from 'src/App';
export default class Root extends Component {
static propTypes = {store: PropTypes.object.isRequired};
render() {
const { store } = this.props;
return (
<Provider store={store}>
<App />
</Provider>
);
}
}
|
frontend/component/Footer.js
|
wangmuming/node-forum
|
import React from 'react';
const footerStyle = {
marginTop: 50,
padding: 20
};
export default class Footer extends React.Component{
render(){
return(
<div className="text-center" style={footerStyle}>
© CopyRight Node.js实战
</div>
);
}
}
|
components/app_bar/AppBar.js
|
react-toolbox/react-toolbox
|
import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { themr } from 'react-css-themr';
import { APP_BAR } from '../identifiers';
import InjectIconButton from '../button/IconButton';
const factory = (IconButton) => {
class AppBar extends React.Component {
static propTypes = {
children: PropTypes.node,
className: PropTypes.string,
fixed: PropTypes.bool,
flat: PropTypes.bool,
leftIcon: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
]),
onLeftIconClick: PropTypes.func,
onRightIconClick: PropTypes.func,
rightIcon: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
]),
scrollHide: PropTypes.bool,
theme: PropTypes.shape({
appBar: PropTypes.string,
fixed: PropTypes.string,
flat: PropTypes.string,
inner: PropTypes.string,
leftIcon: PropTypes.string,
rightIcon: PropTypes.string,
scrollHide: PropTypes.string,
title: PropTypes.string,
}),
title: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
]),
};
static defaultProps = {
className: '',
fixed: false,
flat: false,
scrollHide: false,
};
state = { hidden: false, height: 0 }; // eslint-disable-line react/no-unused-state
componentDidMount() {
if (this.props.scrollHide) {
this.initializeScroll();
}
}
componentWillReceiveProps(nextProps) {
if (!this.props.scrollHide && nextProps.scrollHide) {
this.initializeScroll();
}
if (this.props.scrollHide && !nextProps.scrollHide) {
this.endScroll();
}
}
componentWillUnmount() {
if (this.props.scrollHide) {
this.endScroll();
}
}
handleScroll = () => {
const scrollDiff = this.curScroll - window.scrollY;
this.setState(state => ({
hidden: scrollDiff < 0
&& window.scrollY !== undefined
&& window.scrollY > state.height,
}));
this.curScroll = window.scrollY;
};
initializeScroll = () => {
window.addEventListener('scroll', this.handleScroll);
const { height } = this.rootNode.getBoundingClientRect();
this.curScroll = window.scrollY;
this.setState({ height }); // eslint-disable-line react/no-unused-state
}
endScroll() {
window.removeEventListener('scroll', this.handleScroll);
}
render() {
const {
children,
leftIcon,
onLeftIconClick,
onRightIconClick,
rightIcon,
theme,
title,
} = this.props;
const className = cn(theme.appBar, {
[theme.fixed]: this.props.fixed,
[theme.flat]: this.props.flat,
[theme.scrollHide]: this.state.hidden,
}, this.props.className);
const renderedTitle = typeof title === 'string'
? <h1 className={cn(theme.title)}>{title}</h1>
: title;
const renderedLeftIcon = leftIcon && (
<IconButton
inverse
className={cn(theme.leftIcon)}
onClick={onLeftIconClick}
icon={leftIcon}
/>
);
const renderedRightIcon = rightIcon && (
<IconButton
inverse
className={cn(theme.rightIcon)}
onClick={onRightIconClick}
icon={rightIcon}
/>
);
return (
<header
className={className}
data-react-toolbox="app-bar"
ref={(node) => { this.rootNode = node; }}
>
<div className={theme.inner}>
{renderedLeftIcon}
{renderedTitle}
{children}
{renderedRightIcon}
</div>
</header>
);
}
}
return AppBar;
};
const AppBar = factory(InjectIconButton);
export default themr(APP_BAR)(AppBar);
export { factory as appBarFactory };
export { AppBar };
|
src/routes/Projects/components/NewProjectDialog/NewProjectDialog.js
|
ronihcohen/magic-vote
|
import React from 'react'
import PropTypes from 'prop-types'
import Dialog from 'material-ui/Dialog'
import FlatButton from 'material-ui/FlatButton'
import { Field, reduxForm } from 'redux-form'
import { TextField } from 'redux-form-material-ui'
import { required } from 'utils/form'
import { NEW_PROJECT_FORM_NAME } from 'constants'
import classes from './NewProjectDialog.scss'
export const NewProjectDialog = ({
open,
onRequestClose,
submit,
handleSubmit
}) => (
<Dialog
title="New Project"
open={open}
onRequestClose={onRequestClose}
contentClassName={classes.container}
actions={[
<FlatButton label="Cancel" secondary onTouchTap={onRequestClose} />,
<FlatButton label="Create" primary onTouchTap={submit} />
]}>
<form onSubmit={handleSubmit} className={classes.inputs}>
<Field
name="name"
component={TextField}
floatingLabelText="Project Name"
validate={[required]}
/>
</form>
</Dialog>
)
NewProjectDialog.propTypes = {
open: PropTypes.bool.isRequired,
onRequestClose: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired, // eslint-disable-line react/no-unused-prop-types
handleSubmit: PropTypes.func.isRequired, // added by redux-form
submit: PropTypes.func.isRequired // added by redux-form
}
export default reduxForm({
form: NEW_PROJECT_FORM_NAME
})(NewProjectDialog)
|
test/pullHook-test.js
|
OnsenUI/react-onsenui
|
/* global describe it assert */
import React from 'react';
import ReactDOM from 'react-dom';
import {PullHook} from '../dist/react-onsenui.js';
import TestUtils from 'react/lib/ReactTestUtils';
import rendersToComponent from './testUtil.js';
describe('PullHook', function() {
rendersToComponent(
<PullHook />,
'ons-pull-hook'
);
});
|
node_modules/react-router/es6/Redirect.js
|
sauceSquatch/we_are_razorfish_experience
|
'use strict';
import React from 'react';
import invariant from 'invariant';
import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils';
import { formatPattern } from './PatternUtils';
import { falsy } from './PropTypes';
var _React$PropTypes = React.PropTypes;
var string = _React$PropTypes.string;
var object = _React$PropTypes.object;
/**
* A <Redirect> is used to declare another URL path a client should
* be sent to when they request a given URL.
*
* Redirects are placed alongside routes in the route configuration
* and are traversed in the same manner.
*/
var Redirect = React.createClass({
displayName: 'Redirect',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element) {
var route = _createRouteFromReactElement(element);
if (route.from) route.path = route.from;
route.onEnter = function (nextState, replace) {
var location = nextState.location;
var params = nextState.params;
var pathname = undefined;
if (route.to.charAt(0) === '/') {
pathname = formatPattern(route.to, params);
} else if (!route.to) {
pathname = location.pathname;
} else {
var routeIndex = nextState.routes.indexOf(route);
var parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1);
var pattern = parentPattern.replace(/\/*$/, '/') + route.to;
pathname = formatPattern(pattern, params);
}
replace({
pathname: pathname,
query: route.query || location.query,
state: route.state || location.state
});
};
return route;
},
getRoutePattern: function getRoutePattern(routes, routeIndex) {
var parentPattern = '';
for (var i = routeIndex; i >= 0; i--) {
var route = routes[i];
var pattern = route.path || '';
parentPattern = pattern.replace(/\/*$/, '/') + parentPattern;
if (pattern.indexOf('/') === 0) break;
}
return '/' + parentPattern;
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Redirect> elements are for router configuration only and should not be rendered') : invariant(false) : undefined;
}
});
export default Redirect;
|
fields/explorer/components/FieldType.js
|
trentmillar/keystone
|
import React from 'react';
import Markdown from 'react-markdown';
import Col from './Col';
import Row from './Row';
import FieldSpec from './FieldSpec';
const ExplorerFieldType = React.createClass({
getInitialState () {
return {
readmeIsVisible: !!this.props.readme,
filter: this.props.FilterComponent.getDefaultValue(),
value: this.props.value,
};
},
componentWillReceiveProps (newProps) {
if (this.props.params.type === newProps.params.type) return;
this.setState({
filter: newProps.FilterComponent.getDefaultValue(),
readmeIsVisible: newProps.readme
? this.state.readmeIsVisible
: false,
value: newProps.value,
});
},
onFieldChange (e) {
var logValue = typeof e.value === 'string' ? `"${e.value}"` : e.value;
console.log(`${this.props.params.type} field value changed:`, logValue);
this.setState({
value: e.value,
});
},
onFilterChange (value) {
console.log(`${this.props.params.type} filter value changed:`, value);
this.setState({
filter: value,
});
},
toggleReadme () {
this.setState({ readmeIsVisible: !this.state.readmeIsVisible });
},
render () {
const { FieldComponent, FilterComponent, readme, toggleSidebar } = this.props;
const { readmeIsVisible } = this.state;
const specs = Array.isArray(this.props.spec) ? this.props.spec : [this.props.spec];
return (
<div className="fx-page">
<div className="fx-page__header">
<div className="fx-page__header__title">
<button
className="fx-page__header__button fx-page__header__button--sidebar mega-octicon octicon-three-bars"
onClick={toggleSidebar}
type="button"
/>
{FieldComponent.type}
</div>
{!!readme && (
<button
className="fx-page__header__button fx-page__header__button--readme mega-octicon octicon-file-text"
onClick={this.toggleReadme}
title={readmeIsVisible ? 'Hide Readme' : 'Show Readme'}
type="button"
/>
)}
</div>
<div className="fx-page__content">
<Row>
<Col>
<div className="fx-page__content__inner">
{specs.map((spec, i) => (
<FieldSpec
key={spec.path}
i={i}
FieldComponent={FieldComponent}
FilterComponent={FilterComponent}
spec={spec}
readmeIsVisible={readmeIsVisible}
/>
))}
</div>
</Col>
{!!readmeIsVisible && (
<Col width={380}>
<Markdown
className="Markdown"
source={readme}
/>
</Col>
)}
</Row>
</div>
</div>
);
},
});
module.exports = ExplorerFieldType;
|
src/icons/IosReverseCameraOutline.js
|
fbfeix/react-icons
|
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosReverseCameraOutline extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M301.815,318.608c-13.114,11.029-28.956,17.356-45.815,17.356c-36.36,0-66.286-28.965-70.89-61.965h30.61l-38.87-50
l-37.534,50h29.479c4.696,42,41.717,78,87.205,78c20.9,0,41.17-7.566,57.076-21.218l2.37-2.159l-11.599-11.662L301.815,318.608z"></path>
<path d="M315.736,198.885c-16.188-14.775-37.402-22.839-59.736-22.839c-20.9,0-41.169,7.556-57.075,21.206l-2.371,2.052
l11.599,11.61l2.033-1.706c12.927-10.872,29.197-17.005,45.814-17.005c36.343,0,66.274,28.797,70.891,63.797h-30.644l38.846,51.225
L372.719,256h-29.512C340.966,236,331.275,213.064,315.736,198.885z"></path>
<path d="M417.5,160h-61.725c-32.105-36-42.219-48-54.525-48h-88.5c-12.314,0-22.167,12-54.521,48H145v-16h-34v16H97.5
C79.855,160,64,173.217,64,190.684v176.018C64,384.169,79.855,400,97.5,400h320c17.645,0,30.5-15.831,30.5-33.299V190.684
C448,173.217,435.145,160,417.5,160z M432,366.701c0,9.263-6.229,17.299-14.5,17.299h-320c-8.738,0-17.5-8.664-17.5-17.299V190.684
C80,182.518,88.126,176,97.5,176h60.729c0,0,4.124,0,6.133,0s3.225-0.199,5.768-3.2s7.702-10.008,11.08-13.795
c11.296-12.666,19.457-21.915,25.316-27.132c4.746-4.225,6.211-3.873,6.225-3.873h88.5c0.016,0,1.611-0.363,6.709,4.219
c6.141,5.521,14.705,16.84,26.558,30.198c2.888,3.255,7.214,8.11,9.317,10.44s4.252,3.143,5.771,3.143s6.17,0,6.17,0H417.5
c8.832,0,14.5,5.965,14.5,14.684V366.701z"></path>
</g>
</g>;
} return <IconBase>
<g>
<path d="M301.815,318.608c-13.114,11.029-28.956,17.356-45.815,17.356c-36.36,0-66.286-28.965-70.89-61.965h30.61l-38.87-50
l-37.534,50h29.479c4.696,42,41.717,78,87.205,78c20.9,0,41.17-7.566,57.076-21.218l2.37-2.159l-11.599-11.662L301.815,318.608z"></path>
<path d="M315.736,198.885c-16.188-14.775-37.402-22.839-59.736-22.839c-20.9,0-41.169,7.556-57.075,21.206l-2.371,2.052
l11.599,11.61l2.033-1.706c12.927-10.872,29.197-17.005,45.814-17.005c36.343,0,66.274,28.797,70.891,63.797h-30.644l38.846,51.225
L372.719,256h-29.512C340.966,236,331.275,213.064,315.736,198.885z"></path>
<path d="M417.5,160h-61.725c-32.105-36-42.219-48-54.525-48h-88.5c-12.314,0-22.167,12-54.521,48H145v-16h-34v16H97.5
C79.855,160,64,173.217,64,190.684v176.018C64,384.169,79.855,400,97.5,400h320c17.645,0,30.5-15.831,30.5-33.299V190.684
C448,173.217,435.145,160,417.5,160z M432,366.701c0,9.263-6.229,17.299-14.5,17.299h-320c-8.738,0-17.5-8.664-17.5-17.299V190.684
C80,182.518,88.126,176,97.5,176h60.729c0,0,4.124,0,6.133,0s3.225-0.199,5.768-3.2s7.702-10.008,11.08-13.795
c11.296-12.666,19.457-21.915,25.316-27.132c4.746-4.225,6.211-3.873,6.225-3.873h88.5c0.016,0,1.611-0.363,6.709,4.219
c6.141,5.521,14.705,16.84,26.558,30.198c2.888,3.255,7.214,8.11,9.317,10.44s4.252,3.143,5.771,3.143s6.17,0,6.17,0H417.5
c8.832,0,14.5,5.965,14.5,14.684V366.701z"></path>
</g>
</IconBase>;
}
};IosReverseCameraOutline.defaultProps = {bare: false}
|
app/controllers/routine.js
|
crodriguez1a/react-my-pace
|
// TODO Deprecate this controller pattern
import React from 'react';
import ReactDOM from 'react-dom';
import moment from 'moment';
import Timer from 'timer.js';
import Session from './../session/routine';
import { PieChart } from 'react-d3-basic';
import ProgressClock from './../components/progress-clock';
import ProgressBar from './../components/progress-bar';
import ProgressControls from './../components/progress-controls';
import RoutineForm from './../components/routine-form';
import TaskCount from './../components/task-count';
import ThemePicker from './../components/theme-picker';
import RestDuration from './../components/rest-duration';
import { radialColors, Sounds } from './../utils/constants';
import Player from 'audio-player';
const audioPlayer = new Player();
/**
Assemblage of all components
@module RoutineController
@returns Class
@private
*/
class RoutineController {
/**
Keep track elapsed intervals in sequence (including rests)
@property progressCount
@private
@returns Number
*/
progressCount = 0;
/**
Keep track of elapsed tasks in sequence (excludes rest intervals)
@property taskCount
@private
@returns Number
*/
taskCount = Session.find('totalTasks');
/**
Configure D3 pie chart
@property chartConf
@private
@returns Object
*/
chartConf = {
width: 320,
height: 320,
innerRadius: 110,
name(d) {
return d.name;
},
value(d) {
return d.value;
},
series: [
{
field: 'remaining',
name: 'remaining',
color: radialColors.background
},
{
field: 'time',
name: 'time',
color: radialColors.primary
}
]
}
/**
Render chart as part of running timer callback
@method renderChart
@private
*/
renderChart = () => {
this.timer = new Timer({
tick: 0.001,
ontick: (ms) => {
this.updateClock(ms);
},
onend: () => {
this.updateCount();
if (Session.find('withSound')) {
//play sound
let currentSequenceInterval = Session.find('sequence')[this.progressCount];
audioPlayer.play(currentSequenceInterval && currentSequenceInterval.rest ? Sounds.rest : Sounds.end);
}
}/*,
onstart() { },
onpause() { }*/
});
}
/**
Sync display with model, when model has changes have been applied from form
@method routineSync
@private
*/
routineSync = () => {
let interval = Session.find('interval');
// Update interval sequence for this session
Session.buildIntervalSequence();
// Update timer interval internally
this.timer._.interval = interval;
// Update display
this.updateClock(interval * 1000);
this.updateCount(true);
this.renderRestDuration();
}
/**
Update the progress of the clock
@method updateClock
@param ms {Number} Current timer progress in milliseconds
@private
*/
updateClock = (ms) => {
// Fetch current interval from model
let currentInterval = Session.find('interval');
// Calc running time
let running = (ms / 1000) / currentInterval * 100;
// Computed data based on running timer
let data = [
{
name: 'time',
value: 100 - running
},
{
name: 'remaining',
value: running
}
];
// Render Clock
this.clock = ReactDOM.render(
<ProgressClock
clock={ms === -1 ? moment(currentInterval * 1000).format('mm:ss:SS') : moment(ms).format('mm:ss:SS')}
count={this.progressCount}
>
<PieChart
data={data}
width={this.chartConf.width}
height={this.chartConf.height}
chartSeries={this.chartConf.series}
value={this.chartConf.value}
name={this.chartConf.name}
innerRadius={this.chartConf.innerRadius}
/>
</ProgressClock>,
document.getElementById('progress-clock')
);
}
/**
Alternate colors for intervals in sequence
@method updateRadialColor
@param sequenceItem {Object} An item in the invterval sequence
@private
*/
updateRadialColor = (sequenceItem) => {
this.chartConf.series[1].color = sequenceItem && sequenceItem.rest ? radialColors.alternative : radialColors.primary;
}
/**
Evaluate the interval sequence and update the progress and task counts accordingly
@method updateCount
@param reset {Bool} Signal if count should reset to default
@private
*/
updateCount = (reset) => {
let timer = this.timer;
let totalTasks = Session.find('totalTasks');
// Advance progress count
this.progressCount = reset ? totalTasks : this.progressCount + 1;
// Find the current interval in the sequence based on the progress count
let currentSequenceInterval = Session.find('sequence')[this.progressCount];
// Apply the next interval in the sequence
if (!reset && totalTasks >= this.taskCount && this.taskCount > 1) {
// Only when rest is enabled
if (Session.find('shouldRest')) {
// Alternate colors
this.updateRadialColor(currentSequenceInterval);
// Save the udpated interval in the model
Session.save('interval', currentSequenceInterval.value);
// Update the timer with new interval
timer.start(currentSequenceInterval.value);
// Pulsate rest duration
this.renderRestDuration(currentSequenceInterval.rest);
} else {
// Rest is disabled, advance as usual
timer.start();
this.progressCount = this.progressCount + 1;
}
} else {
// Task is complete, reset task count
this.progressCount = 0;
this.taskCount = totalTasks;
this.updateTaskProgress(0, totalTasks);
}
// For non-rest intervals, update the task count and render accordingly
if (!reset && currentSequenceInterval && !currentSequenceInterval.rest) {
this.taskCount = this.taskCount - 1;
this.updateTaskProgress(100 - (((this.taskCount - 1) / totalTasks) * 100), this.taskCount);
}
}
/**
Render the progress bar and the updated task count components
@method updateTaskProgress
@param percentage {Number} computed percentage of task progress
@param count {Number} elapsed number of tasks
@private
*/
updateTaskProgress = (percentage, count) => {
this.renderProgressBar(percentage);
this.renderTaskCount(count);
}
/**
Render the task count component
@method renderTaskCount
@param count {Number} elapsed number of tasks
@private
*/
renderTaskCount = (count) => {
ReactDOM.render(
<TaskCount
count={count}
/>,
document.getElementById('task-count')
);
}
/**
Render the progress bar component
@method renderProgressBar
@param percentage {Number} computed percentage of task progress
@private
*/
renderProgressBar = (percentage) => {
ReactDOM.render(
<ProgressBar
percentage={percentage}
/>,
document.getElementById('progress-bar')
);
}
/**
Render the progress controls component
@method renderControls
@private
*/
renderControls = () => {
let timer = this.timer;
this.controls = ReactDOM.render(
<ProgressControls
timer={timer}
/>,
document.getElementById('progress-controls')
);
}
/**
Render the rest duration component which displays the current duration of the rest interval
@method renderRestDuration
@param resting {Bool} Signal if current interval is a rest interval
@private
*/
renderRestDuration = (resting) => {
ReactDOM.render(
<RestDuration
duration={Session.find('restInterval')}
shouldRest={Session.find('shouldRest')}
pulsate={resting}
/>,
document.getElementById('rest-duration')
);
}
/**
Render the routine form component
@method _renderRoutineForm
@private
*/
renderRoutineForm = () => {
let timer = this.timer;
ReactDOM.render(
<RoutineForm
timer={timer}
controller={this}
controls={this.controls}
/>,
document.getElementById('routine-form')
);
}
/**
Render the theme picker component
@method renderThemes
@private
*/
renderThemes = () => {
ReactDOM.render(
<ThemePicker />,
document.getElementById('theme-picker')
);
}
/**
Initialize the radial progress modules
@method init
@private
*/
init = () => {
// Initialize this session
Session.init();
// setup chart class
this.renderChart();
// renders task count
this.renderTaskCount(Session.find('totalTasks'));
// renders progress bar
this.renderProgressBar(0);
// renders controls
this.renderControls();
// renders settings
this.renderRoutineForm();
// renders themes
this.renderThemes();
// renders the clock
this.updateClock(-1);
// renders rest duration
this.renderRestDuration();
}
};
export default RoutineController;
|
src/client/router.js
|
gustavoisensee/twittercounter
|
import React from 'react';
import Provider from 'react-redux';
import { history } from './store';
import { Router, Route, IndexRoute } from 'react-router';
import MainLayout from './layouts/main';
import GroupContainer from './modules/group/container';
export default (
<Router history={history}>
<Route component={MainLayout}>
<Route path='/' component={GroupContainer} />
</Route>
</Router>
);
|
src/components/LibraryItem.js
|
jenca-cloud/jenca-gui
|
import React from 'react'
import { Grid, Cell } from 'react-mdl'
import RunButton from "./RunButton";
const buttonTitles = {
run:"Add to Project",
link:"Open App"
}
export default function LibraryItem(props) {
var title = buttonTitles[props.app.type] || "click me"
return (
<div id="library-item">
<div className="demo-card-square mdl-card mdl-shadow--2dp">
<img src={'thumbnails/' + props.name + '.png'} />
<div className="mdl-card__title mdl-card--expand">
<h2 className="mdl-card__title-text">{props.name}</h2>
</div>
<div className="mdl-card__supporting-text">
{props.description}
</div>
<div id="run-button">
<RunButton
app={props.app}
handleRun={props.handleRun}
title={title} />
</div>
</div>
</div>
)
}
|
presentation/examples/future-advisor-lite/client/components/About.js
|
iansinnott/react-static-presentation
|
import React from 'react';
import s from './About.styl';
export const WhoWeAre = React.createClass({
render() {
return (
<div>
<div className={s.banner}>
<div className={s.container}>
<h1>Get advice from our industry-leading experts</h1>
<p>
We are an award-winning investment advisory firm serving clients
nationwide from our offices in downtown San Francisco. And we're
working for you.
</p>
</div>
</div>
<div className={s.container}>
<div className={s.siteTitle}>
<h1>More information about us</h1>
</div>
<p style={{ maxWidth: 600 }}>
Our investment decisions are backed by Nobel-Prize winning theory
and continuously refined by an Investment Council of notable
scholars and finance experts. The Committee has decades of
experience and billions of dollars behind them.
</p>
</div>
</div>
);
},
});
|
ui/src/playlist/PlaylistList.js
|
cloudsonic/sonic-server
|
import React from 'react'
import {
Datagrid,
DateField,
EditButton,
Filter,
NumberField,
SearchInput,
TextField,
useUpdate,
useNotify,
} from 'react-admin'
import Switch from '@material-ui/core/Switch'
import { DurationField, List, Writable, isWritable } from '../common'
const PlaylistFilter = (props) => (
<Filter {...props} variant={'outlined'}>
<SearchInput source="name" alwaysOn />
</Filter>
)
const TogglePublicInput = ({ permissions, resource, record = {}, source }) => {
const notify = useNotify()
const [togglePublic] = useUpdate(
resource,
record.id,
{
...record,
public: !record.public,
},
{
undoable: false,
onFailure: (error) => {
console.log(error)
notify('ra.page.error', 'warning')
},
}
)
const handleClick = (e) => {
togglePublic()
e.stopPropagation()
}
const canChange =
permissions === 'admin' ||
localStorage.getItem('username') === record['owner']
return (
<Switch
checked={record[source]}
onClick={handleClick}
disabled={!canChange}
/>
)
}
const PlaylistList = ({ permissions, ...props }) => (
<List {...props} exporter={false} filters={<PlaylistFilter />}>
<Datagrid rowClick="show" isRowSelectable={(r) => isWritable(r && r.owner)}>
<TextField source="name" />
<TextField source="owner" />
<NumberField source="songCount" />
<DurationField source="duration" />
<DateField source="updatedAt" sortByOrder={'DESC'} />
<TogglePublicInput
source="public"
permissions={permissions}
sortByOrder={'DESC'}
/>
<Writable>
<EditButton />
</Writable>
/>
</Datagrid>
</List>
)
export default PlaylistList
|
app/components/button.js
|
garth/material-components
|
import React from 'react';
import Example from './example';
import { Button } from '../../lib';
export default () => (
<div>
<Example
code={`
import { Button } from 'material-components';
`}
/>
<Example
code={`
// enabled buttons
<Button onClick={onClick}>Normal</Button>
<Button onClick={onClick} primary>Primary</Button>
<Button onClick={onClick} flat>Flat</Button>
<Button onClick={onClick} primary flat>Primary Flat</Button>
`}
/>
<p>
<Button onClick={e => {}}>Normal</Button>
<Button onClick={e => {}} primary>
Primary
</Button>
<Button onClick={e => {}} flat>
Flat
</Button>
<Button onClick={e => {}} primary flat>
Primary Flat
</Button>
</p>
<Example
code={`
// disabled buttons
<Button>Normal</Button>
<Button primary>Primary</Button>
<Button flat>Flat</Button>
<Button primary flat>Primary Flat</Button>
`}
/>
<p>
<Button>Normal</Button>
<Button primary>Primary</Button>
<Button flat>Flat</Button>
<Button primary flat>
Primary Flat
</Button>
</p>
</div>
);
|
src/components/videoDetail.js
|
gabriellisboa/reduxStudies
|
import React from 'react';
const VideoDetail = ({ video }) => {
if(!video) {
return <div>Loading...</div>
}
const videoId = video.id.videoId;
const url = `https://www.youtube.com/embed/${videoId}`;
return (
<div className="video-detail">
<div className="embed-responsive embed-responsive-16by9">
<iframe className="embed-response-item" src={url}></iframe>
</div>
<div className="details">
<div>{video.snippet.title}</div>
<div>{video.snippet.description}</div>
</div>
</div>
)
};
export default VideoDetail;
|
packages/wix-style-react/src/Notification/TextLabel/TextLabel.spec.js
|
wix/wix-style-react
|
import React from 'react';
import TextLabel from '.';
describe('TextLabel', () => {
it('should have correct displayName', () => {
expect(TextLabel.displayName).toBe('Notification.TextLabel');
});
});
|
src/components/ColourPreview.js
|
colouroscope/colouroscope
|
import React from 'react'
let ColourPreview = ({ colour }) => {
const preview = {
height: 300,
width: '100%',
backgroundColor: colour,
border: '2px solid grey',
}
return (
<div className="mb-4" style={preview}></div>
)
}
export default ColourPreview
|
stories/SingleDatePicker_calendar.js
|
intwarehq/react-dates
|
import React from 'react';
import moment from 'moment';
import { storiesOf } from '@kadira/storybook';
import SingleDatePickerWrapper from '../examples/SingleDatePickerWrapper';
import { VERTICAL_ORIENTATION, ANCHOR_RIGHT } from '../constants';
const TestPrevIcon = () => (
<span
style={{
border: '1px solid #dce0e0',
backgroundColor: '#fff',
color: '#484848',
padding: '3px',
}}
>
Prev
</span>
);
const TestNextIcon = () => (
<span
style={{
border: '1px solid #dce0e0',
backgroundColor: '#fff',
color: '#484848',
padding: '3px',
}}
>
Next
</span>
);
const TestCustomInfoPanel = () => (
<div
style={{
padding: '10px 21px',
borderTop: '1px solid #dce0e0',
color: '#484848',
}}
>
❕ Some useful info here
</div>
);
storiesOf('SDP - Calendar Props', module)
.addWithInfo('default', () => (
<SingleDatePickerWrapper autoFocus />
))
.addWithInfo('single month', () => (
<SingleDatePickerWrapper
numberOfMonths={1}
autoFocus
/>
))
.addWithInfo('with custom day size', () => (
<SingleDatePickerWrapper daySize={50} autoFocus />
))
.addWithInfo('anchored right', () => (
<div style={{ float: 'right' }}>
<SingleDatePickerWrapper
anchorDirection={ANCHOR_RIGHT}
autoFocus
/>
</div>
))
.addWithInfo('vertical', () => (
<SingleDatePickerWrapper
orientation={VERTICAL_ORIENTATION}
autoFocus
/>
))
.addWithInfo('horizontal with portal', () => (
<SingleDatePickerWrapper
withPortal
autoFocus
/>
))
.addWithInfo('horizontal with fullscreen portal', () => (
<SingleDatePickerWrapper withFullScreenPortal autoFocus />
))
.addWithInfo('vertical with full screen portal', () => (
<SingleDatePickerWrapper
orientation={VERTICAL_ORIENTATION}
withFullScreenPortal
autoFocus
/>
))
.addWithInfo('does not autoclose the DayPicker on date selection', () => (
<SingleDatePickerWrapper
keepOpenOnDateSelect
autoFocus
/>
))
.addWithInfo('with month specified on open', () => (
<SingleDatePickerWrapper
initialVisibleMonth={() => moment('01 2017', 'MM YYYY')}
autoFocus
/>
))
.addWithInfo('with custom arrows', () => (
<SingleDatePickerWrapper
navPrev={<TestPrevIcon />}
navNext={<TestNextIcon />}
autoFocus
/>
))
.addWithInfo('with outside days enabled', () => (
<SingleDatePickerWrapper
numberOfMonths={1}
enableOutsideDays
autoFocus
/>
))
.addWithInfo('with info panel', () => (
<SingleDatePickerWrapper
renderCalendarInfo={() => (
<TestCustomInfoPanel />
)}
autoFocus
/>
));
|
server/sonar-web/src/main/js/app/components/nav/global/GlobalNavSearch.js
|
Builders-SonarSource/sonarqube-bis
|
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import Backbone from 'backbone';
import React from 'react';
import { connect } from 'react-redux';
import SearchView from './SearchView';
import { getCurrentUser } from '../../../../store/rootReducer';
function contains (root, node) {
while (node) {
if (node === root) {
return true;
}
node = node.parentNode;
}
return false;
}
class GlobalNavSearch extends React.Component {
state = { open: false };
componentDidMount () {
key('s', () => {
const isModalOpen = document.querySelector('html').classList.contains('modal-open');
if (!isModalOpen) {
this.openSearch();
}
return false;
});
}
componentWillUnmount () {
this.closeSearch();
key.unbind('s');
}
openSearch = () => {
document.addEventListener('click', this.onClickOutside);
this.setState({ open: true }, this.renderSearchView);
};
closeSearch = () => {
document.removeEventListener('click', this.onClickOutside);
this.resetSearchView();
this.setState({ open: false });
};
renderSearchView = () => {
const searchContainer = this.refs.container;
this.searchView = new SearchView({
model: new Backbone.Model(this.props),
hide: this.closeSearch
});
this.searchView.render().$el.appendTo(searchContainer);
};
resetSearchView = () => {
if (this.searchView) {
this.searchView.destroy();
}
};
onClick = e => {
e.preventDefault();
if (this.state.open) {
this.closeSearch();
} else {
this.openSearch();
}
};
onClickOutside = e => {
if (!contains(this.refs.dropdown, e.target)) {
this.closeSearch();
}
};
render () {
const dropdownClassName = 'dropdown' + (this.state.open ? ' open' : '');
return (
<li ref="dropdown" className={dropdownClassName}>
<a className="navbar-search-dropdown" href="#" onClick={this.onClick}>
<i className="icon-search navbar-icon"/> <i className="icon-dropdown"/>
</a>
<div ref="container" className="dropdown-menu dropdown-menu-right global-navbar-search-dropdown"/>
</li>
);
}
}
const mapStateToProps = state => ({
currentUser: getCurrentUser(state)
});
export default connect(mapStateToProps)(GlobalNavSearch);
|
js/src/views/Home/Dapps/dapp.spec.js
|
nipunn1313/parity
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import { shallow } from 'enzyme';
import React from 'react';
import Dapp from './dapp';
import { createStore } from './dapps.test.js';
let component;
let instance;
let store;
function render () {
store = createStore();
component = shallow(
<Dapp
id='testId'
store={ store }
timestamp={ Date.now() }
/>
);
instance = component.instance();
return component;
}
describe('views/Home/Dapp', () => {
beforeEach(() => {
render();
return instance.componentWillMount();
});
it('renders defaults', () => {
expect(component).to.be.ok;
});
it('loads the dapp on mount', () => {
expect(store.loadApp).to.have.been.calledWith('testId');
});
});
|
app/javascript/mastodon/features/home_timeline/components/column_settings.js
|
codl/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import SettingToggle from '../../notifications/components/setting_toggle';
import SettingText from '../../../components/setting_text';
const messages = defineMessages({
filter_regex: { id: 'home.column_settings.filter_regex', defaultMessage: 'Filter out by regular expressions' },
settings: { id: 'home.settings', defaultMessage: 'Column settings' },
});
@injectIntl
export default class ColumnSettings extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
render () {
const { settings, onChange, intl } = this.props;
return (
<div>
<span className='column-settings__section'><FormattedMessage id='home.column_settings.basic' defaultMessage='Basic' /></span>
<div className='column-settings__row'>
<SettingToggle prefix='home_timeline' settings={settings} settingPath={['shows', 'reblog']} onChange={onChange} label={<FormattedMessage id='home.column_settings.show_reblogs' defaultMessage='Show boosts' />} />
</div>
<div className='column-settings__row'>
<SettingToggle prefix='home_timeline' settings={settings} settingPath={['shows', 'reply']} onChange={onChange} label={<FormattedMessage id='home.column_settings.show_replies' defaultMessage='Show replies' />} />
</div>
<span className='column-settings__section'><FormattedMessage id='home.column_settings.advanced' defaultMessage='Advanced' /></span>
<div className='column-settings__row'>
<SettingText prefix='home_timeline' settings={settings} settingKey={['regex', 'body']} onChange={onChange} label={intl.formatMessage(messages.filter_regex)} />
</div>
</div>
);
}
}
|
examples/with-supertokens/pages/_app.js
|
JeromeFitz/next.js
|
import '../styles/globals.css'
import React from 'react'
import { useEffect } from 'react'
import SuperTokensReact from 'supertokens-auth-react'
import * as SuperTokensConfig from '../config/frontendConfig'
import Session from 'supertokens-auth-react/recipe/session'
import { redirectToAuth } from 'supertokens-auth-react/recipe/thirdpartyemailpassword'
if (typeof window !== 'undefined') {
SuperTokensReact.init(SuperTokensConfig.frontendConfig())
}
function MyApp({ Component, pageProps }) {
useEffect(() => {
async function doRefresh() {
if (pageProps.fromSupertokens === 'needs-refresh') {
if (await Session.attemptRefreshingSession()) {
location.reload()
} else {
// user has been logged out
redirectToAuth()
}
}
}
doRefresh()
}, [pageProps.fromSupertokens])
if (pageProps.fromSupertokens === 'needs-refresh') {
return null
}
return <Component {...pageProps} />
}
export default MyApp
|
tests/components/Counter/Counter.spec.js
|
sqdron/sqdron.UI
|
// import React from 'react'
// import { bindActionCreators } from 'redux'
// import { Counter } from 'components/Counter/Counter'
// import { shallow } from 'enzyme'
//
// describe('(Component) Counter', () => {
// let _props, _spies, _wrapper
//
// beforeEach(() => {
// _spies = {}
// _props = {
// counter : 5,
// ...bindActionCreators({
// doubleAsync : (_spies.doubleAsync = sinon.spy()),
// increment : (_spies.increment = sinon.spy())
// }, _spies.dispatch = sinon.spy())
// }
// _wrapper = shallow(<Counter {..._props} />)
// })
//
// it('Should render as a <div>.', () => {
// expect(_wrapper.is('div')).to.equal(true)
// })
//
// it('Should render with an <h2> that includes Sample Counter text.', () => {
// expect(_wrapper.find('h2').text()).to.match(/Counter:/)
// })
//
// it('Should render props.counter at the end of the sample counter <h2>.', () => {
// expect(_wrapper.find('h2').text()).to.match(/5$/)
// _wrapper.setProps({ counter: 8 })
// expect(_wrapper.find('h2').text()).to.match(/8$/)
// })
//
// it('Should render exactly two buttons.', () => {
// expect(_wrapper.find('button')).to.have.length(2)
// })
//
// describe('An increment button...', () => {
// let _button
//
// beforeEach(() => {
// _button = _wrapper.find('button').filterWhere(a => a.text() === 'Increment')
// })
//
// it('has bootstrap classes', () => {
// expect(_button.hasClass('btn btn-default')).to.be.true
// })
//
// it('Should dispatch a `increment` action when clicked', () => {
// _spies.dispatch.should.have.not.been.called
//
// _button.simulate('click')
//
// _spies.dispatch.should.have.been.called
// _spies.increment.should.have.been.called
// })
// })
//
// describe('A Double (Async) button...', () => {
// let _button
//
// beforeEach(() => {
// _button = _wrapper.find('button').filterWhere(a => a.text() === 'Double (Async)')
// })
//
// it('has bootstrap classes', () => {
// expect(_button.hasClass('btn btn-default')).to.be.true
// })
//
// it('Should dispatch a `doubleAsync` action when clicked', () => {
// _spies.dispatch.should.have.not.been.called
//
// _button.simulate('click')
//
// _spies.dispatch.should.have.been.called
// _spies.doubleAsync.should.have.been.called
// })
// })
// })
|
static/src/js/components/executions/ConsoleOutput.js
|
enginyoyen/blackcrystal
|
import React from 'react';
import { Label } from 'react-bootstrap';
import $ from 'jquery';
import { jobExecutionLogURI } from '../../utils/Config'
const ConsoleOutput = React.createClass({
loadData() {
return $.ajax({
type: "GET",
url: jobExecutionLogURI(this.props.jobName, this.props.executionId),
contentType: 'text/plain',
});
},
getInitialState() {
return {logs: ''};
},
componentDidMount(){
this.loadData().success(function (data) {
if (this.isMounted()) {
this.setState({logs: data});
}
}.bind(this))
},
render() {
return (
<div className="box">
<div className="box-header with-border">
<h3 className="box-title">Console Output</h3>
</div>
<div className="box-body" >
<pre className="console-output">{this.state.logs}</pre>
</div>
</div>
);
}
});
export default ConsoleOutput;
|
src/svg-icons/av/high-quality.js
|
kittyjumbalaya/material-components-web
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvHighQuality = (props) => (
<SvgIcon {...props}>
<path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 11H9.5v-2h-2v2H6V9h1.5v2.5h2V9H11v6zm7-1c0 .55-.45 1-1 1h-.75v1.5h-1.5V15H14c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v4zm-3.5-.5h2v-3h-2v3z"/>
</SvgIcon>
);
AvHighQuality = pure(AvHighQuality);
AvHighQuality.displayName = 'AvHighQuality';
AvHighQuality.muiName = 'SvgIcon';
export default AvHighQuality;
|
src/templates/category-template.js
|
faizhasim/faizhasim.github.io
|
// @flow strict
import React from 'react';
import { graphql } from 'gatsby';
import Layout from '../components/Layout';
import Sidebar from '../components/Sidebar';
import Feed from '../components/Feed';
import Page from '../components/Page';
import Pagination from '../components/Pagination';
import { useSiteMetadata } from '../hooks';
import type { PageContext, AllMarkdownRemark } from '../types';
type Props = {
data: AllMarkdownRemark,
pageContext: PageContext
};
const CategoryTemplate = ({ data, pageContext }: Props) => {
const { title: siteTitle, subtitle: siteSubtitle } = useSiteMetadata();
const {
category,
currentPage,
prevPagePath,
nextPagePath,
hasPrevPage,
hasNextPage,
} = pageContext;
const { edges } = data.allMarkdownRemark;
const pageTitle = currentPage > 0 ? `${category} - Page ${currentPage} - ${siteTitle}` : `${category} - ${siteTitle}`;
return (
<Layout title={pageTitle} description={siteSubtitle}>
<Sidebar />
<Page title={category}>
<Feed edges={edges} />
<Pagination
prevPagePath={prevPagePath}
nextPagePath={nextPagePath}
hasPrevPage={hasPrevPage}
hasNextPage={hasNextPage}
/>
</Page>
</Layout>
);
};
export const query = graphql`
query CategoryPage($category: String, $postsLimit: Int!, $postsOffset: Int!) {
allMarkdownRemark(
limit: $postsLimit,
skip: $postsOffset,
filter: { frontmatter: { category: { eq: $category }, template: { eq: "post" }, draft: { ne: true } } },
sort: { order: DESC, fields: [frontmatter___date] }
){
edges {
node {
fields {
categorySlug
slug
}
frontmatter {
date
description
category
title
}
}
}
}
}
`;
export default CategoryTemplate;
|
admin/client/App/screens/Item/index.js
|
ONode/keystone
|
/**
* Item View
*
* This is the item view, it is rendered when users visit a page of a specific
* item. This mainly renders the form to edit the item content in.
*/
import React from 'react';
import { Center, Container, Spinner } from '../../elemental';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { listsByKey } from '../../../utils/lists';
import CreateForm from '../../shared/CreateForm';
import Alert from '../../elemental/Alert';
import EditForm from './components/EditForm';
import EditFormHeader from './components/EditFormHeader';
import RelatedItemsList from './components/RelatedItemsList/RelatedItemsList';
// import FlashMessages from '../../shared/FlashMessages';
import {
selectItem,
loadItemData,
} from './actions';
import {
selectList,
} from '../List/actions';
var ItemView = React.createClass({
displayName: 'ItemView',
contextTypes: {
router: React.PropTypes.object.isRequired,
},
getInitialState () {
return {
createIsOpen: false,
};
},
componentDidMount () {
// When we directly navigate to an item without coming from another client
// side routed page before, we need to select the list before initializing the item
// We also need to update when the list id has changed
if (!this.props.currentList || this.props.currentList.id !== this.props.params.listId) {
this.props.dispatch(selectList(this.props.params.listId));
}
this.initializeItem(this.props.params.itemId);
},
componentWillReceiveProps (nextProps) {
// We've opened a new item from the client side routing, so initialize
// again with the new item id
if (nextProps.params.itemId !== this.props.params.itemId) {
this.props.dispatch(selectList(nextProps.params.listId));
this.initializeItem(nextProps.params.itemId);
}
},
// Initialize an item
initializeItem (itemId) {
this.props.dispatch(selectItem(itemId));
this.props.dispatch(loadItemData());
},
// Called when a new item is created
onCreate (item) {
// Hide the create form
this.toggleCreateModal(false);
// Redirect to newly created item path
const list = this.props.currentList;
this.context.router.push(`${Keystone.adminPath}/${list.path}/${item.id}`);
},
// Open and close the create new item modal
toggleCreateModal (visible) {
this.setState({
createIsOpen: visible,
});
},
// Render this items relationships
renderRelationships () {
const { relationships } = this.props.currentList;
const keys = Object.keys(relationships);
if (!keys.length) return;
return (
<div className="Relationships">
<Container>
<h2>Relationships</h2>
{keys.map(key => {
const relationship = relationships[key];
const refList = listsByKey[relationship.ref];
const { currentList, params, relationshipData, drag } = this.props;
return (
<RelatedItemsList
key={relationship.path}
list={currentList}
refList={refList}
relatedItemId={params.itemId}
relationship={relationship}
items={relationshipData[relationship.path]}
dragNewSortOrder={drag.newSortOrder}
dispatch={this.props.dispatch}
/>
);
})}
</Container>
</div>
);
},
// Handle errors
handleError (error) {
const detail = error.detail;
if (detail) {
// Item not found
if (detail.name === 'CastError'
&& detail.path === '_id') {
return (
<Container>
<Alert color="danger" style={{ marginTop: '2em' }}>
No item matching id "{this.props.routeParams.itemId}".
<Link to={`${Keystone.adminPath}/${this.props.routeParams.listId}`}>
Got back to {this.props.routeParams.listId}?
</Link>
</Alert>
</Container>
);
}
}
if (error.message) {
// Server down + possibly other errors
if (error.message === 'Internal XMLHttpRequest Error') {
return (
<Container>
<Alert color="danger" style={{ marginTop: '2em' }}>
We encountered some network problems, please refresh.
</Alert>
</Container>
);
}
}
return (
<Container>
<Alert color="danger" style={{ marginTop: '2em' }}>
An unknown error has ocurred, please refresh.
</Alert>
</Container>
);
},
render () {
// If we don't have any data yet, show the loading indicator
if (!this.props.ready) {
return (
<Center height="50vh" data-screen-id="item">
<Spinner />
</Center>
);
}
// When we have the data, render the item view with it
return (
<div data-screen-id="item">
{(this.props.error) ? this.handleError(this.props.error) : (
<div>
<Container>
<EditFormHeader
list={this.props.currentList}
data={this.props.data}
toggleCreate={this.toggleCreateModal}
/>
<CreateForm
list={this.props.currentList}
isOpen={this.state.createIsOpen}
onCancel={() => this.toggleCreateModal(false)}
onCreate={(item) => this.onCreate(item)}
/>
<EditForm
list={this.props.currentList}
data={this.props.data}
dispatch={this.props.dispatch}
router={this.context.router}
/>
</Container>
{this.renderRelationships()}
</div>
)}
</div>
);
},
});
module.exports = connect((state) => ({
data: state.item.data,
loading: state.item.loading,
ready: state.item.ready,
error: state.item.error,
currentList: state.lists.currentList,
relationshipData: state.item.relationshipData,
drag: state.item.drag,
}))(ItemView);
|
app/containers/Orders/index.js
|
RichAbrahams/electron-project
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import * as actions from './actions';
import * as selectors from './selectors';
import SectionHeader from '../../components/SectionHeader';
class Orders extends Component {
componentDidMount() {
this.props.getUnfullfilledOrders();
}
render() {
return (
<SectionHeader text="ORDERS" icon="envelope">
{this.props.data}
</SectionHeader>
);
}
}
const mapStateToProps = createStructuredSelector({
});
function mapDispatchToProps(dispatch) {
return {
getUnfullfilledOrders: () => dispatch(actions.getUnfulfilledOrders()),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Orders);
|
react_native_frontend/index.android.js
|
CUNYTech/BudgetApp
|
import React, { Component } from 'react';
import {
AppRegistry,
StatusBar
} from 'react-native';
import App from './src/app';
StatusBar.setHidden(true);
AppRegistry.registerComponent('BudgetApp', () => App);
|
project/src/scenes/Admin/Navigation/components/NavigationEditor/NavigationEditor.js
|
boldr/boldr
|
/* @flow */
import React from 'react';
import styled from 'styled-components';
import NavigationForm from '../NavigationForm';
export type Props = {
onFormSubmit?: Function,
initialValues?: {
position?: number,
link?: string,
name?: string,
},
};
const FormInner = styled.div`padding: 1em;`;
const NavigationEditor = (props: Props) => {
return (
<FormInner>
<NavigationForm
initialValues={props.initialValues}
enableReinitialize
onSubmit={props.onFormSubmit}
/>
</FormInner>
);
};
export default NavigationEditor;
|
src/components/NotFoundPage/NotFoundPage.js
|
ShaneDrury/clicker
|
/*
* React.js Starter Kit
* Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
'use strict';
//require('./NotFoundPage.less');
import React from 'react';
var NotFoundPage = React.createClass({
render() {
return (
/* jshint ignore:start */
<div>
<h1>Page Not Found</h1>
<p>Sorry, but the page you were trying to view does not exist.</p>
</div>
/* jshint ignore:end */
);
}
});
module.exports = NotFoundPage;
|
packages/material-ui-icons/src/TabletAndroid.js
|
AndriusBil/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let TabletAndroid = props =>
<SvgIcon {...props}>
<path d="M18 0H6C4.34 0 3 1.34 3 3v18c0 1.66 1.34 3 3 3h12c1.66 0 3-1.34 3-3V3c0-1.66-1.34-3-3-3zm-4 22h-4v-1h4v1zm5.25-3H4.75V3h14.5v16z" />
</SvgIcon>;
TabletAndroid = pure(TabletAndroid);
TabletAndroid.muiName = 'SvgIcon';
export default TabletAndroid;
|
src/Select.js
|
prometheusresearch/react-ui
|
/**
* @copyright 2016-present, Prometheus Research, LLC
* @flow
*/
import React from 'react';
export const NOVALUE = '__NOVALUE__';
const NOVALUE_OPTION = {label: '', value: NOVALUE};
type Option = {
value: string,
label?: string,
hint?: string,
};
type Props = {
options: Array<Option>,
value: string,
allowNoValue?: boolean,
onChange: (?string) => *,
};
export default class Select extends React.Component<*, Props, *> {
render() {
let {options, value, allowNoValue} = this.props;
if (value == null) {
value = NOVALUE;
}
if (value === NOVALUE || allowNoValue) {
options = [NOVALUE_OPTION].concat(options);
}
return (
<select value={value} onChange={this.onChange}>
{options.map(this.renderOption, this)}
</select>
);
}
renderOption(option: Option) {
let key = option.value === NOVALUE ? '__NOVALUE__' : option.value;
return (
<option key={key} value={option.value}>
{option.label}
</option>
);
}
onChange = (event: UIEvent) => {
// $FlowIssue: ...
let value = event.target.value;
if (value === NOVALUE) {
value = null;
}
this.props.onChange(value);
};
}
|
src/utils/createContextWrapper.js
|
insionng/react-bootstrap
|
import React from 'react';
/**
* Creates new trigger class that injects context into overlay.
*/
export default function createContextWrapper(Trigger, propName) {
return function (contextTypes) {
class ContextWrapper extends React.Component {
getChildContext() {
return this.props.context;
}
render() {
// Strip injected props from below.
const {wrapped, context, ...props} = this.props;
return React.cloneElement(wrapped, props);
}
}
ContextWrapper.childContextTypes = contextTypes;
class TriggerWithContext {
render() {
const props = {...this.props};
props[propName] = this.getWrappedOverlay();
return (
<Trigger {...props}>
{this.props.children}
</Trigger>
);
}
getWrappedOverlay() {
return (
<ContextWrapper
context={this.context}
wrapped={this.props[propName]}
/>
);
}
}
TriggerWithContext.contextTypes = contextTypes;
return TriggerWithContext;
};
}
|
src/views/Statistic/StatisticLabel.js
|
Semantic-Org/Semantic-UI-React
|
import cx from 'clsx'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
createShorthandFactory,
customPropTypes,
getElementType,
getUnhandledProps,
} from '../../lib'
/**
* A statistic can contain a label to help provide context for the presented value.
*/
function StatisticLabel(props) {
const { children, className, content } = props
const classes = cx('label', className)
const rest = getUnhandledProps(StatisticLabel, props)
const ElementType = getElementType(StatisticLabel, props)
return (
<ElementType {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
StatisticLabel.propTypes = {
/** An element type to render as (string or function). */
as: PropTypes.elementType,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
}
StatisticLabel.create = createShorthandFactory(StatisticLabel, (content) => ({ content }))
export default StatisticLabel
|
React Fundamentals/Exam_prep_2/exam-prep-2/src/App.js
|
NikiStanchev/SoftUni
|
import React, { Component } from 'react';
import { Route, Switch, withRouter } from 'react-router-dom';
import Header from './components/common/Header';
import RegisterPage from './components/Auth/RegisterPage';
import LoginPage from './components/Auth/LoginPage';
import HomePage from './components/HomePage/HomePage';
import CreatePage from './components/Create/CreatePage'
import DetailsPage from './components/Details/DetailsPage'
import PrivateRoute from './components/common/PrivateRoute'
class App extends Component {
constructor(props) {
super(props);
this.onLogout = this.onLogout.bind(this);
}
onLogout() {
localStorage.clear();
this.props.history.push('/');
}
render() {
return (
<div className="App">
<Header loggedIn={localStorage.getItem('authToken') !== null} onLogout={this.onLogout} />
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/view/:page" component={HomePage} />
<PrivateRoute path="/details/:id" component={DetailsPage} />
<Route path="/login" component={LoginPage} />
<Route path="/register" component={RegisterPage} />
<Route path="/create" component={CreatePage} />
</Switch>
</div>
);
}
}
export default withRouter(App);
|
src/DatePicker.js
|
yyssc/ssc-grid
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { default as ReactBootstrapDatePicker } from 'react-bootstrap-date-picker';
/**
* DatePicker控件
*/
export default class DatePicker extends Component {
static displayName = 'DatePicker'
static defaultProps = {
dateFormat: 'YYYY-MM-DD'
}
static propTypes = {
id: PropTypes.string,
/**
* value
*/
value: PropTypes.string,
/**
* 日期格式,支持如下集中格式
* <pre><code>'MM/DD/YYYY', 'DD/MM/YYYY', 'YYYY/MM/DD', 'DD-MM-YYYY'</code></pre>
*/
dateFormat: PropTypes.string,
onChange: PropTypes.func
};
state = {
};
constructor(props) {
super(props);
}
handleChange(event) {
if (this.props.onChange) {
this.props.onChange(event);
}
}
render() {
const { id, value, dateFormat } = this.props;
return (<ReactBootstrapDatePicker
id={id} value={value}
dayLabels={['日', '一', '二', '三', '四', '五', '六']}
monthLabels={['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']}
dateFormat={dateFormat}
onChange={this.handleChange.bind(this)}
/>);
}
}
|
src/main.js
|
rickyduck/pp-frontend
|
import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import AppContainer from './containers/AppContainer'
// ========================================================
// Store Instantiation
// ========================================================
const initialState = window.___INITIAL_STATE__
const store = createStore(initialState)
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('collections-holder')
let render = () => {
const routes = require('./routes/index').default(store)
ReactDOM.render(
<AppContainer store={store} routes={routes} />,
MOUNT_NODE
)
}
// This code is excluded from production bundle
if (__DEV__) {
if (module.hot) {
// Development render functions
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react').default
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
// Wrap render in try/catch
render = () => {
try {
renderApp()
} catch (error) {
console.error(error)
renderError(error)
}
}
// Setup hot module replacement
module.hot.accept('./routes/index', () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE)
render()
})
)
}
}
// ========================================================
// Go!
// ========================================================
render()
|
project-the-best/src/component/dialog/Dialog.js
|
renhongl/Summary
|
import React, { Component } from 'react';
import { Draggable } from '../../share/mr/mr';
import { Icon } from 'antd';
import { lang } from '../../share/config/lang';
import './style.less';
export default class Dialog extends Component{
constructor(props) {
super(props);
}
componentDidMount() {
new Draggable({
container: this.dialog,
dragZone: '.dialog-header'
});
}
onClick = () => {
let allDialog = document.querySelectorAll('.dialog');
for(let dialog of allDialog) {
dialog.style.zIndex = 10;
}
this.dialog.style.zIndex = 20;
}
closeDialog = () => {
this.props.closeDialog(this.dialog.id);
}
minDialog = () => {
this.props.minDialog(this.dialog.id);
}
render() {
const { config, options } = this.props;
const { backgroundColor, opacity, fontColor, language } = config;
const { show, id, status, width, height, left, top } = options;
const w = width || window.innerWidth * 0.9;
const h = height || window.innerHeight * 0.9;
const style = {
backgroundColor: `rgba(${backgroundColor},${opacity})`,
color: fontColor,
width: w,
height: h,
zIndex: 10,
left: left || (window.innerWidth - w) * 0.5,
top: top || (window.innerHeight - h) * 0.5
}
const styleHeader = {
// backgroundColor: `rgba(${backgroundColor},${opacity})`,
color: fontColor,
}
return (
<section
ref={dialog => this.dialog = dialog}
className={show ? 'dialog show' : 'dialog hide'}
style={style}
id={id}
status={status}
onClick={this.onClick}
>
<div className='dialog-header' style={styleHeader} >
<span className='title'>{lang[language][id.toUpperCase()]}</span>
<span className='dialog-close'><Icon type="close" onClick={this.closeDialog}/></span>
<span className='dialog-close'><Icon type="minus" onClick={this.minDialog}/></span>
</div>
<div className='dialog-content'>{this.props.children}</div>
</section>
)
}
}
|
packages/slate-react/test/rendering/fixtures/custom-decorator.js
|
ashutoshrishi/slate
|
/** @jsx h */
import React from 'react'
import h from '../../helpers/h'
function decorateNode(block) {
const text = block.getFirstText()
return [
{
anchorKey: text.key,
anchorOffset: 1,
focusKey: text.key,
focusOffset: 2,
marks: [{ type: 'bold' }],
},
]
}
function Bold(props) {
return React.createElement('strong', null, props.children)
}
function renderMark(props) {
switch (props.mark.type) {
case 'bold':
return Bold(props)
}
}
export const props = {
decorateNode,
renderMark,
}
export const value = (
<value>
<document>
<paragraph>one</paragraph>
</document>
</value>
)
export const output = `
<div data-slate-editor="true" contenteditable="true" role="textbox">
<div style="position:relative">
<span>
<span>o</span>
<span><strong>n</strong></span>
<span>e</span>
</span>
</div>
</div>
`.trim()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.