@jhits/plugin-images 0.0.4 → 0.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +27 -36
- package/src/api/resolve/route.ts +130 -11
- package/src/api/upload/index.ts +0 -4
- package/src/assets/noimagefound.jpg +0 -0
- package/src/components/BackgroundImage.tsx +25 -44
- package/src/components/GlobalImageEditor/config.ts +21 -0
- package/src/components/GlobalImageEditor/eventHandlers.ts +267 -0
- package/src/components/GlobalImageEditor/imageDetection.ts +160 -0
- package/src/components/GlobalImageEditor/imageSetup.ts +306 -0
- package/src/components/GlobalImageEditor/saveLogic.ts +133 -0
- package/src/components/GlobalImageEditor/stylingDetection.ts +122 -0
- package/src/components/GlobalImageEditor/transformParsing.ts +83 -0
- package/src/components/GlobalImageEditor/types.ts +39 -0
- package/src/components/GlobalImageEditor.tsx +186 -637
- package/src/components/Image.tsx +269 -103
- package/src/components/ImageBrowserModal.tsx +837 -0
- package/src/components/ImageEditor.tsx +323 -0
- package/src/components/ImageEffectsPanel.tsx +116 -0
- package/src/components/ImagePicker.tsx +208 -484
- package/src/components/index.ts +3 -0
- package/src/hooks/useImagePicker.ts +344 -0
- package/src/types/index.ts +24 -0
- package/src/utils/transforms.ts +54 -0
package/src/components/Image.tsx
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
3
|
import NextImage from 'next/image';
|
|
4
|
-
import React, { useState, useEffect, useCallback } from 'react';
|
|
4
|
+
import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
|
|
5
5
|
import { Edit2, Loader2 } from 'lucide-react';
|
|
6
|
+
import { getImageTransform, getImageFilter } from '../utils/transforms';
|
|
7
|
+
import { getFallbackImageUrl } from '../utils/fallback';
|
|
6
8
|
|
|
7
9
|
export interface PluginImageProps {
|
|
8
10
|
id: string;
|
|
@@ -17,6 +19,12 @@ export interface PluginImageProps {
|
|
|
17
19
|
objectPosition?: string;
|
|
18
20
|
style?: React.CSSProperties;
|
|
19
21
|
editable?: boolean;
|
|
22
|
+
// Props take precedence over API-fetched values
|
|
23
|
+
scale?: number;
|
|
24
|
+
positionX?: number;
|
|
25
|
+
positionY?: number;
|
|
26
|
+
brightness?: number;
|
|
27
|
+
blur?: number;
|
|
20
28
|
}
|
|
21
29
|
|
|
22
30
|
export function Image({
|
|
@@ -32,145 +40,303 @@ export function Image({
|
|
|
32
40
|
objectPosition = 'center',
|
|
33
41
|
style,
|
|
34
42
|
editable = true,
|
|
43
|
+
...props // Using rest for override props
|
|
35
44
|
}: PluginImageProps) {
|
|
36
|
-
|
|
45
|
+
// 1. State management (Local only, used if props are undefined)
|
|
46
|
+
const [apiData, setApiData] = useState({
|
|
47
|
+
filename: null as string | null,
|
|
48
|
+
brightness: 100,
|
|
49
|
+
blur: 0,
|
|
50
|
+
scale: 1.0,
|
|
51
|
+
positionX: 0,
|
|
52
|
+
positionY: 0,
|
|
53
|
+
});
|
|
54
|
+
|
|
37
55
|
const [isResolving, setIsResolving] = useState(true);
|
|
38
|
-
const [
|
|
39
|
-
const [
|
|
40
|
-
const [
|
|
41
|
-
const [authChecked, setAuthChecked] = useState<boolean>(false);
|
|
56
|
+
const [baseScale, setBaseScale] = useState(1);
|
|
57
|
+
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
|
58
|
+
const [imageError, setImageError] = useState(false);
|
|
42
59
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
if (editable && !authChecked) {
|
|
46
|
-
const checkAuth = async () => {
|
|
47
|
-
try {
|
|
48
|
-
const res = await fetch('/api/me');
|
|
49
|
-
const data = await res.json();
|
|
50
|
-
if (data.loggedIn && (data.user?.role === 'admin' || data.user?.role === 'dev')) {
|
|
51
|
-
setIsAuthenticated(true);
|
|
52
|
-
}
|
|
53
|
-
} catch (error) {
|
|
54
|
-
// User is not authenticated or API call failed
|
|
55
|
-
setIsAuthenticated(false);
|
|
56
|
-
} finally {
|
|
57
|
-
setAuthChecked(true);
|
|
58
|
-
}
|
|
59
|
-
};
|
|
60
|
-
checkAuth();
|
|
61
|
-
} else if (!editable) {
|
|
62
|
-
// If explicitly set to false, skip auth check
|
|
63
|
-
setAuthChecked(true);
|
|
64
|
-
}
|
|
65
|
-
}, [editable, authChecked]);
|
|
60
|
+
const imageRef = useRef<HTMLImageElement | null>(null);
|
|
61
|
+
const containerRef = useRef<HTMLDivElement>(null);
|
|
66
62
|
|
|
67
|
-
//
|
|
68
|
-
const
|
|
63
|
+
// 2. Derive "Effective" values (Prop > Local State)
|
|
64
|
+
const effective = useMemo(() => ({
|
|
65
|
+
brightness: props.brightness ?? apiData.brightness,
|
|
66
|
+
blur: props.blur ?? apiData.blur,
|
|
67
|
+
scale: props.scale ?? apiData.scale,
|
|
68
|
+
positionX: props.positionX ?? apiData.positionX,
|
|
69
|
+
positionY: props.positionY ?? apiData.positionY,
|
|
70
|
+
filename: apiData.filename || id
|
|
71
|
+
}), [props, apiData, id]);
|
|
69
72
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
73
|
+
// 3. Optimized Image Resolution
|
|
74
|
+
const fetchImageMetadata = useCallback(async (targetId: string) => {
|
|
75
|
+
const isLikelyPath = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(targetId) || /^\d+-/.test(targetId);
|
|
76
|
+
|
|
77
|
+
if (isLikelyPath) {
|
|
78
|
+
setApiData(prev => ({ ...prev, filename: targetId }));
|
|
74
79
|
setIsResolving(false);
|
|
75
80
|
return;
|
|
76
81
|
}
|
|
77
82
|
|
|
78
|
-
|
|
79
|
-
|
|
83
|
+
try {
|
|
84
|
+
const res = await fetch(`/api/plugin-images/resolve?id=${encodeURIComponent(targetId)}`);
|
|
85
|
+
if (!res.ok) throw new Error();
|
|
86
|
+
const data = await res.json();
|
|
87
|
+
const apiPositionX = data.positionX ?? 0;
|
|
88
|
+
const apiPositionY = data.positionY ?? 0;
|
|
89
|
+
const apiScale = data.scale ?? 1.0;
|
|
90
|
+
setApiData({
|
|
91
|
+
filename: data.filename || targetId,
|
|
92
|
+
brightness: data.brightness ?? 100,
|
|
93
|
+
blur: data.blur ?? 0,
|
|
94
|
+
scale: apiScale,
|
|
95
|
+
positionX: apiPositionX,
|
|
96
|
+
positionY: apiPositionY,
|
|
97
|
+
});
|
|
98
|
+
// Reset error state when resolution succeeds (in case it was set during pre-check)
|
|
99
|
+
setImageError(false);
|
|
100
|
+
} catch {
|
|
101
|
+
setApiData(prev => ({ ...prev, filename: targetId }));
|
|
102
|
+
} finally {
|
|
103
|
+
setIsResolving(false);
|
|
104
|
+
}
|
|
105
|
+
}, []);
|
|
106
|
+
|
|
107
|
+
// 4. Auth Check (Single mount only)
|
|
108
|
+
useEffect(() => {
|
|
109
|
+
if (!editable) return;
|
|
110
|
+
fetch('/api/me')
|
|
111
|
+
.then(res => res.json())
|
|
80
112
|
.then(data => {
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
setIsResolving(false);
|
|
113
|
+
if (data.loggedIn && ['admin', 'dev'].includes(data.user?.role)) {
|
|
114
|
+
setIsAuthenticated(true);
|
|
115
|
+
}
|
|
85
116
|
})
|
|
86
|
-
.catch(() =>
|
|
87
|
-
|
|
88
|
-
setBrightness(100);
|
|
89
|
-
setBlur(0);
|
|
90
|
-
setIsResolving(false);
|
|
91
|
-
});
|
|
92
|
-
}, [id]);
|
|
117
|
+
.catch(() => setIsAuthenticated(false));
|
|
118
|
+
}, [editable]);
|
|
93
119
|
|
|
120
|
+
// 5. Stable Event Listener (Prevents closure staleness)
|
|
121
|
+
// Only fetch from API if props are not provided (parent controls the values)
|
|
122
|
+
const hasProps = props.scale !== undefined || props.positionX !== undefined || props.positionY !== undefined || props.brightness !== undefined || props.blur !== undefined;
|
|
123
|
+
|
|
94
124
|
useEffect(() => {
|
|
95
|
-
|
|
96
|
-
|
|
125
|
+
fetchImageMetadata(id);
|
|
126
|
+
|
|
127
|
+
// Only listen to events if props are not provided
|
|
128
|
+
if (hasProps) return;
|
|
129
|
+
|
|
130
|
+
const handleUpdate = (e: any) => {
|
|
97
131
|
if (e.detail?.id === id) {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
if (
|
|
101
|
-
|
|
132
|
+
// Only update if the event contains new data
|
|
133
|
+
const eventData = e.detail;
|
|
134
|
+
if (eventData.scale !== undefined || eventData.positionX !== undefined || eventData.positionY !== undefined || eventData.brightness !== undefined || eventData.blur !== undefined) {
|
|
135
|
+
// Update local state directly from event to avoid unnecessary API call
|
|
136
|
+
setApiData(prev => ({
|
|
137
|
+
...prev,
|
|
138
|
+
brightness: eventData.brightness ?? prev.brightness,
|
|
139
|
+
blur: eventData.blur ?? prev.blur,
|
|
140
|
+
scale: eventData.scale ?? prev.scale,
|
|
141
|
+
positionX: eventData.positionX ?? prev.positionX,
|
|
142
|
+
positionY: eventData.positionY ?? prev.positionY,
|
|
143
|
+
}));
|
|
144
|
+
}
|
|
102
145
|
}
|
|
103
146
|
};
|
|
104
|
-
window.addEventListener('image-mapping-updated', handleMappingUpdate as EventListener);
|
|
105
|
-
return () => window.removeEventListener('image-mapping-updated', handleMappingUpdate as EventListener);
|
|
106
|
-
}, [id, resolveImage]);
|
|
107
147
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
148
|
+
window.addEventListener('image-mapping-updated', handleUpdate);
|
|
149
|
+
return () => window.removeEventListener('image-mapping-updated', handleUpdate);
|
|
150
|
+
}, [id, fetchImageMetadata, hasProps]);
|
|
151
|
+
|
|
152
|
+
// 6. Layout & Transforms
|
|
153
|
+
const calculateBaseScale = useCallback(() => {
|
|
154
|
+
if (!imageRef.current || !containerRef.current) return;
|
|
155
|
+
const containerWidth = containerRef.current.offsetWidth;
|
|
156
|
+
const containerHeight = containerRef.current.offsetHeight;
|
|
157
|
+
|
|
158
|
+
// Ensure container has dimensions before calculating
|
|
159
|
+
if (containerWidth === 0 || containerHeight === 0) {
|
|
160
|
+
// Try to get dimensions from computed styles or parent
|
|
161
|
+
const parentWidth = containerRef.current.parentElement?.clientWidth;
|
|
162
|
+
const parentHeight = containerRef.current.parentElement?.clientHeight;
|
|
163
|
+
|
|
164
|
+
if (parentWidth && parentHeight && imageRef.current.naturalWidth > 0) {
|
|
165
|
+
const widthRatio = parentWidth / imageRef.current.naturalWidth;
|
|
166
|
+
const heightRatio = parentHeight / imageRef.current.naturalHeight;
|
|
167
|
+
const calculatedBaseScale = Math.max(widthRatio, heightRatio);
|
|
168
|
+
setBaseScale(calculatedBaseScale);
|
|
169
|
+
}
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (imageRef.current.naturalWidth === 0 || imageRef.current.naturalHeight === 0) return;
|
|
174
|
+
|
|
175
|
+
const widthRatio = containerWidth / imageRef.current.naturalWidth;
|
|
176
|
+
const heightRatio = containerHeight / imageRef.current.naturalHeight;
|
|
177
|
+
const calculatedBaseScale = Math.max(widthRatio, heightRatio);
|
|
178
|
+
setBaseScale(calculatedBaseScale);
|
|
179
|
+
}, []);
|
|
111
180
|
|
|
112
|
-
//
|
|
113
|
-
//
|
|
181
|
+
// Only construct image URL if we have a valid filename (not a semantic ID)
|
|
182
|
+
// Check if filename looks like an actual file (has extension or starts with timestamp)
|
|
183
|
+
const filename = effective.filename;
|
|
184
|
+
const hasFileExtension = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(filename);
|
|
185
|
+
const looksLikeTimestamp = /^\d+-/.test(filename);
|
|
186
|
+
const isValidFilename = hasFileExtension || looksLikeTimestamp;
|
|
187
|
+
|
|
188
|
+
// Don't construct URL until resolution is complete AND we have a valid filename
|
|
189
|
+
const shouldConstructUrl = !isResolving && isValidFilename;
|
|
190
|
+
const baseSrc = shouldConstructUrl ? `/api/uploads/${encodeURIComponent(filename)}` : null;
|
|
191
|
+
const src = imageError ? getFallbackImageUrl() : (baseSrc || getFallbackImageUrl());
|
|
114
192
|
const shouldFill = fill || className.includes('w-full') || className.includes('h-full');
|
|
193
|
+
const hasTransforms = effective.scale !== 1 || effective.positionX !== 0 || effective.positionY !== 0;
|
|
194
|
+
|
|
195
|
+
// Pre-check image URL to detect errors early (only for valid filenames after resolution)
|
|
196
|
+
useEffect(() => {
|
|
197
|
+
// Don't check if:
|
|
198
|
+
// 1. Already in error state
|
|
199
|
+
// 2. Still resolving
|
|
200
|
+
// 3. No valid base src
|
|
201
|
+
// 4. Base src is the fallback URL
|
|
202
|
+
if (imageError || isResolving || !baseSrc || baseSrc === getFallbackImageUrl() || !isValidFilename) return;
|
|
203
|
+
|
|
204
|
+
const testImg = document.createElement('img');
|
|
205
|
+
const handleError = () => {
|
|
206
|
+
setImageError(true);
|
|
207
|
+
};
|
|
208
|
+
const handleLoad = () => {
|
|
209
|
+
setImageError(false);
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
testImg.onerror = handleError;
|
|
213
|
+
testImg.onload = handleLoad;
|
|
214
|
+
testImg.src = baseSrc;
|
|
215
|
+
|
|
216
|
+
return () => {
|
|
217
|
+
testImg.onerror = null;
|
|
218
|
+
testImg.onload = null;
|
|
219
|
+
};
|
|
220
|
+
}, [baseSrc, imageError, isResolving, isValidFilename]);
|
|
115
221
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
222
|
+
// Recalculate baseScale when container is resized
|
|
223
|
+
useEffect(() => {
|
|
224
|
+
if (!hasTransforms || !shouldFill || !containerRef.current) return;
|
|
225
|
+
|
|
226
|
+
const resizeObserver = new ResizeObserver(() => {
|
|
227
|
+
calculateBaseScale();
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
resizeObserver.observe(containerRef.current);
|
|
231
|
+
return () => resizeObserver.disconnect();
|
|
232
|
+
}, [hasTransforms, shouldFill, calculateBaseScale]);
|
|
233
|
+
|
|
234
|
+
const transformStyle = hasTransforms && baseScale > 0 ? (() => {
|
|
235
|
+
return getImageTransform({
|
|
236
|
+
scale: effective.scale,
|
|
237
|
+
positionX: effective.positionX,
|
|
238
|
+
positionY: effective.positionY,
|
|
239
|
+
baseScale
|
|
240
|
+
}, true);
|
|
241
|
+
})() : undefined;
|
|
119
242
|
|
|
120
|
-
const
|
|
121
|
-
e.preventDefault();
|
|
122
|
-
e.stopPropagation();
|
|
123
|
-
window.dispatchEvent(new CustomEvent('open-image-editor', {
|
|
124
|
-
detail: { id, currentBrightness: brightness, currentBlur: blur }
|
|
125
|
-
}));
|
|
126
|
-
};
|
|
243
|
+
const filterStyle = getImageFilter(effective.brightness, effective.blur);
|
|
127
244
|
|
|
128
245
|
return (
|
|
129
246
|
<div
|
|
247
|
+
ref={containerRef}
|
|
130
248
|
className={`group/image relative overflow-hidden transition-all duration-300 ${className}`}
|
|
131
|
-
style={{
|
|
132
|
-
...style,
|
|
133
|
-
position: 'relative',
|
|
249
|
+
style={{
|
|
250
|
+
...style,
|
|
134
251
|
filter: filterStyle || style?.filter,
|
|
252
|
+
// Ensure container has explicit positioning context
|
|
253
|
+
position: 'relative',
|
|
135
254
|
}}
|
|
136
255
|
data-image-id={id}
|
|
137
256
|
>
|
|
138
|
-
{/* RESOLVING STATE */}
|
|
139
257
|
{isResolving && (
|
|
140
258
|
<div className="absolute inset-0 z-20 flex items-center justify-center bg-neutral-100 dark:bg-neutral-800 animate-pulse">
|
|
141
259
|
<Loader2 className="w-5 h-5 animate-spin text-neutral-400" />
|
|
142
260
|
</div>
|
|
143
261
|
)}
|
|
144
262
|
|
|
145
|
-
{
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
263
|
+
{hasTransforms && shouldFill ? (
|
|
264
|
+
baseSrc ? (
|
|
265
|
+
<img
|
|
266
|
+
ref={imageRef}
|
|
267
|
+
src={src}
|
|
268
|
+
alt={alt}
|
|
269
|
+
loading={priority ? 'eager' : 'lazy'}
|
|
270
|
+
onLoad={calculateBaseScale}
|
|
271
|
+
onError={() => setImageError(true)}
|
|
272
|
+
className="absolute max-w-none select-none"
|
|
273
|
+
style={{
|
|
274
|
+
top: '50%',
|
|
275
|
+
left: '50%',
|
|
276
|
+
width: 'auto', // Allow image to maintain natural aspect ratio
|
|
277
|
+
height: 'auto', // Allow image to maintain natural aspect ratio
|
|
278
|
+
minWidth: '100%', // Ensure image covers container width
|
|
279
|
+
minHeight: '100%', // Ensure image covers container height
|
|
280
|
+
transform: baseScale > 0 && transformStyle
|
|
281
|
+
? transformStyle
|
|
282
|
+
: 'translate(-50%, -50%)',
|
|
283
|
+
transformOrigin: 'center center',
|
|
284
|
+
position: 'absolute',
|
|
285
|
+
}}
|
|
286
|
+
draggable={false}
|
|
287
|
+
/>
|
|
288
|
+
) : null
|
|
289
|
+
) : imageError || !baseSrc ? (
|
|
290
|
+
// Fallback to regular img tag when error occurs or no valid filename yet
|
|
291
|
+
<img
|
|
292
|
+
src={getFallbackImageUrl()}
|
|
293
|
+
alt={alt}
|
|
294
|
+
loading={priority ? 'eager' : 'lazy'}
|
|
295
|
+
className={`transition-all duration-500 ${editable ? 'group-hover/image:scale-105' : ''}`}
|
|
296
|
+
style={{
|
|
297
|
+
objectFit,
|
|
298
|
+
objectPosition,
|
|
299
|
+
width: shouldFill ? '100%' : width,
|
|
300
|
+
height: shouldFill ? '100%' : height,
|
|
301
|
+
...(transformStyle ? { transform: transformStyle } : {}),
|
|
302
|
+
...style,
|
|
303
|
+
}}
|
|
304
|
+
/>
|
|
305
|
+
) : (
|
|
306
|
+
<NextImage
|
|
307
|
+
src={src}
|
|
308
|
+
alt={alt}
|
|
309
|
+
width={!shouldFill ? width : undefined}
|
|
310
|
+
height={!shouldFill ? height : undefined}
|
|
311
|
+
fill={shouldFill}
|
|
312
|
+
sizes={sizes || (shouldFill ? "(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw" : undefined)}
|
|
313
|
+
priority={priority}
|
|
314
|
+
loading={priority ? 'eager' : undefined}
|
|
315
|
+
className={`transition-all duration-500 ${editable ? 'group-hover/image:scale-105' : ''}`}
|
|
316
|
+
style={{
|
|
317
|
+
objectFit,
|
|
318
|
+
objectPosition,
|
|
319
|
+
...(transformStyle ? { transform: transformStyle } : {}),
|
|
320
|
+
...style,
|
|
321
|
+
}}
|
|
322
|
+
/>
|
|
323
|
+
)}
|
|
168
324
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
325
|
+
{editable && isAuthenticated && (
|
|
326
|
+
<button
|
|
327
|
+
onClick={(e) => {
|
|
328
|
+
e.preventDefault();
|
|
329
|
+
window.dispatchEvent(new CustomEvent('open-image-editor', {
|
|
330
|
+
detail: { id, currentBrightness: effective.brightness, currentBlur: effective.blur }
|
|
331
|
+
}));
|
|
332
|
+
}}
|
|
333
|
+
className="absolute inset-0 z-30 flex items-center justify-center opacity-0 group-hover/image:opacity-100 transition-all duration-300 bg-neutral-900/40 backdrop-blur-[2px]"
|
|
334
|
+
>
|
|
335
|
+
<div className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-neutral-800 rounded-full shadow-xl">
|
|
336
|
+
<Edit2 size={14} className="text-primary" />
|
|
337
|
+
<span className="text-[10px] font-bold uppercase tracking-widest">Edit</span>
|
|
172
338
|
</div>
|
|
173
|
-
</
|
|
339
|
+
</button>
|
|
174
340
|
)}
|
|
175
341
|
</div>
|
|
176
342
|
);
|