화면정보 수정 및 미리보기 기능

This commit is contained in:
kjs 2025-10-15 18:31:40 +09:00
parent c42853f261
commit 716cfcb2cf
10 changed files with 742 additions and 230 deletions

View File

@ -104,6 +104,30 @@ export const updateScreen = async (
}
};
// 화면 정보 수정 (메타데이터만)
export const updateScreenInfo = async (
req: AuthenticatedRequest,
res: Response
) => {
try {
const { id } = req.params;
const { companyCode } = req.user as any;
const { screenName, description, isActive } = req.body;
await screenManagementService.updateScreenInfo(
parseInt(id),
{ screenName, description, isActive },
companyCode
);
res.json({ success: true, message: "화면 정보가 수정되었습니다." });
} catch (error) {
console.error("화면 정보 수정 실패:", error);
res
.status(500)
.json({ success: false, message: "화면 정보 수정에 실패했습니다." });
}
};
// 화면 의존성 체크
export const checkScreenDependencies = async (
req: AuthenticatedRequest,

View File

@ -5,6 +5,7 @@ import {
getScreen,
createScreen,
updateScreen,
updateScreenInfo,
deleteScreen,
checkScreenDependencies,
restoreScreen,
@ -34,6 +35,7 @@ router.get("/screens", getScreens);
router.get("/screens/:id", getScreen);
router.post("/screens", createScreen);
router.put("/screens/:id", updateScreen);
router.put("/screens/:id/info", updateScreenInfo); // 화면 정보만 수정
router.get("/screens/:id/dependencies", checkScreenDependencies); // 의존성 체크
router.delete("/screens/:id", deleteScreen); // 휴지통으로 이동
router.post("/screens/:id/copy", copyScreen);

View File

@ -300,6 +300,51 @@ export class ScreenManagementService {
return this.mapToScreenDefinition(screen);
}
/**
* () -
*/
async updateScreenInfo(
screenId: number,
updateData: { screenName: string; description?: string; isActive: string },
userCompanyCode: string
): Promise<void> {
// 권한 확인
const existingResult = await query<{ company_code: string | null }>(
`SELECT company_code FROM screen_definitions WHERE screen_id = $1 LIMIT 1`,
[screenId]
);
if (existingResult.length === 0) {
throw new Error("화면을 찾을 수 없습니다.");
}
const existingScreen = existingResult[0];
if (
userCompanyCode !== "*" &&
existingScreen.company_code !== userCompanyCode
) {
throw new Error("이 화면을 수정할 권한이 없습니다.");
}
// 화면 정보 업데이트
await query(
`UPDATE screen_definitions
SET screen_name = $1,
description = $2,
is_active = $3,
updated_date = $4
WHERE screen_id = $5`,
[
updateData.screenName,
updateData.description || null,
updateData.isActive,
new Date(),
screenId,
]
);
}
/**
* -
*/

View File

@ -132,3 +132,16 @@
@apply bg-background text-foreground;
}
}
/* Dialog 오버레이 커스터마이징 - 어두운 배경 */
[data-radix-dialog-overlay],
.fixed.inset-0.z-50.bg-black {
background-color: rgba(0, 0, 0, 0.6) !important;
backdrop-filter: none !important;
}
/* DialogPrimitive.Overlay 클래스 오버라이드 */
.fixed.inset-0.z-50 {
background-color: rgba(0, 0, 0, 0.6) !important;
backdrop-filter: none !important;
}

View File

@ -80,6 +80,12 @@ export const InteractiveScreenViewer: React.FC<InteractiveScreenViewerProps> = (
showValidationPanel = false,
validationOptions = {},
}) => {
// component가 없으면 빈 div 반환
if (!component) {
console.warn("⚠️ InteractiveScreenViewer: component가 undefined입니다.");
return <div className="h-full w-full" />;
}
const { userName, user } = useAuth(); // 현재 로그인한 사용자명과 사용자 정보 가져오기
const [localFormData, setLocalFormData] = useState<Record<string, any>>({});
const [dateValues, setDateValues] = useState<Record<string, Date | undefined>>({});

View File

@ -26,11 +26,26 @@ import {
} from "@/components/ui/alert-dialog";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { MoreHorizontal, Edit, Trash2, Copy, Eye, Plus, Search, Palette, RotateCcw, Trash } from "lucide-react";
import { ScreenDefinition } from "@/types/screen";
import { screenApi } from "@/lib/api/screen";
import CreateScreenModal from "./CreateScreenModal";
import CopyScreenModal from "./CopyScreenModal";
import dynamic from "next/dynamic";
import { DynamicComponentRenderer } from "@/lib/registry/DynamicComponentRenderer";
import { DynamicWebTypeRenderer } from "@/lib/registry";
import { isFileComponent, getComponentWebType } from "@/lib/utils/componentTypeUtils";
// InteractiveScreenViewer를 동적으로 import (SSR 비활성화)
const InteractiveScreenViewer = dynamic(
() => import("./InteractiveScreenViewer").then((mod) => mod.InteractiveScreenViewer),
{
ssr: false,
loading: () => <div className="flex items-center justify-center p-8"> ...</div>,
},
);
interface ScreenListProps {
onScreenSelect: (screen: ScreenDefinition) => void;
@ -82,6 +97,22 @@ export default function ScreenList({ onScreenSelect, selectedScreen, onDesignScr
const [bulkDeleteDialogOpen, setBulkDeleteDialogOpen] = useState(false);
const [bulkDeleting, setBulkDeleting] = useState(false);
// 편집 관련 상태
const [editDialogOpen, setEditDialogOpen] = useState(false);
const [screenToEdit, setScreenToEdit] = useState<ScreenDefinition | null>(null);
const [editFormData, setEditFormData] = useState({
screenName: "",
description: "",
isActive: "Y",
});
// 미리보기 관련 상태
const [previewDialogOpen, setPreviewDialogOpen] = useState(false);
const [screenToPreview, setScreenToPreview] = useState<ScreenDefinition | null>(null);
const [previewLayout, setPreviewLayout] = useState<any>(null);
const [isLoadingPreview, setIsLoadingPreview] = useState(false);
const [previewFormData, setPreviewFormData] = useState<Record<string, any>>({});
// 화면 목록 로드 (실제 API)
useEffect(() => {
let abort = false;
@ -138,8 +169,42 @@ export default function ScreenList({ onScreenSelect, selectedScreen, onDesignScr
};
const handleEdit = (screen: ScreenDefinition) => {
// 편집 모달 열기
// console.log("편집:", screen);
setScreenToEdit(screen);
setEditFormData({
screenName: screen.screenName,
description: screen.description || "",
isActive: screen.isActive,
});
setEditDialogOpen(true);
};
const handleEditSave = async () => {
if (!screenToEdit) return;
try {
// 화면 정보 업데이트 API 호출
await screenApi.updateScreenInfo(screenToEdit.screenId, editFormData);
// 목록에서 해당 화면 정보 업데이트
setScreens((prev) =>
prev.map((s) =>
s.screenId === screenToEdit.screenId
? {
...s,
screenName: editFormData.screenName,
description: editFormData.description,
isActive: editFormData.isActive,
}
: s,
),
);
setEditDialogOpen(false);
setScreenToEdit(null);
} catch (error) {
console.error("화면 정보 업데이트 실패:", error);
alert("화면 정보 업데이트에 실패했습니다.");
}
};
const handleDelete = async (screen: ScreenDefinition) => {
@ -295,9 +360,22 @@ export default function ScreenList({ onScreenSelect, selectedScreen, onDesignScr
setIsCopyOpen(true);
};
const handleView = (screen: ScreenDefinition) => {
// 미리보기 모달 열기
// console.log("미리보기:", screen);
const handleView = async (screen: ScreenDefinition) => {
setScreenToPreview(screen);
setPreviewDialogOpen(true);
setIsLoadingPreview(true);
try {
// 화면 레이아웃 로드
const layoutData = await screenApi.getLayout(screen.screenId);
console.log("📊 미리보기 레이아웃 로드:", layoutData);
setPreviewLayout(layoutData);
} catch (error) {
console.error("❌ 레이아웃 로드 실패:", error);
toast.error("화면 레이아웃을 불러오는데 실패했습니다.");
} finally {
setIsLoadingPreview(false);
}
};
const handleCopySuccess = () => {
@ -329,11 +407,7 @@ export default function ScreenList({ onScreenSelect, selectedScreen, onDesignScr
/>
</div>
</div>
<Button
variant="default"
onClick={() => setIsCreateOpen(true)}
disabled={activeTab === "trash"}
>
<Button variant="default" onClick={() => setIsCreateOpen(true)} disabled={activeTab === "trash"}>
<Plus className="mr-2 h-4 w-4" />
</Button>
</div>
@ -386,7 +460,9 @@ export default function ScreenList({ onScreenSelect, selectedScreen, onDesignScr
</Badge>
</TableCell>
<TableCell>
<span className="font-mono text-sm text-muted-foreground">{screen.tableLabel || screen.tableName}</span>
<span className="text-muted-foreground font-mono text-sm">
{screen.tableLabel || screen.tableName}
</span>
</TableCell>
<TableCell>
<Badge
@ -399,7 +475,7 @@ export default function ScreenList({ onScreenSelect, selectedScreen, onDesignScr
</Badge>
</TableCell>
<TableCell>
<div className="text-sm text-muted-foreground">{screen.createdDate.toLocaleDateString()}</div>
<div className="text-muted-foreground text-sm">{screen.createdDate.toLocaleDateString()}</div>
<div className="text-xs text-gray-400">{screen.createdBy}</div>
</TableCell>
<TableCell>
@ -504,16 +580,18 @@ export default function ScreenList({ onScreenSelect, selectedScreen, onDesignScr
</Badge>
</TableCell>
<TableCell>
<span className="font-mono text-sm text-muted-foreground">{screen.tableLabel || screen.tableName}</span>
<span className="text-muted-foreground font-mono text-sm">
{screen.tableLabel || screen.tableName}
</span>
</TableCell>
<TableCell>
<div className="text-sm text-muted-foreground">{screen.deletedDate?.toLocaleDateString()}</div>
<div className="text-muted-foreground text-sm">{screen.deletedDate?.toLocaleDateString()}</div>
</TableCell>
<TableCell>
<div className="text-sm text-muted-foreground">{screen.deletedBy}</div>
<div className="text-muted-foreground text-sm">{screen.deletedBy}</div>
</TableCell>
<TableCell>
<div className="max-w-32 truncate text-sm text-muted-foreground" title={screen.deleteReason}>
<div className="text-muted-foreground max-w-32 truncate text-sm" title={screen.deleteReason}>
{screen.deleteReason || "-"}
</div>
</TableCell>
@ -563,7 +641,7 @@ export default function ScreenList({ onScreenSelect, selectedScreen, onDesignScr
>
</Button>
<span className="text-sm text-muted-foreground">
<span className="text-muted-foreground text-sm">
{currentPage} / {totalPages}
</span>
<Button
@ -643,7 +721,7 @@ export default function ScreenList({ onScreenSelect, selectedScreen, onDesignScr
<div className="flex items-center justify-between">
<div>
<div className="font-medium text-gray-900">{dep.screenName}</div>
<div className="text-sm text-muted-foreground"> : {dep.screenCode}</div>
<div className="text-muted-foreground text-sm"> : {dep.screenCode}</div>
</div>
<div className="text-right">
<div className="text-sm font-medium text-orange-600">
@ -737,16 +815,304 @@ export default function ScreenList({ onScreenSelect, selectedScreen, onDesignScr
>
</AlertDialogCancel>
<AlertDialogAction
onClick={confirmBulkDelete}
variant="destructive"
disabled={bulkDeleting}
>
<AlertDialogAction onClick={confirmBulkDelete} variant="destructive" disabled={bulkDeleting}>
{bulkDeleting ? "삭제 중..." : `${selectedScreenIds.length}개 영구 삭제`}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* 화면 편집 다이얼로그 */}
<Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle> </DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="edit-screenName"> *</Label>
<Input
id="edit-screenName"
value={editFormData.screenName}
onChange={(e) => setEditFormData({ ...editFormData, screenName: e.target.value })}
placeholder="화면명을 입력하세요"
/>
</div>
<div className="space-y-2">
<Label htmlFor="edit-description"></Label>
<Textarea
id="edit-description"
value={editFormData.description}
onChange={(e) => setEditFormData({ ...editFormData, description: e.target.value })}
placeholder="화면 설명을 입력하세요"
rows={3}
/>
</div>
<div className="space-y-2">
<Label htmlFor="edit-isActive"></Label>
<Select
value={editFormData.isActive}
onValueChange={(value) => setEditFormData({ ...editFormData, isActive: value })}
>
<SelectTrigger id="edit-isActive">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="Y"></SelectItem>
<SelectItem value="N"></SelectItem>
</SelectContent>
</Select>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setEditDialogOpen(false)}>
</Button>
<Button onClick={handleEditSave} disabled={!editFormData.screenName.trim()}>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 화면 미리보기 다이얼로그 */}
<Dialog open={previewDialogOpen} onOpenChange={setPreviewDialogOpen}>
<DialogContent className="data-[state=open]:animate-in data-[state=open]:fade-in data-[state=open]:zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out data-[state=closed]:zoom-out-95 h-[95vh] max-w-[95vw]">
<DialogHeader>
<DialogTitle> - {screenToPreview?.screenName}</DialogTitle>
</DialogHeader>
<div className="flex flex-1 items-center justify-center overflow-hidden bg-gradient-to-br from-gray-50 to-slate-100 p-6">
{isLoadingPreview ? (
<div className="flex h-full items-center justify-center">
<div className="text-center">
<div className="mb-2 text-lg font-medium"> ...</div>
<div className="text-sm text-gray-500"> .</div>
</div>
</div>
) : previewLayout && previewLayout.components ? (
(() => {
const screenWidth = previewLayout.screenResolution?.width || 1200;
const screenHeight = previewLayout.screenResolution?.height || 800;
// 모달 내부 가용 공간 계산 (헤더, 푸터, 패딩 제외)
const availableWidth = typeof window !== "undefined" ? window.innerWidth * 0.95 - 100 : 1800; // 95vw - 패딩
const availableHeight = typeof window !== "undefined" ? window.innerHeight * 0.95 - 200 : 800; // 95vh - 헤더/푸터
// 축소 비율 계산 (가로, 세로 중 더 작은 비율 사용)
const scaleX = availableWidth / screenWidth;
const scaleY = availableHeight / screenHeight;
const scale = Math.min(scaleX, scaleY, 1); // 최대 1 (확대하지 않음)
return (
<div
className="relative mx-auto rounded-xl border border-gray-200/60 bg-white shadow-lg shadow-gray-900/5"
style={{
width: `${screenWidth}px`,
height: `${screenHeight}px`,
transform: `scale(${scale})`,
transformOrigin: "center center",
}}
>
{/* 실제 화면과 동일한 렌더링 */}
{previewLayout.components
.filter((comp: any) => !comp.parentId) // 최상위 컴포넌트만 렌더링
.map((component: any) => {
if (!component || !component.id) return null;
// 그룹 컴포넌트인 경우 특별 처리
if (component.type === "group") {
const groupChildren = previewLayout.components.filter(
(child: any) => child.parentId === component.id,
);
return (
<div
key={component.id}
style={{
position: "absolute",
left: `${component.position?.x || 0}px`,
top: `${component.position?.y || 0}px`,
width: component.style?.width || `${component.size?.width || 200}px`,
height: component.style?.height || `${component.size?.height || 40}px`,
zIndex: component.position?.z || 1,
backgroundColor: component.backgroundColor || "rgba(59, 130, 246, 0.05)",
border: component.border || "1px solid rgba(59, 130, 246, 0.2)",
borderRadius: component.borderRadius || "12px",
padding: "20px",
boxShadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",
}}
>
{/* 그룹 제목 */}
{component.title && (
<div className="mb-3 inline-block rounded-lg bg-blue-50 px-3 py-1 text-sm font-semibold text-blue-700">
{component.title}
</div>
)}
{/* 그룹 내 자식 컴포넌트들 렌더링 */}
{groupChildren.map((child: any) => (
<div
key={child.id}
style={{
position: "absolute",
left: `${child.position.x}px`,
top: `${child.position.y}px`,
width: child.style?.width || `${child.size.width}px`,
height: child.style?.height || `${child.size.height}px`,
zIndex: child.position.z || 1,
}}
>
<InteractiveScreenViewer
component={child}
allComponents={previewLayout.components}
formData={previewFormData}
onFormDataChange={(fieldName, value) => {
setPreviewFormData((prev) => ({
...prev,
[fieldName]: value,
}));
}}
screenInfo={{
id: screenToPreview!.screenId,
tableName: screenToPreview?.tableName,
}}
/>
</div>
))}
</div>
);
}
// 라벨 표시 여부 계산
const templateTypes = ["datatable"];
const shouldShowLabel =
component.style?.labelDisplay !== false &&
(component.label || component.style?.labelText) &&
!templateTypes.includes(component.type);
const labelText = component.style?.labelText || component.label || "";
const labelStyle = {
fontSize: component.style?.labelFontSize || "14px",
color: component.style?.labelColor || "#212121",
fontWeight: component.style?.labelFontWeight || "500",
backgroundColor: component.style?.labelBackgroundColor || "transparent",
};
const labelMarginBottom = component.style?.labelMarginBottom || "4px";
// 일반 컴포넌트 렌더링
return (
<div key={component.id}>
{/* 라벨을 외부에 별도로 렌더링 */}
{shouldShowLabel && (
<div
style={{
position: "absolute",
left: `${component.position.x}px`,
top: `${component.position.y - 25}px`, // 컴포넌트 위쪽에 라벨 배치
zIndex: (component.position.z || 1) + 1,
...labelStyle,
}}
>
{labelText}
{component.required && <span style={{ color: "#f97316", marginLeft: "2px" }}>*</span>}
</div>
)}
{/* 실제 컴포넌트 */}
<div
style={{
position: "absolute",
left: `${component.position.x}px`,
top: `${component.position.y}px`,
width: component.style?.width || `${component.size.width}px`,
height: component.style?.height || `${component.size.height}px`,
zIndex: component.position.z || 1,
}}
>
{/* 위젯 컴포넌트가 아닌 경우 DynamicComponentRenderer 사용 */}
{component.type !== "widget" ? (
<DynamicComponentRenderer
component={{
...component,
style: {
...component.style,
labelDisplay: shouldShowLabel ? false : (component.style?.labelDisplay ?? true), // 상위에서 라벨을 표시했으면 컴포넌트 내부에서는 숨김
},
}}
isInteractive={true}
formData={previewFormData}
onFormDataChange={(fieldName, value) => {
setPreviewFormData((prev) => ({
...prev,
[fieldName]: value,
}));
}}
screenId={screenToPreview!.screenId}
tableName={screenToPreview?.tableName}
/>
) : (
<DynamicWebTypeRenderer
webType={(() => {
// 유틸리티 함수로 파일 컴포넌트 감지
if (isFileComponent(component)) {
return "file";
}
// 다른 컴포넌트는 유틸리티 함수로 webType 결정
return getComponentWebType(component) || "text";
})()}
config={component.webTypeConfig}
props={{
component: component,
value: previewFormData[component.columnName || component.id] || "",
onChange: (value: any) => {
const fieldName = component.columnName || component.id;
setPreviewFormData((prev) => ({
...prev,
[fieldName]: value,
}));
},
onFormDataChange: (fieldName, value) => {
setPreviewFormData((prev) => ({
...prev,
[fieldName]: value,
}));
},
isInteractive: true,
formData: previewFormData,
readonly: component.readonly,
required: component.required,
placeholder: component.placeholder,
className: "w-full h-full",
}}
/>
)}
</div>
</div>
);
})}
</div>
);
})()
) : (
<div className="flex h-full items-center justify-center">
<div className="text-center">
<div className="mb-2 text-lg font-medium text-gray-600"> </div>
<div className="text-sm text-gray-500"> .</div>
</div>
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setPreviewDialogOpen(false)}>
</Button>
<Button onClick={() => onDesignScreen(screenToPreview!)}>
<Palette className="mr-2 h-4 w-4" />
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

View File

@ -21,28 +21,30 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
const [isDragOver, setIsDragOver] = useState(false);
const [uploadQueue, setUploadQueue] = useState<File[]>([]);
// 전역 파일 상태 관리 함수들
const getGlobalFileState = (): {[key: string]: any[]} => {
if (typeof window !== 'undefined') {
const getGlobalFileState = (): { [key: string]: any[] } => {
if (typeof window !== "undefined") {
return (window as any).globalFileState || {};
}
return {};
};
const setGlobalFileState = (updater: (prev: {[key: string]: any[]}) => {[key: string]: any[]}) => {
if (typeof window !== 'undefined') {
const setGlobalFileState = (updater: (prev: { [key: string]: any[] }) => { [key: string]: any[] }) => {
if (typeof window !== "undefined") {
const currentState = getGlobalFileState();
const newState = updater(currentState);
(window as any).globalFileState = newState;
// console.log("🌐 FileUpload 전역 파일 상태 업데이트:", {
// componentId: component.id,
// newFileCount: newState[component.id]?.length || 0
// componentId: component.id,
// newFileCount: newState[component.id]?.length || 0
// });
// 강제 리렌더링을 위한 이벤트 발생
window.dispatchEvent(new CustomEvent('globalFileStateChanged', {
detail: { componentId: component.id, fileCount: newState[component.id]?.length || 0 }
}));
window.dispatchEvent(
new CustomEvent("globalFileStateChanged", {
detail: { componentId: component.id, fileCount: newState[component.id]?.length || 0 },
}),
);
}
};
@ -51,14 +53,14 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
const globalFiles = getGlobalFileState()[component.id] || [];
const componentFiles = component.uploadedFiles || [];
const finalFiles = globalFiles.length > 0 ? globalFiles : componentFiles;
// console.log("🚀 FileUpload 파일 상태 초기화:", {
// componentId: component.id,
// globalFiles: globalFiles.length,
// componentFiles: componentFiles.length,
// finalFiles: finalFiles.length
// componentId: component.id,
// globalFiles: globalFiles.length,
// componentFiles: componentFiles.length,
// finalFiles: finalFiles.length
// });
return finalFiles;
};
@ -71,23 +73,23 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
if (event.detail.componentId === component.id) {
const globalFiles = getGlobalFileState()[component.id] || [];
// console.log("🔄 FileUpload 전역 상태 변경 감지:", {
// componentId: component.id,
// newFileCount: globalFiles.length
// componentId: component.id,
// newFileCount: globalFiles.length
// });
setLocalUploadedFiles(globalFiles);
}
};
if (typeof window !== 'undefined') {
window.addEventListener('globalFileStateChanged', handleGlobalFileStateChange as EventListener);
if (typeof window !== "undefined") {
window.addEventListener("globalFileStateChanged", handleGlobalFileStateChange as EventListener);
return () => {
window.removeEventListener('globalFileStateChanged', handleGlobalFileStateChange as EventListener);
window.removeEventListener("globalFileStateChanged", handleGlobalFileStateChange as EventListener);
};
}
}, [component.id]);
const { fileConfig } = component;
const { fileConfig = {} } = component;
const { user: authUser, isLoading, isLoggedIn } = useAuth(); // 인증 상태도 함께 가져오기
// props로 받은 userInfo를 우선 사용, 없으면 useAuth에서 가져온 user 사용
@ -102,16 +104,16 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
// 사용자 정보 디버깅
useEffect(() => {
// console.log("👤 File 컴포넌트 인증 상태 및 사용자 정보:", {
// isLoading,
// isLoggedIn,
// hasUser: !!user,
// user: user,
// userId: user?.userId,
// company_code: user?.company_code,
// companyCode: user?.companyCode,
// userType: typeof user,
// userKeys: user ? Object.keys(user) : "no user",
// userValues: user ? Object.entries(user) : "no user",
// isLoading,
// isLoggedIn,
// hasUser: !!user,
// user: user,
// userId: user?.userId,
// company_code: user?.company_code,
// companyCode: user?.companyCode,
// userType: typeof user,
// userKeys: user ? Object.keys(user) : "no user",
// userValues: user ? Object.entries(user) : "no user",
// });
// 사용자 정보가 유효하면 initialUser와 userRef 업데이트
@ -124,18 +126,18 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
// 회사 관련 필드들 확인
if (user) {
// console.log("🔍 회사 관련 필드 검색:", {
// company_code: user.company_code,
// companyCode: user.companyCode,
// company: user.company,
// deptCode: user.deptCode,
// partnerCd: user.partnerCd,
// 모든 필드에서 company 관련된 것들 찾기
// allFields: Object.keys(user).filter(
// (key) =>
// key.toLowerCase().includes("company") ||
// key.toLowerCase().includes("corp") ||
// key.toLowerCase().includes("code"),
// ),
// company_code: user.company_code,
// companyCode: user.companyCode,
// company: user.company,
// deptCode: user.deptCode,
// partnerCd: user.partnerCd,
// 모든 필드에서 company 관련된 것들 찾기
// allFields: Object.keys(user).filter(
// (key) =>
// key.toLowerCase().includes("company") ||
// key.toLowerCase().includes("corp") ||
// key.toLowerCase().includes("code"),
// ),
// });
} else {
// console.warn("⚠️ 사용자 정보가 없습니다. 인증 상태 확인 필요");
@ -145,8 +147,8 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
// 컴포넌트 props가 변경될 때 로컬 상태 동기화
useEffect(() => {
// console.log("🔄 File 컴포넌트 props 변경:", {
// propsUploadedFiles: component.uploadedFiles?.length || 0,
// localUploadedFiles: localUploadedFiles.length,
// propsUploadedFiles: component.uploadedFiles?.length || 0,
// localUploadedFiles: localUploadedFiles.length,
// });
setLocalUploadedFiles(component.uploadedFiles || []);
}, [component.uploadedFiles]);
@ -177,9 +179,9 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
const fileName = file.name.toLowerCase();
// console.log("🔍 파일 타입 검증:", {
// fileName: file.name,
// fileType: file.type,
// acceptRules: fileConfig.accept,
// fileName: file.name,
// fileType: file.type,
// acceptRules: fileConfig.accept,
// });
const result = fileConfig.accept.some((accept) => {
@ -225,11 +227,11 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
const errors: string[] = [];
// console.log("🔍 파일 검증 시작:", {
// totalFiles: fileArray.length,
// currentUploadedCount: uploadedFiles.length,
// maxFiles: fileConfig.maxFiles,
// maxSize: fileConfig.maxSize,
// allowedTypes: fileConfig.accept,
// totalFiles: fileArray.length,
// currentUploadedCount: uploadedFiles.length,
// maxFiles: fileConfig.maxFiles,
// maxSize: fileConfig.maxSize,
// allowedTypes: fileConfig.accept,
// });
// 파일 검증
@ -270,23 +272,23 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
// 유효한 파일들을 업로드 큐에 추가
if (validFiles.length > 0) {
// console.log(
// "✅ 유효한 파일들 업로드 큐에 추가:",
// validFiles.map((f) => f.name),
// "✅ 유효한 파일들 업로드 큐에 추가:",
// validFiles.map((f) => f.name),
// );
setUploadQueue((prev) => [...prev, ...validFiles]);
if (fileConfig.autoUpload) {
// console.log("🚀 자동 업로드 시작:", {
// autoUpload: fileConfig.autoUpload,
// filesCount: validFiles.length,
// fileNames: validFiles.map((f) => f.name),
// autoUpload: fileConfig.autoUpload,
// filesCount: validFiles.length,
// fileNames: validFiles.map((f) => f.name),
// });
// 자동 업로드 실행
validFiles.forEach(uploadFile);
} else {
// console.log("⏸️ 자동 업로드 비활성화:", {
// autoUpload: fileConfig.autoUpload,
// filesCount: validFiles.length,
// autoUpload: fileConfig.autoUpload,
// filesCount: validFiles.length,
// });
}
} else {
@ -312,18 +314,18 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
// 실시간 사용자 정보 디버깅
// console.log("🔍 FileUpload - uploadFile ref를 통한 실시간 상태:", {
// hasCurrentUser: !!currentUser,
// currentUser: currentUser
// ? {
// userId: currentUser.userId,
// companyCode: currentUser.companyCode,
// company_code: currentUser.company_code,
// }
// : null,
// 기존 상태와 비교
// originalUser: user,
// originalInitialUser: initialUser,
// refExists: !!userRef.current,
// hasCurrentUser: !!currentUser,
// currentUser: currentUser
// ? {
// userId: currentUser.userId,
// companyCode: currentUser.companyCode,
// company_code: currentUser.company_code,
// }
// : null,
// 기존 상태와 비교
// originalUser: user,
// originalInitialUser: initialUser,
// refExists: !!userRef.current,
// });
// 사용자 정보가 로드되지 않은 경우 잠시 대기
@ -351,15 +353,15 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
// console.log("✅ 회사코드 추가:", companyCode);
} else {
// console.warn("⚠️ 회사코드가 없음, DEFAULT 사용. 사용자 정보:", {
// user: user,
// initialUser: initialUser,
// effectiveUser: effectiveUser,
// companyCode: effectiveUser?.companyCode,
// company_code: effectiveUser?.company_code,
// deptCode: effectiveUser?.deptCode,
// isLoading,
// isLoggedIn,
// allUserKeys: effectiveUser ? Object.keys(effectiveUser) : "no user",
// user: user,
// initialUser: initialUser,
// effectiveUser: effectiveUser,
// companyCode: effectiveUser?.companyCode,
// company_code: effectiveUser?.company_code,
// deptCode: effectiveUser?.deptCode,
// isLoading,
// isLoggedIn,
// allUserKeys: effectiveUser ? Object.keys(effectiveUser) : "no user",
// });
formData.append("companyCode", "DEFAULT");
}
@ -499,28 +501,28 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
setLocalUploadedFiles(updatedFiles);
// 전역 상태 업데이트
setGlobalFileState(prev => ({
setGlobalFileState((prev) => ({
...prev,
[component.id]: updatedFiles
[component.id]: updatedFiles,
}));
// RealtimePreview 동기화를 위한 추가 이벤트 발생
if (typeof window !== 'undefined') {
if (typeof window !== "undefined") {
const eventDetail = {
componentId: component.id,
files: updatedFiles,
fileCount: updatedFiles.length,
action: 'upload',
timestamp: Date.now()
action: "upload",
timestamp: Date.now(),
};
// console.log("🚀 FileUpload 위젯 이벤트 발생:", eventDetail);
const event = new CustomEvent('globalFileStateChanged', {
detail: eventDetail
const event = new CustomEvent("globalFileStateChanged", {
detail: eventDetail,
});
window.dispatchEvent(event);
// console.log("✅ FileUpload globalFileStateChanged 이벤트 발생 완료");
}
@ -540,19 +542,19 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
setUploadQueue((prev) => prev.filter((f) => f !== file));
} catch (error) {
// console.error("❌ 파일 업로드 실패:", {
// error,
// errorMessage: error instanceof Error ? error.message : "알 수 없는 오류",
// errorStack: error instanceof Error ? error.stack : undefined,
// user: user ? { userId: user.userId, companyCode: user.companyCode, hasUser: true } : "no user",
// authState: { isLoading, isLoggedIn },
// error,
// errorMessage: error instanceof Error ? error.message : "알 수 없는 오류",
// errorStack: error instanceof Error ? error.stack : undefined,
// user: user ? { userId: user.userId, companyCode: user.companyCode, hasUser: true } : "no user",
// authState: { isLoading, isLoggedIn },
// });
// API 응답 에러인 경우 상세 정보 출력
if ((error as any)?.response) {
// console.error("📡 API 응답 에러:", {
// status: (error as any).response.status,
// statusText: (error as any).response.statusText,
// data: (error as any).response.data,
// status: (error as any).response.status,
// statusText: (error as any).response.statusText,
// data: (error as any).response.data,
// });
}
@ -598,50 +600,54 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
setLocalUploadedFiles(filteredFiles);
// 전역 상태 업데이트
setGlobalFileState(prev => ({
setGlobalFileState((prev) => ({
...prev,
[component.id]: filteredFiles
[component.id]: filteredFiles,
}));
// 🎯 화면설계 모드와 동기화를 위한 전역 이벤트 발생
if (typeof window !== 'undefined') {
if (typeof window !== "undefined") {
try {
const eventDetail = {
componentId: component.id,
files: filteredFiles,
fileCount: filteredFiles.length,
action: 'delete',
action: "delete",
timestamp: Date.now(),
source: 'realScreen' // 실제 화면에서 온 이벤트임을 표시
source: "realScreen", // 실제 화면에서 온 이벤트임을 표시
};
// console.log("🚀🚀🚀 FileUpload 위젯 삭제 이벤트 발생:", eventDetail);
const event = new CustomEvent('globalFileStateChanged', {
detail: eventDetail
const event = new CustomEvent("globalFileStateChanged", {
detail: eventDetail,
});
window.dispatchEvent(event);
// console.log("✅✅✅ FileUpload 위젯 → 화면설계 모드 동기화 이벤트 발생 완료");
// 추가 지연 이벤트들
setTimeout(() => {
try {
// console.log("🔄 FileUpload 위젯 추가 삭제 이벤트 발생 (지연 100ms)");
window.dispatchEvent(new CustomEvent('globalFileStateChanged', {
detail: { ...eventDetail, delayed: true }
}));
window.dispatchEvent(
new CustomEvent("globalFileStateChanged", {
detail: { ...eventDetail, delayed: true },
}),
);
} catch (error) {
// console.warn("FileUpload 지연 이벤트 발생 실패:", error);
}
}, 100);
setTimeout(() => {
try {
// console.log("🔄 FileUpload 위젯 추가 삭제 이벤트 발생 (지연 300ms)");
window.dispatchEvent(new CustomEvent('globalFileStateChanged', {
detail: { ...eventDetail, delayed: true, attempt: 2 }
}));
window.dispatchEvent(
new CustomEvent("globalFileStateChanged", {
detail: { ...eventDetail, delayed: true, attempt: 2 },
}),
);
} catch (error) {
// console.warn("FileUpload 지연 이벤트 발생 실패:", error);
}
@ -704,8 +710,8 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
{/* 드래그 앤 드롭 영역 */}
<div
className={`group relative rounded-2xl border-2 border-dashed p-10 text-center transition-all duration-300 ${
isDragOver
? "border-primary bg-gradient-to-br from-blue-100/90 to-indigo-100/80 shadow-xl shadow-blue-500/20 scale-105"
isDragOver
? "border-primary scale-105 bg-gradient-to-br from-blue-100/90 to-indigo-100/80 shadow-xl shadow-blue-500/20"
: "border-gray-300/60 bg-gradient-to-br from-gray-50/80 to-blue-50/40 hover:border-blue-400/80 hover:bg-gradient-to-br hover:from-blue-50/90 hover:to-indigo-50/60 hover:shadow-lg hover:shadow-blue-500/10"
}`}
onDragOver={handleDragOver}
@ -713,59 +719,61 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
onDrop={handleDrop}
>
<div className="relative">
<Upload className={`mx-auto mb-4 h-16 w-16 transition-all duration-300 ${
isDragOver
? "text-blue-500 scale-110"
: "text-gray-400 group-hover:text-blue-500 group-hover:scale-105"
}`} />
<Upload
className={`mx-auto mb-4 h-16 w-16 transition-all duration-300 ${
isDragOver ? "scale-110 text-blue-500" : "text-gray-400 group-hover:scale-105 group-hover:text-blue-500"
}`}
/>
<div className="absolute inset-0 flex items-center justify-center">
<div className={`h-20 w-20 rounded-full transition-all duration-300 ${
isDragOver
? "bg-blue-200/80 scale-110"
: "bg-primary/20/50 opacity-0 group-hover:opacity-100 group-hover:scale-110"
}`}></div>
<div
className={`h-20 w-20 rounded-full transition-all duration-300 ${
isDragOver
? "scale-110 bg-blue-200/80"
: "bg-primary/20/50 opacity-0 group-hover:scale-110 group-hover:opacity-100"
}`}
></div>
</div>
</div>
<p className={`mb-2 text-xl font-semibold transition-colors duration-300 ${
isDragOver
? "text-primary"
: "text-gray-700 group-hover:text-primary"
}`}>
<p
className={`mb-2 text-xl font-semibold transition-colors duration-300 ${
isDragOver ? "text-primary" : "group-hover:text-primary text-gray-700"
}`}
>
{fileConfig.dragDropText || "파일을 드래그하여 업로드하세요"}
</p>
<p className={`mb-4 text-sm transition-colors duration-300 ${
isDragOver
? "text-blue-500"
: "text-gray-500 group-hover:text-blue-500"
}`}>
<p
className={`mb-4 text-sm transition-colors duration-300 ${
isDragOver ? "text-blue-500" : "text-gray-500 group-hover:text-blue-500"
}`}
>
</p>
<Button
variant="outline"
onClick={handleFileInputClick}
<Button
variant="outline"
onClick={handleFileInputClick}
className={`mb-4 rounded-xl border-2 transition-all duration-200 ${
isDragOver
? "border-blue-400 bg-accent text-primary shadow-md"
: "border-gray-300/60 hover:border-blue-400/60 hover:bg-accent/50 hover:shadow-sm"
isDragOver
? "bg-accent text-primary border-blue-400 shadow-md"
: "hover:bg-accent/50 border-gray-300/60 hover:border-blue-400/60 hover:shadow-sm"
}`}
>
<Upload className="mr-2 h-4 w-4" />
{fileConfig.uploadButtonText || "파일 선택"}
{fileConfig?.uploadButtonText || "파일 선택"}
</Button>
<div className="text-xs text-gray-500">
<p> : {fileConfig.accept.join(", ")}</p>
<p> : {(fileConfig?.accept || ["*/*"]).join(", ")}</p>
<p>
: {fileConfig.maxSize}MB | : {fileConfig.maxFiles}
: {fileConfig?.maxSize || 10}MB | : {fileConfig?.maxFiles || 5}
</p>
</div>
<input
ref={fileInputRef}
type="file"
multiple={fileConfig.multiple}
accept={fileConfig.accept.join(",")}
multiple={fileConfig?.multiple !== false}
accept={(fileConfig?.accept || ["*/*"]).join(",")}
onChange={(e) => handleFileSelect(e.target.files)}
className="hidden"
/>
@ -774,44 +782,51 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
{/* 업로드된 파일 목록 */}
{uploadedFiles.length > 0 && (
<div className="space-y-4">
<div className="flex items-center justify-between rounded-xl bg-gradient-to-r from-blue-50/80 to-indigo-50/60 px-4 py-3 border border-primary/20/40">
<div className="border-primary/20/40 flex items-center justify-between rounded-xl border bg-gradient-to-r from-blue-50/80 to-indigo-50/60 px-4 py-3">
<div className="flex items-center space-x-3">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/20">
<File className="h-4 w-4 text-primary" />
<div className="bg-primary/20 flex h-8 w-8 items-center justify-center rounded-full">
<File className="text-primary h-4 w-4" />
</div>
<div>
<h4 className="text-lg font-semibold text-gray-800">
({uploadedFiles.length}/{fileConfig.maxFiles})
</h4>
<p className="text-sm text-muted-foreground">
<p className="text-muted-foreground text-sm">
{formatFileSize(uploadedFiles.reduce((sum, file) => sum + file.fileSize, 0))}
</p>
</div>
</div>
<Button variant="outline" size="sm" className="rounded-lg border-primary/20/60 bg-white/80 hover:bg-accent/80">
<Button
variant="outline"
size="sm"
className="border-primary/20/60 hover:bg-accent/80 rounded-lg bg-white/80"
>
</Button>
</div>
<div className="space-y-3">
{uploadedFiles.map((fileInfo) => (
<div key={fileInfo.objid} className="group relative flex items-center justify-between rounded-xl border border-gray-200/60 bg-white/90 p-4 shadow-sm transition-all duration-200 hover:shadow-md hover:border-blue-300/60 hover:bg-accent/30">
<div
key={fileInfo.objid}
className="group hover:bg-accent/30 relative flex items-center justify-between rounded-xl border border-gray-200/60 bg-white/90 p-4 shadow-sm transition-all duration-200 hover:border-blue-300/60 hover:shadow-md"
>
<div className="flex flex-1 items-center space-x-4">
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-gray-50 to-gray-100/80 shadow-sm">
{getFileIcon(fileInfo.fileExt)}
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-base font-semibold text-gray-800 group-hover:text-primary transition-colors duration-200">
<p className="group-hover:text-primary truncate text-base font-semibold text-gray-800 transition-colors duration-200">
{fileInfo.realFileName}
</p>
<div className="flex items-center space-x-3 text-sm text-gray-500 mt-1">
<div className="mt-1 flex items-center space-x-3 text-sm text-gray-500">
<span className="flex items-center space-x-1">
<div className="h-1.5 w-1.5 rounded-full bg-blue-400"></div>
<span className="font-medium">{formatFileSize(fileInfo.fileSize)}</span>
</span>
<span className="flex items-center space-x-1">
<div className="h-1.5 w-1.5 rounded-full bg-gray-400"></div>
<span className="px-2 py-1 rounded-md bg-gray-100 text-xs font-medium">
<span className="rounded-md bg-gray-100 px-2 py-1 text-xs font-medium">
{fileInfo.fileExt.toUpperCase()}
</span>
</span>
@ -835,7 +850,7 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
{/* 에러 메시지 */}
{fileInfo.hasError && (
<div className="mt-2 flex items-center space-x-2 rounded-md bg-destructive/10 p-2 text-sm text-red-700">
<div className="bg-destructive/10 mt-2 flex items-center space-x-2 rounded-md p-2 text-sm text-red-700">
<AlertCircle className="h-4 w-4 flex-shrink-0" />
<span>{fileInfo.errorMessage}</span>
</div>
@ -846,9 +861,9 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
<div className="flex items-center space-x-2">
{/* 상태 표시 */}
{fileInfo.isUploading && (
<div className="flex items-center space-x-2 rounded-lg bg-accent px-3 py-2">
<div className="bg-accent flex items-center space-x-2 rounded-lg px-3 py-2">
<Loader2 className="h-4 w-4 animate-spin text-blue-500" />
<span className="text-xs font-medium text-primary"> ...</span>
<span className="text-primary text-xs font-medium"> ...</span>
</div>
)}
{fileInfo.status === "ACTIVE" && (
@ -858,9 +873,9 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
</div>
)}
{fileInfo.hasError && (
<div className="flex items-center space-x-2 rounded-lg bg-destructive/10 px-3 py-2">
<div className="bg-destructive/10 flex items-center space-x-2 rounded-lg px-3 py-2">
<AlertCircle className="h-4 w-4 text-red-500" />
<span className="text-xs font-medium text-destructive"></span>
<span className="text-destructive text-xs font-medium"></span>
</div>
)}
@ -868,21 +883,21 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
{!fileInfo.isUploading && !fileInfo.hasError && (
<div className="flex items-center space-x-1">
{fileConfig.showPreview && (
<Button
variant="ghost"
size="sm"
onClick={() => previewFile(fileInfo)}
className="h-9 w-9 rounded-lg hover:bg-accent hover:text-primary transition-all duration-200"
<Button
variant="ghost"
size="sm"
onClick={() => previewFile(fileInfo)}
className="hover:bg-accent hover:text-primary h-9 w-9 rounded-lg transition-all duration-200"
>
<Eye className="h-4 w-4" />
</Button>
)}
<Button
variant="ghost"
size="sm"
onClick={() => previewFile(fileInfo)}
className="h-9 w-9 rounded-lg hover:bg-green-50 hover:text-green-600 transition-all duration-200"
<Button
variant="ghost"
size="sm"
onClick={() => previewFile(fileInfo)}
className="h-9 w-9 rounded-lg transition-all duration-200 hover:bg-green-50 hover:text-green-600"
>
<Download className="h-4 w-4" />
</Button>
@ -891,7 +906,7 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
variant="ghost"
size="sm"
onClick={() => deleteFile(fileInfo)}
className="h-9 w-9 rounded-lg text-red-500 hover:bg-destructive/10 hover:text-red-700 transition-all duration-200"
className="hover:bg-destructive/10 h-9 w-9 rounded-lg text-red-500 transition-all duration-200 hover:text-red-700"
>
<X className="h-4 w-4" />
</Button>
@ -905,7 +920,7 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
)}
{/* 문서 타입 정보 */}
<div className="flex items-center justify-center space-x-2 rounded-xl bg-gradient-to-r from-amber-50/80 to-orange-50/60 border border-amber-200/40 px-4 py-3">
<div className="flex items-center justify-center space-x-2 rounded-xl border border-amber-200/40 bg-gradient-to-r from-amber-50/80 to-orange-50/60 px-4 py-3">
<div className="flex items-center space-x-2">
<div className="flex h-6 w-6 items-center justify-center rounded-full bg-amber-100">
<File className="h-3 w-3 text-amber-600" />
@ -914,7 +929,7 @@ export function FileUpload({ component, onUpdateComponent, onFileUpload, userInf
"전체 자세히보기"
</span>
</div>
<Badge variant="outline" className="bg-white/80 border-amber-200/60 text-amber-700">
<Badge variant="outline" className="border-amber-200/60 bg-white/80 text-amber-700">
{fileConfig.docTypeName}
</Badge>
</div>

View File

@ -21,7 +21,7 @@ const DialogOverlay = React.forwardRef<
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"bg-background/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-[999] backdrop-blur-sm",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-[999] bg-black/60",
className,
)}
{...props}

View File

@ -64,6 +64,14 @@ export const screenApi = {
return response.data.data;
},
// 화면 정보 수정 (메타데이터만)
updateScreenInfo: async (
screenId: number,
data: { screenName: string; description?: string; isActive: string },
): Promise<void> => {
await apiClient.put(`/screen-management/screens/${screenId}/info`, data);
},
// 화면 의존성 체크
checkScreenDependencies: async (
screenId: number,

View File

@ -7,48 +7,59 @@ import { ComponentData } from "@/types/screen";
/**
*
*
*
* :
* - 레거시: type="file"
* - 레거시: type="widget" + widgetType="file"
* - 레거시: type="widget" + widgetType="file"
* - 신규: type="component" + widgetType="file"
* - 신규: type="component" + componentType="file-upload"
* - 신규: type="component" + componentConfig.webType="file"
*/
export const isFileComponent = (component: ComponentData): boolean => {
return component.type === "file" ||
(component.type === "widget" && (component as any).widgetType === "file") ||
(component.type === "component" &&
((component as any).widgetType === "file" || // ✅ ScreenDesigner에서 설정됨
(component as any).componentType === "file-upload" || // ✅ ComponentRegistry ID
(component as any).componentConfig?.webType === "file")); // ✅ componentConfig 내부
if (!component || !component.type) return false;
return (
component.type === "file" ||
(component.type === "widget" && (component as any).widgetType === "file") ||
(component.type === "component" &&
((component as any).widgetType === "file" || // ✅ ScreenDesigner에서 설정됨
(component as any).componentType === "file-upload" || // ✅ ComponentRegistry ID
(component as any).componentConfig?.webType === "file"))
); // ✅ componentConfig 내부
};
/**
*
*/
export const isButtonComponent = (component: ComponentData): boolean => {
return component.type === "button" ||
(component.type === "widget" && (component as any).widgetType === "button") ||
(component.type === "component" &&
((component as any).webType === "button" ||
(component as any).componentType === "button"));
if (!component || !component.type) return false;
return (
component.type === "button" ||
(component.type === "widget" && (component as any).widgetType === "button") ||
(component.type === "component" &&
((component as any).webType === "button" || (component as any).componentType === "button"))
);
};
/**
*
*/
export const isDataTableComponent = (component: ComponentData): boolean => {
return component.type === "datatable" ||
(component.type === "component" &&
((component as any).componentType === "datatable" ||
(component as any).componentType === "data-table"));
if (!component || !component.type) return false;
return (
component.type === "datatable" ||
(component.type === "component" &&
((component as any).componentType === "datatable" || (component as any).componentType === "data-table"))
);
};
/**
*
*/
export const isWidgetComponent = (component: ComponentData): boolean => {
if (!component || !component.type) return false;
return component.type === "widget";
};
@ -56,17 +67,19 @@ export const isWidgetComponent = (component: ComponentData): boolean => {
*
*/
export const getComponentWebType = (component: ComponentData): string | undefined => {
if (!component || !component.type) return undefined;
// 파일 컴포넌트는 무조건 "file" 웹타입 반환
if (isFileComponent(component)) {
console.log(`🎯 파일 컴포넌트 감지 → webType: "file" 반환`, {
componentId: component.id,
componentType: component.type,
widgetType: (component as any).widgetType,
componentConfig: (component as any).componentConfig
componentConfig: (component as any).componentConfig,
});
return "file";
}
if (component.type === "widget") {
return (component as any).widgetType;
}
@ -80,6 +93,8 @@ export const getComponentWebType = (component: ComponentData): string | undefine
* ( )
*/
export const getComponentType = (component: ComponentData): string => {
if (!component || !component.type) return "unknown";
if (component.type === "component") {
return (component as any).componentType || (component as any).webType || "unknown";
}
@ -90,10 +105,26 @@ export const getComponentType = (component: ComponentData): string => {
*
*/
export const isInputComponent = (component: ComponentData): boolean => {
const inputTypes = ["text", "number", "email", "password", "tel", "url", "search",
"textarea", "select", "checkbox", "radio", "date", "time",
"datetime-local", "file", "code", "entity"];
const inputTypes = [
"text",
"number",
"email",
"password",
"tel",
"url",
"search",
"textarea",
"select",
"checkbox",
"radio",
"date",
"time",
"datetime-local",
"file",
"code",
"entity",
];
const webType = getComponentWebType(component);
return webType ? inputTypes.includes(webType) : false;
};
@ -103,7 +134,7 @@ export const isInputComponent = (component: ComponentData): boolean => {
*/
export const isDisplayComponent = (component: ComponentData): boolean => {
const displayTypes = ["label", "text", "image", "video", "chart", "table", "datatable"];
const webType = getComponentWebType(component);
return webType ? displayTypes.includes(webType) : false;
};
@ -112,12 +143,14 @@ export const isDisplayComponent = (component: ComponentData): boolean => {
*
*/
export const getComponentFieldName = (component: ComponentData): string => {
return (component as any).columnName || component.id;
if (!component) return "";
return (component as any).columnName || component.id || "";
};
/**
*
*/
export const getComponentLabel = (component: ComponentData): string => {
return (component as any).label || (component as any).title || component.id;
if (!component) return "";
return (component as any).label || (component as any).title || component.id || "";
};