salix/front/core/components/json-value/index.js

80 lines
2.2 KiB
JavaScript

import ngModule from '../../module';
import Component from 'core/lib/component';
import './style.scss';
const maxStrLen = 512;
/**
* Displays pretty JSON value.
*
* @property {*} value The value
*/
export default class Controller extends Component {
get value() {
return this._value;
}
set value(value) {
const wasEmpty = this._value === undefined;
this._value = value;
let text;
let cssClass;
const type = typeof value;
if (value == null) {
text = '∅';
cssClass = 'null';
} else {
cssClass = type;
switch (type) {
case 'number':
if (Number.isInteger(value))
text = value;
else
text = Math.round((value + Number.EPSILON) * 1000) / 1000;
break;
case 'boolean':
text = value ? '✓' : '✗';
cssClass = value ? 'true' : 'false';
break;
case 'string':
text = value.length <= maxStrLen
? value
: value.substring(0, maxStrLen) + '...';
break;
case 'object':
if (value instanceof Date) {
const hasZeroTime =
value.getHours() === 0 &&
value.getMinutes() === 0 &&
value.getSeconds() === 0;
const format = hasZeroTime ? 'dd/MM/yyyy' : 'dd/MM/yyyy HH:mm:ss';
text = this.$filter('date')(value, format);
} else
text = value;
break;
default:
text = value;
}
}
const el = this.element;
el.textContent = text;
el.title = type == 'string' && value.length > maxStrLen ? value : '';
cssClass = `json-${cssClass}`;
if (wasEmpty)
el.classList.add(cssClass);
else
el.classList.replace(this.className, cssClass);
}
}
ngModule.vnComponent('vnJsonValue', {
controller: Controller,
bindings: {
value: '<?'
}
});