ContextMenuButton.jsx (2031B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this file, 3 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 import React from "react"; 6 7 export class ContextMenuButton extends React.PureComponent { 8 constructor(props) { 9 super(props); 10 this.state = { 11 showContextMenu: false, 12 contextMenuKeyboard: false, 13 }; 14 this.onClick = this.onClick.bind(this); 15 this.onKeyDown = this.onKeyDown.bind(this); 16 this.onUpdate = this.onUpdate.bind(this); 17 } 18 19 openContextMenu(isKeyBoard) { 20 if (this.props.onUpdate) { 21 this.props.onUpdate(true); 22 } 23 this.setState({ 24 showContextMenu: true, 25 contextMenuKeyboard: isKeyBoard, 26 }); 27 } 28 29 onClick(event) { 30 event.preventDefault(); 31 this.openContextMenu(false, event); 32 } 33 34 onKeyDown(event) { 35 if (event.key === "Enter" || event.key === " ") { 36 event.preventDefault(); 37 this.openContextMenu(true, event); 38 } 39 } 40 41 onUpdate(showContextMenu) { 42 if (this.props.onUpdate) { 43 this.props.onUpdate(showContextMenu); 44 } 45 this.setState({ showContextMenu }); 46 } 47 48 render() { 49 const { tooltipArgs, tooltip, children, refFunction } = this.props; 50 const { showContextMenu, contextMenuKeyboard } = this.state; 51 52 return ( 53 <React.Fragment> 54 <button 55 aria-haspopup="menu" 56 aria-expanded={showContextMenu} 57 data-l10n-id={tooltip} 58 data-l10n-args={tooltipArgs ? JSON.stringify(tooltipArgs) : null} 59 className="context-menu-button icon" 60 onKeyDown={this.onKeyDown} 61 onClick={this.onClick} 62 ref={refFunction} 63 tabIndex={this.props.tabIndex || 0} 64 onFocus={this.props.onFocus} 65 /> 66 {showContextMenu 67 ? React.cloneElement(children, { 68 keyboardAccess: contextMenuKeyboard, 69 onUpdate: this.onUpdate, 70 }) 71 : null} 72 </React.Fragment> 73 ); 74 } 75 }