Last active
July 21, 2021 13:53
-
-
Save jgwhite/2c3773cd8bd25fb97707c3f43a962776 to your computer and use it in GitHub Desktop.
list-manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Component from '@glimmer/component'; | |
import { tracked } from '@glimmer/tracking'; | |
import { action } from '@ember/object'; | |
function tick() { | |
return new Promise((resolve) => setTimeout(resolve)); | |
} | |
export default class extends Component { | |
@tracked state; | |
element; | |
@action | |
install(element) { | |
this.element = element; | |
this.element.addEventListener('keydown', this.update); | |
this.element.addEventListener('focus', this.update); | |
this.element.addEventListener('focusenter', this.update); | |
this.element.addEventListener('focusleave', this.update); | |
document.addEventListener('mousedown', this.update); | |
this.update(); | |
} | |
@action | |
async update(event) { | |
await tick(); | |
this.state = applyListBehavior(this.element, event); | |
} | |
} | |
function applyListBehavior(element, event) { | |
let items = [...element.querySelectorAll('*')].filter(e => e.tabIndex >= 0); | |
let activeItem = items.find(i => i === document.activeElement); | |
let activeIndex = items.indexOf(activeItem); | |
if (!event) { | |
return { activeIndex }; | |
} | |
if (event.key === 'Escape') { | |
if (activeItem) { | |
activeItem.blur(); | |
} | |
return { activeIndex: -1 }; | |
} | |
if (event.key === 'ArrowDown') { | |
activeIndex = Math.min(activeIndex + 1, items.length - 1); | |
items[activeIndex].focus(); | |
return { activeIndex }; | |
} | |
if (event.key === 'ArrowUp') { | |
activeIndex = Math.max(0, activeIndex - 1); | |
items[activeIndex].focus(); | |
return { activeIndex }; | |
} | |
return { activeIndex }; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"version": "0.17.1", | |
"EmberENV": { | |
"FEATURES": {}, | |
"_TEMPLATE_ONLY_GLIMMER_COMPONENTS": false, | |
"_APPLICATION_TEMPLATE_WRAPPER": true, | |
"_JQUERY_INTEGRATION": true | |
}, | |
"options": { | |
"use_pods": false, | |
"enable-testing": false | |
}, | |
"dependencies": { | |
"ember": "3.18.1", | |
"ember-template-compiler": "3.18.1", | |
"ember-testing": "3.18.1" | |
}, | |
"addons": { | |
"@glimmer/component": "1.0.0", | |
"@ember/render-modifiers": "1.0.2" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment