Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Component): add react component for declarative management #1

Merged
merged 5 commits into from
Sep 11, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .babelrc
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
{
"presets": [
["@babel/preset-env", {"modules": false}],
"@babel/preset-react",
"@babel/preset-typescript"
],
"plugins": ["@babel/plugin-proposal-class-properties"],
"plugins": [
"@babel/plugin-proposal-class-properties",
["transform-react-remove-prop-types", {"mode": "wrap"}]
],
"env": {
"test": {
"plugins": [ "istanbul" ]
Expand Down
48 changes: 46 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Event Stack
<!-- Name -->
<h1 align="center">Event Stack</h1>

<!-- Badges -->
<p align="center">
Expand All @@ -21,14 +22,53 @@
<img src="http://img.badgesize.io/https://unpkg.com/@semantic-ui-react/event-stack/lib/cjs/event-stack.production.js?compression=gzip&label=gzip%20size&style=flat-square">
</p>

> A React component for binding events on the global scope.

## Installation

```bash
yarn add @semantic-ui-react/event-stack
# or
npm install @semantic-ui-react/event-stack
```

## Why?

The `EventStack` solves two design problems:

1. Reduces the number of connected listeners to DOM nodes compared to `element.addListener()`.
2. Respects event ordering. Example, two modals are open and you only want the top modal to close on document click.

## EventStack
## Usage

```jsx
import React, { Component } from 'react'
import EventStack from '@semantic-ui-react/event-stack'

class MyComponent extends Component {
handleResize = () => {
console.log('resize')
}

render() {
return (
<div>
<EventStack on={this.handleResize} target="window" />
</div>
)
}
}
```

##### Note on server-side rendering

When doing server side rendering, document and window aren't available. You can use a string as a `target`, or check that they exist before rendering the component with [`exenv`](https://github.com/JedWatson/exenv), for example.

##### Note on performance

You should avoid passing inline functions for listeners, because this creates a new Function instance on every render, defeating `EventListener`'s `shouldComponentUpdate`, and triggering an update cycle where it removes its old listeners and adds its new listeners (so that it can stay up-to-date with the props you passed in).

## Implementation details

The `EventStack` is a public API that allows subscribing a DOM node to events. The event subscription for
each unique DOM node creates a new `EventTarget` object.
Expand Down Expand Up @@ -77,3 +117,7 @@ subscribed handlers.
| | | |
+-----------+ +----------+
```

#### Credits

The idea of a React component is taken from [`react-event-listener`](https://www.npmjs.com/package/react-event-listener).
79 changes: 79 additions & 0 deletions build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
const fs = require('fs')
const rimraf = require('rimraf')
const { rollup } = require('rollup')

const plugins = require('./rollup.plugins')

const buildEntry = async (format, mode) => {
const inputConfig = {
external: [format === 'cjs' && 'exenv', 'prop-types', 'react'],
input: 'src/index.ts',
plugins: plugins(mode),
}
const outputConfig = {
exports: 'named',
file: `lib/${format}/event-stack.${mode}.js`,
format,
globals: format === 'umd' && {
'prop-types': 'PropTypes',
react: 'React',
},
name: 'EventStack',
}

const bundle = await rollup(inputConfig)

await bundle.generate(outputConfig)
await bundle.write(outputConfig)
}

const removeFiles = glob =>
new Promise((resolve, reject) =>
rimraf(glob, err => {
if (err) reject(err)
else resolve()
}),
)

const writeEntry = () =>
new Promise((resolve, reject) =>
fs.writeFile(
'./lib/index.js',
`
'use strict';

if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/event-stack.production.js');
} else {
module.exports = require('./cjs/event-stack.development.js');
}
`,
err => {
if (err) reject(err)
else resolve()
},
),
)

const build = async () => {
await removeFiles('./lib')

await Promise.all([
buildEntry('cjs', 'development'),
buildEntry('cjs', 'production'),
buildEntry('umd', 'development'),
buildEntry('umd', 'production'),
buildEntry('es', 'declarations'),
])

await Promise.all([
removeFiles('./lib/es'),
removeFiles('./lib/types/**/*.spec.d.ts'),
writeEntry(),
])
}

build().catch(err => {
console.error(err.stack)
process.exit(1)
})
23 changes: 19 additions & 4 deletions karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,37 @@ module.exports = config => {
reporters: [{ type: 'lcov', dir: 'coverage', subdir: '.' }],
includeAllSources: true,
},
files: [{ pattern: 'src/**/*.spec.ts', type: 'js', watched: false }],
files: [
// use UMD builds
{ pattern: 'node_modules/prop-types/prop-types.js', type: 'js', watched: false },
{ pattern: 'node_modules/react/umd/react.development.js', type: 'js', watched: false },
{
pattern: 'node_modules/react-test-renderer/umd/react-test-renderer.development.js',
type: 'js',
watched: false,
},

{ pattern: 'src/**/*.spec.ts', type: 'js', watched: false },
{ pattern: 'src/**/*.spec.tsx', type: 'js', watched: false },
],
frameworks: ['jasmine'],
mime: {
'text/x-typescript': ['ts', 'tsx'],
},
preprocessors: {
'src/**/*.ts': ['rollup'],
'test/**/*.ts': ['rollup'],
'src/**/*.{ts,tsx}': ['rollup'],
},
rollupPreprocessor: {
plugins: plugins(),
external: ['prop-types', 'react', 'react-test-renderer'],
plugins: plugins('test'),
output: {
globals: {
describe: 'describe',
expect: 'expect',
it: 'it',
'prop-types': 'PropTypes',
react: 'React',
'react-test-renderer': 'ReactTestRenderer',
},
file: 'test.js',
format: 'iife',
Expand Down
23 changes: 18 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,22 @@
"main": "lib/index.js",
"types": "lib/types/index.d.ts",
"dependencies": {
"exenv": "^1.2.2"
"exenv": "^1.2.2",
"prop-types": "^15.6.2"
},
"devDependencies": {
"@babel/core": "^7.0.0",
"@babel/plugin-proposal-class-properties": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"@babel/preset-typescript": "^7.0.0",
"@types/exenv": "^1.2.0",
"@types/jasmine": "^2.8.8",
"@types/prop-types": "^15.5.5",
"@types/react": "^16.4.14",
"@types/react-test-renderer": "^16.0.2",
"babel-plugin-istanbul": "^5.0.1",
"babel-plugin-transform-react-remove-prop-types": "^0.4.15",
"cross-env": "^5.2.0",
"husky": "^0.14.3",
"jasmine-core": "^3.2.1",
Expand All @@ -34,12 +40,15 @@
"karma-spec-reporter": "^0.0.32",
"lint-staged": "^7.2.2",
"prettier": "^1.14.2",
"react": "^16.5.0",
"react-dom": "^16.5.0",
"react-test-renderer": "^16.5.0",
"release-it": "^7.6.1",
"rollup": "^0.65.2",
"rollup-plugin-alias": "^1.4.0",
"rollup-plugin-babel": "^4.0.3",
"rollup-plugin-commonjs": "^9.1.6",
"rollup-plugin-node-resolve": "^3.4.0",
"rollup-plugin-replace": "^2.0.0",
"rollup-plugin-terser": "^2.0.2",
"rollup-plugin-typescript2": "^0.17.0",
"simulant": "^0.2.2",
Expand All @@ -48,9 +57,13 @@
"tslint-config-prettier": "^1.15.0",
"typescript": "^3.0.3"
},
"peerDependencies": {
"react": "^16.0.0",
"react-dom": "^16.0.0"
},
"scripts": {
"build": "node rollup.js",
"lint": "tslint \"./src/**/*.ts\" \"./test/**/*.ts\"",
"build": "node build.js",
"lint": "tslint \"./src/**/*.{ts,tsx}\" \"./test/**/*.{ts,tsx}\"",
"precommit": "lint-staged",
"postcommit": "git update-index --again",
"prerelease": "yarn lint && yarn test --browsers ChromeHeadless && yarn build",
Expand All @@ -77,7 +90,7 @@
"prettier --write",
"git add"
],
"*.ts": [
"*.{ts,tsx}": [
"prettier --parser typescript --write",
"tslint --fix",
"git add"
Expand Down
48 changes: 0 additions & 48 deletions rollup.js

This file was deleted.

17 changes: 7 additions & 10 deletions rollup.plugins.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
const path = require('path')

module.exports = mode =>
[
mode !== 'declarations' &&
require('rollup-plugin-alias')({
resolve: ['.ts'],
lib: path.resolve('./src/lib'),
}),
require('rollup-plugin-commonjs')({
include: /exenv/,
include: ['node_modules/exenv/**'].filter(Boolean),
extensions: ['.js'],
namedExports: {
'node_modules/exenv/index.js': ['canUseDOM'],
Expand All @@ -17,13 +10,17 @@ module.exports = mode =>
mode !== 'declarations' &&
require('rollup-plugin-babel')({
exclude: 'node_modules/**',
extensions: ['.ts', '.js'],
extensions: ['.ts', '.tsx', '.js'],
}),
require('rollup-plugin-node-resolve')({
extensions: ['.ts', '.js'],
extensions: ['.ts', '.tsx', '.js'],
browser: true,
jsnext: true,
main: true,
}),
require('rollup-plugin-replace')({
'process.env.NODE_ENV': JSON.stringify(mode),
}),
mode === 'production' && require('rollup-plugin-terser').terser(),
mode === 'declarations' &&
require('rollup-plugin-typescript2')({
Expand Down
Loading