File size: 9,394 Bytes
238d8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13ef64d
 
 
 
 
 
238d8e3
 
 
13ef64d
 
 
 
 
 
 
238d8e3
 
13ef64d
 
 
 
 
 
238d8e3
 
 
13ef64d
 
238d8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13ef64d
238d8e3
 
 
 
 
 
 
 
 
13ef64d
 
 
 
238d8e3
 
 
 
13ef64d
 
238d8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import { useCallback, useEffect, useRef, useState } from 'react'
import { ChevronLeft, Crop, Maximize2 } from 'lucide-react'
import {
  clampCropRect,
  computeDisplayLayout,
  cropToDisplay,
  defaultCropRect,
  type CropRect,
  type DisplayLayout,
} from '../lib/cropImage'
import { t } from '../lib/i18n'
import type { Lang } from '../lib/types'

type Handle = 'move' | 'nw' | 'ne' | 'sw' | 'se'

interface Props {
  lang: Lang
  imageSrc: string
  naturalW: number
  naturalH: number
  onBack: () => void
  onConfirm: (crop: CropRect) => void
  onUseFull: () => void
}

export function StepCrop({
  lang,
  imageSrc,
  naturalW,
  naturalH,
  onBack,
  onConfirm,
  onUseFull,
}: Props) {
  const containerRef = useRef<HTMLDivElement>(null)
  const [layout, setLayout] = useState<DisplayLayout | null>(null)
  const [crop, setCrop] = useState<CropRect>(() => defaultCropRect(naturalW, naturalH))
  const dragRef = useRef<{
    handle: Handle
    startX: number
    startY: number
    startCrop: CropRect
  } | null>(null)
  const layoutRef = useRef(layout)
  layoutRef.current = layout
  const naturalRef = useRef({ w: naturalW, h: naturalH })
  naturalRef.current = { w: naturalW, h: naturalH }

  const measure = useCallback(() => {
    const el = containerRef.current
    if (!el) return
    const next = computeDisplayLayout(el.clientWidth, el.clientHeight, naturalW, naturalH)
    if (next.width > 0 && next.height > 0) setLayout(next)
  }, [naturalW, naturalH])

  useEffect(() => {
    measure()
    const el = containerRef.current
    if (!el) return
    const ro = new ResizeObserver(measure)
    ro.observe(el)
    return () => ro.disconnect()
  }, [measure])

  useEffect(() => {
    setCrop(defaultCropRect(naturalW, naturalH))
  }, [naturalW, naturalH, imageSrc])

  const displayCrop = layout ? cropToDisplay(crop, layout, naturalW, naturalH) : null

  const startDrag = (handle: Handle, clientX: number, clientY: number) => {
    dragRef.current = { handle, startX: clientX, startY: clientY, startCrop: crop }
  }

  const onPointerMove = useCallback((clientX: number, clientY: number) => {
    const drag = dragRef.current
    const layoutNow = layoutRef.current
    if (!drag || !layoutNow) return

    const { w: naturalWNow, h: naturalHNow } = naturalRef.current
    const dx = ((clientX - drag.startX) / layoutNow.width) * naturalWNow
    const dy = ((clientY - drag.startY) / layoutNow.height) * naturalHNow
    const s = drag.startCrop
    let next: CropRect

    switch (drag.handle) {
      case 'move':
        next = { ...s, x: s.x + dx, y: s.y + dy }
        break
      case 'nw':
        next = {
          x: s.x + dx,
          y: s.y + dy,
          width: s.width - dx,
          height: s.height - dy,
        }
        break
      case 'ne':
        next = {
          x: s.x,
          y: s.y + dy,
          width: s.width + dx,
          height: s.height - dy,
        }
        break
      case 'sw':
        next = {
          x: s.x + dx,
          y: s.y,
          width: s.width - dx,
          height: s.height + dy,
        }
        break
      case 'se':
        next = {
          x: s.x,
          y: s.y,
          width: s.width + dx,
          height: s.height + dy,
        }
        break
    }

    setCrop(clampCropRect(next, naturalWNow, naturalHNow))
  }, [])

  const endDrag = () => {
    dragRef.current = null
  }

  useEffect(() => {
    const onMove = (e: PointerEvent) => onPointerMove(e.clientX, e.clientY)
    const onUp = () => endDrag()
    window.addEventListener('pointermove', onMove)
    window.addEventListener('pointerup', onUp)
    window.addEventListener('pointercancel', onUp)
    return () => {
      window.removeEventListener('pointermove', onMove)
      window.removeEventListener('pointerup', onUp)
      window.removeEventListener('pointercancel', onUp)
    }
  }, [onPointerMove])

  const handleCorner = (corner: Exclude<Handle, 'move'>) => (
    e: React.PointerEvent<HTMLDivElement>,
  ) => {
    e.stopPropagation()
    e.currentTarget.setPointerCapture(e.pointerId)
    startDrag(corner, e.clientX, e.clientY)
  }

  return (
    <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-[var(--bg)]">
      <div className="flex items-center justify-between px-4 py-2.5">
        <button
          type="button"
          className="ct-btn-ghost rise-enter flex h-9 items-center gap-1 px-3 text-sm"
          style={{ animationDelay: '0.04s' }}
          onClick={onBack}
        >
          <ChevronLeft size={16} strokeWidth={2.5} />
          {t(lang, 'previewBack')}
        </button>
        <p
          className="rise-enter text-[var(--text)]"
          style={{ font: 'var(--type-h3)', animationDelay: '0.08s' }}
        >
          {t(lang, 'cropTitle')}
        </p>
        <div className="rise-enter w-16" style={{ animationDelay: '0.08s' }} />
      </div>

      <p
        className="rise-enter px-4 pb-2 text-center text-xs text-[var(--text-dim)]"
        style={{ animationDelay: '0.12s' }}
      >
        {t(lang, 'cropHint')}
      </p>

      <div
        ref={containerRef}
        className="rise-enter relative mx-4 min-h-0 flex-1 overflow-hidden rounded-2xl border border-[var(--hairline)] bg-black shadow-[var(--shadow-lg)]"
        style={{ animationDelay: '0.16s' }}
      >
        <img src={imageSrc} alt="" className="absolute inset-0 h-full w-full object-contain" draggable={false} />

        {displayCrop && (
          <div className="absolute inset-0 touch-none">
            <div
              className="absolute bg-black/55"
              style={{ left: 0, top: 0, right: 0, height: displayCrop.y }}
            />
            <div
              className="absolute bg-black/55"
              style={{
                left: 0,
                top: displayCrop.y,
                width: displayCrop.x,
                height: displayCrop.height,
              }}
            />
            <div
              className="absolute bg-black/55"
              style={{
                left: displayCrop.x + displayCrop.width,
                top: displayCrop.y,
                right: 0,
                height: displayCrop.height,
              }}
            />
            <div
              className="absolute bg-black/55"
              style={{
                left: 0,
                top: displayCrop.y + displayCrop.height,
                right: 0,
                bottom: 0,
              }}
            />

            <div
              className="absolute cursor-move border-2 border-[var(--brand)]"
              style={{
                left: displayCrop.x,
                top: displayCrop.y,
                width: displayCrop.width,
                height: displayCrop.height,
                boxShadow: '0 0 0 1px rgba(255,255,255,0.35) inset',
              }}
              onPointerDown={(e) => {
                e.currentTarget.setPointerCapture(e.pointerId)
                startDrag('move', e.clientX, e.clientY)
              }}
            >
              <div className="pointer-events-none absolute inset-0 grid grid-cols-3 grid-rows-3 opacity-40">
                {Array.from({ length: 9 }).map((_, i) => (
                  <div key={i} className="border border-white/50" />
                ))}
              </div>

              {(['nw', 'ne', 'sw', 'se'] as const).map((corner) => {
                const pos =
                  corner === 'nw'
                    ? 'left-0 top-0 -translate-x-1/2 -translate-y-1/2'
                    : corner === 'ne'
                      ? 'right-0 top-0 translate-x-1/2 -translate-y-1/2'
                      : corner === 'sw'
                        ? 'left-0 bottom-0 -translate-x-1/2 translate-y-1/2'
                        : 'right-0 bottom-0 translate-x-1/2 translate-y-1/2'
                return (
                  <div
                    key={corner}
                    className={`absolute h-5 w-5 rounded-full border-2 border-white bg-[var(--brand)] shadow-[var(--shadow-md)] transition-transform duration-150 will-change-transform hover:scale-110 active:scale-95 ${pos}`}
                    onPointerDown={handleCorner(corner)}
                  />
                )
              })}
            </div>
          </div>
        )}
      </div>

      <p
        className="rise-enter mt-2 text-center text-[11px] tabular-nums text-[var(--text-faint)]"
        style={{ fontFamily: 'var(--font-mono)', animationDelay: '0.2s' }}
      >
        {Math.round(crop.width)} × {Math.round(crop.height)}
      </p>

      <div
        className="rise-enter mt-3 shrink-0 space-y-2 border-t border-[var(--hairline)] bg-[var(--header-bg)] px-4 pt-3 shadow-[0_-4px_24px_rgba(15,23,42,0.06)]"
        style={{ paddingBottom: 'max(1rem, env(safe-area-inset-bottom))', animationDelay: '0.24s' }}
      >
        <button
          type="button"
          className="ct-btn-secondary flex w-full items-center justify-center gap-2"
          onClick={onUseFull}
        >
          <Maximize2 size={18} />
          {t(lang, 'cropUseFull')}
        </button>
        <button
          type="button"
          className="ct-btn-primary flex w-full items-center justify-center gap-2"
          onClick={() => onConfirm(clampCropRect(crop, naturalW, naturalH))}
        >
          <Crop size={18} />
          {t(lang, 'cropContinue')}
        </button>
      </div>
    </div>
  )
}