Skip to content
Open
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
47 changes: 47 additions & 0 deletions core/modules/utils/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,53 @@ exports.slowInSlowOut = function(t) {
return (1 - ((Math.cos(t * Math.PI) + 1) / 2));
};

exports.copyObjectPropertiesSafe = function(object) {
const seen = new Set(),
isDOMElement = value => value instanceof Node || value instanceof Window;

function safeCopy(obj) {
// skip circular references
if(seen.has(obj)) {
return undefined;
}
// primitives and null are safe
if(typeof obj !== "object" || obj === null) {
return obj;
}
// skip DOM elements
if(isDOMElement(obj)) {
return undefined;
}
// copy arrays, preserving positions
if(Array.isArray(obj)) {
return obj.map(item => {
const value = safeCopy(item);
return value === undefined ? null : value;
});
}

seen.add(obj);
const copy = {};
let key,
value;
for(key in obj) {
try {
value = safeCopy(obj[key]);
if(value !== undefined) {
copy[key] = value;
}
} catch(e) {
// silently skip unserializable properties
}
}
return copy;
}

const result = safeCopy(object);
seen.clear();
return result;
};

exports.formatTitleString = function(template,options) {
var base = options.base || "",
separator = options.separator || "",
Expand Down
310 changes: 235 additions & 75 deletions core/modules/widgets/eventcatcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,75 +39,12 @@ EventWidget.prototype.render = function(parent,nextSibling) {
this.domNode = domNode;
// Assign classes
this.assignDomNodeClasses();
// Add our event handler
$tw.utils.each(this.types,function(type) {
domNode.addEventListener(type,function(event) {
var selector = self.getAttribute("selector"),
matchSelector = self.getAttribute("matchSelector"),
actions = self.getAttribute("$"+type),
stopPropagation = self.getAttribute("stopPropagation","onaction"),
selectedNode = event.target,
selectedNodeRect,
catcherNodeRect,
variables = {};
// Firefox can fire dragover and dragenter events on text nodes instead of their parents
if(selectedNode.nodeType === 3) {
selectedNode = selectedNode.parentNode;
}
// Check that the selected node matches any matchSelector
if(matchSelector && !$tw.utils.domMatchesSelector(selectedNode,matchSelector)) {
return false;
}
if(selector) {
// Search ancestors for a node that matches the selector
while(!$tw.utils.domMatchesSelector(selectedNode,selector) && selectedNode !== domNode) {
selectedNode = selectedNode.parentNode;
}
// Exit if we didn't find one
if(selectedNode === domNode) {
return false;
}
// Only set up variables if we have actions to invoke
if(actions) {
variables = $tw.utils.collectDOMVariables(selectedNode,self.domNode,event);
}
}
// Execute our actions with the variables
if(actions) {
// Add a variable for the modifier key
variables.modifier = $tw.keyboardManager.getEventModifierKeyDescriptor(event);
// Add a variable for the mouse button
if("button" in event) {
if(event.button === 0) {
variables["event-mousebutton"] = "left";
} else if(event.button === 1) {
variables["event-mousebutton"] = "middle";
} else if(event.button === 2) {
variables["event-mousebutton"] = "right";
}
}
variables["event-type"] = event.type.toString();
if(typeof event.detail === "object" && !!event.detail) {
$tw.utils.each(event.detail,function(detailValue,detail) {
variables["event-detail-" + detail] = detailValue.toString();
});
} else if(!!event.detail) {
variables["event-detail"] = event.detail.toString();
}
self.invokeActionString(actions,self,event,variables);
}
if((actions && stopPropagation === "onaction") || stopPropagation === "always") {
event.preventDefault();
event.stopPropagation();
return true;
}
return false;
},false);
});
// Add our event handlers
this.toggleListeners();
// Insert element
parent.insertBefore(domNode,nextSibling);
this.renderChildren(domNode,null);
this.domNodes.push(domNode);
this.renderChildren(domNode,null);
};

/*
Expand All @@ -122,30 +59,253 @@ EventWidget.prototype.execute = function() {
self.types.push(key.slice(1));
}
});
this.pointerCaptureMode = this.getAttribute("pointerCapture","no");
this.elementTag = this.getAttribute("tag");
// Make child widgets
this.makeChildWidgets();
};

/*
Cache and pre-create all event listeners, called when first needed
*/
EventWidget.prototype.cacheEventListeners = function() {
if(this._eventListeners) {
return;
}
this._eventListeners = Object.create(null);
this._captureActiveListeners = Object.create(null);
this._dynamicOnlyEvents = ["pointerup","pointercancel","pointermove"];

const clearPointerCapture = event => {
if(Number.isInteger(this._capturePointerId)) {
this.stopPointerCapture(this._capturePointerId);
}
};

const attachDynamicOnlyListeners = () => {
this._dynamicOnlyEvents.forEach(dt => {
const listener = this._eventListeners[dt];
if(listener) {
this._captureActiveListeners[dt] = listener;
this.domNode.addEventListener(dt, listener, false);
}
});
};

// Dynamic pointer capture listeners
if(this.pointerCaptureMode === "dynamic") {
["pointerup","pointercancel"].forEach(type => {
this._eventListeners[type] = event => {
const selectedNode = this.checkEvent(event, type);
if(selectedNode) {
clearPointerCapture(event);
}
// Remove dynamic-only listeners
this.cleanupDynamicListeners();
return this.handleEvent(event, type, selectedNode);
};
});
if(!this.types.includes("pointerdown")) {
this.types.push("pointerdown");
}
}

// Create any listeners not already defined above
this.types.forEach(type => {
if(!this._eventListeners[type]) {
this._eventListeners[type] = event => {
const selectedNode = this.checkEvent(event, type);
if(!selectedNode) {
return false;
}
// Handle pointer capture for pointerdown
if(type === "pointerdown") {
if(this.pointerCaptureMode !== "no") {
this.startPointerCapture(event.pointerId, event.target);
}

if(this.pointerCaptureMode === "dynamic") {
attachDynamicOnlyListeners();
}
} else if(type === "pointerup" || type === "pointercancel") {
clearPointerCapture(event);
}
return this.handleEvent(event, type, selectedNode);
};
}
});
};

/*
Check if an event qualifies and return the matching selected node
*/
EventWidget.prototype.checkEvent = function(event, type) {
let selectedNode = event.target;
const domNode = this.domNode;

if(this._captureTarget && event.pointerId !== undefined) {
// Use captureTarget only if it’s still attached to the DOM
if(document.contains(this._captureTarget)) {
selectedNode = this._captureTarget;
} else {
// Clear stale reference
this.stopPointerCapture(this._capturePointerId);
selectedNode = event.target;
}
}

if(selectedNode.nodeType === 3) {
selectedNode = selectedNode.parentNode;
}
const selector = this.getAttribute("selector"),
matchSelector = this.getAttribute("matchSelector");

if(matchSelector && !selectedNode.matches(matchSelector)) {
return null;
}
if(selector) {
while(!selectedNode.matches(selector) && selectedNode !== domNode) {
selectedNode = selectedNode.parentNode;
}
if(selectedNode === domNode) {
return null;
}
}
return selectedNode;
};

/*
Handle the event and execute actions
*/
EventWidget.prototype.handleEvent = function(event, type, selectedNode) {
if(!selectedNode) {
return false;
}
let actions = this.getAttribute("$"+type),
stopPropagation = this.getAttribute("stopPropagation","onaction");

if(actions) {
let variables = $tw.utils.extend(
{},
$tw.utils.collectDOMVariables(selectedNode, this.domNode, event),
{
"eventJSON": JSON.stringify($tw.utils.copyObjectPropertiesSafe(event)),
"modifier": $tw.keyboardManager.getEventModifierKeyDescriptor(event),
"event-type": event.type.toString()
}
);

if("button" in event) {
const mouseButtonMap = {0:"left",1:"middle",2:"right"};
variables["event-mousebutton"] = mouseButtonMap[event.button];
}
this.invokeActionString(actions, this, event, variables);
}

if((actions && stopPropagation === "onaction") || stopPropagation === "always") {
event.preventDefault();
event.stopPropagation();
return true;
}
return false;
};

EventWidget.prototype.startPointerCapture = function(pointerId, captureTarget) {
// Start capture only if none active; pointerId can be 0
if(!Number.isInteger(this._capturePointerId) && this.domNode && this.domNode.setPointerCapture) {
this.domNode.setPointerCapture(pointerId);
this._capturePointerId = pointerId;
this._captureTarget = captureTarget;
}
};

EventWidget.prototype.stopPointerCapture = function(pointerId) {
if(this.domNode && this.domNode.hasPointerCapture && this.domNode.hasPointerCapture(pointerId)) {
this.domNode.releasePointerCapture(pointerId);
}
this._capturePointerId = undefined;
this._captureTarget = undefined;
};

/*
Attach all relevant listeners
*/
EventWidget.prototype.attachListeners = function() {
this.cacheEventListeners();
const domNode = this.domNode;
Object.keys(this._eventListeners).forEach(type => {
if(this.pointerCaptureMode === "dynamic" && this._dynamicOnlyEvents.includes(type)) {
return; //skip dynamic-only events
}
domNode.addEventListener(type, this._eventListeners[type], false);
});
};

/*
Remove dynamic active listeners
*/
EventWidget.prototype.cleanupDynamicListeners = function() {
const domNode = this.domNode;
Object.keys(this._captureActiveListeners || {}).forEach(type => {
domNode.removeEventListener(type, this._captureActiveListeners[type], false);
});
this._captureActiveListeners = Object.create(null);
};

/*
Remove all listeners
*/
EventWidget.prototype.removeAllListeners = function() {
if(Number.isInteger(this._capturePointerId)) {
this.stopPointerCapture(this._capturePointerId);
}
const domNode = this.domNode;
Object.keys(this._eventListeners || {}).forEach(type => {
domNode.removeEventListener(type, this._eventListeners[type], false);
});
this.cleanupDynamicListeners();
this._captureTarget = null;
};

/*
Enable or disable listeners
*/
EventWidget.prototype.toggleListeners = function() {
let disabled = this.getAttribute("disabled","no") === "yes";
if(disabled) {
this.removeAllListeners();
} else {
this.attachListeners();
}
};

/*
Assign DOM node classes
*/
EventWidget.prototype.assignDomNodeClasses = function() {
var classes = this.getAttribute("class","").split(" ");
classes.push("tc-eventcatcher");
this.domNode.className = classes.join(" ").trim();
};

/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
Refresh widget
*/
EventWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes(),
changedAttributesCount = $tw.utils.count(changedAttributes);
if(changedAttributesCount === 1 && changedAttributes["class"]) {
this.assignDomNodeClasses();
} else if(changedAttributesCount > 0) {
this.refreshSelf();
return true;
const changedAttributes = this.computeAttributes(),
changedKeys = Object.keys(changedAttributes),
canUpdateAttributes = changedKeys.every(key => key === "class" || key === "disabled");
if(canUpdateAttributes) {
if(changedAttributes["class"]) {
this.assignDomNodeClasses();
}
if(changedAttributes["disabled"]) {
this.toggleListeners();
}
return this.refreshChildren(changedTiddlers);
}
return this.refreshChildren(changedTiddlers);
this.refreshSelf();
return true;
};

exports.eventcatcher = EventWidget;
Loading