index.js 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. type Props = {
  108. options?: Object,
  109. captureMode?: "mount" | "continuous" | "update",
  110. children: React.Element<*>,
  111. onLayout?: (e: *) => void,
  112. onCapture: (uri: string) => void,
  113. onCaptureFailure: (e: Error) => void
  114. };
  115. function checkCompatibleProps(props: Props) {
  116. if (!props.captureMode && props.onCapture) {
  117. console.warn(
  118. "react-native-view-shot: a captureMode prop must be provided for `onCapture`"
  119. );
  120. } else if (props.captureMode && !props.onCapture) {
  121. console.warn(
  122. "react-native-view-shot: captureMode prop is defined but onCapture prop callback is missing"
  123. );
  124. } else if (
  125. (props.captureMode === "continuous" || props.captureMode === "update") &&
  126. props.options &&
  127. props.options.result &&
  128. props.options.result !== "tmpfile"
  129. ) {
  130. console.warn(
  131. "react-native-view-shot: result=tmpfile is recommended for captureMode=" +
  132. props.captureMode
  133. );
  134. }
  135. }
  136. export default class ViewShot extends Component {
  137. static captureRef = captureRef;
  138. static releaseCapture = releaseCapture;
  139. props: Props;
  140. root: ?View;
  141. _raf: *;
  142. lastCapturedURI: ?string;
  143. resolveFirstLayout: (layout: Object) => void;
  144. firstLayoutPromise = new Promise(resolve => {
  145. this.resolveFirstLayout = resolve;
  146. });
  147. capture = (): Promise<string> =>
  148. this.firstLayoutPromise
  149. .then(() => {
  150. const { root } = this;
  151. if (!root) return neverEndingPromise; // component is unmounted, you never want to hear back from the promise
  152. return captureRef(root, this.props.options);
  153. })
  154. .then(
  155. (uri: string) => {
  156. this.onCapture(uri);
  157. return uri;
  158. },
  159. (e: Error) => {
  160. this.onCaptureFailure(e);
  161. throw e;
  162. }
  163. );
  164. onCapture = (uri: string) => {
  165. if (!this.root) return;
  166. if (this.lastCapturedURI) {
  167. // schedule releasing the previous capture
  168. setTimeout(releaseCapture, 500, this.lastCapturedURI);
  169. }
  170. this.lastCapturedURI = uri;
  171. const { onCapture } = this.props;
  172. if (onCapture) onCapture(uri);
  173. };
  174. onCaptureFailure = (e: Error) => {
  175. if (!this.root) return;
  176. const { onCaptureFailure } = this.props;
  177. if (onCaptureFailure) onCaptureFailure(e);
  178. };
  179. syncCaptureLoop = (captureMode: ?string) => {
  180. cancelAnimationFrame(this._raf);
  181. if (captureMode === "continuous") {
  182. let previousCaptureURI = "-"; // needs to capture at least once at first, so we use "-" arbitrary string
  183. const loop = () => {
  184. this._raf = requestAnimationFrame(loop);
  185. if (previousCaptureURI === this.lastCapturedURI) return; // previous capture has not finished, don't capture yet
  186. previousCaptureURI = this.lastCapturedURI;
  187. this.capture();
  188. };
  189. this._raf = requestAnimationFrame(loop);
  190. }
  191. };
  192. onRef = (ref: View) => {
  193. this.root = ref;
  194. };
  195. onLayout = (e: { nativeEvent: { layout: Object } }) => {
  196. const { onLayout } = this.props;
  197. this.resolveFirstLayout(e.nativeEvent.layout);
  198. if (onLayout) onLayout(e);
  199. };
  200. componentDidMount() {
  201. if (__DEV__) checkCompatibleProps(this.props);
  202. if (this.props.captureMode === "mount") {
  203. this.capture();
  204. } else {
  205. this.syncCaptureLoop(this.props.captureMode);
  206. }
  207. }
  208. componentWillReceiveProps(nextProps: Props) {
  209. if (nextProps.captureMode !== this.props.captureMode) {
  210. this.syncCaptureLoop(nextProps.captureMode);
  211. }
  212. }
  213. componentDidUpdate() {
  214. if (this.props.captureMode === "update") {
  215. this.capture();
  216. }
  217. }
  218. componentWillUnmount() {
  219. this.syncCaptureLoop(null);
  220. }
  221. render() {
  222. const { children } = this.props;
  223. return (
  224. <View ref={this.onRef} collapsable={false} onLayout={this.onLayout}>
  225. {children}
  226. </View>
  227. );
  228. }
  229. }