-
Notifications
You must be signed in to change notification settings - Fork 320
Expand file tree
/
Copy pathevents.js
More file actions
68 lines (57 loc) · 2.03 KB
/
events.js
File metadata and controls
68 lines (57 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { addToHistory, EditType } from "./history";
import { finder } from '@medv/finder'
export const getUniqueSelector = (el) => {
let selector = el.tagName.toLowerCase()
try {
if (el.nodeType !== Node.ELEMENT_NODE) { return selector }
// Class names can change too much between states so should ignore.
selector = finder(el, { className: () => false })
} catch (e) {
console.error("Error creating selector ", e);
}
return selector
}
const elementSelectorCache = new WeakMap(); // Cache for element selectors
function debounce(func, wait) {
const timeouts = {};
return function (...args) {
const context = this;
const editEvent = args[0];
const element = editEvent.el;
// Use cached selector if available, otherwise compute and cache it
if (!elementSelectorCache.has(element)) {
elementSelectorCache.set(
element,
getUniqueSelector(element)
);
}
const elementSelector = elementSelectorCache.get(element);
if (timeouts[elementSelector]) clearTimeout(timeouts[elementSelector]);
const later = () => {
delete timeouts[elementSelector];
func.apply(context, args);
};
clearTimeout(timeouts[elementSelector]);
timeouts[elementSelector] = setTimeout(later, wait);
};
}
function undebounceHandleEditEvent(param) {
const selector =
elementSelectorCache.get(param.el) || getUniqueSelector(param.el);
const event = {
createdAt: new Date().toISOString(),
selector: selector,
editType: param.editType,
newVal: param.newValue,
oldVal: param.oldValue,
};
addToHistory(event);
}
let debouncedHandleEditEvent = debounce(undebounceHandleEditEvent, 1000);
export function handleEditEvent(param) {
if (param.editType === EditType.STYLE || param.editType === EditType.TEXT) {
debouncedHandleEditEvent(param);
} else {
undebounceHandleEditEvent(param);
}
}