Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Adam-D-Lewis/b768806753e5fab9c55b57c4a483aa5d to your computer and use it in GitHub Desktop.
Save Adam-D-Lewis/b768806753e5fab9c55b57c4a483aa5d to your computer and use it in GitHub Desktop.
import panel as pn
script = """
<script>
function querySelectorDeep(selector, rootNode=document.body) {
const arr = []
const traverser = node => {
// 1. decline all nodes that are not elements
if(node.nodeType !== Node.ELEMENT_NODE) {
return
}
// 2. add the node to the array, if it matches the selector
if(node.matches(selector)) {
arr.push(node)
}
// 3. loop through the children
const children = node.children
if (children.length) {
for(const child of children) {
traverser(child)
}
}
// 4. check for shadow DOM, and loop through it's children
const shadowRoot = node.shadowRoot
if (shadowRoot) {
const shadowChildren = shadowRoot.children
for(const shadowChild of shadowChildren) {
traverser(shadowChild)
}
}
}
traverser(rootNode)
return arr
}
const doc = window.parent.document;
doc.addEventListener('keydown', function(e) {
buttons = Array.from(querySelectorDeep('button'));
const left_button = buttons.find(el => el.innerText === 'LEFT');
const right_button = buttons.find(el => el.innerText === 'RIGHT');
switch (e.keyCode) {
case 37: // (37 = left arrow)
left_button.click();
break;
case 39: // (39 = right arrow)
right_button.click();
break;
}
});
</script>
"""
html = pn.pane.HTML(script)
button_left = pn.widgets.Button(name="LEFT")
button_right = pn.widgets.Button(name="RIGHT")
button_left.on_click(lambda x: print("left"))
# OR
pn.bind(lambda x: print("right"), button_right, watch=True)
app = pn.Row(
pn.Column(button_left, button_left.param.clicks),
pn.Column(button_right, button_right.param.clicks),
html,
)
pn.serve(app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment