ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/layout-basic/lens.js

lens.js

128 líneas, 4.7 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // lens.js: the client every lens links (contract §7). Gives the page window.shtuk.
  2. // In a frame (sandbox="allow-scripts", opaque origin) it talks to the shell by postMessage and
  3. // matches replies by id; standalone (no parent) it calls POST /_api itself.
  4. // Link it in <head> without defer: it sets data-skin / data-theme on <html> before the first paint.
  5. (function () {
  6. 'use strict';
  7. var root = document.documentElement;
  8. var query = new URLSearchParams(location.search);
  9. var framed = window.parent !== window;
  10. function applyTheme(skin, theme) {
  11. root.setAttribute('data-skin', skin || 'desktop');
  12. if (theme === 'dark') root.setAttribute('data-theme', 'dark');
  13. else root.removeAttribute('data-theme');
  14. }
  15. // Theme before paint: the shell puts it in the frame URL; standalone reads the page.js keys.
  16. (function () {
  17. var skin = query.get('skin');
  18. var theme = query.get('theme');
  19. if (!framed) {
  20. try {
  21. skin = skin || localStorage.getItem('lx-skin');
  22. theme = theme || localStorage.getItem('lx-theme');
  23. } catch (e) { /* storage may be blocked */ }
  24. if (!theme && window.matchMedia && matchMedia('(prefers-color-scheme: dark)').matches) theme = 'dark';
  25. }
  26. applyTheme(skin, theme);
  27. })();
  28. var handlers = { changed: [], theme: [], focus: [] };
  29. var pending = new Map();
  30. var seq = 0;
  31. var readySent = false;
  32. function emit(name, data) {
  33. var list = handlers[name] || [];
  34. for (var i = 0; i < list.length; i++) {
  35. try { list[i](data); } catch (e) { console.error(e); }
  36. }
  37. }
  38. function post(msg) { window.parent.postMessage(msg, '*'); }
  39. if (framed) {
  40. window.addEventListener('message', function (event) {
  41. if (event.source !== window.parent) return;
  42. var msg = event.data;
  43. if (!msg || typeof msg !== 'object') return;
  44. if (msg.type === 'reply') {
  45. var p = pending.get(msg.id);
  46. if (!p) return;
  47. pending.delete(msg.id);
  48. if (msg.error != null) p.reject(new Error(msg.error));
  49. else p.resolve(msg.result);
  50. } else if (msg.type === 'theme') {
  51. applyTheme(msg.skin, msg.theme);
  52. emit('theme', msg);
  53. } else if (msg.type === 'changed') {
  54. emit('changed', msg);
  55. } else if (msg.type === 'focus' && typeof msg.path === 'string') {
  56. window.shtuk.path = msg.path;
  57. emit('focus', msg);
  58. }
  59. });
  60. }
  61. function ask(msg) {
  62. return new Promise(function (resolve, reject) {
  63. msg.id = ++seq;
  64. pending.set(msg.id, { resolve: resolve, reject: reject });
  65. post(msg);
  66. });
  67. }
  68. // Per-lens storage. A sandboxed frame has no localStorage: the shell keeps the values under
  69. // shtuk.lens.<package>.<key>; standalone, the same key in this page's localStorage.
  70. var pkg = (location.pathname.match(/\/_pkg\/([^/]+)\//) || [])[1] || 'page';
  71. function localKey(key) { return 'shtuk.lens.' + pkg + '.' + key; }
  72. var storage = {
  73. get: function (key) {
  74. if (framed) return ask({ type: 'storage', key: String(key) });
  75. try { var s = localStorage.getItem(localKey(key)); return Promise.resolve(s == null ? null : JSON.parse(s)); }
  76. catch (e) { return Promise.resolve(null); }
  77. },
  78. set: function (key, value) {
  79. if (framed) return ask({ type: 'storage', key: String(key), value: value === undefined ? null : value });
  80. try { localStorage.setItem(localKey(key), JSON.stringify(value === undefined ? null : value)); } catch (e) { /* blocked or full */ }
  81. return Promise.resolve(null);
  82. }
  83. };
  84. function call(action, params) {
  85. if (framed) return ask({ type: 'call', action: action, params: params || {} });
  86. var body = Object.assign({ do: action }, params || {});
  87. return fetch('/_api', {
  88. method: 'POST',
  89. credentials: 'same-origin',
  90. headers: { 'content-type': 'application/json' },
  91. body: JSON.stringify(body)
  92. }).then(function (r) { return r.json(); }).then(function (data) {
  93. if (data && data.error != null) throw new Error(data.error);
  94. var result = data ? data.result : undefined;
  95. if (action === 'records.write') setTimeout(function () { emit('changed', { path: params && params.path }); }, 0);
  96. return result;
  97. });
  98. }
  99. window.shtuk = {
  100. path: query.get('path') || '/',
  101. framed: framed,
  102. call: call,
  103. storage: storage,
  104. open: function (path, opts) {
  105. var mode = opts && opts.mode;
  106. if (framed) post(mode ? { type: 'open', path: path, mode: mode } : { type: 'open', path: path });
  107. else location.href = '/?path=' + encodeURIComponent(path);
  108. },
  109. ready: function () {
  110. if (readySent) return;
  111. readySent = true;
  112. if (framed) post({ type: 'ready' });
  113. },
  114. on: function (name, fn) {
  115. (handlers[name] = handlers[name] || []).push(fn);
  116. }
  117. };
  118. })();