Skip to content

Commit

Permalink
Initial release of ng.EventOptions
Browse files Browse the repository at this point in the history
  • Loading branch information
PierreDuc committed Sep 13, 2017
0 parents commit d9e86e4
Show file tree
Hide file tree
Showing 45 changed files with 7,938 additions and 0 deletions.
52 changes: 52 additions & 0 deletions .angular-cli.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
"name": "test-ng-event-options"
},
"apps": [
{
"root": "test/src",
"outDir": "test/dist-test",
"assets": [],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [],
"scripts": [],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"e2e": {
"protractor": {
"config": "./test/protractor.conf.js"
}
},
"lint": [
{
"project": "test/src/tsconfig.app.json"
},
{
"project": "test/src/tsconfig.spec.json"
},
{
"project": "test/e2e/tsconfig.e2e.json"
}
],
"test": {
"karma": {
"config": "./test/karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"component": {}
}
}
43 changes: 43 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# compiled output
/dist
/tmp
/out-tsc

# dependencies
/node_modules

# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
*.iml

# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
testem.log
/typings

# e2e
/test/e2e/*.js
/test/e2e/*.map

# System Files
.DS_Store
Thumbs.db

# cli
15 changes: 15 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
MIT License
Copyright (c) 2017 Kruijt

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
104 changes: 104 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# ng.EventOptions

This angular module will enable you to add event listener options inside the angular template. Like, capture,
passive and once, but also add an event listener outside the `NgZone` for additional performance of
your application and/or when fired stop the event from bubbling.

The module is only `2KB` gzipped

## Usage

Add an event like you are used to, but add a `*` after the name. To add the options to this event you
add an attribute which starts with the name of the event followed by a dot and then any of the
following characters (order is not important). All options default to `false`:

* p (creates an passive event)
* c (captures the event in the capture phase)
* o (after firing the event once, the listener will be removed)
* n (add the event listener outside the `NgZone`)
* s (stop the event from bubbling any further and preventing default)

Basic example:

<button (click*)="onClick($event)" click.pcon>Click</button>

This will create a click event on the button which is passive (p), will be fired on the capture (c) phase, will only be
fired once (o), and is running outside the `ngZone` (n)

There is also the option to add an event listener to a `nativeElement` inside your class. This will check
for compatibility of the current browser. If you add the optional `NgZone` reference, it will add the
event outside the `NgZone`. It returns an intermediate `EventListener` which you can use to remove the listener from
the element on `ngOnDestroy` for instance:

addEventOptionListener(
element: HTMLElement,
eventName: keyof DocumentEventMap,
eventListener: EventListener,
options: EventOptions,
ngZone?: NgZone
): EventListener;

Where `EventOptions` is :

interface EventOptions extends AddEventListenerOptions {
noZone?: boolean;
stop?: boolean;
}

Example:

@Component({/*...*/})
export class ExampleComponent implements OnInit, OnDestroy {
private listener: EventListener;
constructor(private elementRef: ElementRef, private ngZone: NgZone) {}
ngOnInit(): void {
this.listener = addEventOptionListener(this.elementRef.nativeElement, 'click', this.onClick, {
passive: true,
noZone: true,
}, this.ngZone);
}
ngOnDestroy(): void {
this.elementRef.nativeElement.removeEventListener('click', this.listener);
}
onClick: EventListener = (event: MouseEvent): void => {
console.log("I have been clicked");
};
}

## Supported events

blur, change, click, focus, input, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup,
scroll, touchend, touchmove, touchstart

## Extendability

If you are missing an event which you would like to have these features as well, you can extend
the `EoBaseDirective`:

@Directive({
selector: '[submit*]'
})
export class EoSubmitEventDirective extends EoBaseDirective<'customDocEvent'> {

@Output('submit*')
public output: EventEmitter<Event> = new EventEmitter<Event>();

protected eventName: 'submit' = 'submit';

constructor(elementRef: ElementRef, ngZone: NgZone) {
super(elementRef, ngZone);
}

}

## Limitations

* Keymap event is not (yet) supported `(keydown*.enter)`
* `@HostListener` is not supported. This is core angular, and cannot be hooked into. You can use the `ElementRef` of the
component, in combination with `addEventOptionListener`.

17 changes: 17 additions & 0 deletions generate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const replaceInTemplate = require('./generate/util/replaceInTemplate');
const parseDirectiveTemplate = require('./generate/util/parseDirectiveTemplate');
const supportedEvents = require('./generate/const/supportedEvents');

// Parsing directive template
const eventFiles = Object.keys(supportedEvents).map(parseDirectiveTemplate);

// Getting export import and class name strings
const exportsStr = eventFiles.map(eventFile => `export {${eventFile[0]}} from '${eventFile[1]}';`).join('\n');
const importsStr = eventFiles.map(eventFile => `import {${eventFile[0]}} from '${eventFile[1]}';`).join('\n');
const classNamesStr = eventFiles.map(eventFile => eventFile[0]).join(',\n');


// Replacing template replacement keys with appropriate values
replaceInTemplate('./directive/index.ts', 'Exports', exportsStr);
replaceInTemplate('./directive/eo-directives.ts', 'Imports', importsStr);
replaceInTemplate('./directive/eo-directives.ts', 'ClassNames', classNamesStr);
20 changes: 20 additions & 0 deletions generate/const/directiveTemplate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module.exports =
`import {EoBaseDirective} from "../eo-base.directive";
import {Directive, ElementRef, EventEmitter, NgZone, Output} from "@angular/core";
@Directive({
selector: '[{{eventName}}*]'
})
export class Eo{{EventName}}Directive extends EoBaseDirective<'{{eventName}}'> {
@Output('{{eventName}}*')
public output: EventEmitter<{{EventType}}> = new EventEmitter<{{EventType}}>();
protected eventName: '{{eventName}}' = '{{eventName}}';
constructor(elementRef: ElementRef, ngZone: NgZone) {
super(elementRef, ngZone);
}
}
`;
1 change: 1 addition & 0 deletions generate/const/sourceDir.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = './src/';
19 changes: 19 additions & 0 deletions generate/const/supportedEvents.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module.exports = {
"blur": "FocusEvent",
"change": "Event",
"click": "MouseEvent",
"focus": "FocusEvent",
"input": "Event",
"keydown": "KeyboardEvent",
"keypress": "KeyboardEvent",
"keyup": "KeyboardEvent",
"mousedown": "MouseEvent",
"mousemove": "MouseEvent",
"mouseout": "MouseEvent",
"mouseover": "MouseEvent",
"mouseup": "MouseEvent",
"scroll": "UIEvent",
"touchend": "TouchEvent",
"touchmove": "TouchEvent",
"touchstart": "TouchEvent"
};
20 changes: 20 additions & 0 deletions generate/util/parseDirectiveTemplate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const fs = require('fs');
const directiveTemplate = require('../const/directiveTemplate');
const supportedEvents = require('../const/supportedEvents');
const sourceDir = require('../const/sourceDir');

function parseDirectiveTemplate(eventName) {
const filename = `./events/eo-${eventName}.directive`;
const ucEventName = eventName.charAt(0).toUpperCase() + eventName.slice(1);
const className = `Eo${ucEventName}Directive`;
const template = directiveTemplate
.replace(/{{eventName}}/g, eventName)
.replace(/{{EventName}}/g, ucEventName)
.replace(/{{EventType}}/g, supportedEvents[eventName]);

fs.writeFileSync(`${sourceDir}directive/${filename}.ts`, template);
return [className, filename];

}

module.exports = parseDirectiveTemplate;
12 changes: 12 additions & 0 deletions generate/util/replaceInTemplate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const fs = require('fs');
const sourceDir = require('../const/sourceDir');

function replaceInTemplate(filename, replaceKey, replace) {
const fileData = fs
.readFileSync(sourceDir + filename, 'UTF-8')
.replace(new RegExp(`(//{{BEGIN:${replaceKey}})[\\s\\S]*(//{{END:${replaceKey}}})`, 'gm'), `$1\n${replace}\n$2`);
fs.writeFileSync(sourceDir + filename, fileData);

}

module.exports = replaceInTemplate;
1 change: 1 addition & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './public_api';
Loading

0 comments on commit d9e86e4

Please sign in to comment.