"""The game in the browser. boot.js loads Python (Pyodide) and this package, then calls start(). The page is screen.py's, on the browser's document; this adds what only a browser does: keys and clicks, scrolling, and fetching pictures ahead of time. On a page longer than the window, it scrolls as the release's interpreter (Haven) did: * As the story starts waiting for a command, the page goes to its end if it's nearly there already. If not, it scrolls a window further down if the last wait was for a command too, and if that wait was for a key, it brings the screen's first words up to a third of the way down the window. * While the story waits for a key, any key or click goes on (Tab still moves between links). If there's more of the page below the window, a click, Space, Enter, or a key that types scrolls a window further down instead. * While the story waits for a command, a click, Space, Enter, or a key that types scrolls a window further down, or to the end once it's nearly there. A command link also sends its command; clicked while the story waits for a key, it goes on too, and the command runs as soon as the story next asks for one. That's how `play` on the cover works. Three things are better than Haven, on purpose. Once a key at a pause had only scrolled the page, Haven also kept the key that went on and spent it on the next pause, so that pause could pass unseen. A tap at a pause on a long page mostly did nothing. And while it waited for a command, every key but the punctuation scrolled down, the arrows, Page Up, Home, End and F5 among them, and links to other pages didn't open until the page was read to its end. Here those keys and links do what they always do. """ from __future__ import annotations import asyncio import math import re import traceback from js import Image, NodeFilter, console, document, performance, requestAnimationFrame, window from pyodide.ffi import create_proxy from .screen import Screen from .story import Story SCROLL_TIME = 500 # ms: `scroll to the end of the page` glides there this long, easing in and out (jQuery's swing) MARGIN = 40 # px: the release's interpreter counts the page as read when its end is this close to the window's class Page(Screen): def __init__(self): super().__init__(document) self.scrolling = None # the scroll animation running, if any self.paging = False # the last wait was for a command, so the next one pages down (Haven's doScroll) self.handlers = [create_proxy(self.on_key), create_proxy(self.on_click)] document.addEventListener("keydown", self.handlers[0]) document.addEventListener("click", self.handlers[1]) def preload(self, sources: list[str]) -> None: for source in sources: Image.new().src = source # -- Scrolling ------------------------------------------------------------------------------------------------- def unseen(self) -> float: """How much of the page is below the window, less the margin; as in Haven, the page is the body.""" return document.body.clientHeight - MARGIN - (window.scrollY + window.innerHeight) def page_down(self) -> None: window.scrollTo(0, window.scrollY + window.innerHeight - MARGIN) def scroll_on(self) -> None: """Haven's scrollOrFocus: to the end if nearly there; a window down after a command; or the first words.""" if self.unseen() < 0: window.scrollTo(0, document.documentElement.scrollHeight) elif self.paging: self.page_down() else: self.scroll_to_content() def scroll_to_content(self) -> None: """Haven's scrollToContent: brings the screen's first words up to a third of the way down the window. As in Haven, it measures them from the top of the window, not the page, so on a page already scrolled down it scrolls less, or not at all. """ texts = document.createTreeWalker(self.window, NodeFilter.SHOW_TEXT) text = texts.nextNode() while text is not None and not re.search(r"\S", text.textContent): text = texts.nextNode() if text is not None: top = text.parentNode.getBoundingClientRect().top - window.innerHeight / 3 if window.scrollY < top: window.scrollTo(0, top) def scroll_to_end(self) -> None: start = window.scrollY end = document.documentElement.scrollHeight - document.documentElement.clientHeight began = performance.now() token = self.scrolling = object() def step(now): if self.scrolling is not token: # a newer scroll took over frame.destroy() return done = min(1, max(0, (now - began) / SCROLL_TIME)) window.scrollTo(0, start + (end - start) * (0.5 - math.cos(done * math.pi) / 2)) if done < 1: requestAnimationFrame(frame) else: frame.destroy() frame = create_proxy(step) requestAnimationFrame(frame) # -- Waiting --------------------------------------------------------------------------------------------------- async def wait_for_key(self) -> None: self.paging = False await super().wait_for_key() def showing_prompt(self) -> None: self.scroll_on() self.paging = True # -- Keys and clicks ------------------------------------------------------------------------------------------- def on_key(self, event) -> None: if event.altKey or event.ctrlKey or event.metaKey or event.shiftKey or event.key == "Tab": return # The keys for reading on: Space, Enter, and any that types something. The rest (the arrows, Page Up and # Down, Home, End, Escape, the function keys) keep their own jobs, except that at the end of a pause any key # goes on. reading = event.key == "Enter" or len(event.key) == 1 if self.waiting == "key": if self.unseen() <= 0: self.press_key() elif reading: event.preventDefault() # the page down is instead of the key's own scrolling self.page_down() elif self.waiting == "command" and reading and event.keyCode <= 127 and not selecting(): # (Haven left the keys above 127, the punctuation, alone) if event.key == "Enter" and event.target.closest("a"): return # Enter on a link follows it if self.unseen() >= 0: event.preventDefault() # the page down is instead of the key's own scrolling self.scroll_on() def on_click(self, event) -> None: target = event.target link = target.closest("a") if getattr(target, "nodeType", 0) == 1 else None command = link if link is not None and link.classList.contains("vorple-commandlink") else None if self.waiting == "key": if self.unseen() <= 0: self.press_key() elif not selecting(): self.page_down() elif self.waiting == "command" and not selecting() and (link is None or command is not None): self.scroll_on() if command is not None: event.preventDefault() self.send_command(command.getAttribute("data-command")) def selecting() -> bool: """Whether the reader has text selected: then a click is for that, not for reading on.""" return bool(str(window.getSelection())) def start() -> None: """Take the loading message down and play.""" page = Page() loader = document.getElementById("loader") if loader: loader.remove() game = asyncio.ensure_future(Story(page).play()) game.add_done_callback(report) def report(game: asyncio.Future) -> None: if not game.cancelled() and game.exception() is not None: console.error("".join(traceback.format_exception(game.exception())))