Skip to content

Instantly share code, notes, and snippets.

@RaoHai
Created September 28, 2016 06:58
Show Gist options
  • Save RaoHai/2eaff0be4a28187b80887a3be55de239 to your computer and use it in GitHub Desktop.
Save RaoHai/2eaff0be4a28187b80887a3be55de239 to your computer and use it in GitHub Desktop.
import React from 'react';
import classnames from 'classnames';
import './highlightMenu.less';
function getSelectionClientRect() {
const selection = window.getSelection();
console.log('> getSelectionClientRect', selection.rangeCount, selection.isCollapsed);
if (selection.rangeCount && !selection.isCollapsed ) {
const range = selection.getRangeAt(0).cloneRange();
return range.getBoundingClientRect && range.getBoundingClientRect();
}
return null;
}
function getButtonSet() {
return ['bold', 'italic'].map(item => <button className="highlightMenu-Button">
<i className={`fa fa-${item}`} />
</button>);
}
export default class HighlightMenu extends React.Component {
componentWillReceiveProps() {
this.render();
}
componentDidUpdate() {
const menu = this.refs.menu;
const width = menu.clientWidth;
const height = menu.clientHeight;
const selectRect = getSelectionClientRect();
if (selectRect) {
menu.style.top = `${selectRect.top - height - 8}px`;
menu.style.left = `${selectRect.left + selectRect.width / 2 - width / 2}px`;
}
}
render() {
const { props } = this;
const selectRect = getSelectionClientRect();
const buttonSet = getButtonSet(props);
const highlightMenuCls = classnames({
highlightMenu: true,
active: !!selectRect,
});
return (<div className={highlightMenuCls} ref="menu">
<div className="highlightMenu-inner">{buttonSet}</div>
<div className="highlightMenu-arrowClip">
<span className="highlightMenu-arrow"></span>
</div>
</div>);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment