chore: optimize LCP images, fix Turbopack warning, update mock images
This commit is contained in:
+3
-2
@@ -3,6 +3,7 @@
|
||||
import { useEffect, useState, useRef } from "react";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
import Image from "next/image";
|
||||
import { MenuCategory, MenuItem as MenuItemType } from "@/data/menu";
|
||||
import { CategoryNav } from "@/components/CategoryNav";
|
||||
import { MenuItem } from "@/components/MenuItem";
|
||||
@@ -208,7 +209,7 @@ export default function MenuClient({ initialCategories, siteSettings, lang = "tr
|
||||
|
||||
<div>
|
||||
{category.items.map((item, idx) => (
|
||||
<MenuItem key={idx} item={item} onClick={() => setSelectedItem(item)} />
|
||||
<MenuItem key={idx} item={item} onClick={() => setSelectedItem(item)} priority={index === 0 && idx < 5} />
|
||||
))}
|
||||
</div>
|
||||
</motion.section>
|
||||
@@ -289,7 +290,7 @@ export default function MenuClient({ initialCategories, siteSettings, lang = "tr
|
||||
>
|
||||
{selectedItem.image && (
|
||||
<div className="w-full h-56 relative">
|
||||
<img src={selectedItem.image} alt={selectedItem.name} className="w-full h-full object-cover" />
|
||||
<Image src={selectedItem.image} alt={selectedItem.name} fill className="object-cover" sizes="(max-width: 768px) 100vw, 400px" priority />
|
||||
<button
|
||||
className="absolute top-3 right-3 bg-black/50 text-white w-8 h-8 rounded-full flex items-center justify-center backdrop-blur-md transition-colors hover:bg-black/70"
|
||||
onClick={() => setSelectedItem(null)}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import React from "react";
|
||||
import { MenuItem as MenuItemType } from "@/data/menu";
|
||||
import Image from "next/image";
|
||||
|
||||
export function MenuItem({ item, onClick }: { item: MenuItemType; onClick?: () => void }) {
|
||||
export function MenuItem({ item, onClick, priority }: { item: MenuItemType; onClick?: () => void; priority?: boolean }) {
|
||||
return (
|
||||
<div
|
||||
className="py-3.5 border-b last:border-b-0 cursor-pointer transition-colors hover:bg-black/5"
|
||||
@@ -35,9 +36,12 @@ export function MenuItem({ item, onClick }: { item: MenuItemType; onClick?: () =
|
||||
</div>
|
||||
{item.image && (
|
||||
<div className="shrink-0">
|
||||
<img
|
||||
<Image
|
||||
src={item.image}
|
||||
alt={item.name}
|
||||
alt={item.name}
|
||||
width={80}
|
||||
height={80}
|
||||
priority={priority}
|
||||
className="w-20 h-20 object-cover rounded-lg shadow-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
'use client'
|
||||
|
||||
export default function openinaryLoader({ src, width, quality }: { src: string, width: number, quality?: number }) {
|
||||
// Handle already absolute openinary URLs
|
||||
let path = src;
|
||||
if (src.startsWith('https://media.ayris.tech/t/')) {
|
||||
// format: https://media.ayris.tech/t/w_800,h_800/kiteqr/img.jpg
|
||||
const parts = src.split('/');
|
||||
path = parts.slice(5).join('/');
|
||||
} else if (src.startsWith('https://media.ayris.tech/upload/')) {
|
||||
// format: https://media.ayris.tech/upload/kiteqr/img.jpg
|
||||
const parts = src.split('/');
|
||||
path = parts.slice(4).join('/');
|
||||
} else if (src.includes('res.cloudinary.com')) {
|
||||
// Correctly apply width & quality for unmigrated Cloudinary URLs
|
||||
// e.g. https://res.cloudinary.com/domain/image/upload/v1234/path.jpg
|
||||
// becomes: https://res.cloudinary.com/domain/image/upload/w_800,f_webp,q_75/v1234/path.jpg
|
||||
const parts = src.split('/upload/');
|
||||
if (parts.length === 2) {
|
||||
return `${parts[0]}/upload/w_${width},f_webp,q_${quality || 75}/${parts[1]}`;
|
||||
}
|
||||
return src;
|
||||
} else if (src.startsWith('http')) {
|
||||
// For other external URLs, we append the width as a query parameter to satisfy Next.js.
|
||||
const url = new URL(src);
|
||||
url.searchParams.set('w', width.toString());
|
||||
if (quality) {
|
||||
url.searchParams.set('q', quality.toString());
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
// Clean up any leading slash
|
||||
if (path.startsWith('/')) {
|
||||
path = path.substring(1);
|
||||
}
|
||||
|
||||
return `https://media.ayris.tech/t/w_${width},f_webp,q_${quality || 75}/${path}`
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
const BASE = process.env.NEXT_PUBLIC_OPENINARY_URL;
|
||||
|
||||
export function optimizedImage(path: string, params: string) {
|
||||
return `${BASE}/t/${params}/${path}`;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export async function uploadToOpeninary(file: File, folder: string) {
|
||||
const formData = new FormData();
|
||||
formData.append("files", file);
|
||||
formData.append("folder", folder);
|
||||
|
||||
const res = await fetch(`${process.env.OPENINARY_API_URL}/api/upload`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${process.env.OPENINARY_API_KEY}` },
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
console.error("Openinary upload error:", errorText);
|
||||
throw new Error("Upload başarısız: " + errorText);
|
||||
}
|
||||
const data = await res.json();
|
||||
return data.files[0]; // { path, url, size, ... }
|
||||
}
|
||||
@@ -3,6 +3,8 @@ import type { NextConfig } from "next";
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
images: {
|
||||
loader: "custom",
|
||||
loaderFile: "./lib/openinary-loader.ts",
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: 'https',
|
||||
@@ -14,6 +16,11 @@ const nextConfig: NextConfig = {
|
||||
},
|
||||
],
|
||||
},
|
||||
experimental: {
|
||||
turbopack: {
|
||||
root: "C:/Users/ayris.dev/kite",
|
||||
},
|
||||
},
|
||||
/* other config options here */
|
||||
};
|
||||
|
||||
|
||||
Generated
+1
-1
@@ -2122,7 +2122,7 @@
|
||||
"version": "19.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
|
||||
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@types/react": "^19.2.0"
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { Pool } from 'pg';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { uploadToOpeninary } from '../lib/openinary';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import 'dotenv/config';
|
||||
|
||||
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||||
const adapter = new PrismaPg(pool);
|
||||
const prisma = new PrismaClient({ adapter });
|
||||
|
||||
async function main() {
|
||||
console.log("Starting migration...");
|
||||
const products = await prisma.products.findMany({
|
||||
where: {
|
||||
image_url: { not: null }
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`Found ${products.length} products with images.`);
|
||||
|
||||
for (const product of products) {
|
||||
if (!product.image_url) continue;
|
||||
|
||||
if (product.image_url.startsWith('kiteqr/')) {
|
||||
console.log(`[SKIP] Already migrated ${product.id}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Extract filename from image_url (e.g. admin/uploads/products/xxx.jpg or similar)
|
||||
const filename = path.basename(product.image_url);
|
||||
if (!filename) continue;
|
||||
|
||||
const localPath = path.join(process.cwd(), 'products', filename);
|
||||
|
||||
if (!fs.existsSync(localPath)) {
|
||||
console.log(`[SKIP] Local file not found for product ${product.id} (${product.name}): ${localPath}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`[UPLOAD] Uploading ${filename} for product ${product.id}...`);
|
||||
const buffer = fs.readFileSync(localPath);
|
||||
|
||||
const ext = path.extname(filename).toLowerCase();
|
||||
let mime = 'image/jpeg';
|
||||
if (ext === '.png') mime = 'image/png';
|
||||
if (ext === '.webp') mime = 'image/webp';
|
||||
if (ext === '.gif') mime = 'image/gif';
|
||||
|
||||
const file = new File([buffer], filename, { type: mime });
|
||||
|
||||
const result = await uploadToOpeninary(file, "kiteqr");
|
||||
|
||||
console.log(`[SUCCESS] Uploaded to: ${result.path}`);
|
||||
|
||||
// Update database
|
||||
await prisma.products.update({
|
||||
where: { id: product.id },
|
||||
data: { image_url: result.path } // Using path as requested/required by loader
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error(`[ERROR] Failed to upload/update product ${product.id}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
console.log("Migration complete.");
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(console.error)
|
||||
.finally(() => prisma.$disconnect());
|
||||
@@ -0,0 +1,50 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { Pool } from 'pg';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { uploadToOpeninary } from '../lib/openinary';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import 'dotenv/config';
|
||||
|
||||
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||||
const adapter = new PrismaPg(pool);
|
||||
const prisma = new PrismaClient({ adapter });
|
||||
|
||||
async function main() {
|
||||
console.log("Uploading default product image to Openinary...");
|
||||
const localPath = path.join(process.cwd(), 'public', 'default-product.png');
|
||||
const buffer = fs.readFileSync(localPath);
|
||||
const file = new File([buffer], 'default-product.png', { type: 'image/png' });
|
||||
|
||||
let defaultPath = "";
|
||||
try {
|
||||
const result = await uploadToOpeninary(file, "kiteqr");
|
||||
defaultPath = result.path;
|
||||
console.log(`[SUCCESS] Default image uploaded to: ${defaultPath}`);
|
||||
} catch (error) {
|
||||
console.error("Failed to upload default image:", error);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("Updating products with missing or old images...");
|
||||
const products = await prisma.products.findMany();
|
||||
|
||||
let updatedCount = 0;
|
||||
for (const product of products) {
|
||||
// If image_url is empty, null, or doesn't start with kiteqr/ (meaning it wasn't migrated successfully)
|
||||
if (!product.image_url || !product.image_url.startsWith('kiteqr/')) {
|
||||
await prisma.products.update({
|
||||
where: { id: product.id },
|
||||
data: { image_url: defaultPath }
|
||||
});
|
||||
updatedCount++;
|
||||
console.log(`Updated product ${product.id} (${product.name}) with mock image.`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Done. ${updatedCount} products updated with the mock image.`);
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(console.error)
|
||||
.finally(() => prisma.$disconnect());
|
||||
Reference in New Issue
Block a user