XLink.js 2.2 KB

1234567891011121314151617
  1. export default class XLink extends UI.XElement{static create(url,linkText,className,preventClick){if(!linkText){linkText=url;}
  2. className=className||'';return UI.html`
  3. <x-link href='${url}' class='${className} devtools-link' ${preventClick ? 'no-click' : ''}
  4. >${linkText.trimMiddle(UI.MaxLengthForDisplayedURLs)}</x-link>`;}
  5. constructor(){super();this.style.setProperty('display','inline');UI.ARIAUtils.markAsLink(this);this.tabIndex=0;this.target='_blank';this.rel='noopener';this._href=null;this._clickable=true;this._onClick=event=>{event.consume(true);Host.InspectorFrontendHost.openInNewTab((this._href));};this._onKeyDown=event=>{if(isEnterOrSpaceKey(event)){event.consume(true);Host.InspectorFrontendHost.openInNewTab((this._href));}};}
  6. static get observedAttributes(){return UI.XElement.observedAttributes.concat(['href','no-click']);}
  7. attributeChangedCallback(attr,oldValue,newValue){if(attr==='no-click'){this._clickable=!newValue;this._updateClick();return;}
  8. if(attr==='href'){if(!newValue){newValue='';}
  9. let href=null;let url=null;try{url=new URL(newValue);href=url.toString();}catch(error){}
  10. if(url&&url.protocol==='javascript:'){href=null;}
  11. this._href=href;this.title=newValue;this._updateClick();return;}
  12. super.attributeChangedCallback(attr,oldValue,newValue);}
  13. _updateClick(){if(this._href!==null&&this._clickable){this.addEventListener('click',this._onClick,false);this.addEventListener('keydown',this._onKeyDown,false);this.style.setProperty('cursor','pointer');}else{this.removeEventListener('click',this._onClick,false);this.removeEventListener('keydown',this._onKeyDown,false);this.style.removeProperty('cursor');}}}
  14. export class ContextMenuProvider{appendApplicableItems(event,contextMenu,target){let targetNode=(target);while(targetNode&&!(targetNode instanceof XLink)){targetNode=targetNode.parentNodeOrShadowHost();}
  15. if(!targetNode||!targetNode._href){return;}
  16. contextMenu.revealSection().appendItem(UI.openLinkExternallyLabel(),()=>Host.InspectorFrontendHost.openInNewTab(targetNode._href));contextMenu.revealSection().appendItem(UI.copyLinkAddressLabel(),()=>Host.InspectorFrontendHost.copyText(targetNode._href));}}
  17. self.customElements.define('x-link',XLink);self.UI=self.UI||{};UI=UI||{};UI.XLink=XLink;UI.XLink.ContextMenuProvider=ContextMenuProvider;