UNPKG

@tamagui/react-native-web-lite

Version:
79 lines (78 loc) 2.52 kB
import { canUseDOM, invariant } from "@tamagui/react-native-web-internals"; const initialURL = canUseDOM ? window.location.href : ""; class Linking { /** * An object mapping of event name * and all the callbacks subscribing to it */ _eventCallbacks = {}; _dispatchEvent(event, ...data) { const listeners = this._eventCallbacks[event]; if (listeners != null && Array.isArray(listeners)) { listeners.map(listener => { listener(...data); }); } } /** * Adds a event listener for the specified event. The callback will be called when the * said event is dispatched. */ addEventListener = (event, callback) => { if (!this._eventCallbacks[event]) { this._eventCallbacks[event] = [callback]; return; } this._eventCallbacks[event].push(callback); }; /** * Removes a previously added event listener for the specified event. The callback must * be the same object as the one passed to `addEventListener`. */ removeEventListener = (event, callback) => { const callbacks = this._eventCallbacks[event]; const filteredCallbacks = callbacks.filter(c => c.toString() !== callback.toString()); this._eventCallbacks[event] = filteredCallbacks; }; canOpenURL() { return Promise.resolve(true); } getInitialURL() { return Promise.resolve(initialURL); } /** * Try to open the given url in a secure fashion. The method returns a Promise object. * If a target is passed (including undefined) that target will be used, otherwise '_blank'. * If the url opens, the promise is resolved. If not, the promise is rejected. * Dispatches the `onOpen` event if `url` is opened successfully. */ openURL(url, target) { if (arguments.length === 1) { target = "_blank"; } try { open(url, target); this._dispatchEvent("onOpen", url); return Promise.resolve(); } catch (e) { return Promise.reject(e); } } _validateURL(url) { invariant(typeof url === "string", "Invalid URL: should be a string. Was: " + url); invariant(url, "Invalid URL: cannot be empty"); } } const open = (url, target) => { if (canUseDOM) { const urlToOpen = new URL(url, window.location).toString(); if (urlToOpen.indexOf("tel:") === 0) { window.location = urlToOpen; } else { window.open(urlToOpen, target, "noopener"); } } }; const LinkingInstance = new Linking(); export { LinkingInstance as Linking }; //# sourceMappingURL=index.mjs.map