eda932b8367b8b89fc225794670ef0436c67f7f8
[WebKit-https.git] / Source / WebCore / inspector / front-end / ElementsPanel.js
1 /*
2  * Copyright (C) 2007, 2008 Apple Inc.  All rights reserved.
3  * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>
4  * Copyright (C) 2009 Joseph Pecoraro
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer.
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution.
15  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 WebInspector.ElementsPanel = function()
32 {
33     WebInspector.Panel.call(this, "elements");
34
35     this.contentElement = document.createElement("div");
36     this.contentElement.id = "elements-content";
37     this.contentElement.className = "outline-disclosure source-code";
38
39     this.treeOutline = new WebInspector.ElementsTreeOutline();
40     this.treeOutline.panel = this;
41     this.treeOutline.includeRootDOMNode = false;
42     this.treeOutline.selectEnabled = true;
43
44     this.treeOutline.focusedNodeChanged = function(forceUpdate)
45     {
46         if (this.panel.visible && WebInspector.currentFocusElement !== document.getElementById("search"))
47             WebInspector.currentFocusElement = this.element;
48
49         this.panel.updateBreadcrumb(forceUpdate);
50
51         for (var pane in this.panel.sidebarPanes)
52            this.panel.sidebarPanes[pane].needsUpdate = true;
53
54         this.panel.updateStyles(true);
55         this.panel.updateMetrics();
56         this.panel.updateProperties();
57         this.panel.updateEventListeners();
58
59         if (this._focusedDOMNode) {
60             DOMAgent.addInspectedNode(this._focusedDOMNode.id);
61             WebInspector.extensionServer.notifyObjectSelected(this.panel.name);
62         }
63     };
64
65     this.contentElement.appendChild(this.treeOutline.element);
66
67     this.crumbsElement = document.createElement("div");
68     this.crumbsElement.className = "crumbs";
69     this.crumbsElement.addEventListener("mousemove", this._mouseMovedInCrumbs.bind(this), false);
70     this.crumbsElement.addEventListener("mouseout", this._mouseMovedOutOfCrumbs.bind(this), false);
71
72     this.sidebarPanes = {};
73     this.sidebarPanes.computedStyle = new WebInspector.ComputedStyleSidebarPane();
74     this.sidebarPanes.styles = new WebInspector.StylesSidebarPane(this.sidebarPanes.computedStyle);
75     this.sidebarPanes.metrics = new WebInspector.MetricsSidebarPane();
76     this.sidebarPanes.properties = new WebInspector.PropertiesSidebarPane();
77     if (Preferences.nativeInstrumentationEnabled)
78         this.sidebarPanes.domBreakpoints = WebInspector.createDOMBreakpointsSidebarPane();
79     this.sidebarPanes.eventListeners = new WebInspector.EventListenersSidebarPane();
80
81     this.sidebarPanes.styles.onexpand = this.updateStyles.bind(this);
82     this.sidebarPanes.metrics.onexpand = this.updateMetrics.bind(this);
83     this.sidebarPanes.properties.onexpand = this.updateProperties.bind(this);
84     this.sidebarPanes.eventListeners.onexpand = this.updateEventListeners.bind(this);
85
86     this.sidebarPanes.styles.expanded = true;
87
88     this.sidebarPanes.styles.addEventListener("style edited", this._stylesPaneEdited, this);
89     this.sidebarPanes.styles.addEventListener("style property toggled", this._stylesPaneEdited, this);
90     this.sidebarPanes.metrics.addEventListener("metrics edited", this._metricsPaneEdited, this);
91     WebInspector.cssModel.addEventListener("stylesheet changed", this._styleSheetChanged, this);
92
93     this.sidebarElement = document.createElement("div");
94     this.sidebarElement.id = "elements-sidebar";
95
96     for (var pane in this.sidebarPanes)
97         this.sidebarElement.appendChild(this.sidebarPanes[pane].element);
98
99     this.sidebarResizeElement = document.createElement("div");
100     this.sidebarResizeElement.className = "sidebar-resizer-vertical";
101     this.sidebarResizeElement.addEventListener("mousedown", this.rightSidebarResizerDragStart.bind(this), false);
102
103     this._nodeSearchButton = new WebInspector.StatusBarButton(WebInspector.UIString("Select an element in the page to inspect it."), "node-search-status-bar-item");
104     this._nodeSearchButton.addEventListener("click", this.toggleSearchingForNode.bind(this), false);
105
106     this.element.appendChild(this.contentElement);
107     this.element.appendChild(this.sidebarElement);
108     this.element.appendChild(this.sidebarResizeElement);
109
110     this._registerShortcuts();
111
112     this.reset();
113 }
114
115 WebInspector.ElementsPanel.prototype = {
116     get toolbarItemLabel()
117     {
118         return WebInspector.UIString("Elements");
119     },
120
121     get statusBarItems()
122     {
123         return [this._nodeSearchButton.element, this.crumbsElement];
124     },
125
126     get defaultFocusedElement()
127     {
128         return this.treeOutline.element;
129     },
130
131     updateStatusBarItems: function()
132     {
133         this.updateBreadcrumbSizes();
134     },
135
136     show: function()
137     {
138         WebInspector.Panel.prototype.show.call(this);
139         this.sidebarResizeElement.style.right = (this.sidebarElement.offsetWidth - 3) + "px";
140         this.updateBreadcrumb();
141         this.treeOutline.updateSelection();
142         if (this.recentlyModifiedNodes.length)
143             this.updateModifiedNodes();
144     },
145
146     hide: function()
147     {
148         WebInspector.Panel.prototype.hide.call(this);
149
150         WebInspector.highlightDOMNode(0);
151         this.setSearchingForNode(false);
152     },
153
154     resize: function()
155     {
156         this.treeOutline.updateSelection();
157         this.updateBreadcrumbSizes();
158     },
159
160     reset: function()
161     {
162         if (this.focusedDOMNode)
163             this._selectedPathOnReset = this.focusedDOMNode.path();
164
165         this.rootDOMNode = null;
166         this.focusedDOMNode = null;
167
168         WebInspector.highlightDOMNode(0);
169
170         this.recentlyModifiedNodes = [];
171
172         delete this.currentQuery;
173     },
174
175     setDocument: function(inspectedRootDocument)
176     {
177         this.reset();
178         this.searchCanceled();
179
180         if (!inspectedRootDocument)
181             return;
182
183         inspectedRootDocument.addEventListener("DOMNodeInserted", this._nodeInserted.bind(this));
184         inspectedRootDocument.addEventListener("DOMNodeRemoved", this._nodeRemoved.bind(this));
185         inspectedRootDocument.addEventListener("DOMAttrModified", this._attributesUpdated.bind(this));
186         inspectedRootDocument.addEventListener("DOMCharacterDataModified", this._characterDataModified.bind(this));
187
188         this.rootDOMNode = inspectedRootDocument;
189
190         function selectNode(candidateFocusNode)
191         {
192             if (!candidateFocusNode)
193                 candidateFocusNode = inspectedRootDocument.body || inspectedRootDocument.documentElement;
194
195             if (!candidateFocusNode)
196                 return;
197
198             this.focusedDOMNode = candidateFocusNode;
199             if (this.treeOutline.selectedTreeElement)
200                 this.treeOutline.selectedTreeElement.expand();
201         }
202
203         function selectLastSelectedNode(nodeId)
204         {
205             if (this.focusedDOMNode) {
206                 // Focused node has been explicitly set while reaching out for the last selected node.
207                 return;
208             }
209             var node = nodeId ? WebInspector.domAgent.nodeForId(nodeId) : 0;
210             selectNode.call(this, node);
211         }
212
213         if (this._selectedPathOnReset)
214             DOMAgent.pushNodeByPathToFrontend(this._selectedPathOnReset, selectLastSelectedNode.bind(this));
215         else
216             selectNode.call(this);
217         delete this._selectedPathOnReset;
218     },
219
220     searchCanceled: function()
221     {
222         delete this._searchQuery;
223         this._hideSearchHighlights();
224
225         WebInspector.updateSearchMatchesCount(0, this);
226
227         delete this._currentSearchResultIndex;
228         this._searchResults = [];
229         DOMAgent.searchCanceled();
230     },
231
232     performSearch: function(query)
233     {
234         // Call searchCanceled since it will reset everything we need before doing a new search.
235         this.searchCanceled();
236
237         const whitespaceTrimmedQuery = query.trim();
238         if (!whitespaceTrimmedQuery.length)
239             return;
240
241         this._updatedMatchCountOnce = false;
242         this._matchesCountUpdateTimeout = null;
243         this._searchQuery = query;
244
245         DOMAgent.performSearch(whitespaceTrimmedQuery, false);
246     },
247
248     populateHrefContextMenu: function(contextMenu, event, anchorElement)
249     {
250         if (!anchorElement.href)
251             return false;
252
253         var resourceURL = WebInspector.resourceURLForRelatedNode(this.focusedDOMNode, anchorElement.href);
254         if (!resourceURL)
255             return false;
256
257         // Add resource-related actions.
258         contextMenu.appendItem(WebInspector.openLinkExternallyLabel(), WebInspector.openResource.bind(null, resourceURL, false));
259         if (WebInspector.resourceForURL(resourceURL))
260             contextMenu.appendItem(WebInspector.UIString("Open Link in Resources Panel"), WebInspector.openResource.bind(null, resourceURL, true));
261         return true;
262     },
263
264     switchToAndFocus: function(node)
265     {
266         // Reset search restore.
267         WebInspector.cancelSearch();
268         WebInspector.currentPanel = this;
269         this.focusedDOMNode = node;
270     },
271
272     _updateMatchesCount: function()
273     {
274         WebInspector.updateSearchMatchesCount(this._searchResults.length, this);
275         this._matchesCountUpdateTimeout = null;
276         this._updatedMatchCountOnce = true;
277     },
278
279     _updateMatchesCountSoon: function()
280     {
281         if (!this._updatedMatchCountOnce)
282             return this._updateMatchesCount();
283         if (this._matchesCountUpdateTimeout)
284             return;
285         // Update the matches count every half-second so it doesn't feel twitchy.
286         this._matchesCountUpdateTimeout = setTimeout(this._updateMatchesCount.bind(this), 500);
287     },
288
289     addNodesToSearchResult: function(nodeIds)
290     {
291         if (!nodeIds.length)
292             return;
293
294         var oldSearchResultIndex = this._currentSearchResultIndex;
295         for (var i = 0; i < nodeIds.length; ++i) {
296             var nodeId = nodeIds[i];
297             var node = WebInspector.domAgent.nodeForId(nodeId);
298             if (!node)
299                 continue;
300
301             this._currentSearchResultIndex = 0;
302             this._searchResults.push(node);
303         }
304
305         // Avoid invocations of highlighting for every chunk of nodeIds.
306         if (oldSearchResultIndex !== this._currentSearchResultIndex)
307             this._highlightCurrentSearchResult();
308         this._updateMatchesCountSoon();
309     },
310
311     jumpToNextSearchResult: function()
312     {
313         if (!this._searchResults || !this._searchResults.length)
314             return;
315
316         if (++this._currentSearchResultIndex >= this._searchResults.length)
317             this._currentSearchResultIndex = 0;
318         this._highlightCurrentSearchResult();
319     },
320
321     jumpToPreviousSearchResult: function()
322     {
323         if (!this._searchResults || !this._searchResults.length)
324             return;
325
326         if (--this._currentSearchResultIndex < 0)
327             this._currentSearchResultIndex = (this._searchResults.length - 1);
328         this._highlightCurrentSearchResult();
329     },
330
331     _highlightCurrentSearchResult: function()
332     {
333         this._hideSearchHighlights();
334         var node = this._searchResults[this._currentSearchResultIndex];
335         var treeElement = this.treeOutline.findTreeElement(node);
336         if (treeElement) {
337             treeElement.highlightSearchResults(this._searchQuery);
338             treeElement.reveal();
339         }
340     },
341
342     _hideSearchHighlights: function(node)
343     {
344         for (var i = 0; this._searchResults && i < this._searchResults.length; ++i) {
345             var node = this._searchResults[i];
346             var treeElement = this.treeOutline.findTreeElement(node);
347             if (treeElement)
348                 treeElement.highlightSearchResults(null);
349         }
350     },
351
352     renameSelector: function(oldIdentifier, newIdentifier, oldSelector, newSelector)
353     {
354         // TODO: Implement Shifting the oldSelector, and its contents to a newSelector
355     },
356
357     get rootDOMNode()
358     {
359         return this.treeOutline.rootDOMNode;
360     },
361
362     set rootDOMNode(x)
363     {
364         this.treeOutline.rootDOMNode = x;
365     },
366
367     get focusedDOMNode()
368     {
369         return this.treeOutline.focusedDOMNode;
370     },
371
372     set focusedDOMNode(x)
373     {
374         this.treeOutline.focusedDOMNode = x;
375     },
376
377     _attributesUpdated: function(event)
378     {
379         this.recentlyModifiedNodes.push({node: event.target, updated: true});
380         if (this.visible)
381             this._updateModifiedNodesSoon();
382
383         if (!this.sidebarPanes.styles.isModifyingStyle && event.target === this.focusedDOMNode)
384             this._styleSheetChanged();
385     },
386
387     _characterDataModified: function(event)
388     {
389         this.recentlyModifiedNodes.push({node: event.target, updated: true});
390         if (this.visible)
391             this._updateModifiedNodesSoon();
392     },
393
394     _nodeInserted: function(event)
395     {
396         this.recentlyModifiedNodes.push({node: event.target, parent: event.relatedNode, inserted: true});
397         if (this.visible)
398             this._updateModifiedNodesSoon();
399     },
400
401     _nodeRemoved: function(event)
402     {
403         this.recentlyModifiedNodes.push({node: event.target, parent: event.relatedNode, removed: true});
404         if (this.visible)
405             this._updateModifiedNodesSoon();
406     },
407
408     _updateModifiedNodesSoon: function()
409     {
410         if ("_updateModifiedNodesTimeout" in this)
411             return;
412         this._updateModifiedNodesTimeout = setTimeout(this.updateModifiedNodes.bind(this), 0);
413     },
414
415     updateModifiedNodes: function()
416     {
417         if ("_updateModifiedNodesTimeout" in this) {
418             clearTimeout(this._updateModifiedNodesTimeout);
419             delete this._updateModifiedNodesTimeout;
420         }
421
422         var updatedParentTreeElements = [];
423         var updateBreadcrumbs = false;
424
425         for (var i = 0; i < this.recentlyModifiedNodes.length; ++i) {
426             var replaced = this.recentlyModifiedNodes[i].replaced;
427             var parent = this.recentlyModifiedNodes[i].parent;
428             var node = this.recentlyModifiedNodes[i].node;
429
430             if (this.recentlyModifiedNodes[i].updated) {
431                 var nodeItem = this.treeOutline.findTreeElement(node);
432                 if (nodeItem)
433                     nodeItem.updateTitle();
434                 continue;
435             }
436             
437             if (!parent)
438                 continue;
439
440             var parentNodeItem = this.treeOutline.findTreeElement(parent);
441             if (parentNodeItem && !parentNodeItem.alreadyUpdatedChildren) {
442                 parentNodeItem.updateChildren(replaced);
443                 parentNodeItem.alreadyUpdatedChildren = true;
444                 updatedParentTreeElements.push(parentNodeItem);
445             }
446
447             if (!updateBreadcrumbs && (this.focusedDOMNode === parent || isAncestorNode(this.focusedDOMNode, parent)))
448                 updateBreadcrumbs = true;
449         }
450
451         for (var i = 0; i < updatedParentTreeElements.length; ++i)
452             delete updatedParentTreeElements[i].alreadyUpdatedChildren;
453
454         this.recentlyModifiedNodes = [];
455
456         if (updateBreadcrumbs)
457             this.updateBreadcrumb(true);
458     },
459
460     _stylesPaneEdited: function()
461     {
462         // Once styles are edited, the Metrics pane should be updated.
463         this.sidebarPanes.metrics.needsUpdate = true;
464         this.updateMetrics();
465     },
466
467     _metricsPaneEdited: function()
468     {
469         // Once metrics are edited, the Styles pane should be updated.
470         this.sidebarPanes.styles.needsUpdate = true;
471         this.updateStyles(true);
472     },
473
474     _styleSheetChanged: function()
475     {
476         this._metricsPaneEdited();
477         this._stylesPaneEdited();
478     },
479
480     _mouseMovedInCrumbs: function(event)
481     {
482         var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY);
483         var crumbElement = nodeUnderMouse.enclosingNodeOrSelfWithClass("crumb");
484
485         WebInspector.highlightDOMNode(crumbElement ? crumbElement.representedObject.id : 0);
486
487         if ("_mouseOutOfCrumbsTimeout" in this) {
488             clearTimeout(this._mouseOutOfCrumbsTimeout);
489             delete this._mouseOutOfCrumbsTimeout;
490         }
491     },
492
493     _mouseMovedOutOfCrumbs: function(event)
494     {
495         var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY);
496         if (nodeUnderMouse && nodeUnderMouse.isDescendant(this.crumbsElement))
497             return;
498
499         WebInspector.highlightDOMNode(0);
500
501         this._mouseOutOfCrumbsTimeout = setTimeout(this.updateBreadcrumbSizes.bind(this), 1000);
502     },
503
504     updateBreadcrumb: function(forceUpdate)
505     {
506         if (!this.visible)
507             return;
508
509         var crumbs = this.crumbsElement;
510
511         var handled = false;
512         var foundRoot = false;
513         var crumb = crumbs.firstChild;
514         while (crumb) {
515             if (crumb.representedObject === this.rootDOMNode)
516                 foundRoot = true;
517
518             if (foundRoot)
519                 crumb.addStyleClass("dimmed");
520             else
521                 crumb.removeStyleClass("dimmed");
522
523             if (crumb.representedObject === this.focusedDOMNode) {
524                 crumb.addStyleClass("selected");
525                 handled = true;
526             } else {
527                 crumb.removeStyleClass("selected");
528             }
529
530             crumb = crumb.nextSibling;
531         }
532
533         if (handled && !forceUpdate) {
534             // We don't need to rebuild the crumbs, but we need to adjust sizes
535             // to reflect the new focused or root node.
536             this.updateBreadcrumbSizes();
537             return;
538         }
539
540         crumbs.removeChildren();
541
542         var panel = this;
543
544         function selectCrumbFunction(event)
545         {
546             var crumb = event.currentTarget;
547             if (crumb.hasStyleClass("collapsed")) {
548                 // Clicking a collapsed crumb will expose the hidden crumbs.
549                 if (crumb === panel.crumbsElement.firstChild) {
550                     // If the focused crumb is the first child, pick the farthest crumb
551                     // that is still hidden. This allows the user to expose every crumb.
552                     var currentCrumb = crumb;
553                     while (currentCrumb) {
554                         var hidden = currentCrumb.hasStyleClass("hidden");
555                         var collapsed = currentCrumb.hasStyleClass("collapsed");
556                         if (!hidden && !collapsed)
557                             break;
558                         crumb = currentCrumb;
559                         currentCrumb = currentCrumb.nextSibling;
560                     }
561                 }
562
563                 panel.updateBreadcrumbSizes(crumb);
564             } else {
565                 // Clicking a dimmed crumb or double clicking (event.detail >= 2)
566                 // will change the root node in addition to the focused node.
567                 if (event.detail >= 2 || crumb.hasStyleClass("dimmed"))
568                     panel.rootDOMNode = crumb.representedObject.parentNode;
569                 panel.focusedDOMNode = crumb.representedObject;
570             }
571
572             event.preventDefault();
573         }
574
575         foundRoot = false;
576         for (var current = this.focusedDOMNode; current; current = current.parentNode) {
577             if (current.nodeType === Node.DOCUMENT_NODE)
578                 continue;
579
580             if (current === this.rootDOMNode)
581                 foundRoot = true;
582
583             var crumb = document.createElement("span");
584             crumb.className = "crumb";
585             crumb.representedObject = current;
586             crumb.addEventListener("mousedown", selectCrumbFunction, false);
587
588             var crumbTitle;
589             switch (current.nodeType) {
590                 case Node.ELEMENT_NODE:
591                     this.decorateNodeLabel(current, crumb);
592                     break;
593
594                 case Node.TEXT_NODE:
595                     if (isNodeWhitespace.call(current))
596                         crumbTitle = WebInspector.UIString("(whitespace)");
597                     else
598                         crumbTitle = WebInspector.UIString("(text)");
599                     break
600
601                 case Node.COMMENT_NODE:
602                     crumbTitle = "<!-->";
603                     break;
604
605                 case Node.DOCUMENT_TYPE_NODE:
606                     crumbTitle = "<!DOCTYPE>";
607                     break;
608
609                 default:
610                     crumbTitle = this.treeOutline.nodeNameToCorrectCase(current.nodeName);
611             }
612
613             if (!crumb.childNodes.length) {
614                 var nameElement = document.createElement("span");
615                 nameElement.textContent = crumbTitle;
616                 crumb.appendChild(nameElement);
617                 crumb.title = crumbTitle;
618             }
619
620             if (foundRoot)
621                 crumb.addStyleClass("dimmed");
622             if (current === this.focusedDOMNode)
623                 crumb.addStyleClass("selected");
624             if (!crumbs.childNodes.length)
625                 crumb.addStyleClass("end");
626
627             crumbs.appendChild(crumb);
628         }
629
630         if (crumbs.hasChildNodes())
631             crumbs.lastChild.addStyleClass("start");
632
633         this.updateBreadcrumbSizes();
634     },
635
636     decorateNodeLabel: function(node, parentElement)
637     {
638         var title = this.treeOutline.nodeNameToCorrectCase(node.nodeName);
639
640         var nameElement = document.createElement("span");
641         nameElement.textContent = title;
642         parentElement.appendChild(nameElement);
643
644         var idAttribute = node.getAttribute("id");
645         if (idAttribute) {
646             var idElement = document.createElement("span");
647             parentElement.appendChild(idElement);
648
649             var part = "#" + idAttribute;
650             title += part;
651             idElement.appendChild(document.createTextNode(part));
652
653             // Mark the name as extra, since the ID is more important.
654             nameElement.className = "extra";
655         }
656
657         var classAttribute = node.getAttribute("class");
658         if (classAttribute) {
659             var classes = classAttribute.split(/\s+/);
660             var foundClasses = {};
661
662             if (classes.length) {
663                 var classesElement = document.createElement("span");
664                 classesElement.className = "extra";
665                 parentElement.appendChild(classesElement);
666
667                 for (var i = 0; i < classes.length; ++i) {
668                     var className = classes[i];
669                     if (className && !(className in foundClasses)) {
670                         var part = "." + className;
671                         title += part;
672                         classesElement.appendChild(document.createTextNode(part));
673                         foundClasses[className] = true;
674                     }
675                 }
676             }
677         }
678         parentElement.title = title;
679     },
680
681     linkifyNodeReference: function(node)
682     {
683         var link = document.createElement("span");
684         link.className = "node-link";
685         this.decorateNodeLabel(node, link);
686         WebInspector.wireElementWithDOMNode(link, node.id);
687         return link;
688     },
689
690     linkifyNodeById: function(nodeId)
691     {
692         var node = WebInspector.domAgent.nodeForId(nodeId);
693         if (!node)
694             return document.createTextNode(WebInspector.UIString("<node>"));
695         return this.linkifyNodeReference(node);
696     },
697
698     updateBreadcrumbSizes: function(focusedCrumb)
699     {
700         if (!this.visible)
701             return;
702
703         if (document.body.offsetWidth <= 0) {
704             // The stylesheet hasn't loaded yet or the window is closed,
705             // so we can't calculate what is need. Return early.
706             return;
707         }
708
709         var crumbs = this.crumbsElement;
710         if (!crumbs.childNodes.length || crumbs.offsetWidth <= 0)
711             return; // No crumbs, do nothing.
712
713         // A Zero index is the right most child crumb in the breadcrumb.
714         var selectedIndex = 0;
715         var focusedIndex = 0;
716         var selectedCrumb;
717
718         var i = 0;
719         var crumb = crumbs.firstChild;
720         while (crumb) {
721             // Find the selected crumb and index. 
722             if (!selectedCrumb && crumb.hasStyleClass("selected")) {
723                 selectedCrumb = crumb;
724                 selectedIndex = i;
725             }
726
727             // Find the focused crumb index. 
728             if (crumb === focusedCrumb)
729                 focusedIndex = i;
730
731             // Remove any styles that affect size before
732             // deciding to shorten any crumbs.
733             if (crumb !== crumbs.lastChild)
734                 crumb.removeStyleClass("start");
735             if (crumb !== crumbs.firstChild)
736                 crumb.removeStyleClass("end");
737
738             crumb.removeStyleClass("compact");
739             crumb.removeStyleClass("collapsed");
740             crumb.removeStyleClass("hidden");
741
742             crumb = crumb.nextSibling;
743             ++i;
744         }
745
746         // Restore the start and end crumb classes in case they got removed in coalesceCollapsedCrumbs().
747         // The order of the crumbs in the document is opposite of the visual order.
748         crumbs.firstChild.addStyleClass("end");
749         crumbs.lastChild.addStyleClass("start");
750
751         function crumbsAreSmallerThanContainer()
752         {
753             var rightPadding = 20;
754             var errorWarningElement = document.getElementById("error-warning-count");
755             if (!WebInspector.drawer.visible && errorWarningElement)
756                 rightPadding += errorWarningElement.offsetWidth;
757             return ((crumbs.totalOffsetLeft + crumbs.offsetWidth + rightPadding) < window.innerWidth);
758         }
759
760         if (crumbsAreSmallerThanContainer())
761             return; // No need to compact the crumbs, they all fit at full size.
762
763         var BothSides = 0;
764         var AncestorSide = -1;
765         var ChildSide = 1;
766
767         function makeCrumbsSmaller(shrinkingFunction, direction, significantCrumb)
768         {
769             if (!significantCrumb)
770                 significantCrumb = (focusedCrumb || selectedCrumb);
771
772             if (significantCrumb === selectedCrumb)
773                 var significantIndex = selectedIndex;
774             else if (significantCrumb === focusedCrumb)
775                 var significantIndex = focusedIndex;
776             else {
777                 var significantIndex = 0;
778                 for (var i = 0; i < crumbs.childNodes.length; ++i) {
779                     if (crumbs.childNodes[i] === significantCrumb) {
780                         significantIndex = i;
781                         break;
782                     }
783                 }
784             }
785
786             function shrinkCrumbAtIndex(index)
787             {
788                 var shrinkCrumb = crumbs.childNodes[index];
789                 if (shrinkCrumb && shrinkCrumb !== significantCrumb)
790                     shrinkingFunction(shrinkCrumb);
791                 if (crumbsAreSmallerThanContainer())
792                     return true; // No need to compact the crumbs more.
793                 return false;
794             }
795
796             // Shrink crumbs one at a time by applying the shrinkingFunction until the crumbs
797             // fit in the container or we run out of crumbs to shrink.
798             if (direction) {
799                 // Crumbs are shrunk on only one side (based on direction) of the signifcant crumb.
800                 var index = (direction > 0 ? 0 : crumbs.childNodes.length - 1);
801                 while (index !== significantIndex) {
802                     if (shrinkCrumbAtIndex(index))
803                         return true;
804                     index += (direction > 0 ? 1 : -1);
805                 }
806             } else {
807                 // Crumbs are shrunk in order of descending distance from the signifcant crumb,
808                 // with a tie going to child crumbs.
809                 var startIndex = 0;
810                 var endIndex = crumbs.childNodes.length - 1;
811                 while (startIndex != significantIndex || endIndex != significantIndex) {
812                     var startDistance = significantIndex - startIndex;
813                     var endDistance = endIndex - significantIndex;
814                     if (startDistance >= endDistance)
815                         var index = startIndex++;
816                     else
817                         var index = endIndex--;
818                     if (shrinkCrumbAtIndex(index))
819                         return true;
820                 }
821             }
822
823             // We are not small enough yet, return false so the caller knows.
824             return false;
825         }
826
827         function coalesceCollapsedCrumbs()
828         {
829             var crumb = crumbs.firstChild;
830             var collapsedRun = false;
831             var newStartNeeded = false;
832             var newEndNeeded = false;
833             while (crumb) {
834                 var hidden = crumb.hasStyleClass("hidden");
835                 if (!hidden) {
836                     var collapsed = crumb.hasStyleClass("collapsed"); 
837                     if (collapsedRun && collapsed) {
838                         crumb.addStyleClass("hidden");
839                         crumb.removeStyleClass("compact");
840                         crumb.removeStyleClass("collapsed");
841
842                         if (crumb.hasStyleClass("start")) {
843                             crumb.removeStyleClass("start");
844                             newStartNeeded = true;
845                         }
846
847                         if (crumb.hasStyleClass("end")) {
848                             crumb.removeStyleClass("end");
849                             newEndNeeded = true;
850                         }
851
852                         continue;
853                     }
854
855                     collapsedRun = collapsed;
856
857                     if (newEndNeeded) {
858                         newEndNeeded = false;
859                         crumb.addStyleClass("end");
860                     }
861                 } else
862                     collapsedRun = true;
863                 crumb = crumb.nextSibling;
864             }
865
866             if (newStartNeeded) {
867                 crumb = crumbs.lastChild;
868                 while (crumb) {
869                     if (!crumb.hasStyleClass("hidden")) {
870                         crumb.addStyleClass("start");
871                         break;
872                     }
873                     crumb = crumb.previousSibling;
874                 }
875             }
876         }
877
878         function compact(crumb)
879         {
880             if (crumb.hasStyleClass("hidden"))
881                 return;
882             crumb.addStyleClass("compact");
883         }
884
885         function collapse(crumb, dontCoalesce)
886         {
887             if (crumb.hasStyleClass("hidden"))
888                 return;
889             crumb.addStyleClass("collapsed");
890             crumb.removeStyleClass("compact");
891             if (!dontCoalesce)
892                 coalesceCollapsedCrumbs();
893         }
894
895         function compactDimmed(crumb)
896         {
897             if (crumb.hasStyleClass("dimmed"))
898                 compact(crumb);
899         }
900
901         function collapseDimmed(crumb)
902         {
903             if (crumb.hasStyleClass("dimmed"))
904                 collapse(crumb);
905         }
906
907         if (!focusedCrumb) {
908             // When not focused on a crumb we can be biased and collapse less important
909             // crumbs that the user might not care much about.
910
911             // Compact child crumbs.
912             if (makeCrumbsSmaller(compact, ChildSide))
913                 return;
914
915             // Collapse child crumbs.
916             if (makeCrumbsSmaller(collapse, ChildSide))
917                 return;
918
919             // Compact dimmed ancestor crumbs.
920             if (makeCrumbsSmaller(compactDimmed, AncestorSide))
921                 return;
922
923             // Collapse dimmed ancestor crumbs.
924             if (makeCrumbsSmaller(collapseDimmed, AncestorSide))
925                 return;
926         }
927
928         // Compact ancestor crumbs, or from both sides if focused.
929         if (makeCrumbsSmaller(compact, (focusedCrumb ? BothSides : AncestorSide)))
930             return;
931
932         // Collapse ancestor crumbs, or from both sides if focused.
933         if (makeCrumbsSmaller(collapse, (focusedCrumb ? BothSides : AncestorSide)))
934             return;
935
936         if (!selectedCrumb)
937             return;
938
939         // Compact the selected crumb.
940         compact(selectedCrumb);
941         if (crumbsAreSmallerThanContainer())
942             return;
943
944         // Collapse the selected crumb as a last resort. Pass true to prevent coalescing.
945         collapse(selectedCrumb, true);
946     },
947
948     updateStyles: function(forceUpdate)
949     {
950         var stylesSidebarPane = this.sidebarPanes.styles;
951         var computedStylePane = this.sidebarPanes.computedStyle;
952         if ((!stylesSidebarPane.expanded && !computedStylePane.expanded) || !stylesSidebarPane.needsUpdate)
953             return;
954
955         stylesSidebarPane.update(this.focusedDOMNode, null, forceUpdate);
956         stylesSidebarPane.needsUpdate = false;
957     },
958
959     updateMetrics: function()
960     {
961         var metricsSidebarPane = this.sidebarPanes.metrics;
962         if (!metricsSidebarPane.expanded || !metricsSidebarPane.needsUpdate)
963             return;
964
965         metricsSidebarPane.update(this.focusedDOMNode);
966         metricsSidebarPane.needsUpdate = false;
967     },
968
969     updateProperties: function()
970     {
971         var propertiesSidebarPane = this.sidebarPanes.properties;
972         if (!propertiesSidebarPane.expanded || !propertiesSidebarPane.needsUpdate)
973             return;
974
975         propertiesSidebarPane.update(this.focusedDOMNode);
976         propertiesSidebarPane.needsUpdate = false;
977     },
978
979     updateEventListeners: function()
980     {
981         var eventListenersSidebarPane = this.sidebarPanes.eventListeners;
982         if (!eventListenersSidebarPane.expanded || !eventListenersSidebarPane.needsUpdate)
983             return;
984
985         eventListenersSidebarPane.update(this.focusedDOMNode);
986         eventListenersSidebarPane.needsUpdate = false;
987     },
988
989     _registerShortcuts: function()
990     {
991         var shortcut = WebInspector.KeyboardShortcut;
992         var section = WebInspector.shortcutsHelp.section(WebInspector.UIString("Elements Panel"));
993         var keys = [
994             shortcut.shortcutToString(shortcut.Keys.Up),
995             shortcut.shortcutToString(shortcut.Keys.Down)
996         ];
997         section.addRelatedKeys(keys, WebInspector.UIString("Navigate elements"));
998         var keys = [
999             shortcut.shortcutToString(shortcut.Keys.Right),
1000             shortcut.shortcutToString(shortcut.Keys.Left)
1001         ];
1002         section.addRelatedKeys(keys, WebInspector.UIString("Expand/collapse"));
1003         section.addKey(shortcut.shortcutToString(shortcut.Keys.Enter), WebInspector.UIString("Edit attribute"));
1004
1005         this.sidebarPanes.styles.registerShortcuts();
1006     },
1007
1008     handleShortcut: function(event)
1009     {
1010         // Cmd/Control + Shift + C should be a shortcut to clicking the Node Search Button.
1011         // This shortcut matches Firebug.
1012         if (event.keyIdentifier === "U+0043") {     // C key
1013             if (WebInspector.isMac())
1014                 var isNodeSearchKey = event.metaKey && !event.ctrlKey && !event.altKey && event.shiftKey;
1015             else
1016                 var isNodeSearchKey = event.ctrlKey && !event.metaKey && !event.altKey && event.shiftKey;
1017
1018             if (isNodeSearchKey) {
1019                 this.toggleSearchingForNode();
1020                 event.handled = true;
1021                 return;
1022             }
1023         }
1024     },
1025
1026     handleCopyEvent: function(event)
1027     {
1028         // Don't prevent the normal copy if the user has a selection.
1029         if (!window.getSelection().isCollapsed)
1030             return;
1031         event.clipboardData.clearData();
1032         event.preventDefault();
1033         DOMAgent.copyNode(this.focusedDOMNode.id);
1034     },
1035
1036     rightSidebarResizerDragStart: function(event)
1037     {
1038         WebInspector.elementDragStart(this.sidebarElement, this.rightSidebarResizerDrag.bind(this), this.rightSidebarResizerDragEnd.bind(this), event, "col-resize");
1039     },
1040
1041     rightSidebarResizerDragEnd: function(event)
1042     {
1043         WebInspector.elementDragEnd(event);
1044         this.saveSidebarWidth();
1045     },
1046
1047     rightSidebarResizerDrag: function(event)
1048     {
1049         var x = event.pageX;
1050         var newWidth = Number.constrain(window.innerWidth - x, Preferences.minElementsSidebarWidth, window.innerWidth * 0.66);
1051         this.setSidebarWidth(newWidth);
1052         event.preventDefault();
1053     },
1054
1055     setSidebarWidth: function(newWidth)
1056     {
1057         this.sidebarElement.style.width = newWidth + "px";
1058         this.contentElement.style.right = newWidth + "px";
1059         this.sidebarResizeElement.style.right = (newWidth - 3) + "px";
1060         this.treeOutline.updateSelection();
1061     },
1062
1063     updateFocusedNode: function(nodeId)
1064     {
1065         var node = WebInspector.domAgent.nodeForId(nodeId);
1066         if (!node)
1067             return;
1068
1069         this.focusedDOMNode = node;
1070         this._nodeSearchButton.toggled = false;
1071     },
1072
1073     _setSearchingForNode: function(enabled)
1074     {
1075         this._nodeSearchButton.toggled = enabled;
1076     },
1077
1078     setSearchingForNode: function(enabled)
1079     {
1080         InspectorAgent.setSearchingForNode(enabled, this._setSearchingForNode.bind(this));
1081     },
1082
1083     toggleSearchingForNode: function()
1084     {
1085         this.setSearchingForNode(!this._nodeSearchButton.toggled);
1086     },
1087
1088     elementsToRestoreScrollPositionsFor: function()
1089     {
1090         return [ this.contentElement, this.sidebarElement ];
1091     }
1092 }
1093
1094 WebInspector.ElementsPanel.prototype.__proto__ = WebInspector.Panel.prototype;