@jhits/plugin-images 0.0.8 → 0.0.10

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 (102) hide show
  1. package/package.json +15 -9
  2. package/src/api/fallback/route.ts +0 -69
  3. package/src/api/index.ts +0 -10
  4. package/src/api/list/index.ts +0 -96
  5. package/src/api/resolve/route.ts +0 -241
  6. package/src/api/router.ts +0 -85
  7. package/src/api/upload/index.ts +0 -88
  8. package/src/api/uploads/[filename]/route.ts +0 -93
  9. package/src/api-server.ts +0 -11
  10. package/src/assets/noimagefound.jpg +0 -0
  11. package/src/components/BackgroundImage.d.ts +0 -11
  12. package/src/components/BackgroundImage.d.ts.map +0 -1
  13. package/src/components/BackgroundImage.js +0 -35
  14. package/src/components/BackgroundImage.tsx +0 -92
  15. package/src/components/GlobalImageEditor/config.d.ts +0 -9
  16. package/src/components/GlobalImageEditor/config.d.ts.map +0 -1
  17. package/src/components/GlobalImageEditor/config.js +0 -18
  18. package/src/components/GlobalImageEditor/config.ts +0 -21
  19. package/src/components/GlobalImageEditor/eventHandlers.d.ts +0 -20
  20. package/src/components/GlobalImageEditor/eventHandlers.d.ts.map +0 -1
  21. package/src/components/GlobalImageEditor/eventHandlers.js +0 -206
  22. package/src/components/GlobalImageEditor/eventHandlers.ts +0 -267
  23. package/src/components/GlobalImageEditor/imageDetection.d.ts +0 -16
  24. package/src/components/GlobalImageEditor/imageDetection.d.ts.map +0 -1
  25. package/src/components/GlobalImageEditor/imageDetection.js +0 -130
  26. package/src/components/GlobalImageEditor/imageDetection.ts +0 -160
  27. package/src/components/GlobalImageEditor/imageSetup.d.ts +0 -9
  28. package/src/components/GlobalImageEditor/imageSetup.d.ts.map +0 -1
  29. package/src/components/GlobalImageEditor/imageSetup.js +0 -261
  30. package/src/components/GlobalImageEditor/imageSetup.ts +0 -306
  31. package/src/components/GlobalImageEditor/saveLogic.d.ts +0 -26
  32. package/src/components/GlobalImageEditor/saveLogic.d.ts.map +0 -1
  33. package/src/components/GlobalImageEditor/saveLogic.js +0 -99
  34. package/src/components/GlobalImageEditor/saveLogic.ts +0 -133
  35. package/src/components/GlobalImageEditor/stylingDetection.d.ts +0 -9
  36. package/src/components/GlobalImageEditor/stylingDetection.d.ts.map +0 -1
  37. package/src/components/GlobalImageEditor/stylingDetection.js +0 -110
  38. package/src/components/GlobalImageEditor/stylingDetection.ts +0 -122
  39. package/src/components/GlobalImageEditor/transformParsing.d.ts +0 -16
  40. package/src/components/GlobalImageEditor/transformParsing.d.ts.map +0 -1
  41. package/src/components/GlobalImageEditor/transformParsing.js +0 -68
  42. package/src/components/GlobalImageEditor/transformParsing.ts +0 -83
  43. package/src/components/GlobalImageEditor/types.d.ts +0 -36
  44. package/src/components/GlobalImageEditor/types.d.ts.map +0 -1
  45. package/src/components/GlobalImageEditor/types.js +0 -4
  46. package/src/components/GlobalImageEditor/types.ts +0 -39
  47. package/src/components/GlobalImageEditor.d.ts +0 -8
  48. package/src/components/GlobalImageEditor.d.ts.map +0 -1
  49. package/src/components/GlobalImageEditor.js +0 -227
  50. package/src/components/GlobalImageEditor.tsx +0 -327
  51. package/src/components/Image.d.ts +0 -22
  52. package/src/components/Image.d.ts.map +0 -1
  53. package/src/components/Image.js +0 -229
  54. package/src/components/Image.tsx +0 -343
  55. package/src/components/ImageBrowserModal.d.ts +0 -13
  56. package/src/components/ImageBrowserModal.d.ts.map +0 -1
  57. package/src/components/ImageBrowserModal.js +0 -504
  58. package/src/components/ImageBrowserModal.tsx +0 -837
  59. package/src/components/ImageEditor.d.ts +0 -27
  60. package/src/components/ImageEditor.d.ts.map +0 -1
  61. package/src/components/ImageEditor.js +0 -173
  62. package/src/components/ImageEditor.tsx +0 -323
  63. package/src/components/ImageEffectsPanel.tsx +0 -116
  64. package/src/components/ImagePicker.d.ts +0 -3
  65. package/src/components/ImagePicker.d.ts.map +0 -1
  66. package/src/components/ImagePicker.js +0 -143
  67. package/src/components/ImagePicker.tsx +0 -265
  68. package/src/components/ImagesPluginInit.d.ts +0 -24
  69. package/src/components/ImagesPluginInit.d.ts.map +0 -1
  70. package/src/components/ImagesPluginInit.js +0 -28
  71. package/src/components/ImagesPluginInit.tsx +0 -31
  72. package/src/components/index.ts +0 -10
  73. package/src/config.ts +0 -179
  74. package/src/hooks/useImagePicker.d.ts +0 -20
  75. package/src/hooks/useImagePicker.d.ts.map +0 -1
  76. package/src/hooks/useImagePicker.js +0 -322
  77. package/src/hooks/useImagePicker.ts +0 -344
  78. package/src/index.d.ts +0 -23
  79. package/src/index.d.ts.map +0 -1
  80. package/src/index.js +0 -28
  81. package/src/index.server.ts +0 -12
  82. package/src/index.tsx +0 -56
  83. package/src/init.d.ts +0 -33
  84. package/src/init.d.ts.map +0 -1
  85. package/src/init.js +0 -43
  86. package/src/init.tsx +0 -58
  87. package/src/types/index.d.ts +0 -80
  88. package/src/types/index.d.ts.map +0 -1
  89. package/src/types/index.js +0 -4
  90. package/src/types/index.ts +0 -84
  91. package/src/utils/fallback.d.ts +0 -27
  92. package/src/utils/fallback.d.ts.map +0 -1
  93. package/src/utils/fallback.js +0 -63
  94. package/src/utils/fallback.ts +0 -73
  95. package/src/utils/transforms.d.ts +0 -26
  96. package/src/utils/transforms.d.ts.map +0 -1
  97. package/src/utils/transforms.js +0 -38
  98. package/src/utils/transforms.ts +0 -54
  99. package/src/views/ImageManager.d.ts +0 -10
  100. package/src/views/ImageManager.d.ts.map +0 -1
  101. package/src/views/ImageManager.js +0 -9
  102. package/src/views/ImageManager.tsx +0 -30
@@ -1 +0,0 @@
1
- {"version":3,"file":"Image.d.ts","sourceRoot":"","sources":["Image.tsx"],"names":[],"mappings":"AAGA,OAAO,KAA4D,MAAM,OAAO,CAAC;AAKjF,MAAM,WAAW,gBAAgB;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,SAAS,CAAC,EAAE,SAAS,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,YAAY,CAAC;IACjE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,KAAK,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC;IAC5B,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,wBAAgB,KAAK,CAAC,EAClB,EAAE,EACF,GAAG,EACH,KAAK,EACL,MAAM,EACN,SAAc,EACd,IAAY,EACZ,KAAK,EACL,QAAgB,EAChB,SAAmB,EACnB,cAAyB,EACzB,KAAK,EACL,QAAe,EACf,GAAG,KAAK,EACX,EAAE,gBAAgB,2CA2SlB"}
@@ -1,229 +0,0 @@
1
- 'use client';
2
- var __rest = (this && this.__rest) || function (s, e) {
3
- var t = {};
4
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
- t[p] = s[p];
6
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
- t[p[i]] = s[p[i]];
10
- }
11
- return t;
12
- };
13
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
14
- import NextImage from 'next/image';
15
- import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
16
- import { Edit2, Loader2 } from 'lucide-react';
17
- import { getImageTransform, getImageFilter } from '../utils/transforms';
18
- import { getFallbackImageUrl } from '../utils/fallback';
19
- export function Image(_a) {
20
- var { id, alt, width, height, className = '', fill = false, sizes, priority = false, objectFit = 'cover', objectPosition = 'center', style, editable = true } = _a, props = __rest(_a, ["id", "alt", "width", "height", "className", "fill", "sizes", "priority", "objectFit", "objectPosition", "style", "editable"]) // Using rest for override props
21
- ;
22
- // 1. State management (Local only, used if props are undefined)
23
- const [apiData, setApiData] = useState({
24
- filename: null,
25
- brightness: 100,
26
- blur: 0,
27
- scale: 1.0,
28
- positionX: 0,
29
- positionY: 0,
30
- });
31
- const [isResolving, setIsResolving] = useState(true);
32
- const [baseScale, setBaseScale] = useState(1);
33
- const [isAuthenticated, setIsAuthenticated] = useState(false);
34
- const [imageError, setImageError] = useState(false);
35
- const imageRef = useRef(null);
36
- const containerRef = useRef(null);
37
- // 2. Derive "Effective" values (Prop > Local State)
38
- const effective = useMemo(() => {
39
- var _a, _b, _c, _d, _e;
40
- return ({
41
- brightness: (_a = props.brightness) !== null && _a !== void 0 ? _a : apiData.brightness,
42
- blur: (_b = props.blur) !== null && _b !== void 0 ? _b : apiData.blur,
43
- scale: (_c = props.scale) !== null && _c !== void 0 ? _c : apiData.scale,
44
- positionX: (_d = props.positionX) !== null && _d !== void 0 ? _d : apiData.positionX,
45
- positionY: (_e = props.positionY) !== null && _e !== void 0 ? _e : apiData.positionY,
46
- filename: apiData.filename || id
47
- });
48
- }, [props, apiData, id]);
49
- // 3. Optimized Image Resolution
50
- const fetchImageMetadata = useCallback(async (targetId) => {
51
- var _a, _b, _c, _d, _e;
52
- const isLikelyPath = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(targetId) || /^\d+-/.test(targetId);
53
- if (isLikelyPath) {
54
- setApiData(prev => (Object.assign(Object.assign({}, prev), { filename: targetId })));
55
- setIsResolving(false);
56
- return;
57
- }
58
- try {
59
- const res = await fetch(`/api/plugin-images/resolve?id=${encodeURIComponent(targetId)}`);
60
- if (!res.ok)
61
- throw new Error();
62
- const data = await res.json();
63
- const apiPositionX = (_a = data.positionX) !== null && _a !== void 0 ? _a : 0;
64
- const apiPositionY = (_b = data.positionY) !== null && _b !== void 0 ? _b : 0;
65
- const apiScale = (_c = data.scale) !== null && _c !== void 0 ? _c : 1.0;
66
- setApiData({
67
- filename: data.filename || targetId,
68
- brightness: (_d = data.brightness) !== null && _d !== void 0 ? _d : 100,
69
- blur: (_e = data.blur) !== null && _e !== void 0 ? _e : 0,
70
- scale: apiScale,
71
- positionX: apiPositionX,
72
- positionY: apiPositionY,
73
- });
74
- // Reset error state when resolution succeeds (in case it was set during pre-check)
75
- setImageError(false);
76
- }
77
- catch (_f) {
78
- setApiData(prev => (Object.assign(Object.assign({}, prev), { filename: targetId })));
79
- }
80
- finally {
81
- setIsResolving(false);
82
- }
83
- }, []);
84
- // 4. Auth Check (Single mount only)
85
- useEffect(() => {
86
- if (!editable)
87
- return;
88
- fetch('/api/me')
89
- .then(res => res.json())
90
- .then(data => {
91
- var _a;
92
- if (data.loggedIn && ['admin', 'dev'].includes((_a = data.user) === null || _a === void 0 ? void 0 : _a.role)) {
93
- setIsAuthenticated(true);
94
- }
95
- })
96
- .catch(() => setIsAuthenticated(false));
97
- }, [editable]);
98
- // 5. Stable Event Listener (Prevents closure staleness)
99
- // Only fetch from API if props are not provided (parent controls the values)
100
- const hasProps = props.scale !== undefined || props.positionX !== undefined || props.positionY !== undefined || props.brightness !== undefined || props.blur !== undefined;
101
- useEffect(() => {
102
- fetchImageMetadata(id);
103
- // Only listen to events if props are not provided
104
- if (hasProps)
105
- return;
106
- const handleUpdate = (e) => {
107
- var _a;
108
- if (((_a = e.detail) === null || _a === void 0 ? void 0 : _a.id) === id) {
109
- // Only update if the event contains new data
110
- const eventData = e.detail;
111
- if (eventData.scale !== undefined || eventData.positionX !== undefined || eventData.positionY !== undefined || eventData.brightness !== undefined || eventData.blur !== undefined) {
112
- // Update local state directly from event to avoid unnecessary API call
113
- setApiData(prev => {
114
- var _a, _b, _c, _d, _e;
115
- return (Object.assign(Object.assign({}, prev), { brightness: (_a = eventData.brightness) !== null && _a !== void 0 ? _a : prev.brightness, blur: (_b = eventData.blur) !== null && _b !== void 0 ? _b : prev.blur, scale: (_c = eventData.scale) !== null && _c !== void 0 ? _c : prev.scale, positionX: (_d = eventData.positionX) !== null && _d !== void 0 ? _d : prev.positionX, positionY: (_e = eventData.positionY) !== null && _e !== void 0 ? _e : prev.positionY }));
116
- });
117
- }
118
- }
119
- };
120
- window.addEventListener('image-mapping-updated', handleUpdate);
121
- return () => window.removeEventListener('image-mapping-updated', handleUpdate);
122
- }, [id, fetchImageMetadata, hasProps]);
123
- // 6. Layout & Transforms
124
- const calculateBaseScale = useCallback(() => {
125
- var _a, _b;
126
- if (!imageRef.current || !containerRef.current)
127
- return;
128
- const containerWidth = containerRef.current.offsetWidth;
129
- const containerHeight = containerRef.current.offsetHeight;
130
- // Ensure container has dimensions before calculating
131
- if (containerWidth === 0 || containerHeight === 0) {
132
- // Try to get dimensions from computed styles or parent
133
- const parentWidth = (_a = containerRef.current.parentElement) === null || _a === void 0 ? void 0 : _a.clientWidth;
134
- const parentHeight = (_b = containerRef.current.parentElement) === null || _b === void 0 ? void 0 : _b.clientHeight;
135
- if (parentWidth && parentHeight && imageRef.current.naturalWidth > 0) {
136
- const widthRatio = parentWidth / imageRef.current.naturalWidth;
137
- const heightRatio = parentHeight / imageRef.current.naturalHeight;
138
- const calculatedBaseScale = Math.max(widthRatio, heightRatio);
139
- setBaseScale(calculatedBaseScale);
140
- }
141
- return;
142
- }
143
- if (imageRef.current.naturalWidth === 0 || imageRef.current.naturalHeight === 0)
144
- return;
145
- const widthRatio = containerWidth / imageRef.current.naturalWidth;
146
- const heightRatio = containerHeight / imageRef.current.naturalHeight;
147
- const calculatedBaseScale = Math.max(widthRatio, heightRatio);
148
- setBaseScale(calculatedBaseScale);
149
- }, []);
150
- // Only construct image URL if we have a valid filename (not a semantic ID)
151
- // Check if filename looks like an actual file (has extension or starts with timestamp)
152
- const filename = effective.filename;
153
- const hasFileExtension = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(filename);
154
- const looksLikeTimestamp = /^\d+-/.test(filename);
155
- const isValidFilename = hasFileExtension || looksLikeTimestamp;
156
- // Don't construct URL until resolution is complete AND we have a valid filename
157
- const shouldConstructUrl = !isResolving && isValidFilename;
158
- const baseSrc = shouldConstructUrl ? `/api/uploads/${encodeURIComponent(filename)}` : null;
159
- const src = imageError ? getFallbackImageUrl() : (baseSrc || getFallbackImageUrl());
160
- const shouldFill = fill || className.includes('w-full') || className.includes('h-full');
161
- const hasTransforms = effective.scale !== 1 || effective.positionX !== 0 || effective.positionY !== 0;
162
- // Pre-check image URL to detect errors early (only for valid filenames after resolution)
163
- useEffect(() => {
164
- // Don't check if:
165
- // 1. Already in error state
166
- // 2. Still resolving
167
- // 3. No valid base src
168
- // 4. Base src is the fallback URL
169
- if (imageError || isResolving || !baseSrc || baseSrc === getFallbackImageUrl() || !isValidFilename)
170
- return;
171
- const testImg = document.createElement('img');
172
- const handleError = () => {
173
- setImageError(true);
174
- };
175
- const handleLoad = () => {
176
- setImageError(false);
177
- };
178
- testImg.onerror = handleError;
179
- testImg.onload = handleLoad;
180
- testImg.src = baseSrc;
181
- return () => {
182
- testImg.onerror = null;
183
- testImg.onload = null;
184
- };
185
- }, [baseSrc, imageError, isResolving, isValidFilename]);
186
- // Recalculate baseScale when container is resized
187
- useEffect(() => {
188
- if (!hasTransforms || !shouldFill || !containerRef.current)
189
- return;
190
- const resizeObserver = new ResizeObserver(() => {
191
- calculateBaseScale();
192
- });
193
- resizeObserver.observe(containerRef.current);
194
- return () => resizeObserver.disconnect();
195
- }, [hasTransforms, shouldFill, calculateBaseScale]);
196
- const transformStyle = hasTransforms && baseScale > 0 ? (() => {
197
- return getImageTransform({
198
- scale: effective.scale,
199
- positionX: effective.positionX,
200
- positionY: effective.positionY,
201
- baseScale
202
- }, true);
203
- })() : undefined;
204
- const filterStyle = getImageFilter(effective.brightness, effective.blur);
205
- return (_jsxs("div", { ref: containerRef, className: `group/image relative overflow-hidden transition-all duration-300 ${className}`, style: Object.assign(Object.assign({}, style), { filter: filterStyle || (style === null || style === void 0 ? void 0 : style.filter),
206
- // Ensure container has explicit positioning context
207
- position: 'relative' }), "data-image-id": id, children: [isResolving && (_jsx("div", { className: "absolute inset-0 z-20 flex items-center justify-center bg-neutral-100 dark:bg-neutral-800 animate-pulse", children: _jsx(Loader2, { className: "w-5 h-5 animate-spin text-neutral-400" }) })), hasTransforms && shouldFill ? (baseSrc ? (_jsx("img", { ref: imageRef, src: src, alt: alt, loading: priority ? 'eager' : 'lazy', onLoad: calculateBaseScale, onError: () => setImageError(true), className: "absolute max-w-none select-none", style: {
208
- top: '50%',
209
- left: '50%',
210
- width: 'auto', // Allow image to maintain natural aspect ratio
211
- height: 'auto', // Allow image to maintain natural aspect ratio
212
- minWidth: '100%', // Ensure image covers container width
213
- minHeight: '100%', // Ensure image covers container height
214
- transform: baseScale > 0 && transformStyle
215
- ? transformStyle
216
- : 'translate(-50%, -50%)',
217
- transformOrigin: 'center center',
218
- position: 'absolute',
219
- }, draggable: false })) : null) : imageError || !baseSrc ? (
220
- // Fallback to regular img tag when error occurs or no valid filename yet
221
- _jsx("img", { src: getFallbackImageUrl(), alt: alt, loading: priority ? 'eager' : 'lazy', className: `transition-all duration-500 ${editable ? 'group-hover/image:scale-105' : ''}`, style: Object.assign(Object.assign({ objectFit,
222
- objectPosition, width: shouldFill ? '100%' : width, height: shouldFill ? '100%' : height }, (transformStyle ? { transform: transformStyle } : {})), style) })) : (_jsx(NextImage, { src: src, alt: alt, width: !shouldFill ? width : undefined, height: !shouldFill ? height : undefined, fill: shouldFill, sizes: sizes || (shouldFill ? "(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw" : undefined), priority: priority, loading: priority ? 'eager' : undefined, className: `transition-all duration-500 ${editable ? 'group-hover/image:scale-105' : ''}`, style: Object.assign(Object.assign({ objectFit,
223
- objectPosition }, (transformStyle ? { transform: transformStyle } : {})), style) })), editable && isAuthenticated && (_jsx("button", { onClick: (e) => {
224
- e.preventDefault();
225
- window.dispatchEvent(new CustomEvent('open-image-editor', {
226
- detail: { id, currentBrightness: effective.brightness, currentBlur: effective.blur }
227
- }));
228
- }, 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]", children: _jsxs("div", { className: "flex items-center gap-2 px-4 py-2 bg-white dark:bg-neutral-800 rounded-full shadow-xl", children: [_jsx(Edit2, { size: 14, className: "text-primary" }), _jsx("span", { className: "text-[10px] font-bold uppercase tracking-widest", children: "Edit" })] }) }))] }));
229
- }
@@ -1,343 +0,0 @@
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
- }
@@ -1,13 +0,0 @@
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
@@ -1 +0,0 @@
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"}