UNPKG

smart-table-keyboard

Version:

provide keyboard navigation to widget implementing the grid pattern

75 lines (71 loc) 2.13 kB
import { findContainer, dataSelectorAttribute, dataSkipAttribute, valFunc } from './util'; export function regularCell (element, {rowSelector, cellSelector}) { const row = findContainer(element, rowSelector); const cells = [...row.querySelectorAll(cellSelector)]; const index = cells.indexOf(element); const returnEl = valFunc(element); return { selectFromAfter: returnEl, selectFromBefore: returnEl, next(){ return cells[index + 1] !== void 0 ? cells[index + 1] : null; }, previous(){ return cells[index - 1] !== void 0 ? cells[index - 1] : null; } } } export function skipCell (element, options) { const reg = regularCell(element, options); return { previous: reg.previous, next: reg.next } } export function compositeCell (element, options) { const cellElement = findContainer(element, options.cellSelector); const selector = cellElement.getAttribute(dataSelectorAttribute); const subWidgets = [...cellElement.querySelectorAll(selector)]; const widgetsLength = subWidgets.length; const isSubWidget = element !== cellElement; return { selectFromBefore(){ return isSubWidget ? element : subWidgets[0]; }, selectFromAfter(){ return isSubWidget ? element : subWidgets[widgetsLength - 1]; }, next(){ const index = subWidgets.indexOf(element); if (isSubWidget && index + 1 < widgetsLength) { return subWidgets[index + 1]; } else { return regularCell(cellElement, options).next(); } }, previous(){ const index = subWidgets.indexOf(element); if (isSubWidget && index > 0) { return subWidgets[index - 1]; } else { return regularCell(cellElement, options).previous(); } } } } export function createCell (el, options) { if (el === null) { return null; } else if (el.hasAttribute(dataSkipAttribute)) { return skipCell(el, options); } else if (el.hasAttribute(dataSelectorAttribute) || !el.matches(options.cellSelector)) { return compositeCell(el, options); } else { return regularCell(el, options); } }