|
| 1 | +import * as React from "react"; |
| 2 | +import renderProp from "../util/renderProp"; |
| 3 | +import { IUniversalInterfaceProps } from "../typing"; |
| 4 | + |
| 5 | +export interface DocumentTouchConstructor extends Document { |
| 6 | + [key: string]: any; |
| 7 | + new (): DocumentTouchConstructor; |
| 8 | + readonly prototype: Document; |
| 9 | +} |
| 10 | + |
| 11 | +export interface TouchWindow extends Window { |
| 12 | + DocumentTouch?: DocumentTouchConstructor; |
| 13 | +} |
| 14 | + |
| 15 | +let DocumentTouch: DocumentTouchConstructor; |
| 16 | + |
| 17 | +export interface ITouchSupportSensorState { |
| 18 | + touchSupported: boolean; |
| 19 | +} |
| 20 | + |
| 21 | +export interface ITouchSupportSensorProps |
| 22 | + extends IUniversalInterfaceProps<ITouchSupportSensorState> { |
| 23 | + onlyTouch?: boolean; |
| 24 | + onlyMouse?: boolean; |
| 25 | +} |
| 26 | + |
| 27 | +export const touchSupported = () => { |
| 28 | + const prefixes = " -webkit- -moz- -o- -ms- ".split(" "); |
| 29 | + // include the 'heartz' as a way to have a non matching MQ to help terminate the join |
| 30 | + // https://git.io/vznFH |
| 31 | + const query = ["(", prefixes.join("touch-enabled),("), "heartz", ")"].join( |
| 32 | + "" |
| 33 | + ); |
| 34 | + |
| 35 | + if ( |
| 36 | + "ontouchstart" in window || |
| 37 | + ((window as TouchWindow).DocumentTouch && document instanceof DocumentTouch) |
| 38 | + ) { |
| 39 | + return true; |
| 40 | + } |
| 41 | + |
| 42 | + // TypeScript seems to think "ontouchstart" will always be on window, causing incorrect type narrowing |
| 43 | + return (window as Window).matchMedia(query).matches; |
| 44 | +}; |
| 45 | + |
| 46 | +export class TouchSupportSensor extends React.Component< |
| 47 | + ITouchSupportSensorProps, |
| 48 | + ITouchSupportSensorState |
| 49 | +> { |
| 50 | + constructor(props, context) { |
| 51 | + super(props, context); |
| 52 | + |
| 53 | + if (props.onlyMouse && props.onlyTouch) { |
| 54 | + console.warn( |
| 55 | + "You're using both `onlyMouse` and `onlyTouch` on the TouchSupportSensor component. This is unsupported and may lead to unexpected results." |
| 56 | + ); |
| 57 | + } |
| 58 | + |
| 59 | + this.state = { touchSupported: touchSupported() }; |
| 60 | + } |
| 61 | + |
| 62 | + render() { |
| 63 | + if (this.props.onlyMouse && this.state.touchSupported) { |
| 64 | + return null; |
| 65 | + } |
| 66 | + |
| 67 | + if (this.props.onlyTouch && !this.state.touchSupported) { |
| 68 | + return null; |
| 69 | + } |
| 70 | + |
| 71 | + return renderProp(this.props, this.state); |
| 72 | + } |
| 73 | +} |
0 commit comments