# @supportworks/Multi-ImagePicker

This library wraps `react-native-image-crop-picker` for React Native apps and provides a shared image-picking flow with support for:

- selecting one or more images
- editing image titles/descriptions before attach
- per-image metadata such as `showToCust` and `saveToDevice`
- attaching images to a project, appointment, or other app-specific target

## Getting started

See `peerDependencies` in `package.json` and install the required libraries in the app.

Install with:

```bash
npm install @supportworks/Multi-ImagePicker
```

Version `3.x` has breaking changes for React Native `>= 0.60`.

iOS note: when building the app the first time, in Xcode under `Embedded Binaries`, add:

- `RSKImageCropper.framework`
- `QBImagePicker.framework`

## Current AddImages architecture

`AddImages` no longer presents itself with a native React Native `Modal`.

Instead:

- `AddImages` is the trigger/controller
- `AddImagesProvider` renders the full-screen overlay host

This avoids nested native modal presentation problems on iOS, especially when `AddImages` is launched from a sheet, bottom modal, or other modal-like container.

`AddImages` must be rendered inside an `AddImagesProvider`. If it is not, the component will throw:

```txt
AddImages must be used within an AddImagesProvider.
```

## Thumbnail previews

Attach and the camera Session Roll render small previews in virtualized lists. The full-size files remain available to the viewer, annotation, and save callbacks.

The API instance may provide `makeThumbnail(path)` and `deleteThumbnail(path)` for persistent thumbnail caching. Consumers without those optional methods use temporary previews, generated serially and removed when the preview unmounts. Existing `RNFS`, file-path, and annotation APIs are still required.

Version 8.4.2 requires `@supportworks/navbars >=3.0.0` for `LoadingOverlayHost` and the shared loading service. Keep `AddImagesProvider` mounted around the editor flow.

## Camera layout testing and optional zoom slider

`MultiImagePicker` and `AddImages` accept `enableZoomSlider` (default `false`). When enabled, the camera offers an adjustment button to switch between zoom presets and the original vertical slider, with a button to return to the presets. The slider uses the camera's supported range, capped at 5×, in 0.5× steps.

A dedicated test harness can pass `testImageSource` (a React Native image source) directly to `src/components/CameraModal`. This replaces the native camera with a sample background, bypasses camera permission requests, and supplies simulated zoom and front/back states. Shutter presses create disposable sample files for Session Roll testing. They are deleted when the tester unmounts, including after Done; do not save its results to customer records. Captures use the source image, not an optically zoomed or focused camera image.

Keep that input out of normal camera launches. Ripple only supplies it from its core.test menu tester, presented in the same full-screen modal as normal camera use. Flash, focus, lens switching, and zoom in this mode exercise UI state only; they do not verify camera hardware.

## Usage - imports

```javascript
import {
  AddImages,
  AddImagesProvider,
  MultiImagePicker,
  SelectedImages
} from '@supportworks/Multi-ImagePicker'
```

## Info.plist additions for iOS

Saving to Camera Roll currently applies to iOS only.

```xml
<key>NSPhotoLibraryAddUsageDescription</key>
<string>We allow you to save photos into your media library that were taken within the app.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>We access your media library to let you upload pictures you already took to your appointments.</string>
```

## Library Usage 1 - AddImages with AddImagesProvider
## How to use AddImagesProvider

Wrap `AddImagesProvider` around the highest React subtree that the image picker needs to cover.

That is the key rule.

Examples:

- normal screen: wrap the screen root
- tabbed screen: wrap the tab container, not just the tab body
- modal or sheet: wrap the modal or sheet content tree itself
- bottom modal inside another screen: wrap inside that bottom modal host, not only at app root

Do not assume a single provider in `App.js` is always enough. If `AddImages` is used inside a modal or sheet, an app-root provider can render behind that host instead of above it.

Multiple providers in different parts of the app are acceptable when `AddImages` is used in different host layers.

## How to choose the correct provider location

Start at the `AddImages` call site and walk up the render tree.

Place the provider around the component that owns the highest piece of UI that should be hidden behind the picker.

### Signs the provider is too low

- the picker is clipped to a smaller area
- headers or tabs are still visible above it
- part of the current screen remains tappable

### Signs the provider is too high or outside the wrong host

- the picker renders behind a modal or sheet
- touches go to the underlying modal instead of the picker

## Basic screen example

Use this pattern when `AddImages` is launched from a normal full-screen page.

```javascript
import React from 'react'
import { View } from 'react-native'
import { AddImages, AddImagesProvider } from '@supportworks/Multi-ImagePicker'

const ProjectScreen = ({ Project, Api }) => {
  const onImagesAdded = () => {
    // refresh screen state after attach
  }

  return (
    <AddImagesProvider>
      <View style={{ flex: 1 }}>
        <Header />
        <Content />

        <AddImages
          parentStyle={styles.AddPhoto}
          prospectInst={Project}
          addPicture={Api.addOnePictureToProject}
          callback={onImagesAdded}
        >
          <CameraButton />
        </AddImages>
      </View>
    </AddImagesProvider>
  )
}
```

## Modal or sheet example

Use this pattern when `AddImages` is launched from inside a bottom sheet or modal-like container.

If the underlying modal chrome is still visible at the top, set `sheetTopInset={0}`.

```javascript
import React from 'react'
import { AddImagesProvider } from '@supportworks/Multi-ImagePicker'
import SwipeModal from '@supportworks/core-controls/src/SwipeModal'

const SheetAddImagesProvider = ({ children }) => (
  <AddImagesProvider sheetTopInset={0}>
    {children}
  </AddImagesProvider>
)

const MyScreen = () => (
  <SwipeModal
    contentWrapper={SheetAddImagesProvider}
    visible={showBottomModal}
    close={closeBottomModal}
  >
    <BottomModalContent />
  </SwipeModal>
)
```

## AddImages props

`AddImages` is still the main trigger component. Common props include:

- `parentStyle`: style passed to `MultiImagePicker`
- `prospectInst`: project/appointment instance passed back to `addPicture`
- `addPicture`: async handler for saving one image
- `callback`: called after images are attached
- `hitSlop`: passed to the picker trigger
- `allowEdit`: whether filenames/descriptions can be edited
- `annotationAllowed`: whether annotations are allowed
- `showToCustomerAllowed`: whether "show to customer" is available
- `maxCount`: max images selectable
- `children`: the button/icon/link users tap to open the picker

## Troubleshooting

### The picker is not full screen

The provider is probably too low in the tree.

Move `AddImagesProvider` higher, around the component that owns the header/tabs/navigation you want covered.

### The picker appears behind a modal or sheet

The provider is probably outside the modal or sheet host.

Move the provider inside that modal or sheet content tree.

### The top of the old modal is still visible

Use:

```javascript
<AddImagesProvider sheetTopInset={0}>
```

This is useful when the picker is hosted inside an existing modal or bottom-sheet style container and should fully cover that host.

## ChatGPT / implementation prompt

This section is intentionally written so it can be pasted into a ChatGPT or Codex prompt when integrating `AddImages` into an app.

```txt
The Multi-ImagePicker library uses AddImagesProvider and AddImages.

AddImages is only the trigger/controller. It does not use a native Modal to present itself.
AddImagesProvider is the overlay host that renders the full-screen picker UI.

When integrating AddImages:
1. Find every AddImages call site.
2. Trace the render tree upward from each call site.
3. Place AddImagesProvider around the highest React subtree that the picker needs to cover.
4. If AddImages is used inside a modal, bottom sheet, SwipeModal, react-native-modal, or other sheet host, place AddImagesProvider inside that host's content tree, not only at app root.
5. If the picker is clipped or headers/tabs still show above it, the provider is too low.
6. If the picker renders behind a modal or sheet, the provider is outside the correct host.
7. If the underlying modal chrome is still visible at the top, use AddImagesProvider with sheetTopInset={0}.

Use AddImages + AddImagesProvider as the default integration path. Only use MultiImagePicker or SelectedImages directly when custom flow control is required.
```

## Library Usage 2 - MultiImagePicker
`MultiImagePicker` allows you to select multiple images and return the results in arrays.  
The child you include (AddButton in this example) should display an icon that will be touched to open the picker.  
Note that your child component will be wrapped with a TouchableOpacity component, so any props you supply for 
MultiImagePicker will be passed to that TouchableOpacity component.

```javascript
onImageSelect(payload) {
    //handle return of selected images from MultiImagePicker
    //payload expected (json): {index: integer, cancelIndex: integer, imageArray: [image info], imageDescArray: [image descriptions], imageValidArray: [array of true booleans], callbackData: any}

    let cRef = this;

    cRef.imgArr = payload.imageArray;
    cRef.imgDescArr = payload.imageDescArray;
    cRef.imgValidArr = payload.imageValidArray;
    cRef.setState({showAdd: true});
}
    
render() {
...
    <MultiImagePicker callback={cRef.onImageSelect}>
       <AddButton/>
    </MultiImagePicker>
...
}
```


## Library Usage 3 - SelectedImages
`SelectedImages` allows you to display the images that were selected, before saving them, so you can edit their titles and descriptions.

```javascript

onItemChange (idx, patch) {
    this.setState((prevState) => {
        const items = prevState.items.map((item, i) => (i === idx ? {...item, ...patch} : item))
        const allValid = items.every(it => it?.isValid !== false)
        return {items, allImageDataValid: allValid}
    })
}

render() {
...
    <KeyboardAwareScrollView>
        <SelectedImages items={cRef.state.items}  onItemChange={cRef.onItemChange}/>
    </KeyboardAwareScrollView>
...
}
```

Camera pinch zoom uses two fingers on the preview and continuously adjusts within the reported camera range (up to 5×). It works independently of `enableZoomSlider`, which remains false by default. Presets and the optional original slider retain their fixed/half-step values. Single-finger taps still focus; finishing a pinch does not trigger focus. Physical-device testing is required to assess lens-transition smoothness.

Zoom presets are `.5`, `1`, and `3` when supported by the camera. The nearest preset stays selected and shows the current zoom while pinching or using the slider (for example, `1.5×` on the middle button). Exact midpoint ties select the lower preset. Tapping a button always returns to its fixed preset value.

## Optional iOS LiDAR capture and units (DEV-10310)

Pass `useLiDARPhotoDepth={true}` to opt in; the default is false so existing hosts do not gain a new capture option. `measurementSystem="imperial"` or `"metric"` controls the initial distance display. These props pass through `MultiImagePicker`, `AddImages`, its editor/provider, `SelectedImages`, `SingleImage`, and `CameraModal`. Hosts supply the same enum used by drawing settings; drawing-tool callers use their existing measurement-system resolver.

```jsx
<MultiImagePicker useLiDARPhotoDepth measurementSystem="imperial" callback={handlePhotos}>
  <Text>Take or choose photos</Text>
</MultiImagePicker>

<CameraModal useLiDARPhotoDepth measurementSystem="metric" onDone={handlePhotos} onCancel={handleCancel} />
```

Opt-in exposes the toggle only for a supported active camera configuration. Depth capture still starts off. Turning the option off disables an active depth mode. It is iOS-only; existing non-iOS behavior remains. Bottom session-roll thumbnails open the common full-screen review, which receives the host's visibility choice and measurement system.

A validated depth HEIC bypasses the existing JPEG resize step. File inspection, not the extension or a caller-supplied boolean, determines whether depth/calibration are usable. Copy the original HEIC unchanged when saving/uploading; preserve `image/heic`. No separate LiDAR JSON is required. Normal annotation drawing JSON can still hold saved lines, labels and their calibrated values. Ripple currently converts HEIC to JPEG in its own save API, so host integration must preserve the source before production depth-photo persistence can work. Ripple source is not changed here.

Beta integration: install the matching camera, multi-imagepicker and react-native-annotate beta versions together, and rebuild the native application. The photo-depth prop is `useLiDARPhotoDepth`; it defaults to false. False or omission hides depth controls in capture and review. A true flag only exposes capture on an active supported rear LiDAR camera at 1×; unsupported/front cameras do not show the capture icon. Preserve original HEIC bytes and any annotation JSON before producing a separate JPEG for the host.
