@jhits/plugin-images 0.0.7 → 0.0.9

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 +8 -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
package/src/config.ts DELETED
@@ -1,179 +0,0 @@
1
- /**
2
- * Plugin Images Configuration
3
- * Automatically creates required API routes in client apps
4
- */
5
-
6
- import { writeFileSync, mkdirSync, existsSync } from 'fs';
7
- import { join } from 'path';
8
-
9
- /**
10
- * Automatically creates plugin-images API catch-all route
11
- * This route forwards requests to the plugin's API router
12
- */
13
- /**
14
- * @deprecated Routes are now handled by the unified /api/[pluginId]/[...path]/route.ts
15
- * This function is kept for backwards compatibility but does nothing
16
- */
17
- export function ensureImagesRoutes() {
18
- // Routes are now handled by the unified /api/[pluginId]/[...path]/route.ts
19
- // No need to generate individual routes anymore
20
- return;
21
- try {
22
- // Find the host app directory (where next.config.ts is)
23
- let appDir = process.cwd();
24
- const possiblePaths = [
25
- appDir,
26
- join(appDir, '..'),
27
- join(appDir, '..', '..'),
28
- ];
29
-
30
- for (const basePath of possiblePaths) {
31
- const configPath = join(basePath, 'next.config.ts');
32
- if (existsSync(configPath)) {
33
- appDir = basePath;
34
- break;
35
- }
36
- }
37
-
38
- const apiDir = join(appDir, 'src', 'app', 'api');
39
- const pluginImagesApiDir = join(apiDir, 'plugin-images', '[...path]');
40
- const pluginImagesApiPath = join(pluginImagesApiDir, 'route.ts');
41
-
42
- // Check if route already exists
43
- if (existsSync(pluginImagesApiPath)) {
44
- const fs = require('fs');
45
- const existingContent = fs.readFileSync(pluginImagesApiPath, 'utf8');
46
- if (existingContent.includes('@jhits/plugin-images') || existingContent.includes('plugin-images')) {
47
- // Already set up, skip
48
- return;
49
- }
50
- }
51
-
52
- // Create plugin-images API catch-all route
53
- mkdirSync(pluginImagesApiDir, { recursive: true });
54
- writeFileSync(pluginImagesApiPath, `// Auto-generated by @jhits/plugin-images - Images Plugin API
55
- // This route is automatically created for the images plugin
56
- import { NextRequest } from 'next/server';
57
- import { handleImagesApi } from '@jhits/plugin-images/api';
58
-
59
- export async function GET(
60
- req: NextRequest,
61
- { params }: { params: Promise<{ path: string[] }> }
62
- ) {
63
- const { path } = await params;
64
- return handleImagesApi(req, path);
65
- }
66
-
67
- export async function POST(
68
- req: NextRequest,
69
- { params }: { params: Promise<{ path: string[] }> }
70
- ) {
71
- const { path } = await params;
72
- return handleImagesApi(req, path);
73
- }
74
-
75
- export async function PUT(
76
- req: NextRequest,
77
- { params }: { params: Promise<{ path: string[] }> }
78
- ) {
79
- const { path } = await params;
80
- return handleImagesApi(req, path);
81
- }
82
-
83
- export async function DELETE(
84
- req: NextRequest,
85
- { params }: { params: Promise<{ path: string[] }> }
86
- ) {
87
- const { path } = await params;
88
- return handleImagesApi(req, path);
89
- }
90
-
91
- export async function PATCH(
92
- req: NextRequest,
93
- { params }: { params: Promise<{ path: string[] }> }
94
- ) {
95
- const { path } = await params;
96
- return handleImagesApi(req, path);
97
- }
98
- `);
99
-
100
- // Also create uploads route for serving files
101
- const uploadsApiDir = join(apiDir, 'uploads', '[filename]');
102
- const uploadsApiPath = join(uploadsApiDir, 'route.ts');
103
-
104
- if (!existsSync(uploadsApiPath)) {
105
- mkdirSync(uploadsApiDir, { recursive: true });
106
- writeFileSync(uploadsApiPath, `// Auto-generated by @jhits/plugin-images - Image Uploads API
107
- // This route is automatically created for the images plugin
108
- import { NextRequest, NextResponse } from 'next/server';
109
- import { readFile } from 'fs/promises';
110
- import path from 'path';
111
- import { existsSync } from 'fs';
112
-
113
- export async function GET(
114
- request: NextRequest,
115
- { params }: { params: Promise<{ filename: string }> }
116
- ) {
117
- const { filename } = await params;
118
-
119
- // Security: Prevent directory traversal (only allow the filename)
120
- const sanitizedFilename = path.basename(filename);
121
- const filePath = path.join(process.cwd(), 'data', 'uploads', sanitizedFilename);
122
-
123
- try {
124
- const fileBuffer = await readFile(filePath);
125
-
126
- // Determine content type based on extension
127
- const ext = path.extname(sanitizedFilename).toLowerCase();
128
- let contentType = 'application/octet-stream';
129
- if (ext === '.png') contentType = 'image/png';
130
- else if (ext === '.jpg' || ext === '.jpeg') contentType = 'image/jpeg';
131
- else if (ext === '.gif') contentType = 'image/gif';
132
- else if (ext === '.webp') contentType = 'image/webp';
133
- else if (ext === '.svg') contentType = 'image/svg+xml';
134
-
135
- return new NextResponse(fileBuffer, {
136
- headers: {
137
- 'Content-Type': contentType,
138
- 'Cache-Control': 'public, max-age=31536000, immutable',
139
- },
140
- });
141
- } catch (e) {
142
- console.error('File serving error:', e);
143
- return new NextResponse('File not found', { status: 404 });
144
- }
145
- }
146
-
147
- export async function DELETE(
148
- request: NextRequest,
149
- { params }: { params: Promise<{ filename: string }> }
150
- ) {
151
- const { filename } = await params;
152
-
153
- if (!filename) {
154
- return new NextResponse('Missing filename', { status: 400 });
155
- }
156
-
157
- const sanitizedFilename = path.basename(filename);
158
- const filePath = path.join(process.cwd(), 'data', 'uploads', sanitizedFilename);
159
-
160
- if (!existsSync(filePath)) {
161
- return new NextResponse('File not found', { status: 404 });
162
- }
163
-
164
- try {
165
- const { unlink } = require('fs/promises');
166
- await unlink(filePath);
167
- return NextResponse.json({ success: true, message: \`"\${sanitizedFilename}" deleted successfully.\` });
168
- } catch (error) {
169
- console.error('Failed to delete file:', error);
170
- return new NextResponse('Failed to delete file', { status: 500 });
171
- }
172
- }
173
- `);
174
- }
175
- } catch (error) {
176
- // Ignore errors - route might already exist or app structure is different
177
- console.warn('[plugin-images] Could not ensure images routes:', error);
178
- }
179
- }
@@ -1,20 +0,0 @@
1
- /**
2
- * Hook for Image Picker Logic
3
- */
4
- import type { ImageMetadata } from '../types';
5
- export interface UseImagePickerOptions {
6
- value?: string;
7
- images: ImageMetadata[];
8
- }
9
- export declare function useImagePicker({ value, images }: UseImagePickerOptions): {
10
- selectedImage: ImageMetadata | null;
11
- setSelectedImage: import("react").Dispatch<import("react").SetStateAction<ImageMetadata | null>>;
12
- uploading: boolean;
13
- fileInputRef: import("react").RefObject<HTMLInputElement | null>;
14
- handleFileSelect: (e?: React.ChangeEvent<HTMLInputElement> | {
15
- target: {
16
- files: File[] | null;
17
- };
18
- }) => Promise<any>;
19
- };
20
- //# sourceMappingURL=useImagePicker.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useImagePicker.d.ts","sourceRoot":"","sources":["useImagePicker.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAE9C,MAAM,WAAW,qBAAqB;IAClC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,aAAa,EAAE,CAAC;CAC3B;AAED,wBAAgB,cAAc,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,qBAAqB;;;;;2BA6R/B,KAAK,CAAC,WAAW,CAAC,gBAAgB,CAAC,GAAG;QAAE,MAAM,EAAE;YAAE,KAAK,EAAE,IAAI,EAAE,GAAG,IAAI,CAAA;SAAE,CAAA;KAAE;EA8CjH"}
@@ -1,322 +0,0 @@
1
- /**
2
- * Hook for Image Picker Logic
3
- */
4
- import { useState, useEffect, useRef } from 'react';
5
- export function useImagePicker({ value, images }) {
6
- const [selectedImage, setSelectedImage] = useState(null);
7
- const [uploading, setUploading] = useState(false);
8
- const fileInputRef = useRef(null);
9
- const lastResolvedValueRef = useRef(undefined);
10
- const isResolvingRef = useRef(false);
11
- const lastImagesRef = useRef('');
12
- // Find selected image from value (can be ID or URL)
13
- useEffect(() => {
14
- // Create a stable reference for images array to detect actual changes
15
- const imagesKey = JSON.stringify(images.map(img => ({ id: img.id, url: img.url })));
16
- // Prevent infinite loops by checking if we're already resolving or if value and images haven't changed
17
- if (isResolvingRef.current || (lastResolvedValueRef.current === value && lastImagesRef.current === imagesKey)) {
18
- return;
19
- }
20
- lastImagesRef.current = imagesKey;
21
- if (!value) {
22
- if (selectedImage !== null) {
23
- setSelectedImage(null);
24
- }
25
- lastResolvedValueRef.current = value;
26
- return;
27
- }
28
- isResolvingRef.current = true;
29
- const resolveImage = async () => {
30
- var _a, _b, _c;
31
- // Normalize the value - extract filename if it's a URL
32
- const isFullUrl = value.startsWith('http://') || value.startsWith('https://');
33
- const isRelativeUrl = value.startsWith('/');
34
- const isUrl = isFullUrl || isRelativeUrl;
35
- // Extract filename from URL if it's a URL
36
- let filenameFromUrl = null;
37
- let imageIdToResolve = value;
38
- if (isUrl) {
39
- const urlParts = value.split('/');
40
- filenameFromUrl = ((_a = urlParts[urlParts.length - 1]) === null || _a === void 0 ? void 0 : _a.split('?')[0]) || null;
41
- // If it's a full URL, try to resolve using the filename instead
42
- if (isFullUrl && filenameFromUrl) {
43
- imageIdToResolve = filenameFromUrl;
44
- }
45
- }
46
- // First, try to find by ID (preferred method)
47
- let found = images.find(img => img.id === value || img.id === imageIdToResolve);
48
- // If not found by ID, try to find by URL
49
- if (!found) {
50
- found = images.find(img => img.url === value);
51
- }
52
- // If still not found, try to match by filename extracted from URL
53
- if (!found && filenameFromUrl) {
54
- found = images.find(img => img.id === filenameFromUrl || img.filename === filenameFromUrl);
55
- }
56
- if (found) {
57
- // Only update if the image is actually different
58
- setSelectedImage(prev => {
59
- if ((prev === null || prev === void 0 ? void 0 : prev.id) === found.id && (prev === null || prev === void 0 ? void 0 : prev.url) === found.url) {
60
- return prev;
61
- }
62
- return found;
63
- });
64
- }
65
- else {
66
- // If value is already a full URL, use it directly
67
- if (isFullUrl) {
68
- const newImage = {
69
- id: value,
70
- filename: filenameFromUrl || value,
71
- url: value, // Use the full URL as-is
72
- size: 0,
73
- mimeType: 'image/jpeg',
74
- uploadedAt: new Date().toISOString(),
75
- };
76
- setSelectedImage(prev => {
77
- if ((prev === null || prev === void 0 ? void 0 : prev.id) === newImage.id && (prev === null || prev === void 0 ? void 0 : prev.url) === newImage.url) {
78
- return prev;
79
- }
80
- return newImage;
81
- });
82
- lastResolvedValueRef.current = value;
83
- isResolvingRef.current = false;
84
- return;
85
- }
86
- // If value is a relative URL, use it directly
87
- if (isRelativeUrl) {
88
- const newImage = {
89
- id: value,
90
- filename: filenameFromUrl || value,
91
- url: value, // Use the relative URL as-is
92
- size: 0,
93
- mimeType: 'image/jpeg',
94
- uploadedAt: new Date().toISOString(),
95
- };
96
- setSelectedImage(prev => {
97
- if ((prev === null || prev === void 0 ? void 0 : prev.id) === newImage.id && (prev === null || prev === void 0 ? void 0 : prev.url) === newImage.url) {
98
- return prev;
99
- }
100
- return newImage;
101
- });
102
- lastResolvedValueRef.current = value;
103
- isResolvingRef.current = false;
104
- return;
105
- }
106
- // Check if value looks like a filename (has extension or starts with digits)
107
- const isLikelyPath = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(value) || /^\d+-/.test(value);
108
- if (isLikelyPath) {
109
- // It's likely a filename, create image object directly
110
- const newImage = {
111
- id: value,
112
- filename: value,
113
- url: `/api/uploads/${value}`,
114
- size: 0,
115
- mimeType: 'image/jpeg',
116
- uploadedAt: new Date().toISOString(),
117
- };
118
- setSelectedImage(prev => {
119
- if ((prev === null || prev === void 0 ? void 0 : prev.id) === newImage.id && (prev === null || prev === void 0 ? void 0 : prev.url) === newImage.url) {
120
- return prev;
121
- }
122
- return newImage;
123
- });
124
- lastResolvedValueRef.current = value;
125
- isResolvingRef.current = false;
126
- }
127
- else {
128
- // It might be a semantic ID, try to resolve via API
129
- // Use the extracted ID (filename) if value was a URL, otherwise use value
130
- try {
131
- const response = await fetch(`/api/plugin-images/resolve?id=${encodeURIComponent(imageIdToResolve)}`);
132
- if (response.ok) {
133
- const data = await response.json();
134
- // Normalize the URL - ensure it's a proper URL
135
- let imageUrl;
136
- if (data.url) {
137
- // If API returns a URL, use it (but check if it's already a full URL)
138
- if (data.url.startsWith('http://') || data.url.startsWith('https://')) {
139
- imageUrl = data.url;
140
- }
141
- else if (data.url.startsWith('/')) {
142
- imageUrl = data.url;
143
- }
144
- else {
145
- // Relative path without leading slash
146
- imageUrl = `/api/uploads/${data.url}`;
147
- }
148
- }
149
- else if (data.filename) {
150
- // Use filename to construct URL
151
- imageUrl = `/api/uploads/${data.filename}`;
152
- }
153
- else {
154
- // Fallback: if original value was a URL, use it; otherwise construct
155
- imageUrl = isFullUrl ? value : (isRelativeUrl ? value : `/api/uploads/${value}`);
156
- }
157
- const newImage = {
158
- id: value,
159
- filename: data.filename || filenameFromUrl || value,
160
- url: imageUrl,
161
- size: 0,
162
- mimeType: 'image/jpeg',
163
- uploadedAt: new Date().toISOString(),
164
- };
165
- setSelectedImage(prev => {
166
- if ((prev === null || prev === void 0 ? void 0 : prev.id) === newImage.id && (prev === null || prev === void 0 ? void 0 : prev.url) === newImage.url) {
167
- return prev;
168
- }
169
- return newImage;
170
- });
171
- lastResolvedValueRef.current = value;
172
- isResolvingRef.current = false;
173
- }
174
- else {
175
- // API resolution failed - check if it's a semantic ID or actual filename
176
- const isLikelyFilename = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(imageIdToResolve) || /^\d+-/.test(imageIdToResolve);
177
- if (!isLikelyFilename) {
178
- // It's a semantic ID that couldn't be resolved - clear selection
179
- // This prevents showing broken URLs like /api/uploads/blog-featured-...
180
- setSelectedImage(null);
181
- lastResolvedValueRef.current = value;
182
- isResolvingRef.current = false;
183
- return;
184
- }
185
- // It's a filename, create fallback object
186
- const isFullUrl = value.startsWith('http://') || value.startsWith('https://');
187
- const isRelativeUrl = value.startsWith('/');
188
- let imageUrl;
189
- if (isFullUrl) {
190
- // Already a full URL, use as-is
191
- imageUrl = value;
192
- }
193
- else if (isRelativeUrl) {
194
- // Already a relative URL starting with /, use as-is
195
- imageUrl = value;
196
- }
197
- else {
198
- // It's a filename, construct the URL
199
- imageUrl = `/api/uploads/${value}`;
200
- }
201
- const urlParts = value.split('/');
202
- const filename = ((_b = urlParts[urlParts.length - 1]) === null || _b === void 0 ? void 0 : _b.split('?')[0]) || value;
203
- const newImage = {
204
- id: value,
205
- filename: filename,
206
- url: imageUrl,
207
- size: 0,
208
- mimeType: 'image/jpeg',
209
- uploadedAt: new Date().toISOString(),
210
- };
211
- setSelectedImage(prev => {
212
- if ((prev === null || prev === void 0 ? void 0 : prev.id) === newImage.id && (prev === null || prev === void 0 ? void 0 : prev.url) === newImage.url) {
213
- return prev;
214
- }
215
- return newImage;
216
- });
217
- lastResolvedValueRef.current = value;
218
- isResolvingRef.current = false;
219
- }
220
- }
221
- catch (error) {
222
- // API call failed - check if it's a semantic ID or actual filename
223
- const isLikelyFilename = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(imageIdToResolve) || /^\d+-/.test(imageIdToResolve);
224
- if (!isLikelyFilename) {
225
- // It's a semantic ID that couldn't be resolved - clear selection
226
- // This prevents showing broken URLs like /api/uploads/blog-featured-...
227
- setSelectedImage(null);
228
- lastResolvedValueRef.current = value;
229
- isResolvingRef.current = false;
230
- return;
231
- }
232
- // It's a filename, create fallback object
233
- const isFullUrl = value.startsWith('http://') || value.startsWith('https://');
234
- const isRelativeUrl = value.startsWith('/');
235
- let imageUrl;
236
- if (isFullUrl) {
237
- // Already a full URL, use as-is
238
- imageUrl = value;
239
- }
240
- else if (isRelativeUrl) {
241
- // Already a relative URL starting with /, use as-is
242
- imageUrl = value;
243
- }
244
- else {
245
- // It's a filename, construct the URL
246
- imageUrl = `/api/uploads/${value}`;
247
- }
248
- const urlParts = value.split('/');
249
- const filename = ((_c = urlParts[urlParts.length - 1]) === null || _c === void 0 ? void 0 : _c.split('?')[0]) || value;
250
- const newImage = {
251
- id: value,
252
- filename: filename,
253
- url: imageUrl,
254
- size: 0,
255
- mimeType: 'image/jpeg',
256
- uploadedAt: new Date().toISOString(),
257
- };
258
- setSelectedImage(prev => {
259
- if ((prev === null || prev === void 0 ? void 0 : prev.id) === newImage.id && (prev === null || prev === void 0 ? void 0 : prev.url) === newImage.url) {
260
- return prev;
261
- }
262
- return newImage;
263
- });
264
- lastResolvedValueRef.current = value;
265
- isResolvingRef.current = false;
266
- }
267
- }
268
- }
269
- };
270
- resolveImage().catch(() => {
271
- // Error already handled in catch block
272
- isResolvingRef.current = false;
273
- });
274
- }, [value, images]);
275
- // Handle file upload
276
- const handleFileSelect = async (e) => {
277
- var _a, _b;
278
- const file = (_b = (_a = e === null || e === void 0 ? void 0 : e.target) === null || _a === void 0 ? void 0 : _a.files) === null || _b === void 0 ? void 0 : _b[0];
279
- if (!file)
280
- return null;
281
- setUploading(true);
282
- try {
283
- const formData = new FormData();
284
- formData.append('file', file);
285
- const response = await fetch('/api/plugin-images/upload', {
286
- method: 'POST',
287
- body: formData,
288
- });
289
- const data = await response.json();
290
- if (data.success && data.image) {
291
- // Select the newly uploaded image
292
- setSelectedImage(data.image);
293
- if (fileInputRef.current) {
294
- fileInputRef.current.value = '';
295
- }
296
- return data.image;
297
- }
298
- else {
299
- alert(data.error || 'Failed to upload image');
300
- return null;
301
- }
302
- }
303
- catch (error) {
304
- console.error('Upload error:', error);
305
- alert('Failed to upload image');
306
- return null;
307
- }
308
- finally {
309
- setUploading(false);
310
- if (fileInputRef.current) {
311
- fileInputRef.current.value = '';
312
- }
313
- }
314
- };
315
- return {
316
- selectedImage,
317
- setSelectedImage,
318
- uploading,
319
- fileInputRef,
320
- handleFileSelect,
321
- };
322
- }