Skip to content
Snippets Groups Projects
bindings.js 2.31 KiB
Newer Older
Louis's avatar
Louis committed
export function orientation_lock(orientation) {
	window.screen.orientation.lock(orientation)
}
export function orientation_unlock() {
	window.screen.orientation.unlock()

}
export function make_selector_fullscreen(selector) {
	const el = document.querySelector(selector);
	if (el) {
		el.requestFullscreen()
	}
}
export function exit_fullscreen() {
	document.exitFullscreen()
}
export function is_fullscreen() {
	return document.fullscreenEnabled
}
export function is_touch_device() {
	return (navigator?.maxTouchPoints ?? 0) > 0
}
export function toggle_selector_fullscreen(selector) {
	if (is_fullscreen()) {
		exit_fullscreen()
	} else {
		make_selector_fullscreen(selector)
	}
}
export function bind_selector_touch_events(selector) {
	function touch(evt) {
		let phase = null
		switch(evt.type) {
			case 'touchstart':
				phase = 'Started';
				break;
			case 'touchend':
				phase = 'Ended';
				break;
			case 'touchmove':
				phase = 'Moved';
				break;
			case 'touchcancel':
				phase = 'Cancelled';
				break;
		}

		if (phase == null) {
			return
		}

		for (const touch of evt.changedTouches) {
			console.log(touch)
			window.touch_events.push({
				id: touch.identifier,
				phase,
				position: [touch.pageX, window.document.documentElement.getBoundingClientRect().height - touch.pageY],
				force: null,
			})
		}
	}

	if (window.touch_events == null) {
		window.touch_events = []
		window.touch_handlers = window.touch_handlers || {}
	}

	const el = document.querySelector(selector)
	if (el != null) {
		window.touch_handlers[selector] = touch
		el.addEventListener('touchstart', touch)
		el.addEventListener('touchend', touch)
		el.addEventListener('touchcancel', touch)
		el.addEventListener('touchmove', touch)
	}

}

export function teardown_selector_touch_events(selector) {
	const handler = window.touch_handlers?.[selector]
	delete window.touch_handlers?.[selector]

	if (handler != null) {
		const el = document.querySelector(selector)
		if (el != null) {
			el.removeEventListener('touchstart', handler)
			el.removeEventListener('touchend', handler)
			el.removeEventListener('touchcancel', handler)
			el.removeEventListener('touchmove', handler)
		}
	}
}
export function take_touch_events() {
	if (window.touch_events) {
		let events = window.touch_events
		window.touch_events = []
		return JSON.stringify(events)
	}
	return '[]'
}