@adminforth/upload 2.0.0 → 2.1.0

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/README.md CHANGED
@@ -4,4 +4,4 @@
4
4
 
5
5
  Allows to upload files to Amazon S3 bucket from adminforth application.
6
6
 
7
- ## For usage, see [AdminForth Upload Documentation](https://adminforth.dev/docs/tutorial/Plugins/upload/)
7
+ ## For usage, see [AdminForth Upload Documentation](https://adminforth.dev/docs/tutorial/Plugins/upload/)
package/build.log CHANGED
@@ -11,5 +11,5 @@ custom/preview.vue
11
11
  custom/tsconfig.json
12
12
  custom/uploader.vue
13
13
 
14
- sent 43,158 bytes received 134 bytes 86,584.00 bytes/sec
15
- total size is 42,676 speedup is 0.99
14
+ sent 46,094 bytes received 134 bytes 92,456.00 bytes/sec
15
+ total size is 45,612 speedup is 0.99
@@ -21,10 +21,41 @@
21
21
  </div>
22
22
  <!-- Modal body -->
23
23
  <div class="p-4 md:p-5 space-y-4">
24
- <textarea id="message" rows="3" class="block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
25
- :placeholder="$t('Prompt which will be passed to AI network')" v-model="prompt"
24
+ <!-- PROMPT TEXTAREA -->
25
+ <!-- Textarea -->
26
+ <textarea
27
+ id="message"
28
+ rows="3"
29
+ class="block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
30
+ :placeholder="$t('Prompt which will be passed to AI network')"
31
+ v-model="prompt"
26
32
  :title="$t('Prompt which will be passed to AI network')"
27
- ></textarea>
33
+ ></textarea>
34
+
35
+ <!-- Thumbnails -->
36
+ <div class="mt-2 flex flex-wrap gap-2">
37
+ <img
38
+ v-for="(img, idx) in attachmentFiles"
39
+ :key="idx"
40
+ :src="img"
41
+ class="w-20 h-20 object-cover rounded cursor-pointer border hover:border-blue-500 transition"
42
+ :alt="`Generated image ${idx + 1}`"
43
+ @click="zoomImage(img)"
44
+ />
45
+ </div>
46
+
47
+ <!-- Fullscreen Modal -->
48
+ <div
49
+ v-if="zoomedImage"
50
+ class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-80"
51
+ @click.self="closeZoom"
52
+ >
53
+ <img
54
+ :src="zoomedImage"
55
+ ref="zoomedImg"
56
+ class="max-w-full max-h-full rounded-lg object-contain cursor-grab"
57
+ />
58
+ </div>
28
59
 
29
60
  <div class="flex flex-col items-center justify-center w-full relative">
30
61
  <div
@@ -144,7 +175,7 @@
144
175
 
145
176
  <script setup lang="ts">
146
177
 
147
- import { ref, onMounted, nextTick, Ref, h, computed } from 'vue'
178
+ import { ref, onMounted, nextTick, Ref, h, computed, watch, reactive } from 'vue'
148
179
  import { Carousel } from 'flowbite';
149
180
  import { callAdminForthApi } from '@/utils';
150
181
  import { useI18n } from 'vue-i18n';
@@ -158,6 +189,7 @@ const emit = defineEmits(['close', 'uploadImage']);
158
189
  const props = defineProps(['meta', 'record']);
159
190
  const images = ref([]);
160
191
  const loading = ref(false);
192
+ const attachmentFiles = ref<string[]>([])
161
193
 
162
194
  function minifyField(field: string): string {
163
195
  if (field.length > 100) {
@@ -167,7 +199,7 @@ function minifyField(field: string): string {
167
199
  }
168
200
 
169
201
  const caurosel = ref(null);
170
- onMounted(() => {
202
+ onMounted(async () => {
171
203
  // Initialize carousel
172
204
  const context = {
173
205
  field: props.meta.pathColumnLabel,
@@ -203,7 +235,24 @@ onMounted(() => {
203
235
  prompt.value = template.replace(regex, (_, field) => {
204
236
  return context[field.trim()] || '';
205
237
  });
238
+
239
+ const recordId = props.record[props.meta.recorPkFieldName];
240
+ if (!recordId) return;
241
+
242
+ try {
243
+ const resp = await callAdminForthApi({
244
+ path: `/plugin/${props.meta.pluginInstanceId}/get_attachment_files`,
245
+ method: 'POST',
246
+ body: { recordId },
247
+ });
206
248
 
249
+ if (resp?.files?.length) {
250
+ attachmentFiles.value = resp.files;
251
+ console.log('attachmentFiles', attachmentFiles.value);
252
+ }
253
+ } catch (err) {
254
+ console.error('Failed to fetch attachment files', err);
255
+ }
207
256
  });
208
257
 
209
258
  async function slide(direction: number) {
@@ -357,6 +406,27 @@ async function generateImages() {
357
406
  loading.value = false;
358
407
  }
359
408
 
409
+ import mediumZoom from 'medium-zoom'
360
410
 
411
+ const zoomedImage = ref(null)
412
+ const zoomedImg = ref(null)
413
+
414
+ function zoomImage(img) {
415
+ zoomedImage.value = img
416
+ }
361
417
 
418
+ function closeZoom() {
419
+ zoomedImage.value = null
420
+ }
421
+
422
+ watch(zoomedImage, async (val) => {
423
+ await nextTick()
424
+ if (val && zoomedImg.value) {
425
+ mediumZoom(zoomedImg.value, {
426
+ margin: 24,
427
+ background: 'rgba(0, 0, 0, 0.9)',
428
+ scrollOffset: 150
429
+ }).show()
430
+ }
431
+ })
362
432
  </script>
@@ -58,7 +58,7 @@
58
58
  } */
59
59
  </style>
60
60
  <script setup>
61
- import { ref, computed , onMounted, watch} from 'vue'
61
+ import { ref, computed , onMounted, watch, nextTick} from 'vue'
62
62
  import mediumZoom from 'medium-zoom'
63
63
  import { useRoute } from 'vue-router'
64
64
 
@@ -71,6 +71,30 @@ const props = defineProps({
71
71
  meta: Object,
72
72
  })
73
73
 
74
+ const trueContentType = ref(null);
75
+
76
+ onMounted(async () => {
77
+ // try to get HEAD request
78
+ try {
79
+ const response = await fetch(url.value, {
80
+ method: 'HEAD',
81
+ });
82
+ const ct = response.headers.get('Content-Type');
83
+ if (ct) {
84
+ trueContentType.value = ct;
85
+ }
86
+ } catch (e) {
87
+ console.error('fetch error for getting content type, please check CORS allowed for HEAD request', e);
88
+ }
89
+ });
90
+
91
+ const contentType = computed(() => {
92
+ if (trueContentType.value) {
93
+ return trueContentType.value;
94
+ }
95
+ return guessedContentType.value;
96
+ });
97
+
74
98
  const route = useRoute();
75
99
  const url = computed(() => {
76
100
  return props.record[`previewUrl_${props.meta.pluginInstanceId}`];
@@ -95,11 +119,11 @@ const minWidth = computed(() => {
95
119
  });
96
120
  // since we have no way to know the content type of the file, we will try to guess it from extension
97
121
  // for better experience probably we should check whether user saves content type in the database and use it here
98
- const contentType = computed(() => {
122
+ const guessedContentType = computed(() => {
99
123
  if (!url.value) {
100
124
  return null;
101
125
  }
102
- const u = new URL(url.value);
126
+ const u = new URL(url.value, url.value.startsWith('http') ? undefined : location.origin);
103
127
  return guessContentType(u.pathname);
104
128
  });
105
129
 
@@ -117,14 +141,18 @@ function guessContentType(url) {
117
141
  }
118
142
 
119
143
 
120
- onMounted(async () => {
121
-
122
- if (contentType.value?.startsWith('image')) {
144
+ watch([contentType], async ([contentType]) => {
145
+ // since content type might change after true guessing (HEAD request might be slow) we need to try initializing zoom again
146
+ if (zoom.value) {
147
+ zoom.value.detach();
148
+ }
149
+ await nextTick();
150
+ if (contentType?.startsWith('image')) {
123
151
  zoom.value = mediumZoom(img.value, {
124
152
  margin: 24,
125
153
  });
126
154
  }
127
155
 
128
- });
156
+ }, { immediate: true });
129
157
 
130
158
  </script>
@@ -273,7 +273,7 @@ const onFileChange = async (e) => {
273
273
  });
274
274
  if (!success) {
275
275
  adminforth.alert({
276
- messageHtml: `<div>${t('Sorry but the file was not uploaded because of S3 Request Error:')}</div>
276
+ messageHtml: `<div>${t('Sorry but the file was not uploaded because of internal storage Request Error:')}</div>
277
277
  <pre style="white-space: pre-wrap; word-wrap: break-word; overflow-wrap: break-word; max-width: 100%;">${
278
278
  xhr.responseText.replace(/</g, '&lt;').replace(/>/g, '&gt;')
279
279
  }</pre>`,
@@ -21,10 +21,41 @@
21
21
  </div>
22
22
  <!-- Modal body -->
23
23
  <div class="p-4 md:p-5 space-y-4">
24
- <textarea id="message" rows="3" class="block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
25
- :placeholder="$t('Prompt which will be passed to AI network')" v-model="prompt"
24
+ <!-- PROMPT TEXTAREA -->
25
+ <!-- Textarea -->
26
+ <textarea
27
+ id="message"
28
+ rows="3"
29
+ class="block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
30
+ :placeholder="$t('Prompt which will be passed to AI network')"
31
+ v-model="prompt"
26
32
  :title="$t('Prompt which will be passed to AI network')"
27
- ></textarea>
33
+ ></textarea>
34
+
35
+ <!-- Thumbnails -->
36
+ <div class="mt-2 flex flex-wrap gap-2">
37
+ <img
38
+ v-for="(img, idx) in attachmentFiles"
39
+ :key="idx"
40
+ :src="img"
41
+ class="w-20 h-20 object-cover rounded cursor-pointer border hover:border-blue-500 transition"
42
+ :alt="`Generated image ${idx + 1}`"
43
+ @click="zoomImage(img)"
44
+ />
45
+ </div>
46
+
47
+ <!-- Fullscreen Modal -->
48
+ <div
49
+ v-if="zoomedImage"
50
+ class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-80"
51
+ @click.self="closeZoom"
52
+ >
53
+ <img
54
+ :src="zoomedImage"
55
+ ref="zoomedImg"
56
+ class="max-w-full max-h-full rounded-lg object-contain cursor-grab"
57
+ />
58
+ </div>
28
59
 
29
60
  <div class="flex flex-col items-center justify-center w-full relative">
30
61
  <div
@@ -144,7 +175,7 @@
144
175
 
145
176
  <script setup lang="ts">
146
177
 
147
- import { ref, onMounted, nextTick, Ref, h, computed } from 'vue'
178
+ import { ref, onMounted, nextTick, Ref, h, computed, watch, reactive } from 'vue'
148
179
  import { Carousel } from 'flowbite';
149
180
  import { callAdminForthApi } from '@/utils';
150
181
  import { useI18n } from 'vue-i18n';
@@ -158,6 +189,7 @@ const emit = defineEmits(['close', 'uploadImage']);
158
189
  const props = defineProps(['meta', 'record']);
159
190
  const images = ref([]);
160
191
  const loading = ref(false);
192
+ const attachmentFiles = ref<string[]>([])
161
193
 
162
194
  function minifyField(field: string): string {
163
195
  if (field.length > 100) {
@@ -167,7 +199,7 @@ function minifyField(field: string): string {
167
199
  }
168
200
 
169
201
  const caurosel = ref(null);
170
- onMounted(() => {
202
+ onMounted(async () => {
171
203
  // Initialize carousel
172
204
  const context = {
173
205
  field: props.meta.pathColumnLabel,
@@ -203,7 +235,24 @@ onMounted(() => {
203
235
  prompt.value = template.replace(regex, (_, field) => {
204
236
  return context[field.trim()] || '';
205
237
  });
238
+
239
+ const recordId = props.record[props.meta.recorPkFieldName];
240
+ if (!recordId) return;
241
+
242
+ try {
243
+ const resp = await callAdminForthApi({
244
+ path: `/plugin/${props.meta.pluginInstanceId}/get_attachment_files`,
245
+ method: 'POST',
246
+ body: { recordId },
247
+ });
206
248
 
249
+ if (resp?.files?.length) {
250
+ attachmentFiles.value = resp.files;
251
+ console.log('attachmentFiles', attachmentFiles.value);
252
+ }
253
+ } catch (err) {
254
+ console.error('Failed to fetch attachment files', err);
255
+ }
207
256
  });
208
257
 
209
258
  async function slide(direction: number) {
@@ -357,6 +406,27 @@ async function generateImages() {
357
406
  loading.value = false;
358
407
  }
359
408
 
409
+ import mediumZoom from 'medium-zoom'
360
410
 
411
+ const zoomedImage = ref(null)
412
+ const zoomedImg = ref(null)
413
+
414
+ function zoomImage(img) {
415
+ zoomedImage.value = img
416
+ }
361
417
 
418
+ function closeZoom() {
419
+ zoomedImage.value = null
420
+ }
421
+
422
+ watch(zoomedImage, async (val) => {
423
+ await nextTick()
424
+ if (val && zoomedImg.value) {
425
+ mediumZoom(zoomedImg.value, {
426
+ margin: 24,
427
+ background: 'rgba(0, 0, 0, 0.9)',
428
+ scrollOffset: 150
429
+ }).show()
430
+ }
431
+ })
362
432
  </script>
@@ -58,7 +58,7 @@
58
58
  } */
59
59
  </style>
60
60
  <script setup>
61
- import { ref, computed , onMounted, watch} from 'vue'
61
+ import { ref, computed , onMounted, watch, nextTick} from 'vue'
62
62
  import mediumZoom from 'medium-zoom'
63
63
  import { useRoute } from 'vue-router'
64
64
 
@@ -71,6 +71,30 @@ const props = defineProps({
71
71
  meta: Object,
72
72
  })
73
73
 
74
+ const trueContentType = ref(null);
75
+
76
+ onMounted(async () => {
77
+ // try to get HEAD request
78
+ try {
79
+ const response = await fetch(url.value, {
80
+ method: 'HEAD',
81
+ });
82
+ const ct = response.headers.get('Content-Type');
83
+ if (ct) {
84
+ trueContentType.value = ct;
85
+ }
86
+ } catch (e) {
87
+ console.error('fetch error for getting content type, please check CORS allowed for HEAD request', e);
88
+ }
89
+ });
90
+
91
+ const contentType = computed(() => {
92
+ if (trueContentType.value) {
93
+ return trueContentType.value;
94
+ }
95
+ return guessedContentType.value;
96
+ });
97
+
74
98
  const route = useRoute();
75
99
  const url = computed(() => {
76
100
  return props.record[`previewUrl_${props.meta.pluginInstanceId}`];
@@ -95,11 +119,11 @@ const minWidth = computed(() => {
95
119
  });
96
120
  // since we have no way to know the content type of the file, we will try to guess it from extension
97
121
  // for better experience probably we should check whether user saves content type in the database and use it here
98
- const contentType = computed(() => {
122
+ const guessedContentType = computed(() => {
99
123
  if (!url.value) {
100
124
  return null;
101
125
  }
102
- const u = new URL(url.value);
126
+ const u = new URL(url.value, url.value.startsWith('http') ? undefined : location.origin);
103
127
  return guessContentType(u.pathname);
104
128
  });
105
129
 
@@ -117,14 +141,18 @@ function guessContentType(url) {
117
141
  }
118
142
 
119
143
 
120
- onMounted(async () => {
121
-
122
- if (contentType.value?.startsWith('image')) {
144
+ watch([contentType], async ([contentType]) => {
145
+ // since content type might change after true guessing (HEAD request might be slow) we need to try initializing zoom again
146
+ if (zoom.value) {
147
+ zoom.value.detach();
148
+ }
149
+ await nextTick();
150
+ if (contentType?.startsWith('image')) {
123
151
  zoom.value = mediumZoom(img.value, {
124
152
  margin: 24,
125
153
  });
126
154
  }
127
155
 
128
- });
156
+ }, { immediate: true });
129
157
 
130
158
  </script>
@@ -273,7 +273,7 @@ const onFileChange = async (e) => {
273
273
  });
274
274
  if (!success) {
275
275
  adminforth.alert({
276
- messageHtml: `<div>${t('Sorry but the file was not uploaded because of S3 Request Error:')}</div>
276
+ messageHtml: `<div>${t('Sorry but the file was not uploaded because of internal storage Request Error:')}</div>
277
277
  <pre style="white-space: pre-wrap; word-wrap: break-word; overflow-wrap: break-word; max-width: 100%;">${
278
278
  xhr.responseText.replace(/</g, '&lt;').replace(/>/g, '&gt;')
279
279
  }</pre>`,
package/dist/index.js CHANGED
@@ -24,7 +24,8 @@ export default class UploadPlugin extends AdminForthPlugin {
24
24
  }
25
25
  setupLifecycleRule() {
26
26
  return __awaiter(this, void 0, void 0, function* () {
27
- this.options.storageAdapter.setupLifecycle();
27
+ const adapterUserUniqueRepresentation = `${this.resourceConfig.resourceId}-${this.pluginInstanceId}`;
28
+ this.options.storageAdapter.setupLifecycle(adapterUserUniqueRepresentation);
28
29
  });
29
30
  }
30
31
  genPreviewUrl(record) {
@@ -45,6 +46,7 @@ export default class UploadPlugin extends AdminForthPlugin {
45
46
  return __awaiter(this, void 0, void 0, function* () {
46
47
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
47
48
  _super.modifyResourceConfig.call(this, adminforth, resourceConfig);
49
+ this.resourceConfig = resourceConfig;
48
50
  // after column to store the path of the uploaded file, add new VirtualColumn,
49
51
  // show only in edit and create views
50
52
  // use component uploader.vue
@@ -316,7 +318,7 @@ export default class UploadPlugin extends AdminForthPlugin {
316
318
  if (!record) {
317
319
  return { error: `Record with id ${recordId} not found` };
318
320
  }
319
- attachmentFiles = this.options.generation.attachFiles({ record, adminUser });
321
+ attachmentFiles = yield this.options.generation.attachFiles({ record, adminUser });
320
322
  // if files is not array, make it array
321
323
  if (!Array.isArray(attachmentFiles)) {
322
324
  attachmentFiles = [attachmentFiles];
@@ -360,5 +362,26 @@ export default class UploadPlugin extends AdminForthPlugin {
360
362
  return null;
361
363
  })
362
364
  });
365
+ server.endpoint({
366
+ method: 'POST',
367
+ path: `/plugin/${this.pluginInstanceId}/get_attachment_files`,
368
+ handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser }) {
369
+ var _b;
370
+ const { recordId } = body;
371
+ if (!recordId)
372
+ return { error: 'Missing recordId' };
373
+ const record = yield this.adminforth.resource(this.resourceConfig.resourceId).get([
374
+ Filters.EQ((_b = this.resourceConfig.columns.find((col) => col.primaryKey)) === null || _b === void 0 ? void 0 : _b.name, recordId),
375
+ ]);
376
+ if (!record)
377
+ return { error: 'Record not found' };
378
+ if (!this.options.generation.attachFiles)
379
+ return { files: [] };
380
+ const files = yield this.options.generation.attachFiles({ record, adminUser });
381
+ return {
382
+ files: Array.isArray(files) ? files : [files],
383
+ };
384
+ }),
385
+ });
363
386
  }
364
387
  }
package/index.ts CHANGED
@@ -14,6 +14,8 @@ export default class UploadPlugin extends AdminForthPlugin {
14
14
  totalCalls: number;
15
15
  totalDuration: number;
16
16
 
17
+ resourceConfig: AdminForthResource;
18
+
17
19
  constructor(options: PluginOptions) {
18
20
  super(options, import.meta.url);
19
21
  this.options = options;
@@ -28,7 +30,8 @@ export default class UploadPlugin extends AdminForthPlugin {
28
30
  }
29
31
 
30
32
  async setupLifecycleRule() {
31
- this.options.storageAdapter.setupLifecycle();
33
+ const adapterUserUniqueRepresentation = `${this.resourceConfig.resourceId}-${this.pluginInstanceId}`;
34
+ this.options.storageAdapter.setupLifecycle(adapterUserUniqueRepresentation);
32
35
  }
33
36
 
34
37
  async genPreviewUrl(record: any) {
@@ -43,6 +46,7 @@ export default class UploadPlugin extends AdminForthPlugin {
43
46
 
44
47
  async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
45
48
  super.modifyResourceConfig(adminforth, resourceConfig);
49
+ this.resourceConfig = resourceConfig;
46
50
  // after column to store the path of the uploaded file, add new VirtualColumn,
47
51
  // show only in edit and create views
48
52
  // use component uploader.vue
@@ -361,7 +365,7 @@ export default class UploadPlugin extends AdminForthPlugin {
361
365
  return { error: `Record with id ${recordId} not found` };
362
366
  }
363
367
 
364
- attachmentFiles = this.options.generation.attachFiles({ record, adminUser });
368
+ attachmentFiles = await this.options.generation.attachFiles({ record, adminUser });
365
369
  // if files is not array, make it array
366
370
  if (!Array.isArray(attachmentFiles)) {
367
371
  attachmentFiles = [attachmentFiles];
@@ -419,6 +423,30 @@ export default class UploadPlugin extends AdminForthPlugin {
419
423
  return null
420
424
  }
421
425
  });
426
+
427
+ server.endpoint({
428
+ method: 'POST',
429
+ path: `/plugin/${this.pluginInstanceId}/get_attachment_files`,
430
+ handler: async ({ body, adminUser }) => {
431
+ const { recordId } = body;
432
+
433
+ if (!recordId) return { error: 'Missing recordId' };
434
+
435
+ const record = await this.adminforth.resource(this.resourceConfig.resourceId).get([
436
+ Filters.EQ(this.resourceConfig.columns.find((col: any) => col.primaryKey)?.name, recordId),
437
+ ]);
438
+
439
+ if (!record) return { error: 'Record not found' };
440
+
441
+ if (!this.options.generation.attachFiles) return { files: [] };
442
+
443
+ const files = await this.options.generation.attachFiles({ record, adminUser });
444
+
445
+ return {
446
+ files: Array.isArray(files) ? files : [files],
447
+ };
448
+ },
449
+ });
422
450
 
423
451
  }
424
452
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adminforth/upload",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Plugin for uploading files for adminforth",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/types.ts CHANGED
@@ -131,7 +131,7 @@ export type PluginOptions = {
131
131
  attachFiles?: ({ record, adminUser }: {
132
132
  record: any,
133
133
  adminUser: AdminUser,
134
- }) => string[],
134
+ }) => string[] | Promise<string[]>,
135
135
 
136
136
 
137
137
  /**