@ -1,3 +1,14 @@
// FIXME: Ok questo file è abbastanza self-contained però sarebbe meglio riorganizzarlo un po' in modo da non avere così tante variabili globali
/ *
Un 'idea (spastica) sarebbe che `addTooltipElementListener` si aspetta che il callback dell' evento ` false ` se non ha nulla da mostrare oppure una funzione che riceve come parametro l ' elemento della tooltip ( in questo modo ` setTooltip(callback) ` non servirebbe più e setTooltipText ( text ) diventerebbe una funzione parziale che ritorna una "mounting function" ) .
In questo modo :
- ` setTooltip ` non esisterebbe più e ci sarebbero meno "momenti" in cui il testo della tooltip può cambiare .
- Anche ` resetTooltip ` non esisterebbe più perché semplicemente la tooltip scomparirebbe se tutti i listener ritornano ` false ` .
- ` setTooltipText ` diventerebbe una funzione "pura rispetto al mondo esterno" ( che modifica solo cose nel suo scope ) che è sempre meglio di modificare variabili globali .
* /
const LISTENERS = [ ]
const $tooltip = document . querySelector ( '#tooltip' )
@ -6,29 +17,58 @@ export function attachTooltip() {
$tooltip . style . setProperty ( '--x' , 10 + e . pageX + 'px' )
$tooltip . style . setProperty ( '--y' , 10 + e . pageY + 'px' )
LISTENERS . find ( listener => listener ( e . target ) )
for ( const listener of LISTENERS ) {
if ( listener ( e . target ) ) {
return
}
}
resetTooltip ( )
} )
resetTooltip ( )
}
/ * *
* addTooltipElementListener attaches a listener on the mouse moved event . The listener should return true only if it needs the tooltip to be visible ( TODO : change this to return a mounting function ) , otherwise it should return false .
* @ param { * } callbackFn
* /
export function addTooltipElementListener ( callbackFn ) {
LISTENERS . push ( callbackFn )
}
/ * *
* setTooltip shows the tooltip and calls the given callback with the tooltip element to
* let the caller modify the tooltip as preferred .
* /
export function setTooltip ( mountFn ) {
$tooltip . classList . remove ( 'hidden' )
mountFn ( $tooltip )
RESET _DIRTY = true
}
let TEXT _BUFFER = null
export function setTooltipText ( text ) {
$tooltip . classList . remove ( 'hidden' )
setTooltip ( $t => {
$t . innerText = text
if ( text !== TEXT _BUFFER ) {
$t . innerText = text
TEXT _BUFFER = text
}
} )
}
let RESET _DIRTY = true
export function resetTooltip ( ) {
if ( ! RESET _DIRTY ) return
TEXT _BUFFER = null
$tooltip . classList . add ( 'hidden' )
$tooltip . innerHTML = ''
while ( $tooltip . firstChild ) {
$tooltip . firstChild . remove ( )
}
RESET _DIRTY = false
}