pseudo-dom 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,8 @@ require('core-js/modules/esnext.iterator.constructor.js')
4
4
  require('core-js/modules/esnext.iterator.filter.js')
5
5
  require('core-js/modules/esnext.iterator.find.js')
6
6
  require('core-js/modules/esnext.iterator.for-each.js')
7
+ require('core-js/modules/esnext.iterator.map.js')
8
+ require('core-js/modules/esnext.iterator.some.js')
7
9
  const __importDefault = void 0 && (void 0).__importDefault || function (mod) {
8
10
  return mod && mod.__esModule
9
11
  ? mod
@@ -21,9 +23,13 @@ Object.defineProperty(exports, '__esModule', {
21
23
  */
22
24
  const EventService_1 = require('./EventService')
23
25
  const PseudoEventListener_1 = __importDefault(require('../classes/PseudoEventListener'))
26
+ const getParentNodes_1 = __importDefault(require('../functions/getParentNodes'))
24
27
  const LinkedList_1 = require('collect-your-stuff/dist/collections/linked-list/LinkedList')
25
28
  /**
26
29
  * Simulate the behaviour of the EventTarget Class when there is no DOM available.
30
+ * Dispatching an event sends it through the tree the way the DOM does: down from the root to the target (capture
31
+ * listeners), to the target itself, then back up to the root (the listeners which are not capture listeners, when the
32
+ * event bubbles).
27
33
  * @author Joshua Heagle <joshuaheagle@gmail.com>
28
34
  * @class
29
35
  * @property {Object.<string, Array.<PseudoEventListener>>} listeners
@@ -53,33 +59,51 @@ class EventTargetService {
53
59
  }
54
60
 
55
61
  /**
56
- * Run each of the listeners registered on this target for the type of the event.
57
- * Listeners which do not apply to the event's phase are skipped, running stops once immediate propagation is stopped,
58
- * and listeners added or removed while running do not change which ones run for this event.
59
- * @param {EventService} event
60
- * @returns {*} true when there was nothing registered, otherwise the last value returned from a handler (null when none ran)
62
+ * Run the listeners registered on this target for the type of the event which apply to the phase the event is in
63
+ * (at the target, the capture listeners run before the others). Listeners which are added while this runs do not run
64
+ * for this event, and listeners which are removed while it runs no longer do. Running stops as soon as immediate
65
+ * propagation is stopped. A listener which throws does not stop the others.
66
+ * @param {EventService} event The event, which is at a phase and has a current target
67
+ * @returns {Array<*>} The errors which the listeners threw
61
68
  */
62
69
  runEvents (event) {
70
+ const errors = []
63
71
  if (!(event.type in this.listeners)) {
64
- return true
72
+ return errors
65
73
  }
66
- const listeners = this.listeners[event.type]
67
- let eventReturn = null
68
- // Work from a copy of the linkers so that removing a listener (for example a once listener) does not disturb the walk
69
- for (const linker of Array.from(listeners)) {
70
- const listener = linker.data
74
+ const listeners = Array.from(this.listeners[event.type]).map(linker => linker.data)
75
+ // At the target the capture listeners come first, otherwise the order is the order they were added
76
+ const ordered = event.eventPhase === EventService_1.EventService.AT_TARGET ? listeners.filter(listener => listener.capture).concat(listeners.filter(listener => !listener.capture)) : listeners
77
+ for (const listener of ordered) {
71
78
  if (event.inner.immediatePropagationStopped) {
72
79
  break
73
80
  }
74
81
  if (listener.rejectEvent(event)) {
75
82
  continue
76
83
  }
77
- eventReturn = listener.handleEvent(event)
78
84
  if (listener.once) {
79
- listeners.remove(linker)
85
+ this.removeListener(event.type, listener)
80
86
  }
87
+ event.inner.inPassiveListener = listener.passive
88
+ try {
89
+ listener.handleEvent(event)
90
+ } catch (error) {
91
+ errors.push(error)
92
+ }
93
+ event.inner.inPassiveListener = false
81
94
  }
82
- return eventReturn
95
+ return errors
96
+ }
97
+
98
+ /**
99
+ * Take a listener out of the registered listeners, so that it does not run again.
100
+ * @param {string} type
101
+ * @param {PseudoEventListener} listener
102
+ */
103
+ removeListener (type, listener) {
104
+ listener.removed = true
105
+ const registered = this.listeners[type]
106
+ Array.from(registered).filter(linker => linker.data === listener).forEach(linker => registered.remove(linker))
83
107
  }
84
108
 
85
109
  /**
@@ -92,48 +116,34 @@ class EventTargetService {
92
116
  this.defaultEvent[type] = callback
93
117
  }
94
118
 
95
- runDefaultEvent (event) {
96
- if (event.defaultPrevented) {
97
- return false
98
- }
99
- this.defaultEvent[event.type](event)
100
- return true
101
- }
102
-
103
- startEvents (eventType) {
104
- const event = new EventService_1.EventService(eventType)
105
- event.inner.target = this;
106
- [EventService_1.EventService.CAPTURING_PHASE, EventService_1.EventService.AT_TARGET, EventService_1.EventService.BUBBLING_PHASE].forEach(phase => {
107
- let continueEvents = null
108
- if (phase === EventService_1.EventService.AT_TARGET || !event.inner.propagationStopped) {
109
- event.inner.eventPhase = phase
110
- event.composedPath().forEach(target => {
111
- event.inner.currentTarget = target
112
- continueEvents = event.currentTarget.runEvents(event)
113
- })
114
- }
115
- if (event.eventPhase === EventService_1.EventService.AT_TARGET && typeof continueEvents !== 'boolean' && this.defaultEvent[eventType]) {
116
- this.runDefaultEvent(event)
117
- }
118
- })
119
- return true
120
- }
121
-
119
+ /**
120
+ * Registers an event handler of a specific event type. Adding the same handler again for the same type and phase does
121
+ * nothing, like the DOM.
122
+ * @param {string} type The type of event to listen for
123
+ * @param {Function|Object} callback The function to call (or an object with a handleEvent function)
124
+ * @param {Object|boolean} [useCapture=false] Listen while the event travels down to the target (true), or an object with capture, once and passive
125
+ */
122
126
  addEventListener (type, callback, useCapture = false) {
123
127
  let options = {
124
128
  capture: false,
125
129
  once: false,
126
130
  passive: false
127
131
  }
128
- if (typeof useCapture === 'object') {
132
+ if (typeof useCapture === 'object' && useCapture !== null) {
129
133
  // Originally useCapture was a single boolean flag, later optional other flags can be used
130
134
  // Here we take all the given flags from the object and assign them as the options
131
135
  options = Object.assign(options, useCapture)
132
136
  } else {
133
- options.capture = useCapture
137
+ options.capture = !!useCapture
134
138
  }
135
- const listener = new PseudoEventListener_1.default(type, options, (callback.handleEvent || callback).bind(this), callback)
136
139
  const listeners = this.listenersFor(type)
140
+ const alreadyAdded = Array.from(listeners).some(linker => linker.data.callback === callback && linker.data.capture === options.capture)
141
+ if (alreadyAdded) {
142
+ return
143
+ }
144
+ // A function runs with this target as this, an object runs its handleEvent as itself
145
+ const handler = typeof callback === 'function' ? callback.bind(this) : callback.handleEvent.bind(callback)
146
+ const listener = new PseudoEventListener_1.default(type, options, handler, callback)
137
147
  // Listeners run in the order they were added, except that listeners which are not defaults always come before the defaults
138
148
  const firstDefault = Array.from(listeners).find(linker => linker.data.isDefault)
139
149
  if (firstDefault && !listener.isDefault) {
@@ -143,20 +153,79 @@ class EventTargetService {
143
153
  }
144
154
  }
145
155
 
146
- removeEventListener (type, callback) {
156
+ /**
157
+ * Removes an event listener, the one which was added with the same type, handler and phase.
158
+ * @param {string} type The type of event
159
+ * @param {Function|Object} callback The handler which was added
160
+ * @param {Object|boolean} [options=false] Whether the listener was a capture listener (true), or an object with capture
161
+ */
162
+ removeEventListener (type, callback, options = false) {
147
163
  if (!(type in this.listeners)) {
148
164
  return
149
165
  }
150
- const listeners = this.listeners[type]
151
- Array.from(listeners).filter(linker => !linker.data.isDefault && linker.data.callback === callback).forEach(linker => listeners.remove(linker))
166
+ const capture = typeof options === 'object' && options !== null ? !!options.capture : !!options
167
+ Array.from(this.listeners[type]).map(linker => linker.data).filter(listener => !listener.isDefault && listener.callback === callback && listener.capture === capture).forEach(listener => this.removeListener(type, listener))
152
168
  }
153
169
 
154
- dispatchEvent (event, target = this) {
155
- event.inner.target = target
156
- if (!(event.type in this.listeners)) {
157
- return true
170
+ /**
171
+ * Dispatches an event to this target and through the tree: capture listeners of the ancestors from the root down,
172
+ * then the listeners of this target, then (when the event bubbles) the other listeners of the ancestors from the
173
+ * parent up to the root. stopPropagation() stops it reaching further targets, stopImmediatePropagation() also stops
174
+ * the remaining listeners of the current target. Afterwards, unless the default was prevented, the default action
175
+ * of this target (see setDefaultEvent) runs. The event can be dispatched again afterwards.
176
+ * @param {EventService} event The event to dispatch
177
+ * @returns {boolean} False when the event was cancelable and a listener prevented the default, otherwise true
178
+ * @throws {Error} When the event is already being dispatched, or (after the whole dispatch has finished) the error
179
+ * which a listener threw (an error with all of them in its errors property when several did)
180
+ */
181
+ dispatchEvent (event) {
182
+ if (event.inner.dispatching) {
183
+ throw new Error('The event is already being dispatched.')
184
+ }
185
+ event.inner.dispatching = true
186
+ event.inner.target = this
187
+ // The ancestors, the root first, which can have listeners
188
+ const ancestors = (0, getParentNodes_1.default)(this).filter(node => node instanceof EventTargetService)
189
+ event.inner.path = [this].concat(ancestors.slice().reverse())
190
+ const errors = []
191
+ const visit = (target, phase) => {
192
+ event.inner.eventPhase = phase
193
+ event.inner.currentTarget = target
194
+ errors.push(...target.runEvents(event))
195
+ }
196
+ for (const ancestor of ancestors) {
197
+ if (event.inner.propagationStopped) {
198
+ break
199
+ }
200
+ visit(ancestor, EventService_1.EventService.CAPTURING_PHASE)
201
+ }
202
+ if (!event.inner.propagationStopped) {
203
+ visit(this, EventService_1.EventService.AT_TARGET)
204
+ }
205
+ if (event.bubbles) {
206
+ for (const ancestor of ancestors.slice().reverse()) {
207
+ if (event.inner.propagationStopped) {
208
+ break
209
+ }
210
+ visit(ancestor, EventService_1.EventService.BUBBLING_PHASE)
211
+ }
212
+ }
213
+ event.inner.finishDispatch()
214
+ if (!event.defaultPrevented && typeof this.defaultEvent[event.type] === 'function') {
215
+ try {
216
+ this.defaultEvent[event.type](event)
217
+ } catch (error) {
218
+ errors.push(error)
219
+ }
220
+ }
221
+ if (errors.length === 1) {
222
+ throw errors[0]
223
+ }
224
+ if (errors.length > 1) {
225
+ throw Object.assign(new Error(`${errors.length} listeners threw an error while dispatching the ${event.type} event.`), {
226
+ errors
227
+ })
158
228
  }
159
- this.runEvents(event)
160
229
  return !event.defaultPrevented
161
230
  }
162
231
  }
@@ -1 +1 @@
1
- "use strict";require("core-js/modules/esnext.iterator.constructor.js"),require("core-js/modules/esnext.iterator.filter.js"),require("core-js/modules/esnext.iterator.find.js"),require("core-js/modules/esnext.iterator.for-each.js");var __importDefault=function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});const EventService_1=require("./EventService"),PseudoEventListener_1=__importDefault(require("../classes/PseudoEventListener")),LinkedList_1=require("collect-your-stuff/dist/collections/linked-list/LinkedList");class EventTargetService{constructor(){this.listeners={},this.defaultEvent={}}listenersFor(e){return e in this.listeners||(this.listeners[e]=new LinkedList_1.LinkedList),this.listeners[e]}runEvents(e){if(!(e.type in this.listeners))return!0;const t=this.listeners[e.type];let r=null;for(const n of Array.from(t)){const s=n.data;if(e.inner.immediatePropagationStopped)break;s.rejectEvent(e)||(r=s.handleEvent(e),s.once&&t.remove(n))}return r}setDefaultEvent(e,t){this.listenersFor(e),this.defaultEvent[e]=t}runDefaultEvent(e){return!e.defaultPrevented&&(this.defaultEvent[e.type](e),!0)}startEvents(e){const t=new EventService_1.EventService(e);return t.inner.target=this,[EventService_1.EventService.CAPTURING_PHASE,EventService_1.EventService.AT_TARGET,EventService_1.EventService.BUBBLING_PHASE].forEach(r=>{let n=null;r!==EventService_1.EventService.AT_TARGET&&t.inner.propagationStopped||(t.inner.eventPhase=r,t.composedPath().forEach(e=>{t.inner.currentTarget=e,n=t.currentTarget.runEvents(t)})),t.eventPhase===EventService_1.EventService.AT_TARGET&&"boolean"!=typeof n&&this.defaultEvent[e]&&this.runDefaultEvent(t)}),!0}addEventListener(e,t,r=!1){let n={capture:!1,once:!1,passive:!1};"object"==typeof r?n=Object.assign(n,r):n.capture=r;const s=new PseudoEventListener_1.default(e,n,(t.handleEvent||t).bind(this),t),i=this.listenersFor(e),o=Array.from(i).find(e=>e.data.isDefault);o&&!s.isDefault?i.insertBefore(o,s):i.append(s)}removeEventListener(e,t){if(!(e in this.listeners))return;const r=this.listeners[e];Array.from(r).filter(e=>!e.data.isDefault&&e.data.callback===t).forEach(e=>r.remove(e))}dispatchEvent(e,t=this){return e.inner.target=t,!(e.type in this.listeners)||(this.runEvents(e),!e.defaultPrevented)}}exports.default=EventTargetService;
1
+ "use strict";require("core-js/modules/esnext.iterator.constructor.js"),require("core-js/modules/esnext.iterator.filter.js"),require("core-js/modules/esnext.iterator.find.js"),require("core-js/modules/esnext.iterator.for-each.js"),require("core-js/modules/esnext.iterator.map.js"),require("core-js/modules/esnext.iterator.some.js");var __importDefault=function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});const EventService_1=require("./EventService"),PseudoEventListener_1=__importDefault(require("../classes/PseudoEventListener")),getParentNodes_1=__importDefault(require("../functions/getParentNodes")),LinkedList_1=require("collect-your-stuff/dist/collections/linked-list/LinkedList");class EventTargetService{constructor(){this.listeners={},this.defaultEvent={}}listenersFor(e){return e in this.listeners||(this.listeners[e]=new LinkedList_1.LinkedList),this.listeners[e]}runEvents(e){const t=[];if(!(e.type in this.listeners))return t;const r=Array.from(this.listeners[e.type]).map(e=>e.data),n=e.eventPhase===EventService_1.EventService.AT_TARGET?r.filter(e=>e.capture).concat(r.filter(e=>!e.capture)):r;for(const r of n){if(e.inner.immediatePropagationStopped)break;if(!r.rejectEvent(e)){r.once&&this.removeListener(e.type,r),e.inner.inPassiveListener=r.passive;try{r.handleEvent(e)}catch(e){t.push(e)}e.inner.inPassiveListener=!1}}return t}removeListener(e,t){t.removed=!0;const r=this.listeners[e];Array.from(r).filter(e=>e.data===t).forEach(e=>r.remove(e))}setDefaultEvent(e,t){this.listenersFor(e),this.defaultEvent[e]=t}addEventListener(e,t,r=!1){let n={capture:!1,once:!1,passive:!1};"object"==typeof r&&null!==r?n=Object.assign(n,r):n.capture=!!r;const i=this.listenersFor(e);if(Array.from(i).some(e=>e.data.callback===t&&e.data.capture===n.capture))return;const s="function"==typeof t?t.bind(this):t.handleEvent.bind(t),o=new PseudoEventListener_1.default(e,n,s,t),a=Array.from(i).find(e=>e.data.isDefault);a&&!o.isDefault?i.insertBefore(a,o):i.append(o)}removeEventListener(e,t,r=!1){if(!(e in this.listeners))return;const n="object"==typeof r&&null!==r?!!r.capture:!!r;Array.from(this.listeners[e]).map(e=>e.data).filter(e=>!e.isDefault&&e.callback===t&&e.capture===n).forEach(t=>this.removeListener(e,t))}dispatchEvent(e){if(e.inner.dispatching)throw new Error("The event is already being dispatched.");e.inner.dispatching=!0,e.inner.target=this;const t=(0,getParentNodes_1.default)(this).filter(e=>e instanceof EventTargetService);e.inner.path=[this].concat(t.slice().reverse());const r=[],n=(t,n)=>{e.inner.eventPhase=n,e.inner.currentTarget=t,r.push(...t.runEvents(e))};for(const r of t){if(e.inner.propagationStopped)break;n(r,EventService_1.EventService.CAPTURING_PHASE)}if(e.inner.propagationStopped||n(this,EventService_1.EventService.AT_TARGET),e.bubbles)for(const r of t.slice().reverse()){if(e.inner.propagationStopped)break;n(r,EventService_1.EventService.BUBBLING_PHASE)}if(e.inner.finishDispatch(),!e.defaultPrevented&&"function"==typeof this.defaultEvent[e.type])try{this.defaultEvent[e.type](e)}catch(e){r.push(e)}if(1===r.length)throw r[0];if(r.length>1)throw Object.assign(new Error(`${r.length} listeners threw an error while dispatching the ${e.type} event.`),{errors:r});return!e.defaultPrevented}}exports.default=EventTargetService;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pseudo-dom",
3
3
  "description": "Mock the DOM on the server side for managing state and testing",
4
- "version": "0.2.0",
4
+ "version": "0.3.0",
5
5
  "main": "dist/main.js",
6
6
  "types": "dist/main.d.ts",
7
7
  "author": "Joshua Heagle",