UNPKG

16.3 kBMarkdownView Raw
1# Composi
2
3[![npm](https://img.shields.io/npm/v/composi.svg)](https://www.npmjs.org/package/composi)
4[![Gzip Size](https://img.badgesize.io/https://unpkg.com/composi/dist/composi.js.gzip)](https://www.npmjs.org/package/composi)
5[![apm](https://img.shields.io/npm/l/composi.svg)](https://www.npmjs.org/package/composi)
6[![npm](https://img.shields.io/npm/dt/composi.svg)](https://www.npmjs.org/package/composi)
7[![Read the Docs (version)](https://img.shields.io/readthedocs/pip/stable.svg)](https://composor.github.io)
8
9Composi is a framework for creating desktop and mobile apps. With Composi you can create a dynamic website with reactive components, a progressive web app, or a hybrid app for mobile app stores. Visit the [website](https://composor.github.io).
10
11Composi is small. The core is barely 3KB gzipped. It therefore loads fast. Its virtual DOM updates components efficiently and quickly. It has an API very similar to React, while mainting it's emphasis on simplicity, size, and ease of learning. In fact, you can learn everything you need to know to build apps with Composi in an hour or two.
12
13Composi components can be stateless or stateful. Stateful components are reactive. When you change a component's state, that triggers the component's render function. That in turn creates a new virtual DOM based on the data changes. It then patches the DOM to match the changes. If there are no changes, nothing will happen.
14
15A component's markup is written with JSX. This means you can create custom tags to organize your component's template. You can also pass props to a component tag. If you prefer, you can instead use the `h` function to define the component's markup with hyperscript. In fact, at render time the JSX is converted to this.
16
17## Browser Support
18
19Composi is compatible with browsers back to IE 9 on Windows 7, although you may need to include a [polyfill for promises](https://github.com/stefanpenner/es6-promise) for complete compatibility.
20
21
22
23## Breaking Changes in Version 3.0.0
24
25Upgrading from Composi 2.x.x to 3.x.x will require addressing two breaking changes. If you are using functional components, pay attention to the change in the call signature for the `render` function. Secondly, if you are using hydration with class components, this is now done with a `hydrate` property.
26
27### render
28
29In version 3.x.x the `render` function returns a vitual node representing the current tree of the component. This needs to be assigned to the same variable used to capture the result of the `mount` function. Also, the `render` function now expects a third argument, the container the component is in. Notice in the following example how we mount a component, capturing its result in the variable `list`, then use that again when we `render` the component in the `addItem` function:
30
31```javascript
32import { h, mount, render } from 'composi'
33
34let input = null
35let key = 104
36const fruits = [
37 { key: 101, value: 'Apples' },
38 { key: 102, value: 'Oranges' },
39 { key: 103, value: 'Bananas' }
40]
41function List(props) {
42 function init(el) {
43 input = el.querySelector('input')
44 input.focus()
45 }
46 function addItem() {
47 const value = input.value
48 if (value) {
49 fruits.push({
50 key: key++,
51 value
52 })
53 // Update the component.
54 // Pass list from mount and re-capture it.
55 // Don't forget to pass in container as last argument.
56 list = render(<List fruits={fruits} />, list, 'section')
57 input.value = ''
58 input.focus()
59 } else {
60 alert('Please add a value before submitting.')
61 }
62 }
63 return (
64 <div onmount={el => init(el)}>
65 <p>
66 <input type="text"/>
67 <button onclick={() => addItem()}>Add</button>
68 </p>
69 <ul>
70 {
71 props.fruits.map(item => <li key={item.key}>{item.value}</li>)
72 }
73 </ul>
74 </div>
75 )
76}
77
78let list = mount(<List fruits={fruits}/>, 'section')
79```
80
81### Class Component Hydration
82
83In version 3.x.x how class components hydrate was changed. It now uses the `hydrate` property to tell Composi what element to use for hydration. When Composi finds the `hydrate` property, it creates a virtual node from the DOM element and uses that to patch the DOM during the first render. This means faster initial render and reaching first interactivity sooner. Below is an example of using the `hydrate` property:
84
85```javascript
86import { h, Component }
87
88class List extends Component {
89 // Define list component here...
90}
91
92// Instantiate list component:
93const list = new List({
94 state: fruits,
95 container: 'section',
96 hydrate: '#old-list-from-server'
97})
98```
99
100If your class component is a single use one, you can put the `hydrate` property directly in the constuctor:
101
102```javascript
103import { h, Component }
104
105class List extends Component {
106 constructor(props) {
107 super(props)
108 this.state = fruits
109 this.container = 'section'
110 this.hydrate = '#old-list-from-server'
111 }
112 // Define rest of list component here...
113}
114
115// Instantiate list component:
116const list = new List()
117```
118
119## Live Examples on Codepen
120
1211. <a href='https://codepen.io/rbiggs/pen/GOyObq' target='__blank'>Todo List</a>
1223. <a href='https://codepen.io/rbiggs/pen/zPmERR' target='__blank'>Minimal Hacker News</a>
1232. <a href='https://codepen.io/rbiggs/pen/POMbxG' target='__blank'>Tour of Heroes (Client Side Routing)s</a>
1244. <a href='https://codepen.io/rbiggs/pen/MBdMKw' target='__blank'>Calculator</a>
1255. <a href='https://codepen.io/rbiggs/pen/qVxvOp' target='__blank'>Cat Image Browser</a>
1266. <a href='https://codepen.io/rbiggs/pen/EbovjJ' target='__blank'>Pythagoras Dancing Tree</a>
1277. <a href='https://codepen.io/rbiggs/pen/POpMMz' target='__blank'>Tic-Tac-Toe</a>
1288. <a href='https://codepen.io/rbiggs/pen/jYbVPe' target='__blank'>Rick and Morty Character Viewer</a>
1299. <a href='https://codepen.io/rbiggs/pen/VywZWE' target='__blank'>Slideshow Component</a>
13010. <a href='https://codepen.io/rbiggs/pen/gXopyN' target='__blank'>Coin Flip App</a>
13111. <a href='https://codepen.io/rbiggs/pen/LOZmbG' target='__blank'>Canvas Clock</a>
13212. <a href='https://codepen.io/rbiggs/pen/RjRpxL' target='__blank'>SVG Clock</a>
13313. <a href='https://codepen.io/rbiggs/pen/mqyxJX' target='__blank'>Spreadsheet</a>
13414. <a href='https://codepen.io/rbiggs/pen/oervxx' target='__blank'>Counter with Redux</a>
13515. <a href='https://codepen.io/rbiggs/pen/JygrLo' target='__blank'>Counter with Mobx</a>
136
137## Installation
138
139To install Composi, you'll need to have [Nodejs](https://nodejs.org/en/) installed. Open your terminal and run:
140
141```sh
142npm i -g composi
143```
144
145**Note:** On macOS and Linux, you may need to run the above command with `sudo`.
146
147## Create a New Project
148
149After installing Composi, you can use it to create a new project. The simplest way to do this is to provide a project name following the `-n` flag:
150
151```sh
152composi -n myproject
153```
154This will create a project named "myproject" on your desktop. If you want to have the project placed somewhere else, you can provide a path with the `-p` flag:
155
156```sh
157npm -n myproject -p dev/New \Projects
158```
159On Windows use the standard Windows file system path notation to define your project's path.
160
161## Project Structure
162
163A new project will have the following folder structure:
164```
165+--myproject
166| +--dev
167| +--components
168| |--title.js
169| +--css
170| |--styles.css
171| |--app.js
172| +--js
173|--.babelrc
174|--.editorconfig
175|--gulpfile.js
176|--index.html
177|--jsconfig.json
178|--package.json
179|--README.md
180```
181
182## Building
183
184To build your project, `cd` to its folder and run:
185
186```sh
187npm i
188```
189
190This will install the dependencies, build the project the first time and launch it in your default browser.
191
192At any other time you can build and launch the project. While in your project's root folder, run:
193
194```sh
195npm start
196```
197
198You can add other sub-folders to components, or create other folders inside the `dev` folder as necessary.
199
200`styles.css` is a CSS reset. We are using the Bootstrap 4 rest since it provides a consistent baseline for HTML across all browsers. `app.js` is the core of your website/app. `components` folder has one component: `list.js`. You can add more files for other component as needs. Feel free to add more folders and files to the `dev` folder as you see fit to achieve the structure your app needs. Import them into `app.js`. At build time the build script uses `app.js` to bundle all your files and output them to `js/app.js`. The `index.html` is automatically setup to import that script. `index.html` is your main page.
201
202## Example Code - Functional Component
203
204```javascript
205import { h, mount } from 'composi'
206
207function HelloWorld({name}) {
208 return (
209 <nav>
210 <h1>Hello, {name}!</h1>
211 </nav>
212 )
213}
214
215let hello = mount(<HelloWorld name='World' />, 'header')
216```
217
218## Example Code - Class Component
219
220```javascript
221import { h, Component } from 'composi'
222import { sampleData } from './data/sample-data'
223
224class List extends Component {
225 render(data) {
226 return (
227 <ul class='list'>
228 {
229 data.map(item => <li key={item.key}>{item.name}</li>)
230 }
231 </ul>
232 )
233 }
234}
235
236// Instantiate class to render component to DOM:
237new List({
238 container: 'section',
239 state: sampleData
240})
241```
242
243## Documentation
244
245To learn how to use Composi, open the [docs](./docs/index.md) folder for project documentation, or for in depth tutorials visit the [website](https://composor.github.io)
246
247## Summary
248
249Composi is all about components. These provide a great way to organize your code into modular and reusable chunks. The virtual DOM means you never have to touch the DOM to change something.
250
251Because Composi uses JSX, there are many similarities to React patterns. Please note that Composi is not a React clone. It is not trying to be compatible with React and the React ecosystem the way Preact and Inferno do. Component state is managed quite differently from React. Components lack the React refs and context properties. Also lacking, PropTypes. Events are not synthetic. They are either real inline events or the `handleEvent` interface. Props and custom tags are supported only because JSX provides these by default. The component architecture is actually adapted from the Component class of [ChocolateChip-UI](https://github.com/chocolatechip-ui/chocolatechipui). Changes were made to the API to work with a virtual DOM.
252
253Composi is small, just 3KB for the gzipped core. It loads quickly. Its small and focused API means you can learn everything in half a day and be productive. If you're already familiar with JSX, then you only need to learn the Component API. You can easily do that in an hour.
254
255## Type Safety
256
257Composi is written in standard ES6 with JSDoc comments to document type usage. This exposes Composi's type system to TypeScript during build time to verify that the source code is correctly typed. This also provides enhanced features when using Composi with [Visual Studio Code](https://code.visualstudio.com). Open `Settings` from the `Preferences` menu in Visual Studio Code and add the following:
258
259```javascript
260"javascript.implicitProjectConfig.checkJs": true
261```
262This tells Visual Studio Code to use TypeScript to check the JavaScript in a project. By default it uses inference to understand JavaScript types, which is very lax. But with JSDoc comments specifying types, it uses those instead for a more strict check of the code structure.
263
264This also gives intellisense when hovering over terms, intelligent code completion, symbol definition peek, symbol renaming across files, typo detection, flagging of unused variables, and wrong use of types as parameters, wrong number of parameters, etc. All of this is happening live, as you are coding. Not build step necessary.
265
266You can run a type check on Composi with TypeScript using this package script:
267
268```javascript
269npm run checkjs
270```
271This test gets run automatically when performiing a build:
272
273```shell
274npm run build
275> npm run format && npm run lint && npm run checkjs && npm run bundle && gulp gzip
276> prettier --no-semi --single-quote --write ./lib/*.js ./lib/utils/*.js
277> eslint --config ./.eslintrc.json lib
278> tsc --allowJs --checkJs --noEmit --target ES6 lib/*.js lib/**/*.js
279> rollup -c
280```
281
282## Running Tests
283
284Composi comes with unit test written with Mocha and Chai. These are loaded from a CDN, so you require an internet connect to run these tests. To run them, open your terminal and execute:
285
286```bash
287npm test
288```
289
290This will open a navigation page in your default browser. There are four tests:
291
2921. h
2932. fragment
2943. mount and render
2954. Component
296
297Clicking on one of these will open the test page. The test runs automatically when you open the page. Some errors may only show in the browser console, so open it to check. You can get back to the test navigation page by clicking any where on the top header.
298
299## What's Missing
300
301Composi is focused on one thing - providing a solution for components for building and structureing a projects. That means there are certain things it does not address, such as state management, routing, Ajax, and data persistence. There are already solutions that provide these, as enumerated below.
302
303### State Management
304Composi provides the barest support for state through the component's `state` property and `setState` method. However for a more robust solution you may prefer to use [Redux](http://redux.js.org), [Mobx](https://mobx.js.org), or some other state management solution. When you do so, you'll want to create stateless components. Read the documentation for [Component](./docs/components.md) to learn more about stateless components. If yo want something really minimal, take a look at [trkl](https://www.npmjs.com/package/trkl) and [pure](https://www.npmjs.com/package/purestate). You could event roll your own state management solution by defining a class and using Composi's [pubsub functions](./docs/pubsub.md), `subscribe` and `dispatch` for making it reactive. Another possibility for state management is [freezer-js](https://www.npmjs.com/package/freezer-js)
305
306### Router
307Composi does not provide a client-side router. However, you can use our blessed router [composi-router](https://www.npmjs.com/package/composi-router). The Github repository has documentation on how to use.
308
309Other alternatives for client-side routing are [Page.js](https://www.npmjs.com/package/page.js), [Universal Router](https://www.npmjs.com/package/universal-router), [Navigo](https://www.npmjs.com/package/navigo) or [rlite-router](https://www.npmjs.com/package/rlite-router).
310
311### Ajax
312Composi does not provide a means of aquiring remote data. If you only need to support current, ever-green browsers, you an use [fectch](). If you would like to use `fetch` with older browsers, you can provide the [WHATWG polyfill](https://github.com/whatwg/fetch). If don't need every possible feature of `fetch` and are concerned about the polyfill size, you can consider [unfetch](https://www.npmjs.com/package/unfetch). It's tiny and provides good support for the basics.
313
314If you would prefer an approach more like tradition Ajax championed by jQuery, you can take a look at [Axios](https://www.npmjs.com/package/axios).
315
316### Local Data Persistence
317If you need to persist data locally, you could use the browser's [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). If you need greater storage or a more sophisticated API, you might look at [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API). If you need support for older browsers, you might consider [localForage](https://www.npmjs.com/package/localforage). This is a libarary that uses whatever local dataStore is the best choice for the browser. It provides a simple interface that works the same for localStorage, WebSQL and IndexedDB.
318
319## Assorted Resources
320
321Useful resources for Composi, such as routing, Ajax, etc.: [Awesome Composi](https://github.com/composor/awesome-composi)
322
323
324## Prior Art
325
326Composi was not conceived in a vacuum. Inspiration came from exposure to:
327
3281. [vue](https://github.com/vuejs/vue)
3292. [react](https://github.com/facebook/react)
3303. [preact](https://github.com/developit/preact)
3314. [domvm](https://github.com/leeoniya/domvm)
3325. [yo-yo](https://github.com/maxogden/yo-yo)
3336. [choo](https://github.com/choojs/choo)
3347. [hyperapp](https://github.com/hyperapp/hyperapp)