about summary refs log tree commit diff
path: root/src/view/com/composer/photos/EditImageDialog.web.tsx
blob: cda4e9ecfa7029677bec3d0c3f05fdd352f774c7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import 'react-image-crop/dist/ReactCrop.css'

import {useCallback, useImperativeHandle, useRef, useState} from 'react'
import {View} from 'react-native'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import ReactCrop, {type PercentCrop} from 'react-image-crop'

import {
  type ImageSource,
  type ImageTransformation,
  manipulateImage,
} from '#/state/gallery'
import {atoms as a, useTheme} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
import * as Dialog from '#/components/Dialog'
import {Loader} from '#/components/Loader'
import {type EditImageDialogProps} from './EditImageDialog'

export function EditImageDialog(props: EditImageDialogProps) {
  return (
    <Dialog.Outer control={props.control}>
      <Dialog.Handle />
      <DialogInner {...props} />
    </Dialog.Outer>
  )
}

function DialogInner({
  control,
  image,
  onChange,
  circularCrop,
  aspectRatio,
}: EditImageDialogProps) {
  const {_} = useLingui()
  const [pending, setPending] = useState(false)
  const ref = useRef<{save: () => Promise<void>}>(null)

  const cancelButton = useCallback(
    () => (
      <Button
        label={_(msg`Cancel`)}
        disabled={pending}
        onPress={() => control.close()}
        size="small"
        color="primary"
        variant="ghost"
        style={[a.rounded_full]}
        testID="cropImageCancelBtn">
        <ButtonText style={[a.text_md]}>
          <Trans>Cancel</Trans>
        </ButtonText>
      </Button>
    ),
    [control, _, pending],
  )

  const saveButton = useCallback(
    () => (
      <Button
        label={_(msg`Save`)}
        onPress={async () => {
          setPending(true)
          await ref.current?.save()
          setPending(false)
        }}
        disabled={pending}
        size="small"
        color="primary"
        variant="ghost"
        style={[a.rounded_full]}
        testID="cropImageSaveBtn">
        <ButtonText style={[a.text_md]}>
          <Trans>Save</Trans>
        </ButtonText>
        {pending && <ButtonIcon icon={Loader} />}
      </Button>
    ),
    [_, pending],
  )

  return (
    <Dialog.Inner
      label={_(msg`Edit image`)}
      header={
        <Dialog.Header renderLeft={cancelButton} renderRight={saveButton}>
          <Dialog.HeaderText>
            <Trans>Edit image</Trans>
          </Dialog.HeaderText>
        </Dialog.Header>
      }>
      {image && (
        <EditImageInner
          saveRef={ref}
          key={image.source.id}
          image={image}
          onChange={onChange}
          circularCrop={circularCrop}
          aspectRatio={aspectRatio}
        />
      )}
    </Dialog.Inner>
  )
}

function EditImageInner({
  image,
  onChange,
  saveRef,
  circularCrop = false,
  aspectRatio,
}: Required<Pick<EditImageDialogProps, 'image'>> &
  Omit<EditImageDialogProps, 'control' | 'image'> & {
    saveRef: React.RefObject<{save: () => Promise<void>} | null>
  }) {
  const t = useTheme()
  const [isDragging, setIsDragging] = useState(false)
  const {_} = useLingui()
  const control = Dialog.useDialogContext()

  const source = image.source

  const initialCrop = getInitialCrop(source, image.manips)
  const [crop, setCrop] = useState(initialCrop)

  const onPressSubmit = useCallback(async () => {
    const result = await manipulateImage(image, {
      crop:
        crop && (crop.width || crop.height) !== 0
          ? {
              originX: (crop.x * source.width) / 100,
              originY: (crop.y * source.height) / 100,
              width: (crop.width * source.width) / 100,
              height: (crop.height * source.height) / 100,
            }
          : undefined,
    })

    control.close(() => {
      onChange(result)
    })
  }, [crop, image, source, control, onChange])

  useImperativeHandle(
    saveRef,
    () => ({
      save: onPressSubmit,
    }),
    [onPressSubmit],
  )

  return (
    <View
      style={[
        a.mx_auto,
        a.border,
        t.atoms.border_contrast_low,
        a.rounded_xs,
        a.overflow_hidden,
        a.align_center,
      ]}>
      <ReactCrop
        crop={crop}
        aspect={aspectRatio}
        circularCrop={circularCrop}
        onChange={(_pixelCrop, percentCrop) => setCrop(percentCrop)}
        className="ReactCrop--no-animate"
        onDragStart={() => setIsDragging(true)}
        onDragEnd={() => setIsDragging(false)}>
        <img src={source.path} style={{maxHeight: `50vh`}} />
      </ReactCrop>
      {/* Eat clicks when dragging, otherwise mousing up over the backdrop
        causes the dialog to close */}
      {isDragging && <View style={[a.fixed, a.inset_0]} />}
    </View>
  )
}

const getInitialCrop = (
  source: ImageSource,
  manips: ImageTransformation | undefined,
): PercentCrop | undefined => {
  const initialArea = manips?.crop

  if (initialArea) {
    return {
      unit: '%',
      x: (initialArea.originX / source.width) * 100,
      y: (initialArea.originY / source.height) * 100,
      width: (initialArea.width / source.width) * 100,
      height: (initialArea.height / source.height) * 100,
    }
  }
}