Merge branch 'refs/heads/main' into feature/0612_sentry_fr_merge

# Conflicts:
#	apps/as/next.config.ts
This commit is contained in:
2026-09-11 10:33:13 +09:00
904 changed files with 75682 additions and 20891 deletions
@@ -31,6 +31,7 @@
"@radix-ui/react-scroll-area": "^1.2.3",
"@radix-ui/react-select": "^2.1.6",
"@radix-ui/react-slot": "^1.1.2",
"@tanstack/react-table": "^8.21.2",
"axios": "1.8.1",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -91,4 +92,4 @@
]
},
"packageManager": "pnpm@8.15.5+sha1.a58c038faac410c947dbdb93eb30994037d0fce2"
}
}
@@ -1 +1,2 @@
export * from "./ui";
export * from "./lib/user-message";
@@ -0,0 +1,27 @@
export type BusinessUserMessageHandler = (message: string) => void;
let userMessageHandler: BusinessUserMessageHandler | undefined;
/** 사용하는 앱이 공통 비즈니스 컴포넌트의 사용자 메시지 표시 방식을 연결한다. */
export const setBusinessUserMessageHandler = (
handler: BusinessUserMessageHandler,
) => {
userMessageHandler = handler;
return () => {
if (userMessageHandler === handler) userMessageHandler = undefined;
};
};
/** 앱 핸들러가 연결되면 공통 UI를 사용하고, 미연결 앱은 기존 브라우저 알림을 유지한다. */
export const showBusinessUserMessage = (message: unknown) => {
const normalizedMessage = String(message ?? "").trim();
if (!normalizedMessage) return;
if (userMessageHandler) {
userMessageHandler(normalizedMessage);
return;
}
if (typeof window !== "undefined") window.alert(normalizedMessage);
};
@@ -225,7 +225,7 @@ export default function LineBarchart({
domain={[0, leftScale.max]}
ticks={leftScale.ticks}
orientation="left"
label={(props) => <CustomAxisText {...props} fieldText={yFieldText} position="left" />}
label={(props: any) => <CustomAxisText {...props} fieldText={yFieldText} position="left" />}
/>}
{/* 오른쪽 Y축: barVal */}
{yFieldText2 && <YAxis
@@ -237,7 +237,7 @@ export default function LineBarchart({
}
domain={[0, rightScale.max]}
ticks={rightScale.ticks}
label={(props) => <CustomAxisText {...props} fieldText={yFieldText2} position="right" />}
label={(props: any) => <CustomAxisText {...props} fieldText={yFieldText2} position="right" />}
reversed={true}
/>}
<Tooltip content={<CustomTooltip active={undefined} payload={undefined} label={undefined} />} />
@@ -254,7 +254,7 @@ export default function Linechart({
tickFormatter={(value) =>
typeof value === "number" ? value.toLocaleString() : value
}
label={(props) => <CustomAxisText {...props} fieldText={yFieldText} position="left" />}/>
label={(props: any) => <CustomAxisText {...props} fieldText={yFieldText} position="left" />}/>
<Tooltip content={<CustomTooltip />} />
{showLegend && <Legend content={CustomLegend as ContentType}/>}
{Object.keys(chartData).map((key) => {
@@ -13,58 +13,63 @@ import {
isEqual,
isFuture,
parse,
startOfMonth,
// startOfMonth,
startOfToday,
} from "date-fns";
import { ko } from "date-fns/locale";
function getStartOfCurrentMonth() {
return startOfMonth(startOfToday());
}
// function getStartOfCurrentMonth() {
// return startOfMonth(startOfToday());
// }
export type MonthPickerProps = {
currentMonth: Date;
onMonthChange: (
newMonth: Date | undefined,
shouldClosePopover?: boolean
shouldClosePopover?: boolean,
) => void;
startYear?: number;
yearReadOnly?: boolean;
enableMonth?: string[];
};
export function MonthPicker({ currentMonth, onMonthChange, startYear, yearReadOnly, enableMonth }: MonthPickerProps) {
export function MonthPicker({
currentMonth,
onMonthChange,
startYear,
yearReadOnly,
enableMonth,
}: MonthPickerProps) {
const today = startOfToday();
const currentYear = today.getFullYear();
const currentYear = today.getFullYear();
const yearFromProp = format(currentMonth, "yyyy");
const selectedYear = parseInt(yearFromProp);
const selectedYear = parseInt(yearFromProp);
// 현재 월의 시작 날짜
const fullYearStart = parse(yearFromProp, "yyyy", new Date());
const yearEnd =
selectedYear === currentYear ? today : endOfYear(fullYearStart);
// startYear가 없으면 기존과 동일하게 (현재년도 - 20년부터 현재년도까지)
// startYear가 있으면 해당 년도부터 현재년도까지, 내림차순으로 정렬
const yearRange = startYear
? Array.from({ length: currentYear - startYear + 1 }, (_, i) => currentYear - i)
const yearRange = startYear
? Array.from(
{ length: currentYear - startYear + 1 },
(_, i) => currentYear - i,
)
: Array.from({ length: 21 }, (_, i) => currentYear - 20 + i);
const months = eachMonthOfInterval({ start: fullYearStart, end: yearEnd });
const getMonthButtonClass = (month: Date) =>
cn(
"inline-flex h-9 w-16 items-center justify-center rounded-md p-0 text-sm font-normal ring-offset-white transition-colors hover:bg-slate-100 hover:text-slate-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 aria-selected:opacity-100 dark:ring-offset-slate-950 dark:hover:bg-slate-800 dark:hover:text-slate-50 dark:focus-visible:ring-slate-800",
"inline-flex h-9 w-16 items-center justify-center rounded-md p-0 text-sm font-normal text-foreground ring-offset-background transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 aria-selected:opacity-100",
isEqual(month, currentMonth) &&
"bg-slate-900 text-slate-50 hover:bg-slate-900 hover:text-slate-50 focus:bg-slate-900 focus:text-slate-50 dark:bg-slate-50 dark:text-slate-900 dark:hover:bg-slate-50 dark:hover:text-slate-900 dark:focus:bg-slate-50 dark:focus:text-slate-900",
"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
// !isEqual(month, currentMonth) &&
// isEqual(month, getStartOfCurrentMonth()) &&
// "bg-slate-100 text-slate-900 dark:bg-slate-800 dark:text-slate-50"
// "bg-accent text-accent-foreground"
);
return (
@@ -81,12 +86,12 @@ const selectedYear = parseInt(yearFromProp);
const newDate = new Date(
selectedYearNum,
currentMonth.getMonth(),
1
1,
);
onMonthChange(newDate, false);
}}
>
<SelectTrigger className="w-[140px] h-9 text-base">
<SelectTrigger className="h-9 w-[140px] text-base">
<SelectValue placeholder="년도" />
</SelectTrigger>
<SelectContent>
@@ -108,20 +113,26 @@ const selectedYear = parseInt(yearFromProp);
{months.map((month) => (
<div
key={month.toString()}
className="relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-slate-100 first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md dark:[&:has([aria-selected])]:bg-slate-800"
className="relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md"
role="presentation"
>
<button
name="month"
className={getMonthButtonClass(month)}
disabled={isFuture(month) || (enableMonth && !enableMonth?.includes(format(month, 'MMM', { locale: ko })))}
disabled={
isFuture(month) ||
(enableMonth &&
!enableMonth?.includes(
format(month, "MMM", { locale: ko }),
))
}
role="gridcell"
tabIndex={-1}
type="button"
onClick={() => onMonthChange(month, true)}
>
<time dateTime={format(month, "yyyy-MM-dd")}>
{format(month, 'MMM', { locale: ko })}
{format(month, "MMM", { locale: ko })}
</time>
</button>
</div>
@@ -1,83 +1,97 @@
// import type { sheetParameter } from '@/index';
import * as XlsxPopulate from '@xlsx/xlsx-populate';
import type { SheetParameter } from './index';
import type * as XlsxPopulateTypes from "@xlsx/xlsx-populate";
import type { SheetParameter } from "./index";
const loadXlsxPopulate = () => import("@xlsx/xlsx-populate");
const makeCellStyle = (styleQ: XlsxPopulateTypes.StyleQuery) => {
styleQ.fill({ type: "solid", color: { rgb: "9bc1e7" } });
styleQ.borderEach({ style: "thin", color: { rgb: "FFFFFF" } });
styleQ.wrapText(true);
// styleQ.fontColor({rgb:"FFFFFF"});
styleQ.fontSize(13);
styleQ.horizontalAlignment("center");
styleQ.verticalAlignment("center");
styleQ.bold(true);
};
const makeCellStyle =(styleQ: XlsxPopulate.StyleQuery )=>{
styleQ.fill({ type: "solid", color: {rgb:"9bc1e7"} });
styleQ.borderEach( { style: "thin", color: { rgb: "FFFFFF" } } );
styleQ.wrapText(true);
// styleQ.fontColor({rgb:"FFFFFF"});
styleQ.fontSize(13);
styleQ.horizontalAlignment("center");
styleQ.verticalAlignment("center");
styleQ.bold(true);
}
const makeExcelFile = async (
workbook: XlsxPopulateTypes.Workbook,
fileNm: string,
) => {
const outputData = await workbook.output("array-buffer");
const blob = new Blob([outputData], { type: "application/octet-stream" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = fileNm + ".xlsx";
link.click();
};
const makeExcelFile = async(workbook: XlsxPopulate.Workbook,fileNm:string)=>{
const outputData = await workbook.output("array-buffer");
const blob = new Blob([outputData], { type: "application/octet-stream" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = fileNm+".xlsx";
link.click();
export const excelStyle = async (
data: ArrayBuffer,
range: string = "A1:V3",
fileNm: string,
) => {
const XlsxPopulate = await loadXlsxPopulate();
const workbook = await XlsxPopulate.Workbook.fromData(data);
const rangeCells = workbook.activeSheet(0)?.sheet(0)?.range(range);
console.log(rangeCells);
rangeCells?.style((styleQ) => {
makeCellStyle(styleQ);
});
makeExcelFile(workbook, fileNm);
};
}
export const excelArrayStyle = async (
data: ArrayBuffer,
range: SheetParameter[],
fileNm: string,
) => {
const XlsxPopulate = await loadXlsxPopulate();
const workbook = await XlsxPopulate.Workbook.fromData(data);
if (range) {
range.forEach((item, index) => {
const rangeCells = workbook
.activeSheet(index)
?.sheet(index)
?.range(item.headerRange);
console.log(rangeCells);
rangeCells?.style((styleQ) => {
makeCellStyle(styleQ);
});
export const excelStyle = async (data: ArrayBuffer, range: string = "A1:V3", fileNm:string) => {
const workbook = await XlsxPopulate.Workbook.fromData(data);
const rangeCells = workbook.activeSheet(0)?.sheet(0)?.range(range);
console.log(rangeCells);
rangeCells?.style((styleQ)=>{
makeCellStyle(styleQ)
});
makeExcelFile(workbook, fileNm)
}
export const excelArrayStyle = async (data: ArrayBuffer, range: SheetParameter[], fileNm: string) => {
const workbook = await XlsxPopulate.Workbook.fromData(data);
if (range) {
range.forEach((item, index) => {
const rangeCells = workbook.activeSheet(index)?.sheet(index)?.range(item.headerRange);
console.log(rangeCells);
rangeCells?.style((styleQ) => {
makeCellStyle(styleQ)
});
// 모든 데이터 셀에 세로 가운데 정렬 적용
if (item.data && item.data.length > 0) {
const numCols = item.data[0]?.length || 0;
const numRows = item.data.length;
const lastColLetter = getExcelColumnLetter(numCols);
const dataRange = workbook.activeSheet(index)?.sheet(index)?.range(`A1:${lastColLetter}${numRows}`);
dataRange?.style((styleQ) => {
styleQ.verticalAlignment("center");
});
}
// 모든 데이터 셀에 세로 가운데 정렬 적용
if (item.data && item.data.length > 0) {
const numCols = item.data[0]?.length || 0;
const numRows = item.data.length;
const lastColLetter = getExcelColumnLetter(numCols);
const dataRange = workbook
.activeSheet(index)
?.sheet(index)
?.range(`A1:${lastColLetter}${numRows}`);
dataRange?.style((styleQ) => {
styleQ.verticalAlignment("center");
});
}
makeExcelFile(workbook, fileNm)
}
}
});
}
makeExcelFile(workbook, fileNm);
};
export const excelStyleWithKoreanHeaders = async (
data: ArrayBuffer,
range: string = "A1:V3",
data: ArrayBuffer,
range: string = "A1:V3",
fileNm: string,
headerMapping: { [key: string]: string },
sampleData: any,
mergeRanges?: string[]
mergeRanges?: string[],
) => {
const XlsxPopulate = await loadXlsxPopulate();
const workbook = await XlsxPopulate.Workbook.fromData(data);
const sheet = workbook.activeSheet();
if (!sheet) {
throw new Error('워크시트를 찾을 수 없습니다.');
throw new Error("워크시트를 찾을 수 없습니다.");
}
// 1. 영문 헤더를 한글로 교체
@@ -97,7 +111,7 @@ export const excelStyleWithKoreanHeaders = async (
// 3. 모든 데이터 셀에 세로 가운데 정렬 적용
const numCols = englishHeaders.length;
const numRows = sheet.usedRange()?.endCell()?.rowNumber() || 1;
if (numRows > 1) {
const lastColLetter = getExcelColumnLetter(numCols);
const dataRange = sheet.range(`A1:${lastColLetter}${numRows}`);
@@ -117,14 +131,12 @@ export const excelStyleWithKoreanHeaders = async (
await makeExcelFile(workbook, fileNm);
};
const getExcelColumnLetter = (colIndex: number): string => {
let letter = '';
while (colIndex > 0) {
const mod = (colIndex - 1) % 26;
letter = String.fromCharCode(65 + mod) + letter;
colIndex = Math.floor((colIndex - 1) / 26);
}
return letter;
};
let letter = "";
while (colIndex > 0) {
const mod = (colIndex - 1) % 26;
letter = String.fromCharCode(65 + mod) + letter;
colIndex = Math.floor((colIndex - 1) / 26);
}
return letter;
};
@@ -1,3 +1,5 @@
"use client";
import "./form-ui.css";
import React, { useCallback, useEffect, useState } from "react";
@@ -17,6 +17,9 @@ export * from "./search_input_select";
// export * from "./search_input_address";
export * from "./search_address";
export * from "./select";
export * from "./standard_data_table";
export * from "./standard_form";
export * from "./standard_popup";
export * from "./tab";
export * from "./table";
export * from "./table_div";
@@ -24,5 +27,5 @@ export * from "./title";
export * from "./sdmInsertForm";
export * from "./popover_ui";
export * from "./date_month_picker";
export * from "./date_picker_range"
export * from "./date_picker_range";
export * from "./map/GisOverlay";
@@ -13,6 +13,7 @@ const LoadingOverlay: React.FC<LoadingOverlayProps> = ({
if (!isLoading) return null;
return (
// 화면을 차단하는 로딩 오버레이는 배경 콘텐츠를 가리는 의미색이므로 반투명 검정을 유지한다.
<div
className={`fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 ${customZindex || "z-50"}`}
>
@@ -54,12 +54,23 @@ function Gis({
sinkholeLegendIconVisible = false,
setIsSearchModalOpen,
onCheckedLayersChange,
// 외부 업무 흐름에서 특정 시설물 레이어를 기존 체크 상태에 추가하도록 요청한다.
checkedLayerRequest = null,
searchBar: SearchBar,
// 화면별 상단 정렬과 인접 패널 회피를 위한 검색바 위치 전용 클래스다.
searchBarContainerClassName = "",
// sn 관망도처럼 베이스맵 선택지를 항상 노출하는 화면에서만 탭 형태를 사용한다.
alwaysVisibleMapTabs = false,
waterDepth: WaterDepth = null,
layerSettingView: LayerSettingView = null,
inlineLayerSettingView,
treeSectionClassName = "",
layerIconVisible,
layerLegendIconVisible,
// 목록·액션 아이콘이 지도 레이어 체크를 선행 조건으로 요구하는지 여부다.
layerIconRequiresChecked = true,
// 목록 액션의 기능은 유지하면서 텍스트를 목록 아이콘으로 표시할지 여부다.
layerActionIconOnly = false,
isPlaying = false,
setIsPlaying = () => { },
targetLayerTypes = [],
@@ -74,10 +85,14 @@ function Gis({
viewExtent,
viewMinZoom,
showZoomLevel = false,
toolBarIconSize,
zoomGuide,
showFloatingSearchButton = true,
treeTogglePosition = "center",
detachedTreeToggleButton = false,
showLayerPanelTitle = true,
// sn 관망도처럼 트리와 선택 설정을 카드 두 개로 구분해야 하는 화면에서만 활성화한다.
sectionedTreePanel = false,
showZoomScaleInfo = false,
}) {
const mapRef = useRef();
@@ -305,6 +320,7 @@ function Gis({
visible={tabVisible}
setVisible={setTabVisible}
onCheckedChange={handleCheckedLayersChange}
checkedLayerRequest={checkedLayerRequest}
onLayerIconClick={(layerNm, node) => {
layerNmRef.current = layerNm;
setLayerNm(layerNm);
@@ -313,6 +329,9 @@ function Gis({
}}
imageVisible={imgVisble}
layerIconVisible={layerIconVisible}
layerLegendIconVisible={layerLegendIconVisible}
layerIconRequiresChecked={layerIconRequiresChecked}
layerActionIconOnly={layerActionIconOnly}
sinkholeLegendIconVisible={sinkholeLegendIconVisible}
isPlaying={isPlaying}
setIsPlaying={setIsPlaying}
@@ -324,6 +343,8 @@ function Gis({
treeSectionClassName={treeSectionClassName}
toggleButtonPosition={treeTogglePosition}
detachedToggleButton={detachedTreeToggleButton}
showLayerPanelTitle={showLayerPanelTitle}
sectionedPanel={sectionedTreePanel}
/>
{typeof WaterDepth === "function" && (
@@ -353,15 +374,15 @@ function Gis({
)}
{/* 시도/시군구 조회 영역 */}
{SearchBar && (
<div className="absolute left-1/2 top-4 z-30 w-max -translate-x-1/2 rounded">
<div className={`absolute left-1/2 top-4 z-30 w-max -translate-x-1/2 rounded ${searchBarContainerClassName}`}>
{SearchBar}
</div>
)}
<GisToolBar />
<GisToolBar iconSize={toolBarIconSize} />
{showZoomLevel && (
<GisZoomLevel zoomGuide={zoomGuide} showZoomScaleInfo={showZoomScaleInfo} />
)}
<GisMapToggle />
<GisMapToggle alwaysVisibleTabs={alwaysVisibleMapTabs} />
<GisSelect
onFeatureSelect={handleFeatureSelect}
onMapBlankClick={onMapBlankClick}
@@ -2,6 +2,7 @@ import GisApp from './lib/gis.core';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { GisContext, setTree } from './Gis';
import { Button } from "@common/components";
import { showBusinessUserMessage } from '../../lib/user-message';
import { gAlert, gConfirm } from './lib/util';
// import { fclApi } from '../../js/apis/fcl/fclApi';
@@ -39,12 +40,12 @@ export default React.memo(function GisEdit() {
let add = !btnEvt.add;
if (add) {
if (!checkedLayerIds?.current?.includes(selectedLyrId.current)) {
alert('트리에서 레이어 체크 후 추가 가능합니다.');
showBusinessUserMessage('트리에서 레이어 체크 후 추가 가능합니다.');
return;
}
const errMsg = editModule.setDraw(selectedLyrId.current);
if (errMsg) {
alert(errMsg);
showBusinessUserMessage(errMsg);
return;
}
} else {
@@ -1,30 +1,67 @@
import React, { useContext, useState } from 'react';
import { GisContext } from './Gis';
import React, { useContext, useState } from "react";
import { GisContext } from "./Gis";
export default React.memo(function MapToggleBtn() {
const { gisCore } = useContext(GisContext);
const [activeMap, setActiveMap] = useState({ label: '일반', type: 'base' }); // 기본 선택값
export default React.memo(function MapToggleBtn({ alwaysVisibleTabs = false }) {
const { gisCore } = useContext(GisContext);
const [activeMap, setActiveMap] = useState({ label: "일반", type: "base" }); // 기본 선택값
const handleSelect = mapObj => {
setActiveMap(mapObj);
gisCore.changeBaseLayer(mapObj.type);
};
const handleSelect = (mapObj) => {
setActiveMap(mapObj);
gisCore.changeBaseLayer(mapObj.type);
};
return (
<div className="mapbtn">
<button className="sprite_gis viewer" title="지도선택">지도 선택</button>
<ul className="choice_map">
<li className={activeMap.type === 'base' ? 'on' : ''}>
<button className="map1" id="base" title="일반지도" onClick={() => handleSelect({ label: '일반', type: 'base' })}>
<div>일반지도</div>
</button>
</li>
<li className={activeMap.type === 'satellite' ? 'on' : ''}>
<button className="map2" id="satelite" title="위성지도" onClick={() => handleSelect({ label: '위성', type: 'satellite' })}>
<div>위성지도</div>
</button>
</li>
</ul>
</div>
);
if (alwaysVisibleTabs) {
return (
<div className="mapbtn mapbtn-tabs">
<div className="map-type-tabs" role="group" aria-label="지도 유형 선택">
<button
type="button"
aria-pressed={activeMap.type === "base"}
className={activeMap.type === "base" ? "on" : ""}
onClick={() => handleSelect({ label: "일반", type: "base" })}
>
일반지도
</button>
<button
type="button"
aria-pressed={activeMap.type === "satellite"}
className={activeMap.type === "satellite" ? "on" : ""}
onClick={() => handleSelect({ label: "위성", type: "satellite" })}
>
위성지도
</button>
</div>
</div>
);
}
return (
<div className="mapbtn">
<button className="sprite_gis viewer" title="지도선택">
지도 선택
</button>
<ul className="choice_map">
<li className={activeMap.type === "base" ? "on" : ""}>
<button
className="map1"
id="base"
title="일반지도"
onClick={() => handleSelect({ label: "일반", type: "base" })}
>
<div>일반지도</div>
</button>
</li>
<li className={activeMap.type === "satellite" ? "on" : ""}>
<button
className="map2"
id="satelite"
title="위성지도"
onClick={() => handleSelect({ label: "위성", type: "satellite" })}
>
<div>위성지도</div>
</button>
</li>
</ul>
</div>
);
});
@@ -1,71 +1,102 @@
import React from 'react';
import GisApp from './lib/gis.core';
import GisOlMeasure from './lib/gis.measure';
import { useContext } from 'react';
import { useGisContext } from './Gis';
export default React.memo(function GisToolBar() {
const { gisMap } = useGisContext();
if (!gisMap) return <></>;
const gisMeasuer = new GisOlMeasure(gisMap);
GisApp.Module.measure = gisMeasuer;
const zoomIn = () => {
if (gisMap.getView().getMaxZoom() > gisMap.getView().getZoom()) {
gisMap.getView().animate({
zoom: gisMap.getView().getZoom() + 1,
duration: 250,
});
}
};
const zoomOut = () => {
if (gisMap.getView().getMaxZoom() > gisMap.getView().getZoom()) {
gisMap.getView().animate({
zoom: gisMap.getView().getZoom() - 1,
duration: 250,
});
}
};
import React from "react";
import { RotateCcw, Ruler, Scan, ZoomIn, ZoomOut } from "lucide-react";
import GisApp from "./lib/gis.core";
import GisOlMeasure from "./lib/gis.measure";
import { useContext } from "react";
import { useGisContext } from "./Gis";
export default React.memo(function GisToolBar({ iconSize }) {
const { gisMap } = useGisContext();
const useVectorIcons = Number.isFinite(iconSize) && iconSize > 0;
if (!gisMap) return <></>;
const gisMeasuer = new GisOlMeasure(gisMap);
GisApp.Module.measure = gisMeasuer;
const zoomIn = () => {
if (gisMap.getView().getMaxZoom() > gisMap.getView().getZoom()) {
gisMap.getView().animate({
zoom: gisMap.getView().getZoom() + 1,
duration: 250,
});
}
};
const zoomOut = () => {
if (gisMap.getView().getMaxZoom() > gisMap.getView().getZoom()) {
gisMap.getView().animate({
zoom: gisMap.getView().getZoom() - 1,
duration: 250,
});
}
};
const measure = type => {
gisMeasuer.addInteraction(type);
};
const measure = (type) => {
gisMeasuer.addInteraction(type);
};
const reset = () => {
gisMeasuer.removeFeature();
};
return (
<>
<div className="custom-toolbar">
<div className="tool-bar">
<h3>toolbar 영역</h3>
<ul>
<li>
<div className="btn_control_zoomin" title="확대" onClick={zoomIn}>
<span>확대</span>
</div>
</li>
<li>
<div className="btn_control_zoomout" title="축소" onClick={zoomOut}>
<span>축소</span>
</div>
</li>
<li>
<div className="btn_control_ruler btn_control_measure" title="거리 측정" onClick={() => measure(GisApp.measure.LineString)}>
<span>거리측정</span>
</div>
</li>
<li>
<div className="btn_control_area btn_control_measure" title="면적 측정" onClick={() => measure(GisApp.measure.Polygon)}>
<span>면적측정</span>
</div>
</li>
<li>
<div className="sprite_gis icon4 btn_select_cancel" title="리셋" onClick={() => reset()}>
<span>리셋</span>
</div>
</li>
</ul>
</div>
</div>
</>
);
const reset = () => {
gisMeasuer.removeFeature();
};
return (
<>
<div className="custom-toolbar">
<div
className={`tool-bar ${useVectorIcons ? "tool-bar-vector-icons" : ""}`}
>
<h3>toolbar 영역</h3>
<ul>
<li>
<div className="btn_control_zoomin" title="확대" onClick={zoomIn}>
{useVectorIcons && (
<ZoomIn size={iconSize} aria-hidden="true" />
)}
<span>확대</span>
</div>
</li>
<li>
<div
className="btn_control_zoomout"
title="축소"
onClick={zoomOut}
>
{useVectorIcons && (
<ZoomOut size={iconSize} aria-hidden="true" />
)}
<span>축소</span>
</div>
</li>
<li>
<div
className="btn_control_ruler btn_control_measure"
title="거리 측정"
onClick={() => measure(GisApp.measure.LineString)}
>
{useVectorIcons && <Ruler size={iconSize} aria-hidden="true" />}
<span>거리측정</span>
</div>
</li>
<li>
<div
className="btn_control_area btn_control_measure"
title="면적 측정"
onClick={() => measure(GisApp.measure.Polygon)}
>
{useVectorIcons && <Scan size={iconSize} aria-hidden="true" />}
<span>면적측정</span>
</div>
</li>
<li>
<div
className="sprite_gis icon4 btn_select_cancel"
title="리셋"
onClick={() => reset()}
>
{useVectorIcons && (
<RotateCcw size={iconSize} aria-hidden="true" />
)}
<span>리셋</span>
</div>
</li>
</ul>
</div>
</div>
</>
);
});
@@ -4,9 +4,10 @@ import {
getBackendOptions,
DndProvider,
} from "@minoru/react-dnd-treeview";
import { ChevronLeft, ChevronRight } from "lucide-react";
import React, { useEffect, useState, useRef, useCallback } from "react";
import { ChevronLeft, ChevronRight, Layers } from "lucide-react";
import React, { useEffect, useLayoutEffect, useState, useRef, useCallback } from "react";
import { showBusinessUserMessage } from "../../lib/user-message";
import { useGisContext } from "./Gis";
import GisApp from "./lib/gis.core";
@@ -18,6 +19,7 @@ import GisApp from "./lib/gis.core";
*
* Props 요약
* - checkedNodes, setCheckedNodes: (선택) 외부 관리 체크 상태 (현재 내부 state 사용)
* - checkedLayerRequest: (선택) 기존 체크 상태를 유지하면서 지정 레이어를 추가로 체크하는 요청
* - visible, setVisible: 사이드 패널 가시성 on/off
* - onCheckedChange(checkedIds, checkedNodesData): 체크 변경 시 콜백
* - onLayerIconClick(nodeNm): 각 노드의 미리보기/아이콘 클릭 시 콜백
@@ -29,11 +31,16 @@ import GisApp from "./lib/gis.core";
* - onProgressChange(total, current): 애니메이션 진행상태 콜백
* - layerSettingView: (선택) 좌측 레이어 트리 하단에 표시할 설정 영역
* - layerIconVisible: (선택) 레이어 행 우측 액션 아이콘 노출 여부를 결정하는 함수
* - layerLegendIconVisible: (선택) 레이어 행 범례 아이콘 노출 여부를 결정하는 함수
* - layerIconRequiresChecked: (선택) 액션 실행 전에 레이어 체크를 요구할지 여부
* - layerActionIconOnly: (선택) 목록 액션을 텍스트 대신 목록 아이콘으로 표시할지 여부
* - detachedToggleButton: (선택) 접기/펼치기 버튼을 패널 밖 고정 핸들로 노출할지 여부
* - sectionedPanel: (선택) 트리와 선택 레이어 설정을 회색 배경 위의 독립 카드로 표시할지 여부
*/
export default React.memo(function GisTree({
checkedNodes = [],
setCheckedNodes = () => { },
checkedLayerRequest = null,
visible,
setVisible,
onCheckedChange,
@@ -46,12 +53,16 @@ export default React.memo(function GisTree({
onProgressChange = () => { },
layerSettingView: LayerSettingView = null,
layerIconVisible,
layerLegendIconVisible = () => true,
layerIconRequiresChecked = true,
layerActionIconOnly = false,
sinkholeLegendIconVisible = false,
inlineLayerSettingView,
treeSectionClassName = "",
toggleButtonPosition = "center",
showLayerPanelTitle = true,
detachedToggleButton = false,
sectionedPanel = false,
}) {
const { gisCore, treeData } = useGisContext();
@@ -66,6 +77,31 @@ export default React.memo(function GisTree({
const targetNodesRef = useRef([]);
const isPausedRef = useRef(false);
const timeoutIdRef = useRef(null);
// 동일한 외부 체크 요청이 리렌더링마다 반복 적용되지 않도록 마지막 요청 키를 보관한다.
const lastCheckedLayerRequestKeyRef = useRef(null);
// 체크 후 부모 설정영역까지 다시 렌더되어도 사용자가 보던 트리 위치를 유지한다.
const layerPanelScrollRef = useRef(null);
const layerPanelScrollTopRef = useRef(0);
const handleLayerPanelScroll = useCallback((event) => {
layerPanelScrollTopRef.current = event.currentTarget.scrollTop;
}, []);
useLayoutEffect(() => {
const scrollContainer = layerPanelScrollRef.current;
if (!scrollContainer) return;
const maxScrollTop = Math.max(
0,
scrollContainer.scrollHeight - scrollContainer.clientHeight
);
const nextScrollTop = Math.min(layerPanelScrollTopRef.current, maxScrollTop);
if (scrollContainer.scrollTop !== nextScrollTop) {
scrollContainer.scrollTop = nextScrollTop;
}
layerPanelScrollTopRef.current = nextScrollTop;
});
// =====================
// 유틸리티: 트리 탐색 관련 함수들
@@ -294,6 +330,37 @@ export default React.memo(function GisTree({
[nodes]
);
/**
* 업무 화면이 요청한 레이어를 기존 사용자 체크 상태에 추가하고 조상 그룹을 펼친다.
* 레이어명은 공백 차이를 무시하며, 실제 지도 반영과 onCheckedChange는 수동 체크와 같은 경로를 사용한다.
*/
useEffect(() => {
const requestKey = checkedLayerRequest?.requestKey;
if (requestKey == null || nodes.length === 0) return;
if (lastCheckedLayerRequestKeyRef.current === requestKey) return;
const normalizeLayerName = (value) => String(value ?? "")
.replace(/\s+/g, "")
.trim();
const requestedLayerNames = new Set(
(checkedLayerRequest?.layerNames ?? [])
.map(normalizeLayerName)
.filter(Boolean)
);
const targetNodes = nodes.filter((node) => requestedLayerNames.has(
normalizeLayerName(node?.data?.lyrNm ?? node?.text)
));
if (targetNodes.length === 0) return;
setExpanded((current) => Array.from(new Set([
...current,
...targetNodes.map((node) => node.id),
...targetNodes.flatMap((node) => getAncestors(node.id, nodes)),
])));
targetNodes.forEach((node) => checkSpecificNode(node.id, true));
lastCheckedLayerRequestKeyRef.current = requestKey;
}, [checkedLayerRequest, checkSpecificNode, nodes]);
// =====================
// 자동 애니메이션: 지정된 순서/간격으로 노드 체크 상태를 순차 변경
// =====================
@@ -323,7 +390,13 @@ export default React.memo(function GisTree({
// orderedLayers 순서를 우선 적용하면서, 타입 필터에 맞는 타겟 노드만 선별
const getTargetNodesInOrder = () => {
const target = nodes.filter((n) => n.data?.actlLyrYn === 'N' && layerTypes.includes(n.data?.lyrTyNm));
const target = nodes.filter((node) => {
const hasChildren = nodes.some((child) => child.parent === node.id);
const isWmsGroupLayer = node.data?.srvcNm === 'wms' && hasChildren;
return node.data?.exprsYn === 'Y'
&& layerTypes.includes(node.data?.lyrTyNm)
&& (node.data?.actlLyrYn === 'N' || isWmsGroupLayer);
});
// drawOrdr 값을 기준으로 오름차순 정렬
target.sort((a, b) => {
@@ -507,7 +580,7 @@ export default React.memo(function GisTree({
* 각 레이어 행의 아이콘 클릭 시 호출. 선택되지 않은 레이어면 경고, 선택된 경우 콜백 전달.
*/
const handleLayerImgClick = (nodeNm, nodeId, node) => {
if (!checked.includes(nodeId)) alert("시설을 선택해주세요");
if (layerIconRequiresChecked && !checked.includes(nodeId)) showBusinessUserMessage("시설을 선택해주세요");
else onLayerIconClick(nodeNm, node);
};
@@ -515,36 +588,57 @@ export default React.memo(function GisTree({
// 렌더링
// =====================
if (!treeData || treeData.length === 0) return null;
const toggleButtonPositionClass =
toggleButtonPosition === "top" ? "top-4" : "top-1/2 -translate-y-1/2";
const thinScrollbarClass =
"[scrollbar-width:thin] [&::-webkit-scrollbar]:w-[4px]";
const treeSectionClassNames = [treeSectionClassName, thinScrollbarClass].filter(Boolean).join(" ");
"[scrollbar-gutter:stable] [scrollbar-width:thin] [&::-webkit-scrollbar]:w-[4px]";
const treeSectionClassNames = [treeSectionClassName].filter(Boolean).join(" ");
// 섹션형 패널은 지도 트리와 선택 레이어 설정을 각각 독립된 카드로 구분한다.
const panelShellClassName = sectionedPanel
? "gap-[6px] border-r-0 bg-[#E5E5E5] p-1"
: "border-r border-border bg-background";
const treePanelClassName = sectionedPanel
? "min-h-0 grow flex-col overflow-hidden rounded-[6px] border border-border bg-background shadow-none"
: "min-h-0 grow overflow-hidden border-none bg-background shadow-none";
const treeContentScrollClassName = sectionedPanel
? `min-h-0 flex-1 overflow-y-scroll ${thinScrollbarClass}`
: `h-full overflow-y-auto p-2 ${showLayerPanelTitle ? "pt-0" : "pt-2"} ${thinScrollbarClass}`;
return (
<>
{/* 사이드 패널 */}
<div
className={`gis-layer-panel absolute left-0 top-0 z-40 flex h-full w-[250px] flex-col overflow-hidden border-r border-border bg-background text-foreground transition-all duration-300 ${visible
? "translate-x-0 opacity-100"
: "pointer-events-none -translate-x-full opacity-0"
className={`gis-layer-panel absolute left-0 top-0 z-40 flex h-full w-[250px] flex-col overflow-hidden text-foreground duration-300 ${sectionedPanel ? "transition-transform ease-in-out" : "transition-all"} ${panelShellClassName} ${visible
? sectionedPanel ? "translate-x-0" : "translate-x-0 opacity-100"
: sectionedPanel ? "pointer-events-none -translate-x-full" : "pointer-events-none -translate-x-full opacity-0"
}`}
>
<div
className={`grow overflow-y-auto border-none p-2 ${showLayerPanelTitle ? "pt-0" : "pt-2"} shadow-none ${activeTab === "layers" ? "block" : "hidden"
className={`${treePanelClassName} ${activeTab === "layers" ? (sectionedPanel ? "flex" : "block") : "hidden"
}`}
>
{showLayerPanelTitle && (
<>
<h3 className="gis-layer-panel-title mx-2 my-4 text-center text-3xl font-bold text-label">시설물</h3>
<hr className="mb-4 border-border" />
</>
{sectionedPanel && (
<div className="gis-layer-section-header flex h-[38px] shrink-0 items-center gap-2 border-b border-border bg-background px-3">
<span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-sm bg-[#EAF3FF] text-[#168CFF]">
<Layers size={14} strokeWidth={2} />
</span>
<h3 className="text-[1.4rem] font-bold text-foreground">레이어 관리</h3>
</div>
)}
{/* DnD Tree */}
<div className={treeSectionClassNames || undefined}>
<DndProvider backend={MultiBackend} options={getBackendOptions()}>
<div
ref={layerPanelScrollRef}
onScroll={handleLayerPanelScroll}
className={treeContentScrollClassName}
>
{showLayerPanelTitle && (
<>
<h3 className="gis-layer-panel-title mx-2 my-4 text-center text-3xl font-bold text-label">시설물</h3>
<hr className="mb-4 border-border" />
</>
)}
{/* DnD Tree */}
<div className={treeSectionClassNames || undefined}>
<DndProvider backend={MultiBackend} options={getBackendOptions()}>
<Tree
tree={nodes}
rootId={null}
@@ -560,10 +654,9 @@ export default React.memo(function GisTree({
const isSinkholeRootTreeNode =
String(node.id) === "SN_SINKHOLE" ||
nodeLabel === "지반침하정보";
const isFloodHistoryRootTreeNode = nodeLabel === "침수흔적도";
const hideTreeLegendIcon =
(isSinkholeRootTreeNode && !sinkholeLegendIconVisible) ||
isFloodHistoryRootTreeNode;
!layerLegendIconVisible(node);
const showLayerActionButton = layerIconVisible?.(node);
const showLayerActionIcon = depth > 0 && imageVisible;
@@ -572,7 +665,7 @@ export default React.memo(function GisTree({
return (
<div style={{ display: isVisible ? "block" : "none" }}>
<div
className="gis-layer-row flex w-full items-center gap-2 rounded px-2 py-1 hover:bg-accent"
className={`gis-layer-row flex w-full items-center gap-2 rounded px-2 py-1 ${sectionedPanel ? "hover:bg-[#f5f5f5]" : "hover:bg-accent"}`}
style={{
marginInlineStart: depth * 16,
width: `calc(100% - ${depth * 16}px)`,
@@ -601,21 +694,39 @@ export default React.memo(function GisTree({
>
{node.text}
</span>
{showLayerActionButton && (
<button
type="button"
className="gis-layer-action-button ml-auto shrink-0 rounded-sm border border-primary bg-background px-2 py-[1px] text-[1.1rem] font-medium leading-5 text-primary transition-colors hover:bg-accent"
onClick={() =>
handleLayerImgClick(
{showLayerActionButton && (
<button
type="button"
className={layerActionIconOnly
? "gis-layer-action-button ml-auto grid h-[24px] w-[24px] shrink-0 place-items-center rounded-sm bg-transparent p-0 text-[#168CFF] transition-colors hover:bg-accent"
: "gis-layer-action-button ml-auto shrink-0 rounded-sm border border-primary bg-background px-2 py-[1px] text-[1.1rem] font-medium leading-5 text-primary transition-colors hover:bg-accent"}
onClick={() =>
handleLayerImgClick(
node.data.lyrTyNm,
node.id,
node
)
}
title={`${node.text} 목록보기`}
>
목록보기
</button>
)
}
title={`${node.text} 목록보기`}
aria-label={`${node.text} 목록보기`}
>
{layerActionIconOnly ? (
<svg
aria-hidden="true"
viewBox="0 0 24 24"
className="h-[18px] w-[18px]"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
>
<path d="M9 6h11M9 12h11M9 18h11" />
<path d="M4 6h.01M4 12h.01M4 18h.01" strokeWidth="3" />
</svg>
) : (
"목록보기"
)}
</button>
)}
{!showLayerActionButton && showLayerActionIcon && (
<span className="shrink-0">
@@ -650,11 +761,16 @@ export default React.memo(function GisTree({
return aOrder - bOrder;
}}
/>
</DndProvider>
</DndProvider>
</div>
</div>
</div>
{LayerSettingView && (
<div className="gis-layer-setting shrink-0 bg-background px-2 pb-3">
<div
className={sectionedPanel
? "gis-layer-setting shrink-0 bg-transparent p-0"
: "gis-layer-setting shrink-0 bg-background px-2 pb-3"}
>
<LayerSettingView />
</div>
)}
@@ -667,24 +783,31 @@ export default React.memo(function GisTree({
</button>
)}
</div>
{detachedToggleButton && visible && (
{detachedToggleButton && (
<button
onClick={() => setVisible(false)}
className={`gis-layer-toggle absolute left-[250px] z-50 flex h-[36px] w-[20px] transform items-center justify-center rounded-[4px] border border-border bg-background text-primary shadow-[0_8px_18px_rgba(15,23,42,0.14)] transition hover:bg-accent ${toggleButtonPositionClass}`}
title="접기"
onClick={() => setVisible(!visible)}
className={`gis-layer-toggle absolute left-[250px] z-50 flex h-[36px] transform items-center justify-center border border-border bg-background shadow-[0_8px_18px_rgba(15,23,42,0.14)] transition-transform duration-300 ease-in-out hover:bg-accent ${visible ? "translate-x-0" : "-translate-x-[250px]"} ${sectionedPanel
? "w-[20px] rounded-l-none rounded-r-[4px] text-[#666666]"
: "w-[20px] rounded-[4px] text-primary"
} ${toggleButtonPositionClass}`}
title={visible ? "접기" : "열기"}
aria-label={visible ? "레이어 패널 접기" : "레이어 패널 열기"}
aria-expanded={visible}
>
<ChevronLeft className="h-4 w-4" />
{visible ? (
<ChevronLeft className={sectionedPanel ? "h-8 w-8" : "h-4 w-4"} />
) : (
<ChevronRight className={sectionedPanel ? "h-8 w-8" : "h-4 w-4"} />
)}
</button>
)}
{!visible && (
{!visible && !detachedToggleButton && (
<button
onClick={() => setVisible(true)}
className={detachedToggleButton
? `gis-layer-toggle absolute left-0 z-50 flex h-[36px] w-[20px] transform items-center justify-center rounded-[4px] border border-border bg-background text-primary shadow-[0_8px_18px_rgba(15,23,42,0.14)] transition hover:bg-accent ${toggleButtonPositionClass}`
: `gis-layer-toggle absolute left-[-3px] z-50 transform rounded-r border border-r border-border bg-background px-1 py-2 text-foreground shadow-sm ${toggleButtonPositionClass}`}
className={`gis-layer-toggle absolute left-[-3px] z-50 transform rounded-r border border-r border-border bg-background px-1 py-2 text-foreground shadow-sm ${toggleButtonPositionClass}`}
title="열기"
>
{detachedToggleButton ? <ChevronRight className="h-4 w-4" /> : <ChevronRight size={16} />}
<ChevronRight size={16} />
</button>
)}
</>
@@ -101,6 +101,56 @@
text-align: center;
}
.mapbtn.mapbtn-tabs {
width: auto;
}
.mapbtn .map-type-tabs {
display: flex;
width: 144px;
height: 40px;
padding: 2px;
overflow: hidden;
box-sizing: border-box;
background: #fff;
border: 1px solid #9aa7b8;
border-radius: 6px;
box-shadow: 0 0 5px #999;
}
.mapbtn .map-type-tabs button {
display: flex;
flex: 1;
align-items: center;
justify-content: center;
min-width: 0;
height: 100%;
padding: 0 8px;
box-sizing: border-box;
background: #fff;
border-radius: 6px;
border: 0;
color: #666;
font-family: inherit;
font-size: 12px;
font-weight: 600;
line-height: 18px;
white-space: nowrap;
}
.mapbtn .map-type-tabs button.on {
background: #0279fa;
color: #fff;
}
.mapbtn .map-type-tabs button:focus-visible {
position: relative;
z-index: 1;
outline: 2px solid #2094fa;
outline-offset: -2px;
}
.tool-bar {
position: absolute;
top: 70px;
@@ -186,9 +236,9 @@
bottom: 6px;
display: flex;
flex-direction: column;
gap: 4px;
min-width: 126px;
padding: 7px 10px;
gap: 8px;
min-width: 130px;
padding: 8px 10px;
border: 1px solid #9aa7b8;
border-radius: 6px;
background: rgba(255, 255, 255, 0.96);
@@ -242,9 +292,14 @@
cursor: pointer;
}
.zoom-level-panel .zoom-level-btn:first-child {
border-radius: 3px 3px 0 0;
}
.zoom-level-panel .zoom-level-btn:last-child {
border-top: 1px solid #eeeeee;
border-bottom: 0 none;
border-radius: 0 0 3px 3px;
}
.zoom-level-btn:hover {
@@ -392,6 +392,7 @@ GisApp.core.prototype = {
*/
addWmsLayer: function (layerCodeObj) {
let layer = GisApp.Module.layer.getWmsLayer(layerCodeObj);
if (!layer) return null;
this.deleteLayer(layer.get('id'));
this.map.addLayer(layer);
return layer;
@@ -20,6 +20,12 @@ import GisOlStyle from './gis.style.js';
import Tile from 'ol/layer/Tile.js';
import TileWMS from 'ol/source/TileWMS.js';
import gisCore from './gis.core.js';
import { showBusinessUserMessage } from '../../../lib/user-message';
import {
buildFloodDngrSldBody,
FLOOD_DNGR_MAP_LAYER_TYPE,
getFloodDngrSldSettings,
} from './gis.wms-sld.js';
/**
* GisApp.layer
@@ -179,6 +185,7 @@ GisOlLayer.prototype = {
let url = GisApp.GEOSERVER_WMS_URL;
let toProj = GisApp.TO_PROJ;
const lyrTyNm = options.lyrTyNm;
const filter = String(options?.flterSql ?? '').trim();
let params = {};
params['LAYERS'] = this.storageNm + lyrTyNm;
params['SERVICE'] = 'WMS';
@@ -186,7 +193,21 @@ GisOlLayer.prototype = {
params['REQUEST'] = 'GetMap';
params['SRS'] = toProj;
params['FORMAT'] = 'image/png';
params['TRANSPARENT'] = true;
params['TILED'] = true;
params['STYLES'] = '';
if (filter) params['CQL_FILTER'] = filter;
if (lyrTyNm === FLOOD_DNGR_MAP_LAYER_TYPE) {
const sldSettings = getFloodDngrSldSettings(GisApp.layerCode, options?.id);
const sldBody = buildFloodDngrSldBody(lyrTyNm, sldSettings);
if (!sldBody) {
console.warn('[GisApp] 도시침수지도 WMS SLD 생성에 필요한 침수심도 설정 5건이 유효하지 않습니다.', options);
return null;
}
params['SLD_BODY'] = sldBody;
}
const wmsLayer = new Tile({
...layerOptions,
id: layerOptions?.id,
@@ -196,8 +217,9 @@ GisOlLayer.prototype = {
serverType: 'geoserver',
}),
});
wmsLayer.setZIndex(options.draw0rdr);
wmsLayer.setMinZoom(options.minViewSize);
wmsLayer.set('id', String(layerOptions?.id));
wmsLayer.setZIndex(Number(options?.drawOrdr) || 1);
wmsLayer.setMinZoom(Number(options?.minViewSize) || 0);
this.layers.push(wmsLayer);
return wmsLayer;
},
@@ -652,7 +674,7 @@ GisOlLayer.prototype = {
// 1) 로드 완료시 extent 맞추기
const onLoadEnd = () => {
if (Object.keys(source.nullGeometryFeatures_).length > 0) alert('해당 시설의 위치 정보가 없습니다.');
if (Object.keys(source.nullGeometryFeatures_).length > 0) showBusinessUserMessage('해당 시설의 위치 정보가 없습니다.');
const feats = source.getFeatures();
if (feats && feats.length > 0) {
@@ -29,9 +29,11 @@ GisOlSelect.prototype = {
dragBox: null,
dragPolygon: null,
selectedFeatures: [],
focusedBoundaryFeatures: null,
selectFeatureFlag: false,
initialize: function (map, options) {
this.map = map;
this.focusedBoundaryFeatures = new WeakSet();
Object.assign(this.defaults, options);
this.setInteraction();
this.pointerMoveEventHandler();
@@ -94,25 +96,31 @@ GisOlSelect.prototype = {
this.selectInteraction = new Select({
style: function (feature, resolution) {
let styles = [];
let layer = feature.getLayer();
let styleFn = GisApp.Module.style.getLayerStyleFunction(layer, null);
let originalStyles = [];
const layer = me.selectInteraction?.getLayer(feature) || feature.getLayer?.();
// 프론트에서 직접 생성한 벡터 레이어도 선택 시 실제 레이어 스타일을 유지한다.
const layerStyleFn = layer?.getStyleFunction?.();
const styleFn = typeof layerStyleFn === 'function'
? layerStyleFn
: layer
? GisApp.Module.style.getLayerStyleFunction(layer, null)
: null;
if (styleFn) {
const style = styleFn(feature, resolution);
if (Array.isArray(style)) {
styles.push(...style);
} else {
styles.push(style);
originalStyles.push(...style.filter(Boolean));
} else if (style) {
originalStyles.push(style);
}
}
const geometryType = feature?.getGeometry?.()?.getType?.();
if (geometryType === 'LineString' || geometryType === 'MultiLineString') {
styles.push(...focusedLineStyle);
} else {
styles.push(baseStyle);
const focusedBoundary = me.focusedBoundaryFeatures.has(feature);
if (focusedBoundary || geometryType === 'LineString' || geometryType === 'MultiLineString') {
return [...originalStyles, ...focusedLineStyle];
}
return styles;
// 점 시설은 원형 선택 강조를 먼저 그린 뒤 원래 아이콘을 위에 다시 그린다.
return [baseStyle, ...originalStyles];
},
layers: function (layer) {
let clickPsblYn = layer?.get('clickPsblYn');
@@ -329,6 +337,7 @@ GisOlSelect.prototype = {
selectedFeatures.remove(feature);
});
selectedFeatures.clear();
this.focusedBoundaryFeatures = new WeakSet();
},
/**
* SELECT 이벤트 활성화
@@ -491,6 +500,20 @@ GisOlSelect.prototype = {
auto: auto,
});
},
/**
* 폴리곤을 선형 피처와 동일한 다중 경계 스타일로 강조한다.
*/
selectFocusedBoundaryFeature: function (feature, auto) {
let me = this;
me.focusedBoundaryFeatures.add(feature);
me.selectedFeatures.push(feature);
me.selectInteraction.dispatchEvent({
type: 'select',
selected: me.selectedFeatures,
deselected: [],
auto: auto,
});
},
};
export default GisOlSelect;
@@ -0,0 +1,103 @@
const FLOOD_DNGR_MAP_LAYER_TYPE = 'tb_ms_flood_dngr_map';
const FLOOD_DEPTH_ATTRIBUTE = 'sbmrg_dpthl_cd';
const FLOOD_DEPTH_CODES = ['N330', 'N331', 'N332', 'N333', 'N334'];
const escapeXml = (value) => String(value ?? '')
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&apos;');
const toHex = (value) => Math.round(value).toString(16).padStart(2, '0');
const parseCssColor = (value) => {
const normalized = String(value ?? '').trim();
const rgbaMatch = normalized.match(/^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})(?:\s*,\s*(0(?:\.\d+)?|1(?:\.0+)?))?\s*\)$/i);
if (rgbaMatch) {
const red = Number(rgbaMatch[1]);
const green = Number(rgbaMatch[2]);
const blue = Number(rgbaMatch[3]);
const opacity = rgbaMatch[4] == null ? 1 : Number(rgbaMatch[4]);
if ([red, green, blue].some((channel) => channel < 0 || channel > 255) || opacity < 0 || opacity > 1) {
return null;
}
return {
hex: `#${toHex(red)}${toHex(green)}${toHex(blue)}`,
opacity,
};
}
const hexMatch = normalized.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);
if (!hexMatch) return null;
const rawHex = hexMatch[1].length === 3
? hexMatch[1].split('').map((character) => character + character).join('')
: hexMatch[1];
return {
hex: `#${rawHex.toLowerCase()}`,
opacity: 1,
};
};
const getFloodDepthCode = (filterSql) => {
const match = String(filterSql ?? '').match(/\bsbmrg_dpthl_cd\s*=\s*'([^']+)'/i);
const depthCode = match?.[1]?.trim();
return FLOOD_DEPTH_CODES.includes(depthCode) ? depthCode : null;
};
const getLineWidth = (value) => {
const lineWidth = Number(value);
return Number.isFinite(lineWidth) && lineWidth >= 0 && lineWidth <= 20 ? lineWidth : null;
};
/**
* 빈도 부모 레이어 바로 아래에 있는 침수심도 설정만 선별한다.
* 부모는 WMS 요청을 담당하고, 반환된 자식 5건은 SLD 규칙의 필터와 색상 원본으로 사용한다.
*/
export const getFloodDngrSldSettings = (layerCode, parentLayerId) => Object.values(layerCode ?? {})
.filter((layerSetting) => (
String(layerSetting?.upperLyrSn ?? '') === String(parentLayerId ?? '')
&& layerSetting?.lyrTyNm === FLOOD_DNGR_MAP_LAYER_TYPE
))
.sort((left, right) => Number(left?.sortOrdr ?? 0) - Number(right?.sortOrdr ?? 0));
/**
* DB의 침수심도 필터와 RGBA 스타일을 GeoServer가 해석할 수 있는 SLD 1.0 XML로 변환한다.
* 다섯 침수심도 코드나 색상값 중 하나라도 유효하지 않으면 잘못된 기본 스타일 표출을 막기 위해 null을 반환한다.
*/
export const buildFloodDngrSldBody = (layerName, layerSettings) => {
if (!Array.isArray(layerSettings) || layerSettings.length !== FLOOD_DEPTH_CODES.length) return null;
const settingsByDepthCode = new Map();
for (const layerSetting of layerSettings) {
const depthCode = getFloodDepthCode(layerSetting?.flterSql);
if (depthCode && !settingsByDepthCode.has(depthCode)) {
settingsByDepthCode.set(depthCode, layerSetting);
}
}
if (settingsByDepthCode.size !== FLOOD_DEPTH_CODES.length) return null;
const rules = [];
for (const depthCode of FLOOD_DEPTH_CODES) {
const layerSetting = settingsByDepthCode.get(depthCode);
const fillColor = parseCssColor(layerSetting?.polgnColor);
const strokeColor = parseCssColor(layerSetting?.lnColor);
const lineWidth = getLineWidth(layerSetting?.lnWdth);
if (!fillColor || !strokeColor || lineWidth == null) return null;
rules.push(
`<sld:Rule><sld:Name>${escapeXml(depthCode)}</sld:Name><sld:Title>${escapeXml(layerSetting?.lyrNm || depthCode)}</sld:Title>`
+ `<ogc:Filter><ogc:PropertyIsEqualTo><ogc:PropertyName>${FLOOD_DEPTH_ATTRIBUTE}</ogc:PropertyName><ogc:Literal>${escapeXml(depthCode)}</ogc:Literal></ogc:PropertyIsEqualTo></ogc:Filter>`
+ `<sld:PolygonSymbolizer><sld:Fill><sld:CssParameter name="fill">${fillColor.hex}</sld:CssParameter><sld:CssParameter name="fill-opacity">${fillColor.opacity}</sld:CssParameter></sld:Fill>`
+ `<sld:Stroke><sld:CssParameter name="stroke">${strokeColor.hex}</sld:CssParameter><sld:CssParameter name="stroke-opacity">${strokeColor.opacity}</sld:CssParameter><sld:CssParameter name="stroke-width">${lineWidth}</sld:CssParameter></sld:Stroke></sld:PolygonSymbolizer></sld:Rule>`
);
}
return `<?xml version="1.0" encoding="UTF-8"?>`
+ `<sld:StyledLayerDescriptor version="1.0.0" xmlns="http://www.opengis.net/sld" xmlns:sld="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc">`
+ `<sld:NamedLayer><sld:Name>${escapeXml(layerName)}</sld:Name><sld:UserStyle><sld:FeatureTypeStyle>${rules.join('')}</sld:FeatureTypeStyle></sld:UserStyle></sld:NamedLayer>`
+ `</sld:StyledLayerDescriptor>`;
};
export { FLOOD_DNGR_MAP_LAYER_TYPE };
@@ -1,3 +1,5 @@
import { showBusinessUserMessage } from '../../../lib/user-message';
//공통
export const util = {
@@ -537,7 +539,7 @@ export const getMessage = (msgGroup, msgKey, innerText, fix) => {
// global.js의 message를 읽어오는 alert
export const gAlert = (msgGroup, msgKey, innerText, fix) => {
alert(getMessage(msgGroup, msgKey, innerText, fix));
showBusinessUserMessage(getMessage(msgGroup, msgKey, innerText, fix));
};
// message를 confirm
@@ -640,4 +642,4 @@ export const getFeatureLabelCoordinate = (feature) => {
const y = coordinate[1];
return `${x.toFixed(p)}_${y.toFixed(p)}`;
};
}
}
@@ -77,7 +77,7 @@ export default function SearchInputText({
} else if (e.key === "ArrowDown") {
e.preventDefault();
setHighlightIndex((prev) =>
prev < searchList.length - 1 ? prev + 1 : prev
prev < searchList.length - 1 ? prev + 1 : prev,
);
} else if (e.key === "ArrowUp") {
e.preventDefault();
@@ -93,17 +93,19 @@ export default function SearchInputText({
onKeyDown={handleKeyDown}
placeholder="시설명을 입력하세요"
className={
className + " rounded-lg border px-2 py-1 text-sm h-[29.5px]"
className + " h-[29.5px] rounded-lg border px-2 py-1 text-sm"
}
/>
{showResults && (
<div className="absolute z-10 mt-1 max-h-200 w-full overflow-auto rounded border bg-white shadow">
<div className="max-h-200 absolute z-10 mt-1 w-full overflow-auto rounded border border-border bg-popover text-popover-foreground shadow">
{searchList.length > 0 ? (
searchList.map((item, index) => (
<div
key={index}
className={`cursor-pointer px-3 py-1 hover:bg-gray-100 ${
highlightIndex === index ? "bg-blue-100" : ""
className={`cursor-pointer px-3 py-1 hover:bg-accent hover:text-accent-foreground ${
highlightIndex === index
? "bg-accent text-accent-foreground"
: ""
}`}
onClick={() => handleSelect(item)}
>
@@ -111,7 +113,7 @@ export default function SearchInputText({
</div>
))
) : (
<div className="px-3 py-2 text-sm text-gray-500">
<div className="px-3 py-2 text-sm text-muted-foreground">
검색 결과가 없습니다.
</div>
)}
@@ -2,8 +2,14 @@
import { SelectBox, type SelectDataType } from "../../../ui";
import { Button } from "@common/components/ui";
import { useCallback, useEffect, useState } from "react";
import { showBusinessUserMessage } from "../../../lib/user-message";
import GisApp from "../lib/gis.core";
import { getSigunguCenter, moveMapToCenter, sidoCenter, sigunguCenter } from "./utils";
import {
getSigunguCenter,
moveMapToCenter,
sidoCenter,
sigunguCenter,
} from "./utils";
// import { getGeometryCenter } from "./utils";
const geoserverUrl =
@@ -26,6 +32,8 @@ interface SearchBarProps {
facilityTypes: { text: string; val: string }[];
sidoSearchZoom?: number;
facilityLayerFilter?: FacilityLayerFilter;
/** 관망도 전용 3개 셀렉트와 조회 버튼을 하나로 연결한 검색바 레이아웃이다. */
integrated?: boolean;
}
interface CenterSelectDataType extends SelectDataType {
@@ -37,6 +45,7 @@ export const ProcSearchBar = ({
facilityTypes,
sidoSearchZoom = 11,
facilityLayerFilter,
integrated = false,
}: SearchBarProps) => {
const [sidoValue, setSidoValue] = useState("0");
const [sigunValue, setSigunValue] = useState("0");
@@ -46,20 +55,31 @@ export const ProcSearchBar = ({
const [sigunData, setSigunData] = useState<CenterSelectDataType[]>([
{ text: "시군구", val: "0" },
]);
const [filteredSigunData, setFilteredSigunData] = useState<CenterSelectDataType[]>([
{ text: "시군구", val: "0" },
]);
const [filteredSigunData, setFilteredSigunData] = useState<
CenterSelectDataType[]
>([{ text: "시군구", val: "0" }]);
const [facilityData, setFacilityData] = useState<SelectDataType[]>(() => [
{ text: facilityLayerFilter?.label ?? DEFAULT_SWAGE_PRCS_FCLT_LABEL, val: "0" },
{
text: facilityLayerFilter?.label ?? DEFAULT_SWAGE_PRCS_FCLT_LABEL,
val: "0",
},
]);
const [facilityValue, setFacilityValue] = useState("0");
const [pendingExternalFacilityName, setPendingExternalFacilityName] = useState("");
const [pendingExternalFacilityName, setPendingExternalFacilityName] =
useState("");
const [facilityType, setFacilityType] = useState(
facilityTypes?.length === 1 && facilityTypes[0] ? facilityTypes[0].val : "0",
facilityTypes?.length === 1 && facilityTypes[0]
? facilityTypes[0].val
: "0",
);
const defaultFacilityData = useCallback(
() => [{ text: facilityLayerFilter?.label ?? DEFAULT_SWAGE_PRCS_FCLT_LABEL, val: "0" }],
() => [
{
text: facilityLayerFilter?.label ?? DEFAULT_SWAGE_PRCS_FCLT_LABEL,
val: "0",
},
],
[facilityLayerFilter?.label],
);
@@ -71,7 +91,7 @@ export const ProcSearchBar = ({
.map((f: any) => ({
text: String(f.properties.mctpv_korn_nm ?? "").trim(),
val: String(f.properties.mctpv_cd ?? "").trim(),
center: sidoCenter[String(f.properties.mctpv_cd ?? "").trim()] //getGeometryCenter(f.geometry) ?? undefined,
center: sidoCenter[String(f.properties.mctpv_cd ?? "").trim()], //getGeometryCenter(f.geometry) ?? undefined,
}))
.sort((a: any, b: any) => {
// 커스텀 순서 정의
@@ -85,14 +105,14 @@ export const ProcSearchBar = ({
"울산광역시",
"세종특별자치시",
"경기도",
"강원특별자치도", // 경기도 다음에 배치
"강원특별자치도", // 경기도 다음에 배치
"충청북도",
"충청남도",
"전북특별자치도", // 충청남도 다음에 배치
"전북특별자치도", // 충청남도 다음에 배치
"전라남도",
"경상북도",
"경상남도",
"제주특별자치도"
"제주특별자치도",
];
const indexA = customOrder.indexOf(a.text);
@@ -108,7 +128,7 @@ export const ProcSearchBar = ({
if (indexB !== -1) return 1;
// 둘 다 커스텀 순서에 없으면 기본 알파벳 순서
return a.text.localeCompare(b.text, 'ko');
return a.text.localeCompare(b.text, "ko");
});
setSidoData([{ text: "시도", val: "0" }, ...list]);
};
@@ -122,7 +142,7 @@ export const ProcSearchBar = ({
.map((f: any) => ({
text: String(f.properties.sgg_korn_nm ?? "").trim(),
val: String(f.properties.sgg_cd ?? "").trim(),
center: sigunguCenter[String(f.properties.sgg_cd ?? "").trim()] //getGeometryCenter(f.geometry) ?? undefined,
center: sigunguCenter[String(f.properties.sgg_cd ?? "").trim()], //getGeometryCenter(f.geometry) ?? undefined,
}))
.sort((a: any, b: any) => a.text.localeCompare(b.text, "ko"));
@@ -140,7 +160,8 @@ export const ProcSearchBar = ({
const type = currentFacilityType ?? facilityType;
if (!type || type === "0") return;
const activeFacilityFilter = type === "tb_il_swage_prcs_fclt" ? facilityLayerFilter : undefined;
const activeFacilityFilter =
type === "tb_il_swage_prcs_fclt" ? facilityLayerFilter : undefined;
if (activeFacilityFilter?.disabled) {
setFacilityData(defaultFacilityData());
setFacilityValue("0");
@@ -163,7 +184,8 @@ export const ProcSearchBar = ({
const escapeCqlText = (value: string) => value.replace(/'/g, "''");
const cqlFilters = [`ctpv_nm='${escapeCqlText(sidoNm)}'`];
if (sggNm) cqlFilters.push(`sgg_nm='${escapeCqlText(sggNm)}'`);
if (activeFacilityFilter?.cqlFilter) cqlFilters.push(activeFacilityFilter.cqlFilter);
if (activeFacilityFilter?.cqlFilter)
cqlFilters.push(activeFacilityFilter.cqlFilter);
const params = new URLSearchParams({
typeName: `hasudo:${type}`,
cql_filter: cqlFilters.join(" AND "),
@@ -218,7 +240,9 @@ export const ProcSearchBar = ({
}));
}
const sorted = list.slice().sort((a, b) => a.text.localeCompare(b.text, "ko"));
const sorted = list
.slice()
.sort((a, b) => a.text.localeCompare(b.text, "ko"));
setFacilityData([...defaultFacilityData(), ...sorted]);
setFacilityValue("0");
},
@@ -240,7 +264,17 @@ export const ProcSearchBar = ({
setFacilityData(defaultFacilityData());
setFacilityValue("0");
}, [defaultFacilityData, facilityLayerFilter?.cqlFilter, facilityLayerFilter?.disabled, facilityType, fetchFacilitiesByRegion, sidoData, sidoValue, sigunData, sigunValue]);
}, [
defaultFacilityData,
facilityLayerFilter?.cqlFilter,
facilityLayerFilter?.disabled,
facilityType,
fetchFacilitiesByRegion,
sidoData,
sidoValue,
sigunData,
sigunValue,
]);
useEffect(() => {
if (!pendingExternalFacilityName) return;
@@ -252,7 +286,6 @@ export const ProcSearchBar = ({
setPendingExternalFacilityName("");
}, [facilityData, pendingExternalFacilityName]);
const initializeSigunData = useCallback(
(nextSidoCd: string) => {
if (nextSidoCd === "0") {
@@ -269,6 +302,19 @@ export const ProcSearchBar = ({
[sigunData],
);
// 외부 지도 진입 이벤트가 시군구 원천 조회보다 먼저 도착해도,
// 원천 목록이 준비되는 즉시 현재 시도에 맞는 선택 후보를 다시 구성한다.
useEffect(() => {
if (sidoValue === "0") {
setFilteredSigunData([{ text: "시군구", val: "0" }]);
return;
}
const prefix = sidoValue.substring(0, 2);
const filtered = sigunData.filter((item) => item.val.startsWith(prefix));
setFilteredSigunData([{ text: "시군구", val: "0" }, ...filtered]);
}, [sidoValue, sigunData]);
const onSelectValue = useCallback(
(val: string, type: string) => {
if (type === "ctpvCd") {
@@ -281,7 +327,8 @@ export const ProcSearchBar = ({
if (type === "sggCd") {
setSigunValue(val);
const sidoNm = sidoData.find((item) => item.val === sidoValue)?.text || "";
const sidoNm =
sidoData.find((item) => item.val === sidoValue)?.text || "";
const sggNm = sigunData.find((item) => item.val === val)?.text || "";
const sggCd = sigunData.find((item) => item.val === val)?.val || "";
if (sidoNm) fetchFacilitiesByRegion(sggCd, sggNm, sidoNm, facilityType);
@@ -292,9 +339,12 @@ export const ProcSearchBar = ({
setFacilityType(val);
setFacilityValue("0");
setFacilityData(defaultFacilityData());
const sidoNm = sidoData.find((item) => item.val === sidoValue)?.text || "";
const sggNm = sigunData.find((item) => item.val === sigunValue)?.text || "";
const sggCd = sigunData.find((item) => item.val === sigunValue)?.val || "";
const sidoNm =
sidoData.find((item) => item.val === sidoValue)?.text || "";
const sggNm =
sigunData.find((item) => item.val === sigunValue)?.text || "";
const sggCd =
sigunData.find((item) => item.val === sigunValue)?.val || "";
if (sidoNm) fetchFacilitiesByRegion(sggCd, sggNm, sidoNm, val);
return;
}
@@ -309,12 +359,21 @@ export const ProcSearchBar = ({
}
}
},
[defaultFacilityData, fetchFacilitiesByRegion, initializeSigunData, sigunData, sigunValue, sidoData, sidoValue, facilityType],
[
defaultFacilityData,
fetchFacilitiesByRegion,
initializeSigunData,
sigunData,
sigunValue,
sidoData,
sidoValue,
facilityType,
],
);
const handleSearch = useCallback(() => {
if (sidoValue === "0") {
alert("시도를 선택해 주세요.");
showBusinessUserMessage("시도를 선택해 주세요.");
return;
}
@@ -333,7 +392,15 @@ export const ProcSearchBar = ({
}
moveMapToCenter(gisMaps, selectedSido.center, sidoSearchZoom);
}, [gisMaps, sidoValue, sigunValue, sidoData, filteredSigunData, sigunData, sidoSearchZoom]);
}, [
gisMaps,
sidoValue,
sigunValue,
sidoData,
filteredSigunData,
sigunData,
sidoSearchZoom,
]);
useEffect(() => {
if (typeof window === "undefined") return;
@@ -357,7 +424,9 @@ export const ProcSearchBar = ({
if (nextCtpvCd !== "0") {
const prefix = nextCtpvCd.substring(0, 2);
const filtered = sigunData.filter((item) => item.val.startsWith(prefix));
const filtered = sigunData.filter((item) =>
item.val.startsWith(prefix),
);
setFilteredSigunData([{ text: "시군구", val: "0" }, ...filtered]);
}
@@ -379,9 +448,15 @@ export const ProcSearchBar = ({
}
};
window.addEventListener(INFTWT_PROC_SEARCH_EVENT, handleExternalSearch as EventListener);
window.addEventListener(
INFTWT_PROC_SEARCH_EVENT,
handleExternalSearch as EventListener,
);
return () => {
window.removeEventListener(INFTWT_PROC_SEARCH_EVENT, handleExternalSearch as EventListener);
window.removeEventListener(
INFTWT_PROC_SEARCH_EVENT,
handleExternalSearch as EventListener,
);
};
}, [gisMaps, initializeSigunData, sigunData, sidoSearchZoom]);
@@ -401,40 +476,120 @@ export const ProcSearchBar = ({
await searchLayer.showSearchResultsFromGeoJSON(layerNm, featureId);
};
if (integrated) {
const selectRootClass = "box-border !h-[44px] !w-full !p-0";
const selectTriggerClass =
"relative box-border !h-[44px] !w-full !border-0 !bg-white !px-4 !py-0 !text-[14px] !font-normal !leading-[20px] !text-[#374151] focus:!z-[2] focus:!ring-2 focus:!ring-inset focus:!ring-[#2094FA] data-[state=open]:!z-[2] data-[state=open]:!ring-2 data-[state=open]:!ring-inset data-[state=open]:!ring-[#2094FA] [&>span]:!block [&>span]:min-w-0 [&>span]:overflow-hidden [&>span]:text-ellipsis [&>span]:whitespace-nowrap [&>span]:!leading-[20px] [&>span]:pr-2 [&>svg]:!h-8 [&>svg]:!w-8 [&>svg]:shrink-0 [&>svg]:!text-[#6B7280] [&>svg]:!opacity-100";
return (
<div className="flex h-[44px] w-[656px] box-border items-center overflow-hidden rounded-[8px] bg-white p-0 shadow-[0_2px_4px_rgba(60,64,67,0.3),0_4px_10px_rgba(60,64,67,0.18)]">
<div className="group relative h-[44px] w-[192px] shrink-0 box-border">
<SelectBox
labelClass="hidden"
className={selectRootClass}
selectClass={`${selectTriggerClass} !rounded-none focus:!rounded-l-[8px] data-[state=open]:!rounded-l-[8px]`}
label=""
selectArray={sidoData}
onSelectValue={(val: any) =>
onSelectValue(val.toString(), "ctpvCd")
}
value={sidoValue}
selectContentClass="z-[101]"
/>
<span
aria-hidden="true"
className="pointer-events-none absolute right-0 top-1/2 z-[1] h-[24px] w-px -translate-y-1/2 bg-[#D5DCE5] group-focus-within:hidden"
/>
</div>
<div className="group relative h-[44px] w-[192px] shrink-0 box-border">
<SelectBox
labelClass="hidden"
className={selectRootClass}
selectClass={`${selectTriggerClass} !rounded-none`}
label=""
selectArray={filteredSigunData}
onSelectValue={(val: any) =>
onSelectValue(val.toString(), "sggCd")
}
value={sigunValue}
selectContentClass="z-[101]"
/>
<span
aria-hidden="true"
className="pointer-events-none absolute right-0 top-1/2 z-[1] h-[24px] w-px -translate-y-1/2 bg-[#D5DCE5] group-focus-within:hidden"
/>
</div>
<div className="h-[44px] w-[192px] shrink-0 box-border">
<SelectBox
labelClass="hidden"
className={selectRootClass}
selectClass={`${selectTriggerClass} !rounded-none`}
label=""
selectArray={facilityData}
onSelectValue={(val: any) =>
onSelectValue(val.toString(), "fcltCd")
}
value={facilityValue}
selectContentClass="z-[101]"
/>
</div>
<Button
color="primary"
className="box-border !h-[44px] !w-[80px] shrink-0 !rounded-none !bg-[#0279FA] !p-0 text-[14px] font-semibold leading-5 text-white"
size="default"
onClick={handleSearch}
>
조회
</Button>
</div>
);
}
return (
<div className="grid grid-cols-4 gap-4">
<div className="col-span-4">
<div className="card card-border flex">
<div className="col-span-10 flex flex-row ml-5">
<div className="col-span-10 ml-5 flex flex-row items-center">
<SelectBox
labelClass="w-[40px]"
className="mr-10 w-[150px]"
selectClass="rounded-lg bg-white"
selectClass="rounded-lg bg-background"
label=""
selectArray={sidoData}
onSelectValue={(val: any) => onSelectValue(val.toString(), "ctpvCd")}
onSelectValue={(val: any) =>
onSelectValue(val.toString(), "ctpvCd")
}
value={sidoValue}
/>
<SelectBox
labelClass="w-[65px]"
className="mr-10 w-[150px]"
selectClass="rounded-lg bg-white"
selectClass="rounded-lg bg-background"
label=""
selectArray={filteredSigunData}
onSelectValue={(val: any) => onSelectValue(val.toString(), "sggCd")}
onSelectValue={(val: any) =>
onSelectValue(val.toString(), "sggCd")
}
value={sigunValue}
/>
<SelectBox
labelClass="w-[60px]"
className="mr-5 w-[180px]"
selectClass="rounded-lg bg-white"
selectClass="rounded-lg bg-background"
label=""
selectArray={facilityData}
onSelectValue={(val: any) => onSelectValue(val.toString(), "fcltCd")}
onSelectValue={(val: any) =>
onSelectValue(val.toString(), "fcltCd")
}
value={facilityValue}
/>
<div className="flex flex-row space-x-2">
<Button color="primary" className="mx-2 mt-1" size="sm" onClick={handleSearch}>
<div className="flex flex-row items-center space-x-2">
<Button
color="primary"
className="mx-2"
size="default"
onClick={handleSearch}
>
조회
</Button>
</div>
@@ -444,4 +599,3 @@ export const ProcSearchBar = ({
</div>
);
};
@@ -2,6 +2,7 @@
import { SelectBox, type SelectDataType } from "../../../ui";
import { Button } from "@common/components/ui";
import { useCallback, useEffect, useState } from "react";
import { showBusinessUserMessage } from "../../../lib/user-message";
import SearchInputText from "./SearchInputText";
import GisApp from "../lib/gis.core";
import { getSigunguCenter, moveMapToCenter, sidoCenter } from "./utils";
@@ -38,16 +39,18 @@ export const SearchBar = ({
gisMaps,
facilityTypes,
onFeatureFocus,
onInit = () => { },
onInit = () => {},
}: SearchBarProps) => {
const [sidoValue, setSidoValue] = useState("0");
const [sigunValue, setSigunValue] = useState("0");
const [facilityType, setFacilityType] = useState(
facilityTypes?.length === 1 && facilityTypes[0] ? facilityTypes[0].val : "0"
facilityTypes?.length === 1 && facilityTypes[0]
? facilityTypes[0].val
: "0",
);
const [fcltyNm, setFcltyNm] = useState("");
const [searchList, setSearchList] = useState<{ fnm: string; fid: string }[]>(
[]
[],
);
const [sidoData, setSidoData] = useState<CenterSelectDataType[]>([
@@ -56,9 +59,9 @@ export const SearchBar = ({
const [sigunData, setSigunData] = useState<CenterSelectDataType[]>([
{ text: "시군구", val: "0" },
]);
const [filteredSigunData, setFilteredSigunData] = useState<CenterSelectDataType[]>([
{ text: "시군구", val: "0" },
]);
const [filteredSigunData, setFilteredSigunData] = useState<
CenterSelectDataType[]
>([{ text: "시군구", val: "0" }]);
const fetchSido = async () => {
const res = await fetch("/cms-service/api/v1/code/cache/ADSTDSTRCD/Y");
@@ -82,14 +85,14 @@ export const SearchBar = ({
"울산광역시",
"세종특별자치시",
"경기도",
"강원특별자치도", // 경기도 다음에 배치
"강원특별자치도", // 경기도 다음에 배치
"충청북도",
"충청남도",
"전북특별자치도", // 충청남도 다음에 배치
"전북특별자치도", // 충청남도 다음에 배치
"전라남도",
"경상북도",
"경상남도",
"제주특별자치도"
"제주특별자치도",
];
const indexA = customOrder.indexOf(a.text);
@@ -105,7 +108,7 @@ export const SearchBar = ({
if (indexB !== -1) return 1;
// 둘 다 커스텀 순서에 없으면 기본 알파벳 순서
return a.text.localeCompare(b.text, 'ko');
return a.text.localeCompare(b.text, "ko");
});
const sigunList = json
.filter((item: any) => item.lwpoCd?.length > 2)
@@ -114,7 +117,7 @@ export const SearchBar = ({
text: item.lwpoCdNm,
center: getSigunguCenter(item.lwpoCd),
}));
//.sort((a: any, b: any) => a.text.localeCompare(b.text, 'ko'));
//.sort((a: any, b: any) => a.text.localeCompare(b.text, 'ko'));
setSidoData([{ text: "시도", val: "0" }, ...sidoList]);
setSigunData(sigunList);
};
@@ -131,7 +134,7 @@ export const SearchBar = ({
setFilteredSigunData([{ text: "시군구", val: "0" }, ...filtered]);
setSigunValue("0");
},
[sigunData]
[sigunData],
);
useEffect(() => {
@@ -155,13 +158,13 @@ export const SearchBar = ({
setFcltyNm("");
}
},
[initializeSigunData]
[initializeSigunData],
);
const handleSearch = async () => {
if (!fcltyNm) {
if (sidoValue === "0") {
alert("시도를 선택해 주세요");
showBusinessUserMessage("시도를 선택해 주세요");
return;
}
@@ -206,8 +209,10 @@ export const SearchBar = ({
if (type === "tb_il_swage_prcs_fclt") {
// 하수처리시설
let cqlFilter = `swtrmt_fclt_nm like '%${fcltyNm}%'`;
if (sggNm !== "시군구" && sggNm) cqlFilter = `sgg_nm='${sggNm}' and ` + cqlFilter;
if (sidoNm !== "시도" && sidoNm) cqlFilter = `ctpv_nm='${sidoNm}' and ` + cqlFilter;
if (sggNm !== "시군구" && sggNm)
cqlFilter = `sgg_nm='${sggNm}' and ` + cqlFilter;
if (sidoNm !== "시도" && sidoNm)
cqlFilter = `ctpv_nm='${sidoNm}' and ` + cqlFilter;
url += encodeURIComponent(cqlFilter);
const res = await fetch(url);
const json = await res.json();
@@ -241,7 +246,7 @@ export const SearchBar = ({
});
const procJson2 = await procRes2.json();
const procResult2 = (procJson2.data || []).map(
(item: any) => item.bscFctCd
(item: any) => item.bscFctCd,
);
const res = await fetch(url, {
@@ -284,7 +289,7 @@ export const SearchBar = ({
}
if (list.length === 0) {
alert("검색 결과가 없습니다.");
showBusinessUserMessage("검색 결과가 없습니다.");
setSearchList([]);
setFcltyNm("");
return;
@@ -348,7 +353,7 @@ export const SearchBar = ({
nearest: true,
});
} else {
alert("위치정보를 찾을 수 없습니다.");
showBusinessUserMessage("위치정보를 찾을 수 없습니다.");
console.warn("geometry를 찾을 수 없습니다:", data);
}
} else {
@@ -383,12 +388,12 @@ export const SearchBar = ({
<div className="grid grid-cols-4 gap-4">
<div className="col-span-4">
<div className="card card-border flex">
<div className="col-span-10 flex flex-row">
<div className="col-span-10 flex flex-row items-center">
{facilityTypes.length > 1 && (
<SelectBox
labelClass="w-[120px]"
className="mr-5 w-[150px]"
selectClass="rounded-lg bg-white"
selectClass="rounded-lg bg-background"
label=""
selectArray={[
{ text: "시설 구분", val: "0" },
@@ -403,7 +408,7 @@ export const SearchBar = ({
<SelectBox
labelClass="w-[40px]"
className="mr-5 w-[150px]"
selectClass="rounded-lg bg-white"
selectClass="rounded-lg bg-background"
label=""
selectArray={sidoData}
onSelectValue={(val: any) =>
@@ -414,7 +419,7 @@ export const SearchBar = ({
<SelectBox
labelClass="w-[65px]"
className="mr-5 w-[150px]"
selectClass="rounded-lg bg-white"
selectClass="rounded-lg bg-background"
label=""
selectArray={filteredSigunData}
onSelectValue={(val: any) =>
@@ -439,20 +444,20 @@ export const SearchBar = ({
className="mr-5 w-[150px]"
/>
</div>
<div className="flex flex-row space-x-2">
<div className="flex flex-row items-center space-x-2">
<Button
color="primary"
className="mx-2 mt-1"
size="sm"
className="mx-2"
size="default"
onClick={handleSearch}
>
조회
</Button>
{onInit && (
<Button
color="primary"
className="mx-2 mt-1"
size="sm"
color="white"
className="mx-2"
size="default"
onClick={handleInit}
>
초기화
@@ -463,4 +468,4 @@ export const SearchBar = ({
</div>
</div>
);
}
};
@@ -1,4 +1,6 @@
import { Button, Input } from "@common/components";
"use client";
import { Button, Input } from "@common/components";
import { AsYouType } from "libphonenumber-js";
import React, { useCallback, useEffect, useState } from "react";
import type { ControllerRenderProps, UseFormReturn } from "react-hook-form";
@@ -66,9 +68,9 @@ interface FormSchema {
interface SdmRegFormProps {
form: UseFormReturn<FormSchema>;
onCheckboxChange?: (checked: boolean) => void;
selectSidoData: SelectDataType[]; //시/도 데이터
selectSidoData: SelectDataType[]; //시/도 데이터
selectSigunData: SelectDataType[]; //시/군/구 데이터
dataList: DemandCompType[]; //수요처 목록
dataList: DemandCompType[]; //수요처 목록
rtnValue: (searchText: string, pageCnt: number) => void;
setIsDuplicate: (value: boolean) => void;
updateList?: DemandCompType;
@@ -82,8 +84,8 @@ type FieldComponent = (
const getReadonlyInputClassName = (isReadonly?: boolean) =>
isReadonly
? "!text-xl text-gray-600 bg-gray-100 cursor-default"
: "!text-xl text-gray-600";
? "cursor-default bg-secondary !text-xl text-muted-foreground"
: "!text-xl text-label";
export function SdmRegForm({
form,
@@ -320,203 +322,208 @@ export function SdmRegForm({
form.setValue("zip", zoneNo, { shouldValidate: true });
}, [form, zoneNo]);
const formFields: Array<{
name: keyof FormSchema;
label: string;
component: FieldComponent;
}> = [
{
name: "dmdCoNm",
label: "회사명",
component: (field) => (
<SdmSearchForm
rtnData={setRtnData}
label="수요처명"
initValue={updateCoNm}
dataList={dataList}
rtnValue={setRtnValue}
rtnText={setRtnText}
readOnly={readOnly}
{...field}
/>
),
},
{
name: "dmdInfoId",
label: "사업자등록번호",
component: (field) => (
{
name: "dmdCoNm",
label: "회사명",
component: (field) => (
<SdmSearchForm
rtnData={setRtnData}
label="수요처명"
initValue={updateCoNm}
dataList={dataList}
rtnValue={setRtnValue}
rtnText={setRtnText}
readOnly={readOnly}
{...field}
/>
),
},
{
name: "dmdInfoId",
label: "사업자등록번호",
component: (field) => (
<Input
placeholder="사업자등록번호를 입력하세요"
type="text"
className={getReadonlyInputClassName(readOnly)}
onChange={(e) => bznNoChange(e, "dmdInfoId", field)}
value={formatBusinessNumber(field.value ?? "")}
readOnly={!!readOnly}
/>
),
},
{
name: "bznmTotNo",
label: "",
component: (field) => (
<FormUi
label="종사업자등록번호"
onCheckboxChange={handleCheckboxChange}
isDisabled={isBznmTotNoDisabled}
>
<Input
placeholder="사업자등록번호를 입력하세요"
placeholder="여러사업장이 있을 경우 입력해주세요"
type="text"
className={getReadonlyInputClassName(readOnly)}
onChange={(e) => bznNoChange(e, "dmdInfoId", field)}
value={formatBusinessNumber(field.value ?? "")}
className={`${getReadonlyInputClassName(readOnly)} !mt-5`}
disabled={isBznmTotNoDisabled}
onChange={(e) => bznNoChange(e, "bznmTotNo", field)}
// {...field}
value={field.value ?? ""}
readOnly={!!readOnly}
/>
),
},
{
name: "bznmTotNo",
label: "",
component: (field) => (
<FormUi
label="종사업자등록번호"
onCheckboxChange={handleCheckboxChange}
isDisabled={isBznmTotNoDisabled}
>
<Input
placeholder="여러사업장이 있을 경우 입력해주세요"
type="text"
className={`${getReadonlyInputClassName(readOnly)} !mt-5`}
disabled={isBznmTotNoDisabled}
onChange={(e) => bznNoChange(e, "bznmTotNo", field)}
// {...field}
value={field.value ?? ""}
readOnly={!!readOnly}
/>
</FormUi>
),
},
{
name: "daddr",
label: "사업자주소",
component: (field) =>
openNetwork ? (
<div>
<div className="flex items-center gap-2">
{/* 우편번호 */}
<Input
type="text"
className={`${getReadonlyInputClassName(true)} w-64`}
readOnly={true}
value={form.watch("zip") ?? ""}
placeholder="우편번호"
/>
<Button type="button" className="px-4 py-2 rounded-md" onClick={() => setIsZipModalOpen(true)}>우편번호 검색</Button>
</div>
{/* 주소 */}
</FormUi>
),
},
{
name: "daddr",
label: "사업자주소",
component: (field) =>
openNetwork ? (
<div>
<div className="flex items-center gap-2">
{/* 우편번호 */}
<Input
type="text"
className={getReadonlyInputClassName(true)}
className={`${getReadonlyInputClassName(true)} w-64`}
readOnly={true}
value={address ?? ""}
placeholder="주소"
/>
{/* 상세 주소 */}
<Input
placeholder="상세 주소를 입력하세요"
type="text"
className={getReadonlyInputClassName(readOnly)}
readOnly={readOnly}
onChange={(e) => {
const value = e.target.value;
setDetailedAddress(value);
form.setValue("daddr2", value, { shouldValidate: true });
}}
value={detailedAddress ?? ""}
value={form.watch("zip") ?? ""}
placeholder="우편번호"
/>
<Button
type="button"
className="rounded-md px-4 py-2"
onClick={() => setIsZipModalOpen(true)}
>
우편번호 검색
</Button>
</div>
) : (
{/* 주소 */}
<Input
placeholder="주소를 입력하세요"
type="text"
className={getReadonlyInputClassName(readOnly)}
readOnly={readOnly}
{...field}
value={field.value ?? ""}
className={getReadonlyInputClassName(true)}
readOnly={true}
value={address ?? ""}
placeholder="주소"
/>
),
},
{
name: "ctpvCd",
label: "시도",
component: (field) => (
<Input
placeholder="시도"
type="text"
className={getReadonlyInputClassName(true)}
onChange={(e) => {
field.onChange(e.target.value);
}}
value={
selectSidoData.find((item) => item.val === field.value?.trim())
?.text ?? ""
}
readOnly={true}
/>
),
},
{
name: "sggCd",
label: "시군구",
component: (field) => (
<Input
placeholder="시군구"
type="text"
className={getReadonlyInputClassName(true)}
onChange={(e) => {
field.onChange(e.target.value);
}}
value={
selectSigunData.find((item) => item.val === field.value?.trim())
?.text ?? ""
}
readOnly={true}
/>
),
},
{
name: "telno",
label: "전화번호",
component: (field) => {
const formattedValue = formatPhoneNumber(field.value ?? ""); // 초기 렌더링 시에도 포맷 적용
return (
{/* 상세 주소 */}
<Input
placeholder="전화번호를 입력하세요"
placeholder="상세 주소를 입력하세요"
type="text"
className={getReadonlyInputClassName(readOnly)}
value={formattedValue}
readOnly={readOnly}
onChange={(e) => {
const value = e.target.value.replace(/\D/g, ""); // 숫자만 저장
field.onChange(value);
const value = e.target.value;
setDetailedAddress(value);
form.setValue("daddr2", value, { shouldValidate: true });
}}
value={detailedAddress ?? ""}
/>
);
},
},
</div>
) : (
<Input
placeholder="주소를 입력하세요"
type="text"
className={getReadonlyInputClassName(readOnly)}
readOnly={readOnly}
{...field}
value={field.value ?? ""}
/>
),
},
{
name: "ctpvCd",
label: "시도",
component: (field) => (
<Input
placeholder="시도"
type="text"
className={getReadonlyInputClassName(true)}
onChange={(e) => {
field.onChange(e.target.value);
}}
value={
selectSidoData.find((item) => item.val === field.value?.trim())
?.text ?? ""
}
readOnly={true}
/>
),
},
{
name: "sggCd",
label: "시군구",
component: (field) => (
<Input
placeholder="시군구"
type="text"
className={getReadonlyInputClassName(true)}
onChange={(e) => {
field.onChange(e.target.value);
}}
value={
selectSigunData.find((item) => item.val === field.value?.trim())
?.text ?? ""
}
readOnly={true}
/>
),
},
{
name: "telno",
label: "전화번호",
component: (field) => {
const formattedValue = formatPhoneNumber(field.value ?? ""); // 초기 렌더링 시에도 포맷 적용
{
name: "dmdAplyPswd",
label: "패스워드",
component: (field) => (
return (
<Input
placeholder="패스워드를 입력하세요"
type="password"
placeholder="전화번호를 입력하세요"
type="text"
className={getReadonlyInputClassName(readOnly)}
value={formattedValue}
readOnly={readOnly}
{...field}
value={field.value ?? ""}
onChange={(e) => {
const value = e.target.value.replace(/\D/g, ""); // 숫자만 저장
field.onChange(value);
}}
/>
),
);
},
{
name: "dmdAplyPswdConfirm",
label: "패스워드확인",
component: (field) => (
<Input
placeholder="패스워드를 입력하세요"
type="password"
className={getReadonlyInputClassName(readOnly)}
readOnly={readOnly}
{...field}
value={field.value ?? ""}
/>
),
},
];
},
{
name: "dmdAplyPswd",
label: "패스워드",
component: (field) => (
<Input
placeholder="패스워드를 입력하세요"
type="password"
className={getReadonlyInputClassName(readOnly)}
readOnly={readOnly}
{...field}
value={field.value ?? ""}
/>
),
},
{
name: "dmdAplyPswdConfirm",
label: "패스워드확인",
component: (field) => (
<Input
placeholder="패스워드를 입력하세요"
type="password"
className={getReadonlyInputClassName(readOnly)}
readOnly={readOnly}
{...field}
value={field.value ?? ""}
/>
),
},
];
return (
<>
@@ -550,18 +557,21 @@ export function SdmRegForm({
<div className="mb-4">
<label
htmlFor={inputId}
className="block text-xl font-medium text-gray-800"
className="block text-xl font-medium text-label"
>
{label}
{isRequired && <span className="ml-1 text-red-500">*</span>}
</label>
{React.cloneElement(component(field) as React.ReactElement<any>, {
id: inputId,
"aria-required": isRequired,
"aria-invalid": !!error,
"aria-describedby": error ? errorId : undefined,
})}
{React.cloneElement(
component(field) as React.ReactElement<any>,
{
id: inputId,
"aria-required": isRequired,
"aria-invalid": !!error,
"aria-describedby": error ? errorId : undefined,
},
)}
{error?.message && (
<p
@@ -16,73 +16,95 @@ type thisProps = {
rtnValue: (searchText: string, pageCnt: number) => void;
rtnInputData: (data: DemandCompType) => void;
bodyClassNm?: string;
updateList?:DemandCompType;
readOnly?:boolean;
openNetwork:boolean;
}
updateList?: DemandCompType;
readOnly?: boolean;
openNetwork: boolean;
};
const createFormSchema = (isBznmTotNoDisabled: boolean, isDuplicate: boolean ,updateList?:DemandCompType) => z.object({
ctpvCd: z.string().min(1, "시/도를 선택해주세요"),
sggCd: z.string().min(1, "시/군/구를 선택해주세요"),
dmdCoNm: z.string()
.min(1, "회사명을 입력해주세요")
.max(20, "회사명은 20자 이내로 입력해주세요"),
dmdInfoId: z.string()
.min(1, "사업자등록번호를 입력해주세요")
.regex(/^\d{10}$/, "사업자등록번호는 10자리 숫자만 입력 가능합니다")
.refine(() => isBznmTotNoDisabled ? !isDuplicate : true, "이미 등록된 사업자등록번호입니다"),
zip: z.string().optional(),
bznmTotNo: isBznmTotNoDisabled
? z.string().optional()
: z.string()
.length(4, "종사업자등록번호는 4자리 숫자만 입력 가능합니다")
.refine(() => !isDuplicate, "이미 등록된 사업자등록번호입니다"),
daddr: z.string()
.min(1, "주소를 입력해주세요")
// .min(6, "주소는 6자 이상 입력해주세요")
.max(40, "주소는 40자 이내로 입력해주세요"),
daddr2: z.string().optional(),
telno: z.string()
.min(8, "전화번호는 8자 이상 입력해주세요")
.max(11, "전화번호는 11자 이내로 입력해주세요")
.regex(/^[0-9]+$/, "전화번호는 숫자만 입력 가능합니다"),
rgtr: z.string().optional(),
mdfr: z.string().nullish(),
dmdAplyPswd : updateList?.dmdInfoId // 업데이트일경우
? z.string().optional() // 패스워드는 선택 사항이며 길이 제한 없음
: z.string().optional()
.refine((val) => !val || (val.length >= 8 && val.length <= 16), "패스워드는 8자 이상 16자 이내로 입력해주세요"),
dmdAplyPswdConfirm: updateList?.dmdInfoId // 업데이트일경우
? z.string().optional() // 패스워드는 선택 사항이며 길이 제한 없음
:z.string()
.min(1, "패스워드확인을 입력해주세요"),
}).refine((data) => {
// 패스워드 확인 검증
if (data.dmdAplyPswd && data.dmdAplyPswdConfirm) {
return data.dmdAplyPswd === data.dmdAplyPswdConfirm;
}
return true;
}, {
message: "패스워드가 일치하지 않습니다",
path: ["dmdAplyPswdConfirm"], // 에러를 패스워드 확인 필드에 표시
});
const createFormSchema = (
isBznmTotNoDisabled: boolean,
isDuplicate: boolean,
updateList?: DemandCompType,
) =>
z
.object({
ctpvCd: z.string().min(1, "시/도를 선택해주세요"),
sggCd: z.string().min(1, "시/군/구를 선택해주세요"),
dmdCoNm: z
.string()
.min(1, "회사명을 입력해주세요")
.max(20, "회사명은 20자 이내로 입력해주세요"),
dmdInfoId: z
.string()
.min(1, "사업자등록번호를 입력해주세요")
.regex(/^\d{10}$/, "사업자등록번호는 10자리 숫자만 입력 가능합니다")
.refine(
() => (isBznmTotNoDisabled ? !isDuplicate : true),
"이미 등록된 사업자등록번호입니다",
),
zip: z.string().optional(),
bznmTotNo: isBznmTotNoDisabled
? z.string().optional()
: z
.string()
.length(4, "종사업자등록번호는 4자리 숫자만 입력 가능합니다")
.refine(() => !isDuplicate, "이미 등록된 사업자등록번호입니다"),
daddr: z
.string()
.min(1, "주소를 입력해주세요")
// .min(6, "주소는 6자 이상 입력해주세요")
.max(40, "주소는 40자 이내로 입력해주세요"),
daddr2: z.string().optional(),
telno: z
.string()
.min(8, "전화번호는 8자 이상 입력해주세요")
.max(11, "전화번호는 11자 이내로 입력해주세요")
.regex(/^[0-9]+$/, "전화번호는 숫자만 입력 가능합니다"),
rgtr: z.string().optional(),
mdfr: z.string().nullish(),
dmdAplyPswd: updateList?.dmdInfoId // 업데이트일경우
? z.string().optional() // 패스워드는 선택 사항이며 길이 제한 없음
: z
.string()
.optional()
.refine(
(val) => !val || (val.length >= 8 && val.length <= 16),
"패스워드는 8자 이상 16자 이내로 입력해주세요",
),
dmdAplyPswdConfirm: updateList?.dmdInfoId // 업데이트일경우
? z.string().optional() // 패스워드는 선택 사항이며 길이 제한 없음
: z.string().min(1, "패스워드확인을 입력해주세요"),
})
.refine(
(data) => {
// 패스워드 확인 검증
if (data.dmdAplyPswd && data.dmdAplyPswdConfirm) {
return data.dmdAplyPswd === data.dmdAplyPswdConfirm;
}
return true;
},
{
message: "패스워드가 일치하지 않습니다",
path: ["dmdAplyPswdConfirm"], // 에러를 패스워드 확인 필드에 표시
},
);
type FormSchema = z.infer<ReturnType<typeof createFormSchema>>;
const defaultValues: FormSchema = {
ctpvCd: '',
sggCd: '',
dmdCoNm: '',
dmdInfoId: '',
zip: '',
bznmTotNo: '',
daddr: '',
daddr2: '',
telno: '',
rgtr: '',
mdfr: '',
dmdAplyPswd: '',
dmdAplyPswdConfirm: '',
ctpvCd: "",
sggCd: "",
dmdCoNm: "",
dmdInfoId: "",
zip: "",
bznmTotNo: "",
daddr: "",
daddr2: "",
telno: "",
rgtr: "",
mdfr: "",
dmdAplyPswd: "",
dmdAplyPswdConfirm: "",
};
/**
@@ -92,14 +114,26 @@ const defaultValues: FormSchema = {
* @param dataList 수요처 목록
* @param rtnValue 검색 결과(텍스트) 콜백
* @param rtnInputData 수요처관리 콜백 : 등록/수정 처리
* @returns
* @returns
*/
export default function SdmInsertForm({selectSidoData, selectSigunData, dataList, rtnValue, rtnInputData
, bodyClassNm, updateList, readOnly, openNetwork}: thisProps) {
export default function SdmInsertForm({
selectSidoData,
selectSigunData,
dataList,
rtnValue,
rtnInputData,
bodyClassNm,
updateList,
readOnly,
openNetwork,
}: thisProps) {
const [isBznmTotNoDisabled, setIsBznmTotNoDisabled] = useState(false); // 종사업자등록번호 해당없음
const [isDuplicate, setIsDuplicate] = useState(false);
const formSchema = createFormSchema(isBznmTotNoDisabled, isDuplicate, updateList );
const formSchema = createFormSchema(
isBznmTotNoDisabled,
isDuplicate,
updateList,
);
const form = useForm<FormSchema>({
resolver: zodResolver(formSchema),
@@ -107,37 +141,40 @@ export default function SdmInsertForm({selectSidoData, selectSigunData, dataList
mode: "onChange",
criteriaMode: "all",
shouldFocusError: false,
shouldUnregister: false
shouldUnregister: false,
});
// 체크박스 상태가 변경될 때마다 bznmTotNo 필드의 에러를 초기화
useEffect(() => {
if (isBznmTotNoDisabled===true) {
form.clearErrors('bznmTotNo');
form.setValue('bznmTotNo', '');
if (isBznmTotNoDisabled === true) {
form.clearErrors("bznmTotNo");
form.setValue("bznmTotNo", "");
}
}, [isBznmTotNoDisabled, form]);
const setRtnValue = useCallback((searchText: string, pageCnt: number) => {
rtnValue(searchText, pageCnt);
}, [rtnValue]);
const setRtnValue = useCallback(
(searchText: string, pageCnt: number) => {
rtnValue(searchText, pageCnt);
},
[rtnValue],
);
const onSubmit: SubmitHandler<FormSchema> = async (data) => {
try {
// form 에러 체크
const formErrors = form.formState.errors;
const myUUID = getCookie('token-id') ||'c475824c-0e82-4a06-a282-2b55a20df265';
if (Object.keys(formErrors).length > 0 ) {
const errorMessage = Object.values(formErrors)[0]?.message || '입력값을 확인해주세요.';
const myUUID =
getCookie("token-id") || "c475824c-0e82-4a06-a282-2b55a20df265";
if (Object.keys(formErrors).length > 0) {
const errorMessage =
Object.values(formErrors)[0]?.message || "입력값을 확인해주세요.";
toast.error(errorMessage);
return;
}
const dmdInfoId = data.dmdInfoId + (data.bznmTotNo || '0000');
const dmdInfoId = data.dmdInfoId + (data.bznmTotNo || "0000");
const formData = {
...data,
dmdCoSn: updateList?.dmdCoSn ?? "",
@@ -145,32 +182,40 @@ export default function SdmInsertForm({selectSidoData, selectSigunData, dataList
bzmnNo: data.dmdInfoId,
daddr: data.daddr?.trim() || "",
daddr2: data.daddr2?.trim() || "",
rgtr: myUUID ,
rgtr: myUUID,
};
/* await insertSdmData(formData); */
rtnInputData(formData as unknown as DemandCompType); // 수요처 등록/수정 처리
//router.push(`/pages/sdmMng/sdmInfoInsert?${queryParams.toString()}`);
} catch (error) {
console.error('Error submitting form:', error);
console.error("Error submitting form:", error);
}
};
return (
<>
<div className="mb-8">
<h2 className="px-[1.8rem] pt-[2rem] text-[2.4rem] font-semibold text-title">
{!updateList ? '수요처 등록' : readOnly == true ? '수요처 상세정보' : '수요처 수정'}
{!updateList
? "수요처 등록"
: readOnly == true
? "수요처 상세정보"
: "수요처 수정"}
</h2>
</div>
<div className= {bodyClassNm?bodyClassNm:"!max-w-3xl mx-auto bg-white rounded-lg shadow-md p-6"}>
<div
className={
bodyClassNm
? bodyClassNm
: "mx-auto !max-w-3xl rounded-lg bg-background p-6 shadow-md"
}
>
<FormProvider {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<SdmRegForm
<SdmRegForm
form={form}
onCheckboxChange={setIsBznmTotNoDisabled}
selectSidoData={selectSidoData}
@@ -183,16 +228,16 @@ export default function SdmInsertForm({selectSidoData, selectSigunData, dataList
openNetwork={openNetwork}
/>
<div className="flex justify-center pt-4">
{readOnly==true?<>
</>:
<Button
type="submit"
className="w-32 bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded-md transition-colors duration-200"
>
{updateList ?'수정' :'등록'}
</Button>
}
{readOnly == true ? (
<></>
) : (
<Button
type="submit"
className="hover:bg-primary/90 w-32 rounded-md bg-primary px-4 py-2 font-semibold text-primary-foreground transition-colors duration-200"
>
{updateList ? "수정" : "등록"}
</Button>
)}
</div>
</form>
</FormProvider>
@@ -1,4 +1,6 @@
import React, { useCallback, useEffect, useRef, useState } from "react";
"use client";
import React, { useCallback, useEffect, useRef, useState } from "react";
import type { DemandCompType } from "./form";
export type thisProps = {
@@ -8,7 +10,7 @@ export type thisProps = {
rtnValue: (searchText: string, pageCnt: number) => void;
rtnData: (item: DemandCompType) => void;
rtnText: (text: string) => void;
readOnly?:boolean
readOnly?: boolean;
};
/**
@@ -26,7 +28,7 @@ export const SdmSearchForm = ({
dataList = [],
rtnData = () => {},
rtnText = () => {},
readOnly
readOnly,
}: thisProps) => {
const [isOpen, setIsOpen] = useState(false);
const [textValue, setTextValue] = useState(initValue || "");
@@ -84,18 +86,18 @@ export const SdmSearchForm = ({
value={textValue}
onChange={handleInputChange}
/* onFocus={() => setIsOpen(true)} */
className="h-[3.2rem] w-full rounded-md border border-gray-300 pl-3 !text-xl text-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
className="h-[3.2rem] w-full rounded-md border border-input bg-background pl-3 !text-xl text-label focus:outline-none focus:ring-2 focus:ring-ring"
placeholder={`${label}을(를) 입력하세요`}
readOnly={readOnly}
/>
{isOpen && (
<div className="absolute top-full left-0 z-50 mb-2 max-h-72 w-full overflow-auto rounded-md border border-gray-300 bg-white shadow-lg">
<div className="absolute left-0 top-full z-50 mb-2 max-h-72 w-full overflow-auto rounded-md border border-border bg-popover text-popover-foreground shadow-lg">
<div className="max-h-72">
{dataList && dataList.length > 0 ? (
dataList.map((item: DemandCompType, index: number) => (
<div
key={index}
className="w-full cursor-pointer overflow-auto px-5 py-3 text-left !text-xl hover:bg-gray-100"
className="w-full cursor-pointer overflow-auto px-5 py-3 text-left !text-xl hover:bg-accent hover:text-accent-foreground"
onClick={() => handleSuggestionClick(item)}
role="button"
tabIndex={0}
@@ -107,16 +109,20 @@ export const SdmSearchForm = ({
>
{item.dmdInfoId.substring(10, 14) !== "0000" ? (
<>
<span className="text-gray-500">사업자번호 : </span>{" "}
<span className="text-muted-foreground">
사업자번호 :{" "}
</span>{" "}
{item.dmdInfoId.substring(0, 10)}&nbsp;
<span className="text-gray-500">
<span className="text-muted-foreground">
종사업자번호 :{" "}
</span>{" "}
{item.dmdInfoId.substring(10, 14)}&nbsp;
</>
) : (
<>
<span className="text-gray-500">사업자번호 : </span>{" "}
<span className="text-muted-foreground">
사업자번호 :{" "}
</span>{" "}
{item.dmdInfoId.substring(0, 10)}&nbsp;
</>
)}
@@ -124,7 +130,7 @@ export const SdmSearchForm = ({
</div>
))
) : (
<div className="w-full cursor-pointer overflow-auto px-5 py-3 !text-xl hover:bg-gray-100">
<div className="w-full cursor-pointer overflow-auto px-5 py-3 !text-xl hover:bg-accent hover:text-accent-foreground">
검색 결과가 없습니다.
</div>
)}
@@ -1,3 +1,5 @@
"use client";
/**
* 주소검색
*/
@@ -21,9 +23,9 @@ interface SearchAddressModalProps {
/**
* 주소 검색 값 감시
* @param value
* @param delay
* @returns
* @param value
* @param delay
* @returns
*/
function useDebouncedValue<T>(value: T, delay = 250) {
const [debouncedValue, setDebouncedValue] = useState(value);
@@ -36,7 +38,11 @@ function useDebouncedValue<T>(value: T, delay = 250) {
return debouncedValue;
}
export function SearchAddressModal({ open, onOpenChange, onSelect }: SearchAddressModalProps) {
export function SearchAddressModal({
open,
onOpenChange,
onSelect,
}: SearchAddressModalProps) {
const PAGE_SIZE = 10;
const [curPage, setCurPage] = useState<number>(1);
const [searchInput, setSearchInput] = useState<string>("");
@@ -46,9 +52,13 @@ export function SearchAddressModal({ open, onOpenChange, onSelect }: SearchAddre
const [searchMessage, setSearchMessage] = useState<string>("");
const [suggestions, setSuggestions] = useState<string[]>([]);
const [showSuggestions, setShowSuggestions] = useState<boolean>(true);
const [searchQuery, setSearchQuery] = useState<ZipSearchParams | undefined>(undefined);
const [searchQuery, setSearchQuery] = useState<ZipSearchParams | undefined>(
undefined,
);
const [isResetPage, setIsResetPage] = useState<boolean>(false);
const [selectedRowIndex, setSelectedRowIndex] = useState<number | undefined>(undefined);
const [selectedRowIndex, setSelectedRowIndex] = useState<number | undefined>(
undefined,
);
const [selectedZip, setSelectedZip] = useState<Zip>();
const [isSelectedZip, setIsSelectedZip] = useState<boolean>(false);
@@ -195,16 +205,20 @@ export function SearchAddressModal({ open, onOpenChange, onSelect }: SearchAddre
}
};
const showSuggest = open && showSuggestions && searchInput.trim().length >= 1 && suggestions.length > 0;
const showSuggest =
open &&
showSuggestions &&
searchInput.trim().length >= 1 &&
suggestions.length > 0;
return (
<UiModal
headerTitle="주소 검색"
headerTitleClass="text-2xl font-bold text-gray-900"
headerTitleClass="text-2xl font-bold text-foreground"
open={open}
onOpenChange={onOpenChange}
bodyClass={`
${zipTotalElements > -1 ? 'h-[80vh]' : 'h-[30vh]'}
${zipTotalElements > -1 ? "h-[80vh]" : "h-[30vh]"}
w-[30vw]
min-w-[500px]
max-w-[90vw]
@@ -221,10 +235,7 @@ export function SearchAddressModal({ open, onOpenChange, onSelect }: SearchAddre
`}
body={
<>
<form
onSubmit={handleSearch}
className="mb-4 w-full space-y-2"
>
<form onSubmit={handleSearch} className="mb-4 w-full space-y-2">
<div className="card card-border !m-0 flex flex-col gap-3 p-4">
<div className="relative">
<div className="flex items-center gap-4">
@@ -239,30 +250,37 @@ export function SearchAddressModal({ open, onOpenChange, onSelect }: SearchAddre
className="!text-[1.3rem]"
/>
{showSuggest && (
<div className="absolute left-0 right-0 top-[calc(100%+6px)] z-50 overflow-hidden rounded-md border border-gray-200 bg-white shadow-lg">
<div className="absolute left-0 right-0 top-[calc(100%+6px)] z-50 overflow-hidden rounded-md border border-border bg-popover text-popover-foreground shadow-lg">
{suggestions.map((suggestion) => (
<button
key={suggestion}
type="button"
className="flex w-full items-center justify-between px-4 py-3 text-left text-sm hover:bg-gray-50"
className="flex w-full items-center justify-between px-4 py-3 text-left text-sm hover:bg-accent hover:text-accent-foreground"
onClick={() => {
setSearchInput(suggestion);
setShowSuggestions(false);
setSuggestions([]);
}}
>
<span className="truncate text-gray-800">{suggestion}</span>
<span className="ml-4 text-gray-400">↵</span>
<span className="truncate text-label">
{suggestion}
</span>
<span className="ml-4 text-muted-foreground">
↵
</span>
</button>
))}
</div>
)}
</div>
<Button className="rounded-md shrink-0" type="submit">검색</Button>
<Button className="shrink-0 rounded-md" type="submit">
검색
</Button>
</div>
</div>
<div className="text-sm text-gray-600">
{searchMessage || "도로명과 건물번호를 함께 입력해 주세요. 예) 테헤란로 152-1"}
<div className="text-sm text-muted-foreground">
{searchMessage ||
"도로명과 건물번호를 함께 입력해 주세요. 예) 테헤란로 152-1"}
</div>
</div>
</form>
@@ -288,7 +306,11 @@ export function SearchAddressModal({ open, onOpenChange, onSelect }: SearchAddre
</div>
)}
{zipTotalElements === 0 && (
<div className={cn("flex h-96 flex-col items-center justify-center gap-4")}>
<div
className={cn(
"flex h-96 flex-col items-center justify-center gap-4",
)}
>
<i className="diveicon di-info-circle text-3xl" />
조회된 데이터가 없습니다.
</div>
@@ -296,9 +318,22 @@ export function SearchAddressModal({ open, onOpenChange, onSelect }: SearchAddre
</>
}
footerContent={
<div className="w-full flex justify-center items-center gap-4">
<Button className="rounded-md" size="lg" onClick={handleConfirm} disabled={!isSelectedZip}>선택</Button>
<Button className="rounded-md" size="lg" onClick={() => onOpenChange(false)}>취소</Button>
<div className="flex w-full items-center justify-center gap-4">
<Button
className="rounded-md"
size="lg"
onClick={handleConfirm}
disabled={!isSelectedZip}
>
선택
</Button>
<Button
className="rounded-md"
size="lg"
onClick={() => onOpenChange(false)}
>
취소
</Button>
</div>
}
useDirectRender={true}
@@ -1,9 +1,10 @@
import { showBusinessUserMessage } from "../../lib/user-message";
interface SortConfig {
empty: boolean;
sorted: boolean;
unsorted: boolean;
}
interface PageableConfig {
sort: SortConfig;
offset: number;
@@ -138,7 +139,7 @@ export function searchFilter(search: string): boolean {
const expText = /[%=><]/;
if (expText.test(search)) {
alert("특수문자를 입력 할수 없습니다.");
showBusinessUserMessage("특수문자를 입력 할수 없습니다.");
return false;
}
@@ -160,7 +161,7 @@ export function searchFilter(search: string): boolean {
for (const sqlWord of sqlArray) {
const regex = new RegExp(sqlWord, "gi");
if (regex.test(search)) {
alert(`"${sqlWord}"와(과) 같은 특정문자로 검색할 수 없습니다.`);
showBusinessUserMessage(`"${sqlWord}"와(과) 같은 특정문자로 검색할 수 없습니다.`);
return false;
}
}
@@ -3,6 +3,7 @@
// const addresssKey = 'devU01TX0FVVEgyMDI1MDgyNTEwMzkwNDExNjEwNTM='; //인증키 만료일은 2025-11-23
import type { Zip, ZipSearchParams } from "./zipService";
import { showBusinessUserMessage } from "../../lib/user-message";
/**
* 주소 API 응답 타입
@@ -80,7 +81,6 @@ export const findAddress = async (searchQuery: ZipSearchParams): Promise<any> =>
}
export const searchFilter = (search: string) => {
@@ -88,7 +88,7 @@ export const searchFilter = (search: string) => {
//특수문자 제거
const expText = /[%=><]/;
if (expText.test(search) == true) {
alert("특수문자를 입력 할수 없습니다.");
showBusinessUserMessage("특수문자를 입력 할수 없습니다.");
search = search.split(expText).join("");
return false;
}
@@ -105,7 +105,7 @@ export const searchFilter = (search: string) => {
regex = new RegExp(sqlArray[i] as string, "gi");
if (regex.test(search)) {
alert("\"" + sqlArray[i] + "\"와(과) 같은 특정문자로 검색할 수 없습니다.");
showBusinessUserMessage("\"" + sqlArray[i] + "\"와(과) 같은 특정문자로 검색할 수 없습니다.");
search = search.replace(regex, "");
return false;
}
@@ -1,3 +1,5 @@
"use client";
// import { Input } from "@common/components/ui";
// import React, { useCallback, useEffect, useRef, useState } from "react";
// import { findAddress, searchFilter, type addressType } from "./findAddress";
@@ -91,18 +93,18 @@
// value={textValue}
// onChange={handleInputChange}
// /* onFocus={() => setIsOpen(true)} */
// className="h-[3.2rem] w-full rounded-md border border-gray-300 pl-3 !text-xl text-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
// className="h-[3.2rem] w-full rounded-md border border-input bg-background pl-3 !text-xl text-label focus:outline-none focus:ring-2 focus:ring-ring"
// placeholder={`주소를 입력하세요`}
// readOnly={readonly}
// />
// {isOpen && (
// <div className="absolute left-0 right-0 z-50 mt-2 max-h-72 overflow-auto rounded-md border border-gray-300 bg-white shadow-lg">
// <div className="absolute left-0 right-0 z-50 mt-2 max-h-72 overflow-auto rounded-md border border-border bg-popover text-popover-foreground shadow-lg">
// <div className="max-h-72">
// {searchList && searchList.length > 0 ? (
// searchList.map((item: addressType, index: number) => (
// <div
// key={index}
// className="w-full cursor-pointer overflow-auto px-5 py-3 text-left !text-xl hover:bg-gray-100"
// className="w-full cursor-pointer overflow-auto px-5 py-3 text-left !text-xl hover:bg-accent hover:text-accent-foreground"
// onClick={() => handleSuggestionClick(item.roadAddrPart1)}
// role="button"
// tabIndex={0}
@@ -117,7 +119,7 @@
// </div>
// ))
// ) : (
// <div className="w-full cursor-pointer overflow-auto px-5 py-3 !text-xl hover:bg-gray-100">
// <div className="w-full cursor-pointer overflow-auto px-5 py-3 !text-xl hover:bg-accent hover:text-accent-foreground">
// 검색 결과가 없습니다.
// </div>
// )}
@@ -1,3 +1,5 @@
"use client";
import "./select.css";
// selectBox
@@ -1,14 +1,14 @@
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown, ChevronUp } from "lucide-react"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select";
import { Check, ChevronDown, ChevronUp } from "lucide-react";
import * as React from "react";
import { cn } from "../../../lib/utils"
import { cn } from "../../../lib/utils";
const Select = SelectPrimitive.Root
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
@@ -17,8 +17,8 @@ const SelectTrigger = React.forwardRef<
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-14 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-xl ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-inset focus:ring-ring focus:ring-offset-0 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
"flex h-[3.2rem] w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-[1.3rem] ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-inset focus:ring-ring focus:ring-offset-0 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className,
)}
{...props}
>
@@ -27,8 +27,8 @@ const SelectTrigger = React.forwardRef<
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
@@ -38,14 +38,14 @@ const SelectScrollUpButton = React.forwardRef<
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
className,
)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
))
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
@@ -55,15 +55,15 @@ const SelectScrollDownButton = React.forwardRef<
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
className,
)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
))
));
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName
SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
@@ -76,7 +76,7 @@ const SelectContent = React.forwardRef<
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
className,
)}
position={position}
{...props}
@@ -86,7 +86,7 @@ const SelectContent = React.forwardRef<
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]",
)}
>
{children}
@@ -94,8 +94,8 @@ const SelectContent = React.forwardRef<
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
@@ -106,8 +106,8 @@ const SelectLabel = React.forwardRef<
className={cn("py-1.5 pl-8 pr-2 text-lg font-semibold", className)}
{...props}
/>
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
@@ -117,7 +117,7 @@ const SelectItem = React.forwardRef<
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-lg outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
className,
)}
{...props}
>
@@ -129,8 +129,8 @@ const SelectItem = React.forwardRef<
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
@@ -141,12 +141,18 @@ const SelectSeparator = React.forwardRef<
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue
}
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
};
@@ -0,0 +1,348 @@
"use client";
import "./standard-data-table.css";
import {
useEffect,
useRef,
useState,
type CSSProperties,
type ReactNode,
type UIEventHandler,
} from "react";
import type { Table as TableInstance } from "@tanstack/react-table";
import { ChevronLeft, ChevronRight } from "lucide-react";
import {
Button,
DataTable,
LoadingWithAnimation,
cn,
} from "@common/components";
type ScrollMode = "none" | "horizontal" | "vertical" | "both";
type StandardDataTableRenderContext<T> = {
table: TableInstance<T>;
};
type StandardDataTableProps<T> = {
table: TableInstance<T>;
title?: ReactNode;
total?: number;
actions?: ReactNode;
loading?: boolean;
emptyMessage?: string;
variant?: "default" | "secondary" | "line";
className?: string;
scrollMode?: ScrollMode;
minTableWidth?: string;
maxHeight?: string;
viewPagination?: boolean;
/** 팝업처럼 부모가 카드 간격을 직접 관리할 때 바깥 카드의 기본 margin을 제거한다. */
flushOuterMargin?: boolean;
/** 빈 목록일 때 부모의 남은 높이를 채워 팝업·페이지의 과도한 바깥 여백을 줄인다. */
fillAvailableHeight?: boolean;
/** 병합 셀·고정 열이 필요한 복합표가 공통 카드·로딩·스크롤 안에서 표 본문만 교체한다. */
renderTable?: (context: StandardDataTableRenderContext<T>) => ReactNode;
/** 고정 열 경계처럼 가로 스크롤 위치가 필요한 소비 화면에 공통 스크롤 이벤트를 전달한다. */
onScroll?: UIEventHandler<HTMLDivElement>;
onRowClick?: (row: T) => void;
};
type StandardDataTableStyle = CSSProperties & {
"--standard-data-table-min-width"?: string;
"--standard-data-table-max-height"?: string;
};
const DEFAULT_PAGINATION_MARGIN_TOP = 24;
const STANDARD_ROW_NUMBER_HEADER = "순번";
type StandardRowNumberParams = {
total: number;
rowIndex: number;
pageIndex?: number;
pageSize?: number;
};
/** 전체 건수를 기준으로 현재 페이지의 순번을 큰 값부터 계산한다. */
function getStandardRowNumber({
total,
rowIndex,
pageIndex = 0,
pageSize = 0,
}: StandardRowNumberParams) {
return Math.max(total - (pageIndex * pageSize + rowIndex), 0);
}
/** 스크롤 영역 밖에서 공통 DataTable과 같은 페이지 이동 규칙을 제공한다. */
function StandardDataTablePagination<T>({
table,
marginTop,
}: {
table: TableInstance<T>;
marginTop: number;
}) {
const pageCount = table.getPageCount();
const currentPage = table.getState().pagination.pageIndex;
const maxVisiblePages = 10;
let startPage = Math.max(0, currentPage - maxVisiblePages / 2);
const endPage = Math.min(pageCount, startPage + maxVisiblePages);
if (endPage - startPage < maxVisiblePages) {
startPage = Math.max(0, endPage - maxVisiblePages);
}
const pageNumbers = Array.from(
{ length: Math.max(endPage - startPage, 0) },
(_, index) => startPage + index,
);
return (
<div
className="flex items-center justify-center space-x-2"
style={{ marginTop }}
>
<Button
type="button"
variant="ghost"
color="white"
className="hidden size-10 p-0 lg:flex"
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
aria-label="첫 페이지로"
>
<span className="flex -space-x-2" aria-hidden="true">
<ChevronLeft className="size-4" />
<ChevronLeft className="size-4" />
</span>
</Button>
<Button
type="button"
variant="ghost"
color="white"
className="size-10 p-0"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
aria-label="이전 페이지로"
>
<ChevronLeft className="size-4" />
</Button>
<div className="flex items-center justify-center text-sm font-medium">
{pageNumbers.map((pageNumber) => (
<Button
key={pageNumber}
type="button"
variant="ghost"
className={cn(
"inline-block h-10 min-w-10 !bg-transparent p-1 text-foreground hover:!bg-accent",
currentPage === pageNumber &&
"!bg-primary !font-bold !text-primary-foreground hover:!bg-primary",
)}
onClick={() => table.setPageIndex(pageNumber)}
aria-label={`${pageNumber + 1} 페이지`}
aria-current={currentPage === pageNumber ? "page" : undefined}
>
{pageNumber + 1}
</Button>
))}
</div>
<Button
type="button"
variant="ghost"
color="white"
className="size-10 p-0"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
aria-label="다음 페이지로"
>
<ChevronRight className="size-4" />
</Button>
<Button
type="button"
variant="ghost"
color="white"
className="hidden size-10 p-0 lg:flex"
onClick={() =>
table.setPageIndex(Math.max(table.getPageCount() - 1, 0))
}
disabled={!table.getCanNextPage()}
aria-label="마지막 페이지로"
>
<span className="flex -space-x-2" aria-hidden="true">
<ChevronRight className="size-4" />
<ChevronRight className="size-4" />
</span>
</Button>
</div>
);
}
function StandardDataTable<T>({
table,
title,
total,
actions,
loading = false,
emptyMessage = "조회된 데이터가 없습니다.",
variant = "default",
className,
scrollMode = "none",
minTableWidth = "100%",
maxHeight = "none",
viewPagination = true,
flushOuterMargin = false,
fillAvailableHeight = false,
renderTable,
onScroll,
onRowClick,
}: StandardDataTableProps<T>) {
const rowCount = table.getRowModel().rows.length;
const shouldFillAvailableHeight = fillAvailableHeight && rowCount === 0;
const scrollRef = useRef<HTMLDivElement>(null);
const [paginationMarginTop, setPaginationMarginTop] = useState(
DEFAULT_PAGINATION_MARGIN_TOP,
);
const scrollClassName = cn(
"standard-data-table__scroll",
scrollMode === "horizontal" && "overflow-x-auto overflow-y-visible",
scrollMode === "vertical" && "overflow-x-hidden overflow-y-auto",
scrollMode === "both" && "overflow-auto",
);
const scrollStyle: StandardDataTableStyle = {
"--standard-data-table-min-width": minTableWidth,
"--standard-data-table-max-height": maxHeight,
};
/** 실제 가로 스크롤바가 차지하는 높이만큼 페이징 여백을 줄여 CS의 24px 체감 간격을 유지한다. */
useEffect(() => {
const scrollElement = scrollRef.current;
if (!scrollElement) return;
const updatePaginationMargin = () => {
const hasHorizontalOverflow =
scrollElement.scrollWidth > scrollElement.clientWidth + 1;
const horizontalScrollbarHeight = hasHorizontalOverflow
? Math.max(scrollElement.offsetHeight - scrollElement.clientHeight, 0)
: 0;
const nextMargin = Math.max(
DEFAULT_PAGINATION_MARGIN_TOP - horizontalScrollbarHeight,
0,
);
setPaginationMarginTop((currentMargin) =>
currentMargin === nextMargin ? currentMargin : nextMargin,
);
};
updatePaginationMargin();
const resizeObserver = new ResizeObserver(updatePaginationMargin);
resizeObserver.observe(scrollElement);
const tableElement = scrollElement.querySelector("table");
if (tableElement) resizeObserver.observe(tableElement);
window.addEventListener("resize", updatePaginationMargin);
return () => {
resizeObserver.disconnect();
window.removeEventListener("resize", updatePaginationMargin);
};
}, [maxHeight, minTableWidth, rowCount, scrollMode]);
return (
<div
className={cn(
"standard-data-table card card-border w-full max-w-full min-w-0 overflow-hidden",
flushOuterMargin && "!m-0",
shouldFillAvailableHeight ? "flex min-h-0 flex-1 flex-col" : "shrink-0",
className,
)}
>
{title || actions ? (
<div className="card-header flex flex-wrap items-center justify-between gap-4">
<h3 className="text-2xl font-medium text-label">
{title}
{typeof total === "number" ? (
<span className="ml-2 text-base font-normal text-muted-foreground">
총 {total.toLocaleString("ko-KR")}건
</span>
) : null}
</h3>
{actions ? (
<div className="flex flex-wrap gap-2">{actions}</div>
) : null}
</div>
) : null}
<div
className={cn(
"card !mx-[0.4rem] !my-[1.2rem] min-w-0 overflow-hidden !p-0",
shouldFillAvailableHeight && "flex min-h-0 flex-1 flex-col",
)}
>
<div
ref={scrollRef}
onScroll={onScroll}
className={cn(
scrollClassName,
shouldFillAvailableHeight && "min-h-96 flex-1",
)}
style={scrollStyle}
>
{loading || rowCount === 0 ? (
<div
className={cn(
"flex items-center justify-center text-[1.3rem] text-muted-foreground",
shouldFillAvailableHeight ? "h-full" : "h-96",
)}
>
{loading ? (
<div
className="relative size-16 shrink-0"
role="status"
aria-label="조회 중"
>
<LoadingWithAnimation color="primary" />
</div>
) : (
emptyMessage
)}
</div>
) : (
(renderTable?.({ table }) ?? (
<DataTable
table={table}
variant={variant}
className={cn("w-full", className)}
viewPagination={false}
onRowClick={onRowClick}
/>
))
)}
</div>
{viewPagination && !loading && rowCount > 0 ? (
<StandardDataTablePagination
table={table}
marginTop={paginationMarginTop}
/>
) : null}
</div>
</div>
);
}
export { STANDARD_ROW_NUMBER_HEADER, StandardDataTable, getStandardRowNumber };
export type {
ScrollMode,
StandardDataTableProps,
StandardDataTableRenderContext,
StandardRowNumberParams,
};
export {
StandardTableSortHeader,
compareStandardTableValues,
getNextStandardTableSort,
sortStandardTableRows,
} from "./sort";
export type { StandardTableSortHeaderProps } from "./sort";
@@ -0,0 +1,145 @@
"use client";
import type { ReactNode } from "react";
import { ChevronDown, ChevronUp } from "lucide-react";
import type { UiTableSort } from "../table/types";
const STANDARD_TABLE_SORT_COLLATOR = new Intl.Collator("ko-KR", {
numeric: true,
sensitivity: "base",
});
const isEmptySortValue = (value: unknown) =>
value === null ||
value === undefined ||
String(value).trim() === "" ||
String(value).trim() === "-";
const toComparableNumber = (value: unknown) => {
const normalized = String(value ?? "")
.trim()
.replace(/,/g, "")
.replace(/%$/, "");
if (!/^-?\d+(?:\.\d+)?$/.test(normalized)) return undefined;
const number = Number(normalized);
return Number.isFinite(number) ? number : undefined;
};
/** 공통 표 헤더의 asc → desc → 기본 순환 상태를 계산한다. */
export const getNextStandardTableSort = (
sortKey: string,
currentSort?: UiTableSort,
): UiTableSort | undefined => {
if (currentSort?.key !== sortKey) {
return { key: sortKey, direction: "asc" };
}
if (currentSort.direction === "asc") {
return { key: sortKey, direction: "desc" };
}
return undefined;
};
/** 숫자·날짜·한글 표시값을 비교하고 빈 값은 방향과 무관하게 마지막에 둔다. */
export const compareStandardTableValues = (
leftValue: unknown,
rightValue: unknown,
direction: UiTableSort["direction"],
) => {
const leftEmpty = isEmptySortValue(leftValue);
const rightEmpty = isEmptySortValue(rightValue);
if (leftEmpty || rightEmpty) {
if (leftEmpty && rightEmpty) return 0;
return leftEmpty ? 1 : -1;
}
const leftNumber = toComparableNumber(leftValue);
const rightNumber = toComparableNumber(rightValue);
const comparison =
leftNumber !== undefined && rightNumber !== undefined
? leftNumber - rightNumber
: STANDARD_TABLE_SORT_COLLATOR.compare(
String(leftValue),
String(rightValue),
);
return direction === "asc" ? comparison : -comparison;
};
/** 서버 페이징이 아닌 전체 보유 행을 원본 배열 변경 없이 안정 정렬한다. */
export const sortStandardTableRows = <T extends object>(
rows: T[],
sort?: UiTableSort,
resolveValue: (row: T, key: string) => unknown = (row, key) =>
(row as Record<string, unknown>)[key],
) => {
if (!sort) return rows;
return rows
.map((row, originalIndex) => ({ row, originalIndex }))
.sort((left, right) => {
const comparison = compareStandardTableValues(
resolveValue(left.row, sort.key),
resolveValue(right.row, sort.key),
sort.direction,
);
return comparison || left.originalIndex - right.originalIndex;
})
.map(({ row }) => row);
};
interface StandardTableSortHeaderProps {
label: string;
title?: ReactNode;
sortKey: string;
sort?: UiTableSort;
onSortChange: (sort: UiTableSort | undefined) => void;
}
/** StandardDataTable 계열 화면이 동일한 아이콘·상태 전이를 사용하는 헤더 버튼이다. */
export function StandardTableSortHeader({
label,
title = label,
sortKey,
sort,
onSortChange,
}: StandardTableSortHeaderProps) {
const direction = sort?.key === sortKey ? sort.direction : undefined;
const nextSort = getNextStandardTableSort(sortKey, sort);
const nextAction =
nextSort?.direction === "asc"
? "오름차순"
: nextSort?.direction === "desc"
? "내림차순"
: "기본순서";
return (
<button
type="button"
className="inline-flex w-full items-center justify-center gap-1.5 rounded-sm transition-colors hover:bg-background/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground"
aria-label={`${label} ${nextAction} 정렬`}
onClick={() => onSortChange(nextSort)}
>
<span>{title}</span>
<span
className={`inline-flex shrink-0 items-center justify-center drop-shadow-sm ${
direction
? "text-yellow-300 drop-shadow-[0_1px_1px_rgba(0,0,0,0.8)]"
: "text-white drop-shadow-[0_1px_1px_rgba(0,0,0,0.75)]"
}`}
aria-hidden="true"
>
{direction === "asc" ? (
<ChevronUp className="size-5 stroke-[3]" />
) : direction === "desc" ? (
<ChevronDown className="size-5 stroke-[3]" />
) : (
<span className="inline-flex flex-col -space-y-2">
<ChevronUp className="size-4 stroke-[2.8]" />
<ChevronDown className="size-4 stroke-[2.8]" />
</span>
)}
</span>
</button>
);
}
export type { StandardTableSortHeaderProps };
@@ -0,0 +1,23 @@
@tailwind components;
@layer components {
.standard-data-table {
width: calc(100% - 1.2rem);
max-width: calc(100% - 1.2rem);
}
.standard-data-table__scroll {
width: 100%;
min-width: 0;
max-width: 100%;
max-height: var(--standard-data-table-max-height, none);
}
.standard-data-table__scroll table {
min-width: var(--standard-data-table-min-width, 100%);
}
.standard-data-table__scroll thead th {
text-align: center;
}
}
@@ -0,0 +1,118 @@
import { createContext, useContext, type ReactNode } from "react";
import { Label } from "@common/components";
type StandardFormColumns = 2 | 3;
type StandardFormFieldSpan = 1 | 2 | 3;
const SECTION_GRID_CLASS: Record<StandardFormColumns, string> = {
2: "md:grid-cols-2",
3: "md:grid-cols-2 xl:grid-cols-3",
};
const FIELD_SPAN_CLASS: Record<
StandardFormColumns,
Record<StandardFormFieldSpan, string>
> = {
2: {
1: "",
2: "md:col-span-2",
3: "md:col-span-2",
},
3: {
1: "",
2: "md:col-span-2 xl:col-span-2",
3: "md:col-span-2 xl:col-span-3",
},
};
type StandardFormSectionProps = {
title: ReactNode;
children: ReactNode;
columns?: StandardFormColumns;
className?: string;
wideLabels?: boolean;
};
const StandardFormWideLabelsContext = createContext(false);
type StandardFormFieldProps = {
id?: string;
label: ReactNode;
required?: boolean;
error?: ReactNode;
span?: StandardFormFieldSpan;
columns?: StandardFormColumns;
children: ReactNode;
className?: string;
};
/** CS 표형 입력의 섹션 헤더와 반응형 2~3열 배치를 업무 화면에 공통 제공한다. */
function StandardFormSection({
title,
children,
columns = 3,
className = "",
wideLabels = false,
}: StandardFormSectionProps) {
return (
<section
className={`shrink-0 overflow-hidden rounded-sm border border-border bg-background ${className}`}
>
<h4 className="border-b border-border bg-container px-4 py-3 text-[1.4rem] font-semibold text-label">
{title}
</h4>
<StandardFormWideLabelsContext.Provider value={wideLabels}>
<div
className={`grid grid-cols-1 gap-px bg-border ${SECTION_GRID_CLASS[columns]}`}
>
{children}
</div>
</StandardFormWideLabelsContext.Provider>
</section>
);
}
/** 라벨·필수 표시·검증 문구·입력 영역을 한 셀로 묶고 섹션 열 수에 맞춰 병합한다. */
function StandardFormField({
id,
label,
required = false,
error,
span = 1,
columns = 3,
children,
className = "",
}: StandardFormFieldProps) {
const wideLabels = useContext(StandardFormWideLabelsContext);
return (
<div
className={`grid min-w-0 grid-cols-[9rem_minmax(0,1fr)] bg-background ${wideLabels ? "sm:grid-cols-[18rem_minmax(0,1fr)]" : "sm:grid-cols-[11.5rem_minmax(0,1fr)]"} ${FIELD_SPAN_CLASS[columns][span]} ${className}`}
>
<Label
htmlFor={id}
className="flex min-h-[5.6rem] items-center border-r border-border bg-secondary px-4 py-3 text-[1.25rem] font-medium leading-5 text-label"
>
{required ? <span className="mr-1 text-red-600">*</span> : null}
{label}
</Label>
<div className="flex min-w-0 flex-col justify-center p-3">
{children}
{error ? (
<p className="mt-1 text-[1.2rem] text-red-600" role="alert">
{error}
</p>
) : null}
</div>
</div>
);
}
export { StandardFormField, StandardFormSection };
export type {
StandardFormColumns,
StandardFormFieldProps,
StandardFormFieldSpan,
StandardFormSectionProps,
};
@@ -0,0 +1,85 @@
"use client";
import type { ReactNode } from "react";
import { Button, cn } from "@common/components";
type StandardPopupLayoutProps = {
title: ReactNode;
actions?: ReactNode;
children: ReactNode;
footer?: ReactNode;
className?: string;
bodyClassName?: string;
/** 이미 업무별 취소 액션을 제공하는 화면에서만 false로 설정한다. */
showDefaultCancelAction?: boolean;
onCancel?: () => void;
};
/** CS 카드형 화면 규칙을 별도 창 팝업에도 동일하게 제공한다. */
function StandardPopupLayout({
title,
actions,
children,
footer,
className,
bodyClassName,
showDefaultCancelAction = true,
onCancel,
}: StandardPopupLayoutProps) {
const handleCancel = () => {
if (onCancel) {
onCancel();
return;
}
window.close();
};
return (
<main className="flex h-dvh min-h-0 flex-col bg-container p-3">
<section
className={cn(
"card card-border !m-0 flex min-h-0 flex-1 flex-col overflow-hidden !p-[0.6rem]",
className,
)}
>
<header className="card-header !mx-0 min-h-[5.2rem] shrink-0 gap-3 !px-[1.2rem]">
<h1 className="min-w-0 text-[1.8rem] font-semibold text-label">
{title}
</h1>
{actions || showDefaultCancelAction ? (
<div className="flex shrink-0 flex-wrap items-center justify-end gap-2">
{actions}
{showDefaultCancelAction ? (
<Button
type="button"
color="white"
onClick={handleCancel}
data-testid="window-popup-cancel"
>
취소
</Button>
) : null}
</div>
) : null}
</header>
<div
className={cn(
"flex min-h-0 flex-1 flex-col gap-[1.2rem] overflow-y-auto bg-background p-3 !px-[1.2rem]",
bodyClassName,
)}
>
{children}
</div>
{footer ? (
<footer className="card-footer shrink-0">{footer}</footer>
) : null}
</section>
</main>
);
}
export { StandardPopupLayout };
export type { StandardPopupLayoutProps };
@@ -1,71 +1,120 @@
import { TableHead, TableRow } from "@common/components/ui";
import type { UiHeadProps, UiTableSort } from "./types";
interface TableUpperProps {
id: string;
title: string;
upName?: string;
upSequnce?: number;
row? : number;
rowSpan?: number;
colSpan?: number;
visible?:boolean;
widthPercent?: number;
}
type HeadMakeColSpanProps = {
upHeadList: UiHeadProps[];
sort?: UiTableSort;
onSortChange?: (head: UiHeadProps) => void;
};
const HeadMakeColSpan = ({ upHeadList }: { upHeadList: TableUpperProps[] }) => {
const maxRow = upHeadList?.reduce((max, head) => Math.max(max, head.row || 0), 0);
//upHeadList.forEach((item) => item.visible ?item.visible:true)
const HeadMakeColSpan = ({
upHeadList,
sort,
onSortChange,
}: HeadMakeColSpanProps) => {
const maxRow = upHeadList?.reduce(
(max, head) => Math.max(max, head.row || 0),
0,
);
/** 마지막 헤더 행까지 차지하는 실제 데이터 컬럼인지 판별한다. */
const isLeafHead = (head: UiHeadProps) =>
(head.row ?? 0) + (head.rowSpan ?? 1) - 1 >= maxRow;
/** 현재 정렬 상태에 맞는 헤더 버튼과 방향 아이콘을 만든다. */
const renderHeadContent = (head: UiHeadProps) => {
const key = head.sortKey ?? head.id;
const direction = sort?.key === key ? sort.direction : undefined;
const sortable = Boolean(head.sortable && isLeafHead(head) && onSortChange);
if (!sortable) return head.title;
if(maxRow == 0){
return (
<>
<TableRow className="bg-gray-50">
{upHeadList
.filter((item) => item.visible != false)
.map((head: TableUpperProps) => {
return (
<TableHead
key={head.id}
colSpan={head.colSpan || 1}
rowSpan={head.rowSpan || 1}
style={{ whiteSpace: 'pre-line' }}
className=""
>
{head.title}
</TableHead>
);
})}
</TableRow>
</>
<button
type="button"
className="inline-flex w-full items-center justify-center gap-1.5"
aria-label={`${head.title} 정렬`}
onClick={() => onSortChange?.(head)}
>
<span>{head.title}</span>
{direction === "asc" ? (
<span
className="inline-flex min-w-2 justify-center text-[8px] leading-none text-primary"
aria-hidden="true"
>
▲
</span>
) : direction === "desc" ? (
<span
className="inline-flex min-w-2 justify-center text-[8px] leading-none text-primary"
aria-hidden="true"
>
▼
</span>
) : (
<span
className="inline-flex flex-col items-center gap-px text-[6px] leading-none text-muted-foreground"
aria-hidden="true"
>
<span>▲</span>
<span>▼</span>
</span>
)}
</button>
);
}else{
};
/** 공통 속성과 접근성 정렬 상태를 포함한 헤더 셀을 렌더링한다. */
const renderHead = (head: UiHeadProps, key: string) => {
const sortKey = head.sortKey ?? head.id;
const direction = sort?.key === sortKey ? sort.direction : undefined;
const sortable = Boolean(head.sortable && isLeafHead(head) && onSortChange);
return (
<>
{Array.from({ length: maxRow + 1 }, (_, rowIndex) => (
<TableRow key={rowIndex+ " headerRow"} className="bg-gray-50">
{upHeadList
.filter((item) => item.visible != false)
.map((head: TableUpperProps, idx) => {
if (head.row === rowIndex) {
return (
<TableHead
key={head.id?head.id:rowIndex+"_"+idx}
colSpan={head.colSpan || 1}
rowSpan={head.rowSpan || 1}
style={{ whiteSpace: 'pre-line' }}
className="bg-gray-50"
>
{head.title}
</TableHead>
);
}
})}
</TableRow>
))}
</>
<TableHead
key={key}
colSpan={head.colSpan || 1}
rowSpan={head.rowSpan || 1}
style={{ whiteSpace: "pre-line" }}
className="bg-secondary"
aria-sort={
sortable
? direction === "asc"
? "ascending"
: direction === "desc"
? "descending"
: "none"
: undefined
}
>
{renderHeadContent(head)}
</TableHead>
);
};
if (maxRow === 0) {
return (
<TableRow className="bg-secondary">
{upHeadList
.filter((item) => item.visible !== false)
.map((head) => renderHead(head, head.id))}
</TableRow>
);
}
}
return (
<>
{Array.from({ length: maxRow + 1 }, (_, rowIndex) => (
<TableRow key={`${rowIndex} headerRow`} className="bg-secondary">
{upHeadList
.filter((item) => item.visible !== false && item.row === rowIndex)
.map((head, index) =>
renderHead(head, head.id || `${rowIndex}_${index}`),
)}
</TableRow>
))}
</>
);
};
export { HeadMakeColSpan };
@@ -12,6 +12,10 @@ import { useEffect, useState, useRef } from "react";
import { HeadMakeColSpan } from "./HeadMakeColSpan";
import UiPageNations from "./uiPageNations";
import { Check } from "lucide-react";
import type { UiHeadProps, UiTableSort } from "./types";
export type { UiHeadProps, UiTableSort, UiTableSortDirection } from "./types";
export type ChkClass = {
chk: boolean;
readonly: boolean;
@@ -27,6 +31,11 @@ type UiTableProps<T extends object> = {
onPageChange: (page: number) => void;
cellClassName?: (row: T, headId: string, rowIndex: number) => string;
rowClassName?: (row: T, rowIndex: number) => string;
renderCell?: (
row: T,
headId: string,
rowIndex: number,
) => React.ReactNode | undefined;
className?: string;
resetPageNo?: boolean;
children?: React.ReactNode | undefined;
@@ -36,19 +45,11 @@ type UiTableProps<T extends object> = {
curPage?: number;
headButton?: React.ReactNode | undefined;
widthFixed?: boolean;
noOuterMargin?: boolean; // 외부 스크롤 래퍼가 표 여백을 직접 관리할 때 사용한다.
isHideCount?: boolean; // 총 건수 default false
clickableHeadIds?: string[];
};
type UiHeadProps = {
id: string;
title: string;
align?: string;
visible?: boolean;
row?: number;
widthPercent?: number;
rowSpan?: number;
colSpan?: number;
sort?: UiTableSort;
onSortChange?: (sort: UiTableSort | undefined) => void;
};
export function UiTable<T extends object = Record<string, unknown>>({
@@ -62,6 +63,7 @@ export function UiTable<T extends object = Record<string, unknown>>({
onPageChange,
cellClassName,
rowClassName,
renderCell,
className = "",
resetPageNo = false,
boldArray = [],
@@ -70,8 +72,11 @@ export function UiTable<T extends object = Record<string, unknown>>({
curPage = 1,
headButton = undefined,
widthFixed = false,
noOuterMargin = false,
isHideCount = false,
clickableHeadIds,
sort,
onSortChange,
}: UiTableProps<T>) {
const [cur, setCur] = useState<number>(curPage);
const [idx, setIdx] = useState<number>(index);
@@ -124,15 +129,32 @@ export function UiTable<T extends object = Record<string, unknown>>({
setIdx(index);
};
/** 정렬 가능한 헤더를 asc, desc, 기본 순서로 순환시킨다. */
const handleSortChange = (head: UiHeadProps) => {
if (!head.sortable || !onSortChange) return;
const key = head.sortKey ?? head.id;
if (sort?.key !== key) {
onSortChange({ key, direction: "asc" });
return;
}
if (sort.direction === "asc") {
onSortChange({ key, direction: "desc" });
return;
}
onSortChange(undefined);
};
const getLeafCols = (list: UiHeadProps[]) => {
const maxRow = list?.reduce((max, head) => Math.max(max, head.row || 0), 0);
return list
.filter((h) => h.visible !== false)
.filter((h) => ((h.row ?? 0) + (h.rowSpan ?? 1) - 1) >= maxRow);
.filter((h) => (h.row ?? 0) + (h.rowSpan ?? 1) - 1 >= maxRow);
};
const leafCols = getLeafCols(headlist);
const totalLabel = typeof total === "number" ? total.toLocaleString("ko-KR") : " ";
const totalLabel =
typeof total === "number" ? total.toLocaleString("ko-KR") : " ";
const hasTotal = typeof total === "number";
return (
@@ -157,24 +179,45 @@ export function UiTable<T extends object = Record<string, unknown>>({
) : (
<></>
)}
<div className={`card !m-[1.2rem] ${className}`}>
<div
className={`card ${noOuterMargin ? "!m-0" : "!m-[1.2rem]"} ${className}`}
>
<Table variant="secondary" className={widthFixed ? "table-fixed" : ""}>
{widthFixed ? (
<colgroup>
{leafCols.map((col) => (
<col key={col.id} style={{ width: col.widthPercent ? `${col.widthPercent}%` : undefined }} />
<col
key={col.id}
style={{
width: col.widthPercent
? `${col.widthPercent}%`
: undefined,
}}
/>
))}
</colgroup>
) : (
""
)}
<TableHeader ref={headerRef} className="font-bold">
{children ? children : <HeadMakeColSpan upHeadList={headlist} />}
{children ? (
children
) : (
<HeadMakeColSpan
upHeadList={headlist}
sort={sort}
onSortChange={handleSortChange}
/>
)}
</TableHeader>
<TableBody className="text-center">
{tableData.length > 0 ? (
tableData?.map((el: T, index) => (
<TableRow key={`row-${index}`} className={rowClassName ? rowClassName(el, index) : ""}>
<TableRow
key={`row-${index}`}
data-state={idx === index ? "selected" : undefined}
className={rowClassName ? rowClassName(el, index) : ""}
>
{headlist
.filter((item) => item.visible != false)
.map(
@@ -183,18 +226,31 @@ export function UiTable<T extends object = Record<string, unknown>>({
head.id.length > 1 &&
(boldArray.includes(index) ? (
<TableCell
className={`${head.align === "right" ? "text-right" : head.align === "center" ? "text-center" : "text-center"} ${isHeadClickable(head.id) && idx === index
? "cursor-pointer !font-[1000]"
: isHeadClickable(head.id)
? "cursor-pointer"
: ""
} ${cellClassName ? cellClassName(el, head.id, index) : ""} sticky top-20 z-40 bg-secondary !font-bold whitespace-pre-line`}
style={{ top: `${headerHeight + index * 32 - 4}px` }}
className={`${head.align === "right" ? "text-right" : head.align === "center" ? "text-center" : "text-center"} ${
isHeadClickable(head.id) && idx === index
? "cursor-pointer !font-[1000]"
: isHeadClickable(head.id)
? "cursor-pointer"
: ""
} ${cellClassName ? cellClassName(el, head.id, index) : ""} sticky top-20 z-40 whitespace-pre-line bg-secondary !font-bold`}
style={{
top: `${headerHeight + index * 32 - 4}px`,
}}
onClick={() => handleCellClick(index, head.id)}
key={`cell-${head.id}-${index}`}
>
{(() => {
const cellValue = (el as Record<string, unknown>)[head.id];
const renderedCell = renderCell?.(
el,
head.id,
index,
);
if (renderedCell !== undefined)
return renderedCell;
const cellValue = (el as Record<string, unknown>)[
head.id
];
return typeof cellValue !== "number"
? String(cellValue ?? "")
: String(cellValue).includes(".")
@@ -202,35 +258,58 @@ export function UiTable<T extends object = Record<string, unknown>>({
.split(".")
.map((part, index) =>
index === 0
? part.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
? part.replace(
/\B(?=(\d{3})+(?!\d))/g,
",",
)
: part,
)
.join(".")
: String(cellValue ?? "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
: String(cellValue ?? "").replace(
/\B(?=(\d{3})+(?!\d))/g,
",",
);
})()}
</TableCell>
) : (
<TableCell
className={`${head.align === "right" ? "text-right" : head.align === "center" ? "text-center" : "text-center"} ${isHeadClickable(head.id) && idx === index
? "cursor-pointer !font-[1000]"
: isHeadClickable(head.id)
? "cursor-pointer"
: ""
} ${cellClassName ? cellClassName(el, head.id, index) : ""} mt-[${boldArray.length * 40}px] whitespace-pre-line`}
className={`${head.align === "right" ? "text-right" : head.align === "center" ? "text-center" : "text-center"} ${
isHeadClickable(head.id) && idx === index
? "cursor-pointer !font-[1000]"
: isHeadClickable(head.id)
? "cursor-pointer"
: ""
} ${cellClassName ? cellClassName(el, head.id, index) : ""} mt-[${boldArray.length * 40}px] whitespace-pre-line`}
onClick={() => handleCellClick(index, head.id)}
key={`cell-${head.id}-${index}`}
>
{(() => {
const cellValue = (el as Record<string, unknown>)[head.id];
const renderedCell = renderCell?.(
el,
head.id,
index,
);
if (renderedCell !== undefined)
return renderedCell;
const cellValue = (el as Record<string, unknown>)[
head.id
];
return typeof cellValue === "object" &&
cellValue !== null &&
"chk" in (cellValue as object) &&
"readonly" in (cellValue as object) ? (
<Checkbox
checked={(cellValue as ChkClass)?.chk === true}
checked={
(cellValue as ChkClass)?.chk === true
}
onCheckedChange={(checked) => {
if ((cellValue as ChkClass).readonly == true) return;
(cellValue as ChkClass).chk = Boolean(checked);
if (
(cellValue as ChkClass).readonly == true
)
return;
(cellValue as ChkClass).chk =
Boolean(checked);
}}
>
<Check className="h-6 w-6 text-primary" />
@@ -239,7 +318,8 @@ export function UiTable<T extends object = Record<string, unknown>>({
<Checkbox
checked={cellValue === true}
onCheckedChange={(checked) => {
(el as Record<string, unknown>)[head.id] = checked;
(el as Record<string, unknown>)[head.id] =
checked;
}}
>
<Check className="h-6 w-6 text-primary" />
@@ -250,11 +330,19 @@ export function UiTable<T extends object = Record<string, unknown>>({
String(cellValue)
.split(".")
.map((part, index) =>
index === 0 ? part.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : part,
index === 0
? part.replace(
/\B(?=(\d{3})+(?!\d))/g,
",",
)
: part,
)
.join(".")
) : (
String(cellValue ?? "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
String(cellValue ?? "").replace(
/\B(?=(\d{3})+(?!\d))/g,
",",
)
);
})()}
</TableCell>
@@ -273,7 +361,7 @@ export function UiTable<T extends object = Record<string, unknown>>({
(item.colSpan || ["A", "B", "C"].includes(item.id)),
).length
}
className="h-24 text-center text-gray-500"
className="h-24 text-center text-muted-foreground"
>
조회된 결과가 없습니다.
</TableCell>
@@ -0,0 +1,19 @@
export type UiTableSortDirection = "asc" | "desc";
export type UiTableSort = {
key: string;
direction: UiTableSortDirection;
};
export type UiHeadProps = {
id: string;
title: string;
align?: string;
visible?: boolean;
row?: number;
widthPercent?: number;
rowSpan?: number;
colSpan?: number;
sortable?: boolean;
sortKey?: string;
};
@@ -42,6 +42,18 @@ export const getMenuList = async (siteId: string): Promise<MenuItem[]> => {
return response.json();
};
export const getMenuDetail = async (menuCd: number): Promise<MenuItem> => {
const response = await fetch(
`${BASE_URL}${ENDPOINT.CMS_SERVICE.MENUS}/${menuCd}`,
{
method: "GET",
headers: getAuthHeaders(),
credentials: "include",
},
);
return response.json();
};
export const getPreviewTreeMenuList = async (
siteId: string,
): Promise<TreeMenu[]> => {
@@ -1,55 +0,0 @@
"use client";
import { createContext, useContext, useState, useCallback } from "react";
interface HelpDialogContextType {
openHelp: () => void;
closeHelp: () => void;
isOpen: boolean;
setHelpContent: (content: string) => void;
helpContent: string;
}
const HelpDialogContext = createContext<HelpDialogContextType | undefined>(
undefined,
);
export function HelpDialogProvider({
children,
}: {
children: React.ReactNode;
}) {
const [isOpen, setIsOpen] = useState(false);
const [helpContent, setHelpContent] = useState<string>("");
const openHelp = useCallback(() => {
setIsOpen(true);
}, []);
const closeHelp = useCallback(() => {
setIsOpen(false);
}, []);
return (
<HelpDialogContext.Provider
value={{
openHelp,
closeHelp,
isOpen,
setHelpContent,
helpContent,
}}
>
{children}
</HelpDialogContext.Provider>
);
}
export function useHelpDialog() {
const context = useContext(HelpDialogContext);
if (context === undefined) {
throw new Error("useHelpDialog must be used within a HelpDialogProvider");
}
return context;
}
@@ -77,47 +77,69 @@ function DataTable<T>({
function THead<T>({ table }: { table: TableInstance<T> }) {
return (
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
const columnRelativeDepth = header.depth - header.column.depth;
if (
!header.isPlaceholder &&
columnRelativeDepth > 1 &&
header.id === header.column.id
) {
return null;
}
{table
.getHeaderGroups()
.map((headerGroup, headerGroupIndex, headerGroups) => (
<TableRow
key={headerGroup.id}
className={cn(
headerGroups.length > 1 &&
headerGroupIndex === 0 &&
"!border-b-0",
)}
>
{headerGroup.headers.map((header) => {
const columnRelativeDepth = header.depth - header.column.depth;
if (
!header.isPlaceholder &&
columnRelativeDepth > 1 &&
header.id === header.column.id
) {
return null;
}
let rowSpan = 1;
if (header.isPlaceholder) {
const leafs = header.getLeafHeaders();
rowSpan = (leafs?.[leafs.length - 1]?.depth ?? 0) - header.depth;
}
let rowSpan = 1;
if (header.isPlaceholder) {
const leafs = header.getLeafHeaders();
rowSpan =
(leafs?.[leafs.length - 1]?.depth ?? 0) - header.depth;
}
const { meta } = header.column.columnDef;
const { meta } = header.column.columnDef;
return (
<TableHead
key={header.id}
className="sticky top-0 z-10"
colSpan={header.colSpan}
rowSpan={rowSpan}
{...meta}
>
{flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
);
})}
</TableRow>
))}
const isNestedGroupHeader =
!header.isPlaceholder && hasNestedColumns(header.column);
return (
<TableHead
key={header.id}
className={cn(
"sticky top-0 z-10",
isNestedGroupHeader && "data-table-group-header",
)}
colSpan={header.colSpan}
rowSpan={rowSpan}
{...meta}
>
{flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
);
}
function hasNestedColumns<T>(
column: import("@tanstack/react-table").Column<T, unknown>,
) {
return column.columns.length > 0;
}
function Pagination<T>({ table }: { table: TableInstance<T> }) {
const pageCount = table.getPageCount();
const currentPage = table.getState().pagination.pageIndex;
@@ -2,7 +2,6 @@ import type { AuthService, TokenManager } from "@common/auth";
import type { QueryClient } from "@tanstack/react-query";
import { QueryProvider } from "../../provider/query-provider";
import { PopupProvider } from "../../provider/popup-provider";
import { HelpDialogProvider } from "../../provider/help-dialog-context";
import type { MenuItem } from "../../api";
import { SidebarProvider } from "../sidebar";
import { LNB } from "../lnb";
@@ -29,26 +28,24 @@ export function BaseLayout({
return (
<QueryProvider queryClient={queryClient}>
<PopupProvider>
<HelpDialogProvider>
<SidebarProvider>
<div className="flex-1">
<Header
authService={authService}
tokenManager={authService ? undefined : tokenManager}
<SidebarProvider>
<div className="flex-1">
<Header
authService={authService}
tokenManager={authService ? undefined : tokenManager}
/>
<div className="flex">
<LNB
currentPath={currentPath}
handleMenuClick={handleMenuClick}
/>
<div className="flex">
<LNB
currentPath={currentPath}
handleMenuClick={handleMenuClick}
/>
<div className="flex min-h-[calc(100vh-50px)] flex-1 flex-col">
<div className="flex-1">{children}</div>
<Footer />
</div>
<div className="flex min-h-[calc(100vh-50px)] flex-1 flex-col">
<div className="flex-1">{children}</div>
<Footer />
</div>
</div>
</SidebarProvider>
</HelpDialogProvider>
</div>
</SidebarProvider>
</PopupProvider>
</QueryProvider>
);
@@ -1,7 +1,6 @@
import type { QueryClient } from "@tanstack/react-query";
import { QueryProvider } from "../../provider/query-provider";
import { PopupProvider } from "../../provider/popup-provider";
import { HelpDialogProvider } from "../../provider/help-dialog-context";
import type { MenuItem } from "../../api";
import { SidebarProvider } from "../sidebar";
import { LNB } from "../lnb";
@@ -25,22 +24,20 @@ export function NoFooterLayout({
return (
<QueryProvider queryClient={queryClient}>
<PopupProvider>
<HelpDialogProvider>
<SidebarProvider>
<div className="flex-1">
<Header authService={authService} />
<div className="flex">
<LNB
currentPath={currentPath}
handleMenuClick={handleMenuClick}
/>
<div className="flex min-h-[calc(100vh-50px)] flex-1 flex-col overflow-auto">
<div className="flex-1">{children}</div>
</div>
<SidebarProvider>
<div className="flex-1">
<Header authService={authService} />
<div className="flex">
<LNB
currentPath={currentPath}
handleMenuClick={handleMenuClick}
/>
<div className="flex min-h-[calc(100vh-50px)] flex-1 flex-col overflow-auto">
<div className="flex-1">{children}</div>
</div>
</div>
</SidebarProvider>
</HelpDialogProvider>
</div>
</SidebarProvider>
</PopupProvider>
</QueryProvider>
);
@@ -2,7 +2,6 @@ import type { AuthService } from "@common/auth";
import type { QueryClient } from "@tanstack/react-query";
import { QueryProvider } from "../../provider/query-provider";
import { PopupProvider } from "../../provider/popup-provider";
import { HelpDialogProvider } from "../../provider/help-dialog-context";
import type { MenuItem } from "../../api";
import { SidebarProvider } from "../sidebar";
import { Header } from "../header";
@@ -23,19 +22,17 @@ export function NoLNBLayout({
return (
<QueryProvider queryClient={queryClient}>
<PopupProvider>
<HelpDialogProvider>
<SidebarProvider>
<div className="flex-1">
<Header authService={authService} />
<div className="flex">
<div className="flex min-h-[calc(100vh-50px)] flex-1 flex-col overflow-auto">
<div className="flex-1">{children}</div>
<Footer />
</div>
<SidebarProvider>
<div className="flex-1">
<Header authService={authService} />
<div className="flex">
<div className="flex min-h-[calc(100vh-50px)] flex-1 flex-col overflow-auto">
<div className="flex-1">{children}</div>
<Footer />
</div>
</div>
</SidebarProvider>
</HelpDialogProvider>
</div>
</SidebarProvider>
</PopupProvider>
</QueryProvider>
);
@@ -1,5 +1,4 @@
import { QueryProvider } from "../../provider/query-provider";
import { HelpDialogProvider } from "../../provider/help-dialog-context";
import { SidebarProvider } from "../sidebar";
import { LNB } from "../lnb";
import { Header } from "../header";
@@ -17,8 +16,7 @@ export function VBaseLayout({
}) {
return (
<QueryProvider queryClient={queryClient}>
<HelpDialogProvider>
<SidebarProvider>
<SidebarProvider>
<div className="flex-1">
<Header viewOnly />
<div className="flex h-[calc(100vh-50px)]">
@@ -32,7 +30,6 @@ export function VBaseLayout({
</div>
</div>
</SidebarProvider>
</HelpDialogProvider>
</QueryProvider>
);
}
@@ -22,16 +22,8 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "../collapsible";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "../dialog";
import { ENDPOINT } from "../../config";
import { cn, getCookie, setCookie } from "../../lib";
import { useHelpDialog } from "../../provider/help-dialog-context";
import {
getMenuList,
getPreviewTreeMenuList,
@@ -65,13 +57,6 @@ export function LNB({
const [currentMenuCode, setCurrentMenuCode] = useState<number | null>(null);
const prevPathRef = useRef(currentPath);
const { browser } = useDetectDevice();
const {
isOpen: isHelpModalOpen,
openHelp,
closeHelp,
setHelpContent,
helpContent,
} = useHelpDialog();
const appSiteId = getCookie("site-id-key") ?? "";
const siteId = propSiteId ?? appSiteId;
@@ -110,7 +95,6 @@ export function LNB({
const matchedMenuIds: number[] = [];
let matchedMenuCode: number | null = null;
let matchedMenuHelp: string = "";
const findMatchedMenus = (items: MenuItem[]) => {
items.forEach((item) => {
@@ -127,7 +111,6 @@ export function LNB({
if (matchedMenuCode) return;
if (currentPath === item.urlPath) {
matchedMenuCode = item.menuCd;
matchedMenuHelp = item.menuHlpCn || "";
}
if (item.children) findMatchedMenuCode(item.children);
});
@@ -148,7 +131,6 @@ export function LNB({
if (matchedMenuCode) {
setCurrentMenuCode(matchedMenuCode);
setHelpContent(matchedMenuHelp);
}
// 접속 로그 저장
@@ -298,46 +280,6 @@ export function LNB({
<MenuItem key={item.menuCd} item={item} />
))}
</SidebarMenu>
{/* 도움말 아이콘 */}
<div className="mt-auto pb-4">
<Dialog
open={isHelpModalOpen}
onOpenChange={(open) => (open ? openHelp() : closeHelp())}
>
<DialogTrigger asChild></DialogTrigger>
<DialogContent className="flex max-h-[90vh] flex-col sm:max-w-[85rem]">
<DialogHeader>
<DialogTitle>도움말</DialogTitle>
</DialogHeader>
<div className="min-h-0 flex-1 overflow-y-auto py-4">
{helpContent ? (
<div
style={{
fontSize: "16px",
lineHeight: "1.5",
}}
>
<div
dangerouslySetInnerHTML={{
__html: helpContent
.replace(/<body[^>]*>/gi, "<div>")
.replace(/<\/body>/gi, "</div>"),
}}
style={{
fontSize: "inherit",
}}
/>
</div>
) : (
<p className="text-sm text-muted-foreground">
현재 페이지에 대한 도움말이 없습니다.
</p>
)}
</div>
</DialogContent>
</Dialog>
</div>
</SidebarContent>
</Sidebar>
);
@@ -1,43 +1,95 @@
"use client";
import React from "react";
import { useHelpDialog } from "../../provider/help-dialog-context";
import React, { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "../dialog";
import { useQuery } from "@tanstack/react-query";
import { getMenuDetail } from "../../api";
import { ENDPOINT } from "../../config";
const PageTitle = ({
title,
menuCd,
menuPaths,
}: {
title: string;
menuCd?: number;
menuPaths: string[];
}) => {
const { openHelp } = useHelpDialog();
const [isHelpDialogOpen, setIsHelpDialogOpen] = useState(false);
const { data: menuDetail } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.MENUS, menuCd],
queryFn: () => getMenuDetail(menuCd!),
enabled: !!menuCd,
});
return (
<div className="flex w-full items-center justify-between px-[1.8rem] pt-[2rem]">
<div className="flex items-center gap-3">
<h2 className="text-[2.4rem] font-semibold text-title">{title}</h2>
<>
<div className="flex w-full items-center justify-between px-[1.8rem] pt-[2rem]">
<div className="flex items-center gap-3">
<h2 className="text-[2.4rem] font-semibold text-title">{title}</h2>
</div>
<div className="flex items-center gap-3">
{menuPaths.length > 0 && (
<div className="flex items-center gap-3">
<i className="diveicon di-home-fill text-foreground" />
{menuPaths?.map((path, i) => (
<React.Fragment key={`${i}-${path}`}>
{i !== 0 && (
<i className="diveicon di-arrow-forward text-foreground" />
)}
<span className="text-xl text-foreground">{path}</span>
</React.Fragment>
))}
</div>
)}
<button
onClick={() => setIsHelpDialogOpen(true)}
className="flex cursor-pointer items-center gap-3 transition-opacity hover:opacity-80"
>
<img
src="/images/help.png"
alt="도움말"
className="h-[20px] w-[20px]"
/>
</button>
</div>
</div>
<div className="flex items-center gap-3">
{menuPaths.length > 0 && (
<div className="flex items-center gap-3">
<i className="diveicon di-home-fill text-foreground" />
{menuPaths?.map((path, i) => (
<React.Fragment key={`${i}-${path}`}>
{i !== 0 && (
<i className="diveicon di-arrow-forward text-foreground" />
)}
<span className="text-xl text-foreground">{path}</span>
</React.Fragment>
))}
</div>
)}
<button
onClick={openHelp}
className="flex items-center gap-3 cursor-pointer hover:opacity-80 transition-opacity"
>
<img src="/images/help.png" alt="도움말" className="w-[20px] h-[20px]" />
</button>
</div>
</div>
{/* 도움말 다이얼로그 */}
<Dialog open={isHelpDialogOpen} onOpenChange={setIsHelpDialogOpen}>
<DialogContent className="flex max-h-[90vh] flex-col sm:max-w-[85rem]">
<DialogHeader>
<DialogTitle>도움말</DialogTitle>
</DialogHeader>
<div className="min-h-0 flex-1 overflow-y-auto py-4">
{menuDetail?.menuHlpCn ? (
<div
style={{
fontSize: "16px",
lineHeight: "1.5",
}}
>
<div
dangerouslySetInnerHTML={{
__html: menuDetail.menuHlpCn
.replace(/<body[^>]*>/gi, "<div>")
.replace(/<\/body>/gi, "</div>"),
}}
style={{
fontSize: "inherit",
}}
/>
</div>
) : (
<p className="text-lg text-muted-foreground">
현재 페이지에 대한 도움말이 없습니다.
</p>
)}
</div>
</DialogContent>
</Dialog>
</>
);
};
@@ -18,6 +18,18 @@
.table-ui.default th {
@apply bg-[#5987bf] text-[#fff];
}
.table-ui th.data-table-group-header {
background-image: linear-gradient(
to right,
transparent 0.2rem,
var(--background) 0.2rem,
var(--background) calc(100% - 0.2rem),
transparent calc(100% - 0.2rem)
);
background-position: left bottom;
background-repeat: no-repeat;
background-size: 100% 1px;
}
.table-ui.default td {
@apply border-b border-b-border text-label;
}