Skip to content

Commit

Permalink
Merge pull request #1 from Knape/argument-refactor
Browse files Browse the repository at this point in the history
Argument refactor
  • Loading branch information
Knape authored Jun 20, 2017
2 parents 1a93ca7 + 0cb99f8 commit 76986b2
Show file tree
Hide file tree
Showing 11 changed files with 327 additions and 179 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@

### Releases

### `1.2.0` — June 20, 2017

- ***Beaking change*** - removes first argument in fire and load, so you now only need to pass event-type i.e. click to the method.
- Adds CustomEvent, everything not found in other events will be fired as a custom event

### `1.1.1` — June 15, 2017

- Adds an index value as secondary argument to path and tick in spray method
Expand Down
66 changes: 25 additions & 41 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ npm install --save-dev triggerhappy
import th from 'triggerhappy';

// fires a click event at 0x0 relative to elements position
th.fire('MouseEvent', 'click') // -> event
th.fire('click') // -> event
```

```es6
import th from 'triggerhappy';

// fires a click event at center of screen
const center = th.center(window);
th.fire('MouseEvent', 'click', document, center) // -> event
th.fire('click', document, center) // -> event
```

```es6
Expand All @@ -47,15 +47,15 @@ import th from 'triggerhappy';
// fire a touch event at 20% top and left of the image
const image = document.querySelector('img');
const imgCenter = th.position(image, {x: 20, y: 20});
th.fire('MouseEvent', 'click', image, imgCenter) // -> event
th.fire('click', image, imgCenter) // -> event
```

```es6
import th from 'triggerhappy';

// Simulate a drag horizotal effect (one finger)
th.fire('TouchEvent', 'touchstart');
const clip = th.load('TouchEvent', 'touchmove');
// Simulate a drag horizontal effect (one finger)
th.fire('touchstart');
const clip = th.load('touchmove');
th.spray(clip, {
path: ({touches}, index) => {
// Always good to extend the object so we
Expand All @@ -70,7 +70,7 @@ th.spray(clip, {
})
}
}).then((e) => {
th.fire('TouchEvent', 'touchend', document, e);
th.fire('touchend', document, e);
});
```

Expand All @@ -80,8 +80,8 @@ import th, { touches, center } from 'triggerhappy';
// Simulate a pinch out effect
const img = document.querySelector('img');
const touches = th.touches(th.position(img, {x: 40, y: 50}), th.position(img, {x: 60, y: 50}))
th.fire('TouchEvent', 'touchstart', img);
const clip = th.load('TouchEvent', 'touchmove', img, touches);
th.fire('touchstart', img);
const clip = th.load('touchmove', img, touches);
th.spray(clip, {
path: ({touches}, index) => ({
// Always good to extend the object so we
Expand All @@ -95,39 +95,31 @@ th.spray(clip, {
})
})
}).then((e) => {
th.fire('TouchEvent', 'touchend', img, e);
th.fire('touchend', img, e);
});
```

## API

> The API is still in heavy development, so dont hesitate to create a pull request
> The API is still in heavy development, so don't hesitate to create a pull request
## Fire

### th.fire(eventName, triggerName, [element], [options])
### th.fire(eventName, [element], [options])

> Fires an event specified by the type on the element
```es6
th.fire('MouseEvent', 'click', document, {
th.fire('click', document, {
...
});
```

**returns:** ```Object``` Event triggered

#### eventName ```String```
For the moment the type can either be `MouseEvent`, `TouchEvent`, `KeyboardEvent` or `CustomEvent`

* **required:** ```true```
* **default value:** ```MouseEvent```

#### triggerName ```String```
Depends on the current eventName passed to `th.fire`
Check [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Event) for a list of available triggers


* **required:** ```true```
* **default value:** ```click```

Expand All @@ -149,12 +141,12 @@ For a full list of passable options, see the [MDN documentation](https://develop

## Load

### th.load(eventName, triggerName, [element], [options])
### th.load(eventName, [element], [options])

> Higher order method for configure a fire event to be used with spray.
```es6
const clip = th.load('MouseEvent', document, {
const clip = th.load('click', document, {
...
})

Expand All @@ -163,16 +155,8 @@ const clip = th.load('MouseEvent', document, {
* **returns:** ```Function```

#### eventName ```String```
For the moment the eventName can either be `MouseEvent`, `TouchEvent` or `KeyboardEvent`

* **required:** ```true```
* **default value:** ```MouseEvent```

#### triggerName ```String```
Depends on the current eventName passed to `th.fire`
Check [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Event) for a list of available triggers


* **required:** ```true```
* **default value:** ```click```

Expand Down Expand Up @@ -200,7 +184,7 @@ For a full list of passable options, see the [MDN documentation](https://develop
> The spray method is intended to emulate a constant behavior, for example a pinch or a drag.
```es6
const clip = th.load('MouseEvent', 'click');
const clip = th.load('click');
th.spray(clip)
.then((event) => {});
```
Expand All @@ -219,8 +203,8 @@ Pass the returned function from load to spray either as a pure function or as an

```es6
// Start by creating a touch start event and return the current position that we fired on
const {clientX, clientY} = th.fire('TouchEvent', 'touchstart' document);
const clip = th.load('TouchEvent', 'touchmove', document, {clientX, clientY});
const {clientX, clientY} = th.fire('touchstart' document);
const clip = th.load('touchmove', document, {clientX, clientY});
// then we fire 10 touchmove events
th.spray(clip, {
speed: 10,
Expand All @@ -231,7 +215,7 @@ th.spray(clip, {
.then(({clientX, clientY}) => {
// and finally when we are done we end the cycle with a touchend event
// don't forget to pass our last current position
th.fire('TouchEvent', 'touchend', {clientX, clientY})
th.fire('touchend', {clientX, clientY})
);
```
Expand All @@ -247,7 +231,7 @@ Explanation of each option follows:
Sets the speed between each event that gets fired
```es6
const clip = th.load('MouseEvent', 'click');
const clip = th.load('click');
th.spray(clip, {
speed: 10,
})
Expand All @@ -259,7 +243,7 @@ Will be called with a delay of 10 ms between each cycle
Sets how many iterations spray should fire before calling then
```es6
const clip = th.load('MouseEvent', 'click');
const clip = th.load('click');
th.spray(clip, {
steps: 10,
}).then(() => {
Expand All @@ -277,7 +261,7 @@ Defines the path that each event iteration will use.
// Simulate a double click
// When passing an object each iteration will add to the current value
// i.e. for each iteration clientX will add 50 to its current value
const clip = th.load('MouseEvent', 'click');
const clip = th.load('click');
th.spray(clip, {
path: { clientX: 50, clientY: 50 }
});
Expand All @@ -290,7 +274,7 @@ th.spray(clip, {
// current object and passed to the new event
// In this case it takes its current clientX and adds one on each iteration
// Each function callback also supplies a secondary argument, the current index
const clip = th.load('TouchEvent', 'touchmove');
const clip = th.load('touchmove');
th.spray(clip, {
path: ({clientX, clientX}, index) => ({
// do something with the events
Expand All @@ -304,7 +288,7 @@ th.spray(clip, {
```es6
// Simulate a pinch out effect
const clip = th.load('TouchEvent', 'touchmove', document, touches(center(), center()));
const clip = th.load('touchmove', document, touches(center(), center()));
th.spray(clip, {
path: ({touches}, index) => ({
// Returns an array of events in the same order
Expand All @@ -323,7 +307,7 @@ Callback function for each event that gets fired, get called last after the even
Return true to exit the spray function, good for doing calculation instead of steps.
```es6
const clip = th.load('MouseEvent', 'click');
const clip = th.load('click');
th.spray(clip, {
times: Infinitive,
tick: (event, index) => {
Expand Down
9 changes: 9 additions & 0 deletions src/events/event.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,16 @@ import {
hasTouchEventSupport,
hasMouseEventSupport,
hasKeyboardEventSupport,
hasCustomEventSupport,
} from '../utils/helpers.utils';

export const getEventType = (triggerName: string): string => {
const filteredKeys = Object
.keys(eventMap)
.filter(eventKey => eventMap[eventKey].find(name => name === triggerName));
return first(filteredKeys, 'CustomEvent');
};

/**
* Creates a Native Event and falls back to
* document.createEvent if event does not exist
Expand All @@ -30,6 +38,7 @@ const createEventType = (
MouseEvent: (hasMouseEventSupport()) ? MouseEvent : null,
KeyboardEvent: (hasKeyboardEventSupport()) ? KeyboardEvent : null,
TouchEvent: (hasTouchEventSupport()) ? TouchEvent : null,
CustomEvent: (hasCustomEventSupport()) ? CustomEvent : null,
};

if (!eventNames[eventName]) {
Expand Down
104 changes: 94 additions & 10 deletions src/fire.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,110 @@
// @flow

import event from './events/event';
import { isElement, hasKeys, mergeArrayObjects } from './utils/helpers.utils';
import events, { getEventType } from './events/event';
import { position } from './utils/position.utils';

const fire = (
import {
isElement,
hasKeys,
mergeArrayObjects,
} from './utils/helpers.utils';


const isOldArgStyle = el => typeof el !== 'string';

export const logDeprecationWarning = (method: string): void => {
console.warn(`You are passing a deprecated argument style to ${method}`);
console.warn('Please update your code to the latest API');
console.warn('This will result in an error in the next version');
};

/**
*
* As we have two ways of passing arguents to both fire and load
* we need to convert them to the same argumentstyle
*
* @param {String} eventName
* @param {String} eventType
* @param {Node} element
* @param {Array} rest
*
**/
const createEventWrapper = (
eventName: string = 'MouseEvent',
triggerName: string = 'click',
eventType: string = 'click',
element: HTMLElement | Document = document,
...rest: Array<Object>
...rest: Array<any>
): Event => {
const options = rest.reduce(mergeArrayObjects, {});
const opts = rest.reduce(mergeArrayObjects, {});
// Append the correct client and page props to
// the options object if we dont pass any
if (isElement(element) && !hasKeys(options, 'clientX', 'clientY')) {
Object.assign(options, position(element));
if (isElement(element) && !hasKeys(opts, 'clientX', 'clientY')) {
Object.assign(opts, position(element));
}

// Create the custom event, dispatchit and then return the event
const newEvent = event(eventName)(triggerName, element, options);
const newEvent = events(eventName)(eventType, element, opts);
element.dispatchEvent(newEvent);
return newEvent;
};

export default fire;
export const fire = (
eventType: string = 'click',
element: HTMLElement | Document | string = document,
...rest: Array<Object | HTMLElement | Document>
): Event => {
const isNewStyle = isOldArgStyle(element);

if (!isNewStyle) logDeprecationWarning('fire');

// If we are passing arguments as the new style we
// need to find out what constructor we will use
const eventName = (isNewStyle) ?
getEventType(eventType) : eventType;

// Create the correct event beased on how we suppyly our arguments
return (typeof element !== 'string') ?
createEventWrapper(eventName, eventType, element, rest) :
createEventWrapper(eventName, element, rest[0], rest.slice(1));
};

/**
* Load Instance, works as fire but waiths for the spray method to call it.
*
* @param {String} eventName
* @param {String} eventType
* @param {Node} element
* @param {Object} options
**/
export const load = (
eventType: string = 'click',
element: HTMLElement | Document | string = document,
...rest: Array<Object | HTMLElement | Document>
): Function => {
return (opt: Object = {}) => {
return new Promise((resolve) => {
setTimeout(() => {
const isNewStyle = isOldArgStyle(element);

if (!isNewStyle) logDeprecationWarning('load');

// If we are passing arguments as the new style we
// need to find out what constructor we will use
const eventName = (isNewStyle) ?
getEventType(eventType) : eventType;

// Depending on what kind of arguments style we are using
// we nned to assign the correct argument to options
const options = (isNewStyle) ?
Object.assign({}, rest.reduce(mergeArrayObjects, {}), opt) :
Object.assign({}, rest.slice(1).reduce(mergeArrayObjects, {}), opt);

// Create the correct event beased on how we suppyly our arguments
const event = (typeof element !== 'string') ? // Otherwise flow compains
createEventWrapper(eventName, eventType, element, options) :
createEventWrapper(eventName, element, rest[0], options);
resolve({ event, eventName });
}, opt.speed || 0);
});
};
};
4 changes: 2 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fire from './fire';
import { load, spray } from './spray';
import { fire, load } from './fire';
import spray from './spray';
import rampage from './rampage';
import { position, center } from './utils/position.utils';
import touches from './events/touch.utils';
Expand Down
Loading

0 comments on commit 76986b2

Please sign in to comment.