index.js 7.0KB

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