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

104 lines
2.4 KiB
TypeScript

// comp-data.ts - definition and methods of the Data component
export function Data(name: string, conf: any): object {
const domain = conf.domain || this.conf.domain
const comp = {
state: {
id: this.conf.itemid,
mode: 'view'
},
name: name, // also used as class of incoming/outgoing message
action: conf.action, // (default) action of outgoing message
domain: domain, // domain of incoming/outgoing message
data: {}, // model (2-way data store)
meta: {}, // metadata (params) for each data field
handle, // handle incoming messages
exec, // default function to execute upon button click
initField, // initialize field (= @mounted)
chmode,
copynew
}
//this.components[name] = comp
if (comp.state.id) {
this.sendMsg([domain, 'query', name, comp.state.id], {})
}
return comp
}
// Data methods
function handle(domain, action, class_, item, payload: string) {
const data = JSON.parse(payload)
console.log('handle - action: ', action, ', data: ', data)
if (action === 'data') { // && this.state.id == item) {
Object.assign(this.data, data)
this.state.mode = 'view'
} else if (action === 'response') { // && data.rc == 3) {
this.state.id = item
window.location.hash = item
this.sendMsg([this.domain, 'query', this.name, item], {})
}
}
function exec(action: string) {
action = action || this.action
const data = this.data
let value = ''
for (const k of Object.keys(data)) {
value += `${k}: ${data[k]}, `
}
console.log('exec:', value)
const msgbase = [this.domain, action, this.name]
if (this.state.mode !== 'new') {
msgbase.push(this.state.id)
}
this.sendMsg(msgbase, 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.state.mode == action) {
return
}
switch(action) {
case 'query':
setQuery(this)
break
case 'new':
setNew(this)
break
}
this.state.mode = action
}
function copynew(action: string) {
this.state.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 || ''
} else {
delete obj.data[key]
}
}
}