@formidable-webview/webshell
Version:
🔥 Craft Robust React Native WebView-based components with ease.
277 lines (239 loc) • 15.6 kB
JavaScript
;
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = useAutoheight;
var React = _interopRequireWildcard(require("react"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var initialDimensions = {
width: undefined,
height: undefined
};
var overridenWebViewProps = {
scalesPageToFit: false,
showsVerticalScrollIndicator: false,
disableScrollViewPanResponder: true,
contentMode: 'mobile'
};
var overridenWebViewKeys = Object.keys(overridenWebViewProps);
/**
* The state of synchronization between viewport and content size:
*
* - `init`: the initial state;
* - `syncing`: the content size is being determined;
* - `synced`: the viewport size has been adjusted to content size.
*
* @public
*/
var initialState = {
implementation: null,
contentSize: initialDimensions,
syncState: 'init',
lastFrameChangedWidth: false,
viewportWidth: 0
};
function useDevFeedbackEffect(_ref) {
var webshellProps = _ref.autoHeightParams.webshellProps,
_ref$state = _ref.state,
implementation = _ref$state.implementation,
_ref$state$contentSiz = _ref$state.contentSize,
width = _ref$state$contentSiz.width,
height = _ref$state$contentSiz.height;
var numberOfEventsRef = React.useRef(0);
var webshellDebug = webshellProps.webshellDebug;
var forbiddenWebViewProps = overridenWebViewKeys.map(function (key) {
return [key, webshellProps[key]];
}).reduce(function (prev, _ref2) {
var _ref3 = _slicedToArray(_ref2, 2),
key = _ref3[0],
value = _ref3[1];
prev[key] = value;
return prev;
}, {});
React.useEffect(function warnOverridenProps() {
var _iterator = _createForOfIteratorHelper(overridenWebViewKeys),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var forbiddenKey = _step.value;
if (forbiddenWebViewProps[forbiddenKey] !== undefined && forbiddenWebViewProps[forbiddenKey] !== overridenWebViewProps[forbiddenKey]) {
console.warn("".concat(useAutoheight.name, ": You cannot set \"").concat(forbiddenKey, "\" prop to \"").concat(webshellProps[forbiddenKey], "\" with autoheight hook. The value will be overriden to \"").concat(overridenWebViewProps[forbiddenKey], "\"."));
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}, // eslint-disable-next-line react-hooks/exhaustive-deps
[webshellDebug].concat(_toConsumableArray(Object.values(forbiddenWebViewProps))));
React.useEffect(function debugDOMHTMLDimensions() {
webshellDebug && console.info("".concat(useAutoheight.name, ": DOMHTMLDimensions event #").concat(++numberOfEventsRef.current, " (implementation: ").concat(implementation, ", content width: ").concat(width, ", content height: ").concat(height, ")"));
}, [webshellDebug, implementation, height, width]);
}
function useAutoheightState(autoHeightParams) {
var webshellProps = autoHeightParams.webshellProps,
initialHeight = autoHeightParams.initialHeight;
var _webshellProps$source = webshellProps.source,
source = _webshellProps$source === void 0 ? {} : _webshellProps$source,
webshellDebug = webshellProps.webshellDebug;
var _React$useState = React.useState(initialState),
_React$useState2 = _slicedToArray(_React$useState, 2),
state = _React$useState2[0],
setState = _React$useState2[1];
if (__DEV__) {
// eslint-disable-next-line react-hooks/rules-of-hooks
useDevFeedbackEffect({
autoHeightParams: autoHeightParams,
state: state
});
}
React.useEffect(function resetHeightOnSourceChanges() {
setState(function (_ref4) {
var contentSize = _ref4.contentSize,
viewportWidth = _ref4.viewportWidth;
return {
viewportWidth: viewportWidth,
contentSize: {
height: undefined,
width: contentSize.width
},
implementation: null,
syncState: 'syncing',
lastFrameChangedWidth: false
};
});
__DEV__ && webshellDebug && console.info("".concat(useAutoheight.name, ": source change detected, resetting height to ").concat(initialHeight, "dp."));
}, [source.uri, source.html, webshellDebug, initialHeight]);
if (__DEV__) {}
return {
state: state,
setState: setState
};
}
/**
*
* This hook will provide props to inject in a shell component to implement an "autoheight" behavior.
* It requires {@link HandleHTMLDimensionsFeature} to have be instantiated in the shell.
* Also recommend (see remarks):
*
* - {@link ForceElementSizeFeature},
* - {@link ForceResponsiveViewportFeature}.
*
* @remarks
* This hook has caveats you must understand:
*
* - Because the viewport height is now bound to the content heigh, you cannot
* and must not have an element which height depends on viewport, such as
* when using `vh` unit or `height: 100%;` on body. That will either create
* an infinite loop, or a zero-height page (this happens for Wikipedia).
* Hence, it is strongly advised that you use autoheight only with content
* you have been able to test. This can be worked around by forcing body
* height to 'auto', see {@link ForceElementSizeFeature}.
* - In some circumstances, the mobile browser might use a virtual
* viewport much larger then the available width in the `<WebView />`, often
* around 980px for websites which have been built for desktop. For
* this autoheight component to be reliable, you must ensure that the
* content has a [meta viewport element](https://www.w3schools.com/css/css_rwd_viewport.asp)
* in the header. You can enforce this behavior with {@link ForceResponsiveViewportFeature}.
*
* @example
*
* ```tsx
* export default function MinimalAutoheightWebView(
* webshellProps: ComponentProps<typeof Webshell>
* ) {
* const { autoheightWebshellProps } = useAutoheight({
* webshellProps
* });
* return <Webshell {...autoheightWebshellProps} />;
* }
* ```
*
* @param params - The parameters to specify autoheight behavior.
* @typeparam S - The type of the `Webshell` props used by this hook.
* @returns - An object to implement autoheight behavior.
*
* @public
*/
function useAutoheight(params) {
var webshellProps = params.webshellProps,
_params$initialHeight = params.initialHeight,
initialHeight = _params$initialHeight === void 0 ? 0 : _params$initialHeight,
userExplicitWidth = params.width,
_params$resetHeightOn = params.resetHeightOnViewportWidthChange,
resetHeightOnViewportWidthChange = _params$resetHeightOn === void 0 ? true : _params$resetHeightOn;
var style = webshellProps.style,
onNavigationStateChange = webshellProps.onNavigationStateChange,
scalesPageToFit = webshellProps.scalesPageToFit,
webshellDebug = webshellProps.webshellDebug,
onDOMHTMLDimensions = webshellProps.onDOMHTMLDimensions,
passedProps = _objectWithoutProperties(webshellProps, ["style", "onNavigationStateChange", "scalesPageToFit", "webshellDebug", "onDOMHTMLDimensions"]);
var _useAutoheightState = useAutoheightState(params),
state = _useAutoheightState.state,
setState = _useAutoheightState.setState;
var height = state.contentSize.height,
implementation = state.implementation,
lastFrameChangedWidth = state.lastFrameChangedWidth;
var shouldReinitNextFrameHeight = typeof userExplicitWidth !== 'number' && lastFrameChangedWidth && resetHeightOnViewportWidthChange;
var handleOnDOMHTMLDimensions = React.useCallback(function handleOnDOMHTMLDimensions(htmlDimensions) {
setState(function (prevState) {
return {
viewportWidth: htmlDimensions.layoutViewport.width,
implementation: htmlDimensions.implementation,
contentSize: htmlDimensions.content,
syncState: 'synced',
lastFrameChangedWidth: prevState.viewportWidth !== htmlDimensions.layoutViewport.width
};
});
typeof onDOMHTMLDimensions === 'function' && onDOMHTMLDimensions(htmlDimensions);
}, [setState, onDOMHTMLDimensions]);
var autoHeightStyle = React.useMemo(function () {
return [style, {
width: typeof userExplicitWidth === 'number' ? userExplicitWidth : '100%',
height: shouldReinitNextFrameHeight ? undefined : typeof height === 'number' ? height : initialHeight,
alignSelf: 'stretch'
}];
}, [height, userExplicitWidth, initialHeight, style, shouldReinitNextFrameHeight]);
React.useEffect(function resetLastFrameChangedWidth() {
var timeout = setTimeout(function () {
return setState(function (prevState) {
return _objectSpread(_objectSpread({}, prevState), {}, {
lastFrameChangedWidth: false
});
});
}, 50);
return function () {
return clearTimeout(timeout);
};
}, [shouldReinitNextFrameHeight, setState]);
return {
autoheightWebshellProps: _objectSpread(_objectSpread({}, passedProps), {}, {
webshellDebug: webshellDebug,
onDOMHTMLDimensions: handleOnDOMHTMLDimensions,
style: autoHeightStyle
}, overridenWebViewProps),
resizeImplementation: implementation,
contentSize: state.contentSize,
syncState: state.syncState
};
}
//# sourceMappingURL=useAutoheight.js.map