hugo-theme-cyberscopes/assets/js/comp-data.ts

104 lines
2.3 KiB
TypeScript

// comp-data.ts - definition and methods of the Data component
import { sendMsg } from './common'
// Data component
export function Data(name, action, domain: string): object {
domain = domain || this.conf.domain
const comp = {
id: this.conf.itemid,
name: name, // also used as class of incoming/outgoing message
action: action, // (default) action of outgoing message
domain: domain, // domain of incoming/outgoing message
data: {}, // model (2-way data store)
data_bak: {}, // backup copy when leaving view or edit mode
meta: {}, // metadata (params) for each data field
mode: 'view',
handle, // handle incoming messages
exec, // default function to execute upon button click
initField, // initialize field (= @mounted)
chmode,
copynew
}
this.components[name] = comp
if (comp.id) {
sendMsg(this.conf, [domain, 'query', name, comp.id], {})
}
return comp
}
// Data methods
function handle(domain, action, class_, item: string, data: Object) {
if (action == 'data') {
Object.assign(this.data, data)
}
}
function exec(action: string) {
action = action || this.action
const data = this.data
const conf = this.conf
let value = ''
for (const k of Object.keys(data)) {
value += `${k}: ${data[k]}, `
}
this.output += '\n' + value
console.log('exec:', value)
sendMsg(conf, [this.domain, action, this.name, data.id], data)
}
function initField(name: string, meta: any) {
if (meta.defexpr) {
meta.default = eval(meta.defexpr)
}
this.data[name] = meta.default || ""
this.meta[name] = meta
}
function chmode(action: string) {
if (this.mode == action) {
return
}
if (this.mode == 'view') {
Object.assign(this.data_bak, this.data)
}
switch(action) {
case 'query':
setQuery(this)
break
case 'new':
setNew(this)
break
default:
Object.assign(this.data, this.data_bak)
}
this.mode = action
}
function copynew(action: string) {
Object.assign(this.data, this.data_bak)
this.data.id = ''
this.mode = 'new'
}
// helper functions for data manipulation (used by Data component)
function setQuery(obj) {
for (const key in obj.data) {
obj.data[key] = ''
}
}
function setNew(obj) {
for (const key in obj.data) {
obj.data[key] = ''
const meta = obj.meta[key]
if (meta) {
obj.data[key] = meta.default || ''
}
}
obj.data.id = ''
}