1# vim:fileencoding=utf-8
2# License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
3# globals: ρσ_get_module, self
4from __python__ import hash_literals
5
6import initialize  # noqa: unused-import
7from ajax import ajax, console_print, set_default_timeout
8from autoreload import create_auto_reload_watcher
9from book_list.globals import main_js
10from book_list.main import main
11
12autoreload_enabled = False
13AUTO_UPDATE_THRESHOLD = 1000  # millisecs
14
15
16def worker_main(entry_point):
17    m = ρσ_get_module(entry_point)
18    main = m?.main
19    if main:
20        main()
21    else:
22        console.log('worker entry_point ' + entry_point + ' not found')
23
24
25def iframe_main(script):
26    script.parentNode.removeChild(script)  # free up some memory
27    script = undefined
28    m = ρσ_get_module(window.iframe_entry_point)
29    main = m?.main
30    if main:
31        main()
32    else:
33        console.log('iframe entry_point ' + window.iframe_entry_point + ' not found')
34
35
36def toplevel_main():
37    script = document.currentScript or document.scripts[0]
38    main_js(script.textContent)
39    script.parentNode.removeChild(script) # save some memory
40    script = undefined
41    # We wait for all page elements to load, since this is a single page app
42    # with a largely empty starting document, we can use this to preload any resources
43    # we know are going to be needed immediately.
44    window.addEventListener('load', main)
45
46    ajax('ajax-setup', def(end_type, xhr, event):
47        nonlocal autoreload_enabled, print
48        if end_type is 'load':
49            try:
50                data = JSON.parse(xhr.responseText)
51            except:
52                return
53            tim = data.ajax_timeout
54            if not isNaN(tim) and tim > 0:
55                set_default_timeout(tim)
56            port = data.auto_reload_port
57            if not isNaN(port) and port > 0:
58                autoreload_enabled = True
59                create_auto_reload_watcher(port)
60            if data.allow_console_print:
61                print = console_print
62    ).send()  # We must bypass cache as otherwise we could get stale info
63
64if document?:
65    iframe_script = document.getElementById('bootstrap')
66    if iframe_script:
67        iframe_main(iframe_script)
68    else:
69        toplevel_main()
70elif self?:
71    entry_point = self.location.hash[1:]
72    worker_main(entry_point)
73