import { prot } from "./protocol" ; export let events ; try { events = new EventTarget ( ) ; } catch ( ex ) { events = window ; } export function dispatchEvent ( name , arg ? ) { events . dispatchEvent ( new CustomEvent ( name , { detail : arg } ) ) ; } export function netEvent ( sock , cmd , handler ) { events . addEventListener ( "net." + sock + "Sock." + prot . ids [ cmd ] , handler ) ; } export const dce = document . createElement . bind ( document ) ; export const gebi = document . getElementById . bind ( document ) ; export function encodeText ( text ) { if ( window . TextEncoder ) { return new TextEncoder ( ) . encode ( text ) ; } else { const ret = new Uint8Array ( text . length ) ; for ( let ni = 0 ; ni < text . length ; ni ++ ) { let cc = text . charCodeAt ( ni ) ; if ( cc > 127 ) cc = 95 ; ret [ ni ] = cc ; } return ret ; } } export function decodeText ( text ) { if ( window . TextDecoder ) { return new TextDecoder ( "utf-8" ) . decode ( text ) ; } else { let ret = "" ; const t8 = new Uint8Array ( text ) ; for ( let ni = 0 ; ni < t8 . length ; ni ++ ) { ret += String . fromCharCode ( t8 [ ni ] ) ; } return ret ; } } export function bytesToRepr ( x ) { const suffixes = [ "B" , "KiB" , "MiB" , "GiB" ] ; while ( suffixes . length > 1 && x >= 1024 ) { x /= 1024 ; suffixes . shift ( ) ; } return Math . round ( x ) + suffixes [ 0 ] ; } export function loadLibrary ( name ) { return new Promise ( function ( res , rej ) { const scr = dce ( "script" ) ; scr . addEventListener ( "load" , res ) ; scr . addEventListener ( "error" , rej ) ; scr . src = name ; scr . async = true ; document . body . appendChild ( scr ) ; } ) ; }