package file→ .shtukbase/packages/layout-basic/lens.js
lens.js
128 lines, 4.7 KB.
- // lens.js: the client every lens links (contract §7). Gives the page window.shtuk.
- // In a frame (sandbox="allow-scripts", opaque origin) it talks to the shell by postMessage and
- // matches replies by id; standalone (no parent) it calls POST /_api itself.
- // Link it in <head> without defer: it sets data-skin / data-theme on <html> before the first paint.
- (function () {
- 'use strict';
- var root = document.documentElement;
- var query = new URLSearchParams(location.search);
- var framed = window.parent !== window;
- function applyTheme(skin, theme) {
- root.setAttribute('data-skin', skin || 'desktop');
- if (theme === 'dark') root.setAttribute('data-theme', 'dark');
- else root.removeAttribute('data-theme');
- }
- // Theme before paint: the shell puts it in the frame URL; standalone reads the page.js keys.
- (function () {
- var skin = query.get('skin');
- var theme = query.get('theme');
- if (!framed) {
- try {
- skin = skin || localStorage.getItem('lx-skin');
- theme = theme || localStorage.getItem('lx-theme');
- } catch (e) { /* storage may be blocked */ }
- if (!theme && window.matchMedia && matchMedia('(prefers-color-scheme: dark)').matches) theme = 'dark';
- }
- applyTheme(skin, theme);
- })();
- var handlers = { changed: [], theme: [], focus: [] };
- var pending = new Map();
- var seq = 0;
- var readySent = false;
- function emit(name, data) {
- var list = handlers[name] || [];
- for (var i = 0; i < list.length; i++) {
- try { list[i](data); } catch (e) { console.error(e); }
- }
- }
- function post(msg) { window.parent.postMessage(msg, '*'); }
- if (framed) {
- window.addEventListener('message', function (event) {
- if (event.source !== window.parent) return;
- var msg = event.data;
- if (!msg || typeof msg !== 'object') return;
- if (msg.type === 'reply') {
- var p = pending.get(msg.id);
- if (!p) return;
- pending.delete(msg.id);
- if (msg.error != null) p.reject(new Error(msg.error));
- else p.resolve(msg.result);
- } else if (msg.type === 'theme') {
- applyTheme(msg.skin, msg.theme);
- emit('theme', msg);
- } else if (msg.type === 'changed') {
- emit('changed', msg);
- } else if (msg.type === 'focus' && typeof msg.path === 'string') {
- window.shtuk.path = msg.path;
- emit('focus', msg);
- }
- });
- }
- function ask(msg) {
- return new Promise(function (resolve, reject) {
- msg.id = ++seq;
- pending.set(msg.id, { resolve: resolve, reject: reject });
- post(msg);
- });
- }
- // Per-lens storage. A sandboxed frame has no localStorage: the shell keeps the values under
- // shtuk.lens.<package>.<key>; standalone, the same key in this page's localStorage.
- var pkg = (location.pathname.match(/\/_pkg\/([^/]+)\//) || [])[1] || 'page';
- function localKey(key) { return 'shtuk.lens.' + pkg + '.' + key; }
- var storage = {
- get: function (key) {
- if (framed) return ask({ type: 'storage', key: String(key) });
- try { var s = localStorage.getItem(localKey(key)); return Promise.resolve(s == null ? null : JSON.parse(s)); }
- catch (e) { return Promise.resolve(null); }
- },
- set: function (key, value) {
- if (framed) return ask({ type: 'storage', key: String(key), value: value === undefined ? null : value });
- try { localStorage.setItem(localKey(key), JSON.stringify(value === undefined ? null : value)); } catch (e) { /* blocked or full */ }
- return Promise.resolve(null);
- }
- };
- function call(action, params) {
- if (framed) return ask({ type: 'call', action: action, params: params || {} });
- var body = Object.assign({ do: action }, params || {});
- return fetch('/_api', {
- method: 'POST',
- credentials: 'same-origin',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify(body)
- }).then(function (r) { return r.json(); }).then(function (data) {
- if (data && data.error != null) throw new Error(data.error);
- var result = data ? data.result : undefined;
- if (action === 'records.write') setTimeout(function () { emit('changed', { path: params && params.path }); }, 0);
- return result;
- });
- }
- window.shtuk = {
- path: query.get('path') || '/',
- framed: framed,
- call: call,
- storage: storage,
- open: function (path, opts) {
- var mode = opts && opts.mode;
- if (framed) post(mode ? { type: 'open', path: path, mode: mode } : { type: 'open', path: path });
- else location.href = '/?path=' + encodeURIComponent(path);
- },
- ready: function () {
- if (readySent) return;
- readySent = true;
- if (framed) post({ type: 'ready' });
- },
- on: function (name, fn) {
- (handlers[name] = handlers[name] || []).push(fn);
- }
- };
- })();