index.js 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. //@flow
  2. import React, { Component } from "react";
  3. import { View, NativeModules, Platform, findNodeHandle } from "react-native";
  4. const { RNViewShot } = NativeModules;
  5. import type { Element, ElementRef, ElementType, Ref } from "react";
  6. import type { ViewStyleProp } from "StyleSheet";
  7. import type { LayoutEvent } from "CoreEventTypes";
  8. const neverEndingPromise = new Promise(() => {});
  9. type Options = {
  10. width?: number,
  11. height?: number,
  12. format: "png" | "jpg" | "webm" | "raw",
  13. quality: number,
  14. result: "tmpfile" | "base64" | "data-uri" | "zip-base64",
  15. snapshotContentContainer: boolean
  16. };
  17. if (!RNViewShot) {
  18. console.warn(
  19. "react-native-view-shot: NativeModules.RNViewShot is undefined. Make sure the library is linked on the native side."
  20. );
  21. }
  22. const acceptedFormats = ["png", "jpg"].concat(
  23. Platform.OS === "android" ? ["webm", "raw"] : []
  24. );
  25. const acceptedResults = ["tmpfile", "base64", "data-uri"].concat(
  26. Platform.OS === "android" ? ["zip-base64"] : []
  27. );
  28. const defaultOptions = {
  29. format: "png",
  30. quality: 1,
  31. result: "tmpfile",
  32. snapshotContentContainer: false
  33. };
  34. // validate and coerce options
  35. function validateOptions(
  36. options: ?Object
  37. ): { options: Options, errors: Array<string> } {
  38. options = {
  39. ...defaultOptions,
  40. ...options
  41. };
  42. const errors = [];
  43. if (
  44. "width" in options &&
  45. (typeof options.width !== "number" || options.width <= 0)
  46. ) {
  47. errors.push("option width should be a positive number");
  48. delete options.width;
  49. }
  50. if (
  51. "height" in options &&
  52. (typeof options.height !== "number" || options.height <= 0)
  53. ) {
  54. errors.push("option height should be a positive number");
  55. delete options.height;
  56. }
  57. if (
  58. typeof options.quality !== "number" ||
  59. options.quality < 0 ||
  60. options.quality > 1
  61. ) {
  62. errors.push("option quality should be a number between 0.0 and 1.0");
  63. options.quality = defaultOptions.quality;
  64. }
  65. if (typeof options.snapshotContentContainer !== "boolean") {
  66. errors.push("option snapshotContentContainer should be a boolean");
  67. }
  68. if (acceptedFormats.indexOf(options.format) === -1) {
  69. options.format = defaultOptions.format;
  70. errors.push(
  71. "option format '" +
  72. options.format +
  73. "' is not in valid formats: " +
  74. acceptedFormats.join(" | ")
  75. );
  76. }
  77. if (acceptedResults.indexOf(options.result) === -1) {
  78. options.result = defaultOptions.result;
  79. errors.push(
  80. "option result '" +
  81. options.result +
  82. "' is not in valid formats: " +
  83. acceptedResults.join(" | ")
  84. );
  85. }
  86. return { options, errors };
  87. }
  88. export function ensureModuleIsLoaded() {
  89. if (!RNViewShot) {
  90. throw new Error(
  91. "react-native-view-shot: NativeModules.RNViewShot is undefined. Make sure the library is linked on the native side."
  92. );
  93. }
  94. }
  95. export function captureRef<T: ElementType>(
  96. view: number | ?View | Ref<T>,
  97. optionsObject?: Object
  98. ): Promise<string> {
  99. ensureModuleIsLoaded();
  100. if (view && typeof view === "object" && "current" in view && view.current) {
  101. // React.RefObject
  102. view = view.current;
  103. if (!view) {
  104. return Promise.reject(new Error("ref.current is null"));
  105. }
  106. }
  107. if (typeof view !== "number") {
  108. const node = findNodeHandle(view);
  109. if (!node) {
  110. return Promise.reject(
  111. new Error("findNodeHandle failed to resolve view=" + String(view))
  112. );
  113. }
  114. view = node;
  115. }
  116. const { options, errors } = validateOptions(optionsObject);
  117. if (__DEV__ && errors.length > 0) {
  118. console.warn(
  119. "react-native-view-shot: bad options:\n" +
  120. errors.map(e => `- ${e}`).join("\n")
  121. );
  122. }
  123. return RNViewShot.captureRef(view, options);
  124. }
  125. export function releaseCapture(uri: string): void {
  126. if (typeof uri !== "string") {
  127. if (__DEV__) {
  128. console.warn("Invalid argument to releaseCapture. Got: " + uri);
  129. }
  130. } else {
  131. RNViewShot.releaseCapture(uri);
  132. }
  133. }
  134. export function captureScreen(optionsObject?: Options): Promise<string> {
  135. ensureModuleIsLoaded();
  136. const { options, errors } = validateOptions(optionsObject);
  137. if (__DEV__ && errors.length > 0) {
  138. console.warn(
  139. "react-native-view-shot: bad options:\n" +
  140. errors.map(e => `- ${e}`).join("\n")
  141. );
  142. }
  143. return RNViewShot.captureScreen(options);
  144. }
  145. type Props = {
  146. options?: Object,
  147. captureMode?: "mount" | "continuous" | "update",
  148. children: Element<*>,
  149. onLayout?: (e: *) => void,
  150. onCapture?: (uri: string) => void,
  151. onCaptureFailure?: (e: Error) => void,
  152. style?: ViewStyleProp
  153. };
  154. function checkCompatibleProps(props: Props) {
  155. if (!props.captureMode && props.onCapture) {
  156. console.warn(
  157. "react-native-view-shot: a captureMode prop must be provided for `onCapture`"
  158. );
  159. } else if (props.captureMode && !props.onCapture) {
  160. console.warn(
  161. "react-native-view-shot: captureMode prop is defined but onCapture prop callback is missing"
  162. );
  163. } else if (
  164. (props.captureMode === "continuous" || props.captureMode === "update") &&
  165. props.options &&
  166. props.options.result &&
  167. props.options.result !== "tmpfile"
  168. ) {
  169. console.warn(
  170. "react-native-view-shot: result=tmpfile is recommended for captureMode=" +
  171. props.captureMode
  172. );
  173. }
  174. }
  175. export default class ViewShot extends Component<Props> {
  176. static captureRef = captureRef;
  177. static releaseCapture = releaseCapture;
  178. constructor(props) {
  179. super(props);
  180. this.state = {};
  181. }
  182. root: ?View;
  183. _raf: *;
  184. lastCapturedURI: ?string;
  185. resolveFirstLayout: (layout: Object) => void;
  186. firstLayoutPromise = new Promise(resolve => {
  187. this.resolveFirstLayout = resolve;
  188. });
  189. capture = (): Promise<string> =>
  190. this.firstLayoutPromise
  191. .then(() => {
  192. const { root } = this;
  193. if (!root) return neverEndingPromise; // component is unmounted, you never want to hear back from the promise
  194. return captureRef(root, this.props.options);
  195. })
  196. .then(
  197. (uri: string) => {
  198. this.onCapture(uri);
  199. return uri;
  200. },
  201. (e: Error) => {
  202. this.onCaptureFailure(e);
  203. throw e;
  204. }
  205. );
  206. onCapture = (uri: string) => {
  207. if (!this.root) return;
  208. if (this.lastCapturedURI) {
  209. // schedule releasing the previous capture
  210. setTimeout(releaseCapture, 500, this.lastCapturedURI);
  211. }
  212. this.lastCapturedURI = uri;
  213. const { onCapture } = this.props;
  214. if (onCapture) onCapture(uri);
  215. };
  216. onCaptureFailure = (e: Error) => {
  217. if (!this.root) return;
  218. const { onCaptureFailure } = this.props;
  219. if (onCaptureFailure) onCaptureFailure(e);
  220. };
  221. syncCaptureLoop = (captureMode: ?string) => {
  222. cancelAnimationFrame(this._raf);
  223. if (captureMode === "continuous") {
  224. let previousCaptureURI = "-"; // needs to capture at least once at first, so we use "-" arbitrary string
  225. const loop = () => {
  226. this._raf = requestAnimationFrame(loop);
  227. if (previousCaptureURI === this.lastCapturedURI) return; // previous capture has not finished, don't capture yet
  228. previousCaptureURI = this.lastCapturedURI;
  229. this.capture();
  230. };
  231. this._raf = requestAnimationFrame(loop);
  232. }
  233. };
  234. onRef = (ref: ElementRef<*>) => {
  235. this.root = ref;
  236. };
  237. onLayout = (e: LayoutEvent) => {
  238. const { onLayout } = this.props;
  239. this.resolveFirstLayout(e.nativeEvent.layout);
  240. if (onLayout) onLayout(e);
  241. };
  242. componentDidMount() {
  243. if (__DEV__) checkCompatibleProps(this.props);
  244. if (this.props.captureMode === "mount") {
  245. this.capture();
  246. } else {
  247. this.syncCaptureLoop(this.props.captureMode);
  248. }
  249. }
  250. componentDidUpdate(prevProps) {
  251. if (this.props.captureMode !== undefined) {
  252. if (this.props.captureMode !== prevProps.captureMode) {
  253. this.syncCaptureLoop(this.props.captureMode);
  254. }
  255. }
  256. if (this.props.captureMode === "update") {
  257. this.capture();
  258. }
  259. }
  260. componentWillUnmount() {
  261. this.syncCaptureLoop(null);
  262. }
  263. render() {
  264. const { children } = this.props;
  265. return (
  266. <View
  267. ref={this.onRef}
  268. collapsable={false}
  269. onLayout={this.onLayout}
  270. style={this.props.style}
  271. >
  272. {children}
  273. </View>
  274. );
  275. }
  276. }