{"_id":"@arve.knudsen/fun-component","_rev":"2-02f7e9d9a5cb901380d45f7ffacb66af","name":"@arve.knudsen/fun-component","dist-tags":{"latest":"3.1.0"},"versions":{"3.1.0":{"name":"@arve.knudsen/fun-component","version":"3.1.0","description":"Functional approach to authoring performant HTML components using plugins","main":"index.js","scripts":{"posttest":"standard","test":"npm run test:node && npm run test:browser","test:browser":"browserify test/browser.js | tape-run | tap-format-spec","test:node":"NODE_ENV=test node test/node.js | tap-format-spec","example:mapbox":"npm start --prefix ./examples/mapbox -- -- --transform-key=development","example:list":"npm start --prefix ./examples/list -- -- --transform-key=development","example:expandable":"npm start --prefix ./examples/expandable -- -- --transform-key=development"},"repository":{"type":"git","url":"git+https://github.com/aknuds1/fun-component.git"},"keywords":["choo","bel","component","html","function"],"author":{"name":"Arve Knudsen","email":"arve.knudsen@gmail.com"},"license":"MIT","bugs":{"url":"https://github.com/aknuds1/fun-component/issues"},"homepage":"https://github.com/aknuds1/fun-component#readme","devDependencies":{"@tap-format/spec":"^0.2.0","bel":"^5.1.5","browserify":"^15.2.0","standard":"^10.0.3","tape":"^4.8.0","tape-run":"^3.0.0"},"dependencies":{"nanoassert":"^1.1.0","nanocomponent":"^6.4.2","nanologger":"^1.3.0"},"gitHead":"6dd3c5b187129b64918d8b0d79713aa330a3c207","_id":"@arve.knudsen/fun-component@3.1.0","_npmVersion":"5.6.0","_nodeVersion":"9.5.0","_npmUser":{"name":"arve.knudsen","email":"arve.knudsen@gmail.com"},"dist":{"integrity":"sha512-MEAaysbukNK+l0AUk2GGM1ObX5GWqvJXNRoDiw30RrWrirHKQrxWJ9gLPicQYdP2cs38huF5l5t+LAxGyZMosw==","shasum":"0b3293c19688005b8f9b9fdb88278c66361d7b09","tarball":"https://registry.npmjs.org/@arve.knudsen/fun-component/-/fun-component-3.1.0.tgz","fileCount":23,"unpackedSize":50803,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDPG1zsKLbuMxe4wZpy+brUcJbQ2n6VAlqtSGP71iiwqAIgRSnPDCUY4Sy+OuRwMUKv0U/EHWrd+eWbkYe2vhSzmnM="}]},"maintainers":[{"name":"arve.knudsen","email":"arve.knudsen@gmail.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/fun-component_3.1.0_1518697411071_0.9056601776500239"},"_hasShrinkwrap":false}},"time":{"created":"2018-02-15T12:23:30.787Z","3.1.0":"2018-02-15T12:23:31.894Z","modified":"2022-04-04T15:41:13.691Z"},"maintainers":[{"name":"arve.knudsen","email":"arve.knudsen@gmail.com"}],"description":"Functional approach to authoring performant HTML components using plugins","homepage":"https://github.com/aknuds1/fun-component#readme","keywords":["choo","bel","component","html","function"],"repository":{"type":"git","url":"git+https://github.com/aknuds1/fun-component.git"},"author":{"name":"Arve Knudsen","email":"arve.knudsen@gmail.com"},"bugs":{"url":"https://github.com/aknuds1/fun-component/issues"},"license":"MIT","readme":"<div align=\"center\">\n\n# fun-component\n\n[![npm version](https://img.shields.io/npm/v/fun-component.svg?style=flat-square)](https://npmjs.org/package/fun-component) [![build status](https://img.shields.io/travis/tornqvist/fun-component/master.svg?style=flat-square)](https://travis-ci.org/tornqvist/fun-component)\n[![downloads](http://img.shields.io/npm/dm/fun-component.svg?style=flat-square)](https://npmjs.org/package/fun-component)\n[![style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://npmjs.org/package/fun-component)\n\n</div>\n\nA functional approach to authoring performant HTML components using plugins. Syntactic suggar on top of [nanocomponent](https://github.com/choojs/nanocomponent). Pass in a function and get another function back that handles rerendering as needed when called upon.\n\n- [Usage](#usage)\n- [API](#api)\n  - [Context](#context)\n  - [Lifecycle](#lifecycle)\n  - [Plugins](#plugins)\n- [Examples](#examples)\n- [Why tho?](#why-tho)\n\n## Usage\n\nThe most straightforward use is to pass in a function and have the default shallow diff figure out whether to rerender the component on consecutive calls.\n\n```javascript\n// button.js\nconst html = require('bel')\nconst component = require('fun-component')\n\nmodule.exports = component(function button (ctx, clicks, onclick) {\n  return html`\n    <button onclick=${onclick}>\n      Clicked ${clicks} times\n    </button>\n  `\n})\n```\n\n```javascript\n// app.js\nconst choo = require('choo')\nconst html = require('choo/html')\nconst button = require('./button')\n\nconst app = choo()\napp.route('/', view)\napp.mount('body')\n\nfunction view (state, emit) {\n  return html`\n    <body>\n      ${button(state.clicks, () => emit('click'))}\n    </body>\n  `\n}\n\napp.use(function (state, emitter) {\n  state.clicks = 0\n  emitter.on('click', () => {\n    state.clicks += 1\n    emitter.emit(state.events.RENDER)\n  })\n})\n```\n\n### Standalone\n\nThough fun-component was authored with [choo](https://github.com/choojs/choo) in mind it works just as well standalone!\n\n```javascript\nconst button = require('./button')\n\nlet clicks = 0\nfunction onclick () {\n  clicks += 1\n  button(clicks, onclick)\n}\n\ndocument.body.appendChild(button(clicks, onclick))\n```\n\n## API\n\n### `component(render<function>)`\n### `component(name<string>, render<function>)`\n\nCreate a new component context. Either takes a function as an only argument or a name and a function. Returns a function that renders the element. If no name is supplied the name is derrived from the functions `name` property.\n\n*Warning: implicit function names are most probably mangled during minification. If name consistency is important to your implementation, use the explicit name syntax.*\n\n```javascript\ncomponent('hello', () => html`<h1>Hi there!</h1>`)\n```\n\n### Context\n\nThe component context (`ctx`) is prefixed to the arguments of all lifecycle hooks and the render function itself. The context object can be used to access the underlying nanocomponent instance.\n\n```javascript\n// Exposing nanocomponent inner workings\ncomponent(function echo(ctx) {\n  return html`<h1>I'm ${ctx._name} on the ${ctx._hasWindow ? 'client' : 'server'}</h1>`\n})\n```\n\n### Lifecycle\n\nAll the lifecycle hooks of nanocomponent are supported, i.e. [`beforerender`](https://github.com/choojs/nanocomponent#nanocomponentprototypebeforerenderel), [`load`](https://github.com/choojs/nanocomponent#nanocomponentprototypeloadel), [`unload`](https://github.com/choojs/nanocomponent#nanocomponentprototypeunloadel), [`afterupdate`](https://github.com/choojs/nanocomponent#nanocomponentprototypeafterupdateel), and [`afterreorder`](https://github.com/choojs/nanocomponent#nanocomponentprototypeafterreorderel). Lifecycle hooks are declared on the element itself (with an \"on\" prefix) and are forwarded to the underlying nanocomponent instance.\n\nAll lifecycle hooks are called with the context object and the latest arguments used to call the component.\n\n#### Update\n\nfun-component comes with a baked in default update function that performs a shallow diff of arguments to determine whether to update the component. Setting `onupdate` on the element overrides this default behavior.\n\n##### `onupdate(ctx<object>, args<array>, prev<array>)`\n\nOpposed to how nanocomponent calls the update function to detemrine whether to rerender the component, fun-component not only supplies the next arguments but also the previous arguments. These two can then be compared to determine whether to update.\n\n*Tip: Using ES2015 deconstruction makes this a breeze.*\n\n```javascript\ncomponent(function greeting(ctx, title) {\n  return html`<h1 onupdate=${update}>Hello ${title}!</h1>`\n})\n\n// Deconstruct arguments and compare `title`\nfunction update(ctx, [next], [prev]) {\n  return next !== prev\n}\n```\n\n#### Example\n\nUsing every lifecycle hook available. The rendered element can be accessed on the context object as `ctx.element`.\n\n```javascript\ncomponent(function hooks(ctx, title) {\n  return html`\n    <div onupdate=${update} onbeforerender=${beforerender} onload=${load} onunload=${unload} onafterupdate=${afterupdate} onafterreorder=${afterreorder}>\n      Hello ${title}!\n    </div>\n  `\n})\n\nfunction update(ctx, [title], [prev]) {\n  console.log(`diffing ${title} and ${prev}`)\n  return title !== prev\n}\n\nfunction beforerender(ctx, title) {\n  console.log(`will render with ${title}`)\n}\n\nfunction load(ctx, title) {\n  console.log(ctx.element, `mounted in DOM with ${title}`)\n}\n\nfunction unload(ctx, title) {\n  console.log(ctx.element, `removed from DOM with ${title}`)\n}\n\nfunction afterupdate(ctx, title) {\n  console.log(`updated with ${title}`)\n}\n\nfunction afterreorder(ctx, title) {\n  console.log(`reordered with ${title}`)\n}\n```\n\n### Plugins\n\nPlugins are middleware functions that are called just before the component is rendered or updated. A plugin can inspect the arguments, modify the context object or even return another context object that is to be used for rendering the component.\n\n```javascript\nconst html = require('bel')\nconst component = require('fun-component')\n\nconst greeter = component(function greeting(ctx, title) {\n  return html`<h1>Hello ${title}!</h1>`\n})\n\ngreeter.use(function log(ctx, title) {\n  console.log(`Rendering ${ctx._ncID} with ${title}`)\n  return ctx\n})\n\ndocument.body.appendChild(greeter('world'))\n```\n\nfun-component is bundled with with a handfull of plugins that cover the most common scenarios. Have you written a plugin you want featured in this list? Fork, add, and make a pull request!\n\n- [spawn](spawn) – Spawn component contexts on demand and discard on unload.\n- [restate](restate) – Add state object and state management to the context object.\n- [logger](logger) – Add a logger (using [nanologger](https://github.com/choojs/nanologger)) to the context object.\n- [cache](cache) – Cache element and reuse on consecutive mounts.\n\n## Examples\n\nFor example implementations, see [/examples](/examples). Either spin them up locally or visit the link.\n\n- Mapbox (using [cache](cache))\n  - `npm run example:mapbox`\n  - https://fun-component-mapbox.now.sh\n- List (using [spawn](spawn))\n  - `npm run example:list`\n  - https://fun-component-list.now.sh\n- Expandable (using [spawn](spawn) and [restate](restate))\n  - `npm run example:expandable`\n  - https://fun-component-expandable.now.sh\n\n## Why tho?\n\nAuthoring a component should be as easy as writing a function. Using arguments and scope to handle state is both implicit and transparent. Worrying about calling context, and stashing things on `this` makes for cognitive overhead.\n\nNot for you? If object oriented programming is your thing, use [nanocomponent](https://github.com/choojs/nanocomponent). If you're more into events, maybe [microcomponent](https://github.com/yoshuawuyts/microcomponent) is a good fit.\n\n## See Also\n\n- [yoshuawuyts/microcomponent](https://github.com/yoshuawuyts/microcomponent)\n- [jongacnik/component-box](https://github.com/jongacnik/component-box)\n- [choojs/nanocomponent](https://github.com/choojs/nanocomponent)\n- [choojs/choo](https://github.com/choojs/choo)\n- [shama/bel](https://github.com/shama/bel)\n\n## License\n\n[MIT](https://tldrlegal.com/license/mit-license)\n","readmeFilename":"README.md"}