UNPKG

rn-pixel-perfect

Version:

A simple tool for pixel-perfect layouts, allowing you to compare design screens with your app's implementation.

95 lines (94 loc) 3.55 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { useState, useEffect, useMemo, useCallback, useRef } from 'react'; import { Image, Dimensions, ScrollView } from 'react-native'; import Constants from 'expo-constants'; export var validateMessage = function (data) { try { var parsed = JSON.parse(String(data)); if ('type' in parsed && typeof parsed.type === 'string') return parsed; return null; } catch (_a) { return null; } }; var getHost = function (userHost) { var _a; if (userHost) return userHost; if (!((_a = Constants.expoConfig) === null || _a === void 0 ? void 0 : _a.hostUri)) return 'localhost'; var host = Constants.expoConfig.hostUri.split(':')[0]; return host; }; var ImgStyle = { width: '100%', }; export var Overlay = function (_a) { var host = _a.host, port = _a.port; var _b = useState(null), img = _b[0], setImg = _b[1]; var _c = useState(0.6), opacity = _c[0], setOpacity = _c[1]; var _d = useState(false), hidden = _d[0], setHidden = _d[1]; var _e = useState(false), scroll = _e[0], setScroll = _e[1]; var scrollRef = useRef(null); var onSetImage = useCallback(function (msg) { // Use the callback form of getSize, not the promise form: the latter only // exists in react-native >= 0.75 (callback-only below that). Image.getSize(msg.image, function (width, height) { var screenWidth = Dimensions.get('screen').width; setImg({ src: msg.image, height: height / (width / screenWidth) }); }); }, []); useEffect(function () { var ws = new WebSocket("ws://".concat(getHost(host), ":").concat(port !== null && port !== void 0 ? port : 3210)); ws.onopen = function () { var _a; ws.send(JSON.stringify({ type: 'register', name: (_a = Constants.deviceName) !== null && _a !== void 0 ? _a : 'Unknown', })); }; ws.onmessage = function (e) { var msg = validateMessage(e.data); switch (msg === null || msg === void 0 ? void 0 : msg.type) { case 'setImage': { return onSetImage(msg); } case 'changeOpacity': return setOpacity(function (value) { return Math.min(Math.max(value + msg.value, 0), 1); }); case 'setHidden': return setHidden(msg.value); case 'setScroll': return setScroll(msg.value); case undefined: { throw new Error('Not implemented yet: undefined case'); } } }; ws.onerror = function (e) { console.error('rn-pixel-perfect', e); }; ws.onclose = function () { setImg(null); }; return function () { ws.close(); }; }, [port, host, onSetImage]); var style = useMemo(function () { return ({ position: 'absolute', top: 0, width: '100%', height: '100%', opacity: opacity, pointerEvents: scroll ? undefined : 'none', }); }, [opacity, scroll]); if (!img || hidden) return null; return (_jsx(ScrollView, { ref: scrollRef, style: style, children: _jsx(Image, { style: [ImgStyle, { height: img.height }], source: { uri: img.src } }) })); };