説明なし

index.js 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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 "react-native/Libraries/StyleSheet/StyleSheet";
  7. import type { LayoutEvent } from "react-native/Libraries/Types/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. input: ?$Shape<Options>
  37. ): { options: Options, errors: Array<string> } {
  38. const options: Options = {
  39. ...defaultOptions,
  40. ...input
  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. input: number | ?View | Ref<T>,
  97. optionsObject?: Object
  98. ): Promise<string> {
  99. ensureModuleIsLoaded();
  100. let view;
  101. if (input && typeof input === "object" && "current" in input) {
  102. // $FlowFixMe input is a ref
  103. view = input.current;
  104. if (!view) {
  105. return Promise.reject(new Error("ref.current is null"));
  106. }
  107. }
  108. if (typeof input !== "number") {
  109. const node = findNodeHandle(input);
  110. if (!node) {
  111. return Promise.reject(
  112. new Error("findNodeHandle failed to resolve view=" + String(input))
  113. );
  114. }
  115. view = node;
  116. }
  117. const { options, errors } = validateOptions(optionsObject);
  118. if (__DEV__ && errors.length > 0) {
  119. console.warn(
  120. "react-native-view-shot: bad options:\n" +
  121. errors.map(e => `- ${e}`).join("\n")
  122. );
  123. }
  124. return RNViewShot.captureRef(input, options);
  125. }
  126. export function releaseCapture(uri: string): void {
  127. if (typeof uri !== "string") {
  128. if (__DEV__) {
  129. console.warn("Invalid argument to releaseCapture. Got: " + uri);
  130. }
  131. } else {
  132. RNViewShot.releaseCapture(uri);
  133. }
  134. }
  135. export function captureScreen(optionsObject?: Options): Promise<string> {
  136. ensureModuleIsLoaded();
  137. const { options, errors } = validateOptions(optionsObject);
  138. if (__DEV__ && errors.length > 0) {
  139. console.warn(
  140. "react-native-view-shot: bad options:\n" +
  141. errors.map(e => `- ${e}`).join("\n")
  142. );
  143. }
  144. return RNViewShot.captureScreen(options);
  145. }
  146. type Props = {
  147. options?: Object,
  148. captureMode?: "mount" | "continuous" | "update",
  149. children: Element<*>,
  150. onLayout?: (e: *) => void,
  151. onCapture?: (uri: string) => void,
  152. onCaptureFailure?: (e: Error) => void,
  153. style?: ViewStyleProp
  154. };
  155. function checkCompatibleProps(props: Props) {
  156. if (!props.captureMode && props.onCapture) {
  157. console.warn(
  158. "react-native-view-shot: a captureMode prop must be provided for `onCapture`"
  159. );
  160. } else if (props.captureMode && !props.onCapture) {
  161. console.warn(
  162. "react-native-view-shot: captureMode prop is defined but onCapture prop callback is missing"
  163. );
  164. } else if (
  165. (props.captureMode === "continuous" || props.captureMode === "update") &&
  166. props.options &&
  167. props.options.result &&
  168. props.options.result !== "tmpfile"
  169. ) {
  170. console.warn(
  171. "react-native-view-shot: result=tmpfile is recommended for captureMode=" +
  172. props.captureMode
  173. );
  174. }
  175. }
  176. export default class ViewShot extends Component<Props> {
  177. static captureRef = captureRef;
  178. static releaseCapture = releaseCapture;
  179. root: ?View;
  180. _raf: *;
  181. lastCapturedURI: ?string;
  182. resolveFirstLayout: (layout: Object) => void;
  183. firstLayoutPromise: Promise<Object> = new Promise(resolve => {
  184. this.resolveFirstLayout = resolve;
  185. });
  186. capture = (): Promise<string> =>
  187. this.firstLayoutPromise
  188. .then(() => {
  189. const { root } = this;
  190. if (!root) return neverEndingPromise; // component is unmounted, you never want to hear back from the promise
  191. return captureRef(root, this.props.options);
  192. })
  193. .then(
  194. (uri: string) => {
  195. this.onCapture(uri);
  196. return uri;
  197. },
  198. (e: Error) => {
  199. this.onCaptureFailure(e);
  200. throw e;
  201. }
  202. );
  203. onCapture = (uri: string) => {
  204. if (!this.root) return;
  205. if (this.lastCapturedURI) {
  206. // schedule releasing the previous capture
  207. setTimeout(releaseCapture, 500, this.lastCapturedURI);
  208. }
  209. this.lastCapturedURI = uri;
  210. const { onCapture } = this.props;
  211. if (onCapture) onCapture(uri);
  212. };
  213. onCaptureFailure = (e: Error) => {
  214. if (!this.root) return;
  215. const { onCaptureFailure } = this.props;
  216. if (onCaptureFailure) onCaptureFailure(e);
  217. };
  218. syncCaptureLoop = (captureMode: ?string) => {
  219. cancelAnimationFrame(this._raf);
  220. if (captureMode === "continuous") {
  221. let previousCaptureURI = "-"; // needs to capture at least once at first, so we use "-" arbitrary string
  222. const loop = () => {
  223. this._raf = requestAnimationFrame(loop);
  224. if (previousCaptureURI === this.lastCapturedURI) return; // previous capture has not finished, don't capture yet
  225. previousCaptureURI = this.lastCapturedURI;
  226. this.capture();
  227. };
  228. this._raf = requestAnimationFrame(loop);
  229. }
  230. };
  231. onRef = (ref: ElementRef<*>) => {
  232. this.root = ref;
  233. };
  234. onLayout = (e: LayoutEvent) => {
  235. const { onLayout } = this.props;
  236. this.resolveFirstLayout(e.nativeEvent.layout);
  237. if (onLayout) onLayout(e);
  238. };
  239. componentDidMount() {
  240. if (__DEV__) checkCompatibleProps(this.props);
  241. if (this.props.captureMode === "mount") {
  242. this.capture();
  243. } else {
  244. this.syncCaptureLoop(this.props.captureMode);
  245. }
  246. }
  247. componentDidUpdate(prevProps: Props) {
  248. if (this.props.captureMode !== undefined) {
  249. if (this.props.captureMode !== prevProps.captureMode) {
  250. this.syncCaptureLoop(this.props.captureMode);
  251. }
  252. }
  253. if (this.props.captureMode === "update") {
  254. this.capture();
  255. }
  256. }
  257. componentWillUnmount() {
  258. this.syncCaptureLoop(null);
  259. }
  260. render() {
  261. const { children } = this.props;
  262. return (
  263. <View
  264. ref={this.onRef}
  265. collapsable={false}
  266. onLayout={this.onLayout}
  267. style={this.props.style}
  268. >
  269. {children}
  270. </View>
  271. );
  272. }
  273. }