forked from ChromeDevTools/devtools-frontend
-
Notifications
You must be signed in to change notification settings - Fork 7
/
ObjectPropertiesSection.ts
1860 lines (1672 loc) · 72.6 KB
/
ObjectPropertiesSection.ts
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
* Copyright (C) 2009 Joseph Pecoraro
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import * as Common from '../../../../core/common/common.js';
import type * as Components from '../utils/utils.js';
import * as Root from '../../../../core/root/root.js';
import * as Host from '../../../../core/host/host.js';
import * as i18n from '../../../../core/i18n/i18n.js';
import * as LinearMemoryInspector from '../../../components/linear_memory_inspector/linear_memory_inspector.js';
import * as Platform from '../../../../core/platform/platform.js';
import * as SDK from '../../../../core/sdk/sdk.js';
import * as TextUtils from '../../../../models/text_utils/text_utils.js';
import * as JavaScriptMetaData from '../../../../models/javascript_metadata/javascript_metadata.js';
import * as IconButton from '../../../components/icon_button/icon_button.js';
import * as TextEditor from '../../../components/text_editor/text_editor.js';
import * as UI from '../../legacy.js';
import {CustomPreviewComponent} from './CustomPreviewComponent.js';
import {JavaScriptREPL} from './JavaScriptREPL.js';
import {createSpansForNodeTitle, RemoteObjectPreviewFormatter} from './RemoteObjectPreviewFormatter.js';
import objectValueStyles from './objectValue.css.js';
import objectPropertiesSectionStyles from './objectPropertiesSection.css.js';
const UIStrings = {
/**
*@description Text in Object Properties Section
*@example {function alert() [native code] } PH1
*/
exceptionS: '[Exception: {PH1}]',
/**
*@description Text in Object Properties Section
*/
unknown: 'unknown',
/**
*@description Text to expand something recursively
*/
expandRecursively: 'Expand recursively',
/**
*@description Text to collapse children of a parent group
*/
collapseChildren: 'Collapse children',
/**
*@description Text in Object Properties Section
*/
noProperties: 'No properties',
/**
*@description Element text content in Object Properties Section
*/
dots: '(...)',
/**
*@description Element title in Object Properties Section
*/
invokePropertyGetter: 'Invoke property getter',
/**
*@description Show all text content in Show More Data Grid Node of a data grid
*@example {50} PH1
*/
showAllD: 'Show all {PH1}',
/**
* @description Value element text content in Object Properties Section. Shown when the developer is
* viewing a variable in the Scope view, whose value is not available (i.e. because it was optimized
* out) by the JavaScript engine, or inspecting a JavaScript object accessor property, which has no
* getter. This string should be translated.
*/
valueUnavailable: '<value unavailable>',
/**
* @description Tooltip for value elements in the Scope view that refer to variables whose values
* aren't accessible to the debugger (potentially due to being optimized out by the JavaScript
* engine), or for JavaScript object accessor properties which have no getter.
*/
valueNotAccessibleToTheDebugger: 'Value is not accessible to the debugger',
/**
*@description A context menu item in the Watch Expressions Sidebar Pane of the Sources panel and Network pane request.
*/
copyValue: 'Copy value',
/**
*@description A context menu item in the Object Properties Section
*/
copyPropertyPath: 'Copy property path',
/**
* @description Text shown when displaying a JavaScript object that has a string property that is
* too large for DevTools to properly display a text editor. This is shown instead of the string in
* question. Should be translated.
*/
stringIsTooLargeToEdit: '<string is too large to edit>',
/**
*@description Text of attribute value when text is too long
*@example {30 MB} PH1
*/
showMoreS: 'Show more ({PH1})',
/**
*@description Text of attribute value when text is too long
*@example {30 MB} PH1
*/
longTextWasTruncatedS: 'long text was truncated ({PH1})',
/**
*@description Text for copying
*/
copy: 'Copy',
/**
* @description A tooltip text that shows when hovering over a button next to value objects,
* which are based on bytes and can be shown in a hexadecimal viewer.
* Clicking on the button will display that object in the memory inspector panel.
*/
revealInMemoryInpector: 'Reveal in Memory Inspector panel',
};
const str_ = i18n.i18n.registerUIStrings('ui/legacy/components/object_ui/ObjectPropertiesSection.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
const EXPANDABLE_MAX_LENGTH = 50;
const EXPANDABLE_MAX_DEPTH = 100;
const parentMap = new WeakMap<SDK.RemoteObject.RemoteObjectProperty, SDK.RemoteObject.RemoteObject|null>();
const objectPropertiesSectionMap = new WeakMap<Element, ObjectPropertiesSection>();
const domPinnedProperties =
JavaScriptMetaData.JavaScriptMetadata.JavaScriptMetadataImpl.domPinnedProperties.DOMPinnedProperties;
export const getObjectPropertiesSectionFrom = (element: Element): ObjectPropertiesSection|undefined => {
return objectPropertiesSectionMap.get(element);
};
export class ObjectPropertiesSection extends UI.TreeOutline.TreeOutlineInShadow {
private readonly object: SDK.RemoteObject.RemoteObject;
editable: boolean;
private readonly objectTreeElementInternal: RootElement;
titleElement: Element;
skipProtoInternal?: boolean;
constructor(
object: SDK.RemoteObject.RemoteObject, title?: string|Element|null, linkifier?: Components.Linkifier.Linkifier,
showOverflow?: boolean) {
super();
this.object = object;
this.editable = true;
if (!showOverflow) {
this.hideOverflow();
}
this.setFocusable(true);
this.setShowSelectionOnKeyboardFocus(true);
this.objectTreeElementInternal = new RootElement(object, linkifier);
this.appendChild(this.objectTreeElementInternal);
if (typeof title === 'string' || !title) {
this.titleElement = this.element.createChild('span');
this.titleElement.textContent = title || '';
} else {
this.titleElement = title;
this.element.appendChild(title);
}
if (this.titleElement instanceof HTMLElement && !this.titleElement.hasAttribute('tabIndex')) {
this.titleElement.tabIndex = -1;
}
objectPropertiesSectionMap.set(this.element, this);
this.registerCSSFiles([objectValueStyles, objectPropertiesSectionStyles]);
this.rootElement().childrenListElement.classList.add('source-code', 'object-properties-section');
}
static defaultObjectPresentation(
object: SDK.RemoteObject.RemoteObject, linkifier?: Components.Linkifier.Linkifier, skipProto?: boolean,
readOnly?: boolean): Element {
const objectPropertiesSection =
ObjectPropertiesSection.defaultObjectPropertiesSection(object, linkifier, skipProto, readOnly);
if (!object.hasChildren) {
return objectPropertiesSection.titleElement;
}
return objectPropertiesSection.element;
}
static defaultObjectPropertiesSection(
object: SDK.RemoteObject.RemoteObject, linkifier?: Components.Linkifier.Linkifier, skipProto?: boolean,
readOnly?: boolean): ObjectPropertiesSection {
const titleElement = document.createElement('span');
titleElement.classList.add('source-code');
const shadowRoot = UI.Utils.createShadowRootWithCoreStyles(titleElement, {
cssFile: [objectValueStyles],
delegatesFocus: undefined,
});
const propertyValue =
ObjectPropertiesSection.createPropertyValue(object, /* wasThrown */ false, /* showPreview */ true);
shadowRoot.appendChild(propertyValue.element);
const objectPropertiesSection = new ObjectPropertiesSection(object, titleElement, linkifier);
objectPropertiesSection.editable = false;
if (skipProto) {
objectPropertiesSection.skipProto();
}
if (readOnly) {
objectPropertiesSection.setEditable(false);
}
return objectPropertiesSection;
}
static assignWebIDLMetadata(
value: SDK.RemoteObject.RemoteObject|null, properties: SDK.RemoteObject.RemoteObjectProperty[]): void {
if (!value) {
return;
}
const isInstance = value.type === 'object' && value.className !== null;
const webIdlType = isInstance ? domPinnedProperties[value.className] : undefined;
if (webIdlType) {
value.webIdl = {info: webIdlType, state: new Map()};
} else {
return;
}
const includedWebIdlTypes = webIdlType.includes?.map(className => domPinnedProperties[className]) ?? [];
const includedWebIdlProps = includedWebIdlTypes.flatMap(webIdlType => Object.entries(webIdlType?.props ?? {}));
const webIdlProps = {...webIdlType.props, ...Object.fromEntries(includedWebIdlProps)};
for (const property of properties) {
const webIdlProperty = webIdlProps[property.name];
if (webIdlProperty) {
property.webIdl = {info: webIdlProperty};
}
}
}
static getPropertyValuesByNames(properties: SDK.RemoteObject.RemoteObjectProperty[]):
Map<string, SDK.RemoteObject.RemoteObject|undefined> {
const map = new Map();
for (const property of properties) {
map.set(property.name, property.value);
}
return map;
}
static compareProperties(
propertyA: SDK.RemoteObject.RemoteObjectProperty, propertyB: SDK.RemoteObject.RemoteObjectProperty): number {
if (!propertyA.synthetic && propertyB.synthetic) {
return 1;
}
if (!propertyB.synthetic && propertyA.synthetic) {
return -1;
}
if (!propertyA.isOwn && propertyB.isOwn) {
return 1;
}
if (!propertyB.isOwn && propertyA.isOwn) {
return -1;
}
if (!propertyA.enumerable && propertyB.enumerable) {
return 1;
}
if (!propertyB.enumerable && propertyA.enumerable) {
return -1;
}
if (propertyA.symbol && !propertyB.symbol) {
return 1;
}
if (propertyB.symbol && !propertyA.symbol) {
return -1;
}
if (propertyA.private && !propertyB.private) {
return 1;
}
if (propertyB.private && !propertyA.private) {
return -1;
}
const a = propertyA.name;
const b = propertyB.name;
if (a.startsWith('_') && !b.startsWith('_')) {
return 1;
}
if (b.startsWith('_') && !a.startsWith('_')) {
return -1;
}
return Platform.StringUtilities.naturalOrderComparator(a, b);
}
static createNameElement(name: string|null, isPrivate?: boolean): Element {
if (name === null) {
return UI.Fragment.html`<span class="name"></span>`;
}
if (/^\s|\s$|^$|\n/.test(name)) {
return UI.Fragment.html`<span class="name">"${name.replace(/\n/g, '\u21B5')}"</span>`;
}
if (isPrivate) {
return UI.Fragment.html`<span class="name">
<span class="private-property-hash">${name[0]}</span>${name.substring(1)}
</span>`;
}
return UI.Fragment.html`<span class="name">${name}</span>`;
}
static valueElementForFunctionDescription(description?: string, includePreview?: boolean, defaultName?: string):
Element {
const valueElement = document.createElement('span');
valueElement.classList.add('object-value-function');
description = description || '';
const text = description.replace(/^function [gs]et /, 'function ')
.replace(/^function [gs]et\(/, 'function\(')
.replace(/^[gs]et /, '');
defaultName = defaultName || '';
// This set of best-effort regular expressions captures common function descriptions.
// Ideally, some parser would provide prefix, arguments, function body text separately.
const asyncMatch = text.match(/^(async\s+function)/);
const isGenerator = text.startsWith('function*');
const isGeneratorShorthand = text.startsWith('*');
const isBasic = !isGenerator && text.startsWith('function');
const isClass = text.startsWith('class ') || text.startsWith('class{');
const firstArrowIndex = text.indexOf('=>');
const isArrow = !asyncMatch && !isGenerator && !isBasic && !isClass && firstArrowIndex > 0;
let textAfterPrefix;
if (isClass) {
textAfterPrefix = text.substring('class'.length);
const classNameMatch = /^[^{\s]+/.exec(textAfterPrefix.trim());
let className: string = defaultName;
if (classNameMatch) {
className = classNameMatch[0].trim() || defaultName;
}
addElements('class', textAfterPrefix, className);
} else if (asyncMatch) {
textAfterPrefix = text.substring(asyncMatch[1].length);
addElements('async \u0192', textAfterPrefix, nameAndArguments(textAfterPrefix));
} else if (isGenerator) {
textAfterPrefix = text.substring('function*'.length);
addElements('\u0192*', textAfterPrefix, nameAndArguments(textAfterPrefix));
} else if (isGeneratorShorthand) {
textAfterPrefix = text.substring('*'.length);
addElements('\u0192*', textAfterPrefix, nameAndArguments(textAfterPrefix));
} else if (isBasic) {
textAfterPrefix = text.substring('function'.length);
addElements('\u0192', textAfterPrefix, nameAndArguments(textAfterPrefix));
} else if (isArrow) {
const maxArrowFunctionCharacterLength = 60;
let abbreviation: string = text;
if (defaultName) {
abbreviation = defaultName + '()';
} else if (text.length > maxArrowFunctionCharacterLength) {
abbreviation = text.substring(0, firstArrowIndex + 2) + ' {…}';
}
addElements('', text, abbreviation);
} else {
addElements('\u0192', text, nameAndArguments(text));
}
UI.Tooltip.Tooltip.install(valueElement, Platform.StringUtilities.trimEndWithMaxLength(description, 500));
return valueElement;
function nameAndArguments(contents: string): string {
const startOfArgumentsIndex = contents.indexOf('(');
const endOfArgumentsMatch = contents.match(/\)\s*{/);
if (startOfArgumentsIndex !== -1 && endOfArgumentsMatch && endOfArgumentsMatch.index !== undefined &&
endOfArgumentsMatch.index > startOfArgumentsIndex) {
const name = contents.substring(0, startOfArgumentsIndex).trim() || defaultName;
const args = contents.substring(startOfArgumentsIndex, endOfArgumentsMatch.index + 1);
return name + args;
}
return defaultName + '()';
}
function addElements(prefix: string, body: string, abbreviation: string): void {
const maxFunctionBodyLength = 200;
if (prefix.length) {
valueElement.createChild('span', 'object-value-function-prefix').textContent = prefix + ' ';
}
if (includePreview) {
UI.UIUtils.createTextChild(
valueElement, Platform.StringUtilities.trimEndWithMaxLength(body.trim(), maxFunctionBodyLength));
} else {
UI.UIUtils.createTextChild(valueElement, abbreviation.replace(/\n/g, ' '));
}
}
}
static createPropertyValueWithCustomSupport(
value: SDK.RemoteObject.RemoteObject, wasThrown: boolean, showPreview: boolean, parentElement?: Element,
linkifier?: Components.Linkifier.Linkifier, isSyntheticProperty?: boolean,
variableName?: string): ObjectPropertyValue {
if (value.customPreview()) {
const result = (new CustomPreviewComponent(value)).element;
result.classList.add('object-properties-section-custom-section');
return new ObjectPropertyValue(result);
}
return ObjectPropertiesSection.createPropertyValue(
value, wasThrown, showPreview, parentElement, linkifier, isSyntheticProperty, variableName);
}
static appendMemoryIcon(element: Element, obj: SDK.RemoteObject.RemoteObject, expression?: string): void {
const isOfMemoryType =
(obj.type === 'object' && obj.subtype &&
LinearMemoryInspector.LinearMemoryInspectorController.ACCEPTED_MEMORY_TYPES.includes(obj.subtype));
if (!isOfMemoryType && !LinearMemoryInspector.LinearMemoryInspectorController.isDWARFMemoryObject(obj)) {
return;
}
const memoryIcon = new IconButton.Icon.Icon();
memoryIcon.data = {
iconName: 'memory',
color: 'var(--icon-default)',
width: '16px',
height: '13px',
};
memoryIcon.onclick = async(event: MouseEvent): Promise<void> => {
event.stopPropagation();
const controller =
LinearMemoryInspector.LinearMemoryInspectorController.LinearMemoryInspectorController.instance();
Host.userMetrics.linearMemoryInspectorRevealedFrom(Host.UserMetrics.LinearMemoryInspectorRevealedFrom.MemoryIcon);
void controller.openInspectorView(obj, /* address */ undefined, expression);
};
const revealText = i18nString(UIStrings.revealInMemoryInpector);
UI.Tooltip.Tooltip.install(memoryIcon, revealText);
UI.ARIAUtils.setLabel(memoryIcon, revealText);
// Directly set property on memory icon, so that the memory icon is also
// styled within the context of code mirror.
memoryIcon.style.setProperty('vertical-align', 'sub');
memoryIcon.style.setProperty('cursor', 'pointer');
element.appendChild(memoryIcon);
}
static createPropertyValue(
value: SDK.RemoteObject.RemoteObject, wasThrown: boolean, showPreview: boolean, parentElement?: Element,
linkifier?: Components.Linkifier.Linkifier, isSyntheticProperty = false,
variableName?: string): ObjectPropertyValue {
let propertyValue;
const type = value.type;
const subtype = value.subtype;
const description = value.description || '';
const className = value.className;
if (type === 'object' && subtype === 'internal#location') {
const rawLocation = value.debuggerModel().createRawLocationByScriptId(
value.value.scriptId, value.value.lineNumber, value.value.columnNumber);
if (rawLocation && linkifier) {
return new ObjectPropertyValue(linkifier.linkifyRawLocation(rawLocation, Platform.DevToolsPath.EmptyUrlString));
}
propertyValue = new ObjectPropertyValue(createUnknownInternalLocationElement());
} else if (type === 'string' && typeof description === 'string') {
propertyValue = createStringElement();
} else if (type === 'object' && subtype === 'trustedtype') {
propertyValue = createTrustedTypeElement();
} else if (type === 'function') {
propertyValue = new ObjectPropertyValue(ObjectPropertiesSection.valueElementForFunctionDescription(description));
} else if (type === 'object' && subtype === 'node' && description) {
propertyValue = new ObjectPropertyValue(createNodeElement());
} else {
const valueElement = document.createElement('span');
valueElement.classList.add('object-value-' + (subtype || type));
if (value.preview && showPreview) {
const previewFormatter = new RemoteObjectPreviewFormatter();
previewFormatter.appendObjectPreview(valueElement, value.preview, false /* isEntry */);
propertyValue = new ObjectPropertyValue(valueElement);
UI.Tooltip.Tooltip.install(propertyValue.element as HTMLElement, description || '');
} else if (description.length > maxRenderableStringLength) {
propertyValue = new ExpandableTextPropertyValue(valueElement, description, EXPANDABLE_MAX_LENGTH);
} else {
propertyValue = new ObjectPropertyValue(valueElement);
propertyValue.element.textContent = description;
UI.Tooltip.Tooltip.install(propertyValue.element as HTMLElement, description);
}
if (!isSyntheticProperty) {
this.appendMemoryIcon(valueElement, value, variableName);
}
}
if (wasThrown) {
const wrapperElement = document.createElement('span');
wrapperElement.classList.add('error');
wrapperElement.classList.add('value');
wrapperElement.appendChild(
i18n.i18n.getFormatLocalizedString(str_, UIStrings.exceptionS, {PH1: propertyValue.element}));
propertyValue.element = wrapperElement;
}
propertyValue.element.classList.add('value');
return propertyValue;
function createUnknownInternalLocationElement(): Element {
const valueElement = document.createElement('span');
valueElement.textContent = '<' + i18nString(UIStrings.unknown) + '>';
UI.Tooltip.Tooltip.install(valueElement, description || '');
return valueElement;
}
function createStringElement(): ObjectPropertyValue {
const valueElement = document.createElement('span');
valueElement.classList.add('object-value-string');
const text = JSON.stringify(description);
let propertyValue;
if (description.length > maxRenderableStringLength) {
propertyValue = new ExpandableTextPropertyValue(valueElement, text, EXPANDABLE_MAX_LENGTH);
} else {
UI.UIUtils.createTextChild(valueElement, text);
propertyValue = new ObjectPropertyValue(valueElement);
UI.Tooltip.Tooltip.install(valueElement, description);
}
return propertyValue;
}
function createTrustedTypeElement(): ObjectPropertyValue {
const valueElement = document.createElement('span');
valueElement.classList.add('object-value-trustedtype');
const text = `${className} "${description}"`;
let propertyValue;
if (text.length > maxRenderableStringLength) {
propertyValue = new ExpandableTextPropertyValue(valueElement, text, EXPANDABLE_MAX_LENGTH);
} else {
const contentString = createStringElement();
UI.UIUtils.createTextChild(valueElement, `${className} `);
valueElement.appendChild(contentString.element);
propertyValue = new ObjectPropertyValue(valueElement);
UI.Tooltip.Tooltip.install(valueElement, text);
}
return propertyValue;
}
function createNodeElement(): Element {
const valueElement = document.createElement('span');
valueElement.classList.add('object-value-node');
createSpansForNodeTitle(valueElement, (description as string));
valueElement.addEventListener('click', event => {
void Common.Revealer.reveal(value);
event.consume(true);
}, false);
valueElement.addEventListener(
'mousemove', () => SDK.OverlayModel.OverlayModel.highlightObjectAsDOMNode(value), false);
valueElement.addEventListener('mouseleave', () => SDK.OverlayModel.OverlayModel.hideDOMNodeHighlight(), false);
return valueElement;
}
}
static formatObjectAsFunction(
func: SDK.RemoteObject.RemoteObject, element: Element, linkify: boolean,
includePreview?: boolean): Promise<void> {
return func.debuggerModel().functionDetailsPromise(func).then(didGetDetails);
function didGetDetails(response: SDK.DebuggerModel.FunctionDetails|null): void {
if (linkify && response && response.location) {
element.classList.add('linkified');
element.addEventListener('click', () => {
void Common.Revealer.reveal(response.location);
return false;
});
}
// The includePreview flag is false for formats such as console.dir().
let defaultName: string|('' | 'anonymous') = includePreview ? '' : 'anonymous';
if (response && response.functionName) {
defaultName = response.functionName;
}
const valueElement =
ObjectPropertiesSection.valueElementForFunctionDescription(func.description, includePreview, defaultName);
element.appendChild(valueElement);
}
}
static isDisplayableProperty(
property: SDK.RemoteObject.RemoteObjectProperty,
parentProperty?: SDK.RemoteObject.RemoteObjectProperty): boolean {
if (!parentProperty || !parentProperty.synthetic) {
return true;
}
const name = property.name;
const useless = (parentProperty.name === '[[Entries]]' && (name === 'length' || name === '__proto__'));
return !useless;
}
skipProto(): void {
this.skipProtoInternal = true;
}
expand(): void {
this.objectTreeElementInternal.expand();
}
setEditable(value: boolean): void {
this.editable = value;
}
objectTreeElement(): UI.TreeOutline.TreeElement {
return this.objectTreeElementInternal;
}
enableContextMenu(): void {
this.element.addEventListener('contextmenu', this.contextMenuEventFired.bind(this), false);
}
private contextMenuEventFired(event: Event): void {
const contextMenu = new UI.ContextMenu.ContextMenu(event);
contextMenu.appendApplicableItems(this.object);
if (this.object instanceof SDK.RemoteObject.LocalJSONObject) {
contextMenu.viewSection().appendItem(
i18nString(UIStrings.expandRecursively),
this.objectTreeElementInternal.expandRecursively.bind(this.objectTreeElementInternal, EXPANDABLE_MAX_DEPTH));
contextMenu.viewSection().appendItem(
i18nString(UIStrings.collapseChildren),
this.objectTreeElementInternal.collapseChildren.bind(this.objectTreeElementInternal));
}
void contextMenu.show();
}
titleLessMode(): void {
this.objectTreeElementInternal.listItemElement.classList.add('hidden');
this.objectTreeElementInternal.childrenListElement.classList.add('title-less-mode');
this.objectTreeElementInternal.expand();
}
}
/** @const */
const ARRAY_LOAD_THRESHOLD = 100;
let maxRenderableStringLength = 10000;
export function setMaxRenderableStringLength(value: number): void {
maxRenderableStringLength = value;
}
export function getMaxRenderableStringLength(): number {
return maxRenderableStringLength;
}
export class ObjectPropertiesSectionsTreeOutline extends UI.TreeOutline.TreeOutlineInShadow {
private readonly editable: boolean;
constructor(options?: TreeOutlineOptions|null) {
super();
this.registerCSSFiles([objectValueStyles, objectPropertiesSectionStyles]);
this.editable = !(options && options.readOnly);
this.contentElement.classList.add('source-code');
this.contentElement.classList.add('object-properties-section');
this.hideOverflow();
}
}
export const enum ObjectPropertiesMode {
All = 0, // All properties, including prototype properties
OwnAndInternalAndInherited = 1, // Own, internal, and inherited properties
}
export class RootElement extends UI.TreeOutline.TreeElement {
private readonly object: SDK.RemoteObject.RemoteObject;
private readonly linkifier: Components.Linkifier.Linkifier|undefined;
private readonly emptyPlaceholder: string|null|undefined;
private readonly propertiesMode: ObjectPropertiesMode;
private readonly extraProperties: SDK.RemoteObject.RemoteObjectProperty[];
private readonly targetObject: SDK.RemoteObject.RemoteObject|undefined;
override toggleOnClick: boolean;
constructor(
object: SDK.RemoteObject.RemoteObject, linkifier?: Components.Linkifier.Linkifier, emptyPlaceholder?: string|null,
propertiesMode: ObjectPropertiesMode = ObjectPropertiesMode.OwnAndInternalAndInherited,
extraProperties: SDK.RemoteObject.RemoteObjectProperty[] = [],
targetObject: SDK.RemoteObject.RemoteObject = object) {
const contentElement = document.createElement('slot');
super(contentElement);
this.object = object;
this.linkifier = linkifier;
this.emptyPlaceholder = emptyPlaceholder;
this.propertiesMode = propertiesMode;
this.extraProperties = extraProperties;
this.targetObject = targetObject;
this.setExpandable(true);
this.selectable = true;
this.toggleOnClick = true;
this.listItemElement.classList.add('object-properties-section-root-element');
this.listItemElement.addEventListener('contextmenu', this.onContextMenu.bind(this), false);
}
override onexpand(): void {
if (this.treeOutline) {
this.treeOutline.element.classList.add('expanded');
}
}
override oncollapse(): void {
if (this.treeOutline) {
this.treeOutline.element.classList.remove('expanded');
}
}
override ondblclick(_e: Event): boolean {
return true;
}
private onContextMenu(event: Event): void {
const contextMenu = new UI.ContextMenu.ContextMenu(event);
contextMenu.appendApplicableItems(this.object);
if (this.object instanceof SDK.RemoteObject.LocalJSONObject) {
const {value} = this.object;
const propertyValue = typeof value === 'object' ? JSON.stringify(value, null, 2) : value;
const copyValueHandler = (): void => {
Host.userMetrics.actionTaken(Host.UserMetrics.Action.NetworkPanelCopyValue);
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText((propertyValue as string | undefined));
};
contextMenu.clipboardSection().appendItem(i18nString(UIStrings.copyValue), copyValueHandler);
}
contextMenu.viewSection().appendItem(
i18nString(UIStrings.expandRecursively), this.expandRecursively.bind(this, EXPANDABLE_MAX_DEPTH));
contextMenu.viewSection().appendItem(i18nString(UIStrings.collapseChildren), this.collapseChildren.bind(this));
void contextMenu.show();
}
override async onpopulate(): Promise<void> {
const treeOutline = (this.treeOutline as ObjectPropertiesSection | null);
const skipProto = treeOutline ? Boolean(treeOutline.skipProtoInternal) : false;
return ObjectPropertyTreeElement.populate(
this, this.object, skipProto, false, this.linkifier, this.emptyPlaceholder, this.propertiesMode,
this.extraProperties, this.targetObject);
}
}
// Number of initially visible children in an ObjectPropertyTreeElement.
// Remaining children are shown as soon as requested via a show more properties button.
export const InitialVisibleChildrenLimit = 200;
export class ObjectPropertyTreeElement extends UI.TreeOutline.TreeElement {
property: SDK.RemoteObject.RemoteObjectProperty;
override toggleOnClick: boolean;
private highlightChanges: UI.UIUtils.HighlightChange[];
private linkifier: Components.Linkifier.Linkifier|undefined;
private readonly maxNumPropertiesToShow: number;
nameElement!: HTMLElement;
valueElement!: HTMLElement;
private rowContainer!: HTMLElement;
readOnly!: boolean;
private prompt!: ObjectPropertyPrompt|undefined;
private editableDiv!: HTMLElement;
propertyValue?: ObjectPropertyValue;
expandedValueElement?: Element|null;
constructor(property: SDK.RemoteObject.RemoteObjectProperty, linkifier?: Components.Linkifier.Linkifier) {
// Pass an empty title, the title gets made later in onattach.
super();
this.property = property;
this.toggleOnClick = true;
this.highlightChanges = [];
this.linkifier = linkifier;
this.maxNumPropertiesToShow = InitialVisibleChildrenLimit;
this.listItemElement.addEventListener('contextmenu', this.contextMenuFired.bind(this), false);
this.listItemElement.dataset.objectPropertyNameForTest = property.name;
this.setExpandRecursively(property.name !== '[[Prototype]]');
}
static async populate(
treeElement: UI.TreeOutline.TreeElement, value: SDK.RemoteObject.RemoteObject, skipProto: boolean,
skipGettersAndSetters: boolean, linkifier?: Components.Linkifier.Linkifier, emptyPlaceholder?: string|null,
propertiesMode: ObjectPropertiesMode = ObjectPropertiesMode.OwnAndInternalAndInherited,
extraProperties?: SDK.RemoteObject.RemoteObjectProperty[],
targetValue?: SDK.RemoteObject.RemoteObject): Promise<void> {
if (value.arrayLength() > ARRAY_LOAD_THRESHOLD) {
treeElement.removeChildren();
void ArrayGroupingTreeElement.populateArray(treeElement, value, 0, value.arrayLength() - 1, linkifier);
return;
}
let properties, internalProperties = null;
switch (propertiesMode) {
case ObjectPropertiesMode.All:
({properties} = await value.getAllProperties(false /* accessorPropertiesOnly */, true /* generatePreview */));
break;
case ObjectPropertiesMode.OwnAndInternalAndInherited:
({properties, internalProperties} =
await SDK.RemoteObject.RemoteObject.loadFromObjectPerProto(value, true /* generatePreview */));
break;
}
treeElement.removeChildren();
if (!properties) {
return;
}
if (extraProperties !== undefined) {
properties.push(...extraProperties);
}
ObjectPropertyTreeElement.populateWithProperties(
treeElement, properties, internalProperties, skipProto, skipGettersAndSetters, targetValue || value, linkifier,
emptyPlaceholder);
}
static populateWithProperties(
treeNode: UI.TreeOutline.TreeElement, properties: SDK.RemoteObject.RemoteObjectProperty[],
internalProperties: SDK.RemoteObject.RemoteObjectProperty[]|null, skipProto: boolean,
skipGettersAndSetters: boolean, value: SDK.RemoteObject.RemoteObject|null,
linkifier?: Components.Linkifier.Linkifier, emptyPlaceholder?: string|null): void {
ObjectPropertiesSection.assignWebIDLMetadata(value, properties);
const names = ObjectPropertiesSection.getPropertyValuesByNames(properties);
if (value?.webIdl) {
const parentRules = value.webIdl.info.rules;
if (parentRules) {
for (const {when: name, is: expected} of parentRules) {
if (names.get(name)?.value === expected) {
value.webIdl.state.set(name, expected);
}
}
}
for (const property of properties) {
if (property.webIdl) {
const parentState = value.webIdl.state;
const propertyRules = property.webIdl.info.rules;
if (!parentRules && !propertyRules) {
property.webIdl.applicable = true;
} else {
property.webIdl.applicable =
!propertyRules || propertyRules?.some(rule => parentState.get(rule.when) === rule.is);
}
}
}
}
properties.sort(ObjectPropertiesSection.compareProperties);
internalProperties = internalProperties || [];
const entriesProperty = internalProperties.find(property => property.name === '[[Entries]]');
if (entriesProperty) {
parentMap.set(entriesProperty, value);
const treeElement = new ObjectPropertyTreeElement(entriesProperty, linkifier);
treeElement.setExpandable(true);
treeElement.expand();
treeNode.appendChild(treeElement);
}
const tailProperties = [];
for (let i = 0; i < properties.length; ++i) {
const property = properties[i];
parentMap.set(property, value);
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (!ObjectPropertiesSection.isDisplayableProperty(property, (treeNode as any).property)) {
continue;
}
if (property.isOwn && !skipGettersAndSetters) {
if (property.getter) {
const getterProperty =
new SDK.RemoteObject.RemoteObjectProperty('get ' + property.name, property.getter, false);
parentMap.set(getterProperty, value);
tailProperties.push(getterProperty);
}
if (property.setter) {
const setterProperty =
new SDK.RemoteObject.RemoteObjectProperty('set ' + property.name, property.setter, false);
parentMap.set(setterProperty, value);
tailProperties.push(setterProperty);
}
}
const canShowProperty = property.getter || !property.isAccessorProperty();
if (canShowProperty) {
const element = new ObjectPropertyTreeElement(property, linkifier);
if (property.name === 'memories' && property.value?.className === 'Memories') {
element.updateExpandable();
if (element.isExpandable()) {
element.expand();
}
}
treeNode.appendChild(element);
}
}
for (let i = 0; i < tailProperties.length; ++i) {
treeNode.appendChild(new ObjectPropertyTreeElement(tailProperties[i], linkifier));
}
for (const property of internalProperties) {
parentMap.set(property, value);
const treeElement = new ObjectPropertyTreeElement(property, linkifier);
if (property.name === '[[Entries]]') {
continue;
}
if (property.name === '[[Prototype]]' && skipProto) {
continue;
}
treeNode.appendChild(treeElement);
}
ObjectPropertyTreeElement.appendEmptyPlaceholderIfNeeded(treeNode, emptyPlaceholder);
}
private static appendEmptyPlaceholderIfNeeded(treeNode: UI.TreeOutline.TreeElement, emptyPlaceholder?: string|null):
void {
if (treeNode.childCount()) {
return;
}
const title = document.createElement('div');
title.classList.add('gray-info-message');
title.textContent = emptyPlaceholder || i18nString(UIStrings.noProperties);
const infoElement = new UI.TreeOutline.TreeElement(title);
treeNode.appendChild(infoElement);
}
static createRemoteObjectAccessorPropertySpan(
object: SDK.RemoteObject.RemoteObject|null, propertyPath: string[],
callback: (arg0: SDK.RemoteObject.CallFunctionResult) => void): HTMLElement {
const rootElement = document.createElement('span');
const element = rootElement.createChild('span');
element.textContent = i18nString(UIStrings.dots);
if (!object) {
return rootElement;
}
element.classList.add('object-value-calculate-value-button');
UI.Tooltip.Tooltip.install(element, i18nString(UIStrings.invokePropertyGetter));
element.addEventListener('click', onInvokeGetterClick, false);
function onInvokeGetterClick(event: Event): void {
event.consume();
if (object) {
// The definition of callFunction expects an unknown, and setting to `any` causes Closure to fail.
// However, leaving this as unknown also causes TypeScript to fail, so for now we leave this as unchecked.
// @ts-ignore TODO(crbug.com/1011811): Fix after Closure is removed.
void object.callFunction(invokeGetter, [{value: JSON.stringify(propertyPath)}]).then(callback);
}
}
function invokeGetter(this: Object, arrayStr: string): Object {
let result: Object = this;
const properties = JSON.parse(arrayStr);
for (let i = 0, n = properties.length; i < n; ++i) {
// @ts-ignore callFunction expects this to be a generic Object, so while this works we can't be more specific on types.
result = result[properties[i]];
}
return result;
}
return rootElement;
}
setSearchRegex(regex: RegExp, additionalCssClassName?: string): boolean {
let cssClasses = UI.UIUtils.highlightedSearchResultClassName;
if (additionalCssClassName) {
cssClasses += ' ' + additionalCssClassName;
}
this.revertHighlightChanges();
this.applySearch(regex, this.nameElement, cssClasses);
if (this.property.value) {
const valueType = this.property.value.type;
if (valueType !== 'object') {
this.applySearch(regex, this.valueElement, cssClasses);
}
}
return Boolean(this.highlightChanges.length);
}
private applySearch(regex: RegExp, element: Element, cssClassName: string): void {
const ranges = [];
const content = element.textContent || '';
regex.lastIndex = 0;
let match = regex.exec(content);
while (match) {
ranges.push(new TextUtils.TextRange.SourceRange(match.index, match[0].length));
match = regex.exec(content);
}
if (ranges.length) {
UI.UIUtils.highlightRangesWithStyleClass(element, ranges, cssClassName, this.highlightChanges);
}
}
private showAllPropertiesElementSelected(element: UI.TreeOutline.TreeElement): boolean {
this.removeChild(element);
this.children().forEach(x => {
x.hidden = false;
});
return false;
}
private createShowAllPropertiesButton(): void {
const element = document.createElement('div');
element.classList.add('object-value-calculate-value-button');
element.textContent = i18nString(UIStrings.dots);
UI.Tooltip.Tooltip.install(element, i18nString(UIStrings.showAllD, {PH1: this.childCount()}));
const children = this.children();
for (let i = this.maxNumPropertiesToShow; i < this.childCount(); ++i) {
children[i].hidden = true;
}
const showAllPropertiesButton = new UI.TreeOutline.TreeElement(element);
showAllPropertiesButton.onselect = this.showAllPropertiesElementSelected.bind(this, showAllPropertiesButton);