feat(Nextjs): Add EditableLayoutWrapper and enhance image/icon editing capabilities
This commit is contained in:
parent
19b6ecfc5c
commit
1bdc5e642e
14 changed files with 927 additions and 1601 deletions
|
|
@ -1,505 +0,0 @@
|
|||
import React, { useState } from 'react';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetTitle,
|
||||
SheetHeader,
|
||||
} from "@/components/ui/sheet";
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Plus, ChevronDown, Trash, BarChart3, PieChart as PieChartIcon, LineChart as LineChartIcon } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { StoreChartData } from '../utils/chartDataTransforms';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuItem,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { renderChart } from './slide_config';
|
||||
import { useSelector } from 'react-redux';
|
||||
import { RootState } from '@/store/store';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { ChartSettings } from '@/store/slices/presentationGeneration';
|
||||
|
||||
interface ChartEditorProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
chartData: StoreChartData;
|
||||
onChartDataChange: (newData: StoreChartData) => void;
|
||||
chartSettings: ChartSettings;
|
||||
setChartSettings: (newSettings: ChartSettings) => void;
|
||||
}
|
||||
|
||||
const ChartEditor = ({ isOpen, onClose, chartData, onChartDataChange, chartSettings, setChartSettings }: ChartEditorProps) => {
|
||||
const [selectedCell, setSelectedCell] = useState<{ row: number; col: number } | null>(null);
|
||||
const { currentColors } = useSelector((state: RootState) => state.theme);
|
||||
|
||||
const handleCategoryChange = (index: number, value: string) => {
|
||||
const newData = {
|
||||
...chartData,
|
||||
data: {
|
||||
...chartData.data,
|
||||
categories: [
|
||||
...chartData.data.categories.slice(0, index),
|
||||
value,
|
||||
...chartData.data.categories.slice(index + 1)
|
||||
]
|
||||
}
|
||||
};
|
||||
onChartDataChange(newData);
|
||||
};
|
||||
|
||||
|
||||
const handleValueChange = (categoryIndex: number, seriesIndex: number, value: string) => {
|
||||
const newData = {
|
||||
...chartData,
|
||||
data: {
|
||||
...chartData.data,
|
||||
series: chartData.data.series.map((series, idx) => {
|
||||
if (idx === seriesIndex) {
|
||||
return {
|
||||
...series,
|
||||
data: [...series.data.slice(0, categoryIndex), Number(value), ...series.data.slice(categoryIndex + 1)]
|
||||
};
|
||||
}
|
||||
return series;
|
||||
})
|
||||
}
|
||||
};
|
||||
onChartDataChange(newData);
|
||||
};
|
||||
|
||||
const addCategory = () => {
|
||||
|
||||
const newData = {
|
||||
...chartData,
|
||||
data: {
|
||||
...chartData.data,
|
||||
categories: [...chartData.data.categories, ''],
|
||||
series: chartData.data.series.map(series => ({
|
||||
...series,
|
||||
data: [...series.data, 0]
|
||||
}))
|
||||
}
|
||||
};
|
||||
onChartDataChange(newData);
|
||||
};
|
||||
|
||||
const addSeriesBefore = (index: number) => {
|
||||
if (chartData.type === 'pie' && chartData.data.series.length >= 1) {
|
||||
return;
|
||||
} else {
|
||||
if (chartData.data.series.length >= 4) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const newData = {
|
||||
...chartData,
|
||||
data: {
|
||||
...chartData.data,
|
||||
series: [
|
||||
...chartData.data.series.slice(0, index),
|
||||
{
|
||||
name: `Series ${chartData.data.series.length + 1}`,
|
||||
data: new Array(chartData.data.categories.length).fill(0)
|
||||
},
|
||||
...chartData.data.series.slice(index)
|
||||
]
|
||||
}
|
||||
};
|
||||
onChartDataChange(newData);
|
||||
};
|
||||
|
||||
const addSeriesAfter = (index: number) => {
|
||||
if (chartData.type === 'pie' && chartData.data.series.length >= 1) {
|
||||
return;
|
||||
} else {
|
||||
if (chartData.data.series.length >= 4) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const newData = {
|
||||
...chartData,
|
||||
data: {
|
||||
...chartData.data,
|
||||
series: [
|
||||
...chartData.data.series.slice(0, index + 1),
|
||||
{
|
||||
name: `Series ${chartData.data.series.length + 1}`,
|
||||
data: new Array(chartData.data.categories.length).fill(0)
|
||||
},
|
||||
...chartData.data.series.slice(index + 1)
|
||||
]
|
||||
}
|
||||
};
|
||||
onChartDataChange(newData);
|
||||
};
|
||||
|
||||
const removeCategory = (index: number) => {
|
||||
const newData = {
|
||||
...chartData,
|
||||
data: {
|
||||
...chartData.data,
|
||||
categories: chartData.data.categories.filter((_, idx) => idx !== index),
|
||||
series: chartData.data.series.map(series => ({
|
||||
...series,
|
||||
data: series.data.filter((_, idx) => idx !== index)
|
||||
}))
|
||||
}
|
||||
};
|
||||
onChartDataChange(newData);
|
||||
};
|
||||
|
||||
const removeSeries = (index: number) => {
|
||||
const newData = {
|
||||
...chartData,
|
||||
data: {
|
||||
...chartData.data,
|
||||
series: chartData.data.series.filter((_, idx) => idx !== index)
|
||||
}
|
||||
};
|
||||
onChartDataChange(newData);
|
||||
};
|
||||
|
||||
const getColumnLetter = (index: number) => {
|
||||
return String.fromCharCode(65 + index);
|
||||
};
|
||||
|
||||
const isColumnSelected = (colIndex: number) => {
|
||||
return selectedCell?.col === colIndex;
|
||||
};
|
||||
|
||||
const isRowSelected = (rowIndex: number) => {
|
||||
return selectedCell?.row === rowIndex;
|
||||
};
|
||||
|
||||
const isCellSelected = (rowIndex: number, colIndex: number) => {
|
||||
return selectedCell?.row === rowIndex && selectedCell?.col === colIndex;
|
||||
};
|
||||
const disableAddSeries = (chartType: string) => {
|
||||
if (chartType === 'pie') {
|
||||
return chartData.data.series.length >= 1;
|
||||
} else {
|
||||
return chartData.data.series.length >= 4;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={isOpen} onOpenChange={onClose}>
|
||||
<SheetContent side="bottom" className="h-[80vh] overflow-y-auto" onOpenAutoFocus={(e) => e.preventDefault()}>
|
||||
<SheetHeader className='mb-4'>
|
||||
<SheetTitle>Chart Editor</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="grid grid-cols-2 items-start gap-8 h-full">
|
||||
<div className="space-y-4">
|
||||
{/* Spreadsheet Table */}
|
||||
<div className="rounded-md border bg-white">
|
||||
<div className=" overflow-hidden">
|
||||
<table className="w-full border-collapse ">
|
||||
<thead className='w-full'>
|
||||
<tr>
|
||||
<th className={`w-12 border-b border-r p-2 sticky top-0 z-10 transition-colors duration-200
|
||||
${selectedCell ? 'bg-[#f3f3f3]' : 'bg-[#f8f9fa]'}`}>
|
||||
</th>
|
||||
{/* First column for categories */}
|
||||
<th className={`border-b border-r p-2 sticky top-0 z-10 transition-colors duration-200
|
||||
${isColumnSelected(0) ? 'bg-[#e8f0fe]' : 'bg-[#f8f9fa]'}`}>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-[13px] text-gray-600">A</span>
|
||||
</div>
|
||||
</th>
|
||||
{/* Data columns for each series */}
|
||||
{chartData && chartData.data.series && chartData.data.series.map((_, index) => (
|
||||
<th key={index}
|
||||
className={`border-b border-r p-2 sticky top-0 z-10 transition-colors duration-200
|
||||
${isColumnSelected(index + 1) ? 'bg-[#e8f0fe]' : 'bg-[#f8f9fa]'}`}>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-[13px] text-gray-600">
|
||||
{getColumnLetter(index + 1)}
|
||||
</span>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-6 w-6 p-0">
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-[200px] space-y-2">
|
||||
<DropdownMenuItem className='cursor-pointer hover:bg-gray-100' onClick={() => addSeriesBefore(index)} disabled={disableAddSeries(chartData.type)}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Column before
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className='cursor-pointer hover:bg-gray-100' onClick={() => addSeriesAfter(index)} disabled={disableAddSeries(chartData.type)}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Column after
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className='cursor-pointer hover:bg-gray-100' onClick={() => removeSeries(index)}>
|
||||
<Trash className="mr-2 h-4 w-4 text-red-500" />
|
||||
Delete Column
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</th>
|
||||
))}
|
||||
<th className="w-10 bg-[#f8f9fa] border-b p-2 sticky top-0 z-10">
|
||||
<Button
|
||||
onClick={() => addSeriesAfter(chartData.data.series.length - 1)}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0"
|
||||
disabled={disableAddSeries(chartData.type)}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</th>
|
||||
</tr>
|
||||
{/* New row for series names */}
|
||||
<tr>
|
||||
<td className="border-r p-2 bg-[#f8f9fa]"></td>
|
||||
<td className="border-r p-2 bg-[#f8f9fa]"></td>
|
||||
{chartData.data.series.map((series, index) => (
|
||||
<td key={index} className="border p-1 bg-[#f8f9fa]">
|
||||
<Input
|
||||
value={series.name}
|
||||
onChange={(e) => {
|
||||
const newSeries = chartData.data.series.map((s, i) =>
|
||||
i === index ? { ...s, name: e.target.value } : s
|
||||
);
|
||||
onChartDataChange({
|
||||
...chartData,
|
||||
data: {
|
||||
...chartData.data,
|
||||
series: newSeries
|
||||
}
|
||||
});
|
||||
}}
|
||||
className="border-0 focus-visible:ring-0 focus:ring-0 h-7 text-[13px] bg-transparent"
|
||||
/>
|
||||
</td>
|
||||
))}
|
||||
<td className="w-10 bg-[#f8f9fa]"></td>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody className='block h-full max-h-[500px] custom_scrollbar overflow-y-auto'>
|
||||
{chartData.data.categories.map((category, rowIndex) => (
|
||||
<tr key={rowIndex} className="group">
|
||||
{/* Row Numbers */}
|
||||
<td className={`border-r p-2 text-[13px] text-gray-600 w-12 text-center transition-colors duration-200
|
||||
${isRowSelected(rowIndex) ? 'bg-[#e8f0fe]' : 'bg-[#f8f9fa]'}`}>
|
||||
{rowIndex + 1}
|
||||
</td>
|
||||
|
||||
{/* Category Cell */}
|
||||
<td
|
||||
className={`border p-1 relative transition-all duration-200
|
||||
${isCellSelected(rowIndex, 0)
|
||||
? 'bg-[#e8f0fe] outline outline-2 outline-blue-500 z-10'
|
||||
: 'hover:bg-[#f1f3f4]'}`}
|
||||
onClick={() => setSelectedCell({ row: rowIndex, col: 0 })}
|
||||
>
|
||||
<Input
|
||||
value={category}
|
||||
onChange={(e) => handleCategoryChange(rowIndex, e.target.value)}
|
||||
className="border-0 focus-visible:ring-0 focus:ring-0 h-7 text-[13px] bg-transparent"
|
||||
/>
|
||||
</td>
|
||||
|
||||
|
||||
{/* Series Data Cells */}
|
||||
{/* series name */}
|
||||
{chartData.data.series.map((series, seriesIndex) => (
|
||||
<td
|
||||
key={seriesIndex}
|
||||
className={`border p-1 relative transition-all duration-200
|
||||
${isCellSelected(rowIndex, seriesIndex + 1)
|
||||
? 'bg-[#e8f0fe] outline outline-2 outline-blue-500 z-10'
|
||||
: 'hover:bg-[#f1f3f4]'}`}
|
||||
onClick={() => setSelectedCell({ row: rowIndex, col: seriesIndex + 1 })}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
value={series.data[rowIndex]}
|
||||
onChange={(e) => handleValueChange(rowIndex, seriesIndex, e.target.value)}
|
||||
className="border-0 focus-visible:ring-0 focus:ring-0 h-7 text-[13px] bg-transparent text-right"
|
||||
/>
|
||||
</td>
|
||||
))}
|
||||
|
||||
<td className="w-10 p-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => removeCategory(rowIndex)}
|
||||
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
>
|
||||
<Trash className="h-4 w-4" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{/* Add Row Button */}
|
||||
<div className="p-2 border-t">
|
||||
<Button
|
||||
onClick={addCategory}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full h-7 text-[13px] hover:bg-[#f8f9fa]"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add row
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Add the chart preview section */}
|
||||
<div className="border rounded-lg p-4 bg-white">
|
||||
<h3 className="text-lg font-semibold mb-4">Preview</h3>
|
||||
<div className="w-full" style={{ backgroundColor: currentColors.slideBg }}>
|
||||
{renderChart(chartData, false, currentColors, chartSettings)}
|
||||
</div>
|
||||
|
||||
{/* Add chart type selection */}
|
||||
<div className="mt-4 border-t pt-4 custom_scrollbar">
|
||||
<h4 className="text-sm font-medium mb-2">Chart Type</h4>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant={chartData.type === 'bar' ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
const newData = { ...chartData, type: 'bar' as 'bar' };
|
||||
onChartDataChange(newData);
|
||||
}}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<BarChart3 className="h-4 w-4" />
|
||||
Bar
|
||||
</Button>
|
||||
<Button
|
||||
variant={chartData.type === 'line' ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
const newData = { ...chartData, type: 'line' as 'line' };
|
||||
onChartDataChange(newData);
|
||||
}}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<LineChartIcon className="h-4 w-4" />
|
||||
Line
|
||||
</Button>
|
||||
<Button
|
||||
variant={chartData.type === 'pie' ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
const newData = { ...chartData, type: 'pie' as 'pie' };
|
||||
onChartDataChange(newData);
|
||||
}}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<PieChartIcon className="h-4 w-4" />
|
||||
Pie
|
||||
</Button>
|
||||
</div>
|
||||
<div className="border-t mt-6 pt-4 mb-6 flex flex-col items-start gap-4">
|
||||
{chartData.type !== 'line' && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex w-[350px] items-center justify-between p-3 bg-gray-100 rounded-lg">
|
||||
<Label htmlFor="data-label" className="font-medium">Data Label</Label>
|
||||
<Switch
|
||||
id="data-label"
|
||||
checked={chartSettings.showDataLabel}
|
||||
onCheckedChange={(checked) => setChartSettings({ ...chartSettings, showDataLabel: checked })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{chartSettings.showDataLabel && (
|
||||
<div className="space-y-4 p-4 max-w-[350px] bg-gray-50 rounded-lg">
|
||||
<Label className="font-medium block mb-2">Data Label Position</Label>
|
||||
<Tabs className="w-full" defaultValue={chartSettings.dataLabel.dataLabelPosition.toLowerCase()}>
|
||||
<TabsList className="w-full grid grid-cols-2 mb-4">
|
||||
<TabsTrigger onClick={() => setChartSettings({
|
||||
...chartSettings, dataLabel: {
|
||||
...chartSettings.dataLabel,
|
||||
dataLabelPosition: 'Inside'
|
||||
}
|
||||
})} value="inside">Inside</TabsTrigger>
|
||||
<TabsTrigger onClick={() => setChartSettings({
|
||||
...chartSettings, dataLabel: {
|
||||
...chartSettings.dataLabel,
|
||||
dataLabelPosition: 'Outside'
|
||||
}
|
||||
})} value="outside">Outside</TabsTrigger>
|
||||
</TabsList>
|
||||
{chartData.type === 'bar' && <TabsContent value="inside">
|
||||
<Label className="font-medium block mb-2">Data Label Alignment</Label>
|
||||
<Tabs className="w-full" defaultValue={chartSettings.dataLabel.dataLabelAlignment.toLowerCase()}>
|
||||
<TabsList className="w-full grid grid-cols-3">
|
||||
<TabsTrigger onClick={() => setChartSettings({
|
||||
...chartSettings, dataLabel: {
|
||||
...chartSettings.dataLabel,
|
||||
dataLabelAlignment: 'Base'
|
||||
}
|
||||
})} value="base">Base</TabsTrigger>
|
||||
<TabsTrigger onClick={() => setChartSettings({
|
||||
...chartSettings, dataLabel: {
|
||||
...chartSettings.dataLabel,
|
||||
dataLabelAlignment: 'Center'
|
||||
}
|
||||
})} value="center">Center</TabsTrigger>
|
||||
<TabsTrigger onClick={() => setChartSettings({
|
||||
...chartSettings, dataLabel: {
|
||||
...chartSettings.dataLabel,
|
||||
dataLabelAlignment: 'End'
|
||||
}
|
||||
})} value="end">End</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</TabsContent>}
|
||||
</Tabs>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex w-[350px] items-center justify-between p-3 bg-gray-100 rounded-lg">
|
||||
<Label htmlFor="legend" className="font-medium">Legend</Label>
|
||||
<Switch
|
||||
id="legend"
|
||||
checked={chartSettings.showLegend}
|
||||
onCheckedChange={(checked) => setChartSettings({ ...chartSettings, showLegend: checked })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{chartData.type !== 'pie' && <div className="flex w-[350px] items-center justify-between p-3 bg-gray-100 rounded-lg">
|
||||
<Label htmlFor="grid" className="font-medium">Grid Lines</Label>
|
||||
<Switch
|
||||
id="grid"
|
||||
checked={chartSettings.showGrid}
|
||||
onCheckedChange={(checked) => setChartSettings({ ...chartSettings, showGrid: checked })}
|
||||
/>
|
||||
</div>}
|
||||
|
||||
{chartData.type !== 'pie' && <div className="flex w-[350px] items-center justify-between p-3 bg-gray-100 rounded-lg">
|
||||
<Label htmlFor="axis-labels" className="font-medium">Axis Labels</Label>
|
||||
<Switch
|
||||
id="axis-labels"
|
||||
checked={chartSettings.showAxisLabel}
|
||||
onCheckedChange={(checked) => setChartSettings({ ...chartSettings, showAxisLabel: checked })}
|
||||
/>
|
||||
</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
};
|
||||
|
||||
export default ChartEditor;
|
||||
|
|
@ -0,0 +1,321 @@
|
|||
"use client";
|
||||
|
||||
import React, { ReactNode, useRef, useEffect, useState } from 'react';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { updateSlideImage, updateSlideIcon } from '@/store/slices/presentationGeneration';
|
||||
import ImageEditor from './ImageEditor';
|
||||
import IconsEditor from './IconsEditor';
|
||||
|
||||
interface EditableLayoutWrapperProps {
|
||||
children: ReactNode;
|
||||
slideIndex: number;
|
||||
slideData: any;
|
||||
isEditMode?: boolean;
|
||||
}
|
||||
|
||||
interface EditableElement {
|
||||
id: string;
|
||||
type: 'image' | 'icon';
|
||||
src: string;
|
||||
dataPath: string;
|
||||
data: any;
|
||||
element: HTMLImageElement;
|
||||
}
|
||||
|
||||
const EditableLayoutWrapper: React.FC<EditableLayoutWrapperProps> = ({
|
||||
children,
|
||||
slideIndex,
|
||||
slideData,
|
||||
isEditMode = true,
|
||||
}) => {
|
||||
const dispatch = useDispatch();
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [editableElements, setEditableElements] = useState<EditableElement[]>([]);
|
||||
const [activeEditor, setActiveEditor] = useState<EditableElement | null>(null);
|
||||
|
||||
/**
|
||||
* Recursively searches for image/icon data in the slide data structure
|
||||
*/
|
||||
const findDataPath = (targetUrl: string, data: any, path: string = ''): { path: string; type: 'image' | 'icon'; data: any } | null => {
|
||||
if (!data || typeof data !== 'object') return null;
|
||||
|
||||
// Check current level for __image_url__ or __icon_url__
|
||||
if (data.__image_url__ && isMatchingUrl(data.__image_url__, targetUrl)) {
|
||||
return { path, type: 'image', data };
|
||||
}
|
||||
|
||||
if (data.__icon_url__ && isMatchingUrl(data.__icon_url__, targetUrl)) {
|
||||
return { path, type: 'icon', data };
|
||||
}
|
||||
|
||||
// Recursively check nested objects and arrays
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
const newPath = path ? `${path}.${key}` : key;
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
const result = findDataPath(targetUrl, value[i], `${newPath}[${i}]`);
|
||||
if (result) return result;
|
||||
}
|
||||
} else if (value && typeof value === 'object') {
|
||||
const result = findDataPath(targetUrl, value, newPath);
|
||||
if (result) return result;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if two URLs match using various comparison strategies
|
||||
*/
|
||||
const isMatchingUrl = (url1: string, url2: string): boolean => {
|
||||
if (!url1 || !url2) return false;
|
||||
|
||||
// Direct match
|
||||
if (url1 === url2) return true;
|
||||
|
||||
// Remove protocol and domain differences
|
||||
const cleanUrl1 = url1.replace(/^https?:\/\/[^\/]+/, '').replace(/^\/+/, '');
|
||||
const cleanUrl2 = url2.replace(/^https?:\/\/[^\/]+/, '').replace(/^\/+/, '');
|
||||
|
||||
if (cleanUrl1 === cleanUrl2) return true;
|
||||
|
||||
// Handle app_data paths and placeholder URLs
|
||||
if (url1.includes('/app_data/') || url2.includes('/app_data/') ||
|
||||
url1.includes('placeholder') || url2.includes('placeholder')) {
|
||||
const getFilename = (path: string) => path.split('/').pop() || '';
|
||||
const filename1 = getFilename(url1);
|
||||
const filename2 = getFilename(url2);
|
||||
if (filename1 === filename2 && filename1 !== '') return true;
|
||||
}
|
||||
|
||||
// Extract and compare filenames for other URLs
|
||||
const getFilename = (path: string) => path.split('/').pop() || '';
|
||||
const filename1 = getFilename(url1);
|
||||
const filename2 = getFilename(url2);
|
||||
|
||||
if (filename1 === filename2 && filename1 !== '') {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check if one URL is contained in another (for partial matches)
|
||||
if (url1.includes(url2) || url2.includes(url1)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Finds and processes images in the DOM, making them editable
|
||||
*/
|
||||
const findAndProcessImages = () => {
|
||||
if (!containerRef.current || !isEditMode) return;
|
||||
|
||||
const imgElements = containerRef.current.querySelectorAll('img:not([data-editable-processed])');
|
||||
const newEditableElements: EditableElement[] = [];
|
||||
|
||||
imgElements.forEach((img, index) => {
|
||||
const htmlImg = img as HTMLImageElement;
|
||||
const src = htmlImg.src;
|
||||
|
||||
if (src) {
|
||||
const result = findDataPath(src, slideData);
|
||||
|
||||
if (result) {
|
||||
const { path: dataPath, type, data } = result;
|
||||
|
||||
// Mark as processed to prevent re-processing
|
||||
htmlImg.setAttribute('data-editable-processed', 'true');
|
||||
|
||||
const editableElement: EditableElement = {
|
||||
id: `${type}-${dataPath}-${index}`,
|
||||
type,
|
||||
src,
|
||||
dataPath,
|
||||
data,
|
||||
element: htmlImg
|
||||
};
|
||||
|
||||
newEditableElements.push(editableElement);
|
||||
|
||||
// Add click handler directly to the image
|
||||
const clickHandler = (e: Event) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setActiveEditor(editableElement);
|
||||
};
|
||||
|
||||
htmlImg.addEventListener('click', clickHandler);
|
||||
|
||||
// Add hover effects without changing layout
|
||||
htmlImg.style.cursor = 'pointer';
|
||||
htmlImg.style.transition = 'filter 0.2s, transform 0.2s';
|
||||
|
||||
const mouseEnterHandler = () => {
|
||||
htmlImg.style.filter = 'brightness(0.9)';
|
||||
|
||||
};
|
||||
|
||||
const mouseLeaveHandler = () => {
|
||||
htmlImg.style.filter = 'brightness(1)';
|
||||
|
||||
};
|
||||
|
||||
htmlImg.addEventListener('mouseenter', mouseEnterHandler);
|
||||
htmlImg.addEventListener('mouseleave', mouseLeaveHandler);
|
||||
|
||||
// Store cleanup functions
|
||||
(htmlImg as any)._editableCleanup = () => {
|
||||
htmlImg.removeEventListener('click', clickHandler);
|
||||
htmlImg.removeEventListener('mouseenter', mouseEnterHandler);
|
||||
htmlImg.removeEventListener('mouseleave', mouseLeaveHandler);
|
||||
htmlImg.style.cursor = '';
|
||||
htmlImg.style.transition = '';
|
||||
htmlImg.style.filter = '';
|
||||
htmlImg.style.transform = '';
|
||||
htmlImg.removeAttribute('data-editable-processed');
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
setEditableElements(prev => [...prev, ...newEditableElements]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Cleanup function to remove event listeners and reset styles
|
||||
*/
|
||||
const cleanupElements = () => {
|
||||
editableElements.forEach(({ element }) => {
|
||||
if ((element as any)._editableCleanup) {
|
||||
(element as any)._editableCleanup();
|
||||
}
|
||||
});
|
||||
setEditableElements([]);
|
||||
};
|
||||
|
||||
// Wait for LoadableComponent to render and then process images
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
findAndProcessImages();
|
||||
}, 300);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
cleanupElements();
|
||||
};
|
||||
}, [slideData, children]);
|
||||
|
||||
// Re-run when container content changes
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) return;
|
||||
|
||||
const observer = new MutationObserver((mutations) => {
|
||||
const hasNewImages = mutations.some(mutation =>
|
||||
Array.from(mutation.addedNodes).some(node =>
|
||||
node.nodeType === Node.ELEMENT_NODE &&
|
||||
(
|
||||
(node as Element).tagName === 'IMG' ||
|
||||
(node as Element).querySelector('img:not([data-editable-processed])')
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
if (hasNewImages) {
|
||||
setTimeout(findAndProcessImages, 100);
|
||||
}
|
||||
});
|
||||
|
||||
observer.observe(containerRef.current, {
|
||||
childList: true,
|
||||
subtree: true
|
||||
});
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, [slideData]);
|
||||
|
||||
/**
|
||||
* Handles closing the active editor
|
||||
*/
|
||||
const handleEditorClose = () => {
|
||||
setActiveEditor(null);
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles image change from ImageEditor
|
||||
*/
|
||||
const handleImageChange = (newImageUrl: string, prompt?: string) => {
|
||||
if (activeEditor && activeEditor.element) {
|
||||
// Update the DOM element immediately for visual feedback
|
||||
activeEditor.element.src = newImageUrl;
|
||||
|
||||
// Update Redux store
|
||||
dispatch(updateSlideImage({
|
||||
slideIndex,
|
||||
dataPath: activeEditor.dataPath,
|
||||
imageUrl: newImageUrl,
|
||||
prompt: prompt || activeEditor.data?.__image_prompt__ || ''
|
||||
}));
|
||||
|
||||
setActiveEditor(null);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles icon change from IconsEditor
|
||||
*/
|
||||
const handleIconChange = (newIconUrl: string, query?: string) => {
|
||||
if (activeEditor && activeEditor.element) {
|
||||
// Update the DOM element immediately for visual feedback
|
||||
activeEditor.element.src = newIconUrl;
|
||||
|
||||
// Update Redux store
|
||||
dispatch(updateSlideIcon({
|
||||
slideIndex,
|
||||
dataPath: activeEditor.dataPath,
|
||||
iconUrl: newIconUrl,
|
||||
query: query || activeEditor.data?.__icon_query__ || ''
|
||||
}));
|
||||
|
||||
setActiveEditor(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="editable-layout-wrapper">
|
||||
{children}
|
||||
|
||||
{/* Render ImageEditor when an image is being edited */}
|
||||
{activeEditor && activeEditor.type === 'image' && (
|
||||
<ImageEditor
|
||||
initialImage={activeEditor.src}
|
||||
slideIndex={slideIndex}
|
||||
promptContent={activeEditor.data?.__image_prompt__ || ''}
|
||||
imageIdx={0}
|
||||
properties={null}
|
||||
onClose={handleEditorClose}
|
||||
onImageChange={handleImageChange}
|
||||
>
|
||||
<div />
|
||||
</ImageEditor>
|
||||
)}
|
||||
|
||||
{/* Render IconsEditor when an icon is being edited */}
|
||||
{activeEditor && activeEditor.type === 'icon' && (
|
||||
<IconsEditor
|
||||
icon={activeEditor.src}
|
||||
index={0}
|
||||
icon_prompt={activeEditor.data?.__icon_query__ ? [activeEditor.data.__icon_query__] : []}
|
||||
onClose={handleEditorClose}
|
||||
onIconChange={handleIconChange}
|
||||
>
|
||||
<div />
|
||||
</IconsEditor>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditableLayoutWrapper;
|
||||
|
|
@ -7,66 +7,52 @@ import {
|
|||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { PlusIcon, Search } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { PresentationGenerationApi } from "../services/api/presentation-generation";
|
||||
import { RootState } from "@/store/store";
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
import { Search } from "lucide-react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { updateSlideIcon } from "@/store/slices/presentationGeneration";
|
||||
import { PresentationGenerationApi } from "../services/api/presentation-generation";
|
||||
import { getStaticFileUrl } from "../utils/others";
|
||||
|
||||
interface IconsEditorProps {
|
||||
icon: string;
|
||||
index: number;
|
||||
backgroundColor: string;
|
||||
hasBg: boolean;
|
||||
slideIndex: number;
|
||||
elementId: string;
|
||||
isWhite?: boolean;
|
||||
className?: string;
|
||||
icon_prompt?: string[] | null;
|
||||
onClose?: () => void;
|
||||
onIconChange?: (newIconUrl: string, query?: string) => void;
|
||||
}
|
||||
|
||||
const IconsEditor = ({
|
||||
icon: initialIcon,
|
||||
index,
|
||||
backgroundColor,
|
||||
hasBg,
|
||||
className,
|
||||
slideIndex,
|
||||
elementId,
|
||||
icon_prompt,
|
||||
onClose,
|
||||
}: IconsEditorProps) => {
|
||||
const dispatch = useDispatch();
|
||||
onIconChange,
|
||||
|
||||
}: IconsEditorProps) => {
|
||||
// State management
|
||||
const [icon, setIcon] = useState(initialIcon);
|
||||
const [icons, setIcons] = useState<string[]>([]);
|
||||
const [isEditorOpen, setIsEditorOpen] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState<string>(
|
||||
icon_prompt?.[0] || ""
|
||||
);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
// Update local state when initial icon changes
|
||||
useEffect(() => {
|
||||
setIcon(initialIcon);
|
||||
}, [initialIcon]);
|
||||
|
||||
// Search for icons when component opens
|
||||
useEffect(() => {
|
||||
if (isEditorOpen) {
|
||||
handleIconSearch();
|
||||
}
|
||||
}, [isEditorOpen]);
|
||||
|
||||
const handleIconClick = () => {
|
||||
setIsEditorOpen(true);
|
||||
};
|
||||
handleIconSearch();
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Searches for icons based on the current query
|
||||
*/
|
||||
const handleIconSearch = async () => {
|
||||
setLoading(true);
|
||||
const presentation_id = searchParams.get("id");
|
||||
|
|
@ -88,94 +74,100 @@ const IconsEditor = ({
|
|||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles icon selection and calls the parent callback
|
||||
*/
|
||||
const handleIconChange = (newIcon: string) => {
|
||||
|
||||
|
||||
setIcon(newIcon);
|
||||
dispatch(
|
||||
updateSlideIcon({ index: slideIndex, iconIdx: index, icon: newIcon })
|
||||
);
|
||||
setIsEditorOpen(false);
|
||||
|
||||
if (onIconChange) {
|
||||
onIconChange(newIcon, searchQuery || icon_prompt?.[0] || '');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Sheet open={true} onOpenChange={() => onClose?.()}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="w-[400px]"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<SheetHeader>
|
||||
<SheetTitle>Choose Icon</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="mt-6 space-y-4">
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleIconSearch();
|
||||
}}
|
||||
>
|
||||
<div className="relative mb-3">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 w-4 h-4" />
|
||||
<div className="icons-editor-container">
|
||||
|
||||
<Input
|
||||
placeholder="Search icons..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="outline"
|
||||
className="w-full text-semibold text-[#51459e]"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
|
||||
<Sheet open={true} onOpenChange={() => onClose?.()}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="w-[400px]"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<SheetHeader>
|
||||
<SheetTitle>Choose Icon</SheetTitle>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="mt-6 space-y-4">
|
||||
{/* Search Form */}
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleIconSearch();
|
||||
}}
|
||||
>
|
||||
Search
|
||||
</Button>
|
||||
</form>
|
||||
<div className="relative mb-3">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 w-4 h-4" />
|
||||
<Input
|
||||
placeholder="Search icons..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="outline"
|
||||
className="w-full text-semibold text-[#51459e]"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
Search
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{/* Icons grid */}
|
||||
<div className="max-h-[80vh] hide-scrollbar overflow-y-auto p-1">
|
||||
{loading ? (
|
||||
<div className="grid grid-cols-4 gap-4">
|
||||
{Array.from({ length: 40 }).map((_, index) => (
|
||||
<Skeleton key={index} className="w-16 h-16 rounded-lg" />
|
||||
))}
|
||||
</div>
|
||||
) : icons.length > 0 ? (
|
||||
<div className="grid grid-cols-4 gap-4">
|
||||
{icons.map((iconSrc, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleIconChange(iconSrc);
|
||||
}}
|
||||
className="w-12 h-12 cursor-pointer group relative rounded-lg overflow-hidden hover:bg-gray-100 p-2"
|
||||
>
|
||||
<img
|
||||
src={getStaticFileUrl(iconSrc)}
|
||||
alt={`Icon ${idx + 1}`}
|
||||
className="w-full h-full object-contain "
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center w-full h-[60vh] text-center text-gray-500 space-y-4">
|
||||
<Search className="w-12 h-12 text-gray-400" />
|
||||
<p className="text-sm">No icons found for your search.</p>
|
||||
<p className="text-xs">Try refining your search query.</p>
|
||||
</div>
|
||||
)}
|
||||
{/* Icons Grid */}
|
||||
<div className="max-h-[80vh] hide-scrollbar overflow-y-auto p-1">
|
||||
{loading ? (
|
||||
<div className="grid grid-cols-4 gap-4">
|
||||
{Array.from({ length: 40 }).map((_, index) => (
|
||||
<Skeleton key={index} className="w-16 h-16 rounded-lg" />
|
||||
))}
|
||||
</div>
|
||||
) : icons.length > 0 ? (
|
||||
<div className="grid grid-cols-4 gap-4">
|
||||
{icons.map((iconSrc, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleIconChange(iconSrc);
|
||||
}}
|
||||
className="w-12 h-12 cursor-pointer group relative rounded-lg overflow-hidden hover:bg-gray-100 p-2 transition-colors"
|
||||
>
|
||||
<img
|
||||
src={getStaticFileUrl(iconSrc)}
|
||||
alt={`Icon ${idx + 1}`}
|
||||
className="w-full h-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center w-full h-[60vh] text-center text-gray-500 space-y-4">
|
||||
<Search className="w-12 h-12 text-gray-400" />
|
||||
<p className="text-sm">No icons found for your search.</p>
|
||||
<p className="text-xs">Try refining your search query.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -13,32 +13,25 @@ import {
|
|||
Wand2,
|
||||
Upload,
|
||||
Move,
|
||||
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { useSelector } from "react-redux";
|
||||
import { PresentationGenerationApi } from "../services/api/presentation-generation";
|
||||
import { RootState } from "@/store/store";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import {
|
||||
updateSlideImage,
|
||||
updateSlideProperties,
|
||||
} from "@/store/slices/presentationGeneration";
|
||||
import { getStaticFileUrl, ThemeImagePrompt } from "../utils/others";
|
||||
|
||||
|
||||
import { ThemeImagePrompt } from "../utils/others";
|
||||
|
||||
interface ImageEditorProps {
|
||||
initialImage: string | null;
|
||||
imageIdx?: number;
|
||||
|
||||
slideIndex: number;
|
||||
|
||||
className?: string;
|
||||
promptContent?: string;
|
||||
properties?: null | any;
|
||||
onClose?: () => void;
|
||||
onImageChange?: (newImageUrl: string, prompt?: string) => void;
|
||||
|
||||
}
|
||||
|
||||
const ImageEditor = ({
|
||||
|
|
@ -48,12 +41,13 @@ const ImageEditor = ({
|
|||
promptContent,
|
||||
properties,
|
||||
onClose,
|
||||
onImageChange,
|
||||
|
||||
}: ImageEditorProps) => {
|
||||
const dispatch = useDispatch();
|
||||
|
||||
const { currentTheme } = useSelector((state: RootState) => state.theme);
|
||||
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
// State management
|
||||
const [image, setImage] = useState(initialImage);
|
||||
const [previewImages, setPreviewImages] = useState([initialImage]);
|
||||
const [prompt, setPrompt] = useState<string>("");
|
||||
|
|
@ -62,6 +56,8 @@ const ImageEditor = ({
|
|||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||
const [uploadedImageUrl, setUploadedImageUrl] = useState<string | null>(null);
|
||||
|
||||
// Focus point and object fit for image editing
|
||||
const [isFocusPointMode, setIsFocusPointMode] = useState(false);
|
||||
const [focusPoint, setFocusPoint] = useState(
|
||||
(properties &&
|
||||
|
|
@ -77,11 +73,14 @@ const ImageEditor = ({
|
|||
properties[imageIdx].initialObjectFit) ||
|
||||
"cover"
|
||||
);
|
||||
|
||||
// Refs
|
||||
const imageRef = useRef<HTMLImageElement>(null);
|
||||
const imageContainerRef = useRef<HTMLDivElement>(null);
|
||||
const toolbarRef = useRef<HTMLDivElement>(null);
|
||||
const popoverContentRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Update local state when initial image changes
|
||||
useEffect(() => {
|
||||
setImage(initialImage);
|
||||
setPreviewImages([initialImage]);
|
||||
|
|
@ -97,9 +96,7 @@ const ImageEditor = ({
|
|||
!toolbarRef.current.contains(event.target as Node) &&
|
||||
!popoverContentRef.current
|
||||
) {
|
||||
|
||||
if (isFocusPointMode) {
|
||||
// saveFocusPoint(); // Save focus point before closing
|
||||
saveImageProperties(objectFit, focusPoint);
|
||||
}
|
||||
setIsFocusPointMode(false);
|
||||
|
|
@ -110,21 +107,22 @@ const ImageEditor = ({
|
|||
return () => {
|
||||
document.removeEventListener("mousedown", handleClickOutside);
|
||||
};
|
||||
}, [isFocusPointMode, focusPoint]);
|
||||
|
||||
|
||||
}, [isFocusPointMode, focusPoint, objectFit]);
|
||||
|
||||
/**
|
||||
* Handles image selection and calls the parent callback
|
||||
*/
|
||||
const handleImageChange = (newImage: string) => {
|
||||
setImage(newImage);
|
||||
dispatch(
|
||||
updateSlideImage({
|
||||
index: slideIndex,
|
||||
imageIdx: imageIdx,
|
||||
image: newImage,
|
||||
})
|
||||
);
|
||||
|
||||
if (onImageChange) {
|
||||
onImageChange(newImage, promptContent);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles focus point adjustment when clicking on the image
|
||||
*/
|
||||
const handleFocusPointClick = (e: React.MouseEvent) => {
|
||||
if (!isFocusPointMode || !imageRef.current) return;
|
||||
|
||||
|
|
@ -147,14 +145,19 @@ const ImageEditor = ({
|
|||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Toggles focus point adjustment mode
|
||||
*/
|
||||
const toggleFocusPointMode = () => {
|
||||
if (isFocusPointMode) {
|
||||
// If turning off focus point mode, save the current focus point
|
||||
// saveFocusPoint();
|
||||
saveImageProperties(objectFit, focusPoint);
|
||||
}
|
||||
setIsFocusPointMode(!isFocusPointMode);
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles object fit change
|
||||
*/
|
||||
const handleFitChange = (fit: "cover" | "contain" | "fill") => {
|
||||
setObjectFit(fit);
|
||||
|
||||
|
|
@ -162,10 +165,12 @@ const ImageEditor = ({
|
|||
imageRef.current.style.objectFit = fit;
|
||||
}
|
||||
|
||||
// Save the fit change to your state
|
||||
saveImageProperties(fit, focusPoint);
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves image properties (focus point and object fit)
|
||||
*/
|
||||
const saveImageProperties = (
|
||||
fit: "cover" | "contain" | "fill",
|
||||
focusPoint: { x: number; y: number }
|
||||
|
|
@ -174,16 +179,12 @@ const ImageEditor = ({
|
|||
initialObjectFit: fit,
|
||||
initialFocusPoint: focusPoint,
|
||||
};
|
||||
|
||||
dispatch(
|
||||
updateSlideProperties({
|
||||
index: slideIndex,
|
||||
itemIdx: imageIdx,
|
||||
properties: propertiesData,
|
||||
})
|
||||
);
|
||||
// TODO: Save to Redux store if needed
|
||||
};
|
||||
|
||||
/**
|
||||
* Generates new images using AI
|
||||
*/
|
||||
const handleGenerateImage = async () => {
|
||||
try {
|
||||
setIsGenerating(true);
|
||||
|
|
@ -208,26 +209,24 @@ const ImageEditor = ({
|
|||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles file upload
|
||||
*/
|
||||
const handleFileUpload = async (
|
||||
event: React.ChangeEvent<HTMLInputElement>
|
||||
) => {
|
||||
const presentation_id = searchParams.get("id");
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
// Check file size (e.g., 5MB limit)
|
||||
// Validate file size (5MB limit)
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
const error_message = "File size should be less than 5MB";
|
||||
|
||||
setUploadError(error_message);
|
||||
setUploadError("File size should be less than 5MB");
|
||||
return;
|
||||
}
|
||||
|
||||
// Check file type
|
||||
// Validate file type
|
||||
if (!file.type.startsWith("image/")) {
|
||||
const error_message = "Please upload an image file";
|
||||
|
||||
setUploadError(error_message);
|
||||
setUploadError("Please upload an image file");
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -249,356 +248,191 @@ const ImageEditor = ({
|
|||
throw new Error(result.error || 'Upload failed');
|
||||
}
|
||||
|
||||
// Update state with the returned path
|
||||
setUploadedImageUrl(result.filePath);
|
||||
} catch (err) {
|
||||
const error_message = "Failed to upload image. Please try again.";
|
||||
|
||||
setUploadError(error_message);
|
||||
setUploadError("Failed to upload image. Please try again.");
|
||||
console.error("Upload error:", err);
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<Sheet open={true} onOpenChange={() => onClose?.()}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="w-[600px]"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<SheetHeader>
|
||||
<SheetTitle>Update Image</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="image-editor-container">
|
||||
|
||||
<div className="mt-6">
|
||||
<Tabs defaultValue="edit" className="w-full">
|
||||
<TabsList className="grid bg-blue-100 border border-blue-300 w-full grid-cols-3 mx-auto ">
|
||||
<TabsTrigger className="font-medium" value="edit">
|
||||
Edit
|
||||
</TabsTrigger>
|
||||
<TabsTrigger className="font-medium" value="generate">
|
||||
AI Generate
|
||||
</TabsTrigger>
|
||||
<TabsTrigger className="font-medium" value="upload">
|
||||
Upload
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="edit" className="mt-4 space-y-4">
|
||||
<div className="space-y-4">
|
||||
{/* Current Image Preview */}
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-base font-medium">Current Image</h3>
|
||||
<div
|
||||
ref={imageContainerRef}
|
||||
className="relative aspect-[4/3] w-full overflow-hidden rounded-lg border bg-gray-100"
|
||||
>
|
||||
{image ? (
|
||||
<img
|
||||
ref={imageRef}
|
||||
src={image}
|
||||
alt="Current image"
|
||||
className="w-full h-full object-cover cursor-pointer"
|
||||
style={{
|
||||
objectFit: objectFit,
|
||||
objectPosition: `${focusPoint.x}% ${focusPoint.y}%`,
|
||||
}}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleFocusPointClick(e);
|
||||
}}
|
||||
onError={(e) => {
|
||||
console.error('Image failed to load:', image);
|
||||
e.currentTarget.src = '/placeholder-image.png';
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center text-gray-400">
|
||||
<div className="text-center">
|
||||
<Upload className="w-8 h-8 mx-auto mb-2" />
|
||||
<p className="text-sm">No image selected</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Sheet open={true} onOpenChange={() => onClose?.()}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="w-[600px]"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<SheetHeader>
|
||||
<SheetTitle>Update Image</SheetTitle>
|
||||
</SheetHeader>
|
||||
|
||||
{/* Focus Point Indicator */}
|
||||
{isFocusPointMode && image && (
|
||||
<div
|
||||
className="absolute w-4 h-4 bg-blue-500 border-2 border-white rounded-full transform -translate-x-1/2 -translate-y-1/2 pointer-events-none shadow-lg"
|
||||
style={{
|
||||
left: `${focusPoint.x}%`,
|
||||
top: `${focusPoint.y}%`,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{/* Debug info */}
|
||||
{image && (
|
||||
<div className="text-xs text-gray-500 space-y-1">
|
||||
<p><strong>Image Path:</strong> {image}</p>
|
||||
<p><strong>Resolved URL:</strong> {image}</p>
|
||||
<p><strong>Focus Point:</strong> {focusPoint.x.toFixed(1)}%, {focusPoint.y.toFixed(1)}%</p>
|
||||
<p><strong>Object Fit:</strong> {objectFit}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Editing Controls */}
|
||||
<div className="mt-6">
|
||||
<Tabs defaultValue="generate" className="w-full">
|
||||
<TabsList className="grid bg-blue-100 border border-blue-300 w-full grid-cols-2 mx-auto">
|
||||
<TabsTrigger className="font-medium" value="generate">
|
||||
AI Generate
|
||||
</TabsTrigger>
|
||||
<TabsTrigger className="font-medium" value="upload">
|
||||
Upload
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
{/* Generate Tab */}
|
||||
<TabsContent value="generate" className="mt-4 space-y-4">
|
||||
<div className="space-y-4">
|
||||
{/* Focus Point Controls */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h4 className="text-sm font-medium">Focus Point</h4>
|
||||
<Button
|
||||
variant={isFocusPointMode ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
toggleFocusPointMode();
|
||||
}}
|
||||
disabled={!image}
|
||||
>
|
||||
<Move className="w-4 h-4 mr-2" />
|
||||
{isFocusPointMode ? "Done" : "Adjust"}
|
||||
</Button>
|
||||
</div>
|
||||
{isFocusPointMode && (
|
||||
<p className="text-xs text-gray-500">
|
||||
Click on the image above to set the focus point
|
||||
</p>
|
||||
)}
|
||||
<div>
|
||||
<h3 className="text-sm font-medium mb-1">Current Prompt</h3>
|
||||
<p className="text-sm text-gray-500">{promptContent}</p>
|
||||
</div>
|
||||
|
||||
{/* Object Fit Controls */}
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-medium">Image Fit</h4>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant={objectFit === "cover" ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleFitChange("cover");
|
||||
}}
|
||||
className="flex-1"
|
||||
disabled={!image}
|
||||
>
|
||||
Cover
|
||||
</Button>
|
||||
<Button
|
||||
variant={objectFit === "contain" ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleFitChange("contain");
|
||||
}}
|
||||
className="flex-1"
|
||||
disabled={!image}
|
||||
>
|
||||
Contain
|
||||
</Button>
|
||||
<Button
|
||||
variant={objectFit === "fill" ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleFitChange("fill");
|
||||
}}
|
||||
className="flex-1"
|
||||
disabled={!image}
|
||||
>
|
||||
Fill
|
||||
</Button>
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 space-y-1">
|
||||
<p><strong>Cover:</strong> Fill container, may crop image</p>
|
||||
<p><strong>Contain:</strong> Fit entire image, may show empty space</p>
|
||||
<p><strong>Fill:</strong> Stretch to fill container exactly</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-base font-medium mb-2">Image Description</h3>
|
||||
<Textarea
|
||||
placeholder="Describe the image you want to generate..."
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
className="min-h-[100px]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Quick Actions */}
|
||||
<div className="pt-2 border-t">
|
||||
<h4 className="text-sm font-medium mb-2">Quick Actions</h4>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setFocusPoint({ x: 50, y: 50 });
|
||||
setObjectFit("cover");
|
||||
saveImageProperties("cover", { x: 50, y: 50 });
|
||||
if (imageRef.current) {
|
||||
imageRef.current.style.objectFit = "cover";
|
||||
imageRef.current.style.objectPosition = "50% 50%";
|
||||
}
|
||||
}}
|
||||
className="flex-1"
|
||||
disabled={!image}
|
||||
>
|
||||
Reset to Default
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="generate" className="mt-4 space-y-4">
|
||||
<div></div>
|
||||
<div className="space-y-4">
|
||||
<div className="">
|
||||
<h3 className="text-sm font-medium mb-1">Current Prompt</h3>
|
||||
<Button
|
||||
onClick={handleGenerateImage}
|
||||
className="w-full"
|
||||
disabled={!prompt || isGenerating}
|
||||
>
|
||||
<Wand2 className="w-4 h-4 mr-2" />
|
||||
{isGenerating ? "Generating..." : "Generate Image"}
|
||||
</Button>
|
||||
|
||||
<p className="text-sm text-gray-500">{promptContent}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-base font-medium mb-2">
|
||||
Image Description
|
||||
</h3>
|
||||
<Textarea
|
||||
placeholder="Describe the image you want to generate..."
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
className="min-h-[100px]"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleGenerateImage}
|
||||
className="w-full"
|
||||
disabled={!prompt || isGenerating}
|
||||
>
|
||||
<Wand2 className="w-4 h-4 mr-2" />
|
||||
{isGenerating ? "Generating..." : "Generate Image"}
|
||||
</Button>
|
||||
{error && <p className="text-red-500 text-sm">{error}</p>}
|
||||
|
||||
{error && <p className="text-red-500 text-sm">{error}</p>}
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{isGenerating || previewImages.length === 0
|
||||
? Array.from({ length: 4 }).map((_, index) => (
|
||||
<Skeleton
|
||||
key={index}
|
||||
className="aspect-[4/3] w-full rounded-lg"
|
||||
/>
|
||||
))
|
||||
: previewImages.map((image, index) => (
|
||||
<div
|
||||
key={index}
|
||||
onClick={() => handleImageChange(image as string)}
|
||||
className="aspect-[4/3] w-full overflow-hidden rounded-lg border cursor-pointer"
|
||||
>
|
||||
<img
|
||||
src={
|
||||
image
|
||||
? getStaticFileUrl(image)
|
||||
: ""
|
||||
}
|
||||
alt={`Preview ${index + 1}`}
|
||||
className="w-full h-full object-cover"
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{isGenerating || previewImages.length === 0
|
||||
? Array.from({ length: 4 }).map((_, index) => (
|
||||
<Skeleton
|
||||
key={index}
|
||||
className="aspect-[4/3] w-full rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
))
|
||||
: previewImages.map((image, index) => (
|
||||
<div
|
||||
key={index}
|
||||
onClick={() => handleImageChange(image as string)}
|
||||
className="aspect-[4/3] w-full overflow-hidden rounded-lg border cursor-pointer hover:border-blue-500 transition-colors"
|
||||
>
|
||||
{image && (
|
||||
<img
|
||||
src={image}
|
||||
alt={`Preview ${index + 1}`}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="upload" className="mt-4 space-y-4">
|
||||
<div className="space-y-4">
|
||||
<div
|
||||
className={cn(
|
||||
"border-2 border-dashed rounded-lg p-8 text-center transition-colors",
|
||||
isUploading
|
||||
? "border-gray-400 bg-gray-50"
|
||||
: "border-gray-300"
|
||||
)}
|
||||
>
|
||||
<input
|
||||
type="file"
|
||||
id="file-upload"
|
||||
className="hidden"
|
||||
accept="image/*"
|
||||
onChange={handleFileUpload}
|
||||
disabled={isUploading}
|
||||
/>
|
||||
<label
|
||||
htmlFor="file-upload"
|
||||
</TabsContent>
|
||||
|
||||
{/* Upload Tab */}
|
||||
<TabsContent value="upload" className="mt-4 space-y-4">
|
||||
<div className="space-y-4">
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-center",
|
||||
isUploading ? "cursor-wait" : "cursor-pointer"
|
||||
"border-2 border-dashed rounded-lg p-8 text-center transition-colors",
|
||||
isUploading
|
||||
? "border-gray-400 bg-gray-50"
|
||||
: "border-gray-300 hover:border-blue-400"
|
||||
)}
|
||||
>
|
||||
{isUploading ? (
|
||||
<div className="w-8 h-8 border-2 border-gray-400 border-t-transparent rounded-full animate-spin mb-2" />
|
||||
) : (
|
||||
<Upload className="w-8 h-8 text-gray-500 mb-2" />
|
||||
)}
|
||||
<span className="text-sm text-gray-600">
|
||||
{isUploading
|
||||
? "Uploading your image..."
|
||||
: "Click to upload an image"}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500 mt-1">
|
||||
Maximum file size: 5MB
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
{uploadError && (
|
||||
<p className="text-red-500 text-sm text-center">
|
||||
{uploadError}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{(uploadedImageUrl || isUploading) && (
|
||||
<div className="mt-4">
|
||||
<h3 className="text-sm font-medium mb-2">
|
||||
Uploaded Image Preview
|
||||
</h3>
|
||||
<div className="aspect-[4/3] relative rounded-lg overflow-hidden border border-gray-200">
|
||||
<input
|
||||
type="file"
|
||||
id="file-upload"
|
||||
className="hidden"
|
||||
accept="image/*"
|
||||
onChange={handleFileUpload}
|
||||
disabled={isUploading}
|
||||
/>
|
||||
<label
|
||||
htmlFor="file-upload"
|
||||
className={cn(
|
||||
"flex flex-col items-center",
|
||||
isUploading ? "cursor-wait" : "cursor-pointer"
|
||||
)}
|
||||
>
|
||||
{isUploading ? (
|
||||
<div className="w-full h-full bg-gray-100 flex items-center justify-center">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 border-2 border-gray-400 border-t-transparent rounded-full animate-spin mb-2" />
|
||||
<span className="text-sm text-gray-500">
|
||||
Processing...
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-8 h-8 border-2 border-gray-400 border-t-transparent rounded-full animate-spin mb-2" />
|
||||
) : (
|
||||
uploadedImageUrl && (
|
||||
<div
|
||||
onClick={() =>
|
||||
handleImageChange(uploadedImageUrl)
|
||||
}
|
||||
className="cursor-pointer group w-full h-full"
|
||||
>
|
||||
<img
|
||||
src={uploadedImageUrl}
|
||||
alt="Uploaded preview"
|
||||
className="w-full h-full object-cover group-hover:scale-105 transition-transform"
|
||||
/>
|
||||
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-all duration-200" />
|
||||
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<span className="bg-white/90 px-3 py-1 rounded-full text-sm font-medium">
|
||||
Click to use this image
|
||||
<Upload className="w-8 h-8 text-gray-500 mb-2" />
|
||||
)}
|
||||
<span className="text-sm text-gray-600">
|
||||
{isUploading
|
||||
? "Uploading your image..."
|
||||
: "Click to upload an image"}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500 mt-1">
|
||||
Maximum file size: 5MB
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{uploadError && (
|
||||
<p className="text-red-500 text-sm text-center">
|
||||
{uploadError}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{(uploadedImageUrl || isUploading) && (
|
||||
<div className="mt-4">
|
||||
<h3 className="text-sm font-medium mb-2">
|
||||
Uploaded Image Preview
|
||||
</h3>
|
||||
<div className="aspect-[4/3] relative rounded-lg overflow-hidden border border-gray-200">
|
||||
{isUploading ? (
|
||||
<div className="w-full h-full bg-gray-100 flex items-center justify-center">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 border-2 border-gray-400 border-t-transparent rounded-full animate-spin mb-2" />
|
||||
<span className="text-sm text-gray-500">
|
||||
Processing...
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
) : (
|
||||
uploadedImageUrl && (
|
||||
<div
|
||||
onClick={() =>
|
||||
handleImageChange(uploadedImageUrl)
|
||||
}
|
||||
className="cursor-pointer group w-full h-full"
|
||||
>
|
||||
<img
|
||||
src={uploadedImageUrl}
|
||||
alt="Uploaded preview"
|
||||
className="w-full h-full object-cover group-hover:scale-105 transition-transform"
|
||||
/>
|
||||
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-all duration-200" />
|
||||
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<span className="bg-white/90 px-3 py-1 rounded-full text-sm font-medium">
|
||||
Click to use this image
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@
|
|||
|
||||
import React, { createContext, useContext, useRef, useEffect, ReactNode, useState } from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { updateSlideImage, updateSlideIcon } from '../../../store/slices/presentationGeneration';
|
||||
import ImageEditor from './ImageEditor';
|
||||
import IconsEditor from './IconsEditor';
|
||||
|
||||
|
|
@ -53,6 +55,8 @@ export const SmartEditableProvider: React.FC<SmartEditableProviderProps> = ({
|
|||
rect: DOMRect;
|
||||
} | null>(null);
|
||||
|
||||
const dispatch = useDispatch();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isEditMode || !containerRef.current || !slideData) return;
|
||||
|
||||
|
|
@ -61,13 +65,15 @@ export const SmartEditableProvider: React.FC<SmartEditableProviderProps> = ({
|
|||
const findEditableElements = () => {
|
||||
const elements: EditableElement[] = [];
|
||||
|
||||
console.log('🔍 Starting smart detection with slideData:', slideData);
|
||||
|
||||
// Detect Images and Icons only (text is now handled by SmartText components)
|
||||
// Detect Images and Icons only (text is now handled by TiptapTextReplacer)
|
||||
const detectEditableElementsFromData = (data: any, path: string = '') => {
|
||||
if (!data || typeof data !== 'object') return;
|
||||
|
||||
// Check for __image_url__ pattern
|
||||
if (data.__image_url__) {
|
||||
console.log(`📸 Found __image_url__ at ${path}:`, data.__image_url__);
|
||||
const imgElement = findDOMElementByImageUrl(container, data.__image_url__);
|
||||
if (imgElement) {
|
||||
elements.push({
|
||||
|
|
@ -78,14 +84,25 @@ export const SmartEditableProvider: React.FC<SmartEditableProviderProps> = ({
|
|||
slideIndex,
|
||||
initialImage: data.__image_url__,
|
||||
promptContent: data.__image_prompt__ || '',
|
||||
imageIdx: elements.filter(e => e.type === 'image').length
|
||||
imageIdx: elements.filter(e => e.type === 'image').length,
|
||||
onImageChange: (newImageUrl: string, prompt?: string) => {
|
||||
console.log(`🖼️ Image changed at ${path}:`, newImageUrl);
|
||||
dispatch(updateSlideImage({
|
||||
slideIndex,
|
||||
dataPath: path,
|
||||
imageUrl: newImageUrl,
|
||||
prompt: prompt
|
||||
}));
|
||||
}
|
||||
}
|
||||
});
|
||||
console.log(`✅ Matched image to DOM element:`, imgElement);
|
||||
}
|
||||
}
|
||||
|
||||
// Check for __icon_url__ pattern
|
||||
if (data.__icon_url__) {
|
||||
console.log(`🎯 Found __icon_url__ at ${path}:`, data.__icon_url__);
|
||||
const imgElement = findDOMElementByImageUrl(container, data.__icon_url__);
|
||||
if (imgElement) {
|
||||
elements.push({
|
||||
|
|
@ -99,11 +116,22 @@ export const SmartEditableProvider: React.FC<SmartEditableProviderProps> = ({
|
|||
index: elements.filter(e => e.type === 'icon').length,
|
||||
backgroundColor: '#3B82F6',
|
||||
hasBg: false,
|
||||
icon_prompt: data.__icon_query__ ? [data.__icon_query__] : []
|
||||
icon_prompt: data.__icon_query__ ? [data.__icon_query__] : [],
|
||||
onIconChange: (newIconUrl: string, query?: string) => {
|
||||
console.log(`🎯 Icon changed at ${path}:`, newIconUrl);
|
||||
dispatch(updateSlideIcon({
|
||||
slideIndex,
|
||||
dataPath: path,
|
||||
iconUrl: newIconUrl,
|
||||
query: query
|
||||
}));
|
||||
}
|
||||
}
|
||||
});
|
||||
console.log(`✅ Matched icon to DOM element:`, imgElement);
|
||||
}
|
||||
}
|
||||
|
||||
// Recursively scan nested objects and arrays
|
||||
Object.keys(data).forEach(key => {
|
||||
const value = data[key];
|
||||
|
|
@ -120,6 +148,7 @@ export const SmartEditableProvider: React.FC<SmartEditableProviderProps> = ({
|
|||
};
|
||||
|
||||
detectEditableElementsFromData(slideData);
|
||||
console.log('🎉 Final detected elements:', elements);
|
||||
setEditableElements(elements);
|
||||
};
|
||||
|
||||
|
|
@ -162,7 +191,7 @@ export const SmartEditableProvider: React.FC<SmartEditableProviderProps> = ({
|
|||
return () => {
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [slideIndex, slideId, slideData, isEditMode]); // Removed editableElements from dependency array
|
||||
}, [slideIndex, slideId, slideData, isEditMode, dispatch]);
|
||||
|
||||
// Set up event listeners when editableElements change
|
||||
useEffect(() => {
|
||||
|
|
|
|||
|
|
@ -1,500 +0,0 @@
|
|||
import { Slide } from "../types/slide";
|
||||
|
||||
import Type1Layout from "./slide_layouts/Type1Layout";
|
||||
import Type2Layout from "./slide_layouts/Type2Layout";
|
||||
import Type4Layout from "./slide_layouts/Type4Layout";
|
||||
import Type5Layout from "./slide_layouts/Type5Layout";
|
||||
import Type6Layout from "./slide_layouts/Type6Layout";
|
||||
import Type7Layout from "./slide_layouts/Type7Layout";
|
||||
import Type8Layout from "./slide_layouts/Type8Layout";
|
||||
import Type9Layout from "./slide_layouts/Type9Layout";
|
||||
|
||||
|
||||
import { Chart, ChartSettings } from "@/store/slices/presentationGeneration";
|
||||
|
||||
import { Pie, PieChart, Cell, CartesianGrid, Label } from "recharts";
|
||||
import {
|
||||
LineChart,
|
||||
Bar,
|
||||
Legend,
|
||||
BarChart,
|
||||
Tooltip,
|
||||
YAxis,
|
||||
Line,
|
||||
XAxis,
|
||||
} from "recharts";
|
||||
import { ResponsiveContainer } from "recharts";
|
||||
|
||||
import { ThemeColors } from "../store/themeSlice";
|
||||
import { isDarkColor } from "../utils/others";
|
||||
|
||||
import {
|
||||
formatTooltipValue,
|
||||
formatYAxisTick,
|
||||
transformedData,
|
||||
} from "../utils/chart";
|
||||
|
||||
export const renderSlideContent = (slide: Slide, language: string) => {
|
||||
switch (slide.type) {
|
||||
case 1:
|
||||
return (
|
||||
<Type1Layout
|
||||
slideIndex={slide.index}
|
||||
title={slide.content.title}
|
||||
slideId={slide.id}
|
||||
description={
|
||||
typeof slide.content.body === "string"
|
||||
? slide.content.body
|
||||
: slide.content.body[0]?.description || ""
|
||||
}
|
||||
images={slide.images || []}
|
||||
image_prompts={slide.content.image_prompts || []}
|
||||
properties={slide.properties}
|
||||
/>
|
||||
);
|
||||
case 2:
|
||||
return (
|
||||
<Type2Layout
|
||||
title={slide.content.title}
|
||||
slideId={slide.id}
|
||||
slideIndex={slide.index}
|
||||
body={Array.isArray(slide.content.body) ? slide.content.body : []}
|
||||
language={language || "English"}
|
||||
design_index={slide.design_index || 2}
|
||||
/>
|
||||
);
|
||||
|
||||
case 4:
|
||||
return (
|
||||
<Type4Layout
|
||||
title={slide.content.title}
|
||||
slideId={slide.id}
|
||||
slideIndex={slide.index}
|
||||
images={slide.images || []}
|
||||
body={Array.isArray(slide.content.body) ? slide.content.body : []}
|
||||
image_prompts={slide.content.image_prompts || []}
|
||||
properties={slide.properties}
|
||||
/>
|
||||
);
|
||||
|
||||
case 5:
|
||||
const isFullSizeGraph =
|
||||
slide.content.graph?.data.categories.length > 4 &&
|
||||
slide.content.graph.type !== "pie";
|
||||
return (
|
||||
<Type5Layout
|
||||
title={slide.content.title}
|
||||
slideId={slide.id}
|
||||
slideIndex={slide.index}
|
||||
description={(slide.content.body as string) || ""}
|
||||
isFullSizeGraph={isFullSizeGraph}
|
||||
graphData={slide.content.graph}
|
||||
/>
|
||||
);
|
||||
|
||||
case 6:
|
||||
return (
|
||||
<Type6Layout
|
||||
title={slide.content.title}
|
||||
slideId={slide.id}
|
||||
slideIndex={slide.index}
|
||||
description={slide.content.description || ""}
|
||||
body={Array.isArray(slide.content.body) ? slide.content.body : []}
|
||||
language={language || "English"}
|
||||
/>
|
||||
);
|
||||
|
||||
case 7:
|
||||
return (
|
||||
<Type7Layout
|
||||
title={slide.content.title}
|
||||
slideId={slide.id}
|
||||
slideIndex={slide.index}
|
||||
body={Array.isArray(slide.content.body) ? slide.content.body : []}
|
||||
icons={slide.icons || []}
|
||||
icon_queries={slide.content.icon_queries || []}
|
||||
/>
|
||||
);
|
||||
|
||||
case 8:
|
||||
return (
|
||||
<Type8Layout
|
||||
title={slide.content.title}
|
||||
slideId={slide.id}
|
||||
body={Array.isArray(slide.content.body) ? slide.content.body : []}
|
||||
slideIndex={slide.index}
|
||||
description={slide.content.description || ""}
|
||||
icons={slide.icons || []}
|
||||
icon_queries={slide.content.icon_queries || []}
|
||||
/>
|
||||
);
|
||||
|
||||
case 9:
|
||||
return (
|
||||
<Type9Layout
|
||||
slideIndex={slide.index}
|
||||
slideId={slide.id}
|
||||
title={slide.content.title}
|
||||
// @ts-ignore
|
||||
body={slide.content.body}
|
||||
language={language || "English"}
|
||||
graphData={slide.content.graph}
|
||||
/>
|
||||
);
|
||||
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
// CHART RENDERING
|
||||
export const renderChart = (
|
||||
localChartData: Chart,
|
||||
isMini: boolean = false,
|
||||
theme: ThemeColors,
|
||||
chartSettings?: ChartSettings
|
||||
) => {
|
||||
const chartColors = theme.chartColors || [];
|
||||
|
||||
const renderCustomizedLabel = ({
|
||||
cx,
|
||||
cy,
|
||||
midAngle,
|
||||
innerRadius,
|
||||
outerRadius,
|
||||
percent,
|
||||
index,
|
||||
}: any) => {
|
||||
const RADIAN = Math.PI / 180;
|
||||
const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
|
||||
const x = cx + radius * Math.cos(-midAngle * RADIAN);
|
||||
const y = cy + radius * Math.sin(-midAngle * RADIAN);
|
||||
const isDark = isDarkColor(theme.chartColors[index % chartColors.length]);
|
||||
|
||||
return (
|
||||
<text
|
||||
x={x}
|
||||
y={y}
|
||||
fill={isDark ? "#ffffff" : "#000000"}
|
||||
style={{ cursor: "pointer" }}
|
||||
textAnchor={x > cx ? "start" : "end"}
|
||||
dominantBaseline="central"
|
||||
>
|
||||
{`${(percent * 100).toFixed(0)}%`}
|
||||
</text>
|
||||
);
|
||||
};
|
||||
|
||||
// New function for outside labels
|
||||
const renderOutsideLabel = ({
|
||||
cx,
|
||||
cy,
|
||||
midAngle,
|
||||
innerRadius,
|
||||
outerRadius,
|
||||
percent,
|
||||
index,
|
||||
name,
|
||||
}: any) => {
|
||||
const RADIAN = Math.PI / 180;
|
||||
// Position the label further outside the pie
|
||||
const radius = outerRadius * 1.2;
|
||||
const x = cx + radius * Math.cos(-midAngle * RADIAN);
|
||||
const y = cy + radius * Math.sin(-midAngle * RADIAN);
|
||||
|
||||
return (
|
||||
<text
|
||||
x={x}
|
||||
y={y}
|
||||
fill={theme.slideTitle}
|
||||
style={{ cursor: "pointer" }}
|
||||
textAnchor={x > cx ? "start" : "end"}
|
||||
dominantBaseline="central"
|
||||
>
|
||||
{`${(percent * 100).toFixed(0)}%`}
|
||||
</text>
|
||||
);
|
||||
};
|
||||
|
||||
if (!localChartData) return null;
|
||||
switch (localChartData.type) {
|
||||
case "line":
|
||||
return (
|
||||
<ResponsiveContainer
|
||||
id="line-chart-container"
|
||||
width="100%"
|
||||
height={isMini ? 100 : 300}
|
||||
>
|
||||
<LineChart
|
||||
className="w-full"
|
||||
data={transformedData(localChartData)}
|
||||
style={{ cursor: "pointer" }}
|
||||
margin={{ bottom: !isMini ? 30 : 0, right: 30, left: 10, top: 20 }}
|
||||
>
|
||||
{chartSettings?.showGrid && (
|
||||
<CartesianGrid
|
||||
vertical={false}
|
||||
stroke={theme.slideDescription}
|
||||
opacity={0.2}
|
||||
/>
|
||||
)}
|
||||
{!isMini && chartSettings?.showAxisLabel && (
|
||||
<XAxis
|
||||
dataKey="name"
|
||||
tickSize={10}
|
||||
angle={-10}
|
||||
height={!isMini ? 30 : 0}
|
||||
interval={0}
|
||||
dy={!isMini ? 10 : 0}
|
||||
dx={!isMini ? -15 : 0}
|
||||
tick={{
|
||||
fill: theme.slideTitle,
|
||||
fontSize: 14,
|
||||
alignmentBaseline: "middle",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{!isMini && chartSettings?.showAxisLabel && (
|
||||
<YAxis
|
||||
tick={{ fill: theme.slideTitle }}
|
||||
tickFormatter={formatYAxisTick}
|
||||
padding={{ top: 15 }}
|
||||
>
|
||||
<Label
|
||||
value={localChartData.unit || ""}
|
||||
position="top"
|
||||
style={{
|
||||
textTransform: "capitalize",
|
||||
textAnchor: "start",
|
||||
fontSize: "16px",
|
||||
fill: theme.slideTitle,
|
||||
fontWeight: "bold",
|
||||
}}
|
||||
/>
|
||||
</YAxis>
|
||||
)}
|
||||
<Tooltip
|
||||
cursor={{ fill: "transparent" }}
|
||||
contentStyle={{
|
||||
backgroundColor: theme.slideBox,
|
||||
color: theme.slideTitle,
|
||||
border: "none",
|
||||
}}
|
||||
itemStyle={{
|
||||
color: theme.slideTitle,
|
||||
}}
|
||||
/>
|
||||
{!isMini && chartSettings?.showLegend && (
|
||||
<Legend verticalAlign="top" align="center" />
|
||||
)}
|
||||
{localChartData.data.series.map((serie, index) => (
|
||||
<Line
|
||||
isAnimationActive={false}
|
||||
key={serie.name || `Series ${index + 1}`}
|
||||
type="monotone"
|
||||
strokeWidth={2}
|
||||
dataKey={serie.name || `Series ${index + 1}`}
|
||||
stroke={chartColors[index % chartColors.length]}
|
||||
style={{ cursor: "pointer" }}
|
||||
// label={(chartSettings?.showDataLabel && localChartData.data.series.length === 1) ? {
|
||||
// position: chartSettings?.dataLabel.dataLabelPosition === "Outside" ? "top" : "center",
|
||||
// formatter: (value: number) => formatYAxisTick(value),
|
||||
// fill: chartSettings?.dataLabel.dataLabelPosition === "Outside" ? theme.slideTitle : '#ffffff',
|
||||
// fontWeight: 'bold',
|
||||
// fontSize: '12px',
|
||||
// fontFamily: theme.fontFamily
|
||||
// } : undefined}
|
||||
/>
|
||||
))}
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
);
|
||||
|
||||
case "pie":
|
||||
return (
|
||||
<ResponsiveContainer
|
||||
id="pie-chart-container"
|
||||
width="100%"
|
||||
height={isMini ? 100 : 300}
|
||||
>
|
||||
<PieChart>
|
||||
<Pie
|
||||
isAnimationActive={false}
|
||||
data={transformedData(localChartData)}
|
||||
dataKey="value"
|
||||
nameKey="name"
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
style={{ cursor: "pointer" }}
|
||||
label={
|
||||
chartSettings?.showDataLabel
|
||||
? chartSettings?.dataLabel.dataLabelPosition === "Inside"
|
||||
? renderCustomizedLabel
|
||||
: renderOutsideLabel
|
||||
: false
|
||||
}
|
||||
fill={theme.slideTitle}
|
||||
paddingAngle={2}
|
||||
labelLine={false}
|
||||
outerRadius={
|
||||
chartSettings?.dataLabel.dataLabelPosition === "Outside"
|
||||
? "80%"
|
||||
: "90%"
|
||||
}
|
||||
>
|
||||
{transformedData(localChartData).map((entry: any, index: any) => (
|
||||
<Cell
|
||||
key={`cell-${index}`}
|
||||
fill={chartColors[index % chartColors.length]}
|
||||
focusable={false}
|
||||
stroke="none"
|
||||
style={{
|
||||
border: "none",
|
||||
outline: "none",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip
|
||||
formatter={(value) =>
|
||||
formatTooltipValue(localChartData, value as number)
|
||||
}
|
||||
contentStyle={{
|
||||
backgroundColor: theme.slideBox,
|
||||
color: theme.slideTitle,
|
||||
border: "none",
|
||||
borderRadius: "6px",
|
||||
}}
|
||||
itemStyle={{
|
||||
color: theme.slideTitle,
|
||||
}}
|
||||
/>
|
||||
{!isMini && chartSettings?.showLegend && (
|
||||
<Legend verticalAlign="top" align="center" />
|
||||
)}
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
);
|
||||
|
||||
case "bar":
|
||||
default:
|
||||
return (
|
||||
<ResponsiveContainer
|
||||
id="bar-chart-container"
|
||||
width="100%"
|
||||
height={isMini ? 100 : 330}
|
||||
>
|
||||
<BarChart
|
||||
data={transformedData(localChartData)}
|
||||
margin={{ bottom: !isMini ? 30 : 0, top: 20 }}
|
||||
>
|
||||
{chartSettings?.showGrid && (
|
||||
<CartesianGrid
|
||||
vertical={false}
|
||||
stroke={theme.slideDescription}
|
||||
opacity={0.2}
|
||||
/>
|
||||
)}
|
||||
{!isMini && chartSettings?.showAxisLabel && (
|
||||
<XAxis
|
||||
stroke={theme.slideTitle}
|
||||
className=""
|
||||
dataKey="name"
|
||||
tickSize={10}
|
||||
angle={-10}
|
||||
height={!isMini ? 40 : 0}
|
||||
interval={0}
|
||||
dy={!isMini ? 20 : 0}
|
||||
dx={!isMini ? -10 : 0}
|
||||
tick={{
|
||||
fill: theme.slideTitle,
|
||||
fontSize: 14,
|
||||
alignmentBaseline: "middle",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{!isMini && chartSettings?.showAxisLabel && (
|
||||
<YAxis
|
||||
stroke={theme.slideTitle}
|
||||
tick={{ fill: theme.slideTitle }}
|
||||
tickFormatter={formatYAxisTick}
|
||||
padding={{ top: 20 }}
|
||||
>
|
||||
<Label
|
||||
value={localChartData.unit || ""}
|
||||
position="top"
|
||||
style={{
|
||||
textTransform: "capitalize",
|
||||
textAnchor: "start",
|
||||
fontSize: "16px",
|
||||
fill: theme.slideTitle,
|
||||
fontWeight: "bold",
|
||||
width: "fit",
|
||||
margin: "0 auto",
|
||||
}}
|
||||
/>
|
||||
</YAxis>
|
||||
)}
|
||||
<Tooltip
|
||||
cursor={{ fill: "transparent" }}
|
||||
contentStyle={{
|
||||
backgroundColor: theme.slideBox,
|
||||
color: theme.slideTitle,
|
||||
border: "none",
|
||||
}}
|
||||
itemStyle={{
|
||||
color: theme.slideTitle,
|
||||
}}
|
||||
/>
|
||||
{!isMini && chartSettings?.showLegend && (
|
||||
<Legend verticalAlign="top" align="center" />
|
||||
)}
|
||||
{localChartData &&
|
||||
localChartData.data &&
|
||||
localChartData.data.series &&
|
||||
localChartData.data.series.map((serie, index) => (
|
||||
<Bar
|
||||
isAnimationActive={false}
|
||||
key={serie.name || `Series ${index + 1}`}
|
||||
dataKey={serie.name || `Series ${index + 1}`}
|
||||
fill={chartColors[index % chartColors.length]}
|
||||
barSize={50}
|
||||
style={{ cursor: "pointer" }}
|
||||
radius={[5, 8, 0, 0]}
|
||||
label={
|
||||
chartSettings?.showDataLabel
|
||||
? {
|
||||
position:
|
||||
chartSettings?.dataLabel.dataLabelPosition ===
|
||||
"Outside"
|
||||
? "top"
|
||||
: chartSettings?.dataLabel.dataLabelAlignment ===
|
||||
"Base"
|
||||
? "insideBottom"
|
||||
: chartSettings?.dataLabel.dataLabelAlignment ===
|
||||
"Center"
|
||||
? "center"
|
||||
: "insideTop",
|
||||
formatter: (value: number) => formatYAxisTick(value),
|
||||
fill:
|
||||
chartSettings?.dataLabel.dataLabelPosition ===
|
||||
"Outside"
|
||||
? theme.slideTitle
|
||||
: "#ffffff",
|
||||
fontWeight: "bold",
|
||||
fontSize: "14px",
|
||||
fontFamily: theme.fontFamily,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
|
@ -70,84 +70,92 @@ export const LayoutProvider: React.FC<{ children: ReactNode }> = ({ children })
|
|||
const fileMap = new Map<string, { fileName: string; groupName: string }>();
|
||||
const groupedLayouts = new Map<string, LayoutInfo[]>();
|
||||
|
||||
// Start preloading process
|
||||
setIsPreloading(true);
|
||||
|
||||
for (const groupData of groupedLayoutsData) {
|
||||
try {
|
||||
for (const groupData of groupedLayoutsData) {
|
||||
|
||||
// Initialize group
|
||||
if (!layoutsByGroup.has(groupData.groupName)) {
|
||||
layoutsByGroup.set(groupData.groupName, new Set());
|
||||
}
|
||||
|
||||
// group settings or default settings
|
||||
const settings = groupData.settings || {
|
||||
description: `${groupData.groupName} presentation layouts`,
|
||||
ordered: false,
|
||||
isDefault: false
|
||||
};
|
||||
|
||||
groupSettingsMap.set(groupData.groupName, settings);
|
||||
const groupLayouts: LayoutInfo[] = [];
|
||||
|
||||
for (const fileName of groupData.files) {
|
||||
try {
|
||||
const file = fileName.replace('.tsx', '').replace('.ts', '');
|
||||
|
||||
const module = await import(`@/presentation-layouts/${groupData.groupName}/${file}`);
|
||||
|
||||
|
||||
if (!module.default) {
|
||||
toast({
|
||||
title: `${file} has no default export`,
|
||||
description: 'Please ensure the layout file exports a default component',
|
||||
});
|
||||
console.warn(`❌ ${file} has no default export`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!module.Schema) {
|
||||
toast({
|
||||
title: `${file} has no Schema export`,
|
||||
description: 'Please ensure the layout file exports a Schema',
|
||||
});
|
||||
console.warn(`❌ ${file} has no Schema export`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const originalLayoutId = module.layoutId || file.toLowerCase().replace(/layout$/, '');
|
||||
const uniqueKey = `${groupData.groupName}:${originalLayoutId}`;
|
||||
const layoutName = module.layoutName || file.replace(/([A-Z])/g, ' $1').trim();
|
||||
const layoutDescription = module.layoutDescription || `${layoutName} layout for presentations`;
|
||||
|
||||
|
||||
const jsonSchema = z.toJSONSchema(module.Schema, {
|
||||
override: (ctx) => {
|
||||
delete ctx.jsonSchema.default;
|
||||
},
|
||||
});
|
||||
|
||||
const layout: LayoutInfo = {
|
||||
id: originalLayoutId,
|
||||
name: layoutName,
|
||||
description: layoutDescription,
|
||||
json_schema: jsonSchema,
|
||||
groupName: groupData.groupName,
|
||||
};
|
||||
|
||||
|
||||
layoutsById.set(uniqueKey, layout);
|
||||
layoutsByGroup.get(groupData.groupName)!.add(originalLayoutId);
|
||||
fileMap.set(uniqueKey, { fileName, groupName: groupData.groupName });
|
||||
groupLayouts.push(layout);
|
||||
layouts.push(layout);
|
||||
|
||||
|
||||
} catch (error) {
|
||||
console.error(`💥 Error extracting schema for ${fileName} from ${groupData.groupName}:`, error);
|
||||
// Initialize group
|
||||
if (!layoutsByGroup.has(groupData.groupName)) {
|
||||
layoutsByGroup.set(groupData.groupName, new Set());
|
||||
}
|
||||
}
|
||||
|
||||
// Cache grouped layouts
|
||||
groupedLayouts.set(groupData.groupName, groupLayouts);
|
||||
// group settings or default settings
|
||||
const settings = groupData.settings || {
|
||||
description: `${groupData.groupName} presentation layouts`,
|
||||
ordered: false,
|
||||
isDefault: false
|
||||
};
|
||||
|
||||
groupSettingsMap.set(groupData.groupName, settings);
|
||||
const groupLayouts: LayoutInfo[] = [];
|
||||
|
||||
for (const fileName of groupData.files) {
|
||||
try {
|
||||
const file = fileName.replace('.tsx', '').replace('.ts', '');
|
||||
|
||||
const module = await import(`@/presentation-layouts/${groupData.groupName}/${file}`);
|
||||
|
||||
if (!module.default) {
|
||||
toast({
|
||||
title: `${file} has no default export`,
|
||||
description: 'Please ensure the layout file exports a default component',
|
||||
});
|
||||
console.warn(`❌ ${file} has no default export`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!module.Schema) {
|
||||
toast({
|
||||
title: `${file} has no Schema export`,
|
||||
description: 'Please ensure the layout file exports a Schema',
|
||||
});
|
||||
console.warn(`❌ ${file} has no Schema export`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Cache the layout component immediately after import
|
||||
const cacheKey = createCacheKey(groupData.groupName, fileName);
|
||||
if (!layoutCache.has(cacheKey)) {
|
||||
layoutCache.set(cacheKey, module.default);
|
||||
}
|
||||
|
||||
const originalLayoutId = module.layoutId || file.toLowerCase().replace(/layout$/, '');
|
||||
const uniqueKey = `${groupData.groupName}:${originalLayoutId}`;
|
||||
const layoutName = module.layoutName || file.replace(/([A-Z])/g, ' $1').trim();
|
||||
const layoutDescription = module.layoutDescription || `${layoutName} layout for presentations`;
|
||||
|
||||
const jsonSchema = z.toJSONSchema(module.Schema, {
|
||||
override: (ctx) => {
|
||||
delete ctx.jsonSchema.default;
|
||||
},
|
||||
});
|
||||
|
||||
const layout: LayoutInfo = {
|
||||
id: uniqueKey,
|
||||
name: layoutName,
|
||||
description: layoutDescription,
|
||||
json_schema: jsonSchema,
|
||||
groupName: groupData.groupName,
|
||||
};
|
||||
|
||||
layoutsById.set(uniqueKey, layout);
|
||||
layoutsByGroup.get(groupData.groupName)!.add(uniqueKey);
|
||||
fileMap.set(uniqueKey, { fileName, groupName: groupData.groupName });
|
||||
groupLayouts.push(layout);
|
||||
layouts.push(layout);
|
||||
|
||||
} catch (error) {
|
||||
console.error(`💥 Error extracting schema for ${fileName} from ${groupData.groupName}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// Cache grouped layouts
|
||||
groupedLayouts.set(groupData.groupName, groupLayouts);
|
||||
}
|
||||
} finally {
|
||||
setIsPreloading(false);
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
@ -185,8 +193,7 @@ export const LayoutProvider: React.FC<{ children: ReactNode }> = ({ children })
|
|||
const data = await buildData(groupedLayoutsData);
|
||||
setLayoutData(data);
|
||||
|
||||
// Preload layouts after loading schema
|
||||
await preloadLayouts(data.fileMap);
|
||||
// The preloading is now handled within buildData
|
||||
} catch (err: unknown) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to load layouts';
|
||||
setError(errorMessage);
|
||||
|
|
@ -196,33 +203,6 @@ export const LayoutProvider: React.FC<{ children: ReactNode }> = ({ children })
|
|||
}
|
||||
};
|
||||
|
||||
const preloadLayouts = async (fileMap: Map<string, { fileName: string; groupName: string }>) => {
|
||||
setIsPreloading(true);
|
||||
try {
|
||||
const layoutPromises = Array.from(fileMap.entries()).map(async ([layoutId, { fileName, groupName }]) => {
|
||||
const cacheKey = createCacheKey(groupName, fileName);
|
||||
if (!layoutCache.has(cacheKey)) {
|
||||
const layoutName = fileName.replace('.tsx', '').replace('.ts', '');
|
||||
|
||||
const Layout = dynamic(
|
||||
() => import(`@/presentation-layouts/${groupName}/${layoutName}`),
|
||||
{
|
||||
loading: () => <div className="w-full aspect-[16/9] bg-gray-100 animate-pulse rounded-lg" />,
|
||||
ssr: false,
|
||||
}
|
||||
) as React.ComponentType<{ data: any }>;
|
||||
|
||||
layoutCache.set(cacheKey, Layout);
|
||||
}
|
||||
});
|
||||
await Promise.all(layoutPromises);
|
||||
} catch (error) {
|
||||
console.error('Error preloading layouts:', error);
|
||||
} finally {
|
||||
setIsPreloading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getLayout = (layoutId: string): React.ComponentType<{ data: any }> | null => {
|
||||
if (!layoutData) return null;
|
||||
|
||||
|
|
@ -230,9 +210,7 @@ export const LayoutProvider: React.FC<{ children: ReactNode }> = ({ children })
|
|||
|
||||
// Search through all fileMap entries to find the layout
|
||||
for (const [key, info] of Array.from(layoutData.fileMap.entries())) {
|
||||
// Extract original layout ID from unique key (format: "groupName:layoutId")
|
||||
const originalId = key.split(':')[1];
|
||||
if (originalId === layoutId) {
|
||||
if (key === layoutId) {
|
||||
fileInfo = info;
|
||||
break;
|
||||
}
|
||||
|
|
@ -269,8 +247,7 @@ export const LayoutProvider: React.FC<{ children: ReactNode }> = ({ children })
|
|||
|
||||
// Search through all entries to find the layout (since we don't know the group)
|
||||
for (const [key, layout] of Array.from(layoutData.layoutsById.entries())) {
|
||||
const originalId = key.split(':')[1];
|
||||
if (originalId === layoutId) {
|
||||
if (key === layoutId) {
|
||||
return layout;
|
||||
}
|
||||
}
|
||||
|
|
@ -279,8 +256,7 @@ export const LayoutProvider: React.FC<{ children: ReactNode }> = ({ children })
|
|||
|
||||
const getLayoutByIdAndGroup = (layoutId: string, groupName: string): LayoutInfo | null => {
|
||||
if (!layoutData) return null;
|
||||
const uniqueKey = `${groupName}:${layoutId}`;
|
||||
return layoutData.layoutsById.get(uniqueKey) || null;
|
||||
return layoutData.layoutsById.get(layoutId) || null;
|
||||
};
|
||||
|
||||
const getLayoutsByGroup = (groupName: string): LayoutInfo[] => {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
import React, { useMemo } from 'react';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { useLayout } from '../context/LayoutContext';
|
||||
import { SmartEditableProvider } from '../components/SmartEditableWrapper';
|
||||
import EditableLayoutWrapper from '../components/EditableLayoutWrapper';
|
||||
import TiptapTextReplacer from '../components/TiptapTextReplacer';
|
||||
import { updateSlideContent } from '../../../store/slices/presentationGeneration';
|
||||
|
||||
|
|
@ -33,7 +33,7 @@ export const useGroupLayouts = () => {
|
|||
};
|
||||
}, [getLayoutsByGroup]);
|
||||
|
||||
// Render slide content with group validation and automatic Tiptap text editing
|
||||
// Render slide content with group validation, automatic Tiptap text editing, and editable images/icons
|
||||
const renderSlideContent = useMemo(() => {
|
||||
return (slide: any, isEditMode: boolean = true) => {
|
||||
const Layout = getGroupLayout(slide.layout, slide.layout_group);
|
||||
|
|
@ -46,11 +46,11 @@ export const useGroupLayouts = () => {
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isEditMode) {
|
||||
return (
|
||||
<SmartEditableProvider
|
||||
<EditableLayoutWrapper
|
||||
slideIndex={slide.index}
|
||||
slideId={slide.id || `slide-${slide.index}`}
|
||||
slideData={slide.content}
|
||||
isEditMode={isEditMode}
|
||||
>
|
||||
|
|
@ -74,7 +74,7 @@ export const useGroupLayouts = () => {
|
|||
>
|
||||
<Layout data={slide.content} />
|
||||
</TiptapTextReplacer>
|
||||
</SmartEditableProvider>
|
||||
</EditableLayoutWrapper>
|
||||
);
|
||||
}
|
||||
return <Layout data={slide.content} />;
|
||||
|
|
|
|||
|
|
@ -37,7 +37,6 @@ const LayoutSelection: React.FC<LayoutSelectionProps> = ({
|
|||
const Groups: LayoutGroup[] = groups.map(groupName => {
|
||||
const layouts = getLayoutsByGroup(groupName);
|
||||
const settings = getGroupSetting(groupName);
|
||||
|
||||
return {
|
||||
id: groupName,
|
||||
name: groupName,
|
||||
|
|
|
|||
|
|
@ -139,7 +139,7 @@ const SlideContent = ({
|
|||
{isStreaming && (
|
||||
<Loader2 className="w-8 h-8 absolute right-2 top-2 z-30 text-blue-800 animate-spin" />
|
||||
)}
|
||||
<div className={` w-full group mb-6`}>
|
||||
<div data-layout={slide.layout} data-group={slide.layout_group} className={` w-full group mb-6`}>
|
||||
{/* render slides */}
|
||||
{loading ? <div className="flex flex-col bg-white aspect-video items-center justify-center h-full">
|
||||
<Loader2 className="w-8 h-8 animate-spin" />
|
||||
|
|
|
|||
|
|
@ -100,7 +100,7 @@ export const PresentationCard = ({
|
|||
>
|
||||
<div className="absolute bg-transparent z-40 top-0 left-0 w-full h-full" />
|
||||
<div className="transform scale-[0.2] flex justify-center items-center origin-top-left w-[500%] h-[500%]">
|
||||
{renderSlideContent(slide)}
|
||||
{renderSlideContent(slide, false)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
37
servers/nextjs/package-lock.json
generated
37
servers/nextjs/package-lock.json
generated
|
|
@ -48,6 +48,7 @@
|
|||
"puppeteer": "^24.13.0",
|
||||
"react": "^18",
|
||||
"react-dom": "^18",
|
||||
"react-element-to-jsx-string": "^15.0.0",
|
||||
"react-redux": "^9.1.2",
|
||||
"recharts": "^2.15.4",
|
||||
"sonner": "^2.0.6",
|
||||
|
|
@ -115,6 +116,12 @@
|
|||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@base2/pretty-print-object": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@base2/pretty-print-object/-/pretty-print-object-1.0.1.tgz",
|
||||
"integrity": "sha512-4iri8i1AqYHJE2DstZYkyEprg6Pq6sKx3xn5FpySk9sNhH7qN2LLlHJCfDTZRILNwQNPD7mATWM0TBui7uC1pA==",
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/@cypress/request": {
|
||||
"version": "3.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@cypress/request/-/request-3.0.8.tgz",
|
||||
|
|
@ -4594,6 +4601,15 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/is-plain-object": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz",
|
||||
"integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-stream": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
|
||||
|
|
@ -6055,6 +6071,27 @@
|
|||
"react": "^18.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/react-element-to-jsx-string": {
|
||||
"version": "15.0.0",
|
||||
"resolved": "https://registry.npmjs.org/react-element-to-jsx-string/-/react-element-to-jsx-string-15.0.0.tgz",
|
||||
"integrity": "sha512-UDg4lXB6BzlobN60P8fHWVPX3Kyw8ORrTeBtClmIlGdkOOE+GYQSFvmEU5iLLpwp/6v42DINwNcwOhOLfQ//FQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@base2/pretty-print-object": "1.0.1",
|
||||
"is-plain-object": "5.0.0",
|
||||
"react-is": "18.1.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^0.14.8 || ^15.0.1 || ^16.0.0 || ^17.0.1 || ^18.0.0",
|
||||
"react-dom": "^0.14.8 || ^15.0.1 || ^16.0.0 || ^17.0.1 || ^18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-element-to-jsx-string/node_modules/react-is": {
|
||||
"version": "18.1.0",
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.1.0.tgz",
|
||||
"integrity": "sha512-Fl7FuabXsJnV5Q1qIOQwx/sagGF18kogb4gpfcG4gjLBWO0WDiiz1ko/ExayuxE7InyQkBLkxRFG5oxY6Uu3Kg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/react-is": {
|
||||
"version": "18.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
|
||||
|
|
|
|||
|
|
@ -51,6 +51,7 @@
|
|||
"puppeteer": "^24.13.0",
|
||||
"react": "^18",
|
||||
"react-dom": "^18",
|
||||
"react-element-to-jsx-string": "^15.0.0",
|
||||
"react-redux": "^9.1.2",
|
||||
"recharts": "^2.15.4",
|
||||
"sonner": "^2.0.6",
|
||||
|
|
|
|||
|
|
@ -191,6 +191,146 @@ const presentationGenerationSlice = createSlice({
|
|||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Update slide image at specific data path
|
||||
updateSlideImage: (
|
||||
state,
|
||||
action: PayloadAction<{
|
||||
slideIndex: number;
|
||||
dataPath: string;
|
||||
imageUrl: string;
|
||||
prompt?: string;
|
||||
}>
|
||||
) => {
|
||||
if (
|
||||
state.presentationData &&
|
||||
state.presentationData.slides &&
|
||||
state.presentationData.slides[action.payload.slideIndex]
|
||||
) {
|
||||
const slide = state.presentationData.slides[action.payload.slideIndex];
|
||||
const { dataPath, imageUrl, prompt } = action.payload;
|
||||
|
||||
// Helper function to set nested property value for images
|
||||
const setNestedImageValue = (obj: any, path: string, url: string, promptText?: string) => {
|
||||
const keys = path.split(/[.\[\]]+/).filter(Boolean);
|
||||
let current = obj;
|
||||
|
||||
// Navigate to the parent object
|
||||
for (let i = 0; i < keys.length - 1; i++) {
|
||||
const key = keys[i];
|
||||
if (isNaN(Number(key))) {
|
||||
if (!current[key]) {
|
||||
current[key] = {};
|
||||
}
|
||||
current = current[key];
|
||||
} else {
|
||||
const index = Number(key);
|
||||
if (!current[index]) {
|
||||
current[index] = {};
|
||||
}
|
||||
current = current[index];
|
||||
}
|
||||
}
|
||||
|
||||
// Set the image properties
|
||||
const finalKey = keys[keys.length - 1];
|
||||
if (isNaN(Number(finalKey))) {
|
||||
current[finalKey] = {
|
||||
__image_url__: url,
|
||||
__image_prompt__: promptText || ''
|
||||
};
|
||||
} else {
|
||||
current[Number(finalKey)] = {
|
||||
__image_url__: url,
|
||||
__image_prompt__: promptText || ''
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Update the slide image
|
||||
if (dataPath && slide.content) {
|
||||
setNestedImageValue(slide.content, dataPath, imageUrl, prompt);
|
||||
}
|
||||
|
||||
// Also update the images array if it exists
|
||||
if (slide.images && Array.isArray(slide.images)) {
|
||||
const imageIndex = parseInt(dataPath.split('[')[1]?.split(']')[0]) || 0;
|
||||
if (slide.images[imageIndex] !== undefined) {
|
||||
slide.images[imageIndex] = imageUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Update slide icon at specific data path
|
||||
updateSlideIcon: (
|
||||
state,
|
||||
action: PayloadAction<{
|
||||
slideIndex: number;
|
||||
dataPath: string;
|
||||
iconUrl: string;
|
||||
query?: string;
|
||||
}>
|
||||
) => {
|
||||
if (
|
||||
state.presentationData &&
|
||||
state.presentationData.slides &&
|
||||
state.presentationData.slides[action.payload.slideIndex]
|
||||
) {
|
||||
const slide = state.presentationData.slides[action.payload.slideIndex];
|
||||
const { dataPath, iconUrl, query } = action.payload;
|
||||
|
||||
// Helper function to set nested property value for icons
|
||||
const setNestedIconValue = (obj: any, path: string, url: string, queryText?: string) => {
|
||||
const keys = path.split(/[.\[\]]+/).filter(Boolean);
|
||||
let current = obj;
|
||||
|
||||
// Navigate to the parent object
|
||||
for (let i = 0; i < keys.length - 1; i++) {
|
||||
const key = keys[i];
|
||||
if (isNaN(Number(key))) {
|
||||
if (!current[key]) {
|
||||
current[key] = {};
|
||||
}
|
||||
current = current[key];
|
||||
} else {
|
||||
const index = Number(key);
|
||||
if (!current[index]) {
|
||||
current[index] = {};
|
||||
}
|
||||
current = current[index];
|
||||
}
|
||||
}
|
||||
|
||||
// Set the icon properties
|
||||
const finalKey = keys[keys.length - 1];
|
||||
if (isNaN(Number(finalKey))) {
|
||||
current[finalKey] = {
|
||||
__icon_url__: url,
|
||||
__icon_query__: queryText || ''
|
||||
};
|
||||
} else {
|
||||
current[Number(finalKey)] = {
|
||||
__icon_url__: url,
|
||||
__icon_query__: queryText || ''
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Update the slide icon
|
||||
if (dataPath && slide.content) {
|
||||
setNestedIconValue(slide.content, dataPath, iconUrl, query);
|
||||
}
|
||||
|
||||
// Also update the icons array if it exists
|
||||
if (slide.icons && Array.isArray(slide.icons)) {
|
||||
const iconIndex = parseInt(dataPath.split('[')[1]?.split(']')[0]) || 0;
|
||||
if (slide.icons[iconIndex] !== undefined) {
|
||||
slide.icons[iconIndex] = iconUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
|
@ -209,6 +349,8 @@ export const {
|
|||
updateSlide,
|
||||
deletePresentationSlide,
|
||||
updateSlideContent,
|
||||
updateSlideImage,
|
||||
updateSlideIcon,
|
||||
} = presentationGenerationSlice.actions;
|
||||
|
||||
export default presentationGenerationSlice.reducer;
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue