import React from 'react'; import { Link } from 'react-router-dom' import * as storage from '../../storage' import Bar from '../bar' import numberFormatter from '../../number-formatter' import * as api from '../../api' const MOBILE_UPPER_WIDTH = 767 const DEFAULT_WIDTH = 1080 // https://stackoverflow.com/a/43467144 function isValidHttpUrl(string) { let url; try { url = new URL(string); } catch (_) { return false; } return url.protocol === "http:" || url.protocol === "https:"; } export default class PropertyBreakdown extends React.Component { constructor(props) { super(props) let propKey = props.goal.prop_names[0] this.storageKey = 'goalPropTab__' + props.site.domain + props.goal.name const storedKey = storage.getItem(this.storageKey) if (props.goal.prop_names.includes(storedKey)) { propKey = storedKey } if (props.query.filters['props']) { propKey = Object.keys(props.query.filters['props'])[0] } this.state = { loading: true, propKey: propKey, viewport: DEFAULT_WIDTH, } this.handleResize = this.handleResize.bind(this); } componentDidMount() { window.addEventListener('resize', this.handleResize, false); this.handleResize(); this.fetchPropBreakdown() } componentWillUnmount() { window.removeEventListener('resize', this.handleResize, false); } handleResize() { this.setState({ viewport: window.innerWidth }); } getBarMaxWidth() { const { viewport } = this.state; return viewport > MOBILE_UPPER_WIDTH ? "16rem" : "10rem"; } fetchPropBreakdown() { if (this.props.query.filters['goal']) { api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/property/${encodeURIComponent(this.state.propKey)}`, this.props.query) .then((res) => this.setState({loading: false, breakdown: res})) } } renderUrl(value) { if (isValidHttpUrl(value.name)) { return ( ) } return null } renderPropContent(value, query) { return ( { value.name } { this.renderUrl(value) } ) } renderPropValue(value) { const query = new URLSearchParams(window.location.search) query.set('props', JSON.stringify({[this.state.propKey]: value.name})) const { viewport } = this.state; return (