@jhits/plugin-images 0.0.11 → 0.0.12

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.
Files changed (76) hide show
  1. package/package.json +3 -2
  2. package/src/api/fallback/route.ts +69 -0
  3. package/src/api/index.ts +10 -0
  4. package/src/api/list/index.ts +96 -0
  5. package/src/api/resolve/route.ts +241 -0
  6. package/src/api/router.ts +85 -0
  7. package/src/api/upload/index.ts +88 -0
  8. package/src/api/uploads/[filename]/route.ts +93 -0
  9. package/src/api-server.ts +11 -0
  10. package/src/assets/noimagefound.jpg +0 -0
  11. package/src/components/BackgroundImage.d.ts +11 -0
  12. package/src/components/BackgroundImage.d.ts.map +1 -0
  13. package/src/components/BackgroundImage.tsx +92 -0
  14. package/src/components/GlobalImageEditor/config.d.ts +9 -0
  15. package/src/components/GlobalImageEditor/config.d.ts.map +1 -0
  16. package/src/components/GlobalImageEditor/config.ts +21 -0
  17. package/src/components/GlobalImageEditor/eventHandlers.d.ts +20 -0
  18. package/src/components/GlobalImageEditor/eventHandlers.d.ts.map +1 -0
  19. package/src/components/GlobalImageEditor/eventHandlers.ts +267 -0
  20. package/src/components/GlobalImageEditor/imageDetection.d.ts +16 -0
  21. package/src/components/GlobalImageEditor/imageDetection.d.ts.map +1 -0
  22. package/src/components/GlobalImageEditor/imageDetection.ts +160 -0
  23. package/src/components/GlobalImageEditor/imageSetup.d.ts +9 -0
  24. package/src/components/GlobalImageEditor/imageSetup.d.ts.map +1 -0
  25. package/src/components/GlobalImageEditor/imageSetup.ts +306 -0
  26. package/src/components/GlobalImageEditor/saveLogic.d.ts +26 -0
  27. package/src/components/GlobalImageEditor/saveLogic.d.ts.map +1 -0
  28. package/src/components/GlobalImageEditor/saveLogic.ts +133 -0
  29. package/src/components/GlobalImageEditor/stylingDetection.d.ts +9 -0
  30. package/src/components/GlobalImageEditor/stylingDetection.d.ts.map +1 -0
  31. package/src/components/GlobalImageEditor/stylingDetection.ts +122 -0
  32. package/src/components/GlobalImageEditor/transformParsing.d.ts +16 -0
  33. package/src/components/GlobalImageEditor/transformParsing.d.ts.map +1 -0
  34. package/src/components/GlobalImageEditor/transformParsing.ts +83 -0
  35. package/src/components/GlobalImageEditor/types.d.ts +36 -0
  36. package/src/components/GlobalImageEditor/types.d.ts.map +1 -0
  37. package/src/components/GlobalImageEditor/types.ts +39 -0
  38. package/src/components/GlobalImageEditor.d.ts +8 -0
  39. package/src/components/GlobalImageEditor.d.ts.map +1 -0
  40. package/src/components/GlobalImageEditor.tsx +327 -0
  41. package/src/components/Image.d.ts +22 -0
  42. package/src/components/Image.d.ts.map +1 -0
  43. package/src/components/Image.tsx +343 -0
  44. package/src/components/ImageBrowserModal.d.ts +13 -0
  45. package/src/components/ImageBrowserModal.d.ts.map +1 -0
  46. package/src/components/ImageBrowserModal.tsx +837 -0
  47. package/src/components/ImageEditor.d.ts +27 -0
  48. package/src/components/ImageEditor.d.ts.map +1 -0
  49. package/src/components/ImageEditor.tsx +323 -0
  50. package/src/components/ImageEffectsPanel.tsx +116 -0
  51. package/src/components/ImagePicker.d.ts +3 -0
  52. package/src/components/ImagePicker.d.ts.map +1 -0
  53. package/src/components/ImagePicker.tsx +265 -0
  54. package/src/components/ImagesPluginInit.d.ts +24 -0
  55. package/src/components/ImagesPluginInit.d.ts.map +1 -0
  56. package/src/components/ImagesPluginInit.tsx +31 -0
  57. package/src/components/index.ts +10 -0
  58. package/src/config.ts +179 -0
  59. package/src/hooks/useImagePicker.d.ts +20 -0
  60. package/src/hooks/useImagePicker.d.ts.map +1 -0
  61. package/src/hooks/useImagePicker.ts +344 -0
  62. package/src/index.server.ts +12 -0
  63. package/src/index.tsx +56 -0
  64. package/src/init.tsx +58 -0
  65. package/src/types/index.d.ts +80 -0
  66. package/src/types/index.d.ts.map +1 -0
  67. package/src/types/index.ts +84 -0
  68. package/src/utils/fallback.d.ts +27 -0
  69. package/src/utils/fallback.d.ts.map +1 -0
  70. package/src/utils/fallback.ts +73 -0
  71. package/src/utils/transforms.d.ts +26 -0
  72. package/src/utils/transforms.d.ts.map +1 -0
  73. package/src/utils/transforms.ts +54 -0
  74. package/src/views/ImageManager.d.ts +10 -0
  75. package/src/views/ImageManager.d.ts.map +1 -0
  76. package/src/views/ImageManager.tsx +30 -0
@@ -0,0 +1,343 @@
1
+ 'use client';
2
+
3
+ import NextImage from 'next/image';
4
+ import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
5
+ import { Edit2, Loader2 } from 'lucide-react';
6
+ import { getImageTransform, getImageFilter } from '../utils/transforms';
7
+ import { getFallbackImageUrl } from '../utils/fallback';
8
+
9
+ export interface PluginImageProps {
10
+ id: string;
11
+ alt: string;
12
+ width?: number;
13
+ height?: number;
14
+ className?: string;
15
+ fill?: boolean;
16
+ sizes?: string;
17
+ priority?: boolean;
18
+ objectFit?: 'contain' | 'cover' | 'fill' | 'none' | 'scale-down';
19
+ objectPosition?: string;
20
+ style?: React.CSSProperties;
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;
28
+ }
29
+
30
+ export function Image({
31
+ id,
32
+ alt,
33
+ width,
34
+ height,
35
+ className = '',
36
+ fill = false,
37
+ sizes,
38
+ priority = false,
39
+ objectFit = 'cover',
40
+ objectPosition = 'center',
41
+ style,
42
+ editable = true,
43
+ ...props // Using rest for override props
44
+ }: PluginImageProps) {
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
+
55
+ const [isResolving, setIsResolving] = useState(true);
56
+ const [baseScale, setBaseScale] = useState(1);
57
+ const [isAuthenticated, setIsAuthenticated] = useState(false);
58
+ const [imageError, setImageError] = useState(false);
59
+
60
+ const imageRef = useRef<HTMLImageElement | null>(null);
61
+ const containerRef = useRef<HTMLDivElement>(null);
62
+
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]);
72
+
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 }));
79
+ setIsResolving(false);
80
+ return;
81
+ }
82
+
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())
112
+ .then(data => {
113
+ if (data.loggedIn && ['admin', 'dev'].includes(data.user?.role)) {
114
+ setIsAuthenticated(true);
115
+ }
116
+ })
117
+ .catch(() => setIsAuthenticated(false));
118
+ }, [editable]);
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
+
124
+ useEffect(() => {
125
+ fetchImageMetadata(id);
126
+
127
+ // Only listen to events if props are not provided
128
+ if (hasProps) return;
129
+
130
+ const handleUpdate = (e: any) => {
131
+ if (e.detail?.id === id) {
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
+ }
145
+ }
146
+ };
147
+
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
+ }, []);
180
+
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());
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]);
221
+
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;
242
+
243
+ const filterStyle = getImageFilter(effective.brightness, effective.blur);
244
+
245
+ return (
246
+ <div
247
+ ref={containerRef}
248
+ className={`group/image relative overflow-hidden transition-all duration-300 ${className}`}
249
+ style={{
250
+ ...style,
251
+ filter: filterStyle || style?.filter,
252
+ // Ensure container has explicit positioning context
253
+ position: 'relative',
254
+ }}
255
+ data-image-id={id}
256
+ >
257
+ {isResolving && (
258
+ <div className="absolute inset-0 z-20 flex items-center justify-center bg-neutral-100 dark:bg-neutral-800 animate-pulse">
259
+ <Loader2 className="w-5 h-5 animate-spin text-neutral-400" />
260
+ </div>
261
+ )}
262
+
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
+ )}
324
+
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>
338
+ </div>
339
+ </button>
340
+ )}
341
+ </div>
342
+ );
343
+ }
@@ -0,0 +1,13 @@
1
+ import React from 'react';
2
+ import type { ImageMetadata } from '../types';
3
+ export interface ImageBrowserModalProps {
4
+ isOpen: boolean;
5
+ onClose: () => void;
6
+ onSelectImage: (image: ImageMetadata) => void;
7
+ selectedImageId?: string;
8
+ darkMode?: boolean;
9
+ onUpload?: (file: File) => Promise<void>;
10
+ uploading?: boolean;
11
+ }
12
+ export declare function ImageBrowserModal({ isOpen, onClose, onSelectImage, selectedImageId, darkMode, onUpload, uploading, }: ImageBrowserModalProps): React.ReactPortal | null;
13
+ //# sourceMappingURL=ImageBrowserModal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ImageBrowserModal.d.ts","sourceRoot":"","sources":["ImageBrowserModal.tsx"],"names":[],"mappings":"AAEA,OAAO,KAA4D,MAAM,OAAO,CAAC;AAGjF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AA8P9C,MAAM,WAAW,sBAAsB;IACnC,MAAM,EAAE,OAAO,CAAC;IAChB,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,aAAa,EAAE,CAAC,KAAK,EAAE,aAAa,KAAK,IAAI,CAAC;IAC9C,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzC,SAAS,CAAC,EAAE,OAAO,CAAC;CACvB;AAID,wBAAgB,iBAAiB,CAAC,EAC9B,MAAM,EACN,OAAO,EACP,aAAa,EACb,eAAe,EACf,QAAgB,EAChB,QAAQ,EACR,SAAiB,GACpB,EAAE,sBAAsB,4BA6iBxB"}