dom-ops.mjs raw

   1  // dom-ops.mjs — one description of every DOM operation a Moxie module asks for.
   2  //
   3  // A Moxie wasm module always runs in a Worker: channel receives block in
   4  // Atomics.wait, which the page thread forbids, and a domain that spawns must
   5  // itself be able to create a Worker. The document therefore lives one hop away
   6  // on the page, and every DOM call the module makes is a request. This table is
   7  // the request list in one place: `run` is the page performing the operation
   8  // against the real jsruntime/dom.mjs, and `kind` is what the answer carries.
   9  // relay.mjs serves these ops on the page and makes them from the Worker, so
  10  // both halves of the boundary are built from this table and cannot drift.
  11  //
  12  // Two directions of answer, one table:
  13  //
  14  //   - the ANSWER to the call, described by `kind`, written into the shared
  15  //     buffer before the Worker wakes;
  16  //   - a CALLBACK the page produces later (an event, a timer, a fetch reply),
  17  //     delivered through `cb`, whose ids are the module's own web/callback
  18  //     handles. `cb` is the only difference between the two hosts: over the port
  19  //     it posts a message to the Worker, and the Worker dispatches it into the
  20  //     module's exports.
  21  //
  22  // Arguments arrive in wire order as one array, so the page executes exactly
  23  // what the Worker sent. Names are the stdlib's own: each key is the tail of a
  24  // `//:wasmimport bridge dom_<key>` in src/web/dom/dom_wasm.mx, which is the
  25  // complete list of DOM calls a Moxie program can compile to.
  26  import * as dom from './dom.mjs';
  27  
  28  export const VOID = 0;   // no answer
  29  export const INT = 1;    // one int32
  30  export const STR = 2;    // a string
  31  export const I64 = 3;    // one int64, carried as decimal text
  32  
  33  // The one operation nothing can serve yet. It needs the module's ANSWER before
  34  // the page can act - preventDefault on a keydown - and the page thread cannot
  35  // block waiting on a Worker. smesh's own worker host has the same hole: it
  36  // calls __hook_keydown and drops the return value.
  37  const NO_ANSWER_PATH = {
  38    kind: VOID,
  39    run: null,
  40    why: 'needs a synchronous answer from the module, which the page thread cannot wait for',
  41  };
  42  
  43  // Page-side event registrations. dom.mjs's listener functions take a callback
  44  // id registered on the page, and remove_event_listener has to name the same
  45  // one, so the mapping from the module's id to the page's id lives here.
  46  const eventCallbacks = new Map(); // `${el}:${event}:${moduleId}` -> page callback id
  47  
  48  export const domOps = {
  49    // --- Element creation and query ---
  50    body: { kind: INT, run: () => dom.Body() },
  51    create_element: { kind: INT, run: (a) => dom.CreateElement(a[0]) },
  52    create_text_node: { kind: INT, run: (a) => dom.CreateTextNode(a[0]) },
  53    get_element_by_id: { kind: INT, run: (a) => dom.GetElementById(a[0]) },
  54    query_selector: { kind: INT, run: (a) => dom.QuerySelector(a[0]) },
  55    query_selector_from: { kind: INT, run: (a) => dom.QuerySelectorFrom(a[0], a[1]) },
  56  
  57    // --- Tree ---
  58    append_child: { kind: VOID, run: (a) => dom.AppendChild(a[0], a[1]) },
  59    remove_child: { kind: VOID, run: (a) => dom.RemoveChild(a[0], a[1]) },
  60    remove: { kind: VOID, run: (a) => dom.Remove(a[0]) },
  61    insert_before: { kind: VOID, run: (a) => dom.InsertBefore(a[0], a[1], a[2]) },
  62    first_child: { kind: INT, run: (a) => dom.FirstChild(a[0]) },
  63    first_element_child: { kind: INT, run: (a) => dom.FirstElementChild(a[0]) },
  64    next_sibling: { kind: INT, run: (a) => dom.NextSibling(a[0]) },
  65    release_element: { kind: VOID, run: (a) => dom.ReleaseElement(a[0]) },
  66    release_children: { kind: VOID, run: (a) => dom.ReleaseChildren(a[0]) },
  67    release_all: { kind: VOID, run: (a) => { for (const id of a[0]) dom.ReleaseElement(id); } },
  68  
  69    // --- Attributes, content, style ---
  70    set_attribute: { kind: VOID, run: (a) => dom.SetAttribute(a[0], a[1], a[2]) },
  71    remove_attribute: { kind: VOID, run: (a) => dom.RemoveAttribute(a[0], a[1]) },
  72    get_attribute: { kind: STR, run: (a) => dom.GetAttribute(a[0], a[1]) },
  73    set_text_content: { kind: VOID, run: (a) => dom.SetTextContent(a[0], a[1]) },
  74    set_inner_html: { kind: VOID, run: (a) => dom.SetInnerHTML(a[0], a[1]) },
  75    set_style: { kind: VOID, run: (a) => dom.SetStyle(a[0], a[1], a[2]) },
  76    set_property: { kind: VOID, run: (a) => dom.SetProperty(a[0], a[1], a[2]) },
  77    get_property: { kind: STR, run: (a) => dom.GetProperty(a[0], a[1]) },
  78    add_class: { kind: VOID, run: (a) => dom.AddClass(a[0], a[1]) },
  79    remove_class: { kind: VOID, run: (a) => dom.RemoveClass(a[0], a[1]) },
  80    focus: { kind: VOID, run: (a) => dom.Focus(a[0]) },
  81    insert_mention_chip: {
  82      kind: VOID,
  83      run: (a) => dom.InsertMentionChip(a[0], a[1], a[2], a[3], a[4]),
  84    },
  85  
  86    // --- Geometry ---
  87    bounding_client_left: { kind: INT, run: (a) => dom.BoundingClientLeft(a[0]) },
  88    get_viewport_height: { kind: INT, run: () => dom.GetViewportHeight() },
  89    get_viewport_width: { kind: INT, run: () => dom.GetViewportWidth() },
  90    get_bounding_rect: {
  91      kind: VOID,
  92      run: (a, cb) => dom.GetBoundingRect(a[0], (l, t, r, b, w, h) => cb.i6(a[1], [l, t, r, b, w, h])),
  93    },
  94  
  95    // --- Page state ---
  96    prefers_dark: { kind: INT, run: () => (dom.PrefersDark() ? 1 : 0) },
  97    confirm: { kind: INT, run: (a) => (dom.Confirm(a[0]) ? 1 : 0) },
  98    console_log: { kind: VOID, run: (a) => dom.ConsoleLog(a[0]) },
  99    now_seconds: { kind: I64, run: () => dom.NowSeconds() },
 100    timezone_offset_seconds: { kind: INT, run: () => dom.TimezoneOffsetSeconds() },
 101    get_path: { kind: STR, run: () => dom.GetPath() },
 102    get_hash: { kind: STR, run: () => dom.GetHash() },
 103    hostname: { kind: STR, run: () => dom.Hostname() },
 104    port: { kind: STR, run: () => dom.Port() },
 105    user_agent: { kind: STR, run: () => dom.UserAgent() },
 106    encode_uri_component: { kind: STR, run: (a) => dom.EncodeURIComponent(a[0]) },
 107    push_state: { kind: VOID, run: (a) => dom.PushState(a[0]) },
 108    replace_state: { kind: VOID, run: (a) => dom.ReplaceState(a[0]) },
 109    back: { kind: VOID, run: () => dom.Back() },
 110    location_reload: { kind: VOID, run: () => dom.LocationReload() },
 111    location_assign: { kind: VOID, run: (a) => dom.LocationAssign(a[0]) },
 112    hard_refresh: { kind: VOID, run: () => dom.HardRefresh() },
 113    clear_storage_prefix: { kind: VOID, run: (a) => dom.ClearStoragePrefix(a[0]) },
 114    post_to_sw: { kind: VOID, run: (a) => dom.PostToSW(a[0]) },
 115    window_open: { kind: VOID, run: (a) => dom.WindowOpen(a[0]) },
 116    download_text: { kind: VOID, run: (a) => dom.DownloadText(a[0], a[1], a[2]) },
 117    write_primary_selection: { kind: VOID, run: (a) => dom.WritePrimarySelection(a[0]) },
 118  
 119    // --- Timers and storage ---
 120    set_timeout: { kind: INT, run: (a, cb) => dom.SetTimeout(() => cb.void(a[0]), a[1]) },
 121    clear_timeout: { kind: VOID, run: (a) => dom.ClearTimeout(a[0]) },
 122    idb_set_enc_key: { kind: VOID, run: (a) => dom.IDBSetEncKey(a[0]) },
 123    idb_put: { kind: VOID, run: (a) => dom.IDBPut(a[0], a[1], a[2]) },
 124    idb_get: { kind: VOID, run: (a, cb) => dom.IDBGet(a[0], a[1], (s) => cb.str(a[2], s)) },
 125    idb_get_all: {
 126      kind: VOID,
 127      run: (a, cb) => dom.IDBGetAll(a[0], (k, v) => cb.ss(a[1], k, v), () => cb.void(a[2])),
 128    },
 129  
 130    // --- Events ---
 131    add_event_listener: {
 132      kind: VOID,
 133      run: (a, cb) => {
 134        const pid = dom.RegisterCallback(() => cb.void(a[2]));
 135        dom.AddEventListener(a[0], a[1], pid);
 136        eventCallbacks.set(`${a[0]}:${a[1]}:${a[2]}`, pid);
 137      },
 138    },
 139    add_self_event_listener: {
 140      kind: VOID,
 141      run: (a, cb) => {
 142        const pid = dom.RegisterCallback(() => cb.void(a[2]));
 143        dom.AddSelfEventListener(a[0], a[1], pid);
 144        eventCallbacks.set(`${a[0]}:${a[1]}:${a[2]}`, pid);
 145      },
 146    },
 147    add_enter_key_listener: {
 148      kind: VOID,
 149      run: (a, cb) => {
 150        const pid = dom.RegisterCallback(() => cb.void(a[1]));
 151        dom.AddEnterKeyListener(a[0], pid);
 152        eventCallbacks.set(`${a[0]}:keydown:enter:${a[1]}`, pid);
 153      },
 154    },
 155    remove_event_listener: {
 156      kind: VOID,
 157      run: (a) => {
 158        const key = `${a[0]}:${a[1]}:${a[2]}`;
 159        const pid = eventCallbacks.get(key);
 160        dom.RemoveEventListener(a[0], a[1], pid);
 161        dom.ReleaseCallback(pid);
 162        eventCallbacks.delete(key);
 163      },
 164    },
 165    observe_resize: {
 166      kind: VOID,
 167      run: (a, cb) => dom.ObserveResize(a[0], dom.RegisterCallback(() => cb.void(a[1]))),
 168    },
 169    unobserve_resize: { kind: VOID, run: (a) => dom.UnobserveResize(a[0]) },
 170    request_animation_frame: { kind: VOID, run: (a, cb) => dom.RequestAnimationFrame(() => cb.void(a[0])) },
 171    on_pull_refresh: { kind: VOID, run: (a, cb) => dom.OnPullRefresh(a[0], a[1], () => cb.void(a[2])) },
 172    on_paste_image: { kind: VOID, run: (a, cb) => dom.OnPasteImage(a[0], (d, m) => cb.ss(a[1], d, m)) },
 173    on_drop_image: { kind: VOID, run: (a, cb) => dom.OnDropImage(a[0], (d, m) => cb.ss(a[1], d, m)) },
 174    on_pop_state: { kind: VOID, run: (a, cb) => dom.OnPopState((path) => cb.str(a[0], path)) },
 175    intercept_internal_links: {
 176      kind: VOID,
 177      run: (a, cb) => dom.InterceptInternalLinks((path) => cb.str(a[0], path)),
 178    },
 179    on_sw_message: { kind: VOID, run: (a, cb) => dom.OnSWMessage((s) => cb.str(a[0], s)) },
 180    on_keydown: NO_ANSWER_PATH,
 181  
 182    // --- Fetch, clipboard, files ---
 183    fetch_text: { kind: VOID, run: (a, cb) => dom.FetchText(a[0], (s) => cb.str(a[1], s)) },
 184    fetch_relay_info: { kind: VOID, run: (a, cb) => dom.FetchRelayInfo(a[0], (s) => cb.str(a[1], s)) },
 185    fetch_put_blob_base64: {
 186      kind: VOID,
 187      run: (a, cb) => dom.FetchPutBlobBase64(a[0], a[1], a[2], a[3], (s) => cb.str(a[4], s)),
 188    },
 189    read_clipboard: { kind: VOID, run: (a, cb) => dom.ReadClipboard((s) => cb.str(a[0], s)) },
 190    write_clipboard: { kind: VOID, run: (a, cb) => dom.WriteClipboard(a[0], (ok) => cb.bool(a[1], ok)) },
 191    copy_image_to_clipboard: {
 192      kind: VOID,
 193      run: (a, cb) => dom.CopyImageToClipboard(a[0], (ok) => cb.bool(a[1], ok)),
 194    },
 195    pick_file_text: { kind: VOID, run: (a, cb) => dom.PickFileText(a[0], (s) => cb.str(a[1], s)) },
 196    pick_file_base64: {
 197      kind: VOID,
 198      run: (a, cb) => dom.PickFileBase64(a[0], (d, m) => cb.ss(a[1], d, m)),
 199    },
 200  };
 201  
 202  // methodName maps an op to the jsruntime/dom.mjs function that implements it on
 203  // the page. Only the acronyms need saying: everything else is snake to Camel,
 204  // and the uppercase runs in IDB and SW are the two places that rule breaks.
 205  const METHOD = {
 206    idb_set_enc_key: 'IDBSetEncKey',
 207    idb_get: 'IDBGet',
 208    idb_put: 'IDBPut',
 209    idb_get_all: 'IDBGetAll',
 210    on_sw_message: 'OnSWMessage',
 211    post_to_sw: 'PostToSW',
 212    set_inner_html: 'SetInnerHTML',
 213    encode_uri_component: 'EncodeURIComponent',
 214  };
 215  
 216  export function methodName(op) {
 217    if (METHOD[op]) return METHOD[op];
 218    return op.split('_').map((w) => w[0].toUpperCase() + w.slice(1)).join('');
 219  }
 220