a3f2fc5743ffa104235c2b39e487e69cc3e0a12f
[WebKit-https.git] / Source / WebInspectorUI / UserInterface / Views / SpreadsheetStyleProperty.js
1 /*
2  * Copyright (C) 2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 WI.SpreadsheetStyleProperty = class SpreadsheetStyleProperty extends WI.Object
27 {
28     constructor(delegate, property, options = {})
29     {
30         super();
31
32         console.assert(property instanceof WI.CSSProperty);
33
34         this._delegate = delegate || null;
35         this._property = property;
36         this._readOnly = options.readOnly || false;
37         this._element = document.createElement("div");
38
39         this._contentElement = null;
40         this._nameElement = null;
41         this._valueElement = null;
42         this._jumpToEffectivePropertyButton = null;
43
44         this._nameTextField = null;
45         this._valueTextField = null;
46
47         this._selected = false;
48         this._hasInvalidVariableValue = false;
49
50         this.update();
51         property.addEventListener(WI.CSSProperty.Event.OverriddenStatusChanged, this.updateStatus, this);
52         property.addEventListener(WI.CSSProperty.Event.Changed, this.updateStatus, this);
53
54         if (!this._readOnly) {
55             this._element.tabIndex = -1;
56             property.addEventListener(WI.CSSProperty.Event.ModifiedChanged, this.updateStatus, this);
57
58             this._element.addEventListener("blur", (event) => {
59                 // Keep selection after tabbing out of Web Inspector window and back.
60                 if (document.activeElement === this._element)
61                     return;
62
63                 if (this._delegate.spreadsheetStylePropertyBlur)
64                     this._delegate.spreadsheetStylePropertyBlur(event, this);
65             });
66
67             this._element.addEventListener("mouseenter", (event) => {
68                 if (this._delegate.spreadsheetStylePropertyMouseEnter)
69                     this._delegate.spreadsheetStylePropertyMouseEnter(event, this);
70             });
71
72             new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Slash, () => {
73                 this._toggle();
74                 this._select();
75             }, this._element);
76         }
77     }
78
79     // Public
80
81     get element() { return this._element; }
82     get property() { return this._property; }
83     get enabled() { return this._property.enabled; }
84
85     set index(index)
86     {
87         this._element.dataset.propertyIndex = index;
88     }
89
90     get selected()
91     {
92         return this._selected;
93     }
94
95     set selected(value)
96     {
97         if (value === this._selected)
98             return;
99
100         this._selected = value;
101         this.updateStatus();
102     }
103
104     startEditingName()
105     {
106         if (!this._nameTextField)
107             return;
108
109         this._nameTextField.startEditing();
110     }
111
112     startEditingValue()
113     {
114         if (!this._valueTextField)
115             return;
116
117         this._valueTextField.startEditing();
118     }
119
120     detached()
121     {
122         if (this._nameTextField)
123             this._nameTextField.detached();
124
125         if (this._valueTextField)
126             this._valueTextField.detached();
127     }
128
129     hidden()
130     {
131         if (this._nameTextField && this._nameTextField.editing)
132             this._nameTextField.element.blur();
133         else if (this._valueTextField && this._valueTextField.editing)
134             this._valueTextField.element.blur();
135     }
136
137     remove(replacement = null)
138     {
139         if (this._delegate && typeof this._delegate.spreadsheetStylePropertyWillRemove === "function")
140             this._delegate.spreadsheetStylePropertyWillRemove(this);
141
142         this.element.remove();
143
144         if (replacement)
145             this._property.replaceWithText(replacement);
146         else
147             this._property.remove();
148
149         this.detached();
150     }
151
152     update()
153     {
154         this.element.removeChildren();
155
156         if (this._isEditable()) {
157             this._checkboxElement = this.element.appendChild(document.createElement("input"));
158             this._checkboxElement.classList.add("property-toggle");
159             this._checkboxElement.type = "checkbox";
160             this._checkboxElement.checked = this._property.enabled;
161             this._checkboxElement.tabIndex = -1;
162             this._checkboxElement.addEventListener("click", (event) => {
163                 event.stopPropagation();
164                 this._toggle();
165                 console.assert(this._checkboxElement.checked === this._property.enabled);
166             });
167         }
168
169         this._contentElement = this.element.appendChild(document.createElement("span"));
170         this._contentElement.className = "content";
171
172         if (!this._property.enabled)
173             this._contentElement.append("/* ");
174
175         this._nameElement = this._contentElement.appendChild(document.createElement("span"));
176         this._nameElement.classList.add("name");
177         this._nameElement.textContent = this._property.name;
178
179         let colonElement = this._contentElement.appendChild(document.createElement("span"));
180         colonElement.classList.add("colon");
181         colonElement.textContent = ": ";
182
183         this._valueElement = this._contentElement.appendChild(document.createElement("span"));
184         this._valueElement.classList.add("value");
185         this._renderValue(this._property.rawValue);
186
187         if (this._isEditable() && this._property.enabled) {
188             this._nameElement.tabIndex = 0;
189             this._nameElement.addEventListener("beforeinput", this._handleNameBeforeInput.bind(this));
190             this._nameElement.addEventListener("paste", this._handleNamePaste.bind(this));
191
192             this._nameTextField = new WI.SpreadsheetTextField(this, this._nameElement, this._nameCompletionDataProvider.bind(this));
193
194             this._valueElement.tabIndex = 0;
195             this._valueElement.addEventListener("beforeinput", this._handleValueBeforeInput.bind(this));
196
197             this._valueTextField = new WI.SpreadsheetTextField(this, this._valueElement, this._valueCompletionDataProvider.bind(this));
198         }
199
200         if (this._isEditable()) {
201             this._setupJumpToSymbol(this._nameElement);
202             this._setupJumpToSymbol(this._valueElement);
203         }
204
205         let semicolonElement = this._contentElement.appendChild(document.createElement("span"));
206         semicolonElement.classList.add("semicolon");
207         semicolonElement.textContent = ";";
208
209         if (this._property.enabled) {
210             this._warningElement = this.element.appendChild(document.createElement("span"));
211             this._warningElement.className = "warning";
212         } else
213             this._contentElement.append(" */");
214
215         if (!this._property.implicit && this._property.ownerStyle.type === WI.CSSStyleDeclaration.Type.Computed) {
216             let effectiveProperty = this._property.ownerStyle.nodeStyles.effectivePropertyForName(this._property.name);
217             if (effectiveProperty && !effectiveProperty.styleSheetTextRange)
218                 effectiveProperty = effectiveProperty.relatedShorthandProperty;
219
220             let ownerRule = effectiveProperty ? effectiveProperty.ownerStyle.ownerRule : null;
221
222             let arrowElement = this._contentElement.appendChild(WI.createGoToArrowButton());
223             arrowElement.addEventListener("click", (event) => {
224                 if (!effectiveProperty || !ownerRule || !event.altKey) {
225                     if (this._delegate.spreadsheetStylePropertyShowProperty)
226                         this._delegate.spreadsheetStylePropertyShowProperty(this, this._property);
227                     return;
228                 }
229
230                 let sourceCode = ownerRule.sourceCodeLocation.sourceCode;
231                 let {startLine, startColumn} = effectiveProperty.styleSheetTextRange;
232                 WI.showSourceCodeLocation(sourceCode.createSourceCodeLocation(startLine, startColumn), {
233                     ignoreNetworkTab: true,
234                     ignoreSearchTab: true,
235                 });
236             });
237
238             if (effectiveProperty && ownerRule)
239                 arrowElement.title = WI.UIString("Option-click to show source");
240         }
241
242         this.updateStatus();
243     }
244
245     updateStatus()
246     {
247         let duplicatePropertyExistsBelow = (cssProperty) => {
248             let propertyFound = false;
249
250             for (let property of this._property.ownerStyle.enabledProperties) {
251                 if (property === cssProperty)
252                     propertyFound = true;
253                 else if (property.name === cssProperty.name && propertyFound)
254                     return true;
255             }
256
257             return false;
258         };
259
260         let classNames = [WI.SpreadsheetStyleProperty.StyleClassName];
261         let elementTitle = "";
262
263         if (this._property.overridden) {
264             if (!this._jumpToEffectivePropertyButton && this._delegate && this._delegate.spreadsheetStylePropertySelectByProperty && WI.settings.experimentalEnableStylesJumpToEffective.value) {
265                 console.assert(this._property.overridingProperty, `Overridden property is missing overridingProperty: ${this._property.formattedText}`);
266                 if (this._property.overridingProperty) {
267                     this._jumpToEffectivePropertyButton = WI.createGoToArrowButton();
268                     this._jumpToEffectivePropertyButton.classList.add("select-effective-property");
269                     this._jumpToEffectivePropertyButton.dataset.value = this._property.overridingProperty.rawValue;
270                     this._element.append(this._jumpToEffectivePropertyButton);
271
272                     this._jumpToEffectivePropertyButton.addEventListener("click", (event) => {
273                         console.assert(this._property.overridingProperty);
274                         event.stop();
275                         this._delegate.spreadsheetStylePropertySelectByProperty(this._property.overridingProperty);
276                     });
277                 }
278             }
279
280             classNames.push("overridden");
281             if (duplicatePropertyExistsBelow(this._property)) {
282                 classNames.push("has-warning");
283                 elementTitle = WI.UIString("Duplicate property");
284             }
285         }
286
287         if (this._property.implicit)
288             classNames.push("implicit");
289
290         if (this._property.ownerStyle.inherited && !this._property.inherited)
291             classNames.push("not-inherited");
292
293         if (!this._property.valid && this._property.hasOtherVendorNameOrKeyword())
294             classNames.push("other-vendor");
295         else if (this._hasInvalidVariableValue || (!this._property.valid && this._property.value !== "")) {
296             let propertyNameIsValid = false;
297             if (WI.CSSCompletions.cssNameCompletions)
298                 propertyNameIsValid = WI.CSSCompletions.cssNameCompletions.isValidPropertyName(this._property.name);
299
300             classNames.push("has-warning");
301
302             if (!propertyNameIsValid) {
303                 classNames.push("invalid-name");
304                 elementTitle = WI.UIString("Unsupported property name");
305             } else {
306                 classNames.push("invalid-value");
307                 elementTitle = WI.UIString("Unsupported property value");
308             }
309         }
310
311         if (!this._property.enabled)
312             classNames.push("disabled");
313
314         if (this._property.modified && this._property.name && this._property.rawValue)
315             classNames.push("modified");
316
317         if (this._selected)
318             classNames.push("selected");
319
320         this._element.className = classNames.join(" ");
321         this._element.title = elementTitle;
322     }
323
324     applyFilter(filterText)
325     {
326         let matchesName = this._nameElement.textContent.includes(filterText);
327         this._nameElement.classList.toggle(WI.GeneralStyleDetailsSidebarPanel.FilterMatchSectionClassName, !!matchesName);
328
329         let matchesValue = this._valueElement.textContent.includes(filterText);
330         this._valueElement.classList.toggle(WI.GeneralStyleDetailsSidebarPanel.FilterMatchSectionClassName, !!matchesValue);
331
332         let matches = matchesName || matchesValue;
333         this._contentElement.classList.toggle(WI.GeneralStyleDetailsSidebarPanel.NoFilterMatchInPropertyClassName, !matches);
334         return matches;
335     }
336
337     // SpreadsheetTextField delegate
338
339     spreadsheetTextFieldWillStartEditing(textField)
340     {
341         let isEditingName = textField === this._nameTextField;
342         textField.value = isEditingName ? this._property.name : this._property.rawValue;
343     }
344
345     spreadsheetTextFieldDidChange(textField)
346     {
347         if (textField === this._valueTextField)
348             this._handleValueChange();
349         else if (textField === this._nameTextField)
350             this._handleNameChange();
351     }
352
353     spreadsheetTextFieldDidCommit(textField, {direction})
354     {
355         let willRemoveProperty = false;
356         let isEditingName = textField === this._nameTextField;
357
358         if (!this._property.name || (!this._property.rawValue && !isEditingName && direction === "forward"))
359             willRemoveProperty = true;
360
361         if (!isEditingName && !willRemoveProperty)
362             this._renderValue(this._property.rawValue);
363
364         if (direction === "forward") {
365             if (isEditingName && !willRemoveProperty) {
366                 // Move focus from the name to the value.
367                 this._valueTextField.startEditing();
368                 return;
369             }
370         } else {
371             if (!isEditingName) {
372                 // Move focus from the value to the name.
373                 this._nameTextField.startEditing();
374                 return;
375             }
376         }
377
378         if (typeof this._delegate.spreadsheetStylePropertyFocusMoved === "function") {
379             // Move focus away from the current property, to the next or previous one, if exists, or to the next or previous rule, if exists.
380             this._delegate.spreadsheetStylePropertyFocusMoved(this, {direction, willRemoveProperty});
381         }
382
383         if (willRemoveProperty)
384             this.remove();
385     }
386
387     spreadsheetTextFieldDidBlur(textField, event, changed)
388     {
389         let focusedOutsideThisProperty = event.relatedTarget !== this._nameElement && event.relatedTarget !== this._valueElement;
390         if (focusedOutsideThisProperty && (!this._nameTextField.value.trim() || !this._valueTextField.value.trim())) {
391             this.remove();
392             return;
393         }
394
395         if (textField === this._valueTextField)
396             this._renderValue(this._property.rawValue);
397
398         if (typeof this._delegate.spreadsheetStylePropertyFocusMoved === "function")
399             this._delegate.spreadsheetStylePropertyFocusMoved(this, {direction: null});
400
401         if (changed && window.DOMAgent)
402             DOMAgent.markUndoableState();
403     }
404
405     spreadsheetTextFieldDidBackspace(textField)
406     {
407         if (textField === this._nameTextField)
408             this.spreadsheetTextFieldDidCommit(textField, {direction: "backward"});
409         else if (textField === this._valueTextField)
410             this._nameTextField.startEditing();
411     }
412
413     spreadsheetTextFieldDidPressEsc(textField, textBeforeEditing)
414     {
415         let isNewProperty = !textBeforeEditing;
416         if (isNewProperty)
417             this.remove();
418         else if (this._delegate.spreadsheetStylePropertyDidPressEsc)
419             this._delegate.spreadsheetStylePropertyDidPressEsc(this);
420     }
421
422     // Private
423
424     _toggle()
425     {
426         this._property.commentOut(this.property.enabled);
427         this.update();
428     }
429
430     _select()
431     {
432         if (this._delegate && this._delegate.spreadsheetStylePropertySelect) {
433             let index = parseInt(this._element.dataset.propertyIndex);
434             this._delegate.spreadsheetStylePropertySelect(index);
435         }
436     }
437
438     _isEditable()
439     {
440         return !this._readOnly && this._property.editable;
441     }
442
443     _renderValue(value)
444     {
445         this._hasInvalidVariableValue = false;
446
447         const maxValueLength = 150;
448         let tokens = WI.tokenizeCSSValue(value);
449
450         if (this._property.enabled) {
451             // FIXME: <https://webkit.org/b/178636> Web Inspector: Styles: Make inline widgets work with CSS functions (var(), calc(), etc.)
452
453             // CSS variables may contain color - display color picker for them.
454             if (this._property.variable || WI.CSSKeywordCompletions.isColorAwareProperty(this._property.name)) {
455                 tokens = this._addGradientTokens(tokens);
456                 tokens = this._addColorTokens(tokens);
457             }
458             tokens = this._addTimingFunctionTokens(tokens, "cubic-bezier");
459             tokens = this._addTimingFunctionTokens(tokens, "spring");
460             tokens = this._addVariableTokens(tokens);
461         }
462
463         tokens = tokens.map((token) => {
464             if (token instanceof Element)
465                 return token;
466
467             let className = "";
468
469             if (token.type) {
470                 if (token.type.includes("string"))
471                     className = "token-string";
472                 else if (token.type.includes("link"))
473                     className = "token-link";
474                 else if (token.type.includes("comment"))
475                     className = "token-comment";
476             }
477
478             if (className) {
479                 let span = document.createElement("span");
480                 span.classList.add(className);
481                 span.textContent = token.value.truncateMiddle(maxValueLength);
482
483                 if (token.type && token.type.includes("link"))
484                     span.addEventListener("contextmenu", this._handleLinkContextMenu.bind(this, token));
485
486                 return span;
487             }
488
489             return token.value;
490         });
491
492         this._valueElement.removeChildren();
493         this._valueElement.append(...tokens);
494     }
495
496     _createInlineSwatch(type, text, valueObject)
497     {
498         let tokenElement = document.createElement("span");
499         let innerElement = document.createElement("span");
500         innerElement.textContent = text;
501
502         let readOnly = !this._isEditable();
503         let swatch = new WI.InlineSwatch(type, valueObject, readOnly);
504
505         swatch.addEventListener(WI.InlineSwatch.Event.ValueChanged, (event) => {
506             let value = event.data.value && event.data.value.toString();
507             if (!value)
508                 return;
509
510             innerElement.textContent = value;
511             this._handleValueChange();
512
513             if (type === WI.InlineSwatch.Type.Variable)
514                 this._renderValue(this._property.rawValue);
515         }, this);
516
517         if (this._delegate && typeof this._delegate.stylePropertyInlineSwatchActivated === "function") {
518             swatch.addEventListener(WI.InlineSwatch.Event.Activated, () => {
519                 this._delegate.stylePropertyInlineSwatchActivated();
520             });
521         }
522
523         if (this._delegate && typeof this._delegate.stylePropertyInlineSwatchDeactivated === "function") {
524             swatch.addEventListener(WI.InlineSwatch.Event.Deactivated, () => {
525                 this._delegate.stylePropertyInlineSwatchDeactivated();
526             });
527         }
528
529         tokenElement.append(swatch.element, innerElement);
530
531         return tokenElement;
532     }
533
534     _addGradientTokens(tokens)
535     {
536         let gradientRegex = /^(repeating-)?(linear|radial)-gradient$/i;
537         let newTokens = [];
538         let gradientStartIndex = NaN;
539         let openParenthesis = 0;
540
541         for (let i = 0; i < tokens.length; i++) {
542             let token = tokens[i];
543             if (token.type && token.type.includes("atom") && gradientRegex.test(token.value)) {
544                 gradientStartIndex = i;
545                 openParenthesis = 0;
546             } else if (token.value === "(" && !isNaN(gradientStartIndex))
547                 openParenthesis++;
548             else if (token.value === ")" && !isNaN(gradientStartIndex)) {
549                 openParenthesis--;
550                 if (openParenthesis > 0) {
551                     // Matched a CSS function inside of the gradient.
552                     continue;
553                 }
554
555                 let rawTokens = tokens.slice(gradientStartIndex, i + 1);
556                 let text = rawTokens.map((token) => token.value).join("");
557                 let gradient = WI.Gradient.fromString(text);
558                 if (gradient)
559                     newTokens.push(this._createInlineSwatch(WI.InlineSwatch.Type.Gradient, text, gradient));
560                 else
561                     newTokens.push(...rawTokens);
562
563                 gradientStartIndex = NaN;
564             } else if (isNaN(gradientStartIndex))
565                 newTokens.push(token);
566         }
567
568         return newTokens;
569     }
570
571     _addColorTokens(tokens)
572     {
573         let newTokens = [];
574
575         let pushPossibleColorToken = (text, ...rawTokens) => {
576             let color = WI.Color.fromString(text);
577             if (color)
578                 newTokens.push(this._createInlineSwatch(WI.InlineSwatch.Type.Color, text, color));
579             else
580                 newTokens.push(...rawTokens);
581         };
582
583         let colorFunctionStartIndex = NaN;
584
585         for (let i = 0; i < tokens.length; i++) {
586             let token = tokens[i];
587             if (token.type && token.type.includes("hex-color")) {
588                 // Hex
589                 pushPossibleColorToken(token.value, token);
590             } else if (WI.Color.FunctionNames.has(token.value) && token.type && (token.type.includes("atom") || token.type.includes("keyword"))) {
591                 // Color Function start
592                 colorFunctionStartIndex = i;
593             } else if (isNaN(colorFunctionStartIndex) && token.type && (token.type.includes("atom") || token.type.includes("keyword"))) {
594                 // Color keyword
595                 pushPossibleColorToken(token.value, token);
596             } else if (!isNaN(colorFunctionStartIndex)) {
597                 // Color Function end
598                 if (token.value !== ")")
599                     continue;
600
601                 let rawTokens = tokens.slice(colorFunctionStartIndex, i + 1);
602                 let text = rawTokens.map((token) => token.value).join("");
603                 pushPossibleColorToken(text, ...rawTokens);
604                 colorFunctionStartIndex = NaN;
605             } else
606                 newTokens.push(token);
607         }
608
609         return newTokens;
610     }
611
612     _addTimingFunctionTokens(tokens, tokenType)
613     {
614         let newTokens = [];
615         let startIndex = NaN;
616         let openParenthesis = 0;
617
618         for (let i = 0; i < tokens.length; i++) {
619             let token = tokens[i];
620             if (token.value === tokenType && token.type && token.type.includes("atom")) {
621                 startIndex = i;
622                 openParenthesis = 0;
623             } else if (token.value === "(" && !isNaN(startIndex))
624                 openParenthesis++;
625             else if (token.value === ")" && !isNaN(startIndex)) {
626
627                 openParenthesis--;
628                 if (openParenthesis > 0)
629                     continue;
630
631                 let rawTokens = tokens.slice(startIndex, i + 1);
632                 let text = rawTokens.map((token) => token.value).join("");
633
634                 let valueObject;
635                 let inlineSwatchType;
636                 if (tokenType === "cubic-bezier") {
637                     valueObject = WI.CubicBezier.fromString(text);
638                     inlineSwatchType = WI.InlineSwatch.Type.Bezier;
639                 } else if (tokenType === "spring") {
640                     valueObject = WI.Spring.fromString(text);
641                     inlineSwatchType = WI.InlineSwatch.Type.Spring;
642                 }
643
644                 if (valueObject)
645                     newTokens.push(this._createInlineSwatch(inlineSwatchType, text, valueObject));
646                 else
647                     newTokens.push(...rawTokens);
648
649                 startIndex = NaN;
650             } else if (isNaN(startIndex))
651                 newTokens.push(token);
652         }
653
654         return newTokens;
655     }
656
657     _addVariableTokens(tokens)
658     {
659         let newTokens = [];
660         let startIndex = NaN;
661         let openParenthesis = 0;
662
663         for (let i = 0; i < tokens.length; i++) {
664             let token = tokens[i];
665             if (token.value === "var" && token.type && token.type.includes("atom")) {
666                 startIndex = i;
667                 openParenthesis = 0;
668             } else if (token.value === "(" && !isNaN(startIndex))
669                 ++openParenthesis;
670             else if (token.value === ")" && !isNaN(startIndex)) {
671                 --openParenthesis;
672                 if (openParenthesis > 0)
673                     continue;
674
675                 let rawTokens = tokens.slice(startIndex, i + 1);
676                 let tokenValues = rawTokens.map((token) => token.value);
677                 let variableName = tokenValues.find((value, i) => value.startsWith("--") && /\bvariable-2\b/.test(rawTokens[i].type));
678
679                 const dontCreateIfMissing = true;
680                 let variableProperty = this._property.ownerStyle.nodeStyles.computedStyle.propertyForName(variableName, dontCreateIfMissing);
681                 if (variableProperty) {
682                     let valueObject = variableProperty.value.trim();
683                     newTokens.push(this._createInlineSwatch(WI.InlineSwatch.Type.Variable, tokenValues.join(""), valueObject));
684                 } else {
685                     this._hasInvalidVariableValue = true;
686                     newTokens.push(...rawTokens);
687                 }
688
689                 startIndex = NaN;
690             } else if (isNaN(startIndex))
691                 newTokens.push(token);
692         }
693
694         return newTokens;
695     }
696
697     _handleNameChange()
698     {
699         this._property.name = this._nameElement.textContent.trim();
700     }
701
702     _handleValueChange()
703     {
704         this._property.rawValue = this._valueElement.textContent.trim();
705     }
706
707     _handleNameBeforeInput(event)
708     {
709         if (event.data !== ":" || event.inputType !== "insertText")
710             return;
711
712         event.preventDefault();
713         this._nameTextField.discardCompletion();
714         this._valueTextField.startEditing();
715     }
716
717     _handleNamePaste(event)
718     {
719         let text = event.clipboardData.getData("text/plain");
720         if (!text || !text.includes(":"))
721             return;
722
723         event.preventDefault();
724
725         this.remove(text);
726
727         if (this._delegate.spreadsheetStylePropertyAddBlankPropertySoon) {
728             this._delegate.spreadsheetStylePropertyAddBlankPropertySoon(this, {
729                 index: parseInt(this._element.dataset.propertyIndex) + 1,
730             });
731         }
732     }
733
734     _nameCompletionDataProvider(prefix, options = {})
735     {
736         let completions;
737         if (!prefix && options.allowEmptyPrefix)
738             completions = WI.CSSCompletions.cssNameCompletions.values;
739         else
740             completions = WI.CSSCompletions.cssNameCompletions.startsWith(prefix);
741         return {prefix, completions};
742     }
743
744     _handleValueBeforeInput(event)
745     {
746         if (event.data !== ";" || event.inputType !== "insertText")
747             return;
748
749         let text = this._valueTextField.valueWithoutSuggestion();
750         let selection = window.getSelection();
751         if (!selection.rangeCount || selection.getRangeAt(0).endOffset !== text.length)
752             return;
753
754         let unbalancedCharacters = WI.CSSCompletions.completeUnbalancedValue(text);
755         if (unbalancedCharacters)
756             return;
757
758         event.preventDefault();
759         this._valueTextField.stopEditing();
760         this.spreadsheetTextFieldDidCommit(this._valueTextField, {direction: "forward"});
761     }
762
763     _valueCompletionDataProvider(prefix)
764     {
765         // For "border: 1px so|", we want to suggest "solid" based on "so" prefix.
766         let match = prefix.match(/[a-z0-9()-]+$/i);
767
768         // Clicking on the value of `height: 100%` shouldn't show any completions.
769         if (!match && prefix)
770             return {completions: [], prefix: ""};
771
772         prefix = match ? match[0] : "";
773         let propertyName = this._nameElement.textContent.trim();
774         return {
775             prefix,
776             completions: WI.CSSKeywordCompletions.forProperty(propertyName).startsWith(prefix)
777         };
778     }
779
780     _setupJumpToSymbol(element)
781     {
782         element.addEventListener("mousedown", (event) => {
783             if (event.button !== 0)
784                 return;
785
786             if (!WI.modifierKeys.metaKey)
787                 return;
788
789             if (element.isContentEditable)
790                 return;
791
792             let sourceCodeLocation = null;
793             if (this._property.ownerStyle.ownerRule)
794                 sourceCodeLocation = this._property.ownerStyle.ownerRule.sourceCodeLocation;
795
796             if (!sourceCodeLocation)
797                 return;
798
799             let range = this._property.styleSheetTextRange;
800             const options = {
801                 ignoreNetworkTab: true,
802                 ignoreSearchTab: true,
803             };
804             let sourceCode = sourceCodeLocation.sourceCode;
805             WI.showSourceCodeLocation(sourceCode.createSourceCodeLocation(range.startLine, range.startColumn), options);
806         });
807     }
808
809     _handleLinkContextMenu(token, event)
810     {
811         let contextMenu = WI.ContextMenu.createFromEvent(event);
812
813         let resolveURL = (url) => {
814             let ownerStyle = this._property.ownerStyle;
815             if (!ownerStyle)
816                 return url;
817
818             let ownerStyleSheet = ownerStyle.ownerStyleSheet;
819             if (!ownerStyleSheet) {
820                 let ownerRule = ownerStyle.ownerRule;
821                 if (ownerRule)
822                     ownerStyleSheet = ownerRule.ownerStyleSheet;
823             }
824             if (ownerStyleSheet) {
825                 if (ownerStyleSheet.url)
826                     return absoluteURL(url, ownerStyleSheet.url);
827
828                 let parentFrame = ownerStyleSheet.parentFrame;
829                 if (parentFrame)
830                     return absoluteURL(url, parentFrame.url);
831             }
832
833             let node = ownerStyle.node;
834             if (!node) {
835                 let nodeStyles = ownerStyle.nodeStyles;
836                 if (!nodeStyles) {
837                     let ownerRule = ownerStyle.ownerRule;
838                     if (ownerRule)
839                         nodeStyles = ownerRule.nodeStyles;
840                 }
841                 if (nodeStyles)
842                     node = nodeStyles.node;
843             }
844             if (node) {
845                 let ownerDocument = node.ownerDocument;
846                 if (ownerDocument)
847                     return absoluteURL(url, node.ownerDocument.documentURL);
848             }
849
850             return url;
851         };
852
853         WI.appendContextMenuItemsForURL(contextMenu, resolveURL(token.value));
854     }
855 };
856
857 WI.SpreadsheetStyleProperty.StyleClassName = "property";