대시보드 수정사항 적용 #111

Merged
hyeonsu merged 7 commits from feat/dashboard into main 2025-10-20 17:02:58 +09:00
10 changed files with 483 additions and 121 deletions

View File

@ -1,7 +1,6 @@
"use client";
import React, { useState, useEffect, use } from "react";
import { useRouter } from "next/navigation";
import { DashboardViewer } from "@/components/dashboard/DashboardViewer";
import { DashboardElement } from "@/components/admin/dashboard/types";
@ -18,7 +17,6 @@ interface DashboardViewPageProps {
* -
*/
export default function DashboardViewPage({ params }: DashboardViewPageProps) {
const router = useRouter();
const resolvedParams = use(params);
const [dashboard, setDashboard] = useState<{
id: string;
@ -35,12 +33,7 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// 대시보드 데이터 로딩
useEffect(() => {
loadDashboard();
}, [resolvedParams.dashboardId]);
const loadDashboard = async () => {
const loadDashboard = React.useCallback(async () => {
setIsLoading(true);
setError(null);
@ -50,13 +43,16 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
try {
const dashboardData = await dashboardApi.getDashboard(resolvedParams.dashboardId);
setDashboard(dashboardData);
setDashboard({
...dashboardData,
elements: dashboardData.elements || [],
});
} catch (apiError) {
console.warn("API 호출 실패, 로컬 스토리지 확인:", apiError);
// API 실패 시 로컬 스토리지에서 찾기
const savedDashboards = JSON.parse(localStorage.getItem("savedDashboards") || "[]");
const savedDashboard = savedDashboards.find((d: any) => d.id === resolvedParams.dashboardId);
const savedDashboard = savedDashboards.find((d: { id: string }) => d.id === resolvedParams.dashboardId);
if (savedDashboard) {
setDashboard(savedDashboard);
@ -72,7 +68,12 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
} finally {
setIsLoading(false);
}
};
}, [resolvedParams.dashboardId]);
// 대시보드 데이터 로딩
useEffect(() => {
loadDashboard();
}, [loadDashboard]);
// 로딩 상태
if (isLoading) {
@ -159,10 +160,11 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
</div> */}
{/* 대시보드 뷰어 */}
<DashboardViewer
elements={dashboard.elements}
<DashboardViewer
elements={dashboard.elements}
dashboardId={dashboard.id}
backgroundColor={dashboard.settings?.backgroundColor}
resolution={dashboard.settings?.resolution}
/>
</div>
);
@ -171,8 +173,33 @@ export default function DashboardViewPage({ params }: DashboardViewPageProps) {
/**
*
*/
function generateSampleDashboard(dashboardId: string) {
const dashboards: Record<string, any> = {
function generateSampleDashboard(dashboardId: string): {
id: string;
title: string;
description?: string;
elements: DashboardElement[];
settings?: {
backgroundColor?: string;
resolution?: string;
};
createdAt: string;
updatedAt: string;
} {
const dashboards: Record<
string,
{
id: string;
title: string;
description?: string;
elements: DashboardElement[];
settings?: {
backgroundColor?: string;
resolution?: string;
};
createdAt: string;
updatedAt: string;
}
> = {
"sales-overview": {
id: "sales-overview",
title: "📊 매출 현황 대시보드",

View File

@ -141,18 +141,38 @@ export default function DashboardDesigner({ dashboardId: initialDashboardId }: D
const { dashboardApi } = await import("@/lib/api/dashboard");
const dashboard = await dashboardApi.getDashboard(id);
console.log("📊 대시보드 로드:", {
id: dashboard.id,
title: dashboard.title,
settings: dashboard.settings,
settingsType: typeof dashboard.settings,
});
// 대시보드 정보 설정
setDashboardId(dashboard.id);
setDashboardTitle(dashboard.title);
// 저장된 설정 복원
const settings = (dashboard as { settings?: { resolution?: Resolution; backgroundColor?: string } }).settings;
console.log("🎨 설정 복원:", {
settings,
resolution: settings?.resolution,
backgroundColor: settings?.backgroundColor,
currentResolution: resolution,
});
if (settings?.resolution) {
setResolution(settings.resolution);
console.log("✅ Resolution 설정됨:", settings.resolution);
} else {
console.log("⚠️ Resolution 없음, 기본값 유지:", resolution);
}
if (settings?.backgroundColor) {
setCanvasBackgroundColor(settings.backgroundColor);
console.log("✅ BackgroundColor 설정됨:", settings.backgroundColor);
} else {
console.log("⚠️ BackgroundColor 없음, 기본값 유지:", canvasBackgroundColor);
}
// 요소들 설정

View File

@ -32,11 +32,12 @@ export function BarChart({ data, config, width = 600, height = 400 }: BarChartPr
// X축 스케일 (카테고리)
const xScale = d3.scaleBand().domain(data.labels).range([0, chartWidth]).padding(0.2);
// Y축 스케일 (값)
const maxValue = d3.max(data.datasets.flatMap((ds) => ds.data)) || 0;
// Y축 스케일 (값) - 절대값 기준
const allValues = data.datasets.flatMap((ds) => ds.data);
const maxAbsValue = d3.max(allValues.map((v) => Math.abs(v))) || 0;
const yScale = d3
.scaleLinear()
.domain([0, maxValue * 1.1])
.domain([0, maxAbsValue * 1.1])
.range([chartHeight, 0])
.nice();
@ -49,23 +50,12 @@ export function BarChart({ data, config, width = 600, height = 400 }: BarChartPr
.style("text-anchor", "end")
.style("font-size", "12px");
// Y축 그리기
g.append("g").call(d3.axisLeft(yScale)).style("font-size", "12px");
// Y축 그리기 (값 표시 제거)
g.append("g")
.call(d3.axisLeft(yScale).tickFormat(() => ""))
.style("font-size", "12px");
// 그리드 라인
if (config.showGrid !== false) {
g.append("g")
.attr("class", "grid")
.call(
d3
.axisLeft(yScale)
.tickSize(-chartWidth)
.tickFormat(() => ""),
)
.style("stroke-dasharray", "3,3")
.style("stroke", "#e0e0e0")
.style("opacity", 0.5);
}
// 그리드 라인 제거됨
// 색상 팔레트
const colors = config.colors || ["#3B82F6", "#EF4444", "#10B981", "#F59E0B"];
@ -84,18 +74,48 @@ export function BarChart({ data, config, width = 600, height = 400 }: BarChartPr
.attr("y", chartHeight)
.attr("width", barWidth)
.attr("height", 0)
.attr("fill", dataset.color || colors[i % colors.length])
.attr("fill", (d) => {
// 음수면 빨간색 계열, 양수면 원래 색상
if (d < 0) {
return "#EF4444";
}
return dataset.color || colors[i % colors.length];
})
.attr("rx", 4);
// 애니메이션
// 애니메이션 - 절대값 기준으로 위쪽으로만 렌더링
if (config.enableAnimation !== false) {
bars
.transition()
.duration(config.animationDuration || 750)
.attr("y", (d) => yScale(d))
.attr("height", (d) => chartHeight - yScale(d));
.attr("y", (d) => yScale(Math.abs(d)))
.attr("height", (d) => chartHeight - yScale(Math.abs(d)));
} else {
bars.attr("y", (d) => yScale(d)).attr("height", (d) => chartHeight - yScale(d));
bars.attr("y", (d) => yScale(Math.abs(d))).attr("height", (d) => chartHeight - yScale(Math.abs(d)));
}
// 막대 위에 값 표시 (음수는 - 부호 포함)
const labels = g
.selectAll(`.label-${i}`)
.data(dataset.data)
.enter()
.append("text")
.attr("class", `label-${i}`)
.attr("x", (_, j) => (xScale(data.labels[j]) || 0) + barWidth * i + barWidth / 2)
.attr("y", (d) => yScale(Math.abs(d)) - 5)
.attr("text-anchor", "middle")
.style("font-size", "11px")
.style("font-weight", "500")
.style("fill", (d) => (d < 0 ? "#EF4444" : "#333"))
.text((d) => (d < 0 ? "-" : "") + Math.abs(d).toLocaleString());
// 애니메이션 (라벨)
if (config.enableAnimation !== false) {
labels
.style("opacity", 0)
.transition()
.duration(config.animationDuration || 750)
.style("opacity", 1);
}
// 툴팁

View File

@ -32,37 +32,25 @@ export function HorizontalBarChart({ data, config, width = 600, height = 400 }:
// Y축 스케일 (카테고리) - 수평이므로 Y축이 카테고리
const yScale = d3.scaleBand().domain(data.labels).range([0, chartHeight]).padding(0.2);
// X축 스케일 (값) - 수평이므로 X축이 값
const maxValue = d3.max(data.datasets.flatMap((ds) => ds.data)) || 0;
// X축 스케일 (값) - 수평이므로 X축이 값, 절대값 기준
const allValues = data.datasets.flatMap((ds) => ds.data);
const maxAbsValue = d3.max(allValues.map((v) => Math.abs(v))) || 0;
const xScale = d3
.scaleLinear()
.domain([0, maxValue * 1.1])
.domain([0, maxAbsValue * 1.1])
.range([0, chartWidth])
.nice();
// Y축 그리기 (카테고리)
g.append("g").call(d3.axisLeft(yScale)).style("font-size", "12px").selectAll("text").style("text-anchor", "end");
// X축 그리기 (값)
// X축 그리기 (값 표시 제거)
g.append("g")
.attr("transform", `translate(0,${chartHeight})`)
.call(d3.axisBottom(xScale))
.call(d3.axisBottom(xScale).tickFormat(() => ""))
.style("font-size", "12px");
// 그리드 라인
if (config.showGrid !== false) {
g.append("g")
.attr("class", "grid")
.call(
d3
.axisBottom(xScale)
.tickSize(chartHeight)
.tickFormat(() => ""),
)
.style("stroke-dasharray", "3,3")
.style("stroke", "#e0e0e0")
.style("opacity", 0.5);
}
// 그리드 라인 제거됨
// 색상 팔레트
const colors = config.colors || ["#3B82F6", "#EF4444", "#10B981", "#F59E0B"];
@ -81,17 +69,49 @@ export function HorizontalBarChart({ data, config, width = 600, height = 400 }:
.attr("y", (_, j) => (yScale(data.labels[j]) || 0) + barHeight * i)
.attr("width", 0)
.attr("height", barHeight)
.attr("fill", dataset.color || colors[i % colors.length])
.attr("fill", (d) => {
// 음수면 빨간색 계열, 양수면 원래 색상
if (d < 0) {
return "#EF4444";
}
return dataset.color || colors[i % colors.length];
})
.attr("ry", 4);
// 애니메이션
// 애니메이션 - 절대값 기준으로 오른쪽으로만 렌더링
if (config.enableAnimation !== false) {
bars
.transition()
.duration(config.animationDuration || 750)
.attr("width", (d) => xScale(d));
.attr("x", 0)
.attr("width", (d) => xScale(Math.abs(d)));
} else {
bars.attr("width", (d) => xScale(d));
bars.attr("x", 0).attr("width", (d) => xScale(Math.abs(d)));
}
// 막대 끝에 값 표시 (음수는 - 부호 포함)
const labels = g
.selectAll(`.label-${i}`)
.data(dataset.data)
.enter()
.append("text")
.attr("class", `label-${i}`)
.attr("x", (d) => xScale(Math.abs(d)) + 5)
.attr("y", (_, j) => (yScale(data.labels[j]) || 0) + barHeight * i + barHeight / 2)
.attr("text-anchor", "start")
.attr("dominant-baseline", "middle")
.style("font-size", "11px")
.style("font-weight", "500")
.style("fill", (d) => (d < 0 ? "#EF4444" : "#333"))
.text((d) => (d < 0 ? "-" : "") + Math.abs(d).toLocaleString());
// 애니메이션 (라벨)
if (config.enableAnimation !== false) {
labels
.style("opacity", 0)
.transition()
.duration(config.animationDuration || 750)
.style("opacity", 1);
}
// 툴팁

View File

@ -66,24 +66,12 @@ export function StackedBarChart({ data, config, width = 600, height = 400 }: Sta
.style("text-anchor", "end")
.style("font-size", "12px");
// Y축 그리기
const yAxis = config.stackMode === "percent" ? d3.axisLeft(yScale).tickFormat((d) => `${d}%`) : d3.axisLeft(yScale);
g.append("g").call(yAxis).style("font-size", "12px");
// Y축 그리기 (값 표시 제거)
g.append("g")
.call(d3.axisLeft(yScale).tickFormat(() => ""))
.style("font-size", "12px");
// 그리드 라인
if (config.showGrid !== false) {
g.append("g")
.attr("class", "grid")
.call(
d3
.axisLeft(yScale)
.tickSize(-chartWidth)
.tickFormat(() => ""),
)
.style("stroke-dasharray", "3,3")
.style("stroke", "#e0e0e0")
.style("opacity", 0.5);
}
// 그리드 라인 제거됨
// 색상 팔레트
const colors = config.colors || ["#3B82F6", "#EF4444", "#10B981", "#F59E0B"];
@ -131,6 +119,47 @@ export function StackedBarChart({ data, config, width = 600, height = 400 }: Sta
.attr("height", (d) => yScale(d[0] as number) - yScale(d[1] as number));
}
// 각 세그먼트에 값 표시
layers.each(function (layerData, layerIndex) {
d3.select(this)
.selectAll("text")
.data(layerData)
.enter()
.append("text")
.attr("x", (d) => (xScale((d.data as any).label) || 0) + xScale.bandwidth() / 2)
.attr("y", (d) => {
const segmentHeight = yScale(d[0] as number) - yScale(d[1] as number);
const segmentMiddle = yScale(d[1] as number) + segmentHeight / 2;
return segmentMiddle;
})
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.style("font-size", "11px")
.style("font-weight", "500")
.style("fill", "white")
.style("pointer-events", "none")
.text((d) => {
const value = (d[1] as number) - (d[0] as number);
if (config.stackMode === "percent") {
return value > 5 ? `${value.toFixed(0)}%` : "";
}
return value > 0 ? value.toLocaleString() : "";
})
.style("opacity", 0);
// 애니메이션 (라벨)
if (config.enableAnimation !== false) {
d3.select(this)
.selectAll("text")
.transition()
.delay(config.animationDuration || 750)
.duration(300)
.style("opacity", 1);
} else {
d3.select(this).selectAll("text").style("opacity", 1);
}
});
// 툴팁
if (config.showTooltip !== false) {
bars

View File

@ -95,24 +95,21 @@ export function ListWidgetConfigModal({ isOpen, element, onClose, onSave }: List
}, []);
// 쿼리 실행 결과 처리
const handleQueryTest = useCallback(
(result: QueryResult) => {
setQueryResult(result);
const handleQueryTest = useCallback((result: QueryResult) => {
setQueryResult(result);
// 자동 모드이고 기존 컬럼이 없을 때만 자동 생성
if (listConfig.columnMode === "auto" && result.columns.length > 0 && listConfig.columns.length === 0) {
const autoColumns: ListColumn[] = result.columns.map((col, idx) => ({
id: `col_${idx}`,
label: col,
field: col,
align: "left",
visible: true,
}));
setListConfig((prev) => ({ ...prev, columns: autoColumns }));
}
},
[listConfig.columnMode, listConfig.columns.length],
);
// 쿼리 실행할 때마다 컬럼 초기화 후 자동 생성
if (result.columns.length > 0) {
const autoColumns: ListColumn[] = result.columns.map((col, idx) => ({
id: `col_${idx}`,
label: col,
field: col,
align: "left",
visible: true,
}));
setListConfig((prev) => ({ ...prev, columns: autoColumns }));
}
}, []);
// 다음 단계
const handleNext = () => {
@ -176,9 +173,7 @@ export function ListWidgetConfigModal({ isOpen, element, onClose, onSave }: List
</div>
{/* 참고: 리스트 위젯은 제목이 항상 표시됩니다 */}
<div className="rounded bg-blue-50 p-2 text-xs text-blue-700">
💡
</div>
<div className="rounded bg-blue-50 p-2 text-xs text-blue-700">💡 </div>
</div>
{/* 진행 상태 표시 */}

View File

@ -1,6 +1,6 @@
"use client";
import React from "react";
import React, { useState } from "react";
import { ListColumn } from "../../types";
import { Card } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
@ -21,8 +21,12 @@ interface ColumnSelectorProps {
* -
* -
* - , ,
* -
*/
export function ColumnSelector({ availableColumns, selectedColumns, sampleData, onChange }: ColumnSelectorProps) {
const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
// 컬럼 선택/해제
const handleToggle = (field: string) => {
const exists = selectedColumns.find((col) => col.field === field);
@ -50,17 +54,53 @@ export function ColumnSelector({ availableColumns, selectedColumns, sampleData,
onChange(selectedColumns.map((col) => (col.field === field ? { ...col, align } : col)));
};
// 드래그 시작
const handleDragStart = (index: number) => {
setDraggedIndex(index);
};
// 드래그 오버 - 실시간으로 순서 변경하여 UI 업데이트
const handleDragOver = (e: React.DragEvent, hoverIndex: number) => {
e.preventDefault();
if (draggedIndex === null || draggedIndex === hoverIndex) return;
setDragOverIndex(hoverIndex);
const newColumns = [...selectedColumns];
const draggedItem = newColumns[draggedIndex];
newColumns.splice(draggedIndex, 1);
newColumns.splice(hoverIndex, 0, draggedItem);
setDraggedIndex(hoverIndex);
onChange(newColumns);
};
// 드롭
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
setDraggedIndex(null);
setDragOverIndex(null);
};
// 드래그 종료
const handleDragEnd = () => {
setDraggedIndex(null);
setDragOverIndex(null);
};
return (
<Card className="p-4">
<div className="mb-4">
<h3 className="text-lg font-semibold text-gray-800"> </h3>
<p className="text-sm text-gray-600"> </p>
<p className="text-sm text-gray-600">
. .
</p>
</div>
<div className="space-y-3">
{availableColumns.map((field) => {
const selectedCol = selectedColumns.find((col) => col.field === field);
const isSelected = !!selectedCol;
{/* 선택된 컬럼을 먼저 순서대로 표시 */}
{selectedColumns.map((selectedCol, columnIndex) => {
const field = selectedCol.field;
const preview = sampleData[field];
const previewText =
preview !== undefined && preview !== null
@ -68,19 +108,36 @@ export function ColumnSelector({ availableColumns, selectedColumns, sampleData,
? JSON.stringify(preview).substring(0, 30)
: String(preview).substring(0, 30)
: "";
const isSelected = true;
const isDraggable = true;
return (
<div
key={field}
className={`rounded-lg border p-4 transition-colors ${
draggable={isDraggable}
onDragStart={(e) => {
if (isDraggable) {
handleDragStart(columnIndex);
e.currentTarget.style.cursor = "grabbing";
}
}}
onDragOver={(e) => isDraggable && handleDragOver(e, columnIndex)}
onDrop={handleDrop}
onDragEnd={(e) => {
handleDragEnd();
e.currentTarget.style.cursor = "grab";
}}
className={`rounded-lg border p-4 transition-all ${
isSelected ? "border-blue-300 bg-blue-50" : "border-gray-200"
} ${isDraggable ? "cursor-grab active:cursor-grabbing" : ""} ${
draggedIndex === columnIndex ? "opacity-50" : ""
}`}
>
<div className="mb-3 flex items-start gap-3">
<Checkbox checked={isSelected} onCheckedChange={() => handleToggle(field)} className="mt-1" />
<div className="flex-1">
<div className="flex items-center gap-2">
<GripVertical className="h-4 w-4 text-gray-400" />
<GripVertical className={`h-4 w-4 ${isDraggable ? "text-blue-500" : "text-gray-400"}`} />
<span className="font-medium text-gray-700">{field}</span>
{previewText && <span className="text-xs text-gray-500">(: {previewText})</span>}
</div>
@ -122,6 +179,36 @@ export function ColumnSelector({ availableColumns, selectedColumns, sampleData,
</div>
);
})}
{/* 선택되지 않은 컬럼들을 아래에 표시 */}
{availableColumns
.filter((field) => !selectedColumns.find((col) => col.field === field))
.map((field) => {
const preview = sampleData[field];
const previewText =
preview !== undefined && preview !== null
? typeof preview === "object"
? JSON.stringify(preview).substring(0, 30)
: String(preview).substring(0, 30)
: "";
const isSelected = false;
const isDraggable = false;
return (
<div key={field} className={`rounded-lg border border-gray-200 p-4 transition-all`}>
<div className="mb-3 flex items-start gap-3">
<Checkbox checked={false} onCheckedChange={() => handleToggle(field)} className="mt-1" />
<div className="flex-1">
<div className="flex items-center gap-2">
<GripVertical className="h-4 w-4 text-gray-400" />
<span className="font-medium text-gray-700">{field}</span>
{previewText && <span className="text-xs text-gray-500">(: {previewText})</span>}
</div>
</div>
</div>
</div>
);
})}
</div>
{selectedColumns.length === 0 && (

View File

@ -1,6 +1,6 @@
"use client";
import React from "react";
import React, { useState } from "react";
import { ListColumn } from "../../types";
import { Card } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
@ -19,8 +19,12 @@ interface ManualColumnEditorProps {
*
* - /
* -
* -
*/
export function ManualColumnEditor({ availableFields, columns, onChange }: ManualColumnEditorProps) {
const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
// 새 컬럼 추가
const handleAddColumn = () => {
const newCol: ListColumn = {
@ -43,12 +47,48 @@ export function ManualColumnEditor({ availableFields, columns, onChange }: Manua
onChange(columns.map((col) => (col.id === id ? { ...col, ...updates } : col)));
};
// 드래그 시작
const handleDragStart = (index: number) => {
setDraggedIndex(index);
};
// 드래그 오버 - 실시간으로 순서 변경하여 UI 업데이트
const handleDragOver = (e: React.DragEvent, hoverIndex: number) => {
e.preventDefault();
if (draggedIndex === null || draggedIndex === hoverIndex) return;
setDragOverIndex(hoverIndex);
const newColumns = [...columns];
const draggedItem = newColumns[draggedIndex];
newColumns.splice(draggedIndex, 1);
newColumns.splice(hoverIndex, 0, draggedItem);
setDraggedIndex(hoverIndex);
onChange(newColumns);
};
// 드롭
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
setDraggedIndex(null);
setDragOverIndex(null);
};
// 드래그 종료
const handleDragEnd = () => {
setDraggedIndex(null);
setDragOverIndex(null);
};
return (
<Card className="p-4">
<div className="mb-4 flex items-center justify-between">
<div>
<h3 className="text-lg font-semibold text-gray-800"> </h3>
<p className="text-sm text-gray-600"> </p>
<p className="text-sm text-gray-600">
. .
</p>
</div>
<Button onClick={handleAddColumn} size="sm" className="gap-2">
<Plus className="h-4 w-4" />
@ -58,9 +98,25 @@ export function ManualColumnEditor({ availableFields, columns, onChange }: Manua
<div className="space-y-3">
{columns.map((col, index) => (
<div key={col.id} className="rounded-lg border border-gray-200 bg-gray-50 p-4">
<div
key={col.id}
draggable
onDragStart={(e) => {
handleDragStart(index);
e.currentTarget.style.cursor = "grabbing";
}}
onDragOver={(e) => handleDragOver(e, index)}
onDrop={handleDrop}
onDragEnd={(e) => {
handleDragEnd();
e.currentTarget.style.cursor = "grab";
}}
className={`cursor-grab rounded-lg border border-gray-200 bg-gray-50 p-4 transition-all active:cursor-grabbing ${
draggedIndex === index ? "opacity-50" : ""
}`}
>
<div className="mb-3 flex items-center gap-2">
<GripVertical className="h-4 w-4 text-gray-400" />
<GripVertical className="h-4 w-4 text-blue-500" />
<span className="font-medium text-gray-700"> {index + 1}</span>
<Button
onClick={() => handleRemove(col.id)}

View File

@ -2,13 +2,15 @@
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Save, Loader2, Plus, Settings, Trash2 } from "lucide-react";
import { ArrowLeft, Save, Loader2, Plus, Settings, Trash2, Edit2 } from "lucide-react";
import { yardLayoutApi } from "@/lib/api/yardLayoutApi";
import dynamic from "next/dynamic";
import { YardLayout, YardPlacement } from "./types";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { AlertCircle, CheckCircle } from "lucide-react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
const Yard3DCanvas = dynamic(() => import("./Yard3DCanvas"), {
ssr: false,
@ -45,6 +47,14 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
success: boolean;
message: string;
}>({ open: false, success: false, message: "" });
const [deleteConfirmDialog, setDeleteConfirmDialog] = useState<{
open: boolean;
placementId: number | null;
}>({ open: false, placementId: null });
const [editLayoutDialog, setEditLayoutDialog] = useState<{
open: boolean;
name: string;
}>({ open: false, name: "" });
// 배치 목록 로드
useEffect(() => {
@ -110,11 +120,15 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
setShowConfigPanel(true);
};
// 요소 삭제 (로컬 상태에서만 삭제, 저장 시 서버에 반영)
// 요소 삭제 확인 Dialog 열기
const handleDeletePlacement = (placementId: number) => {
if (!confirm("이 요소를 삭제하시겠습니까?")) {
return;
}
setDeleteConfirmDialog({ open: true, placementId });
};
// 요소 삭제 확정 (로컬 상태에서만 삭제, 저장 시 서버에 반영)
const confirmDeletePlacement = () => {
const { placementId } = deleteConfirmDialog;
if (placementId === null) return;
setPlacements((prev) => prev.filter((p) => p.id !== placementId));
if (selectedPlacement?.id === placementId) {
@ -122,6 +136,7 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
setShowConfigPanel(false);
}
setHasUnsavedChanges(true);
setDeleteConfirmDialog({ open: false, placementId: null });
};
// 자재 드래그 (3D 캔버스에서, 로컬 상태에만 반영)
@ -257,6 +272,32 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
return !!(placement.material_name && placement.quantity && placement.unit);
};
// 레이아웃 편집 Dialog 열기
const handleEditLayout = () => {
setEditLayoutDialog({
open: true,
name: layout.name,
});
};
// 레이아웃 정보 저장
const handleSaveLayoutInfo = async () => {
try {
const response = await yardLayoutApi.updateLayout(layout.id, {
name: editLayoutDialog.name,
});
if (response.success) {
// 레이아웃 정보 업데이트
layout.name = editLayoutDialog.name;
setEditLayoutDialog({ open: false, name: "" });
}
} catch (error) {
console.error("레이아웃 정보 수정 실패:", error);
setError("레이아웃 정보 수정에 실패했습니다.");
}
};
return (
<div className="flex h-full flex-col bg-white">
{/* 상단 툴바 */}
@ -266,9 +307,14 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
<ArrowLeft className="mr-2 h-4 w-4" />
</Button>
<div>
<h2 className="text-lg font-semibold">{layout.name}</h2>
{layout.description && <p className="text-sm text-gray-500">{layout.description}</p>}
<div className="flex items-center gap-2">
<div>
<h2 className="text-lg font-semibold">{layout.name}</h2>
{layout.description && <p className="text-sm text-gray-500">{layout.description}</p>}
</div>
<Button variant="ghost" size="sm" onClick={handleEditLayout} className="h-8 w-8 p-0">
<Edit2 className="h-4 w-4 text-gray-500" />
</Button>
</div>
</div>
@ -442,6 +488,68 @@ export default function YardEditor({ layout, onBack }: YardEditorProps) {
</div>
</DialogContent>
</Dialog>
{/* 삭제 확인 Dialog */}
<Dialog
open={deleteConfirmDialog.open}
onOpenChange={(open) => !open && setDeleteConfirmDialog({ open: false, placementId: null })}
>
<DialogContent onPointerDown={(e) => e.stopPropagation()}>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<AlertCircle className="h-5 w-5 text-orange-600" />
</DialogTitle>
<DialogDescription className="pt-2">
?
<br />
<span className="font-semibold text-orange-600"> .</span>
</DialogDescription>
</DialogHeader>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setDeleteConfirmDialog({ open: false, placementId: null })}>
</Button>
<Button onClick={confirmDeletePlacement} className="bg-red-600 hover:bg-red-700">
</Button>
</div>
</DialogContent>
</Dialog>
{/* 레이아웃 편집 Dialog */}
<Dialog
open={editLayoutDialog.open}
onOpenChange={(open) => !open && setEditLayoutDialog({ open: false, name: "" })}
>
<DialogContent onPointerDown={(e) => e.stopPropagation()}>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Edit2 className="h-5 w-5 text-blue-600" />
</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="layout-name"> </Label>
<Input
id="layout-name"
value={editLayoutDialog.name}
onChange={(e) => setEditLayoutDialog((prev) => ({ ...prev, name: e.target.value }))}
placeholder="레이아웃 이름을 입력하세요"
/>
</div>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setEditLayoutDialog({ open: false, name: "" })}>
</Button>
<Button onClick={handleSaveLayoutInfo} disabled={!editLayoutDialog.name.trim()}>
</Button>
</div>
</DialogContent>
</Dialog>
</div>
);
}

View File

@ -278,11 +278,11 @@ export function DashboardViewer({
return (
<DashboardProvider>
{/* overflow-auto 제거 - 외부 페이지 스크롤 사용 */}
<div className="flex h-full items-start justify-center bg-gray-100 p-8">
{/* 스크롤 가능한 컨테이너 */}
<div className="flex min-h-screen items-start justify-center bg-gray-100 p-8">
{/* 고정 크기 캔버스 (편집 화면과 동일한 레이아웃) */}
<div
className="relative overflow-hidden rounded-lg"
className="relative rounded-lg"
style={{
width: `${canvasConfig.width}px`,
minHeight: `${canvasConfig.height}px`,