Merge commit '16541d6d54b044ec5f6bb60db6ef101401cb81ae' into iipbs/wr/form_fuction
This commit is contained in:
@@ -1,42 +1,127 @@
|
||||
"use client"
|
||||
import type { CSSProperties } from "react";
|
||||
import {
|
||||
Card,
|
||||
CardContent
|
||||
} from "./lib/card";
|
||||
import { Bar, BarChart, CartesianGrid, Legend, XAxis, YAxis } from "recharts";
|
||||
import {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
type ChartConfig
|
||||
} from "./lib/chart";
|
||||
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts";
|
||||
import type { CSSProperties } from "react";
|
||||
|
||||
export default function Chart(props: { chartConfig: ChartConfig; chartData: any[] | undefined; chartTitle: string}) {
|
||||
const customStyles = {
|
||||
legendContainer: {
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
gap: "20px",
|
||||
fontSize: "9px",
|
||||
fontWeight : "bold",
|
||||
marginTop: "10px",
|
||||
} as CSSProperties,
|
||||
};
|
||||
|
||||
type BarChartProps = {
|
||||
chartConfig: ChartConfig | undefined;
|
||||
chartData: any[] | undefined;
|
||||
chartTitle: string;
|
||||
chartClassName?: string;
|
||||
graphSize?: number;
|
||||
yFieldText?: string;
|
||||
showLegend?: boolean;
|
||||
}
|
||||
|
||||
// 커스텀 툴팁
|
||||
const CustomTooltip = ({
|
||||
active,
|
||||
payload,
|
||||
label
|
||||
}: {
|
||||
active?: boolean;
|
||||
payload?: Array<{
|
||||
name: string;
|
||||
value: number;
|
||||
color: string;
|
||||
}>;
|
||||
label?: string;
|
||||
}) => {
|
||||
if (active && payload && payload.length) {
|
||||
return (
|
||||
<div className="w-[180px] rounded bg-white p-2.5 shadow-[0px_2px_10px_rgba(0,0,0,0.2)]">
|
||||
<p className="text-[12px] font-bold m-3">{label}</p>
|
||||
{payload.map((item, index) => (
|
||||
<div key={index} style={{ marginTop: "10px", display: "flex", alignItems: "center", gap: "8px" }}>
|
||||
{/* 색상 박스 추가 (범례 색상과 동일) */}
|
||||
<div style={{ width: "10px", height: "10px", backgroundColor: item.color, borderRadius: "50%" }}></div>
|
||||
<span className="text-[11px] font-bold">{` ${item.name} : ${item.value}`}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// 커스텀 범례 (글씨 크기 키우기 + 스타일 추가)
|
||||
const CustomLegend = (props: any) => {
|
||||
const { payload } = props;
|
||||
return (
|
||||
<Card className="h-full">
|
||||
<CardContent className="h-full">
|
||||
{props.chartTitle && props.chartTitle !== "" && props.chartTitle !== "undefined" ? (
|
||||
<div style={{ textAlign: "left", fontSize: "13px", fontWeight: "bold", marginTop:"13px", marginBottom: "10px" }}>
|
||||
{props.chartTitle}
|
||||
</div>): null}
|
||||
<div className="h-[calc(100%-42px)] flex justify-center">
|
||||
<ChartContainer config={props.chartConfig} className="h-full w-full">
|
||||
<BarChart accessibilityLayer data={props.chartData} className="h-full">
|
||||
<CartesianGrid vertical={false} />
|
||||
<XAxis
|
||||
dataKey="label"
|
||||
tickLine={false}
|
||||
tickMargin={10}
|
||||
axisLine={false}
|
||||
tickFormatter={(value) => value.slice(0, 3)}
|
||||
/>
|
||||
<ChartTooltip cursor={false} content={<ChartTooltipContent indicator="dashed" />}/>
|
||||
<Bar dataKey="val" radius={10} />
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
<div style={customStyles.legendContainer}>
|
||||
{payload.map((entry, index: number) => (
|
||||
<div key={`legend-${index}`} className="flex items-center gap-2">
|
||||
<div className="w-[14px] h-[14px] ml-10" style={{ backgroundColor: entry.color }}></div>
|
||||
<span className="text-[12px]">{entry.value}</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default function Chart({chartConfig=undefined, chartData=[], chartTitle='차트', chartClassName='w-full h-full', graphSize=40, yFieldText='', showLegend=false} : BarChartProps) {
|
||||
const colors = ["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEEAD", "#D4A5A5"];
|
||||
|
||||
return (
|
||||
<>
|
||||
{chartTitle && chartTitle !== "" && chartTitle !== "undefined" ? (
|
||||
<div className="!mt-3 text-[2.5rem] font-bold">
|
||||
{chartTitle}
|
||||
</div>): null}
|
||||
<div className="flex justify-center">
|
||||
<ChartContainer config={chartConfig ?? {}} className={chartClassName + " !w-[90%]"}>
|
||||
<BarChart accessibilityLayer data={chartData}>
|
||||
<CartesianGrid vertical={false} />
|
||||
<XAxis
|
||||
dataKey="label"
|
||||
tickLine={true}
|
||||
tickMargin={10}
|
||||
axisLine={true}
|
||||
fontSize={13}
|
||||
fontWeight={500}
|
||||
/>
|
||||
<YAxis
|
||||
tickLine={true}
|
||||
tickMargin={10}
|
||||
tickCount={6}
|
||||
axisLine={true}
|
||||
fontSize={12}
|
||||
fontWeight={500}
|
||||
label={yFieldText ? { value: yFieldText, className:"text-[13px] foont-bold", position: 'top', textAnchor: 'middle', offset: 20 } : undefined}
|
||||
/>
|
||||
<ChartTooltip cursor={false} content={<CustomTooltip active={undefined} payload={undefined} label={undefined} />}/>
|
||||
{chartData && chartData.length > 0 && (
|
||||
Object.keys(chartData[0])
|
||||
.filter(key => key !== "label")
|
||||
.map((key, idx) => (
|
||||
<Bar
|
||||
dataKey={key}
|
||||
radius={5}
|
||||
key={key}
|
||||
barSize={graphSize}
|
||||
fill={colors[idx % colors.length]}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
{showLegend && <Legend content={CustomLegend}/>}
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,37 +1,15 @@
|
||||
"use client"
|
||||
import type { CSSProperties } from "react";
|
||||
import { Bar, CartesianGrid, ComposedChart, Legend, Line, Tooltip, XAxis, YAxis } from "recharts";
|
||||
import {
|
||||
Card,
|
||||
CardContent
|
||||
} from "./lib/card";
|
||||
import {
|
||||
ChartContainer,
|
||||
type ChartConfig
|
||||
} from "./lib/chart";
|
||||
import React from "react";
|
||||
import type { ContentType } from "recharts/types/component/DefaultLegendContent";
|
||||
|
||||
// 툴팁 커스텀 css
|
||||
// 툴크 커스텀 css
|
||||
/** 차트 기본 스타일 */
|
||||
const styles = {
|
||||
tooltipDiv: {
|
||||
borderRadius: "5px",
|
||||
backgroundColor: "white",
|
||||
padding: "10px",
|
||||
boxShadow: "0px 2px 10px rgba(0,0,0,0.2)",
|
||||
width: "180px", // 적절한 크기로 설정
|
||||
} as React.CSSProperties,
|
||||
tooltipLabel: {
|
||||
fontWeight: "bold",
|
||||
fontSize: "12px",
|
||||
marginBottom: "5px",
|
||||
borderBottom: "1px solid #ddd",
|
||||
paddingBottom: "3px",
|
||||
} as React.CSSProperties,
|
||||
tooltipText: {
|
||||
fontSize: "11px",
|
||||
fontWeight:"bold",
|
||||
} as React.CSSProperties,
|
||||
const customStyles = {
|
||||
legendContainer: {
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
@@ -42,17 +20,39 @@ const styles = {
|
||||
} as CSSProperties,
|
||||
};
|
||||
|
||||
type LineBarChartProps = {
|
||||
chartConfig: ChartConfig | undefined;
|
||||
chartData: any[] | undefined;
|
||||
chartTitle: string;
|
||||
chartClassName?: string;
|
||||
graphSize?: number;
|
||||
yFieldText?: string | undefined;
|
||||
yFieldText2?: string | undefined;
|
||||
showLegend?: boolean;
|
||||
}
|
||||
|
||||
type LegendEntry = {
|
||||
value: string;
|
||||
color: string;
|
||||
type?: string;
|
||||
payload?: unknown;
|
||||
};
|
||||
|
||||
type LegendProps = {
|
||||
payload?: LegendEntry[];
|
||||
};
|
||||
|
||||
// 커스텀 툴팁
|
||||
const CustomTooltip = ({ active, payload, label }) => {
|
||||
const CustomTooltip = ({ active, payload, label }: { active?: boolean; payload?: Array<{ name: string; value: number; color: string }>; label?: string }) => {
|
||||
if (active && payload && payload.length) {
|
||||
return (
|
||||
<div style={styles.tooltipDiv}>
|
||||
<p style={styles.tooltipLabel}>{label}</p>
|
||||
<div className="w-[180px] rounded bg-white p-2.5 shadow-[0px_2px_10px_rgba(0,0,0,0.2)]">
|
||||
<p className="text-[12px] font-bold m-3">{label}</p>
|
||||
{payload.map((item, index) => (
|
||||
<div key={index} style={{ marginTop: "10px", display: "flex", alignItems: "center", gap: "8px" }}>
|
||||
{/* 색상 박스 추가 (범례 색상과 동일) */}
|
||||
<div style={{ width: "10px", height: "10px", backgroundColor: item.color, borderRadius: "50%" }}></div>
|
||||
<span style={styles.tooltipText}>{`${item.name}: ${item.value}`}</span>
|
||||
<span className="text-[11px] font-bold">{` ${item.name} : ${item.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -62,47 +62,128 @@ const CustomTooltip = ({ active, payload, label }) => {
|
||||
};
|
||||
|
||||
// 커스텀 범례 (글씨 크기 키우기 + 스타일 추가)
|
||||
const CustomLegend = (props: any) => {
|
||||
const CustomLegend = (props: LegendProps) => {
|
||||
const { payload } = props;
|
||||
if (!payload) return null;
|
||||
|
||||
return (
|
||||
<div style={styles.legendContainer}>
|
||||
{payload.map((entry, index) => (
|
||||
<div key={`legend-${index}`} style={{ display: "flex", alignItems: "center", gap: "8px" }}>
|
||||
<div style={{ width: "12px", height: "12px", backgroundColor: entry.color, borderRadius: "50%" }}></div>
|
||||
<span>{entry.value}</span>
|
||||
<div style={customStyles.legendContainer}>
|
||||
{payload.map((entry: LegendEntry, index: number) => (
|
||||
<div key={`legend-${index}`} className="flex items-center gap-2">
|
||||
<div className="w-[14px] h-[14px] ml-10" style={{ backgroundColor: entry.color }}></div>
|
||||
<span className="text-[12px]">{entry.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default function LineBarchart(props: { chartConfig: ChartConfig; chartData: any[] | undefined; chartTitle:string }) {
|
||||
export default function LineBarchart({
|
||||
chartConfig,
|
||||
chartData,
|
||||
chartTitle,
|
||||
chartClassName = 'w-full h-full',
|
||||
graphSize = 40,
|
||||
yFieldText,
|
||||
yFieldText2,
|
||||
showLegend = true
|
||||
}: LineBarChartProps) {
|
||||
if (!chartData || chartData.length === 0) {
|
||||
return <div>데이터가 없습니다.</div>;
|
||||
}
|
||||
|
||||
const barConfig = chartConfig?.barVal;
|
||||
const lineConfig = chartConfig?.lineVal;
|
||||
|
||||
// 데이터의 최대값 계산
|
||||
const getMaxValue = (data: any[], keyPrefix: string) => {
|
||||
return Math.max(...data.map(item =>
|
||||
Object.keys(item)
|
||||
.filter(key => key.includes(keyPrefix))
|
||||
.map(key => item[key])
|
||||
).flat());
|
||||
};
|
||||
|
||||
const lineMaxValue = getMaxValue(chartData, 'lineVal');
|
||||
const barMaxValue = getMaxValue(chartData, 'barVal');
|
||||
|
||||
return (
|
||||
<Card className="h-full">
|
||||
<CardContent className="h-full">
|
||||
{props.chartTitle && props.chartTitle !== "" && props.chartTitle !== "undefined" ? (
|
||||
<div className={chartClassName}>
|
||||
{chartTitle && chartTitle !== "" && chartTitle !== "undefined" ? (
|
||||
<div style={{ textAlign: "left", fontSize: "13px", fontWeight: "bold", marginTop:"13px", marginBottom: "10px" }}>
|
||||
{props.chartTitle}
|
||||
</div>): null}
|
||||
<div className="h-[calc(100%-42px)] flex justify-center">
|
||||
<ChartContainer config={props.chartConfig} className="h-full w-full" >
|
||||
<ComposedChart data={props.chartData} className="h-full ">
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="label" fontSize="8px" fontWeight="bold"/>
|
||||
{/* 왼쪽 Y축: lineVal (정상) */}
|
||||
<YAxis yAxisId="left" orientation="left" />
|
||||
{/* 오른쪽 Y축: barVal (위에서 아래로 반전) */}
|
||||
<YAxis yAxisId="right" orientation="right" reversed />
|
||||
<Tooltip content={<CustomTooltip active={undefined} payload={undefined} label={undefined} />} />
|
||||
<Legend content={CustomLegend}/>
|
||||
{/* 바 차트 (오른쪽 Y축 사용, 위에서 아래로) */}
|
||||
<Bar yAxisId="right" dataKey="barVal" fill="#8884d8" name="강수량(mm/일)"/>
|
||||
{/* 라인 차트 (왼쪽 Y축 사용) */}
|
||||
<Line yAxisId="left" type="monotone" dataKey="lineVal" stroke="orange" strokeWidth={2} dot={{r: 0}} name="BOD(mg/L)"/>
|
||||
</ComposedChart>
|
||||
</ChartContainer>
|
||||
{chartTitle}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
) : null}
|
||||
<div className="h-[calc(100%-42px)] flex justify-center">
|
||||
<ChartContainer config={chartConfig ?? {}} className="h-full w-full">
|
||||
<ComposedChart
|
||||
data={chartData}
|
||||
height={graphSize * 7.5}
|
||||
width={graphSize * 12.5}
|
||||
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
|
||||
>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="label" fontSize="8px" fontWeight="bold"/>
|
||||
{/* 왼쪽 Y축: lineVal */}
|
||||
{yFieldText && <YAxis
|
||||
yAxisId="left"
|
||||
className="text-[12px] font-bold"
|
||||
tickCount={6}
|
||||
orientation="left"
|
||||
domain={[0, Math.ceil(lineMaxValue * 1.1)]}
|
||||
label={{ value: yFieldText, angle: -90, position: 'insideLeft' }}
|
||||
/>}
|
||||
{/* 오른쪽 Y축: barVal */}
|
||||
{yFieldText2 && <YAxis
|
||||
yAxisId="right"
|
||||
className="text-[12px] font-bold"
|
||||
tickCount={6}
|
||||
orientation="right"
|
||||
domain={[0, Math.ceil(barMaxValue * 1.1)]}
|
||||
label={{ value: yFieldText2, angle: -90, position: 'insideRight' }}
|
||||
reversed={true}
|
||||
/>}
|
||||
<Tooltip content={<CustomTooltip active={undefined} payload={undefined} label={undefined} />} />
|
||||
{showLegend && <Legend content={CustomLegend as ContentType}/>}
|
||||
{/* 바 차트 (오른쪽 Y축 사용) */}
|
||||
{Object.keys(chartData[0]).map((key, index) => {
|
||||
const config = chartConfig?.[key];
|
||||
if(key.includes("barVal")) {
|
||||
return (
|
||||
<Bar
|
||||
key={`bar-${key}-${index}`}
|
||||
yAxisId="right"
|
||||
dataKey={key}
|
||||
fill={config?.color || "black"}
|
||||
name={String(config?.label || "Y축")}
|
||||
maxBarSize={80}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})}
|
||||
{/* 라인 차트 (왼쪽 Y축 사용) */}
|
||||
{Object.keys(chartData[0]).map((key, index) => {
|
||||
const config = chartConfig?.[key];
|
||||
if(key.includes("lineVal")) {
|
||||
return (
|
||||
<Line
|
||||
key={`line-${key}-${index}`}
|
||||
yAxisId="left"
|
||||
type="linear"
|
||||
dataKey={key}
|
||||
stroke={config?.color || "black"}
|
||||
strokeWidth={2}
|
||||
dot={{r: 0}}
|
||||
name={String(config?.label || "X축")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})}
|
||||
</ComposedChart>
|
||||
</ChartContainer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,37 +1,24 @@
|
||||
"use client"
|
||||
import type { CSSProperties } from "react";
|
||||
import {
|
||||
Card,
|
||||
CardContent
|
||||
} from "./lib/card";
|
||||
import { CartesianGrid, Legend, Line, LineChart, Tooltip, XAxis, YAxis } from "recharts";
|
||||
import {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
type ChartConfig
|
||||
} from "./lib/chart";
|
||||
import { CartesianGrid, Legend, Line, LineChart, Tooltip, XAxis, YAxis } from "recharts";
|
||||
import type { ContentType } from "recharts/types/component/DefaultLegendContent";
|
||||
|
||||
type LineChartProps = {
|
||||
chartConfig: ChartConfig | undefined;
|
||||
chartData: ChartDataType | undefined;
|
||||
chartTitle: string;
|
||||
chartClassName?: string;
|
||||
graphSize?: number;
|
||||
yFieldText?: string;
|
||||
showLegend?: boolean;
|
||||
}
|
||||
|
||||
/** 차트 기본 스타일 */
|
||||
const styles = {
|
||||
tooltipDiv: {
|
||||
borderRadius: "5px",
|
||||
backgroundColor: "white",
|
||||
padding: "10px",
|
||||
boxShadow: "0px 2px 10px rgba(0,0,0,0.2)",
|
||||
width: "180px", // 적절한 크기로 설정
|
||||
} as React.CSSProperties,
|
||||
tooltipLabel: {
|
||||
fontWeight: "bold",
|
||||
fontSize: "12px",
|
||||
marginBottom: "5px",
|
||||
borderBottom: "1px solid #ddd",
|
||||
paddingBottom: "3px",
|
||||
} as React.CSSProperties,
|
||||
tooltipText: {
|
||||
fontSize: "11px",
|
||||
fontWeight:"bold",
|
||||
} as React.CSSProperties,
|
||||
const customStyles = {
|
||||
legendContainer: {
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
@@ -42,17 +29,28 @@ const styles = {
|
||||
} as CSSProperties,
|
||||
};
|
||||
|
||||
type LegendEntry = {
|
||||
value: string;
|
||||
color: string;
|
||||
type?: string;
|
||||
payload?: unknown;
|
||||
};
|
||||
|
||||
type LegendProps = {
|
||||
payload?: LegendEntry[];
|
||||
};
|
||||
|
||||
// 커스텀 툴팁
|
||||
const CustomTooltip = ({ active, payload, label }) => {
|
||||
const CustomTooltip = ({ active, payload, label }: { active?: boolean; payload?: Array<{ name: string; value: number; color: string }>; label?: string }) => {
|
||||
if (active && payload && payload.length) {
|
||||
return (
|
||||
<div style={styles.tooltipDiv}>
|
||||
<p style={styles.tooltipLabel}>{label}</p>
|
||||
<div className="w-[180px] rounded bg-white p-2.5 shadow-[0px_2px_10px_rgba(0,0,0,0.2)]">
|
||||
<p className="text-[12px] font-bold m-3">{label}</p>
|
||||
{payload.map((item, index) => (
|
||||
<div key={index} style={{ marginTop: "10px", display: "flex", alignItems: "center", gap: "8px" }}>
|
||||
{/* 색상 박스 추가 (범례 색상과 동일) */}
|
||||
<div style={{ width: "10px", height: "10px", backgroundColor: item.color, borderRadius: "50%" }}></div>
|
||||
<span style={styles.tooltipText}>{`${item.name}: ${item.value}`}</span>
|
||||
<span className="text-[11px] font-bold">{` ${item.name} : ${item.value}`}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -62,60 +60,107 @@ const CustomTooltip = ({ active, payload, label }) => {
|
||||
};
|
||||
|
||||
// 커스텀 범례 (글씨 크기 키우기 + 스타일 추가)
|
||||
const CustomLegend = (props: any) => {
|
||||
const CustomLegend = (props: LegendProps) => {
|
||||
const { payload } = props;
|
||||
if (!payload) return null;
|
||||
|
||||
return (
|
||||
<div style={styles.legendContainer}>
|
||||
{payload.map((entry, index) => (
|
||||
<div key={`legend-${index}`} style={{ display: "flex", alignItems: "center", gap: "8px" }}>
|
||||
<div style={{ width: "12px", height: "12px", backgroundColor: entry.color, borderRadius: "50%" }}></div>
|
||||
<span>{entry.value}</span>
|
||||
<div style={customStyles.legendContainer}>
|
||||
{payload.map((entry: LegendEntry, index: number) => (
|
||||
<div key={`legend-${index}`} className="flex items-center gap-2">
|
||||
<div className="w-[14px] h-[14px] ml-10" style={{ backgroundColor: entry.color }}></div>
|
||||
<span className="text-[12px]">{entry.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
type DataType = {label : string; val:number};
|
||||
type DataType = {label: string; val: string};
|
||||
|
||||
type ChartDataType = {
|
||||
chartData1: DataType[];
|
||||
chartData2: DataType[];
|
||||
[key: string]: DataType[];
|
||||
};
|
||||
|
||||
export default function Linechart(props: { chartConfig: ChartConfig; chartData: ChartDataType; chartTitle:string}) {
|
||||
const mergedData = Object.values(props.chartData).reduce((acc, dataset) => {
|
||||
export default function Linechart({
|
||||
chartConfig,
|
||||
chartData,
|
||||
chartTitle,
|
||||
chartClassName = 'w-full h-full',
|
||||
graphSize = 40,
|
||||
yFieldText,
|
||||
showLegend = true
|
||||
}: LineChartProps) {
|
||||
if (!chartData || Object.keys(chartData).length === 0) {
|
||||
return <div>데이터가 없습니다.</div>;
|
||||
}
|
||||
|
||||
// 모든 데이터셋이 비어있는지 확인
|
||||
const hasNoData = Object.values(chartData).every(dataset => !dataset || dataset.length === 0);
|
||||
if (hasNoData) {
|
||||
return <div>데이터가 없습니다.</div>;
|
||||
}
|
||||
|
||||
// 데이터 병합 및 변환
|
||||
const mergedData = Object.entries(chartData).reduce<Array<{[key: string]: string | number}>>((acc, [key, dataset]) => {
|
||||
dataset.forEach((entry, index) => {
|
||||
if (!acc[index]) {
|
||||
acc[index] = { label: entry.label }; // label 추가
|
||||
acc[index] = { label: entry.label };
|
||||
}
|
||||
const key = Object.keys(props.chartData).find(k => props.chartData[k] === dataset);
|
||||
if (key) acc[index][key] = entry.val;
|
||||
acc[index][key] = parseFloat(entry.val);
|
||||
});
|
||||
return acc;
|
||||
}, [] as any[]);
|
||||
}, []);
|
||||
|
||||
// 데이터의 최대값 계산
|
||||
const getMaxValue = (data: ChartDataType, keyPrefix: string) => {
|
||||
return Math.max(...Object.values(data).map(item =>
|
||||
Object.keys(item)
|
||||
.filter(key => key.includes(keyPrefix))
|
||||
.map(key => item[key] as unknown as number)
|
||||
).flat());
|
||||
};
|
||||
|
||||
const lineMaxValue = getMaxValue(chartData, 'lineVal');
|
||||
|
||||
return (
|
||||
<Card className="h-full">
|
||||
<CardContent className="h-full">
|
||||
{props.chartTitle && props.chartTitle !== "" && props.chartTitle !== "undefined" ? (
|
||||
<div className={chartClassName}>
|
||||
{chartTitle && chartTitle !== "" && chartTitle !== "undefined" ? (
|
||||
<div style={{ textAlign: "left", fontSize: "13px", fontWeight: "bold", marginTop:"13px", marginBottom: "10px" }}>
|
||||
{props.chartTitle}
|
||||
</div>): null}
|
||||
<div className="h-[calc(100%-42px)] flex justify-center">
|
||||
<ChartContainer config={props.chartConfig} className="h-full w-full">
|
||||
<LineChart data={mergedData} className="h-full">
|
||||
<CartesianGrid vertical={false} />
|
||||
<XAxis dataKey="label" fontSize="8px" fontWeight="bold"/>
|
||||
<YAxis yAxisId="left" orientation="left" />
|
||||
<Tooltip content={<CustomTooltip active={undefined} payload={undefined} label={undefined} />} />
|
||||
<Legend content={CustomLegend}/>
|
||||
{Object.keys(props.chartData).map((key, index) => (
|
||||
<Line key={key} yAxisId="left" dataKey={key} type="linear" strokeWidth={2} dot={false} name={key} />
|
||||
))}
|
||||
</LineChart>
|
||||
</ChartContainer>
|
||||
{chartTitle}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
) : null}
|
||||
<div className="h-[calc(100%-42px)] flex justify-center">
|
||||
<ChartContainer config={chartConfig ?? {}} className="h-full w-full">
|
||||
<LineChart
|
||||
data={mergedData}
|
||||
height={graphSize * 7.5}
|
||||
width={graphSize * 12.5}
|
||||
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
|
||||
>
|
||||
<CartesianGrid vertical={false} />
|
||||
<XAxis dataKey="label" fontSize="8px" fontWeight="bold" />
|
||||
<YAxis yAxisId="left" className="text-[12px] font-bold" domain={[0, Math.ceil(lineMaxValue * 1.1)]} tickCount={6} orientation="left" label={{ value: yFieldText, className:"text-[12px] font-bold", angle: -90, position: 'insideLeft' }} />
|
||||
<Tooltip content={<CustomTooltip />} />
|
||||
{showLegend && <Legend content={CustomLegend as ContentType}/>}
|
||||
{Object.keys(chartData).map((key) => {
|
||||
const config = chartConfig?.[key];
|
||||
return (
|
||||
<Line
|
||||
key={key}
|
||||
yAxisId="left"
|
||||
dataKey={key}
|
||||
type="linear"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
name={String(config?.label || "X축")}
|
||||
stroke={config?.color}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</LineChart>
|
||||
</ChartContainer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -18,15 +18,41 @@ const CHART_FORM = {
|
||||
LINEBAR : 'linebar'
|
||||
};
|
||||
|
||||
function MainChart(props: { chartForm: string; chartConfig: any; chartData: any; chartTitle:string; }) {
|
||||
/**
|
||||
* 차트 컴포넌트
|
||||
* @param chartForm 차트 형태
|
||||
* @param chartConfig 차트 설정
|
||||
* @param chartData 차트 데이터
|
||||
* @param chartTitle 차트 제목
|
||||
* @param chartClassName 차트 클래스명
|
||||
* @param graphSize 차트 크기
|
||||
* @param yFieldText 차트 Y축 텍스트
|
||||
* @param yFieldText2 차트 Y축 텍스트2(라인바 차트때 사용)
|
||||
* @param showLegend 차트 범례 표시 여부
|
||||
* @returns
|
||||
*/
|
||||
|
||||
type MainChartProps = {
|
||||
chartForm: string;
|
||||
chartConfig: any;
|
||||
chartData: any;
|
||||
chartTitle: string;
|
||||
chartClassName?: string;
|
||||
graphSize?: number;
|
||||
yFieldText? : string | undefined;
|
||||
yFieldText2? : string | undefined;
|
||||
showLegend? : boolean;
|
||||
}
|
||||
|
||||
function MainChart(props: MainChartProps) {
|
||||
if( props.chartForm == CHART_FORM.BAR ){
|
||||
return (
|
||||
<BarChart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle}>
|
||||
<BarChart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle} chartClassName={props.chartClassName} graphSize={props.graphSize} yFieldText={props.yFieldText} showLegend={props.showLegend}>
|
||||
</BarChart>
|
||||
);
|
||||
} else if( props.chartForm == CHART_FORM.LINE ){
|
||||
return (
|
||||
<LineChart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle}>
|
||||
<LineChart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle} chartClassName={props.chartClassName} graphSize={props.graphSize} yFieldText={props.yFieldText} showLegend={props.showLegend}>
|
||||
</LineChart>
|
||||
);
|
||||
} else if( props.chartForm == CHART_FORM.DN ){
|
||||
@@ -36,7 +62,7 @@ function MainChart(props: { chartForm: string; chartConfig: any; chartData: any;
|
||||
);
|
||||
} else if (props.chartForm == CHART_FORM.LINEBAR){
|
||||
return (
|
||||
<LineBarchart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle}>
|
||||
<LineBarchart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle} chartClassName={props.chartClassName} graphSize={props.graphSize} yFieldText={props.yFieldText} yFieldText2={props.yFieldText2} showLegend={props.showLegend}>
|
||||
</LineBarchart>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -28,8 +28,8 @@ export const FileUpload =
|
||||
id="fileInput"
|
||||
className="outline-dashed outline-1 outline-slate-500"
|
||||
>
|
||||
<div className="flex items-center justify-center flex-col p-8 w-full ">
|
||||
<CloudUpload className='text-gray-500 w-10 h-10' />
|
||||
<div className="flex items-center justify-center flex-col p-1 w-full ">
|
||||
<CloudUpload className='text-gray-500 w-5 h-4' />
|
||||
<p className="mb-1 text-sm text-gray-500 dark:text-gray-400">
|
||||
<span className="font-semibold">클릭 후 업로드 </span>
|
||||
혹은 파일을 드래그 해주세요
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
export default function MainDiv(props: {children: React.ReactNode}) {
|
||||
return (
|
||||
<div className="min-h-screen bg-container">
|
||||
<div className="h-auto bg-container">
|
||||
{props.children}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -10,14 +10,20 @@ interface UITabProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
defaultValue?: string;
|
||||
tabList: TabItem[];
|
||||
children: React.ReactNode;
|
||||
onValueChange?: (value: string) => void;
|
||||
}
|
||||
|
||||
const UITab = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
UITabProps
|
||||
>(({defaultValue, tabList, children}, ref)=>{
|
||||
>(({defaultValue, tabList, children, onValueChange, ...props}, ref)=>{
|
||||
return (
|
||||
<Tabs defaultValue={defaultValue || tabList[0]?.value} className={"w-full space-x-1 border-b border-gray-200"}>
|
||||
<Tabs
|
||||
defaultValue={defaultValue || tabList[0]?.value}
|
||||
className={"w-full space-x-1 border-b border-gray-200"}
|
||||
onValueChange={onValueChange}
|
||||
{...props}
|
||||
>
|
||||
<TabsList className="flex space-x-1">
|
||||
{tabList.map((tab) => (
|
||||
<TabsTrigger
|
||||
|
||||
@@ -72,7 +72,11 @@ export function UiTable({ tableData, headlist, pageSize, total, headName, childr
|
||||
onClick={() => handleCellClick(index, head.id)}
|
||||
key={`cell-${head.id}-${index}`}
|
||||
>
|
||||
{typeof el[head.id] === 'number' ? String(el[head.id]).replace(/\B(?=(\d{3})+(?!\d))/g, ",") : String(el[head.id] ?? '')}
|
||||
{String(el[head.id]).includes('.')
|
||||
? String(el[head.id]).split('.').map((part, index) =>
|
||||
index === 0 ? part.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : part
|
||||
).join('.')
|
||||
: String(el[head.id] ?? '').replace(/\B(?=(\d{3})+(?!\d))/g, ",")}
|
||||
</TableCell>:
|
||||
<TableCell
|
||||
className={`${head.align === 'right' ? 'text-right' : head.align === 'center' ? 'text-center' : typeof el[head.id] === 'number' ? 'text-right' : 'text-center'} ${
|
||||
@@ -82,7 +86,11 @@ export function UiTable({ tableData, headlist, pageSize, total, headName, childr
|
||||
onClick={() => handleCellClick(index, head.id)}
|
||||
key={`cell-${head.id}-${index}`}
|
||||
>
|
||||
{typeof el[head.id] === 'number' ? String(el[head.id]).replace(/\B(?=(\d{3})+(?!\d))/g, ",") : String(el[head.id] ?? '')}
|
||||
{String(el[head.id]).includes('.')
|
||||
? String(el[head.id]).split('.').map((part, index) =>
|
||||
index === 0 ? part.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : part
|
||||
).join('.')
|
||||
: String(el[head.id] ?? '').replace(/\B(?=(\d{3})+(?!\d))/g, ",")}
|
||||
</TableCell>
|
||||
)
|
||||
))}
|
||||
|
||||
@@ -7,16 +7,17 @@
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist/**"
|
||||
],
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.mjs",
|
||||
"require": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"./index.css": "./dist/index.css"
|
||||
},
|
||||
"files": [
|
||||
"dist/**"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"storybook": "storybook dev -p 6006",
|
||||
@@ -26,6 +27,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@common/assets": "workspace:*",
|
||||
"@common/config": "workspace:*",
|
||||
"@frontend-opensource/use-react-hooks": "^1.1.4",
|
||||
"@minoru/react-dnd-treeview": "^3.5.0",
|
||||
"@radix-ui/react-accordion": "^1.2.3",
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { Client } from "@common/network";
|
||||
import { BASE_URL, SITE_ID } from "../config";
|
||||
import { getConfig } from "@common/config";
|
||||
|
||||
export const client = Client.getInstance({
|
||||
baseURL: BASE_URL,
|
||||
siteId: SITE_ID,
|
||||
});
|
||||
const getClientInstance = () => {
|
||||
const config = getConfig();
|
||||
const { PROXY_HOST, SITE_ID } = config;
|
||||
const BASE_URL = `${PROXY_HOST}/server`;
|
||||
|
||||
return Client.getInstance({
|
||||
baseURL: BASE_URL,
|
||||
siteId: SITE_ID ?? "",
|
||||
});
|
||||
};
|
||||
|
||||
export const getApiClient = () => getClientInstance();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { client } from "./client";
|
||||
import { getApiClient } from "./client";
|
||||
import { ENDPOINT } from "../config";
|
||||
|
||||
export interface MenuItem {
|
||||
@@ -21,6 +21,8 @@ export interface MenuItem {
|
||||
requiredUrlPath: boolean;
|
||||
}
|
||||
|
||||
const client = getApiClient();
|
||||
|
||||
export const getMenuList = async (siteId: string) => {
|
||||
const response = await client.get<MenuItem[]>(
|
||||
`${ENDPOINT.CMS_SERVICE.MENU_ROLES}/${siteId}`,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { client } from "./client";
|
||||
import { getApiClient } from "./client";
|
||||
import { ENDPOINT } from "../config";
|
||||
|
||||
export interface SiteInfo {
|
||||
@@ -23,6 +23,8 @@ export interface SiteInfo {
|
||||
mdfrNm: string;
|
||||
}
|
||||
|
||||
const client = getApiClient();
|
||||
|
||||
export const getSiteInfo = async (siteId: string) => {
|
||||
const response = await client.get<SiteInfo>(
|
||||
`${ENDPOINT.CMS_SERVICE.SITES}/${siteId}`,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { client } from "./client";
|
||||
import { getApiClient } from "./client";
|
||||
import { ENDPOINT } from "../config";
|
||||
|
||||
export interface IUser {
|
||||
@@ -35,6 +35,8 @@ export interface IUser {
|
||||
hasPassword: boolean;
|
||||
}
|
||||
|
||||
const client = getApiClient();
|
||||
|
||||
export const getUserInfo = async (userUniqId: string) => {
|
||||
const response = await client.get<IUser>(
|
||||
`${ENDPOINT.USER_SERVICE.USERS}/${userUniqId}`,
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import { PROXY_HOST } from "./env";
|
||||
|
||||
export const BASE_URL = `${PROXY_HOST}/server`;
|
||||
|
||||
export const ENDPOINT = {
|
||||
CMS_SERVICE: {
|
||||
MENU_ROLES: "/cms-service/api/v1/menu-roles",
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
export const PORT = process.env.PORT || "3000";
|
||||
export const PROXY_HOST = process.env.PROXY_HOST || `http://localhost:${PORT}`;
|
||||
|
||||
export const SERVER_API_URL = process.env.SERVER_API_URL;
|
||||
export const SITE_ID = process.env.SITE_ID || "CS";
|
||||
|
||||
export const CLAIM_NAME = process.env.CLAIM_NAME || "Authorization";
|
||||
export const ACCESS_TOKEN = process.env.ACCESS_TOKEN || "access-token";
|
||||
export const REFRESH_TOKEN = process.env.REFRESH_TOKEN || "refresh-token";
|
||||
export const AUTH_USER_ID = process.env.AUTH_USER_ID || "token-id";
|
||||
@@ -1,2 +1 @@
|
||||
export * from "./api";
|
||||
export * from "./env";
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
@layer components {
|
||||
button[role="checkbox"] {
|
||||
@apply size-[1.5rem] shrink-0 overflow-hidden rounded-[0.5rem] border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground;
|
||||
@apply size-[1.5rem] shrink-0 overflow-hidden rounded-[0.5rem] border border-primary bg-background ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground;
|
||||
}
|
||||
button[role="checkbox"] > span {
|
||||
@apply flex size-full items-center justify-center text-current;
|
||||
}
|
||||
button[role="checkbox"] + label {
|
||||
@apply text-label text-[1.3rem] font-medium;
|
||||
@apply text-[1.3rem] font-medium text-label;
|
||||
}
|
||||
button[role="checkbox"]:disabled + label {
|
||||
@apply cursor-not-allowed opacity-70;
|
||||
|
||||
@@ -13,11 +13,11 @@ import { cn } from "../../lib";
|
||||
import { Button } from "../button";
|
||||
import { Table, TableCell, TableHead, TableHeader, TableRow } from "../table";
|
||||
import type { HTMLAttributes } from "react";
|
||||
|
||||
declare module "@tanstack/react-table" {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
interface ColumnMeta<TData extends RowData, TValue> {
|
||||
align: "left" | "center" | "right";
|
||||
align?: "left" | "center" | "right";
|
||||
rowSpan?: number;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,15 +70,35 @@ function THead<T>({ table }: { table: TableInstance<T> }) {
|
||||
{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;
|
||||
}
|
||||
|
||||
let rowSpan = 1;
|
||||
if (header.isPlaceholder) {
|
||||
const leafs = header.getLeafHeaders();
|
||||
rowSpan = (leafs?.[leafs.length - 1]?.depth ?? 0) - header.depth;
|
||||
}
|
||||
|
||||
const { meta } = header.column.columnDef;
|
||||
|
||||
return (
|
||||
<TableHead key={header.id} className="sticky top-0" {...meta}>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
<TableHead
|
||||
key={header.id}
|
||||
className="sticky top-0"
|
||||
colSpan={header.colSpan}
|
||||
rowSpan={rowSpan}
|
||||
{...meta}
|
||||
>
|
||||
{flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { images } from "@common/assets";
|
||||
import { getConfig } from "@common/config";
|
||||
import { ENDPOINT } from "../../config";
|
||||
import { getCookie, setCookie } from "../../lib";
|
||||
import { getSiteInfo, getUserInfo } from "../../api";
|
||||
import { AUTH_USER_ID, ENDPOINT, SITE_ID } from "../../config";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuTrigger,
|
||||
@@ -11,8 +12,10 @@ import {
|
||||
} from "../dropdown-menu";
|
||||
import { Button } from "../button";
|
||||
|
||||
const { AUTH_USER_ID, SITE_ID } = getConfig();
|
||||
|
||||
export function Header({ viewOnly }: { viewOnly?: boolean }) {
|
||||
const userUniqId = getCookie(AUTH_USER_ID) ?? "";
|
||||
const userUniqId = getCookie(AUTH_USER_ID ?? "") ?? "";
|
||||
|
||||
const { data: userInfo } = useQuery({
|
||||
queryKey: [ENDPOINT.USER_SERVICE.USERS],
|
||||
@@ -22,7 +25,7 @@ export function Header({ viewOnly }: { viewOnly?: boolean }) {
|
||||
|
||||
const { data: siteInfo } = useQuery({
|
||||
queryKey: [ENDPOINT.CMS_SERVICE.SITES, SITE_ID],
|
||||
queryFn: () => getSiteInfo(SITE_ID),
|
||||
queryFn: () => getSiteInfo(SITE_ID ?? ""),
|
||||
select: (data) => {
|
||||
if (data.siteSkn) {
|
||||
const siteSkin = data.siteSkn.toLowerCase();
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { ChevronRight } from "lucide-react";
|
||||
import { getConfig } from "@common/config";
|
||||
import { ENDPOINT } from "../../config";
|
||||
import { cn, setCookie } from "../../lib";
|
||||
import { ENDPOINT, SITE_ID } from "../../config";
|
||||
import { getMenuList, type MenuItem } from "../../api";
|
||||
import {
|
||||
Sidebar,
|
||||
@@ -19,6 +20,8 @@ import {
|
||||
} from "../collapsible";
|
||||
import { getParentIds } from "./lib";
|
||||
|
||||
const { SITE_ID } = getConfig();
|
||||
|
||||
export function LNB({
|
||||
viewOnly,
|
||||
currentPath,
|
||||
@@ -30,7 +33,7 @@ export function LNB({
|
||||
}) {
|
||||
const { data: menuList } = useQuery({
|
||||
queryKey: [ENDPOINT.CMS_SERVICE.MENU_ROLES],
|
||||
queryFn: () => getMenuList(SITE_ID),
|
||||
queryFn: () => getMenuList(SITE_ID ?? ""),
|
||||
enabled: !viewOnly,
|
||||
});
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["src/*"],
|
||||
"@common/network/*": ["../network/*"],
|
||||
"@common/config": ["../config/dist/"],
|
||||
"@common/network": ["../network/"]
|
||||
}
|
||||
},
|
||||
|
||||
@@ -10,7 +10,7 @@ export default defineConfig((options) => ({
|
||||
format: ["esm"],
|
||||
external: ["react", "react-dom"],
|
||||
platform: "browser",
|
||||
target: ["es2020", "chrome70", "edge18", "firefox70", "node18"],
|
||||
target: ["es2020"],
|
||||
tsconfig: path.resolve(__dirname, "tsconfig.build.json"),
|
||||
sourcemap: !options.watch,
|
||||
minify: !options.watch,
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "@common/config",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"dev": "tsup --watch",
|
||||
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
||||
"clean": "rm -rf dist .turbo node_modules"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"eslint": "^9.8.0",
|
||||
"tsup": "^8.2.3",
|
||||
"typescript": "^5.5.3",
|
||||
"vite": "^5.3.5"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./initialize-config";
|
||||
export * from "./initializer";
|
||||
@@ -0,0 +1,54 @@
|
||||
export interface EnvConfig {
|
||||
PORT?: string;
|
||||
PROXY_HOST?: string;
|
||||
SERVER_API_URL?: string;
|
||||
SITE_ID?: string;
|
||||
CLAIM_NAME?: string;
|
||||
ACCESS_TOKEN?: string;
|
||||
REFRESH_TOKEN?: string;
|
||||
AUTH_USER_ID?: string;
|
||||
}
|
||||
|
||||
const defaultConfig: EnvConfig = {
|
||||
PORT: "3000",
|
||||
PROXY_HOST: "",
|
||||
SERVER_API_URL: "",
|
||||
SITE_ID: "CS",
|
||||
CLAIM_NAME: "Authorization",
|
||||
ACCESS_TOKEN: "access-token",
|
||||
REFRESH_TOKEN: "refresh-token",
|
||||
AUTH_USER_ID: "token-id",
|
||||
};
|
||||
|
||||
let isInitialized = false;
|
||||
let envConfig: EnvConfig = { ...defaultConfig };
|
||||
|
||||
export function initializeConfig(values: Partial<EnvConfig>): void {
|
||||
if (isInitialized) {
|
||||
console.warn("Configuration already initialized. Skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredValues = Object.entries(values).reduce((acc, [key, value]) => {
|
||||
if (value !== undefined && value !== null) {
|
||||
acc[key as keyof EnvConfig] = value;
|
||||
}
|
||||
return acc;
|
||||
}, {} as Partial<EnvConfig>);
|
||||
|
||||
if (filteredValues.PORT && !filteredValues.PROXY_HOST) {
|
||||
filteredValues.PROXY_HOST = `http://localhost:${filteredValues.PORT}`;
|
||||
}
|
||||
|
||||
envConfig = { ...defaultConfig, ...filteredValues };
|
||||
isInitialized = true;
|
||||
}
|
||||
|
||||
export function getConfig(): EnvConfig {
|
||||
if (!isInitialized) {
|
||||
console.warn(
|
||||
"Attempted to access config before initialization. Returning default values."
|
||||
);
|
||||
}
|
||||
return envConfig;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { initializeConfig, type EnvConfig } from "./initialize-config";
|
||||
|
||||
export function initializeNextClientConfig(): void {
|
||||
if (typeof window === "undefined") {
|
||||
console.warn("initializeNextClientConfig called on the server. Skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
const env: Partial<EnvConfig> = {
|
||||
PORT: process.env.NEXT_PUBLIC_PORT,
|
||||
PROXY_HOST: process.env.NEXT_PUBLIC_PROXY_HOST,
|
||||
SERVER_API_URL: process.env.NEXT_PUBLIC_SERVER_API_URL,
|
||||
SITE_ID: process.env.NEXT_PUBLIC_SITE_ID,
|
||||
CLAIM_NAME: process.env.NEXT_PUBLIC_CLAIM_NAME,
|
||||
ACCESS_TOKEN: process.env.NEXT_PUBLIC_ACCESS_TOKEN,
|
||||
REFRESH_TOKEN: process.env.NEXT_PUBLIC_REFRESH_TOKEN,
|
||||
AUTH_USER_ID: process.env.NEXT_PUBLIC_AUTH_USER_ID,
|
||||
};
|
||||
initializeConfig(env);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"types": ["node", "vite/client"],
|
||||
"incremental": false
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
format: ["esm"],
|
||||
dts: true,
|
||||
splitting: false,
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
external: [],
|
||||
});
|
||||
Reference in New Issue
Block a user