Skip to content

Instantly share code, notes, and snippets.

@jgwhite
Last active July 21, 2021 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgwhite/2c3773cd8bd25fb97707c3f43a962776 to your computer and use it in GitHub Desktop.
Save jgwhite/2c3773cd8bd25fb97707c3f43a962776 to your computer and use it in GitHub Desktop.
list-manager
{{yield
(hash
install=this.install
state=this.state
)
}}
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 };
}
<ListManager as |lm|>
<ol {{did-insert lm.install}}>
<li tabindex="0">Option 1</li>
<li tabindex="0">Option 2</li>
<li tabindex="0">Option 3</li>
</ol>
<pre>lm.state.activeIndex: {{lm.state.activeIndex}}</pre>
</ListManager>
{
"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