mirror of
https://github.com/cesanta/mongoose.git
synced 2026-11-19 19:40:56 +00:00
Dash OTA dogfooding nits
This commit is contained in:
1 parent
73037880e6
commit
27459efc61
29 files changed
+2635
-1478
No files matched your search
+201
-82
@@ -3,19 +3,13 @@
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
const Rpc = (function() {
|
||||
function Rpc(url, onev) {
|
||||
let ws, id = 1, oncall, q = [], reconnect = true;
|
||||
const pending = new Map();
|
||||
const realsend = s => { ws.send(s); onev && onev('send', s); };
|
||||
const fail = e => { for (const p of pending.values()) p[1](e || 'disconnected'); pending.clear(); };
|
||||
const send = x => ws && ws.readyState === 1
|
||||
? realsend(JSON.stringify(x))
|
||||
: q.push(x);
|
||||
const Watch = (function() {
|
||||
function Watch(url, onev, onmsg) {
|
||||
let ws, reconnect = true;
|
||||
const connect = () => {
|
||||
ws = new WebSocket(url);
|
||||
ws.onopen = () => { onev && onev('open'); while (q.length) realsend(JSON.stringify(q.shift())); };
|
||||
ws.onclose = () => { onev && onev('close'); fail(); reconnect && setTimeout(connect, 1000); };
|
||||
ws.onopen = () => onev && onev('open');
|
||||
ws.onclose = () => { onev && onev('close'); reconnect && setTimeout(connect, 1000); };
|
||||
ws.onmessage = e => {
|
||||
onev && onev('message', e.data);
|
||||
let m;
|
||||
@@ -25,69 +19,92 @@
|
||||
console.log('INVALID JSON:', e.data);
|
||||
return;
|
||||
}
|
||||
|
||||
if (m.id && pending.has(m.id)) {
|
||||
const [ok, bad] = pending.get(m.id);
|
||||
pending.delete(m.id);
|
||||
m.error ? bad(m.error) : ok(m.result);
|
||||
} else if (oncall && m.method) {
|
||||
Promise.resolve(oncall(m.method, m.params))
|
||||
.then(r => m.id && send({ id: m.id, result: r }))
|
||||
.catch(err => m.id && send({
|
||||
id: m.id,
|
||||
error: { code: -32000, message: String(err?.message || err) }
|
||||
}));
|
||||
}
|
||||
onmsg && onmsg(m);
|
||||
};
|
||||
};
|
||||
|
||||
connect();
|
||||
return {
|
||||
close: () => { reconnect = false; ws?.close(); },
|
||||
call: (method, params) => new Promise((ok, bad) => {
|
||||
const i = id++;
|
||||
pending.set(i, [ok, bad]);
|
||||
send({ id: i, method, params });
|
||||
}),
|
||||
notify: (method, params) => send({ method, params }),
|
||||
handle: fn => (oncall = fn, this),
|
||||
get ws() { return ws; }
|
||||
};
|
||||
}
|
||||
|
||||
return Rpc;
|
||||
return Watch;
|
||||
})();
|
||||
|
||||
function rpc_connect() {
|
||||
function fetch_and_ready() {
|
||||
if (isMock) {
|
||||
setTimeout(() => userhandlers['ready']?.(), 500);
|
||||
return;
|
||||
return delay(500).then(rescan).then(mark_ready);
|
||||
}
|
||||
if (rpc) return rpc;
|
||||
//if (settings.auth && !status.authed) return null;
|
||||
rpc = Rpc('api/websocket', function (evname, args) {
|
||||
if (evname == 'open') status.online = true, rescan();
|
||||
if (evname == 'close') status.online = false, rescan();
|
||||
if (settings.debug) console.log('WS', evname, args);
|
||||
});
|
||||
rpc.handle((method, args) => {
|
||||
if (method == 'change' && args) apply_and_rescan(settings.data, args);
|
||||
if (method == 'logout') rpc_disconnect();
|
||||
if (userhandlers[method]) userhandlers[method](args);
|
||||
});
|
||||
return rpc;
|
||||
return fetch('api/get')
|
||||
.then(r => r.ok ? r.json() : Promise.reject(r.status))
|
||||
.then(data => {
|
||||
for (const k in data) {
|
||||
if (typeof data[k] === 'number') {
|
||||
const prev = settings.data[k];
|
||||
const arr = prev && typeof prev === 'object' ? prev : {};
|
||||
data[k] = {
|
||||
...arr,
|
||||
size: data[k],
|
||||
start: typeof arr.start === 'number' ? arr.start : 0,
|
||||
data: Array.isArray(arr.data) ? arr.data : [],
|
||||
};
|
||||
}
|
||||
}
|
||||
return apply_and_rescan(settings.data, data);
|
||||
})
|
||||
.then(expand_arrays)
|
||||
.then(() => {
|
||||
ws_connect();
|
||||
return mark_ready();
|
||||
})
|
||||
.catch(err => console.log('GET failed', err));
|
||||
}
|
||||
|
||||
function rpc_disconnect() {
|
||||
if (!rpc) return;
|
||||
rpc.close();
|
||||
rpc = null;
|
||||
function ws_connect() {
|
||||
if (isMock || ws) return;
|
||||
ws = Watch('api/websocket', function (evname, args) {
|
||||
if (evname == 'open') { status.online = true; rescan(); }
|
||||
if (evname == 'close') { status.online = false; rescan(); }
|
||||
if (settings.debug) console.log('WS', evname, args);
|
||||
}, function (m) {
|
||||
if (m.method == 'change' && m.params) {
|
||||
const rest = {};
|
||||
const arrays = [];
|
||||
for (const k in m.params) {
|
||||
const ma = k.match(/^(.+)\/(\d+)$/);
|
||||
if (ma) {
|
||||
const arr = settings.data[ma[1]];
|
||||
if (arr?.data) { const i = +ma[2] - (arr.start || 0); if (i >= 0 && i < arr.data.length) arr.data[i] = Object.assign(arr.data[i] || {}, m.params[k]); }
|
||||
} else if (typeof m.params[k] === 'number' && settings.data[k]?.data !== undefined) {
|
||||
const arr = settings.data[k];
|
||||
arr.size = m.params[k];
|
||||
if (is_expandable(arr)) arrays.push(expand_array(k, arr.start, arr.end));
|
||||
} else {
|
||||
rest[k] = m.params[k];
|
||||
}
|
||||
}
|
||||
apply(settings.data, rest);
|
||||
prune(settings.data, settings.edits);
|
||||
Promise.all(arrays)
|
||||
.then(rescan)
|
||||
.then(() => userhandlers['change']?.(m.params));
|
||||
}
|
||||
if (m.method == 'logout') ws_disconnect();
|
||||
});
|
||||
}
|
||||
|
||||
function ws_disconnect() {
|
||||
if (!ws) return;
|
||||
ws.close();
|
||||
ws = null;
|
||||
status.online = false;
|
||||
}
|
||||
|
||||
|
||||
function login(params) {
|
||||
if (isMock) { rpc_connect(); return Promise.resolve({}); }
|
||||
if (isMock) return fetch_and_ready().then(() => ({}));
|
||||
const opts = {};
|
||||
if (params) {
|
||||
const username = (params?.username ?? '').trim();
|
||||
@@ -100,19 +117,18 @@
|
||||
.then(resp => {
|
||||
status.username = resp?.user || '';
|
||||
status.userlevel = resp?.level || 0;
|
||||
rpc_connect();
|
||||
return resp;
|
||||
return fetch_and_ready().then(() => resp);
|
||||
});
|
||||
};
|
||||
|
||||
function logout() {
|
||||
if (isMock) { rpc_disconnect(); return Promise.resolve({}); }
|
||||
if (isMock) { ws_disconnect(); return Promise.resolve({}); }
|
||||
return fetch('api/logout')
|
||||
.catch(() => true)
|
||||
.then(() => {
|
||||
status.username = '';
|
||||
status.userlevel = 0;
|
||||
rpc_disconnect();
|
||||
ws_disconnect();
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -122,7 +138,27 @@
|
||||
const settings = {data: {}, edits: {}, debug: true};
|
||||
const userhandlers = {}; // User event handlers
|
||||
const status = { online: false, username: '', userlevel: 0, ready: false };
|
||||
let rpc = null;
|
||||
let ws = null;
|
||||
let ready_started = false;
|
||||
|
||||
function install_ready_gate() {
|
||||
document.documentElement.classList.remove('dashboard-ready');
|
||||
if (document.getElementById('dashboard-ready-gate')) return;
|
||||
const style = document.createElement('style');
|
||||
style.id = 'dashboard-ready-gate';
|
||||
style.textContent = `html:not(.dashboard-ready) *,html:not(.dashboard-ready) *::before,html:not(.dashboard-ready) *::after{transition:none!important;animation:none!important}`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
function mark_ready() {
|
||||
if (ready_started) return Promise.resolve();
|
||||
ready_started = true;
|
||||
return next_frame().then(() => {
|
||||
status.ready = true;
|
||||
document.documentElement.classList.add('dashboard-ready');
|
||||
userhandlers['ready']?.();
|
||||
});
|
||||
}
|
||||
|
||||
const fromPath = (path, value) => path.split('.').reverse().reduce((acc, k) => ({ [k]: acc }), value);
|
||||
const get = (obj, path) => path.split('.').reduce((o, k) => o?.[k], obj);
|
||||
@@ -222,7 +258,11 @@
|
||||
function save(key) {
|
||||
const changes = {};
|
||||
set(changes, key, get(settings.edits, key));
|
||||
rpc.call('set', changes).then(r => apply_and_rescan(settings.data, r));
|
||||
fetch('api/set', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify(changes),
|
||||
}).catch(err => console.log('SET failed', key, err));
|
||||
};
|
||||
|
||||
// Cancel the edits for keys that match pattern
|
||||
@@ -231,6 +271,14 @@
|
||||
rescan();
|
||||
};
|
||||
|
||||
// Set a checkbox's `checked` *property* from a boolean expression. The
|
||||
// `checked` content attribute is presence-based - templating its value
|
||||
// would not work, so this binds straight to the IDL property instead
|
||||
function handle_checked(el, key, context) {
|
||||
if (!has(context, key)) { console.error('EVAL', key, context); return; }
|
||||
el.checked = !!get(context, key);
|
||||
};
|
||||
|
||||
function handle_save(el, key) {
|
||||
el.disabled = !edited(key);
|
||||
if (!el.bound) el.addEventListener("click", ev => save(key)), el.bound = true;
|
||||
@@ -244,18 +292,30 @@
|
||||
function handle_repeat(el, key, context) {
|
||||
if (!has(context, key)) { console.error('EVAL', key, context); return; }
|
||||
if (!el.orig) el.orig = el.children[0].cloneNode(true);
|
||||
const v = get(context, key), v2 = JSON.stringify(v);
|
||||
if (el.v2 === v2) return;
|
||||
const frag = document.createDocumentFragment();
|
||||
const v = get(context, key);
|
||||
const it = el.dataset.iterator ?? '__obj';
|
||||
v.forEach(function (item, index) {
|
||||
const child = el.orig.cloneNode(true);
|
||||
const ctx = { ...context, [it]: item };
|
||||
process(child, ctx, true);
|
||||
frag.appendChild(child);
|
||||
});
|
||||
el.replaceChildren(frag);
|
||||
el.v2 = v2;
|
||||
const json = v.map(item => JSON.stringify(item));
|
||||
const prev = el.itemsJson || [];
|
||||
if (json.length === prev.length && el.children.length === json.length) {
|
||||
// Same length: re-template each changed row's existing DOM node in
|
||||
// place instead of replacing it. Untouched rows are left completely
|
||||
// alone, and changed rows keep their live elements too - so bound
|
||||
// properties (e.g. a checkbox's `checked`) change on an
|
||||
// already-painted node, which is what lets CSS transitions play, and
|
||||
// in-progress edits in unrelated fields of that row survive
|
||||
json.forEach((j, i) => {
|
||||
if (j !== prev[i]) process(el.children[i], { ...context, [it]: v[i] }, true);
|
||||
});
|
||||
} else {
|
||||
const frag = document.createDocumentFragment();
|
||||
v.forEach(item => {
|
||||
const node = el.orig.cloneNode(true);
|
||||
process(node, { ...context, [it]: item }, true);
|
||||
frag.appendChild(node);
|
||||
});
|
||||
el.replaceChildren(frag);
|
||||
}
|
||||
el.itemsJson = json;
|
||||
};
|
||||
|
||||
function upload(el, is_ota) {
|
||||
@@ -267,7 +327,7 @@
|
||||
const reader = new FileReader();
|
||||
reader.readAsArrayBuffer(f);
|
||||
reader.onload = function () {
|
||||
const url = is_ota ? 'api/ota' : `fs/${encodeURIComponent(f.name)}`;
|
||||
const url = is_ota ? 'api/ota' : `fs/${el.dataset.upload}/${encodeURIComponent(f.name)}`;
|
||||
let begin = Date.now(), body = reader.result, ok = false;
|
||||
// console.log(2, url, body);
|
||||
fetch(url, { method: 'POST', body })
|
||||
@@ -295,7 +355,8 @@
|
||||
}
|
||||
|
||||
function process(root, context, x) {
|
||||
const all = root.querySelectorAll("*:not([data-repeat] *)");
|
||||
const selector = x ? "*" : "*:not([data-repeat] *)";
|
||||
const all = root.querySelectorAll(selector);
|
||||
const els = root.nodeType === Node.DOCUMENT_NODE ? all : [root, ...all];
|
||||
els.forEach(function (el) {
|
||||
if (el.tagName === "SCRIPT" || el.tagName === "STYLE") return;
|
||||
@@ -309,14 +370,16 @@
|
||||
}
|
||||
for (const attr of el.attributes) {
|
||||
const cv = attr.value || '';
|
||||
if (attr.originalValue || cv.includes('${')) {
|
||||
if (!attr.originalValue) attr.originalValue = cv;
|
||||
const v = substituteExpressions(attr.originalValue, context);
|
||||
if (!el.originalAttrs) el.originalAttrs = {};
|
||||
if (el.originalAttrs[attr.name] || cv.includes('${')) {
|
||||
if (!el.originalAttrs[attr.name]) el.originalAttrs[attr.name] = cv;
|
||||
const v = substituteExpressions(el.originalAttrs[attr.name], context);
|
||||
if (v !== attr.value) attr.value = v;
|
||||
}
|
||||
}
|
||||
const handlers = {
|
||||
bind: handle_bind,
|
||||
checked: handle_checked,
|
||||
save: handle_save,
|
||||
cancel: handle_cancel,
|
||||
repeat: handle_repeat,
|
||||
@@ -341,21 +404,75 @@
|
||||
|
||||
function rescan() {
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", realrescan, { once: true });
|
||||
return new Promise(resolve => {
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
realrescan();
|
||||
resolve();
|
||||
}, { once: true });
|
||||
});
|
||||
} else {
|
||||
realrescan();
|
||||
return Promise.resolve();
|
||||
}
|
||||
};
|
||||
|
||||
const delay = (ms, value) => new Promise(r => setTimeout(() => r(value), ms));
|
||||
const next_frame = () => new Promise(r => requestAnimationFrame(() => r()));
|
||||
const is_expandable = arr => arr && Array.isArray(arr.data) &&
|
||||
typeof arr.start === 'number' && typeof arr.end === 'number';
|
||||
|
||||
function expand_array(name, start, end) {
|
||||
const arr = settings.data[name];
|
||||
const page = 100, all = [];
|
||||
const stop = Math.min(end, typeof arr?.size === 'number' ? arr.size - 1 : end);
|
||||
const done = () => {
|
||||
set(settings.data, `${name}.data`, all);
|
||||
set(settings.data, `${name}.start`, start);
|
||||
return rescan().then(() => all);
|
||||
};
|
||||
const next = from => {
|
||||
if (from > stop) return Promise.resolve(done());
|
||||
const to = Math.min(from + page - 1, stop);
|
||||
return fetch(`api/get/${name}/${from}/${to}`)
|
||||
.then(r => r.ok ? r.json() : Promise.reject(r.statusText))
|
||||
.then(data => {
|
||||
if (!data || !data.length) return done();
|
||||
all.push(...data);
|
||||
return next(from + data.length);
|
||||
});
|
||||
};
|
||||
return next(start);
|
||||
}
|
||||
|
||||
function expand_arrays() {
|
||||
const all = [];
|
||||
for (const name in settings.data) {
|
||||
const arr = settings.data[name];
|
||||
if (is_expandable(arr)) all.push(expand_array(name, arr.start, arr.end));
|
||||
}
|
||||
return Promise.all(all);
|
||||
}
|
||||
|
||||
function call(name, args) {
|
||||
if (isMock) {
|
||||
return delay(750, true).then(val => console.log('response', name));
|
||||
} else {
|
||||
return rpc.call(name, args)
|
||||
.catch(err => console.log('CALL FAILED', name, args, err));
|
||||
return delay(750, true).then(() => console.log('response', name));
|
||||
}
|
||||
if (name === 'set') {
|
||||
return fetch('api/set', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify(args),
|
||||
}).catch(err => console.log('CALL FAILED', name, args, err));
|
||||
}
|
||||
if (args && typeof args === 'object') {
|
||||
const {name: aname, start: s = 0, size: total = 100, end} = args;
|
||||
const stop = typeof end === 'number' ? end : s + total - 1;
|
||||
return expand_array(aname, s, stop).catch(err => console.log('CALL FAILED', name, args, err));
|
||||
}
|
||||
const path = typeof args === 'string' && args ? '/' + args : '';
|
||||
return fetch('api/get' + path)
|
||||
.then(r => r.ok ? r.json() : Promise.reject(r.statusText))
|
||||
.catch(err => console.log('CALL FAILED', name, args, err));
|
||||
};
|
||||
|
||||
function apply(target, patch) {
|
||||
@@ -373,16 +490,18 @@
|
||||
function apply_and_rescan(target, patch) {
|
||||
apply(target, patch);
|
||||
prune(settings.data, settings.edits);
|
||||
rescan();
|
||||
return rescan();
|
||||
};
|
||||
|
||||
function on(name, fn) {
|
||||
userhandlers[name] = fn;
|
||||
if (name === 'ready' && status.ready) setTimeout(fn, 0);
|
||||
};
|
||||
|
||||
function init(conf) {
|
||||
install_ready_gate();
|
||||
apply_and_rescan(settings, conf);
|
||||
if (!settings.auth) rpc_connect();
|
||||
if (!settings.auth) fetch_and_ready();
|
||||
};
|
||||
|
||||
global.Dashboard = { init, call, on, status, login, logout };
|
||||
|
||||
Reference in new issue
Block a user