colouring-montreal/app/src/frontend/components/tooltip.tsx

97 lines
2.6 KiB
TypeScript
Raw Normal View History

2018-10-02 16:48:27 -04:00
import React, { Component } from 'react';
2018-09-11 15:59:37 -04:00
2019-11-07 02:39:26 -05:00
import './tooltip.css';
2019-11-13 14:20:47 -05:00
import { InfoIcon } from './icons';
import Markdown from 'markdown-to-jsx';
2019-11-13 14:20:47 -05:00
interface TooltipProps {
text: string;
}
interface TooltipState {
active: boolean;
}
2020-03-23 19:32:10 -04:00
const nonCaptureLingRegex = /\[[^[]+?\]\([^(]+?\)/;
const linkRegex = /\[([^[]+?)\]\(([^(]+?)\)/;
function markdownLinkToAnchor(link: string) {
const m = link.match(linkRegex);
return (<a href={m[2]} target="_blank">{m[1]}</a>);
}
function interweave(arr1: any[], arr2: any[]): any[] {
const commonLen = Math.min(arr1.length, arr2.length);
const arr = [];
for(let i=0; i<commonLen; i++) {
arr.push(arr1[i], arr2[i]);
}
arr.push(...arr1.slice(commonLen), ...arr2.slice(commonLen));
return arr;
}
function tooltipTextToComponents(text: string): any[] {
let betweenLinks = text.split(nonCaptureLingRegex);
if(betweenLinks.length <= 1) return [text];
let links = text.match(new RegExp(linkRegex, 'g')).map(markdownLinkToAnchor);
return interweave(betweenLinks, links);
}
class Tooltip extends Component<TooltipProps, TooltipState> {
2018-10-01 11:59:39 -04:00
constructor(props) {
super(props);
this.state = {
active: false
};
2020-03-23 19:31:33 -04:00
this.toggleVisible = this.toggleVisible.bind(this);
this.handleBlur = this.handleBlur.bind(this);
}
toggleVisible() {
this.setState(state => ({
active: !state.active
}));
2018-10-01 11:59:39 -04:00
}
2018-09-11 15:59:37 -04:00
2020-03-23 19:31:33 -04:00
handleBlur(event) {
if(!event.currentTarget.contains(event.relatedTarget)) {
2020-03-23 19:32:10 -04:00
this.setState({
2020-03-23 19:31:33 -04:00
active: false
2020-03-23 19:32:10 -04:00
});
}
2020-03-23 19:31:33 -04:00
}
2018-10-01 11:59:39 -04:00
render() {
return (
2020-03-23 19:31:33 -04:00
<div className="tooltip-wrap" tabIndex={0} onBlur={this.handleBlur}>
<button type="button" className={(this.state.active? 'active ': '') + 'tooltip-hint icon-button'}
onClick={this.toggleVisible}>
Hint
2018-10-01 12:20:25 -04:00
<InfoIcon />
2018-10-01 11:59:39 -04:00
</button>
{
this.state.active?
2019-05-27 11:39:16 -04:00
(
<div className="tooltip bs-tooltip-bottom">
<div className="arrow"></div>
2020-03-23 19:32:10 -04:00
<div className="tooltip-inner">
<Markdown>
{this.props.text}
</Markdown>
2020-03-23 19:32:10 -04:00
</div>
2019-05-27 11:39:16 -04:00
</div>
)
: null
2018-10-01 11:59:39 -04:00
}
</div>
);
}
}
2019-05-27 13:26:29 -04:00
2018-09-11 15:59:37 -04:00
export default Tooltip;