Skip to content

Commit 1ebd5ee

Browse files
committed
Add support for oncommand. Fixes #55
1 parent 1503f23 commit 1ebd5ee

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

invoker.js

+50
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,54 @@ export function apply() {
253253
});
254254
}
255255

256+
const onHandlers = new WeakMap();
257+
Object.defineProperties(HTMLElement.prototype, {
258+
oncommand: {
259+
enumerable: true,
260+
configurable: true,
261+
get() {
262+
oncommandObserver.takeRecords();
263+
return onHandlers.get(this) || null;
264+
},
265+
set(handler) {
266+
const existing = onHandlers.get(this) || null;
267+
if (existing) {
268+
this.removeEventListener("command", existing);
269+
}
270+
onHandlers.set(
271+
this,
272+
typeof handler === "object" || typeof handler === "function"
273+
? handler
274+
: null,
275+
);
276+
if (typeof handler == "function") {
277+
this.addEventListener("command", handler);
278+
}
279+
},
280+
},
281+
});
282+
function applyOnCommandHandler(els) {
283+
for (const el of els) {
284+
el.oncommand = new Function("event", el.getAttribute("oncommand"));
285+
}
286+
}
287+
const oncommandObserver = new MutationObserver((records) => {
288+
for (const record of records) {
289+
const { target } = record;
290+
if (record.type === "childList") {
291+
applyOnCommandHandler(target.querySelectorAll("[oncommand]"));
292+
} else {
293+
applyOnCommandHandler([target]);
294+
}
295+
}
296+
});
297+
oncommandObserver.observe(document, {
298+
subtree: true,
299+
childList: true,
300+
attributeFilter: ["oncommand"],
301+
});
302+
applyOnCommandHandler(document.querySelectorAll("[oncommand]"));
303+
256304
function handleInvokerActivation(event) {
257305
if (event.defaultPrevented) return;
258306
if (event.type !== "click") return;
@@ -362,6 +410,8 @@ export function apply() {
362410

363411
observeShadowRoots(globalThis.HTMLElement || function () {}, (shadow) => {
364412
setupInvokeListeners(shadow);
413+
oncommandObserver.observe(shadow, { attributeFilter: ["oncommand"] });
414+
applyOnCommandHandler(shadow.querySelectorAll("[oncommand]"));
365415
});
366416

367417
setupInvokeListeners(document);

0 commit comments

Comments
 (0)