systemquery/src/static/js/ui/TableView.mjs

97 lines
3.0 KiB
JavaScript

"use strict";
import Emel from 'emel';
import fa_emel from './forkawesome_emel.mjs';
import AbstractUIItem from './AbstractUIItem.mjs';
import ui_item_index from './ui_item_index.mjs';
import tabledefs from '../tabledefs/index.mjs';
class TableView {
constructor(el) {
if(el === null || typeof el === "undefined") throw new Error(`Expected HTML element as the first argument, but got null or undefined.`);
this.el = el;
this.el_parts = new Map();
this.emel = new Emel().emel;
}
/**
* Clears the currently displayed table.
* @return {void}
*/
clear() {
this.el_parts.clear();
// No need to call this here, as everything gets replaced instantly at the end of init()
// this.el.replaceChildren();
}
/**
* Initialises the view to display a new table.
* You probably want to call .switch_table() instead.
* @param {Object} tabledef The table definition to use to render the display for the new table.
* @return {void}
*/
init(tabledef) {
this.clear();
const parts = this.emel(`h2>(${fa_emel(tabledef.icon)}+{?})^div.data-display`, {
placeholders: [
tabledef.name
]
});
const el_dataitems = parts.querySelector(".data-display");
for(let def of tabledef.items) {
let el = document.createElement("div");
el.classList.add("data-item");
console.log(ui_item_index[def.type]);
if(typeof ui_item_index[def.type] !== "undefined") {
let item_manager = new ui_item_index[def.type](el, def);
this.el_parts.set(def.name, item_manager);
console.log(`TableView:UIItem create`, item_manager);
}
else {
console.warn(`Unknown item definition type '${def.type}', ignoring. This is probably a bug.`, def);
continue;
}
// Only append the item to the display if we actually found a manager for it
el_dataitems.appendChild(el);
}
this.el.replaceChildren(parts);
}
/**
* Switches the view to display a new table.
* Fetches table data from the server, so this may take a moment.
* @param {string} table_name The name of the new table to display.
* @return {Promise} A Promise that resolves when the updating of the UI is complete.
*/
async switch_table(table_name) {
table_name = table_name.replace(/[^a-z0-9-_]/g, "");
if(typeof tabledefs[table_name] === "undefined")
throw new Error(`Error: No definition found for table with the name '${table_name}' (in future, we should render thee raw JSON with a header containing the table name or something).`);
this.init(tabledefs[table_name]);
for await (let tabledef of await globalThis.sysquery.table(table_name)) {
this.append_table(tabledef.peer, tabledef.table);
}
}
/**
* Appends the given peer and table data to the UI.
* @param {{id: string, name: string}} peer The peer information.
* @param {Object} table The table itself to display.
* @return {void}
*/
append_table(peer, table) {
console.log(`TableView:append PEER`, peer, `TABLE`, table);
for(let [ def_name, item_manager ] of this.el_parts) {
if(item_manager === null) continue;
item_manager.append(peer, table);
}
}
}
export default TableView;