|
| 1 | +import { Component, Prop, Part } from '@pictogrammers/element'; |
| 2 | + |
| 3 | +import PgJsonArray from '../jsonArray/jsonArray'; |
| 4 | +import PgJsonObject from '../jsonObject/jsonObject'; |
| 5 | + |
| 6 | +import template from './json.html'; |
| 7 | +import style from './json.css'; |
| 8 | + |
| 9 | +function unwrapObject(obj: any) { |
| 10 | + return { |
| 11 | + items: Object.keys(obj).map((key) => { |
| 12 | + return { |
| 13 | + key, |
| 14 | + value: obj[key], |
| 15 | + } |
| 16 | + }) |
| 17 | + }; |
| 18 | +} |
| 19 | + |
| 20 | +function unwrapArray(items: any) { |
| 21 | + return { |
| 22 | + items: items.map((item) => { |
| 23 | + if (Array.isArray(item)) { |
| 24 | + return unwrapArray(item); |
| 25 | + } else { |
| 26 | + return unwrapObject(item); |
| 27 | + } |
| 28 | + }) |
| 29 | + }; |
| 30 | +} |
| 31 | + |
| 32 | +@Component({ |
| 33 | + selector: 'pg-json', |
| 34 | + style, |
| 35 | + template, |
| 36 | +}) |
| 37 | +export default class PgJson extends HTMLElement { |
| 38 | + @Prop() value: any = null; |
| 39 | + @Prop() root = []; |
| 40 | + @Prop() schema: any = null; |
| 41 | + |
| 42 | + @Part() $container: HTMLElement; |
| 43 | + |
| 44 | + render(changes) { |
| 45 | + if (changes.value && this.value !== null) { |
| 46 | + if (typeof this.value === 'object') { |
| 47 | + const $object = document.createElement('pg-json-object') as PgJsonObject; |
| 48 | + $object.items = unwrapObject(this.value).items; |
| 49 | + this.$container.appendChild($object); |
| 50 | + } else if (Array.isArray(this.value)) { |
| 51 | + const $array = document.createElement('pg-json-array') as PgJsonArray; |
| 52 | + $array.items = unwrapArray(this.value).items; |
| 53 | + this.$container.appendChild($array); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments