Bez popisu

index.js 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. input: number | ?View | React$Ref<T>,
  96. optionsObject?: Object
  97. ): Promise<string> {
  98. ensureModuleIsLoaded();
  99. let view;
  100. if (input && typeof input === "object" && "current" in input) {
  101. // $FlowFixMe input is a ref
  102. view = input.current;
  103. if (!view) {
  104. return Promise.reject(new Error("ref.current is null"));
  105. }
  106. }
  107. if (typeof input !== "number") {
  108. const node = findNodeHandle(input);
  109. if (!node) {
  110. return Promise.reject(
  111. new Error("findNodeHandle failed to resolve view=" + String(input))
  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(input, 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: React$Node,
  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. // in that case, it's authorized if you call capture() yourself
  157. } else if (props.captureMode && !props.onCapture) {
  158. console.warn(
  159. "react-native-view-shot: captureMode prop is defined but onCapture prop callback is missing"
  160. );
  161. } else if (
  162. (props.captureMode === "continuous" || props.captureMode === "update") &&
  163. props.options &&
  164. props.options.result &&
  165. props.options.result !== "tmpfile"
  166. ) {
  167. console.warn(
  168. "react-native-view-shot: result=tmpfile is recommended for captureMode=" +
  169. props.captureMode
  170. );
  171. }
  172. }
  173. export default class ViewShot extends Component<Props> {
  174. static captureRef = captureRef;
  175. static releaseCapture = releaseCapture;
  176. root: ?View;
  177. _raf: *;
  178. lastCapturedURI: ?string;
  179. resolveFirstLayout: (layout: Object) => void;
  180. firstLayoutPromise: Promise<Object> = new Promise(resolve => {
  181. this.resolveFirstLayout = resolve;
  182. });
  183. capture = (): Promise<string> =>
  184. this.firstLayoutPromise
  185. .then(() => {
  186. const { root } = this;
  187. if (!root) return neverEndingPromise; // component is unmounted, you never want to hear back from the promise
  188. return captureRef(root, this.props.options);
  189. })
  190. .then(
  191. (uri: string) => {
  192. this.onCapture(uri);
  193. return uri;
  194. },
  195. (e: Error) => {
  196. this.onCaptureFailure(e);
  197. throw e;
  198. }
  199. );
  200. onCapture = (uri: string) => {
  201. if (!this.root) return;
  202. if (this.lastCapturedURI) {
  203. // schedule releasing the previous capture
  204. setTimeout(releaseCapture, 500, this.lastCapturedURI);
  205. }
  206. this.lastCapturedURI = uri;
  207. const { onCapture } = this.props;
  208. if (onCapture) onCapture(uri);
  209. };
  210. onCaptureFailure = (e: Error) => {
  211. if (!this.root) return;
  212. const { onCaptureFailure } = this.props;
  213. if (onCaptureFailure) onCaptureFailure(e);
  214. };
  215. syncCaptureLoop = (captureMode: ?string) => {
  216. cancelAnimationFrame(this._raf);
  217. if (captureMode === "continuous") {
  218. let previousCaptureURI = "-"; // needs to capture at least once at first, so we use "-" arbitrary string
  219. const loop = () => {
  220. this._raf = requestAnimationFrame(loop);
  221. if (previousCaptureURI === this.lastCapturedURI) return; // previous capture has not finished, don't capture yet
  222. previousCaptureURI = this.lastCapturedURI;
  223. this.capture();
  224. };
  225. this._raf = requestAnimationFrame(loop);
  226. }
  227. };
  228. onRef = (ref: React$ElementRef<*>) => {
  229. this.root = ref;
  230. };
  231. onLayout = (e: LayoutEvent) => {
  232. const { onLayout } = this.props;
  233. this.resolveFirstLayout(e.nativeEvent.layout);
  234. if (onLayout) onLayout(e);
  235. };
  236. componentDidMount() {
  237. if (__DEV__) checkCompatibleProps(this.props);
  238. if (this.props.captureMode === "mount") {
  239. this.capture();
  240. } else {
  241. this.syncCaptureLoop(this.props.captureMode);
  242. }
  243. }
  244. componentDidUpdate(prevProps: Props) {
  245. if (this.props.captureMode !== undefined) {
  246. if (this.props.captureMode !== prevProps.captureMode) {
  247. this.syncCaptureLoop(this.props.captureMode);
  248. }
  249. }
  250. if (this.props.captureMode === "update") {
  251. this.capture();
  252. }
  253. }
  254. componentWillUnmount() {
  255. this.syncCaptureLoop(null);
  256. }
  257. render() {
  258. const { children } = this.props;
  259. return (
  260. <View
  261. ref={this.onRef}
  262. collapsable={false}
  263. onLayout={this.onLayout}
  264. style={this.props.style}
  265. >
  266. {children}
  267. </View>
  268. );
  269. }
  270. }