web-portals
Version:
web-portals
60 lines (59 loc) • 1.96 kB
text/typescript
export default (moduleWindow: Window, capture?: string | string[]) => {
const touchActive = {
element: null,
oldStyle: ''
} as {
element: null | HTMLElement
oldStyle: string
}
const addHighlight = (event: TouchEvent) => {
const captureList = capture ? typeof capture === 'string' ? capture.split(' ') : capture : null
const path = event['path'] || event.composedPath() || []
path.splice(-3)
const anchor = (() => {
for (const el of path) {
if (!el.children?.length) continue
if (el.tagName === 'A') return el
if (captureList) {
for (const attr of captureList) {
if (el?.getAttribute(attr)) return el
}
}
}
return (path[0]?.children?.length ? path[0] : path[1]) || event.target
})()
if (!anchor) return
touchActive.element = anchor
touchActive.oldStyle = anchor.style.filter
setTimeout(() => {
if (touchActive.element === anchor) anchor.style.filter = touchActive.oldStyle + ' brightness(.8)'
const continueCheck = () => {
setTimeout(() => {
if (touchActive.element !== anchor) {
anchor.style.filter = touchActive.oldStyle
} else {
continueCheck()
}
}, 600)
}
continueCheck()
}, 60)
}
const cancelHighlight = () => {
if (touchActive.element?.style?.filter) {
touchActive.element.style.filter = touchActive.oldStyle
}
touchActive.element = null
touchActive.oldStyle = ''
}
const delayCancelHighlight = () => {
setTimeout(() => {
cancelHighlight()
}, 600)
}
moduleWindow.document.addEventListener('touchstart', addHighlight)
moduleWindow.addEventListener('touchstart', addHighlight)
moduleWindow.addEventListener('touchmove', cancelHighlight)
moduleWindow.addEventListener('touchcancel', cancelHighlight)
moduleWindow.addEventListener('touchend', delayCancelHighlight)
}