Skip to content

Beautiful Open-Source Form Builder

Better image input - unsplash (#939)

Chirag Chhatralad9baa6d7368d
diff --git a/api/app/Http/Controllers/Content/FontsController.php b/api/app/Http/Controllers/Content/FontsController.php
index 500131902..940ea7ef1 100644
--- a/api/app/Http/Controllers/Content/FontsController.php
+++ b/api/app/Http/Controllers/Content/FontsController.php
@@ -5,6 +5,7 @@ namespace App\Http\Controllers\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Http\Controllers\Controller;
+use Illuminate\Support\Facades\Cache;
class FontsController extends Controller
{
@@ -14,7 +15,7 @@ class FontsController extends Controller
return response()->json([]);
}
- return \Cache::remember('google_fonts', 60 * 60, function () {
+ return Cache::remember('google_fonts', 60 * 60, function () {
$url = "https://www.googleapis.com/webfonts/v1/webfonts?sort=popularity&key=" . config('services.google.fonts_api_key');
$response = Http::get($url);
if ($response->successful()) {
diff --git a/api/app/Http/Controllers/Content/UnsplashController.php b/api/app/Http/Controllers/Content/UnsplashController.php
new file mode 100644
index 000000000..771aa1be1
--- /dev/null
+++ b/api/app/Http/Controllers/Content/UnsplashController.php
@@ -0,0 +1,105 @@
+<?php
+
+namespace App\Http\Controllers\Content;
+
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Http;
+use App\Http\Controllers\Controller;
+use Illuminate\Support\Facades\Cache;
+
+class UnsplashController extends Controller
+{
+ public function index(Request $request)
+ {
+ $accessKey = config('services.unsplash.access_key');
+
+ if (!$accessKey) {
+ return response()->json([]);
+ }
+
+ $term = trim((string) $request->get('term', ''));
+
+ // If a search term is provided, fetch fresh results from the search endpoint (no cache)
+ if ($term !== '') {
+ $photos = $this->fetchUnsplash(
+ 'https://api.unsplash.com/search/photos',
+ [
+ 'client_id' => $accessKey,
+ 'query' => $term,
+ 'per_page' => 9,
+ ],
+ fn ($json) => $json['results'] ?? []
+ );
+
+ return response()->json($photos);
+ }
+
+ // No search term: return cached curated/latest photos
+ $photos = Cache::remember('unsplash_images', 60 * 60, function () use ($accessKey) {
+ return $this->fetchUnsplash(
+ 'https://api.unsplash.com/photos',
+ [
+ 'client_id' => $accessKey,
+ 'per_page' => 9,
+ ]
+ );
+ });
+
+ return response()->json($photos);
+ }
+
+ public function download(Request $request)
+ {
+ $accessKey = config('services.unsplash.access_key');
+ $downloadLocation = $request->get('download_location');
+
+ if (!$accessKey || !$downloadLocation) {
+ return response()->json(['error' => 'Invalid request'], 400);
+ }
+
+ // Trigger download tracking by calling Unsplash download endpoint
+ Http::get($downloadLocation, [
+ 'client_id' => $accessKey,
+ ]);
+
+ return response()->json(['success' => true]);
+ }
+
+ /**
+ * Perform Unsplash HTTP GET and normalize response.
+ *
+ * @param string $url
+ * @param array $params
+ * @param callable|null $transform Receives decoded JSON and returns array
+ * @return array
+ */
+ private function fetchUnsplash(string $url, array $params = [], ?callable $transform = null): array
+ {
+ $response = Http::get($url, $params);
+
+ if (!$response->successful()) {
+ return [];
+ }
+
+ $json = $response->json();
+
+ if (isset($json['errors'])) {
+ return [];
+ }
+
+ $photos = $transform ? $transform($json) : (is_array($json) ? $json : []);
+ return collect($photos)->map(function ($photo) {
+ return [
+ 'id' => $photo['id'],
+ 'url' => $photo['urls']['regular'] ?? null,
+ 'alt_text' => $photo['alt_description'] ?? null,
+ 'photographer_name' => $photo['user']['name'] ?? null,
+ 'photographer_username' => $photo['user']['username'] ?? null,
+ 'photographer_url' => $photo['user']['links']['html'] ?? null,
+ 'download_location' => $photo['links']['download_location'] ?? null,
+ ];
+ })->filter(function ($photo) {
+ return $photo['url'] !== null;
+ })->take(9)->toArray();
+ }
+}
diff --git a/api/routes/api.php b/api/routes/api.php
index faa6fd685..0c2280598 100644
--- a/api/routes/api.php
+++ b/api/routes/api.php
@@ -48,6 +48,9 @@ if (config('app.self_hosted')) {
Route::group(['middleware' => 'auth.multi'], function () {
Route::post('logout', [LoginController::class, 'logout'])->name('logout');
+ // Unsplash
+ Route::get('/unsplash', [\App\Http\Controllers\Content\UnsplashController::class, 'index'])->name('unsplash.index');
+ Route::post('/unsplash/download', [\App\Http\Controllers\Content\UnsplashController::class, 'download'])->name('unsplash.download');
Route::get('user', [UserController::class, 'current'])->name('user.current');
Route::delete('user', [UserController::class, 'deleteAccount']);
diff --git a/client/api/content.js b/client/api/content.js
index fc736f13a..640bd0e12 100644
--- a/client/api/content.js
+++ b/client/api/content.js
@@ -9,5 +9,11 @@ export const contentApi = {
// Feature flags
featureFlags: {
list: (options) => apiService.get('/content/feature-flags', options)
+ },
+
+ // Unsplash
+ unsplash: {
+ list: (options) => apiService.get('/unsplash', options),
+ download: (downloadLocation) => apiService.post('/unsplash/download', { download_location: downloadLocation })
}
}
\ No newline at end of file
diff --git a/client/components/forms/heavy/ImageInput.vue b/client/components/forms/heavy/ImageInput.vue
index 774198f1c..6448c8835 100644
--- a/client/components/forms/heavy/ImageInput.vue
+++ b/client/components/forms/heavy/ImageInput.vue
@@ -64,15 +64,23 @@
<UModal
v-model:open="showUploadModal"
title="Upload an image"
- :ui="{ content: 'sm:max-w-xl' }"
+ :ui="{ content: 'sm:max-w-xl', body: 'pt-2!' }"
>
<template #body>
<div class="max-w-3xl mx-auto lg:max-w-none">
- <div class="sm:grid sm:grid-cols-1 sm:gap-4 sm:items-start">
- <div class="sm:col-span-2 mb-5">
+ <UTabs
+ v-model="activeTab"
+ :items="tabItems"
+ :content="false"
+ variant="link"
+ class="mb-2"
+ />
+
+ <div v-if="activeTab === 'upload'" class="sm:grid sm:grid-cols-1 sm:gap-4 sm:items-start">
+ <div class="sm:col-span-2 mb-5 mt-2">
<div
v-cloak
- class="w-full flex justify-center items-center px-6 pt-5 pb-6 border-2 border-neutral-300 border-dashed rounded-md h-128"
+ class="w-full flex justify-center items-center px-6 pt-5 pb-6 border-2 border-neutral-300 border-dashed rounded-md h-54"
@dragover.prevent="onUploadDragoverEvent($event)"
@drop.prevent="onUploadDropEvent($event)"
>
@@ -124,6 +132,24 @@
</div>
</div>
</div>
+
+ <div v-else-if="activeTab === 'unsplash'">
+ <UnsplashImages @selectImage="selectUnsplashImage" />
+ </div>
+
+ <div v-else-if="activeTab === 'url'" class="p-4">
+ <TextInput
+ v-model="urlInput"
+ name="image_url"
+ label="Enter the URL of the image you want to use"
+ placeholder="https://example.com/image.jpg"
+ />
+ <div class="mt-4 flex justify-end gap-2">
+ <UButton color="primary" :disabled="!urlInput" @click="insertUrl">
+ Insert
+ </UButton>
+ </div>
+ </div>
</div>
</template>
</UModal>
@@ -135,6 +161,7 @@ import { inputProps, useFormInput } from "../useFormInput.js"
import { storeFile } from "~/lib/file-uploads.js"
import { formsApi } from '~/api'
import { imageInputTheme } from '~/lib/forms/themes/image-input.theme.js'
+import { useFeatureFlag } from '~/composables/useFeatureFlag.js'
export default {
components: { },
@@ -154,6 +181,8 @@ export default {
data: () => ({
showUploadModal: false,
+ activeTab: 'upload',
+ urlInput: '',
file: [],
uploadDragoverTracking: false,
@@ -165,6 +194,16 @@ export default {
currentUrl() {
return this.compVal
},
+ tabItems() {
+ const baseTabs = [
+ { label: 'Upload', value: 'upload' },
+ { label: 'URL', value: 'url' },
+ ]
+ if (useFeatureFlag('services.unsplash')) {
+ baseTabs.splice(1, 0, { label: 'Unsplash', value: 'unsplash' })
+ }
+ return baseTabs
+ },
},
watch: {
@@ -193,11 +232,21 @@ export default {
this.droppedFiles(e.dataTransfer.files)
},
onUploadPasteEvent(e) {
- if (!this.showUploadModal) return
+ if (!this.showUploadModal || this.activeTab !== 'upload') return
this.uploadDragoverEvent = false
this.uploadDragoverTracking = false
this.droppedFiles(e.clipboardData.files)
},
+ selectUnsplashImage(imageUrl) {
+ this.compVal = imageUrl
+ this.showUploadModal = false
+ },
+ insertUrl() {
+ if (!this.urlInput || !/^https?:\/\/[^\s$.?#].[^\s]*$/i.test(this.urlInput)) return
+ this.compVal = this.urlInput
+ this.urlInput = ''
+ this.showUploadModal = false
+ },
droppedFiles(droppedFiles) {
if (!droppedFiles) return
diff --git a/client/components/forms/heavy/components/UnsplashImages.vue b/client/components/forms/heavy/components/UnsplashImages.vue
new file mode 100644
index 000000000..b902e129a
--- /dev/null
+++ b/client/components/forms/heavy/components/UnsplashImages.vue
@@ -0,0 +1,108 @@
+<template>
+ <div class="unsplash-images-container">
+ <div class="py-2">
+ <UInput
+ v-model="searchTerm"
+ variant="outline"
+ class="w-full mb-1"
+ placeholder="Search image..."
+ icon="i-heroicons-magnifying-glass-solid"
+ :disabled="!isFeatureEnabled"
+ :ui="{ trailing: 'pe-1' }"
+ >
+ <template v-if="searchTerm?.length" #trailing>
+ <UButton
+ color="neutral"
+ variant="link"
+ size="sm"
+ icon="i-heroicons-x-mark-20-solid"
+ aria-label="Clear"
+ title="Clear"
+ @click="searchTerm = ''"
+ />
+ </template>
+ </UInput>
+ </div>
+
+ <div class="mb-5 border rounded-lg bg-gradient-to-b from-neutral-50 to-neutral-100">
+ <VTransition name="fade">
+ <div v-if="!isFeatureEnabled" key="disabled" class="flex flex-col items-center justify-center h-64 p-4">
+ <UIcon name="i-heroicons-exclamation-triangle-20-solid" class="w-12 h-12 text-amber-500 mb-3" />
+ <p class="text-neutral-600 text-sm font-medium mb-1">Unsplash integration is not available</p>
+ <p class="text-neutral-500 text-xs text-center">Please configure Unsplash API keys to use this feature.</p>
+ </div>
+ <div v-else-if="loading" key="loading" class="grid grid-cols-3 gap-3 p-4">
+ <div v-for="i in 9" :key="i" class="group cursor-pointer rounded-lg overflow-hidden shadow-sm transition-all duration-200">
+ <div class="aspect-square overflow-hidden bg-neutral-200">
+ <USkeleton class="w-full h-full" />
+ </div>
+ </div>
+ </div>
+ <div v-else-if="images.length === 0" key="empty" class="flex flex-col items-center justify-center h-64">
+ <UIcon name="i-heroicons-photo-20-solid" class="w-16 h-16 text-neutral-300 mb-3" />
+ <p class="text-neutral-500 text-sm">{{ searchTerm ? 'No image found' : 'No image available' }}</p>
+ </div>
+ <div v-else key="results" class="grid grid-cols-3 gap-3 p-4">
+ <div v-for="image in images.slice(0, 9)" :key="image.id" class="group cursor-pointer rounded-lg overflow-hidden shadow-sm hover:shadow-md transition-all duration-200 relative">
+ <div class="aspect-square overflow-hidden bg-neutral-200">
+ <img
+ :src="image.url"
+ :alt="image.alt_text"
+ class="w-full h-full object-cover"
+ @click="selectImage(image)"
+ />
+ </div>
+ <div v-if="image.photographer_name || image.photographer_url" class="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-end justify-start z-20 pointer-events-none">
+ <div class="w-full p-2 text-white text-xs pointer-events-auto">
+ <p v-if="image.photographer_name" class="font-medium truncate mb-0.5">{{ image.photographer_name }}</p>
+ <a
+ v-if="image.photographer_url"
+ :href="`${image.photographer_url}?utm_source=opnform&utm_medium=referral`"
+ target="_blank"
+ rel="noopener noreferrer"
+ class="text-white/80 hover:text-white text-xs underline block"
+ @click.stop
+ >
+ {{ image.photographer_name ? 'on Unsplash' : 'View on Unsplash' }}
+ </a>
+ </div>
+ </div>
+ </div>
+ </div>
+ </VTransition>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { refDebounced } from '@vueuse/core'
+import { useContent } from '~/composables/query/useContent'
+import { contentApi } from '~/api/content'
+
+const isFeatureEnabled = useFeatureFlag('services.unsplash', false)
+const { unsplash } = useContent()
+const searchTerm = ref("")
+const debouncedTerm = refDebounced(searchTerm, 300)
+
+const emit = defineEmits(['selectImage'])
+
+// Use TanStack Query for images with caching
+const { data: images = [], isLoading: loading } = unsplash.list(debouncedTerm, {
+ enabled: computed(() => isFeatureEnabled)
+})
+
+const selectImage = async (image) => {
+ // Trigger download tracking as per Unsplash API guidelines
+ if (image.download_location) {
+ try {
+ // Fire-and-forget - no need for mutation wrapper
+ contentApi.unsplash.download(image.download_location)
+ } catch (error) {
+ // Silently fail - don't block image selection if download tracking fails
+ console.warn('Failed to track Unsplash download:', error)
+ }
+ }
+ emit('selectImage', image.url)
+}
+
+</script>
\ No newline at end of file
diff --git a/client/components/open/editors/GoogleFontPicker.vue b/client/components/open/editors/GoogleFontPicker.vue
index d77f2b055..b4f1372ee 100644
--- a/client/components/open/editors/GoogleFontPicker.vue
+++ b/client/components/open/editors/GoogleFontPicker.vue
@@ -5,20 +5,30 @@
title="Google fonts"
>
<template #body>
- <div v-if="loading">
- <Loader class="h-6 w-6 text-blue-500 mx-auto" />
- </div>
- <div v-else>
- <text-input
- v-model="search"
- name="search"
- placeholder="Search fonts"
- />
-
- <div
- ref="scrollContainer"
- class="grid grid-cols-3 gap-2 p-5 mb-5 overflow-y-scroll max-h-[24rem] border rounded-md bg-neutral-50"
- >
+ <text-input
+ v-model="search"
+ name="search"
+ placeholder="Search fonts"
+ />
+
+ <div
+ ref="scrollContainer"
+ class="grid grid-cols-3 gap-2 p-5 mb-5 overflow-y-scroll max-h-[24rem] border rounded-md bg-neutral-50 mt-3"
+ >
+ <template v-if="loading">
+ <div
+ v-for="i in 9"
+ :key="`skeleton-${i}`"
+ class="flex flex-col p-3 rounded-md shadow border-neutral-200 border-[0.5px] bg-white"
+ >
+ <div class="flex flex-wrap gap-2 mb-3">
+ <USkeleton class="h-5 w-full" />
+ <USkeleton class="h-5 w-3/4" />
+ </div>
+ <USkeleton class="h-3 w-1/2" />
+ </div>
+ </template>
+ <template v-else>
<FontCard
v-for="(fontName, index) in enrichedFonts"
:key="fontName"
@@ -28,7 +38,7 @@
:is-selected="selectedFont === fontName"
@select-font="selectedFont = fontName"
/>
- </div>
+ </template>
</div>
</template>
@@ -57,7 +67,7 @@ import { defineEmits } from "vue"
import { refDebounced, useElementVisibility } from "@vueuse/core"
import { useFuse } from '@vueuse/integrations/useFuse'
import FontCard from './FontCard.vue'
-import { contentApi } from "~/api"
+import { useContent } from '~/composables/query/useContent'
const props = defineProps({
show: {
@@ -82,14 +92,28 @@ const isOpen = computed({
const emit = defineEmits(['close', 'apply'])
-const loading = ref(false)
-const fonts = ref([])
+const { fonts: fontsApi } = useContent()
const selectedFont = ref(props.font || null)
const search = ref("")
const debouncedSearch = refDebounced(search, 500)
+
+// Use TanStack Query for fonts with caching
+const fontsQuery = fontsApi.list({
+ enabled: computed(() => props.show)
+})
+
+const fonts = computed(() => {
+ const data = fontsQuery.data.value
+ if (!data) return []
+ // Convert object to array if needed (handles numeric string keys)
+ return Array.isArray(data) ? data : Object.values(data)
+})
+
+const loading = computed(() => fontsQuery.isLoading.value)
+
const { results: fuseResults } = useFuse(
debouncedSearch,
- computed(() => Object.values(fonts.value || [])),
+ fonts,
{
fuseOptions: {
threshold: 0.3,
@@ -126,23 +150,21 @@ const initializeVisibilityTracking = async () => {
})
}
-const fetchFonts = async () => {
- if (props.show) {
+watch(() => props.show, (show) => {
+ if (show) {
selectedFont.value = props.font || null
- loading.value = true
- contentApi.fonts.list().then((data) => {
- fonts.value = data || []
- loading.value = false
- initializeVisibilityTracking()
- })
}
-}
-watch(() => props.show, fetchFonts)
+})
+watch(fonts, (newFonts) => {
+ if (newFonts && newFonts.length > 0) {
+ initializeVisibilityTracking()
+ }
+})
const enrichedFonts = computed(() => {
return fuseResults.value && fuseResults.value.length > 0
? fuseResults.value.map((res) => res.item)
- : (fonts.value || [])
+ : fonts.value
})
</script>
diff --git a/client/composables/query/useContent.js b/client/composables/query/useContent.js
new file mode 100644
index 000000000..541e20047
--- /dev/null
+++ b/client/composables/query/useContent.js
@@ -0,0 +1,65 @@
+import { useQuery, useQueryClient } from '@tanstack/vue-query'
+import { contentApi } from '~/api/content'
+import { computed, toValue } from 'vue'
+
+export function useContent() {
+ const queryClient = useQueryClient()
+
+ // Fonts
+ const fonts = {
+ list: (options = {}) => {
+ return useQuery({
+ queryKey: ['content', 'fonts', 'list'],
+ queryFn: () => contentApi.fonts.list(options),
+ staleTime: 10 * 60 * 1000, // 10 minutes - fonts don't change often
+ ...options
+ })
+ }
+ }
+
+ // Unsplash
+ const unsplash = {
+ list: (searchTerm = '', options = {}) => {
+ const isFeatureEnabled = useFeatureFlag('services.unsplash', false)
+
+ return useQuery({
+ queryKey: ['content', 'unsplash', 'list', searchTerm || 'default'],
+ queryFn: () => {
+ const term = toValue(searchTerm)
+ const queryOptions = term ? { query: { term } } : {}
+ return contentApi.unsplash.list(queryOptions)
+ },
+ enabled: computed(() => {
+ return isFeatureEnabled && (options.enabled !== false)
+ }),
+ staleTime: 5 * 60 * 1000, // 5 minutes
+ ...options
+ })
+ },
+
+ }
+
+ // Invalidate all content queries
+ const invalidate = () => {
+ queryClient.invalidateQueries({ queryKey: ['content'] })
+ }
+
+ // Invalidate fonts
+ const invalidateFonts = () => {
+ queryClient.invalidateQueries({ queryKey: ['content', 'fonts'] })
+ }
+
+ // Invalidate unsplash
+ const invalidateUnsplash = () => {
+ queryClient.invalidateQueries({ queryKey: ['content', 'unsplash'] })
+ }
+
+ return {
+ fonts,
+ unsplash,
+ invalidate,
+ invalidateFonts,
+ invalidateUnsplash
+ }
+}
+