Skip to content

Commit

Permalink
general cleanup
Browse files Browse the repository at this point in the history
Added typescript binding
Fixed flow type issues
renamed NativeModule to RNCCameraRoll
Added basic jest tests
prettier/lint issues fixed
  • Loading branch information
Bartol Karuza committed Mar 3, 2019
1 parent 9f17664 commit 0c453b6
Show file tree
Hide file tree
Showing 18 changed files with 272 additions and 111 deletions.
3 changes: 3 additions & 0 deletions .flowconfig
Expand Up @@ -15,6 +15,9 @@ node_modules/react-native/\.buckd/
; Ignore unexpected extra "@providesModule"
.*/node_modules/.*/node_modules/fbjs/.*

; Ignore extra CameraRoll
.*/node_modules/react-native/Libraries/CameraRoll/CameraRoll.js

; Ignore duplicate module providers
; For RN Apps installed via npm, "Libraries" folder is inside
; "node_modules/react-native" but in the source repo it is in the root
Expand Down
21 changes: 21 additions & 0 deletions LICENCE
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2015-present, Facebook, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
21 changes: 15 additions & 6 deletions README.md
@@ -1,5 +1,6 @@
# `@react-native-community/cameraroll`

# react-native-cameraroll
[![CircleCI Status](https://img.shields.io/circleci/project/github/react-native-community/react-native-netinfo/master.svg)](https://circleci.com/gh/react-native-community/workflows/react-native-cameraroll/tree/master) ![Supports Android and iOS](https://img.shields.io/badge/platforms-android%20|%20ios-lightgrey.svg) ![MIT License](https://img.shields.io/npm/l/@react-native-community/cameraroll.svg)

## Getting started

Expand Down Expand Up @@ -34,12 +35,20 @@
compile project(':@react-native-community/cameraroll')
```

## Migrating from the core `react-native` module
This module was created when the CameraRoll was split out from the core of React Native. To migrate to this module you need to follow the installation instructions above and then change you imports from:

```javascript
import { CameraRoll } from "react-native";
```

to:

```javascript
import CameraRoll from "@react-native-community/cameraroll";
```

## Usage
---
id: cameraroll
title: CameraRoll
---

`CameraRoll` provides access to the local camera roll or photo library.

Expand Down Expand Up @@ -180,4 +189,4 @@ render() {
</View>
);
}
```
```
Expand Up @@ -57,7 +57,7 @@
@ReactModule(name = CameraRollModule.NAME)
public class CameraRollModule extends ReactContextBaseJavaModule {

public static final String NAME = "CameraRollManager";
public static final String NAME = "RNCCameraRoll";

private static final String ERROR_UNABLE_TO_LOAD = "E_UNABLE_TO_LOAD";
private static final String ERROR_UNABLE_TO_LOAD_PERMISSION = "E_UNABLE_TO_LOAD_PERMISSION";
Expand Down
25 changes: 5 additions & 20 deletions example/App.js
@@ -1,23 +1,18 @@
/**
* Sample React Native App
* https://github.com/facebook/react-native
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
* @lint-ignore-every XPLATJSCOPYRIGHT1
*/

import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import CameraRoll from '@react-native-community/cameraroll';
import {StyleSheet, View} from 'react-native';
import CameraRollExample from './js/CameraRollExample';

type Props = {};
export default class App extends Component<Props> {
componentDidMount = async () => {
const photos = await CameraRoll.getPhotos({first: 0, assetType: 'Photos'});
};

render() {
return (
<View style={styles.container}>
Expand All @@ -34,14 +29,4 @@ const styles = StyleSheet.create({
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
15 changes: 0 additions & 15 deletions example/__tests__/App.js

This file was deleted.

19 changes: 15 additions & 4 deletions example/e2e/sanityTest.spec.js
@@ -1,15 +1,26 @@
const {device, expect, element, by, waitFor} = require('detox');
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
/* eslint-env jest */
const {device, expect, element, by} = require('detox');

describe('CameraRoll', () => {
beforeEach(async () => {
await device.launchApp({permissions: {
await device.launchApp({
permissions: {
photos: 'YES',
// camera: 'YES',
}});
},
});
});

it('should load example app with no errors and show all the examples by default', async () => {
await expect(element(by.text('Big Images'))).toExist();
});

});
8 changes: 6 additions & 2 deletions example/index.js
@@ -1,8 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @lint-ignore-every XPLATJSCOPYRIGHT1
* @flow
*/

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
Expand Down
6 changes: 3 additions & 3 deletions example/js/CameraRollExample.js
Expand Up @@ -22,7 +22,7 @@ const {
TouchableOpacity,
} = ReactNative;

const invariant = require('invariant');
const invariant = require('fbjs/lib/invariant');

const CameraRollView = require('./CameraRollView');

Expand All @@ -38,7 +38,7 @@ type Props = $ReadOnly<{|
backButtonTitle: string,
passProps: $ReadOnly<{|asset: PhotoIdentifier|}>,
|}>,
>,
>,
|}>;

type State = {|
Expand Down Expand Up @@ -80,7 +80,7 @@ export default class CameraRollExample extends React.Component<Props, State> {
);
}

loadAsset(asset) {
loadAsset(asset: PhotoIdentifier) {
if (this.props.navigator) {
this.props.navigator.push({
title: 'Camera Roll Image',
Expand Down
28 changes: 14 additions & 14 deletions ios/RNCCameraRollManager.m
Expand Up @@ -69,7 +69,7 @@ + (PHFetchOptions *)PHFetchOptionsFromMediaType:(NSString *)mediaType

@implementation RNCCameraRollManager

RCT_EXPORT_MODULE(CameraRollManager)
RCT_EXPORT_MODULE(RNCCameraRoll)

@synthesize bridge = _bridge;

Expand Down Expand Up @@ -135,7 +135,7 @@ static void requestPhotoLibraryAccess(RCTPromiseRejectBlock reject, PhotosAuthor
}
}];
};

void (^loadBlock)(void) = ^void() {
if ([type isEqualToString:@"video"]) {
inputURI = request.URL;
Expand All @@ -146,13 +146,13 @@ static void requestPhotoLibraryAccess(RCTPromiseRejectBlock reject, PhotosAuthor
reject(kErrorUnableToLoad, nil, error);
return;
}

inputImage = image;
saveBlock();
}];
}
};

requestPhotoLibraryAccess(reject, loadBlock);
}

Expand Down Expand Up @@ -214,13 +214,13 @@ static void RCTResolvePromise(RCTPromiseResolveBlock resolve,
if (groupName != nil) {
collectionFetchOptions.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"localizedTitle == '%@'", groupName]];
}

requestPhotoLibraryAccess(reject, ^{
PHFetchResult<PHAssetCollection *> *const assetCollectionFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:collectionType subtype:collectionSubtype options:collectionFetchOptions];
[assetCollectionFetchResult enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull assetCollection, NSUInteger collectionIdx, BOOL * _Nonnull stopCollections) {
// Enumerate assets within the collection
PHFetchResult<PHAsset *> *const assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:assetFetchOptions];

[assetsFetchResult enumerateObjectsUsingBlock:^(PHAsset * _Nonnull asset, NSUInteger assetIdx, BOOL * _Nonnull stopAssets) {
NSString *const uri = [NSString stringWithFormat:@"ph://%@", [asset localIdentifier]];
if (afterCursor && !foundAfter) {
Expand All @@ -229,31 +229,31 @@ static void RCTResolvePromise(RCTPromiseResolveBlock resolve,
}
return; // skip until we get to the first one
}

// Get underlying resources of an asset - this includes files as well as details about edited PHAssets
if ([mimeTypes count] > 0) {
NSArray<PHAssetResource *> *const assetResources = [PHAssetResource assetResourcesForAsset:asset];
if (![assetResources firstObject]) {
return;
}

PHAssetResource *const _Nonnull resource = [assetResources firstObject];
CFStringRef const uti = (__bridge CFStringRef _Nonnull)(resource.uniformTypeIdentifier);
NSString *const mimeType = (NSString *)CFBridgingRelease(UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType));

BOOL __block mimeTypeFound = NO;
[mimeTypes enumerateObjectsUsingBlock:^(NSString * _Nonnull mimeTypeFilter, NSUInteger idx, BOOL * _Nonnull stop) {
if ([mimeType isEqualToString:mimeTypeFilter]) {
mimeTypeFound = YES;
*stop = YES;
}
}];

if (!mimeTypeFound) {
return;
}
}

// If we've accumulated enough results to resolve a single promise
if (first == assets.count) {
*stopAssets = YES;
Expand All @@ -264,7 +264,7 @@ static void RCTResolvePromise(RCTPromiseResolveBlock resolve,
resolvedPromise = YES;
return;
}

NSString *const assetMediaTypeLabel = (asset.mediaType == PHAssetMediaTypeVideo
? @"video"
: (asset.mediaType == PHAssetMediaTypeImage
Expand All @@ -273,7 +273,7 @@ static void RCTResolvePromise(RCTPromiseResolveBlock resolve,
? @"audio"
: @"unknown")));
CLLocation *const loc = asset.location;

// A note on isStored: in the previous code that used ALAssets, isStored
// was always set to YES, probably because iCloud-synced images were never returned (?).
// To get the "isStored" information and filename, we would need to actually request the
Expand Down Expand Up @@ -304,7 +304,7 @@ static void RCTResolvePromise(RCTPromiseResolveBlock resolve,
}];
}];
}];

// If we get this far and haven't resolved the promise yet, we reached the end of the list of photos
if (!resolvedPromise) {
hasNextPage = NO;
Expand Down
17 changes: 6 additions & 11 deletions js/CameraRoll.js
Expand Up @@ -11,10 +11,9 @@

const PropTypes = require('prop-types');
const {checkPropTypes} = PropTypes;
const RCTCameraRollManager = require('NativeModules').CameraRollManager;

const RNCCameraRoll = require('nativeInterface');
const deprecatedCreateStrictShapeTypeChecker = require('deprecatedCreateStrictShapeTypeChecker');
const invariant = require('invariant');
const invariant = require('fbjs/lib/invariant');

const GROUP_TYPES_OPTIONS = {
Album: 'Album',
Expand Down Expand Up @@ -170,13 +169,12 @@ class CameraRoll {
}

static deletePhotos(photos: Array<string>) {
return RCTCameraRollManager.deletePhotos(photos);
return RNCCameraRoll.deletePhotos(photos);
}

/**
* Saves the photo or video to the camera roll or photo library.
*
* See https://facebook.github.io/react-native/docs/cameraroll.html#savetocameraroll
*/
static saveToCameraRoll(
tag: string,
Expand All @@ -200,7 +198,7 @@ class CameraRoll {
mediaType = 'video';
}
return RCTCameraRollManager.saveToCameraRoll(tag, mediaType);
return RNCCameraRoll.saveToCameraRoll(tag, mediaType);
}
/**
Expand Down Expand Up @@ -236,13 +234,10 @@ class CameraRoll {
};
}
const errorCallback = arguments[2] || (() => {});
RCTCameraRollManager.getPhotos(params).then(
successCallback,
errorCallback,
);
RNCCameraRoll.getPhotos(params).then(successCallback, errorCallback);
}
// TODO: Add the __DEV__ check back in to verify the Promise result
return RCTCameraRollManager.getPhotos(params);
return RNCCameraRoll.getPhotos(params);
}
}

Expand Down
5 changes: 5 additions & 0 deletions js/__mocks__/nativeInterface.js
@@ -0,0 +1,5 @@
module.exports = {
deletePhotos: jest.fn(),
saveToCameraRoll: jest.fn(),
getPhotos: jest.fn(),
};

0 comments on commit 0c453b6

Please sign in to comment.