Web Inspector: Styles: selection lost when inspector is blurred
[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
43         this._nameTextField = null;
44         this._valueTextField = null;
45
46         this._selected = false;
47         this._hasInvalidVariableValue = false;
48
49         this.update();
50         property.addEventListener(WI.CSSProperty.Event.OverriddenStatusChanged, this.updateStatus, this);
51         property.addEventListener(WI.CSSProperty.Event.Changed, this.updateStatus, this);
52
53         if (!this._readOnly) {
54             this._element.tabIndex = -1;
55
56             this._element.addEventListener("blur", (event) => {
57                 // Keep selection after tabbing out of Web Inspector window and back.
58                 if (document.activeElement === this._element)
59                     return;
60
61                 if (this._delegate.spreadsheetStylePropertyBlur)
62                     this._delegate.spreadsheetStylePropertyBlur(event, this);
63             });
64
65             this._element.addEventListener("mouseenter", (event) => {
66                 if (this._delegate.spreadsheetStylePropertyMouseEnter)
67                     this._delegate.spreadsheetStylePropertyMouseEnter(event, this);
68             });
69
70             this._element.copyHandler = this;
71         }
72     }
73
74     // Public
75
76     get element() { return this._element; }
77     get property() { return this._property; }
78     get nameTextField() { return this._nameTextField; }
79     get valueTextField() { return this._valueTextField; }
80     get enabled() { return this._property.enabled; }
81
82     set index(index)
83     {
84         this._element.dataset.propertyIndex = index;
85     }
86
87     get selected()
88     {
89         return this._selected;
90     }
91
92     set selected(value)
93     {
94         if (value === this._selected)
95             return;
96
97         this._selected = value;
98         this.updateStatus();
99     }
100
101     startEditingName()
102     {
103         if (!this._nameTextField)
104             return;
105
106         this._nameTextField.startEditing();
107     }
108
109     startEditingValue()
110     {
111         if (!this._valueTextField)
112             return;
113
114         this._valueTextField.startEditing();
115     }
116
117     detached()
118     {
119         if (this._nameTextField)
120             this._nameTextField.detached();
121
122         if (this._valueTextField)
123             this._valueTextField.detached();
124     }
125
126     hidden()
127     {
128         if (this._nameTextField && this._nameTextField.editing)
129             this._nameTextField.element.blur();
130         else if (this._valueTextField && this._valueTextField.editing)
131             this._valueTextField.element.blur();
132     }
133
134     remove(replacement = null)
135     {
136         console.assert(this._property.ownerStyle.locked, `Removed property was unlocked (${this._property.name})`);
137         this.element.remove();
138
139         if (replacement)
140             this._property.replaceWithText(replacement);
141         else
142             this._property.remove();
143
144         this.detached();
145
146         if (this._delegate && typeof this._delegate.spreadsheetStylePropertyRemoved === "function")
147             this._delegate.spreadsheetStylePropertyRemoved(this);
148     }
149
150     update()
151     {
152         this.element.removeChildren();
153
154         if (this._isEditable()) {
155             this._checkboxElement = this.element.appendChild(document.createElement("input"));
156             this._checkboxElement.classList.add("property-toggle");
157             this._checkboxElement.type = "checkbox";
158             this._checkboxElement.checked = this._property.enabled;
159             this._checkboxElement.tabIndex = -1;
160             this._checkboxElement.addEventListener("click", (event) => {
161                 console.assert(this._property.ownerStyle.locked, `Toggled property was unlocked (${this._property.name})`);
162                 event.stopPropagation();
163                 let disabled = !this._checkboxElement.checked;
164                 this._property.commentOut(disabled);
165                 this.update();
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.properties) {
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             classNames.push("overridden");
265             if (duplicatePropertyExistsBelow(this._property)) {
266                 classNames.push("has-warning");
267                 elementTitle = WI.UIString("Duplicate property");
268             }
269         }
270
271         if (this._property.implicit)
272             classNames.push("implicit");
273
274         if (this._property.ownerStyle.inherited && !this._property.inherited)
275             classNames.push("not-inherited");
276
277         if (!this._property.valid && this._property.hasOtherVendorNameOrKeyword())
278             classNames.push("other-vendor");
279         else if (this._hasInvalidVariableValue || (!this._property.valid && this._property.value !== "")) {
280             let propertyNameIsValid = false;
281             if (WI.CSSCompletions.cssNameCompletions)
282                 propertyNameIsValid = WI.CSSCompletions.cssNameCompletions.isValidPropertyName(this._property.name);
283
284             classNames.push("has-warning");
285
286             if (!propertyNameIsValid) {
287                 classNames.push("invalid-name");
288                 elementTitle = WI.UIString("Unsupported property name");
289             } else {
290                 classNames.push("invalid-value");
291                 elementTitle = WI.UIString("Unsupported property value");
292             }
293         }
294
295         if (!this._property.enabled)
296             classNames.push("disabled");
297
298         if (this._selected)
299             classNames.push("selected");
300
301         this._element.className = classNames.join(" ");
302         this._element.title = elementTitle;
303     }
304
305     applyFilter(filterText)
306     {
307         let matchesName = this._nameElement.textContent.includes(filterText);
308         this._nameElement.classList.toggle(WI.GeneralStyleDetailsSidebarPanel.FilterMatchSectionClassName, !!matchesName);
309
310         let matchesValue = this._valueElement.textContent.includes(filterText);
311         this._valueElement.classList.toggle(WI.GeneralStyleDetailsSidebarPanel.FilterMatchSectionClassName, !!matchesValue);
312
313         let matches = matchesName || matchesValue;
314         this._contentElement.classList.toggle(WI.GeneralStyleDetailsSidebarPanel.NoFilterMatchInPropertyClassName, !matches);
315         return matches;
316     }
317
318     handleCopyEvent(event)
319     {
320         this._delegate.spreadsheetStylePropertyCopy(event, this);
321     }
322
323     // SpreadsheetTextField delegate
324
325     spreadsheetTextFieldWillStartEditing(textField)
326     {
327         let isEditingName = textField === this._nameTextField;
328         textField.value = isEditingName ? this._property.name : this._property.rawValue;
329     }
330
331     spreadsheetTextFieldDidChange(textField)
332     {
333         if (textField === this._valueTextField)
334             this._handleValueChange();
335         else if (textField === this._nameTextField)
336             this._handleNameChange();
337     }
338
339     spreadsheetTextFieldDidCommit(textField, {direction})
340     {
341         let propertyName = this._nameTextField.value.trim();
342         let propertyValue = this._valueTextField.value.trim();
343         let willRemoveProperty = false;
344         let isEditingName = textField === this._nameTextField;
345
346         if (!propertyName || (!propertyValue && !isEditingName && direction === "forward"))
347             willRemoveProperty = true;
348
349         if (!isEditingName && !willRemoveProperty)
350             this._renderValue(propertyValue);
351
352         if (direction === "forward") {
353             if (isEditingName && !willRemoveProperty) {
354                 // Move focus from the name to the value.
355                 this._valueTextField.startEditing();
356                 return;
357             }
358         } else {
359             if (!isEditingName) {
360                 // Move focus from the value to the name.
361                 this._nameTextField.startEditing();
362                 return;
363             }
364         }
365
366         if (typeof this._delegate.spreadsheetStylePropertyFocusMoved === "function") {
367             // Move focus away from the current property, to the next or previous one, if exists, or to the next or previous rule, if exists.
368             this._delegate.spreadsheetStylePropertyFocusMoved(this, {direction, willRemoveProperty});
369         }
370
371         if (willRemoveProperty)
372             this.remove();
373     }
374
375     spreadsheetTextFieldDidBlur(textField, event)
376     {
377         let focusedOutsideThisProperty = event.relatedTarget !== this._nameElement && event.relatedTarget !== this._valueElement;
378         if (focusedOutsideThisProperty && (!this._nameTextField.value.trim() || !this._valueTextField.value.trim())) {
379             this.remove();
380             return;
381         }
382
383         if (textField === this._valueTextField)
384             this._renderValue(this._valueElement.textContent);
385
386         if (typeof this._delegate.spreadsheetStylePropertyFocusMoved === "function")
387             this._delegate.spreadsheetStylePropertyFocusMoved(this, {direction: null});
388     }
389
390     spreadsheetTextFieldDidBackspace(textField)
391     {
392         if (textField === this._nameTextField)
393             this.spreadsheetTextFieldDidCommit(textField, {direction: "backward"});
394         else if (textField === this._valueTextField)
395             this._nameTextField.startEditing();
396     }
397
398     spreadsheetTextFieldDidPressEsc(textField, textBeforeEditing)
399     {
400         let isNewProperty = !textBeforeEditing;
401         if (isNewProperty)
402             this.remove();
403         else if (this._delegate.spreadsheetStylePropertyDidPressEsc)
404             this._delegate.spreadsheetStylePropertyDidPressEsc(this);
405     }
406
407     // Private
408
409     _isEditable()
410     {
411         return !this._readOnly && this._property.editable;
412     }
413
414     _renderValue(value)
415     {
416         this._hasInvalidVariableValue = false;
417
418         const maxValueLength = 150;
419         let tokens = WI.tokenizeCSSValue(value);
420
421         if (this._property.enabled) {
422             // FIXME: <https://webkit.org/b/178636> Web Inspector: Styles: Make inline widgets work with CSS functions (var(), calc(), etc.)
423             tokens = this._addGradientTokens(tokens);
424             tokens = this._addColorTokens(tokens);
425             tokens = this._addTimingFunctionTokens(tokens, "cubic-bezier");
426             tokens = this._addTimingFunctionTokens(tokens, "spring");
427             tokens = this._addVariableTokens(tokens);
428         }
429
430         tokens = tokens.map((token) => {
431             if (token instanceof Element)
432                 return token;
433
434             let className = "";
435
436             if (token.type) {
437                 if (token.type.includes("string"))
438                     className = "token-string";
439                 else if (token.type.includes("link"))
440                     className = "token-link";
441                 else if (token.type.includes("comment"))
442                     className = "token-comment";
443             }
444
445             if (className) {
446                 let span = document.createElement("span");
447                 span.classList.add(className);
448                 span.textContent = token.value.truncateMiddle(maxValueLength);
449
450                 if (token.type && token.type.includes("link"))
451                     span.addEventListener("contextmenu", this._handleLinkContextMenu.bind(this, token));
452
453                 return span;
454             }
455
456             return token.value;
457         });
458
459         this._valueElement.removeChildren();
460         this._valueElement.append(...tokens);
461     }
462
463     _createInlineSwatch(type, text, valueObject)
464     {
465         let tokenElement = document.createElement("span");
466         let innerElement = document.createElement("span");
467         innerElement.textContent = text;
468
469         let readOnly = !this._isEditable();
470         let swatch = new WI.InlineSwatch(type, valueObject, readOnly);
471
472         swatch.addEventListener(WI.InlineSwatch.Event.ValueChanged, (event) => {
473             let value = event.data.value && event.data.value.toString();
474             if (!value)
475                 return;
476
477             innerElement.textContent = value;
478             this._handleValueChange();
479         }, this);
480
481         if (typeof this._delegate.stylePropertyInlineSwatchActivated === "function") {
482             swatch.addEventListener(WI.InlineSwatch.Event.Activated, () => {
483                 this._swatchActive = true;
484                 this._delegate.stylePropertyInlineSwatchActivated();
485             });
486         }
487
488         if (typeof this._delegate.stylePropertyInlineSwatchDeactivated === "function") {
489             swatch.addEventListener(WI.InlineSwatch.Event.Deactivated, () => {
490                 this._swatchActive = false;
491                 this._delegate.stylePropertyInlineSwatchDeactivated();
492             });
493         }
494
495         tokenElement.append(swatch.element, innerElement);
496
497         // Prevent the value from editing when clicking on the swatch.
498         swatch.element.addEventListener("click", (event) => {
499             if (this._swatchActive || event.shiftKey)
500                 event.stop();
501         });
502
503         return tokenElement;
504     }
505
506     _addGradientTokens(tokens)
507     {
508         let gradientRegex = /^(repeating-)?(linear|radial)-gradient$/i;
509         let newTokens = [];
510         let gradientStartIndex = NaN;
511         let openParenthesis = 0;
512
513         for (let i = 0; i < tokens.length; i++) {
514             let token = tokens[i];
515             if (token.type && token.type.includes("atom") && gradientRegex.test(token.value)) {
516                 gradientStartIndex = i;
517                 openParenthesis = 0;
518             } else if (token.value === "(" && !isNaN(gradientStartIndex))
519                 openParenthesis++;
520             else if (token.value === ")" && !isNaN(gradientStartIndex)) {
521                 openParenthesis--;
522                 if (openParenthesis > 0) {
523                     // Matched a CSS function inside of the gradient.
524                     continue;
525                 }
526
527                 let rawTokens = tokens.slice(gradientStartIndex, i + 1);
528                 let text = rawTokens.map((token) => token.value).join("");
529                 let gradient = WI.Gradient.fromString(text);
530                 if (gradient)
531                     newTokens.push(this._createInlineSwatch(WI.InlineSwatch.Type.Gradient, text, gradient));
532                 else
533                     newTokens.push(...rawTokens);
534
535                 gradientStartIndex = NaN;
536             } else if (isNaN(gradientStartIndex))
537                 newTokens.push(token);
538         }
539
540         return newTokens;
541     }
542
543     _addColorTokens(tokens)
544     {
545         let newTokens = [];
546
547         let pushPossibleColorToken = (text, ...rawTokens) => {
548             let color = WI.Color.fromString(text);
549             if (color)
550                 newTokens.push(this._createInlineSwatch(WI.InlineSwatch.Type.Color, text, color));
551             else
552                 newTokens.push(...rawTokens);
553         };
554
555         let colorFunctionStartIndex = NaN;
556
557         for (let i = 0; i < tokens.length; i++) {
558             let token = tokens[i];
559             if (token.type && token.type.includes("hex-color")) {
560                 // Hex
561                 pushPossibleColorToken(token.value, token);
562             } else if (WI.Color.FunctionNames.has(token.value) && token.type && (token.type.includes("atom") || token.type.includes("keyword"))) {
563                 // Color Function start
564                 colorFunctionStartIndex = i;
565             } else if (isNaN(colorFunctionStartIndex) && token.type && token.type.includes("keyword")) {
566                 // Color keyword
567                 pushPossibleColorToken(token.value, token);
568             } else if (!isNaN(colorFunctionStartIndex)) {
569                 // Color Function end
570                 if (token.value !== ")")
571                     continue;
572
573                 let rawTokens = tokens.slice(colorFunctionStartIndex, i + 1);
574                 let text = rawTokens.map((token) => token.value).join("");
575                 pushPossibleColorToken(text, ...rawTokens);
576                 colorFunctionStartIndex = NaN;
577             } else
578                 newTokens.push(token);
579         }
580
581         return newTokens;
582     }
583
584     _addTimingFunctionTokens(tokens, tokenType)
585     {
586         let newTokens = [];
587         let startIndex = NaN;
588         let openParenthesis = 0;
589
590         for (let i = 0; i < tokens.length; i++) {
591             let token = tokens[i];
592             if (token.value === tokenType && token.type && token.type.includes("atom")) {
593                 startIndex = i;
594                 openParenthesis = 0;
595             } else if (token.value === "(" && !isNaN(startIndex))
596                 openParenthesis++;
597             else if (token.value === ")" && !isNaN(startIndex)) {
598
599                 openParenthesis--;
600                 if (openParenthesis > 0)
601                     continue;
602
603                 let rawTokens = tokens.slice(startIndex, i + 1);
604                 let text = rawTokens.map((token) => token.value).join("");
605
606                 let valueObject;
607                 let inlineSwatchType;
608                 if (tokenType === "cubic-bezier") {
609                     valueObject = WI.CubicBezier.fromString(text);
610                     inlineSwatchType = WI.InlineSwatch.Type.Bezier;
611                 } else if (tokenType === "spring") {
612                     valueObject = WI.Spring.fromString(text);
613                     inlineSwatchType = WI.InlineSwatch.Type.Spring;
614                 }
615
616                 if (valueObject)
617                     newTokens.push(this._createInlineSwatch(inlineSwatchType, text, valueObject));
618                 else
619                     newTokens.push(...rawTokens);
620
621                 startIndex = NaN;
622             } else if (isNaN(startIndex))
623                 newTokens.push(token);
624         }
625
626         return newTokens;
627     }
628
629     _addVariableTokens(tokens)
630     {
631         let newTokens = [];
632         let startIndex = NaN;
633         let openParenthesis = 0;
634
635         for (let i = 0; i < tokens.length; i++) {
636             let token = tokens[i];
637             if (token.value === "var" && token.type && token.type.includes("atom")) {
638                 startIndex = i;
639                 openParenthesis = 0;
640             } else if (token.value === "(" && !isNaN(startIndex))
641                 ++openParenthesis;
642             else if (token.value === ")" && !isNaN(startIndex)) {
643                 --openParenthesis;
644                 if (openParenthesis > 0)
645                     continue;
646
647                 let rawTokens = tokens.slice(startIndex, i + 1);
648                 let tokenValues = rawTokens.map((token) => token.value);
649                 let variableName = tokenValues.find((value, i) => value.startsWith("--") && /\bvariable-2\b/.test(rawTokens[i].type));
650
651                 const dontCreateIfMissing = true;
652                 let variableProperty = this._property.ownerStyle.nodeStyles.computedStyle.propertyForName(variableName, dontCreateIfMissing);
653                 if (variableProperty) {
654                     let valueObject = variableProperty.value.trim();
655                     newTokens.push(this._createInlineSwatch(WI.InlineSwatch.Type.Variable, tokenValues.join(""), valueObject));
656                 } else {
657                     this._hasInvalidVariableValue = true;
658                     newTokens.push(...rawTokens);
659                 }
660
661                 startIndex = NaN;
662             } else if (isNaN(startIndex))
663                 newTokens.push(token);
664         }
665
666         return newTokens;
667     }
668
669     _handleNameChange()
670     {
671         console.assert(this._property.ownerStyle.locked, `Modified property was unlocked (${this._property.name})`);
672
673         this._property.name = this._nameElement.textContent.trim();
674     }
675
676     _handleValueChange()
677     {
678         console.assert(this._property.ownerStyle.locked, `Modified property was unlocked (${this._property.name})`);
679
680         this._property.rawValue = this._valueElement.textContent.trim();
681     }
682
683     _handleNameBeforeInput(event)
684     {
685         if (event.data !== ":" || event.inputType !== "insertText")
686             return;
687
688         event.preventDefault();
689         this._nameTextField.discardCompletion();
690         this._valueTextField.startEditing();
691     }
692
693     _handleNamePaste(event)
694     {
695         let text = event.clipboardData.getData("text/plain");
696         if (!text || !text.includes(":"))
697             return;
698
699         event.preventDefault();
700
701         this.remove(text);
702
703         if (this._delegate.spreadsheetStylePropertyAddBlankPropertySoon) {
704             this._delegate.spreadsheetStylePropertyAddBlankPropertySoon(this, {
705                 index: parseInt(this._element.dataset.propertyIndex) + 1,
706             });
707         }
708     }
709
710     _nameCompletionDataProvider(prefix)
711     {
712         return WI.CSSCompletions.cssNameCompletions.startsWith(prefix);
713     }
714
715     _handleValueBeforeInput(event)
716     {
717         if (event.data !== ";" || event.inputType !== "insertText")
718             return;
719
720         let text = this._valueTextField.valueWithoutSuggestion();
721         let selection = window.getSelection();
722         if (!selection.rangeCount || selection.getRangeAt(0).endOffset !== text.length)
723             return;
724
725         // Find the first and last index (if any) of a quote character to ensure that the string
726         // doesn't contain unbalanced quotes. If so, then there's no way that the semicolon could be
727         // part of a string within the value, so we can assume that it's the property "terminator".
728         const quoteRegex = /["']/g;
729         let start = -1;
730         let end = text.length;
731         let match = null;
732         while (match = quoteRegex.exec(text)) {
733             if (start < 0)
734                 start = match.index;
735             end = match.index + 1;
736         }
737
738         if (start !== -1 && !text.substring(start, end).hasMatchingEscapedQuotes())
739             return;
740
741         event.preventDefault();
742         this._valueTextField.stopEditing();
743         this.spreadsheetTextFieldDidCommit(this._valueTextField, {direction: "forward"});
744     }
745
746     _valueCompletionDataProvider(prefix)
747     {
748         let propertyName = this._nameElement.textContent.trim();
749         return WI.CSSKeywordCompletions.forProperty(propertyName).startsWith(prefix);
750     }
751
752     _setupJumpToSymbol(element)
753     {
754         element.addEventListener("mousedown", (event) => {
755             if (event.button !== 0)
756                 return;
757
758             if (!WI.modifierKeys.metaKey)
759                 return;
760
761             if (element.isContentEditable)
762                 return;
763
764             let sourceCodeLocation = null;
765             if (this._property.ownerStyle.ownerRule)
766                 sourceCodeLocation = this._property.ownerStyle.ownerRule.sourceCodeLocation;
767
768             if (!sourceCodeLocation)
769                 return;
770
771             let range = this._property.styleSheetTextRange;
772             const options = {
773                 ignoreNetworkTab: true,
774                 ignoreSearchTab: true,
775             };
776             let sourceCode = sourceCodeLocation.sourceCode;
777             WI.showSourceCodeLocation(sourceCode.createSourceCodeLocation(range.startLine, range.startColumn), options);
778         });
779     }
780
781     _handleLinkContextMenu(token, event)
782     {
783         let contextMenu = WI.ContextMenu.createFromEvent(event);
784
785         let resolveURL = (url) => {
786             let ownerStyle = this._property.ownerStyle;
787             if (!ownerStyle)
788                 return url;
789
790             let ownerStyleSheet = ownerStyle.ownerStyleSheet;
791             if (!ownerStyleSheet) {
792                 let ownerRule = ownerStyle.ownerRule;
793                 if (ownerRule)
794                     ownerStyleSheet = ownerRule.ownerStyleSheet;
795             }
796             if (ownerStyleSheet) {
797                 if (ownerStyleSheet.url)
798                     return absoluteURL(url, ownerStyleSheet.url);
799
800                 let parentFrame = ownerStyleSheet.parentFrame;
801                 if (parentFrame)
802                     return absoluteURL(url, parentFrame.url);
803             }
804
805             let node = ownerStyle.node;
806             if (!node) {
807                 let nodeStyles = ownerStyle.nodeStyles;
808                 if (!nodeStyles) {
809                     let ownerRule = ownerStyle.ownerRule;
810                     if (ownerRule)
811                         nodeStyles = ownerRule.nodeStyles;
812                 }
813                 if (nodeStyles)
814                     node = nodeStyles.node;
815             }
816             if (node) {
817                 let ownerDocument = node.ownerDocument;
818                 if (ownerDocument)
819                     return absoluteURL(url, node.ownerDocument.documentURL);
820             }
821
822             return url;
823         };
824
825         WI.appendContextMenuItemsForURL(contextMenu, resolveURL(token.value));
826     }
827 };
828
829 WI.SpreadsheetStyleProperty.StyleClassName = "property";