-
-
Save phun-ky/1b0a91552b13e20de6c150f667a6d26f to your computer and use it in GitHub Desktop.
This file contains 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
const isVerticalNavigation = (e) => e.key == 'ArrowUp' || e.key == 'ArrowDown'; | |
import whatinput from './whatinput'; | |
class IDSFAQ extends HTMLElement { | |
constructor() { | |
super(); | |
const _shadow_root = this.attachShadow({ mode: 'open' }); | |
const _style = document.createElement('style'); | |
_style.textContent = '%IDS_FAQ_CSS_PLACEHOLDER%'; | |
_shadow_root.appendChild(_style); | |
let _question_index = 0; | |
let _all_questions = null; | |
let nextElement = null; | |
const updateQuestions = (nodes) => { | |
_all_questions = nodes.map((n) => n.querySelector('.if.question')); | |
}; | |
let _faqs = Array.from(this.querySelectorAll('details')).map((details) => details.cloneNode(true)); | |
const arrowNavigationHandler = (e) => { | |
let nextElement; | |
e.preventDefault(); | |
if (e.key == 'ArrowUp') { | |
nextElement = _all_questions[_question_index > 0 ? --_question_index : _all_questions.length - 1]; | |
nextElement.focus(); | |
} else if (e.key == 'ArrowDown') { | |
nextElement = _all_questions[_question_index < _all_questions.length - 1 ? ++_question_index : 0]; | |
nextElement.focus(); | |
} | |
}; | |
const keyUpHandler = (e) => { | |
if (isVerticalNavigation(e)) { | |
arrowNavigationHandler(e); | |
} else if (e.key == 'Home') { | |
nextElement = _all_questions[0]; | |
nextElement.focus(); | |
} else if (e.key == 'End') { | |
nextElement = _all_questions[_all_questions.length - 1]; | |
nextElement.focus(); | |
} | |
}; | |
const focusHandler = (question) => { | |
_question_index = _all_questions.indexOf(question); | |
}; | |
_faqs = _faqs.map((details) => { | |
details.classList.add('if'); | |
details.classList.add('faq'); | |
details.classList.add('webcomponent'); | |
const _question_el = details.querySelector('summary'); | |
const _answer_el = details.querySelector('div'); | |
_answer_el.classList.add('if'); | |
_answer_el.classList.add('answer'); | |
_question_el.classList.add('if'); | |
_question_el.classList.add('question'); | |
_question_el.addEventListener('focus', () => { | |
focusHandler(_question_el); | |
}); | |
_question_el.addEventListener('keyup', (e) => { | |
if (!e.repeat) { | |
keyUpHandler(e); | |
} | |
}); | |
return details; | |
}); | |
updateQuestions(_faqs); | |
const _faqs_el = document.createElement('div'); | |
_faqs_el.classList.add('if'); | |
_faqs_el.classList.add('faqs'); | |
_faqs.forEach((details) => _faqs_el.appendChild(details)); | |
_shadow_root.appendChild(_faqs_el); | |
whatinput(_faqs_el); | |
} | |
} | |
customElements.define('ids-faq', IDSFAQ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment