Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
User Interface Input / Output is a tool for observing all event triggers (UI input) & DOM mutations (UI output). Initialised with an optional callback function which receives all such entries in format {type: 'mutation' || 'event', time: performance.now(), data: originalEventOrMutationRecords}, the returned instance exposes {logs, next, disconne…
import muty from 'muty'
export default function ui_io(callback = Function.prototype){
const {addEventListener} = EventTarget.prototype
const promises = []
const listeners = []
const logs = []
function register(entry){
logs.push(entry)
callback(entry)
promises.forEach(p => p(entry))
promises.length = 0
}
EventTarget.prototype.addEventListener = function addWrapper(type, handler, options){
const listener = [this, type, function handlerWrapper(event){
register({
type : 'event',
timestamp : performance.now(),
data : event,
})
return (handler.handleEvent ? handler.handleEvent(...arguments) : handler(...arguments))
}, options]
addEventListener.call(...listener)
listeners.push(listener)
}
const observer = muty(muty.options, document.documentElement, function(records){
register({
type : 'mutation',
timestamp : performance.now(),
data : records,
})
})
return {
logs : () => logs,
next : () => new Promise(done => {
promises.push(done)
}),
disconnect(){
Object.assign(EventTarget.prototype, {addEventListener})
listeners.forEach(([target, ...signature]) => {
target.removeEventListener(...signature)
})
observer.disconnect()
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment