This repository was archived by the owner on Jan 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjson-viewer.js
More file actions
503 lines (454 loc) · 12.9 KB
/
json-viewer.js
File metadata and controls
503 lines (454 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
/**
@license
Copyright 2018 The Advanced REST client authors <arc@mulesoft.com>
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
*/
import { LitElement, html, css } from 'lit-element';
import './js-max-number-error.js';
import { JsonParser } from './json-parser.js';
/**
* `<json-viewer>` A JSON payload viewer for the JSON response.
*
* This element uses a web worker to process the JSON data.
* To simplify our lives and app build process the worker script is embeded in the
* imported template body. It will extract worker data from it and create the
* worker. Otherwise build process would need to incude a worker script file
* into set path which is not very programmer friendly.
*
* ### Example
*
* ```html
* <json-viewer json='{"json": "test"}'></json-viewer>
* ```
*
* ## Custom search
*
* If the platform doesn't support native text search, this element implements
* `ArcBehaviors.TextSearchBehavior` and exposes the `query` attribute.
* Set any text to the `query` attribute and it will automatically highlight
* occurance of the text.
* See demo for example.
*
* ## Big numbers in JavaScript
*
* This element marks all numbers that are above `Number.MAX_SAFE_INTEGER` value
* and locates the numeric value in source json if passed json was a string or
* when `raw` attribute was set. In this case it will display a warning and
* explanation about use of big numbers in JavaScript.
* See js-max-number-error element documentation for more information.
*
* ## Content actions
*
* The element can render a actions pane above the code view. Action pane is to
* display content actions that is relevan in context of the response displayed
* below the icon buttons. It should be icon buttons or just buttons added to this
* view.
*
* ```html
* <json-viewer json='{"json": "test"}'>
* <paper-icon-button slot="content-action"
* title="Copy content to clipboard" icon="arc:content-copy"></paper-icon-button>
* </json-viewer>
* ```
*
* ### Styling
*
* `<json-viewer>` provides the following custom properties and mixins for styling:
*
* Custom property | Description | Default
* ----------------|-------------|----------
* `--json-viewer` | Mixin applied to the element | `{}`
* `--code-type-null-value-color` | Color of the null value. | `#708`
* `--code-type-boolean-value-color` | Color of the boolean value | `#708`
* `--code-punctuation-value-color` | Punctuation color. | `black`
* `--code-type-number-value-color` | Color of the numeric value | `blue`
* `--code-type-text-value-color` | Color of the string value. | `#295469`
* `--code-array-index-color` | Color of the array counter. | `rgb(119, 119, 119)`
* `--code-type-link-color` | Color of link inserted into the viewer. | `#1976d2`
* `--json-viewer-node` | Mixin applied to a "node" | `{}`
* `--code-dimmed-punctuation-opacity` | Value of the opacity on the "dimmed" punctuation | `0.34`
* `--code-background-color` | Background color of the code area | ``
*
* @group UiElements
* @element json-viewer
* @demo demo/index.html
*/
class JsonViewer extends LitElement {
get styles() {
return css`:host {
display: block;
font-family: var(--arc-font-code-family, monospace);
font-size: var(--arc-font-code-font-size, 1rem);
color: inherit;
cursor: text;
user-select: text;
}
.prettyPrint {
padding: 8px;
}
.stringValue {
white-space: normal;
color: var(--code-type-text-value-color, #295469);
}
.brace {
display: inline-block;
}
.numeric {
color: var(--code-type-number-value-color, blue);
}
.nullValue {
color: var(--code-type-null-value-color, #708);
}
.booleanValue {
color: var(--code-type-boolean-value-color, #708);
}
.punctuation {
color: var(--code-punctuation-value-color, black);
}
.node {
position: relative;
margin-bottom: 4px;
word-break: break-all;
white-space: pre-wrap;
overflow-wrap: break-word;
}
.array-counter {
color: gray;
font-size: 11px;
}
.array-counter::before {
content: "Array[" attr(count) "]";
user-select: none;
pointer-events: none;
}
*[data-expanded="false"] > .array-counter::before {
content: "Array[" attr(count) "] ...";
user-select: none;
pointer-events: none;
}
.array-key-number::before {
content: "" attr(index) ":";
user-select: none;
pointer-events: none;
}
.key-name {
color: var(--code-type-text-value-color, #295469);
}
.rootElementToggleButton {
position: absolute;
top: 0;
left: -9px;
font-size: 14px;
cursor: pointer;
font-weight: bold;
user-select: none;
}
.rootElementToggleButton::after {
content: "-";
}
.array-key-number {
color: var(--code-array-index-color, rgb(119, 119, 119));
}
.info-row {
display: none;
margin: 0 8px;
text-indent: 0;
}
div[data-expanded="false"] div[collapse-indicator] {
display: inline-block !important;
}
div[data-expanded="false"] div[data-element] {
display: none !important;
}
.arc-search-mark.selected {
background-color: #ff9632;
}
div[data-expanded="false"] .punctuation.dimmed {
opacity: 0;
}
.dimmed {
opacity: var(--code-dimmed-punctuation-opacity, 0.54);
}
a[response-anchor] {
color: var(--code-type-link-color, #1976d2);
}
.actions-panel {
display: flex;
flex-direction: row;
align-items: center;
}
.actions-panel.hidden {
display: none;
}
[hidden] {
display: none !important;
}
output {
display: block;
background-color: var(--code-background-color);
}`;
}
render() {
const { working, isError, json } = this;
const showOutput = this._computeShowOutput(working, isError, json);
return html`<style>${this.styles}</style>
${isError ? html`<div class="error">
<p>There was an error parsing JSON data</p>
</div>` : undefined}
<div class="${this._computeActionsPanelClass(showOutput)}">
<slot name="content-action"></slot>
</div>
<output ?hidden="${!showOutput}" @click="${this._handleDisplayClick}"></output>`;
}
static get properties() {
return {
/**
* JSON data to parse and display.
* It can be either JS object (already parsed string) or string value.
* If the passed object is a string then JSON.parse function will be
* used to parse string.
*/
json: { type: String },
/**
* If it's possible, set this property to the JSON string.
* It will help to handle big numbers that are not parsed correctly by
* the JSON.parse function. The parser will try to locate the number
* in the source string and display it in the correct form.
*
* P.S.
* Calling JSON.stringify on a JS won't help here :) Must be source
* string.
*/
raw: { type: String },
/**
* True if error ocurred when parsing the `json` data.
* An error message will be displayed.
*/
_isError: { type: Boolean },
/**
* True when JSON is beeing parsed.
*/
_working: { type: Boolean }
};
}
get isError() {
return this._isError;
}
get _isError() {
return this.__isError;
}
set _isError(value) {
const old = this.__isError;
if (old === value) {
return;
}
this.__isError = value;
this.requestUpdate('_isError', old);
this.dispatchEvent(new CustomEvent('iserror-changed', {
detail: {
value
}
}));
}
get working() {
return this._working;
}
get _working() {
return this.__working;
}
set _working(value) {
const old = this.__working;
if (old === value) {
return;
}
this.__working = value;
this.requestUpdate('_working', old);
this.dispatchEvent(new CustomEvent('working-changed', {
detail: {
value
}
}));
}
get json() {
return this._json;
}
set json(value) {
const old = this._json;
if (old === value) {
return;
}
this._json = value;
this._changed(value);
}
constructor() {
super();
this.raw = undefined;
this._isError = false;
this._working = false;
}
firstUpdated() {
this._isReady = true;
if (this.json) {
this._changed(this.json);
}
}
_clearOutput() {
const node = this.shadowRoot.querySelector('output');
node.innerHTML = '';
}
_writeOutput(text) {
const node = this.shadowRoot.querySelector('output');
node.innerHTML = text;
}
// Called when `json` property changed. It starts parsing the data.
_changed(json) {
if (!this._isReady) {
return;
}
this._isError = false;
this._clearOutput();
if (json === undefined) {
return;
}
this._working = true;
if (json === null) {
this._printPrimitiveValue('null', 'nullValue');
return;
}
if (json === false || json === true) {
this._printPrimitiveValue(String(json), 'booleanValue');
return;
}
try {
const parser = new JsonParser({
json,
raw: this.raw,
cssPrefix: this.nodeName.toLowerCase() + ' style-scope '
});
if (parser.latestError !== null) {
throw new Error(parser.latestError);
}
const html = parser.getHTML();
this._reportResult(html);
} catch (cause) {
this._reportError();
}
}
_printPrimitiveValue(value, klas) {
const html = `<div class="prettyPrint"><span class="${klas}">${value}</span></div>`;
this._writeOutput(html);
this._working = false;
this.dispatchEvent(new CustomEvent('json-viewer-parsed'));
}
_reportResult(html) {
this._writeOutput(html);
this._isError = false;
this._working = false;
this.dispatchEvent(new CustomEvent('json-viewer-parsed'));
}
// Called when worker error received.
_reportError() {
this._isError = true;
this._working = false;
this.dispatchEvent(new CustomEvent('json-viewer-parsed'));
}
// Compute if output should be shown.
_computeShowOutput(working, isError, json) {
if (working) {
return false;
}
if (isError) {
return true;
}
return typeof json !== 'undefined';
}
// Called when the user click on the display area. It will handle view toggle and links clicks.
_handleDisplayClick(e) {
if (!e.target) {
return;
}
if (e.target.nodeName === 'A') {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
const newEntity = e.ctrlKey || e.metaKey;
const url = e.target.getAttribute('href');
if (newEntity) {
this._dispatchNewRequest(url);
} else {
this._dispatchChangeUrl(url);
}
return;
}
const toggleId = e.target.dataset.toggle;
if (!toggleId) {
return;
}
const parent = /** @type HTMLElement */ (this.shadowRoot.querySelector('div[data-element="' + toggleId + '"]'));
if (!parent) {
return;
}
const expanded = parent.dataset.expanded;
if (!expanded || expanded === 'true') {
parent.dataset.expanded = 'false';
} else {
parent.dataset.expanded = 'true';
}
}
_dispatchChangeUrl(url) {
this.dispatchEvent(new CustomEvent('url-change-action', {
detail: {
url
},
bubbles: true,
cancelable: true,
composed: true
}));
}
_dispatchNewRequest(url) {
this.dispatchEvent(new CustomEvent('request-workspace-append', {
detail: {
kind: 'ARC#Request',
request: { url }
},
bubbles: true,
cancelable: true,
composed: true
}));
}
/**
* Computes CSS class for the actions pane.
*
* @param {Boolean} showOutput The `showOutput` propety value of the element.
* @return {String} CSS class names for the panel depending on state of the
* `showOutput`property.
*/
_computeActionsPanelClass(showOutput) {
let clazz = 'actions-panel';
if (!showOutput) {
clazz += ' hidden';
}
return clazz;
}
/**
* Event called when the user click on the anchor in display area.
*
* @event url-change-action
* @param {String} url The URL handled by this event.
* @param {Boolean} asNew When true it should be treated as "new tab" action.
*/
/**
* Fired when web worker finished work and the data are displayed.
*
* @event json-viewer-parsed
*/
}
window.customElements.define('json-viewer', JsonViewer);