index.js 8.1KB

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