This repository was archived by the owner on Jul 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathrules.js
More file actions
2622 lines (2317 loc) · 81.7 KB
/
rules.js
File metadata and controls
2622 lines (2317 loc) · 81.7 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
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const flags = require("resource://devtools/shared/flags.js");
const { l10n } = require("resource://devtools/shared/inspector/css-logic.js");
const {
style: { ELEMENT_STYLE },
} = require("resource://devtools/shared/constants.js");
const {
PSEUDO_CLASSES,
} = require("resource://devtools/shared/css/constants.js");
const OutputParser = require("resource://devtools/client/shared/output-parser.js");
const { PrefObserver } = require("resource://devtools/client/shared/prefs.js");
const ElementStyle = require("resource://devtools/client/inspector/rules/models/element-style.js");
const RuleEditor = require("resource://devtools/client/inspector/rules/views/rule-editor.js");
const RegisteredPropertyEditor = require("resource://devtools/client/inspector/rules/views/registered-property-editor.js");
const TooltipsOverlay = require("resource://devtools/client/inspector/shared/tooltips-overlay.js");
const {
createChild,
promiseWarn,
} = require("resource://devtools/client/inspector/shared/utils.js");
const { debounce } = require("resource://devtools/shared/debounce.js");
const EventEmitter = require("resource://devtools/shared/event-emitter.js");
loader.lazyRequireGetter(
this,
["flashElementOn", "flashElementOff"],
"resource://devtools/client/inspector/markup/utils.js",
true
);
loader.lazyRequireGetter(
this,
"ClassListPreviewer",
"resource://devtools/client/inspector/rules/views/class-list-previewer.js"
);
loader.lazyRequireGetter(
this,
["getNodeInfo", "getNodeCompatibilityInfo", "getRuleFromNode"],
"resource://devtools/client/inspector/rules/utils/utils.js",
true
);
loader.lazyRequireGetter(
this,
"StyleInspectorMenu",
"resource://devtools/client/inspector/shared/style-inspector-menu.js"
);
loader.lazyRequireGetter(
this,
"AutocompletePopup",
"resource://devtools/client/shared/autocomplete-popup.js"
);
loader.lazyRequireGetter(
this,
"KeyShortcuts",
"resource://devtools/client/shared/key-shortcuts.js"
);
loader.lazyRequireGetter(
this,
"clipboardHelper",
"resource://devtools/shared/platform/clipboard.js"
);
const HTML_NS = "http://www.w3.org/1999/xhtml";
const PREF_UA_STYLES = "devtools.inspector.showUserAgentStyles";
const PREF_DEFAULT_COLOR_UNIT = "devtools.defaultColorUnit";
const PREF_DRAGGABLE = "devtools.inspector.draggable_properties";
const PREF_INPLACE_EDITOR_FOCUS_NEXT_ON_ENTER =
"devtools.inspector.rule-view.focusNextOnEnter";
const FILTER_CHANGED_TIMEOUT = 150;
// Removes the flash-out class from an element after 1 second.
const PROPERTY_FLASHING_DURATION = 1000;
// This is used to parse user input when filtering.
const FILTER_PROP_RE = /\s*([^:\s]*)\s*:\s*(.*?)\s*;?$/;
// This is used to parse the filter search value to see if the filter
// should be strict or not
const FILTER_STRICT_RE = /\s*`(.*?)`\s*$/;
const RULE_VIEW_HEADER_CLASSNAME = "ruleview-header";
const PSEUDO_ELEMENTS_CONTAINER_ID = "pseudo-elements-container";
const REGISTERED_PROPERTIES_CONTAINER_ID = "registered-properties-container";
/**
* Our model looks like this:
*
* ElementStyle:
* Responsible for keeping track of which properties are overridden.
* Maintains a list of Rule objects that apply to the element.
* Rule:
* Manages a single style declaration or rule.
* Responsible for applying changes to the properties in a rule.
* Maintains a list of TextProperty objects.
* TextProperty:
* Manages a single property from the authoredText attribute of the
* relevant declaration.
* Maintains a list of computed properties that come from this
* property declaration.
* Changes to the TextProperty are sent to its related Rule for
* application.
*
* View hierarchy mostly follows the model hierarchy.
*
* CssRuleView:
* Owns an ElementStyle and creates a list of RuleEditors for its
* Rules.
* RuleEditor:
* Owns a Rule object and creates a list of TextPropertyEditors
* for its TextProperties.
* Manages creation of new text properties.
* TextPropertyEditor:
* Owns a TextProperty object.
* Manages changes to the TextProperty.
* Can be expanded to display computed properties.
* Can mark a property disabled or enabled.
*/
/**
* CssRuleView is a view of the style rules and declarations that
* apply to a given element. After construction, the 'element'
* property will be available with the user interface.
*
* @param {Inspector} inspector
* Inspector toolbox panel
* @param {Document} document
* The document that will contain the rule view.
* @param {Object} store
* The CSS rule view can use this object to store metadata
* that might outlast the rule view, particularly the current
* set of disabled properties.
*/
function CssRuleView(inspector, document, store) {
EventEmitter.decorate(this);
this.inspector = inspector;
this.cssProperties = inspector.cssProperties;
this.styleDocument = document;
this.styleWindow = this.styleDocument.defaultView;
this.store = store || {};
// Allow tests to override debouncing behavior, as this can cause intermittents.
this.debounce = debounce;
// Variable used to stop the propagation of mouse events to children
// when we are updating a value by dragging the mouse and we then release it
this.childHasDragged = false;
this._outputParser = new OutputParser(document, this.cssProperties);
this._abortController = new this.styleWindow.AbortController();
this._onAddRule = this._onAddRule.bind(this);
this._onContextMenu = this._onContextMenu.bind(this);
this._onCopy = this._onCopy.bind(this);
this._onFilterStyles = this._onFilterStyles.bind(this);
this._onClearSearch = this._onClearSearch.bind(this);
this._onTogglePseudoClassPanel = this._onTogglePseudoClassPanel.bind(this);
this._onTogglePseudoClass = this._onTogglePseudoClass.bind(this);
this._onToggleClassPanel = this._onToggleClassPanel.bind(this);
this._onToggleLightColorSchemeSimulation =
this._onToggleLightColorSchemeSimulation.bind(this);
this._onToggleDarkColorSchemeSimulation =
this._onToggleDarkColorSchemeSimulation.bind(this);
this._onTogglePrintSimulation = this._onTogglePrintSimulation.bind(this);
this.highlightElementRule = this.highlightElementRule.bind(this);
this.highlightProperty = this.highlightProperty.bind(this);
this.refreshPanel = this.refreshPanel.bind(this);
const doc = this.styleDocument;
// Delegate bulk handling of events happening within the DOM tree of the Rules view
// to this.handleEvent(). Listening on the capture phase of the event bubbling to be
// able to stop event propagation on a case-by-case basis and prevent event target
// ancestor nodes from handling them.
this.styleDocument.addEventListener("click", this, { capture: true });
this.element = doc.getElementById("ruleview-container-focusable");
this.addRuleButton = doc.getElementById("ruleview-add-rule-button");
this.searchField = doc.getElementById("ruleview-searchbox");
this.searchClearButton = doc.getElementById("ruleview-searchinput-clear");
this.pseudoClassPanel = doc.getElementById("pseudo-class-panel");
this.pseudoClassToggle = doc.getElementById("pseudo-class-panel-toggle");
this.classPanel = doc.getElementById("ruleview-class-panel");
this.classToggle = doc.getElementById("class-panel-toggle");
this.colorSchemeLightSimulationButton = doc.getElementById(
"color-scheme-simulation-light-toggle"
);
this.colorSchemeDarkSimulationButton = doc.getElementById(
"color-scheme-simulation-dark-toggle"
);
this.printSimulationButton = doc.getElementById("print-simulation-toggle");
this._initSimulationFeatures();
this.searchClearButton.hidden = true;
this.onHighlighterShown = data =>
this.handleHighlighterEvent("highlighter-shown", data);
this.onHighlighterHidden = data =>
this.handleHighlighterEvent("highlighter-hidden", data);
this.inspector.highlighters.on("highlighter-shown", this.onHighlighterShown);
this.inspector.highlighters.on(
"highlighter-hidden",
this.onHighlighterHidden
);
this.shortcuts = new KeyShortcuts({ window: this.styleWindow });
this._onShortcut = this._onShortcut.bind(this);
this.shortcuts.on("Escape", event => this._onShortcut("Escape", event));
this.shortcuts.on("Return", event => this._onShortcut("Return", event));
this.shortcuts.on("Space", event => this._onShortcut("Space", event));
this.shortcuts.on("CmdOrCtrl+F", event =>
this._onShortcut("CmdOrCtrl+F", event)
);
this.element.addEventListener("copy", this._onCopy);
this.element.addEventListener("contextmenu", this._onContextMenu);
this.addRuleButton.addEventListener("click", this._onAddRule);
this.searchField.addEventListener("input", this._onFilterStyles);
this.searchClearButton.addEventListener("click", this._onClearSearch);
this.pseudoClassToggle.addEventListener(
"click",
this._onTogglePseudoClassPanel
);
this.classToggle.addEventListener("click", this._onToggleClassPanel);
// The "change" event bubbles up from checkbox inputs nested within the panel container.
this.pseudoClassPanel.addEventListener("change", this._onTogglePseudoClass);
if (flags.testing) {
// In tests, we start listening immediately to avoid having to simulate a mousemove.
this.highlighters.addToView(this);
} else {
this.element.addEventListener(
"mousemove",
() => {
this.highlighters.addToView(this);
},
{ once: true }
);
}
this._handlePrefChange = this._handlePrefChange.bind(this);
this._handleUAStylePrefChange = this._handleUAStylePrefChange.bind(this);
this._handleDefaultColorUnitPrefChange =
this._handleDefaultColorUnitPrefChange.bind(this);
this._handleDraggablePrefChange = this._handleDraggablePrefChange.bind(this);
this._handleInplaceEditorFocusNextOnEnterPrefChange =
this._handleInplaceEditorFocusNextOnEnterPrefChange.bind(this);
this._prefObserver = new PrefObserver("devtools.");
this._prefObserver.on(PREF_UA_STYLES, this._handleUAStylePrefChange);
this._prefObserver.on(
PREF_DEFAULT_COLOR_UNIT,
this._handleDefaultColorUnitPrefChange
);
this._prefObserver.on(PREF_DRAGGABLE, this._handleDraggablePrefChange);
// Initialize value of this.draggablePropertiesEnabled
this._handleDraggablePrefChange();
this._prefObserver.on(
PREF_INPLACE_EDITOR_FOCUS_NEXT_ON_ENTER,
this._handleInplaceEditorFocusNextOnEnterPrefChange
);
// Initialize value of this.inplaceEditorFocusNextOnEnter
this._handleInplaceEditorFocusNextOnEnterPrefChange();
this.pseudoClassCheckboxes = this._createPseudoClassCheckboxes();
this.showUserAgentStyles = Services.prefs.getBoolPref(PREF_UA_STYLES);
// Add the tooltips and highlighters to the view
this.tooltips = new TooltipsOverlay(this);
this.cssRegisteredPropertiesByTarget = new Map();
}
CssRuleView.prototype = {
// The element that we're inspecting.
_viewedElement: null,
// Used for cancelling timeouts in the style filter.
_filterChangedTimeout: null,
// Empty, unconnected element of the same type as this node, used
// to figure out how shorthand properties will be parsed.
_dummyElement: null,
get popup() {
if (!this._popup) {
// The popup will be attached to the toolbox document.
this._popup = new AutocompletePopup(this.inspector.toolbox.doc, {
autoSelect: true,
});
}
return this._popup;
},
get classListPreviewer() {
if (!this._classListPreviewer) {
this._classListPreviewer = new ClassListPreviewer(
this.inspector,
this.classPanel
);
}
return this._classListPreviewer;
},
get contextMenu() {
if (!this._contextMenu) {
this._contextMenu = new StyleInspectorMenu(this, { isRuleView: true });
}
return this._contextMenu;
},
// Get the dummy elemenet.
get dummyElement() {
return this._dummyElement;
},
// Get the highlighters overlay from the Inspector.
get highlighters() {
if (!this._highlighters) {
// highlighters is a lazy getter in the inspector.
this._highlighters = this.inspector.highlighters;
}
return this._highlighters;
},
// Get the filter search value.
get searchValue() {
return this.searchField.value.toLowerCase();
},
get rules() {
return this._elementStyle ? this._elementStyle.rules : [];
},
get currentTarget() {
return this.inspector.toolbox.target;
},
/**
* Highlight/unhighlight all the nodes that match a given rule's selector
* inside the document of the current selected node.
* Only one selector can be highlighted at a time, so calling the method a
* second time with a different rule will first unhighlight the previously
* highlighted nodes.
* Calling the method a second time with the same rule will just
* unhighlight the highlighted nodes.
*
* @param {Rule} rule
* @param {String} selector
* Elements matching this selector will be highlighted on the page.
* @param {Boolean} highlightFromRulesSelector
*/
async toggleSelectorHighlighter(
rule,
selector,
highlightFromRulesSelector = true
) {
if (this.isSelectorHighlighted(selector)) {
await this.inspector.highlighters.hideHighlighterType(
this.inspector.highlighters.TYPES.SELECTOR
);
} else {
const options = {
hideInfoBar: true,
hideGuides: true,
// we still pass the selector (which can be the StyleRuleFront#computedSelector)
// even if highlightFromRulesSelector is set to true, as it's how we keep track
// of which selector is highlighted.
selector,
};
if (highlightFromRulesSelector) {
options.ruleActorID = rule.domRule.actorID;
}
await this.inspector.highlighters.showHighlighterTypeForNode(
this.inspector.highlighters.TYPES.SELECTOR,
this.inspector.selection.nodeFront,
options
);
}
},
isPanelVisible() {
return (
this.inspector.toolbox &&
this.inspector.sidebar &&
this.inspector.toolbox.currentToolId === "inspector" &&
(this.inspector.sidebar.getCurrentTabID() == "ruleview" ||
this.inspector.is3PaneModeEnabled)
);
},
/**
* Check whether a SelectorHighlighter is active for the given selector text.
*
* @param {String} selector
* @return {Boolean}
*/
isSelectorHighlighted(selector) {
const options = this.inspector.highlighters.getOptionsForActiveHighlighter(
this.inspector.highlighters.TYPES.SELECTOR
);
return options?.selector === selector;
},
/**
* Delegate handler for events happening within the DOM tree of the Rules view.
* Itself delegates to specific handlers by event type.
*
* Use this instead of attaching specific event handlers when:
* - there are many elements with the same event handler (eases memory pressure)
* - you want to avoid having to remove event handlers manually
* - elements are added/removed from the DOM tree arbitrarily over time
*
* @param {MouseEvent|UIEvent} event
*/
handleEvent(event) {
if (this.childHasDragged) {
this.childHasDragged = false;
event.stopPropagation();
return;
}
switch (event.type) {
case "click":
this.handleClickEvent(event);
break;
default:
}
},
/**
* Delegate handler for click events happening within the DOM tree of the Rules view.
* Stop propagation of click event wrapping a CSS rule or CSS declaration to avoid
* triggering the prompt to add a new CSS declaration or to edit the existing one.
*
* @param {MouseEvent} event
*/
async handleClickEvent(event) {
const target = event.target;
// Handle click on the icon next to a CSS selector.
if (target.classList.contains("js-toggle-selector-highlighter")) {
event.stopPropagation();
let selector = target.dataset.computedSelector;
const highlightFromRulesSelector =
!!selector && !target.dataset.isUniqueSelector;
// dataset.computedSelector will be initially empty for inline styles (inherited or not)
// Rules associated with a regular selector should have this data-attribute
// set in devtools/client/inspector/rules/views/rule-editor.js
const rule = getRuleFromNode(target, this._elementStyle);
if (selector === "") {
try {
if (rule.inherited) {
// This is an inline style from an inherited rule. Need to resolve the
// unique selector from the node which this rule is inherited from.
selector = await rule.inherited.getUniqueSelector();
} else {
// This is an inline style from the current node.
selector =
await this.inspector.selection.nodeFront.getUniqueSelector();
}
// Now that the selector was computed, we can store it for subsequent usage.
target.dataset.computedSelector = selector;
target.dataset.isUniqueSelector = true;
} finally {
// Could not resolve a unique selector for the inline style.
}
}
this.toggleSelectorHighlighter(
rule,
selector,
highlightFromRulesSelector
);
}
// Handle click on swatches next to flex and inline-flex CSS properties
if (target.classList.contains("js-toggle-flexbox-highlighter")) {
event.stopPropagation();
this.inspector.highlighters.toggleFlexboxHighlighter(
this.inspector.selection.nodeFront,
"rule"
);
}
// Handle click on swatches next to grid CSS properties
if (target.classList.contains("js-toggle-grid-highlighter")) {
event.stopPropagation();
this.inspector.highlighters.toggleGridHighlighter(
this.inspector.selection.nodeFront,
"rule"
);
}
},
/**
* Delegate handler for highlighter events.
*
* This is the place to observe for highlighter events, check the highlighter type and
* event name, then react to specific events, for example by modifying the DOM.
*
* @param {String} eventName
* Highlighter event name. One of: "highlighter-hidden", "highlighter-shown"
* @param {Object} data
* Object with data associated with the highlighter event.
*/
handleHighlighterEvent(eventName, data) {
switch (data.type) {
// Toggle the "highlighted" class on selector icons in the Rules view when
// the SelectorHighlighter is shown/hidden for a certain CSS selector.
case this.inspector.highlighters.TYPES.SELECTOR:
{
const selector = data?.options?.selector;
if (!selector) {
return;
}
const query = `.js-toggle-selector-highlighter[data-computed-selector='${selector}']`;
for (const node of this.styleDocument.querySelectorAll(query)) {
const isHighlighterDisplayed = eventName == "highlighter-shown";
node.classList.toggle("highlighted", isHighlighterDisplayed);
node.setAttribute("aria-pressed", isHighlighterDisplayed);
}
}
break;
// Toggle the "aria-pressed" attribute on swatches next to flex and inline-flex CSS properties
// when the FlexboxHighlighter is shown/hidden for the currently selected node.
case this.inspector.highlighters.TYPES.FLEXBOX:
{
const query = ".js-toggle-flexbox-highlighter";
for (const node of this.styleDocument.querySelectorAll(query)) {
node.setAttribute("aria-pressed", eventName == "highlighter-shown");
}
}
break;
// Toggle the "aria-pressed" class on swatches next to grid CSS properties
// when the GridHighlighter is shown/hidden for the currently selected node.
case this.inspector.highlighters.TYPES.GRID:
{
const query = ".js-toggle-grid-highlighter";
for (const node of this.styleDocument.querySelectorAll(query)) {
// From the Layout panel, we can toggle grid highlighters for nodes which are
// not currently selected. The Rules view shows `display: grid` declarations
// only for the selected node. Avoid mistakenly marking them as "active".
if (data.nodeFront === this.inspector.selection.nodeFront) {
node.setAttribute(
"aria-pressed",
eventName == "highlighter-shown"
);
}
// When the max limit of grid highlighters is reached (default 3),
// mark inactive grid swatches as disabled.
node.toggleAttribute(
"disabled",
!this.inspector.highlighters.canGridHighlighterToggle(
this.inspector.selection.nodeFront
)
);
}
}
break;
}
},
/**
* Enables the print and color scheme simulation only for local and remote tab debugging.
*/
async _initSimulationFeatures() {
if (!this.inspector.commands.descriptorFront.isTabDescriptor) {
return;
}
this.colorSchemeLightSimulationButton.removeAttribute("hidden");
this.colorSchemeDarkSimulationButton.removeAttribute("hidden");
this.printSimulationButton.removeAttribute("hidden");
this.printSimulationButton.addEventListener(
"click",
this._onTogglePrintSimulation
);
this.colorSchemeLightSimulationButton.addEventListener(
"click",
this._onToggleLightColorSchemeSimulation
);
this.colorSchemeDarkSimulationButton.addEventListener(
"click",
this._onToggleDarkColorSchemeSimulation
);
const { rfpCSSColorScheme } = this.inspector.walker;
if (rfpCSSColorScheme) {
this.colorSchemeLightSimulationButton.setAttribute("disabled", true);
this.colorSchemeDarkSimulationButton.setAttribute("disabled", true);
console.warn("Color scheme simulation is disabled in RFP mode.");
}
},
/**
* Get the type of a given node in the rule-view
*
* @param {DOMNode} node
* The node which we want information about
* @return {Object|null} containing the following props:
* - type {String} One of the VIEW_NODE_XXX_TYPE const in
* client/inspector/shared/node-types.
* - rule {Rule} The Rule object.
* - value {Object} Depends on the type of the node.
* Otherwise, returns null if the node isn't anything we care about.
*/
getNodeInfo(node) {
return getNodeInfo(node, this._elementStyle);
},
/**
* Get the node's compatibility issues
*
* @param {DOMNode} node
* The node which we want information about
* @return {Object|null} containing the following props:
* - type {String} Compatibility issue type.
* - property {string} The incompatible rule
* - alias {Array} The browser specific alias of rule
* - url {string} Link to MDN documentation
* - deprecated {bool} True if the rule is deprecated
* - experimental {bool} True if rule is experimental
* - unsupportedBrowsers {Array} Array of unsupported browser
* Otherwise, returns null if the node has cross-browser compatible CSS
*/
async getNodeCompatibilityInfo(node) {
const compatibilityInfo = await getNodeCompatibilityInfo(
node,
this._elementStyle
);
return compatibilityInfo;
},
/**
* Context menu handler.
*/
_onContextMenu(event) {
if (
event.originalTarget.closest("input[type=text]") ||
event.originalTarget.closest("input:not([type])") ||
event.originalTarget.closest("textarea")
) {
return;
}
event.stopPropagation();
event.preventDefault();
this.contextMenu.show(event);
},
/**
* Callback for copy event. Copy the selected text.
*
* @param {Event} event
* copy event object.
*/
_onCopy(event) {
if (event) {
this.copySelection(event.target);
event.preventDefault();
event.stopPropagation();
}
},
/**
* Copy the current selection. The current target is necessary
* if the selection is inside an input or a textarea
*
* @param {DOMNode} target
* DOMNode target of the copy action
*/
copySelection(target) {
try {
let text = "";
const nodeName = target?.nodeName;
const targetType = target?.type;
if (
// The target can be the enable/disable rule checkbox here (See Bug 1680893).
(nodeName === "input" && targetType !== "checkbox") ||
nodeName == "textarea"
) {
const start = Math.min(target.selectionStart, target.selectionEnd);
const end = Math.max(target.selectionStart, target.selectionEnd);
const count = end - start;
text = target.value.substr(start, count);
} else {
text = this.styleWindow.getSelection().toString();
// Remove any double newlines.
text = text.replace(/(\r?\n)\r?\n/g, "$1");
}
clipboardHelper.copyString(text);
} catch (e) {
console.error(e);
}
},
/**
* Add a new rule to the current element.
*/
async _onAddRule() {
const elementStyle = this._elementStyle;
const element = elementStyle.element;
const pseudoClasses = element.pseudoClassLocks;
// Clear the search input so the new rule is visible
this._onClearSearch();
this._focusNextUserAddedRule = true;
this.pageStyle.addNewRule(element, pseudoClasses);
},
/**
* Disables add rule button when needed
*/
refreshAddRuleButtonState() {
const shouldBeDisabled =
!this._viewedElement ||
!this.inspector.selection.isElementNode() ||
this.inspector.selection.isAnonymousNode();
this.addRuleButton.disabled = shouldBeDisabled;
},
/**
* Return {Boolean} true if the rule view currently has an input
* editor visible.
*/
get isEditing() {
return (
this.tooltips.isEditing ||
!!this.element.querySelectorAll(".styleinspector-propertyeditor").length
);
},
_handleUAStylePrefChange() {
this.showUserAgentStyles = Services.prefs.getBoolPref(PREF_UA_STYLES);
this._handlePrefChange(PREF_UA_STYLES);
},
_handleDefaultColorUnitPrefChange() {
this._handlePrefChange(PREF_DEFAULT_COLOR_UNIT);
},
_handleDraggablePrefChange() {
this.draggablePropertiesEnabled = Services.prefs.getBoolPref(
PREF_DRAGGABLE,
false
);
// This event is consumed by text-property-editor instances in order to
// update their draggable behavior. Preferences observer are costly, so
// we are forwarding the preference update via the EventEmitter.
this.emit("draggable-preference-updated");
},
_handleInplaceEditorFocusNextOnEnterPrefChange() {
this.inplaceEditorFocusNextOnEnter = Services.prefs.getBoolPref(
PREF_INPLACE_EDITOR_FOCUS_NEXT_ON_ENTER,
false
);
this._handlePrefChange(PREF_INPLACE_EDITOR_FOCUS_NEXT_ON_ENTER);
},
_handlePrefChange(pref) {
// Reselect the currently selected element
const refreshOnPrefs = [
PREF_UA_STYLES,
PREF_DEFAULT_COLOR_UNIT,
PREF_INPLACE_EDITOR_FOCUS_NEXT_ON_ENTER,
];
if (this._viewedElement && refreshOnPrefs.includes(pref)) {
this.selectElement(this._viewedElement, true);
}
},
/**
* Set the filter style search value.
* @param {String} value
* The search value.
*/
setFilterStyles(value = "") {
this.searchField.value = value;
this.searchField.focus();
this._onFilterStyles();
},
/**
* Called when the user enters a search term in the filter style search box.
*/
_onFilterStyles() {
if (this._filterChangedTimeout) {
clearTimeout(this._filterChangedTimeout);
}
const filterTimeout = this.searchValue.length ? FILTER_CHANGED_TIMEOUT : 0;
this.searchClearButton.hidden = this.searchValue.length === 0;
this._filterChangedTimeout = setTimeout(() => {
this.searchData = {
searchPropertyMatch: FILTER_PROP_RE.exec(this.searchValue),
searchPropertyName: this.searchValue,
searchPropertyValue: this.searchValue,
strictSearchValue: "",
strictSearchPropertyName: false,
strictSearchPropertyValue: false,
strictSearchAllValues: false,
};
if (this.searchData.searchPropertyMatch) {
// Parse search value as a single property line and extract the
// property name and value. If the parsed property name or value is
// contained in backquotes (`), extract the value within the backquotes
// and set the corresponding strict search for the property to true.
if (FILTER_STRICT_RE.test(this.searchData.searchPropertyMatch[1])) {
this.searchData.strictSearchPropertyName = true;
this.searchData.searchPropertyName = FILTER_STRICT_RE.exec(
this.searchData.searchPropertyMatch[1]
)[1];
} else {
this.searchData.searchPropertyName =
this.searchData.searchPropertyMatch[1];
}
if (FILTER_STRICT_RE.test(this.searchData.searchPropertyMatch[2])) {
this.searchData.strictSearchPropertyValue = true;
this.searchData.searchPropertyValue = FILTER_STRICT_RE.exec(
this.searchData.searchPropertyMatch[2]
)[1];
} else {
this.searchData.searchPropertyValue =
this.searchData.searchPropertyMatch[2];
}
// Strict search for stylesheets will match the property line regex.
// Extract the search value within the backquotes to be used
// in the strict search for stylesheets in _highlightStyleSheet.
if (FILTER_STRICT_RE.test(this.searchValue)) {
this.searchData.strictSearchValue = FILTER_STRICT_RE.exec(
this.searchValue
)[1];
}
} else if (FILTER_STRICT_RE.test(this.searchValue)) {
// If the search value does not correspond to a property line and
// is contained in backquotes, extract the search value within the
// backquotes and set the flag to perform a strict search for all
// the values (selector, stylesheet, property and computed values).
const searchValue = FILTER_STRICT_RE.exec(this.searchValue)[1];
this.searchData.strictSearchAllValues = true;
this.searchData.searchPropertyName = searchValue;
this.searchData.searchPropertyValue = searchValue;
this.searchData.strictSearchValue = searchValue;
}
this._clearHighlight(this.element);
this._clearRules();
this._createEditors();
this.inspector.emit("ruleview-filtered");
this._filterChangeTimeout = null;
}, filterTimeout);
},
/**
* Called when the user clicks on the clear button in the filter style search
* box. Returns true if the search box is cleared and false otherwise.
*/
_onClearSearch() {
if (this.searchField.value) {
this.setFilterStyles("");
return true;
}
return false;
},
destroy() {
this.isDestroyed = true;
this.clear();
this._dummyElement = null;
// off handlers must have the same reference as their on handlers
this._prefObserver.off(PREF_UA_STYLES, this._handleUAStylePrefChange);
this._prefObserver.off(
PREF_DEFAULT_COLOR_UNIT,
this._handleDefaultColorUnitPrefChange
);
this._prefObserver.off(PREF_DRAGGABLE, this._handleDraggablePrefChange);
this._prefObserver.off(
PREF_INPLACE_EDITOR_FOCUS_NEXT_ON_ENTER,
this._handleInplaceEditorFocusNextOnEnterPrefChange
);
this._prefObserver.destroy();
this._outputParser = null;
if (this._classListPreviewer) {
this._classListPreviewer.destroy();
this._classListPreviewer = null;
}
if (this._contextMenu) {
this._contextMenu.destroy();
this._contextMenu = null;
}
if (this._highlighters) {
this._highlighters.removeFromView(this);
this._highlighters = null;
}
// Clean-up for simulations.
this.colorSchemeLightSimulationButton.removeEventListener(
"click",
this._onToggleLightColorSchemeSimulation
);
this.colorSchemeDarkSimulationButton.removeEventListener(
"click",
this._onToggleDarkColorSchemeSimulation
);
this.printSimulationButton.removeEventListener(
"click",
this._onTogglePrintSimulation
);
this.colorSchemeLightSimulationButton = null;
this.colorSchemeDarkSimulationButton = null;
this.printSimulationButton = null;
this.tooltips.destroy();
// Remove bound listeners
this._abortController.abort();
this._abortController = null;
this.shortcuts.destroy();
this.styleDocument.removeEventListener("click", this, { capture: true });
this.element.removeEventListener("copy", this._onCopy);
this.element.removeEventListener("contextmenu", this._onContextMenu);
this.addRuleButton.removeEventListener("click", this._onAddRule);
this.searchField.removeEventListener("input", this._onFilterStyles);
this.searchClearButton.removeEventListener("click", this._onClearSearch);
this.pseudoClassPanel.removeEventListener(
"change",
this._onTogglePseudoClass
);
this.pseudoClassToggle.removeEventListener(
"click",
this._onTogglePseudoClassPanel
);
this.classToggle.removeEventListener("click", this._onToggleClassPanel);
this.inspector.highlighters.off(
"highlighter-shown",
this.onHighlighterShown
);
this.inspector.highlighters.off(
"highlighter-hidden",
this.onHighlighterHidden
);
this.searchField = null;
this.searchClearButton = null;
this.pseudoClassPanel = null;
this.pseudoClassToggle = null;
this.pseudoClassCheckboxes = null;
this.classPanel = null;
this.classToggle = null;
this.inspector = null;
this.styleDocument = null;
this.styleWindow = null;
if (this.element.parentNode) {
this.element.remove();
}
if (this._elementStyle) {
this._elementStyle.destroy();
}
if (this._popup) {
this._popup.destroy();
this._popup = null;
}
},
/**
* Mark the view as selecting an element, disabling all interaction, and
* visually clearing the view after a few milliseconds to avoid confusion