261021_01_ENH: 1차 마이그레이션 완료

This commit is contained in:
2026-10-21 16:08:57 +09:00
parent 964269cd82
commit f0c9b02eae
313 changed files with 11557 additions and 344 deletions

View File

@@ -1,40 +1,237 @@
"use client";
import Image from "next/image";
import { LogOut } from "lucide-react";
import { Button } from "@/components/ui/button";
import { KriHeader } from "@/components/layout/KriHeader";
import { topMenus } from "@/config/menu.data";
import Link from "next/link";
import { useState } from "react";
import { usePathname } from "next/navigation";
import type { LoginUser } from "@kri/common";
import { cn } from "@/lib/utils";
import { kartMenus } from "@/config/menu.data";
import type { KartMenuItem } from "@/config/menu.type";
import { ProjectSelector } from "@/components/project/ProjectSelector";
import { useProjectTitle } from "@/query/project";
import { useProjectParamsMigration, useSelectedProject } from "@/hooks/useSelectedProject";
import { projectPagePath } from "@/lib/report-navigation";
import { useAuth } from "@/hooks/useAuth";
import { useMutation } from "@tanstack/react-query";
import { nextApi } from "@/lib/http-client";
import { apiError } from "@kri/common/http";
import { isExternalUser, isShareLink, REPORT_MEMBER_ROLE } from "@/types/share";
interface AppHeaderProps {
menuOpen: boolean;
showMenuButton: boolean;
activeMenuId?: string;
user?: LoginUser | null;
onToggleMenu: () => void;
onNavigate: (path: string) => void;
user: LoginUser;
}
export function AppHeader({ menuOpen, showMenuButton, activeMenuId, user, onToggleMenu, onNavigate }: AppHeaderProps) {
/** Legacy KART Header.js: fixed GNB (64px) + title bar (80px). */
export function AppHeader({ user }: AppHeaderProps) {
const pathname = usePathname();
const { auth } = useAuth();
const external = isExternalUser(user);
const { project } = useSelectedProject();
useProjectParamsMigration();
const title = useProjectTitle(project);
const [mobileOpen, setMobileOpen] = useState(false);
const menus = project && !(external && auth.external?.pageOnly)
? kartMenus.filter((menu) => !menu.visible || menu.visible(user))
: [];
const projectTitle = project ? title : "Project Overview TOP 6";
const canCopyUrl = !!project && user.userRole < REPORT_MEMBER_ROLE;
const copy = useMutation({
mutationFn: async (mode: "P" | "U") => {
if (!project) return;
const url = new URL(window.location.href);
url.searchParams.delete("projectType");
url.searchParams.delete("pkey");
const link = await nextApi.post<unknown>(`/share/${project.projectType}/${encodeURIComponent(project.pkey)}`, {
realUrl: pathname + url.search + url.hash, mode,
});
if (!isShareLink(link)) throw new Error("공유 링크 응답을 확인해 주세요.");
await navigator.clipboard.writeText(link.url);
},
onSuccess: () => window.alert("주소가 복사되었습니다."),
onError: (error) => window.alert(apiError(error, { fallbackMessage: "주소를 복사하지 못했습니다." }).message),
});
return (
<KriHeader
logo={<Image src="/logo.png" alt="로고" width={120} height={40} className="h-10 w-auto object-contain" priority />}
menus={topMenus}
activeMenuId={activeMenuId}
menuOpen={menuOpen}
showMenuButton={showMenuButton}
onToggleMenu={onToggleMenu}
onNavigate={onNavigate}
right={
<header className="sticky top-0 z-40">
<nav className="bg-kart-bg px-[1.0416vw]">
<div className="flex h-16 items-center justify-between">
{external ? <h1><KartLogo /></h1> : <Link href="/" replace><h1><KartLogo /></h1></Link>}
<button
type="button"
aria-label="메뉴 열기"
aria-expanded={mobileOpen}
className="min-[1301px]:hidden"
onClick={() => setMobileOpen((open) => !open)}
>
<Image
src="/images/kart/bx_menu.svg"
alt=""
width={24}
height={24}
unoptimized
/>
</button>
<div className="hidden h-full items-center gap-[2.604vw] min-[1301px]:flex">
{pathname === "/" ? (
<p className="text-[15px] font-bold">
안녕하세요! {user.userName}님
</p>
) : null}
{project ? (
<ul className="flex h-full items-center">
{menus.map((menu) => (
<li key={menu.id} className="relative">
<GnbLink menu={menu} active={pathname === menu.path} />
</li>
))}
</ul>
) : null}
{!external ? <Link
href="/logout"
replace
className="inline-flex h-7 w-[113px] items-center justify-center rounded-[52px] bg-kart-green text-sm leading-[17px] font-bold text-white"
>
Logout
</Link> : null}
</div>
</div>
</nav>
{mobileOpen ? (
<>
<span className="hidden text-sm text-muted-foreground sm:inline">{user?.userName ?? ""}</span>
<Button variant="ghost" size="sm" className="gap-2" onClick={() => onNavigate("/logout")}>
<LogOut className="size-4" />
<span className="hidden sm:inline">로그아웃</span>
</Button>
<ul className="fixed top-16 right-0 z-50 w-full bg-kart-bg px-[3.076vw] py-[4.102vw] text-right min-[1301px]:hidden">
{menus.map((menu) => (
<li key={menu.id} className="mb-3">
{menu.ready && project ? (
<Link
href={projectPagePath(menu.path)}
className={cn(
"text-lg font-bold text-[#9e9e9e] transition-colors hover:text-kart-green",
pathname === menu.path && "text-kart-green",
)}
onClick={() => setMobileOpen(false)}
>
{menu.label}
</Link>
) : (
<span
aria-disabled="true"
title="준비 중"
className="text-lg font-bold text-[#9e9e9e]"
>
{menu.label}
</span>
)}
</li>
))}
{!external ? <li className="mb-3">
<Link
href="/logout"
replace
className="text-lg font-bold text-[#9e9e9e] hover:text-kart-green"
>
Logout
</Link>
</li> : null}
</ul>
<div
aria-hidden="true"
className="fixed inset-x-0 top-16 bottom-0 z-30 bg-black/20 min-[1301px]:hidden"
onClick={() => setMobileOpen(false)}
/>
</>
}
/>
) : null}
<div className="relative flex h-20 flex-col items-start border-y border-kart-line bg-white px-[1.0416vw] pt-2 max-[1300px]:h-[82px]">
<div className="mt-[2.5px] w-[400px] max-[1300px]:w-full">
{external ? <div className="h-8" /> : <ProjectSelector />}
</div>
<div className="mt-[2.5px] max-[1300px]:mt-1.5">
<h2 className="text-xl leading-[1.28571] font-bold break-all text-kart-title max-[1300px]:text-lg">
{projectTitle}
</h2>
</div>
{canCopyUrl ? (
<div className="absolute top-[23px] right-5 flex max-[1300px]:hidden">
{(
[
["Page Copy", "ic_copy_page.svg"],
["URL Copy", "ic_copy_url.svg"],
] as const
).map(([label, icon]) => (
<button
key={label}
type="button"
disabled={copy.isPending}
onClick={() => copy.mutate(label === "Page Copy" ? "P" : "U")}
className="ml-[15px] inline-block h-7 cursor-pointer rounded-[52px] bg-kart-bg bg-size-[18px_18px] bg-position-[left_12px_center] bg-no-repeat py-1.5 pr-[14px] pl-[34px] text-sm leading-[15px] font-bold text-kart-green"
style={{ backgroundImage: `url(/images/kart/${icon})` }}
>
{label}
</button>
))}
</div>
) : null}
</div>
</header>
);
}
function KartLogo() {
return <Image src="/images/kart/logo_kart.svg" alt="KART" width={135} height={32}
className="mt-2 h-auto w-[135px]" unoptimized priority />;
}
function GnbLink({ menu, active }: { menu: KartMenuItem; active: boolean }) {
const content = (
<>
<span
aria-hidden="true"
className="absolute top-[34%] -left-[17px] size-5 bg-contain bg-left bg-no-repeat"
style={{
backgroundImage: `url(/images/kart/ic_gnb${menu.icon}_20${active ? "-1" : ""}.png)`,
}}
/>
<span
aria-hidden="true"
className="absolute top-[34%] -left-[17px] hidden size-5 bg-contain bg-left bg-no-repeat group-hover:block"
style={{
backgroundImage: `url(/images/kart/ic_gnb${menu.icon}_20-1.png)`,
}}
/>
{menu.label}
<span
aria-hidden="true"
className={cn(
"absolute right-0 bottom-[14px] -left-[17px] h-1 bg-kart-green",
active ? "block" : "hidden group-hover:block",
)}
/>
</>
);
const className = cn(
"group relative ml-[3.125vw] block h-16 pl-2 text-center text-sm leading-[64px] font-bold text-[#444] transition-colors",
active && "text-kart-green",
);
if (!menu.ready)
return (
<span aria-disabled="true" title="준비 중" className={className}>
{menu.label}
<span
aria-hidden="true"
className="absolute top-[34%] -left-[17px] size-5 bg-contain bg-left bg-no-repeat"
style={{
backgroundImage: `url(/images/kart/ic_gnb${menu.icon}_20.png)`,
}}
/>
</span>
);
return (
<Link
href={projectPagePath(menu.path)}
aria-current={active ? "page" : undefined}
className={cn(className, "hover:text-kart-green")}
>
{content}
</Link>
);
}

View File

@@ -1,45 +1,60 @@
"use client";
import type { Route } from "next";
import { useMemo, useState, type ReactNode } from "react";
import { Fragment, Suspense, useEffect, useState, type ReactNode } from "react";
import { usePathname, useRouter } from "next/navigation";
import { KriMainLayout } from "@/components/layout/KriMainLayout";
import { AppHeader } from "./AppHeader";
import { AppSidebar } from "./AppSidebar";
import { sideMenus, topMenus } from "@/config/menu.data";
import { sideMenus } from "@/config/menu.data";
import { useAuth } from "@/hooks/useAuth";
import { externalPageAllowed, isExternalUser, reportUrl } from "@/types/share";
export function AppMainLayout({ children }: { children: ReactNode }) {
const pathname = usePathname();
const router = useRouter();
const { auth } = useAuth();
const { auth, hydrated } = useAuth();
const [menuOpen, setMenuOpen] = useState(true);
const activeMenuId = useMemo(
() => topMenus.find((item) => item.path && (pathname === item.path || pathname.startsWith(`${item.path}/`)))?.id,
[pathname],
);
const navigate = (path: string) => router.push(path as Route);
const external = isExternalUser(auth.user);
const externalAllowed = !external || (!!auth.external && externalPageAllowed(auth.external, pathname));
useEffect(() => {
if (hydrated && !auth.user) router.replace("/logout");
else if (hydrated && !externalAllowed)
router.replace((auth.external ? reportUrl(auth.external.realUrl) : "/logout") as Route);
}, [hydrated, auth.user, auth.external, externalAllowed, router]);
const hasSidebar = sideMenus.length > 0;
if (!hydrated || !auth.user || !externalAllowed)
return (
<p
role="status"
className="p-8 text-center text-sm text-muted-foreground"
>
로그인 정보를 확인하는 중입니다.
</p>
);
return (
<KriMainLayout
className="bg-kart-bg text-kart-text"
sidebarOpen={hasSidebar && menuOpen}
onSidebarOpenChange={setMenuOpen}
header={
<AppHeader
menuOpen={menuOpen}
showMenuButton={hasSidebar}
activeMenuId={activeMenuId}
user={auth.user}
onToggleMenu={() => setMenuOpen((current) => !current)}
onNavigate={navigate}
/>
<Suspense fallback={<div className="h-[146px] bg-kart-bg" />}>
<AppHeader user={auth.user} />
</Suspense>
}
sidebar={hasSidebar ? <AppSidebar items={sideMenus} isOpen={menuOpen} pathname={pathname} onNavigate={navigate} /> : undefined}
sidebar={
hasSidebar ? (
<AppSidebar
items={sideMenus}
isOpen={menuOpen}
pathname={pathname}
onNavigate={(path) => router.push(path as Route)}
/>
) : undefined
}
mainClassName="bg-kart-bg px-[1.0416vw] pt-2.5 pb-6"
>
{children}
<Fragment key={auth.user.userId + ":" + auth.user.userRole}>{children}</Fragment>
</KriMainLayout>
);
}

View File

@@ -3,10 +3,23 @@
import { useAtomValue } from "jotai";
import { KriLoadingOverlay, type KriLoadingOverlayProps } from "@/components/common/KriLoadingOverlay";
import { loadingAtom } from "@/store/jotai/loading";
import { cn } from "@/lib/utils";
export type LoadingOverlayAdapterProps = Omit<KriLoadingOverlayProps, "open"> & { force?: boolean };
export function LoadingOverlayAdapter({ force = false, ...props }: LoadingOverlayAdapterProps) {
// Legacy KART loading: blurred page with the 200px loading.gif instead of the spinner.
const legacyOverlay = "bg-transparent backdrop-blur-[5px]";
const legacyIndicator =
"size-[200px] animate-none rounded-none border-0 bg-[url(/images/kart/loading.gif)] bg-contain bg-center bg-no-repeat";
export function LoadingOverlayAdapter({ force = false, className, spinnerClassName, ...props }: LoadingOverlayAdapterProps) {
const open = useAtomValue(loadingAtom);
return <KriLoadingOverlay open={force || open} {...props} />;
return (
<KriLoadingOverlay
open={force || open}
className={cn(legacyOverlay, className)}
spinnerClassName={cn(legacyIndicator, spinnerClassName)}
{...props}
/>
);
}

View File

@@ -0,0 +1,147 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import type { ComponentType, CSSProperties } from 'react'
import type { EChartsOption } from 'echarts'
import { CHART_HEIGHTS } from './chart.config'
import { useResizeKey } from './useResizeKey'
type EChartsSeries = NonNullable<EChartsOption['series']>
type ReactEChartsProps = {
option: EChartsOption
className?: string
style?: CSSProperties
notMerge?: boolean
lazyUpdate?: boolean
onEvents?: Record<string, (params: unknown) => void>
}
export type BaseEChartProps = {
option: EChartsOption
height?: number | string
className?: string
contentClassName?: string
chartClassName?: string
style?: CSSProperties
contentStyle?: CSSProperties
chartStyle?: CSSProperties
notMerge?: boolean
lazyUpdate?: boolean
onEvents?: Record<string, (params: unknown) => void>
resizeDebounceMs?: number
normalizeValues?: boolean
decimalPlaces?: number
}
const roundNumber = (value: number, decimalPlaces: number) => {
const factor = 10 ** decimalPlaces
return Math.round((value + Number.EPSILON) * factor) / factor
}
const normalizeDataValue = (value: unknown, decimalPlaces: number): unknown => {
if (typeof value === 'number') {
return roundNumber(value, decimalPlaces)
}
if (Array.isArray(value)) {
return value.map((item) => normalizeDataValue(item, decimalPlaces))
}
if (value && typeof value === 'object' && 'value' in value) {
const dataItem = value as Record<string, unknown>
return {
...dataItem,
value: normalizeDataValue(dataItem.value, decimalPlaces),
}
}
return value
}
const normalizeSeries = (
series: EChartsOption['series'] | undefined,
decimalPlaces: number,
): EChartsOption['series'] => {
if (!series) return series
const normalizeOne = (seriesOption: EChartsSeries): EChartsSeries => {
const candidate = seriesOption as Record<string, unknown>
const data = candidate.data
if (!Array.isArray(data)) {
return seriesOption
}
return {
...candidate,
data: data.map((value) => normalizeDataValue(value, decimalPlaces)),
} as EChartsSeries
}
return (Array.isArray(series) ? series.map((item) => normalizeOne(item as EChartsSeries)) : normalizeOne(series)) as EChartsOption['series']
}
export function BaseEChart({
option,
height = CHART_HEIGHTS.DEFAULT,
className,
contentClassName,
chartClassName,
style,
contentStyle,
chartStyle,
notMerge = true,
lazyUpdate = false,
onEvents,
resizeDebounceMs = 150,
normalizeValues = true,
decimalPlaces = 2,
}: BaseEChartProps) {
const resizeKey = useResizeKey(resizeDebounceMs)
const [ReactECharts, setReactECharts] = useState<ComponentType<ReactEChartsProps> | null>(null)
useEffect(() => {
let cancelled = false
void import('echarts-for-react').then((module) => {
if (!cancelled) {
setReactECharts(() => module.default as ComponentType<ReactEChartsProps>)
}
})
return () => {
cancelled = true
}
}, [])
const normalizedOption = useMemo<EChartsOption>(() => {
if (!normalizeValues) return option
return {
...option,
series: normalizeSeries(option.series, decimalPlaces),
}
}, [decimalPlaces, normalizeValues, option])
return (
<div className={className} style={{ display: 'flex', flexDirection: 'column', height, ...style }}>
<div className={contentClassName} style={{ flex: 1, minHeight: 0, ...contentStyle }}>
{ReactECharts ? (
<ReactECharts
key={resizeKey}
option={normalizedOption}
className={chartClassName}
style={{ width: '100%', height: '100%', ...chartStyle }}
notMerge={notMerge}
lazyUpdate={lazyUpdate}
onEvents={onEvents}
/>
) : null}
</div>
</div>
)
}
export default BaseEChart

View File

@@ -0,0 +1,59 @@
'use client'
import { useMemo } from 'react'
import type { EChartsOption } from 'echarts'
import { BaseEChart } from './BaseEChart'
import type { KriCartesianChartProps } from './chart.types'
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
export type KriBarChartProps = KriCartesianChartProps & {
isHorizontal?: boolean
barWidth?: number | string
barMaxWidth?: number | string
}
export function KriBarChart({
categories,
series,
isHorizontal = false,
barWidth,
barMaxWidth,
title,
legend,
tooltip,
grid,
xAxis,
yAxis,
option,
...baseChartProps
}: KriBarChartProps) {
const chartOption = useMemo<EChartsOption>(() => {
const categoryAxis = { type: 'category', data: categories }
const valueAxis = { type: 'value' }
const generated: EChartsOption = {
title,
tooltip: tooltip ?? { trigger: 'axis', axisPointer: { type: 'shadow' } },
legend: legend ?? defaultLegend(series.length),
grid: grid ?? defaultGrid(series.length),
xAxis: mergeObjectOption(isHorizontal ? valueAxis : categoryAxis, xAxis) as EChartsOption['xAxis'],
yAxis: mergeObjectOption(isHorizontal ? categoryAxis : valueAxis, yAxis) as EChartsOption['yAxis'],
series: series.map((item) => ({
type: 'bar',
name: item.name,
data: item.data,
...(barWidth ? { barWidth } : {}),
...(barMaxWidth ? { barMaxWidth } : {}),
...(item.color ? { color: item.color } : {}),
...item.option,
})) as EChartsOption['series'],
}
return mergeChartOptions(generated, option)
}, [barMaxWidth, barWidth, categories, grid, isHorizontal, legend, option, series, title, tooltip, xAxis, yAxis])
return <BaseEChart option={chartOption} {...baseChartProps} />
}
export default KriBarChart

View File

@@ -0,0 +1,58 @@
'use client'
import { useMemo } from 'react'
import type { EChartsOption } from 'echarts'
import { BaseEChart } from './BaseEChart'
import type { KriCartesianChartProps } from './chart.types'
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
export type KriLineChartProps = KriCartesianChartProps & {
smooth?: boolean
area?: boolean
showSymbol?: boolean
}
export function KriLineChart({
categories,
series,
smooth = false,
area = false,
showSymbol = true,
title,
legend,
tooltip,
grid,
xAxis,
yAxis,
option,
...baseChartProps
}: KriLineChartProps) {
const chartOption = useMemo<EChartsOption>(() => {
const generated: EChartsOption = {
title,
tooltip: tooltip ?? { trigger: 'axis' },
legend: legend ?? defaultLegend(series.length),
grid: grid ?? defaultGrid(series.length),
xAxis: mergeObjectOption({ type: 'category', data: categories, boundaryGap: false }, xAxis) as EChartsOption['xAxis'],
yAxis: mergeObjectOption({ type: 'value' }, yAxis) as EChartsOption['yAxis'],
series: series.map((item) => ({
type: 'line',
name: item.name,
data: item.data,
smooth,
showSymbol,
...(area ? { areaStyle: {} } : {}),
...(item.color ? { color: item.color } : {}),
...item.option,
})) as EChartsOption['series'],
}
return mergeChartOptions(generated, option)
}, [area, categories, grid, legend, option, series, showSymbol, smooth, title, tooltip, xAxis, yAxis])
return <BaseEChart option={chartOption} {...baseChartProps} />
}
export default KriLineChart

View File

@@ -0,0 +1,50 @@
'use client'
import { useMemo } from 'react'
import type { EChartsOption } from 'echarts'
import { BaseEChart } from './BaseEChart'
import type { KriChartBaseProps, KriPieChartSeries } from './chart.types'
import { defaultLegend, mergeChartOptions } from './chart.utils'
export type KriPieChartProps = KriChartBaseProps & {
series: KriPieChartSeries[]
}
const getPieCenter = (index: number, count: number) => {
if (count === 1) return ['50%', '55%']
return [`${((index + 0.5) / count) * 100}%`, '55%']
}
export function KriPieChart({
series,
title,
legend,
tooltip,
option,
...baseChartProps
}: KriPieChartProps) {
const chartOption = useMemo<EChartsOption>(() => {
const generated: EChartsOption = {
title,
tooltip: tooltip ?? { trigger: 'item' },
legend: legend ?? defaultLegend(series.length),
series: series.map((item, index) => ({
type: 'pie',
name: item.name,
data: item.data,
radius: item.radius ?? (series.length > 1 ? ['32%', '52%'] : '65%'),
center: item.center ?? getPieCenter(index, series.length),
...item.option,
})) as EChartsOption['series'],
}
return mergeChartOptions(generated, option)
}, [legend, option, series, title, tooltip])
return <BaseEChart option={chartOption} {...baseChartProps} />
}
export default KriPieChart

View File

@@ -0,0 +1,55 @@
'use client'
import { useMemo } from 'react'
import type { EChartsOption } from 'echarts'
import { BaseEChart } from './BaseEChart'
import type { KriChartBaseProps, KriRadarChartSeries, KriRadarDataItem, KriRadarIndicator } from './chart.types'
import { defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
export type KriRadarChartProps = KriChartBaseProps & {
indicators: KriRadarIndicator[]
series: KriRadarChartSeries[]
radar?: EChartsOption['radar']
}
const normalizeRadarData = (series: KriRadarChartSeries): KriRadarDataItem[] => {
if (series.data.every((value) => typeof value === 'number')) {
return [{ name: series.name, value: series.data as number[] }]
}
return series.data as KriRadarDataItem[]
}
export function KriRadarChart({
indicators,
series,
radar,
title,
legend,
tooltip,
option,
...baseChartProps
}: KriRadarChartProps) {
const chartOption = useMemo<EChartsOption>(() => {
const generated: EChartsOption = {
title,
tooltip: tooltip ?? { trigger: 'item' },
legend: legend ?? defaultLegend(series.length),
radar: mergeObjectOption({ indicator: indicators }, radar) as EChartsOption['radar'],
series: series.map((item) => ({
type: 'radar',
name: item.name,
data: normalizeRadarData(item),
...item.option,
})) as EChartsOption['series'],
}
return mergeChartOptions(generated, option)
}, [indicators, legend, option, radar, series, title, tooltip])
return <BaseEChart option={chartOption} {...baseChartProps} />
}
export default KriRadarChart

View File

@@ -0,0 +1,55 @@
'use client'
import { useMemo } from 'react'
import type { EChartsOption } from 'echarts'
import { BaseEChart } from './BaseEChart'
import type { KriChartBaseProps, KriScatterChartSeries } from './chart.types'
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
export type KriScatterChartProps = KriChartBaseProps & {
series: KriScatterChartSeries[]
grid?: EChartsOption['grid']
xAxis?: EChartsOption['xAxis']
yAxis?: EChartsOption['yAxis']
symbolSize?: number | ((value: unknown, params: unknown) => number)
}
export function KriScatterChart({
series,
grid,
xAxis,
yAxis,
symbolSize,
title,
legend,
tooltip,
option,
...baseChartProps
}: KriScatterChartProps) {
const chartOption = useMemo<EChartsOption>(() => {
const generated: EChartsOption = {
title,
tooltip: tooltip ?? { trigger: 'item' },
legend: legend ?? defaultLegend(series.length),
grid: grid ?? defaultGrid(series.length),
xAxis: mergeObjectOption({ type: 'value' }, xAxis) as EChartsOption['xAxis'],
yAxis: mergeObjectOption({ type: 'value' }, yAxis) as EChartsOption['yAxis'],
series: series.map((item) => ({
type: 'scatter',
name: item.name,
data: item.data,
...(symbolSize ? { symbolSize } : {}),
...(item.color ? { color: item.color } : {}),
...item.option,
})) as EChartsOption['series'],
}
return mergeChartOptions(generated, option)
}, [grid, legend, option, series, symbolSize, title, tooltip, xAxis, yAxis])
return <BaseEChart option={chartOption} {...baseChartProps} />
}
export default KriScatterChart

View File

@@ -0,0 +1,62 @@
'use client'
import { useMemo } from 'react'
import type { EChartsOption } from 'echarts'
import { BaseEChart } from './BaseEChart'
import type { KriCartesianChartProps } from './chart.types'
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
export type KriStackedBarChartProps = KriCartesianChartProps & {
isHorizontal?: boolean
stackName?: string
barWidth?: number | string
barMaxWidth?: number | string
}
export function KriStackedBarChart({
categories,
series,
isHorizontal = false,
stackName = 'total',
barWidth,
barMaxWidth,
title,
legend,
tooltip,
grid,
xAxis,
yAxis,
option,
...baseChartProps
}: KriStackedBarChartProps) {
const chartOption = useMemo<EChartsOption>(() => {
const categoryAxis = { type: 'category', data: categories }
const valueAxis = { type: 'value' }
const generated: EChartsOption = {
title,
tooltip: tooltip ?? { trigger: 'axis', axisPointer: { type: 'shadow' } },
legend: legend ?? defaultLegend(series.length),
grid: grid ?? defaultGrid(series.length),
xAxis: mergeObjectOption(isHorizontal ? valueAxis : categoryAxis, xAxis) as EChartsOption['xAxis'],
yAxis: mergeObjectOption(isHorizontal ? categoryAxis : valueAxis, yAxis) as EChartsOption['yAxis'],
series: series.map((item) => ({
type: 'bar',
name: item.name,
data: item.data,
stack: item.stack ?? stackName,
...(barWidth ? { barWidth } : {}),
...(barMaxWidth ? { barMaxWidth } : {}),
...(item.color ? { color: item.color } : {}),
...item.option,
})) as EChartsOption['series'],
}
return mergeChartOptions(generated, option)
}, [barMaxWidth, barWidth, categories, grid, isHorizontal, legend, option, series, stackName, title, tooltip, xAxis, yAxis])
return <BaseEChart option={chartOption} {...baseChartProps} />
}
export default KriStackedBarChart

View File

@@ -0,0 +1,6 @@
export const CHART_HEIGHTS = {
DEFAULT: 320,
SMALL: 240,
LARGE: 420,
} as const

View File

@@ -0,0 +1,71 @@
import type { EChartsOption } from 'echarts'
import type { BaseEChartProps } from './BaseEChart'
export type KriChartBaseProps = Omit<BaseEChartProps, 'option'> & {
option?: EChartsOption
title?: EChartsOption['title']
legend?: EChartsOption['legend']
tooltip?: EChartsOption['tooltip']
}
export type KriCategoryValue = string | number
export type KriCategoryChartSeries = {
name: string
data: unknown[]
color?: string
stack?: string
option?: Record<string, unknown>
}
export type KriCartesianChartProps = KriChartBaseProps & {
categories: KriCategoryValue[]
series: KriCategoryChartSeries[]
grid?: EChartsOption['grid']
xAxis?: EChartsOption['xAxis']
yAxis?: EChartsOption['yAxis']
}
export type KriNamedChartData = {
name: string
value: unknown
[key: string]: unknown
}
export type KriPieChartSeries = {
name?: string
data: KriNamedChartData[]
radius?: string | number | Array<string | number>
center?: Array<string | number>
option?: Record<string, unknown>
}
export type KriRadarIndicator = {
name: string
max?: number
min?: number
color?: string
}
export type KriRadarDataItem = {
name?: string
value: number[]
[key: string]: unknown
}
export type KriRadarChartSeries = {
name: string
data: number[] | KriRadarDataItem[]
option?: Record<string, unknown>
}
export type KriScatterDataItem = [number, number] | [string, number] | KriNamedChartData
export type KriScatterChartSeries = {
name: string
data: KriScatterDataItem[]
color?: string
option?: Record<string, unknown>
}

View File

@@ -0,0 +1,34 @@
import type { EChartsOption } from 'echarts'
export const mergeChartOptions = (generated: EChartsOption, option?: EChartsOption): EChartsOption => {
if (!option) return generated
return {
...generated,
...option,
series: option.series ?? generated.series,
}
}
export const mergeObjectOption = <TOption>(defaults: Record<string, unknown>, option?: TOption): TOption | Record<string, unknown> => {
if (!option) return defaults
if (Array.isArray(option)) return option
if (typeof option === 'object') return { ...defaults, ...(option as Record<string, unknown>) }
return option
}
export const defaultLegend = (seriesCount: number): EChartsOption['legend'] | undefined => {
return seriesCount > 1 ? { top: 0 } : undefined
}
export const defaultGrid = (seriesCount: number): EChartsOption['grid'] => {
return {
top: seriesCount > 1 ? 44 : 24,
right: 24,
bottom: 24,
left: 24,
containLabel: true,
}
}

View File

@@ -0,0 +1,29 @@
export { BaseEChart, default } from './BaseEChart'
export type { BaseEChartProps } from './BaseEChart'
export { KriBarChart } from './KriBarChart'
export type { KriBarChartProps } from './KriBarChart'
export { KriLineChart } from './KriLineChart'
export type { KriLineChartProps } from './KriLineChart'
export { KriPieChart } from './KriPieChart'
export type { KriPieChartProps } from './KriPieChart'
export { KriRadarChart } from './KriRadarChart'
export type { KriRadarChartProps } from './KriRadarChart'
export { KriScatterChart } from './KriScatterChart'
export type { KriScatterChartProps } from './KriScatterChart'
export { KriStackedBarChart } from './KriStackedBarChart'
export type { KriStackedBarChartProps } from './KriStackedBarChart'
export { CHART_HEIGHTS } from './chart.config'
export type {
KriCartesianChartProps,
KriCategoryChartSeries,
KriCategoryValue,
KriChartBaseProps,
KriNamedChartData,
KriPieChartSeries,
KriRadarChartSeries,
KriRadarDataItem,
KriRadarIndicator,
KriScatterChartSeries,
KriScatterDataItem,
} from './chart.types'
export { useResizeKey } from './useResizeKey'

View File

@@ -0,0 +1,31 @@
'use client'
import { useEffect, useState } from 'react'
export function useResizeKey(delay = 150) {
const [resizeKey, setResizeKey] = useState(0)
useEffect(() => {
if (typeof window === 'undefined') return
let timer: number | undefined
const handleResize = () => {
if (timer) window.clearTimeout(timer)
timer = window.setTimeout(() => {
setResizeKey((key) => key + 1)
}, delay)
}
window.addEventListener('resize', handleResize)
return () => {
if (timer) window.clearTimeout(timer)
window.removeEventListener('resize', handleResize)
}
}, [delay])
return resizeKey
}

View File

@@ -11,6 +11,7 @@ export interface KriAutoCompleteBaseProps<T> {
items: T[]
searchable?: boolean
searchMode?: 'filter' | 'inputOnly'
resetScrollOnSearch?: boolean
defaultSearchValue?: string
onSearchValueChange?: (value: string) => void
placeholder?: string
@@ -56,6 +57,7 @@ export function KriMultiSelect<T = unknown>({
onChange,
searchable = true,
searchMode = 'filter',
resetScrollOnSearch = false,
defaultSearchValue = '',
onSearchValueChange,
maxCount = 1,
@@ -96,6 +98,7 @@ export function KriMultiSelect<T = unknown>({
badgeClassName={badgeClassName}
searchable={searchable}
searchMode={searchMode}
resetScrollOnSearch={resetScrollOnSearch}
defaultSearchValue={defaultSearchValue}
onSearchValueChange={onSearchValueChange}
maxCount={maxCount}
@@ -131,6 +134,7 @@ function KriSingleSelectInner<T>({
onChange,
searchable = true,
searchMode = 'filter',
resetScrollOnSearch = false,
defaultSearchValue = '',
onSearchValueChange,
placeholder = 'Select an option',
@@ -208,6 +212,7 @@ function KriSingleSelectInner<T>({
badgeClassName={badgeClassName}
searchable={searchable}
searchMode={searchMode}
resetScrollOnSearch={resetScrollOnSearch}
defaultSearchValue={defaultSearchValue}
onSearchValueChange={onSearchValueChange}
preventDeselect={preventDeselect}

View File

@@ -30,6 +30,7 @@ function MultiSelectInner<T>(
hideSelectAll = false,
searchable = true,
searchMode = 'filter',
resetScrollOnSearch = false,
defaultSearchValue = '',
onSearchValueChange,
emptyIndicator = '검색 결과가 없습니다.',
@@ -199,6 +200,7 @@ function MultiSelectInner<T>(
selectedValues={selectedValues}
searchable={searchable}
searchMode={searchMode}
resetScrollOnSearch={resetScrollOnSearch}
searchValue={searchValue}
onSearchValueChange={handleSearchChange}
hideSelectAll={hideSelectAll}

View File

@@ -1,5 +1,6 @@
'use client'
import * as React from 'react'
import { CheckIcon } from 'lucide-react'
import {
Command,
@@ -20,6 +21,7 @@ interface MultiSelectContentProps<T> {
searchable: boolean
searchMode: 'filter' | 'inputOnly'
searchValue: string
resetScrollOnSearch?: boolean
onSearchValueChange: (value: string) => void
hideSelectAll: boolean
hideOptionCheck: boolean
@@ -97,6 +99,7 @@ export function MultiSelectContent<T>({
searchable,
searchMode,
searchValue,
resetScrollOnSearch = false,
onSearchValueChange,
hideSelectAll,
hideOptionCheck,
@@ -105,6 +108,17 @@ export function MultiSelectContent<T>({
onToggleOption,
onToggleAll,
}: MultiSelectContentProps<T>) {
const listRef = React.useRef<HTMLDivElement>(null)
React.useEffect(() => {
if (!resetScrollOnSearch) return
const frame = requestAnimationFrame(() => {
if (listRef.current) listRef.current.scrollTop = 0
})
return () => cancelAnimationFrame(frame)
}, [resetScrollOnSearch, searchValue])
const grouped = isGroupedOptions(options)
const flatOptions = grouped ? options.flatMap((group) => group.options) : options
const selectableOptions = flatOptions.filter((option) => !option.disabled)
@@ -119,7 +133,7 @@ export function MultiSelectContent<T>({
placeholder="검색..."
/>
) : null}
<CommandList>
<CommandList ref={listRef}>
<CommandEmpty>{emptyIndicator}</CommandEmpty>
{selectionMode === 'multiple' && !hideSelectAll && selectableOptions.length > 0 ? (
<>

View File

@@ -64,6 +64,7 @@ export interface MultiSelectProps<T = unknown>
hideSelectAll?: boolean
searchable?: boolean
searchMode?: 'filter' | 'inputOnly'
resetScrollOnSearch?: boolean
defaultSearchValue?: string
onSearchValueChange?: (value: string) => void
emptyIndicator?: React.ReactNode

View File

@@ -0,0 +1,553 @@
"use client";
import Image from "next/image";
import { useEffect, useState, type ReactNode } from "react";
import { useRouter } from "next/navigation";
import {
DndContext,
PointerSensor,
closestCenter,
useSensor,
useSensors,
type DragEndEvent,
} from "@dnd-kit/core";
import {
SortableContext,
arrayMove,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { apiError } from "@kri/common/http";
import { QueryState } from "@/components/project/QueryState";
import { FilterPopup } from "@/components/report/FilterPopup";
import { PcOnlyNotice } from "@/components/report/ReportChrome";
import { LegacyCheck, SquareButton, StatBox } from "@/components/report/ReportParts";
import { useAuth } from "@/hooks/useAuth";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { useVisitLog } from "@/hooks/useVisitLog";
import { useDerivedListQuery, useDerivedMutations } from "@/query/derived";
import { useQuestionQuery } from "@/query/report";
import { projectKey, type ProjectRef } from "@/types/kart";
import {
DERIVED_TYPES,
derivedFormError,
newDerivedValue,
readDerivedJson,
writeVariableInfo,
type DerivedElse,
type DerivedType,
type DerivedValue,
type DerivedVariable,
} from "@/types/derived";
import {
filterCondition,
readFilterArray,
realFilterCondition,
writeFilterArray,
type LegacyFilterLine,
} from "@/lib/legacy-filter";
import { cn } from "@/lib/utils";
export function DerivedWorkspace() {
const router = useRouter();
const { auth } = useAuth();
const { project, hydrated } = useSelectedProject();
const missing = hydrated && !project;
useEffect(() => {
if (missing) router.replace("/");
}, [missing, router]);
if (!project) return null;
return (
<Workspace
key={JSON.stringify([
projectKey(project),
auth.user?.userId,
auth.user?.userRole,
auth.user?.userTeam,
])}
project={project}
/>
);
}
type Form = {
/** Stored id of the variable being edited; null for "New Variable". */
originId: string | null;
variableId: string;
title: string;
type: DerivedType;
values: DerivedValue[];
otherwise: DerivedElse;
nextValueId: number;
};
// Legacy resetSelectedVariable: Single, no values, Else shown (not Missing).
const emptyForm = (): Form => ({
originId: null,
variableId: "",
title: "",
type: "single",
values: [],
otherwise: { isMissing: false, value: "", label: "" },
nextValueId: 0,
});
const errorMessage = (error: unknown, fallbackMessage: string) =>
apiError(error, { fallbackMessage }).message;
/** Legacy views/Management/Derived.js: variable list, definition form, value rules and Else. */
function Workspace({ project }: { project: ProjectRef }) {
const variables = useDerivedListQuery(project);
const questions = useQuestionQuery(project);
const { save, remove } = useDerivedMutations(project);
const [form, setForm] = useState<Form>(emptyForm);
const [filterFor, setFilterFor] = useState<string | null>(null);
useVisitLog("/Management/Derived", project);
const patch = (next: Partial<Form>) => setForm((current) => ({ ...current, ...next }));
const updateValue = (id: string, next: Partial<DerivedValue>) =>
setForm((current) => ({
...current,
values: current.values.map((row) => (row.id === id ? { ...row, ...next } : row)),
}));
const selectVariable = (variable: DerivedVariable) => {
try {
const { values, otherwise } = readDerivedJson(variable.derivedJson);
setForm({
originId: variable.id,
variableId: variable.id,
title: variable.title,
type: variable.type,
values,
otherwise,
nextValueId: values.length,
});
} catch (error) {
window.alert(errorMessage(error, "파생변수 설정을 읽을 수 없습니다."));
}
};
const submit = async (asNew: boolean) => {
const variableInfo = writeVariableInfo(form.values, form.otherwise);
const invalid = derivedFormError({
variableId: form.variableId,
title: form.title,
type: form.type,
info: variableInfo,
});
if (invalid) {
window.alert(invalid);
return;
}
try {
await save.mutateAsync({
originId: asNew ? null : form.originId,
request: {
variableId: form.variableId.trim(),
variableTitle: form.title.trim(),
variableType: form.type,
variableInfo,
},
});
window.alert("저장되었습니다.");
setForm(emptyForm());
} catch (error) {
window.alert(errorMessage(error, "파생변수를 저장하지 못했습니다."));
}
};
const destroy = async (variable: DerivedVariable) => {
if (!window.confirm("정말 삭제 하시겠습니까?")) return;
try {
await remove.mutateAsync(variable.id);
window.alert("삭제되었습니다.");
setForm(emptyForm());
} catch (error) {
window.alert(errorMessage(error, "파생변수를 삭제하지 못했습니다."));
}
};
const editing = form.values.find((row) => row.id === filterFor);
const editingLines = (() => {
if (!editing) return [];
try {
return readFilterArray(editing.array);
} catch {
return [];
}
})();
const applyFilter = (lines: LegacyFilterLine[]) => {
if (!editing) return;
updateValue(editing.id, {
condition: filterCondition(lines),
realCondition: realFilterCondition(lines),
array: writeFilterArray(lines),
});
};
if (variables.isPending || variables.isError)
return (
<QueryState
pending={variables.isPending}
error={variables.error}
onRetry={() => void variables.refetch()}
/>
);
const numeric = form.type === "num";
return (
<section
aria-label="Create Variable"
className="-mx-[1.0416vw] -mt-2.5 -mb-6 min-h-[calc(100vh-146px)] bg-white"
>
<div className="hidden [@media(pointer:coarse)_and_(max-width:767px)]:block">
<PcOnlyNotice />
</div>
<div className="flex items-start gap-[1.041vw] px-[1.0416vw] py-5 [@media(pointer:coarse)_and_(max-width:767px)]:hidden">
<div className="w-[396px] shrink-0">
<VariableList
variables={variables.data}
selectedId={form.originId}
onSelect={selectVariable}
onDelete={(variable) => void destroy(variable)}
/>
<button
type="button"
onClick={() => setForm(emptyForm())}
className="ml-5 cursor-pointer bg-[url(/images/kart/ic_plus_bl.png)] bg-size-[12px_12px] bg-position-[left_top_4px] bg-no-repeat pl-4 text-sm font-bold text-kart-text"
>
Create
</button>
</div>
<div className="min-w-0 flex-1">
<StatBox icon="document" title={form.originId ? "Update Variable" : "New Variable"}>
<div className="px-4 pb-3">
<div className="flex gap-5">
<div>
<FieldTitle htmlFor="derived_id">Variable Name</FieldTitle>
<input
id="derived_id"
type="text"
value={form.variableId}
placeholder="영어, 숫자만 사용 가능"
// Legacy: letters and digits only, never a leading digit.
onChange={(event) =>
patch({ variableId: event.target.value.replace(/^\d|[^\da-zA-Z]/g, "") })
}
className={inputClass + " w-[22.708vw] max-w-[45.8vw]"}
/>
</div>
<div className="flex flex-col gap-2">
<FieldTitle>Type</FieldTitle>
<div role="radiogroup" aria-label="Type" className="flex h-9 items-center gap-[1.458vw]">
{DERIVED_TYPES.map((type) => (
<label
key={type.value}
className="flex cursor-pointer items-center gap-1.5 text-sm text-kart-text"
>
<input
type="radio"
name="derived_type"
checked={form.type === type.value}
onChange={() => patch({ type: type.value })}
className="size-5 shrink-0 cursor-pointer appearance-none rounded-full border-2 border-[#767676] bg-white checked:border-kart-green checked:bg-kart-green checked:shadow-[inset_0_0_0_3px_white] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-kart-green"
/>
{type.label}
</label>
))}
</div>
</div>
</div>
<FieldTitle htmlFor="derived_title">Title</FieldTitle>
<input
id="derived_title"
type="text"
value={form.title}
onChange={(event) => patch({ title: event.target.value })}
className={inputClass + " w-full max-w-[710px]"}
/>
</div>
</StatBox>
<div className="mb-4 flex h-[55px] items-center gap-2 rounded-[15px] bg-kart-green p-2.5">
<Image
src="/images/kart/ic_filter_36.png"
alt=""
width={36}
height={36}
className="h-[33px] w-9 object-contain"
unoptimized
/>
<h3 className="text-base font-bold text-white">Value</h3>
</div>
<ValueRows
values={form.values}
numeric={numeric}
onMove={(values) => patch({ values })}
onChange={updateValue}
onRemove={(id) =>
patch({ values: form.values.filter((row) => row.id !== id) })
}
onSetting={setFilterFor}
/>
<button
type="button"
onClick={() =>
patch({
values: [...form.values, newDerivedValue("derived_value_" + form.nextValueId)],
nextValueId: form.nextValueId + 1,
})
}
className="my-5 h-7 w-[113px] cursor-pointer rounded-[52px] bg-kart-green bg-[url(/images/kart/ic_plus_s.png)] bg-size-[12px_12px] bg-position-[left_16px_center] bg-no-repeat pl-5 text-sm font-bold text-white"
>
Add Value
</button>
<StatBox icon="document" title="Else">
<div className="px-4 pb-3">
<FieldTitle>Else</FieldTitle>
<LegacyCheck
id="chk_missing"
label="Missing"
checked={form.otherwise.isMissing}
onChange={(isMissing) => patch({ otherwise: { ...form.otherwise, isMissing } })}
/>
{form.otherwise.isMissing ? null : (
<div className="flex gap-2">
<div>
<FieldTitle htmlFor="else_value">Value</FieldTitle>
<input
id="else_value"
type="text"
value={form.otherwise.value}
onChange={(event) =>
patch({
otherwise: {
...form.otherwise,
value: event.target.value.replace(/[^0-9]/g, ""),
},
})
}
className={inputClass + " w-[22.708vw]"}
/>
</div>
{numeric ? null : (
<div>
<FieldTitle htmlFor="else_label">Label</FieldTitle>
<input
id="else_label"
type="text"
value={form.otherwise.label}
onChange={(event) =>
patch({ otherwise: { ...form.otherwise, label: event.target.value } })
}
className={inputClass + " w-[22.708vw]"}
/>
</div>
)}
</div>
)}
</div>
</StatBox>
<div className="flex justify-center gap-1">
<SquareButton done disabled={save.isPending} onClick={() => void submit(false)}>
Save
</SquareButton>
{form.originId ? (
<SquareButton done={false} disabled={save.isPending} onClick={() => void submit(true)}>
Save As
</SquareButton>
) : null}
</div>
</div>
</div>
{editing ? (
<FilterPopup
open
initial={editingLines}
questions={questions.data ?? []}
onOpenChange={(open) => {
if (!open) setFilterFor(null);
}}
onSave={applyFilter}
/>
) : null}
</section>
);
}
const inputClass =
"h-9 rounded-[4px] border border-kart-line bg-white px-3.5 py-1 text-sm leading-[19px] font-light text-[#999] outline-none";
function FieldTitle({ htmlFor, children }: { htmlFor?: string; children: ReactNode }) {
return (
<h3 className="pt-2.5 pb-2 text-base font-bold text-kart-title">
{htmlFor ? <label htmlFor={htmlFor}>{children}</label> : children}
</h3>
);
}
/** Legacy VariableBoxDerived: derived variables with a delete (x) after each title. */
function VariableList({
variables,
selectedId,
onSelect,
onDelete,
}: {
variables: DerivedVariable[];
selectedId: string | null;
onSelect: (variable: DerivedVariable) => void;
onDelete: (variable: DerivedVariable) => void;
}) {
return (
<div className="mb-5 rounded-[15px] bg-white shadow-[1px_0_0_0_#e1e1e1,0_1px_0_0_#e1e1e1,1px_1px_0_0_#e1e1e1,inset_1px_0_0_0_#e1e1e1,inset_0_1px_0_0_#e1e1e1]">
<div className="flex h-[55px] items-center gap-2 rounded-[15px] bg-kart-soft p-2.5 shadow-[1px_0_0_0_#e1e1e1,0_1px_0_0_#e1e1e1,1px_1px_0_0_#e1e1e1,inset_1px_0_0_0_#e1e1e1,inset_0_1px_0_0_#e1e1e1]">
<Image src="/images/kart/ic_document_36-2.svg" alt="" width={36} height={36} unoptimized />
<h3 className="text-base font-bold text-kart-title">Variable List</h3>
</div>
{variables.length ? (
<ul className="px-4 pb-2">
{variables.map((variable) => (
<li key={variable.id} className="mt-2 flex items-center">
<button
type="button"
title={variable.title}
aria-current={variable.id === selectedId ? "true" : undefined}
onClick={() => onSelect(variable)}
className={cn(
"w-[94%] cursor-pointer overflow-hidden bg-kart-bg px-3 py-2 text-left text-sm leading-5 text-ellipsis whitespace-nowrap text-kart-text",
variable.id === selectedId && "text-kart-green",
)}
>
{variable.id + ". " + variable.title}
</button>
<button
type="button"
aria-label={variable.id + " 삭제"}
onClick={() => onDelete(variable)}
className="ml-[7px] cursor-pointer"
>
<Image src="/images/kart/ic_close.png" alt="" width={12} height={12} unoptimized />
</button>
</li>
))}
</ul>
) : null}
</div>
);
}
/** Legacy DerivedChild list: rows reorder by dragging (rule order decides the first match). */
function ValueRows({
values,
numeric,
onMove,
onChange,
onRemove,
onSetting,
}: {
values: DerivedValue[];
numeric: boolean;
onMove: (values: DerivedValue[]) => void;
onChange: (id: string, next: Partial<DerivedValue>) => void;
onRemove: (id: string) => void;
onSetting: (id: string) => void;
}) {
// Pointer only: the rows contain text inputs, where Space/Enter must not start a drag.
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
);
const onDragEnd = ({ active, over }: DragEndEvent) => {
if (!over || active.id === over.id) return;
const ids = values.map((row) => row.id);
onMove(arrayMove(values, ids.indexOf(String(active.id)), ids.indexOf(String(over.id))));
};
return (
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
<SortableContext items={values.map((row) => row.id)} strategy={verticalListSortingStrategy}>
{values.map((row) => (
<ValueRow
key={row.id}
row={row}
numeric={numeric}
onChange={(next) => onChange(row.id, next)}
onRemove={() => onRemove(row.id)}
onSetting={() => onSetting(row.id)}
/>
))}
</SortableContext>
</DndContext>
);
}
function ValueRow({
row,
numeric,
onChange,
onRemove,
onSetting,
}: {
row: DerivedValue;
numeric: boolean;
onChange: (next: Partial<DerivedValue>) => void;
onRemove: () => void;
onSetting: () => void;
}) {
const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: row.id,
});
return (
<div
ref={setNodeRef}
style={{ transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.4 : 1 }}
{...listeners}
className="mb-4 cursor-pointer rounded-[15px] border border-kart-line bg-white px-4 pb-3"
>
<div className="relative flex items-center pt-2.5 pb-2">
<h3 className="text-base font-bold text-kart-title">Condition</h3>
<button
type="button"
onClick={onSetting}
className="ml-5 h-[27px] w-[113px] cursor-pointer rounded-[52px] bg-kart-green text-sm font-bold text-white"
>
Setting
</button>
<button
type="button"
aria-label="값 삭제"
onClick={onRemove}
className="absolute top-2 right-0 cursor-pointer"
>
<Image src="/images/kart/trash_icon.png" alt="" width={24} height={24} unoptimized />
</button>
</div>
<input
type="text"
readOnly
aria-label="Condition"
value={row.condition}
className="h-9 w-full rounded-[4px] bg-kart-bg px-3.5 py-1 text-sm font-light text-[#999] outline-none"
/>
<div className="flex gap-2">
<div>
<FieldTitle>Value</FieldTitle>
<input
type="text"
aria-label="Value"
value={row.value}
onChange={(event) => onChange({ value: event.target.value.replace(/[^0-9]/g, "") })}
className={inputClass + " w-[22.708vw]"}
/>
</div>
{numeric ? null : (
<div>
<FieldTitle>Label</FieldTitle>
<input
type="text"
aria-label="Label"
value={row.label}
onChange={(event) => onChange({ label: event.target.value })}
className={inputClass + " w-[22.708vw]"}
/>
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,314 @@
"use client";
import Image from "next/image";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useRouter } from "next/navigation";
import { apiError } from "@kri/common/http";
import { PcOnlyNotice } from "@/components/report/ReportChrome";
import { useAuth } from "@/hooks/useAuth";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { useVisitLog } from "@/hooks/useVisitLog";
import { useFileDownload, useImportFile, type Download, type ImportTarget } from "@/query/export";
import { useProjectTitle } from "@/query/project";
import { EXPORT_PREFIX, QUESTION_FORM_NAME } from "@/lib/download-name";
import { projectKey, type ProjectRef } from "@/types/kart";
import type { RawDataRequest } from "@/types/export";
export function EximWorkspace() {
const router = useRouter();
const { auth } = useAuth();
const { project, hydrated } = useSelectedProject();
const missing = hydrated && !project;
useEffect(() => {
if (missing) router.replace("/");
}, [missing, router]);
if (!project) return null;
return (
<Workspace
key={JSON.stringify([
projectKey(project),
auth.user?.userId,
auth.user?.userRole,
auth.user?.userTeam,
])}
project={project}
/>
);
}
const failure = (error: unknown, fallbackMessage: string) =>
window.alert(apiError(error, { fallbackMessage }).message);
/** Legacy views/Management/Exim.js: raw data / guide export and the three replacement imports. */
function Workspace({ project }: { project: ProjectRef }) {
const download = useFileDownload();
const upload = useImportFile(project);
const [type, setType] = useState<RawDataRequest["type"]>("COMPLETE");
useVisitLog("/Management/Exim", project);
const title = useProjectTitle(project);
const save = (target: Download, confirmText?: string) => {
if (confirmText && !window.confirm(confirmText)) return;
download.mutate(target, {
onError: (error) => failure(error, "파일을 내려받지 못했습니다."),
});
};
const importFile = (target: ImportTarget, file: File) =>
upload.mutateAsync({ target, file }).then(
(result) =>
window.alert(
"처리 " +
result.processedRows +
"건, 반영 " +
result.affectedRows +
"건, 삭제 " +
result.removedRows +
"건, 보관 " +
result.archivedRows +
"건",
),
(error: unknown) => failure(error, "파일을 올리지 못했습니다."),
);
return (
<section
aria-label="Export/Import"
className="-mx-[1.0416vw] -mt-2.5 -mb-6 min-h-[calc(100vh-146px)] bg-white"
>
<div className="hidden [@media(pointer:coarse)_and_(max-width:767px)]:block">
<PcOnlyNotice />
</div>
<div className="flex items-start gap-4 px-[1.0416vw] py-5 [@media(pointer:coarse)_and_(max-width:767px)]:hidden">
<Column icon="/images/kart/ic_export.svg" title="Export">
<EximBox title="Data Export" info="Raw Data를 다운로드 받을 수 있습니다.">
<div className="flex items-center gap-2">
<h3 className="p-1 text-base font-bold text-kart-title">Type</h3>
<div role="radiogroup" aria-label="Type" className="flex w-[180px] items-center gap-9">
{(
[
["COMPLETE", "완료"],
["INCOMPLETE", "완료 아님"],
] as const
).map(([value, label]) => (
<label key={value} className="flex cursor-pointer items-center gap-1.5 text-sm text-kart-text">
<input
type="radio"
name="data_type"
checked={type === value}
onChange={() => setType(value)}
className="size-5 shrink-0 cursor-pointer appearance-none rounded-full border-2 border-[#767676] bg-white checked:border-kart-green checked:bg-kart-green checked:shadow-[inset_0_0_0_3px_white] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-kart-green"
/>
{label}
</label>
))}
</div>
</div>
<GreyButton
icon="/images/kart/ic_exports.png"
onClick={() =>
save(
{
kind: "data",
project,
request: { type },
name: {
prefix: type === "COMPLETE" ? EXPORT_PREFIX.data : EXPORT_PREFIX.dataIncomplete,
title,
},
},
title + " 데이터를 다운로드 하시겠습니까?",
)
}
>
Export Data
</GreyButton>
</EximBox>
<EximBox title="Variable Guide Export" info="변수 가이드를 다운로드 받을 수 있습니다.">
<span />
<GreyButton
icon="/images/kart/ic_exports.png"
onClick={() =>
save(
{ kind: "guide", project, name: { prefix: EXPORT_PREFIX.guide, title } },
title + " 변수 가이드를 다운로드 하시겠습니까?")
}
>
Export Guide
</GreyButton>
</EximBox>
</Column>
<Column icon="/images/kart/ic_import.svg" title="Import">
<ImportBox
id="import_data"
title="Data Import"
info="Data를 교체 할수 있습니다."
formTitle="Export Header"
onForm={() => save({ kind: "form/data", project, name: { prefix: EXPORT_PREFIX.header, title } })}
confirmText={title + " 프로젝트의 모든 완료 데이터를 삭제 후 진행됩니다.\r\n진행 하시겠습니까?"}
importTitle="Import Data"
onImport={(file) => importFile("data", file)}
/>
<ImportBox
id="import_question"
title="Question Import"
info="설문 문항을 초기화 하고 일괄 세팅할 수 있습니다."
formTitle="Export Form"
onForm={() => save({ kind: "form/question", name: QUESTION_FORM_NAME })}
confirmText={
title +
" 프로젝트의 모든 문항을 삭제 후 진행됩니다. (단 하드 코딩은 유지 됩니다.)\r\n진행 하시겠습니까?"
}
importTitle="Import Question"
onImport={(file) => importFile("question", file)}
wide
/>
<ImportBox
id="import_title"
title="Question Title Import"
info="Table Title을 세팅 할수 있습니다."
formTitle="Export Form"
onForm={() => save({ kind: "form/title", project, name: { prefix: EXPORT_PREFIX.title, title } })}
confirmText={title + " 프로젝트의 Title을 삭제 후 진행됩니다.\r\n진행 하시겠습니까?"}
importTitle="Import Title"
onImport={(file) => importFile("title", file)}
/>
</Column>
</div>
</section>
);
}
function Column({ icon, title, children }: { icon: string; title: string; children: ReactNode }) {
return (
<div className="min-w-0 flex-1">
<div className="mb-3.5 flex items-center gap-1">
<Image src={icon} alt="" width={36} height={36} unoptimized />
<h2 className="text-xl font-semibold text-kart-title">{title}</h2>
</div>
{children}
</div>
);
}
/** Legacy ExportBox / ImportBox frame: title with the description, then one control row. */
function EximBox({
title,
info,
action,
children,
}: {
title: string;
info: string;
action?: ReactNode;
children: ReactNode;
}) {
return (
<div className="mb-4 rounded-[15px] border border-kart-line bg-white">
<div className="-m-px flex h-[55px] items-center justify-between rounded-[15px] border border-kart-line bg-kart-soft p-2.5">
<div className="flex items-baseline gap-2">
<h3 className="text-base font-bold text-kart-title">{title}</h3>
<span className="text-sm text-kart-text">{info}</span>
</div>
{action}
</div>
<div className="flex items-center justify-between gap-5 px-4 py-3.5">{children}</div>
</div>
);
}
function GreyButton({
icon,
onClick,
children,
wide = false,
}: {
icon: string;
onClick: () => void;
children: ReactNode;
wide?: boolean;
}) {
return (
<button
type="button"
onClick={onClick}
style={{ backgroundImage: `url(${icon})` }}
className={
"h-[50px] shrink-0 cursor-pointer rounded-[4px] bg-kart-bg bg-size-[15px] bg-position-[left_20px_center] bg-no-repeat pl-10 text-base font-bold text-[#9e9e9e] grayscale " +
(wide ? "w-[190px]" : "w-[156px]")
}
>
{children}
</button>
);
}
/** Legacy ImportBox: form download (red), file picker, then a confirmed upload. */
function ImportBox({
id,
title,
info,
formTitle,
onForm,
confirmText,
importTitle,
onImport,
wide = false,
}: {
id: string;
title: string;
info: string;
formTitle: string;
onForm: () => void;
confirmText: string;
importTitle: string;
onImport: (file: File) => Promise<unknown>;
wide?: boolean;
}) {
const input = useRef<HTMLInputElement>(null);
const [file, setFile] = useState<File | null>(null);
const submit = () => {
if (!window.confirm(confirmText)) return;
if (!file) {
window.alert("파일을 선택해 주세요.");
return;
}
void onImport(file);
// Legacy clears the picker right after sending.
setFile(null);
if (input.current) input.current.value = "";
};
return (
<EximBox
title={title}
info={info}
action={
<button
type="button"
onClick={onForm}
className="h-7 w-[156px] cursor-pointer rounded-[52px] bg-[#ff5b40] bg-[url(/images/kart/ic_exports_s.png)] bg-size-[12px] bg-position-[left_20px_center] bg-no-repeat pl-3.5 text-sm font-bold text-white"
>
{formTitle}
</button>
}
>
<input
ref={input}
id={id}
type="file"
className="sr-only"
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
/>
<button
type="button"
aria-label={title + " 파일 선택"}
onClick={() => input.current?.click()}
className="h-9 w-[70%] max-w-[700px] cursor-pointer truncate rounded-[4px] border border-kart-line bg-kart-bg bg-[url(/images/kart/ic_gnb5_20.png)] bg-size-[20px] bg-position-[left_20px_center] bg-no-repeat pr-3.5 pl-[46px] text-left text-sm font-light text-[#999]"
>
{file?.name ?? "파일선택"}
</button>
<GreyButton icon="/images/kart/ic_imports.png" onClick={submit} wide={wide}>
{importTitle}
</GreyButton>
</EximBox>
);
}

View File

@@ -0,0 +1,90 @@
"use client";
import type { EChartsOption } from "echarts";
import { BaseEChart } from "@/components/chart";
import { displayCount, displayDate, type ProgressDay } from "@/types/kart";
import type { ZoomWindow } from "@/lib/progress-zoom";
import { chartTextStyle, useChartFontReady } from "@/hooks/useChartFont";
// Legacy Chart.js LineBarChart: Total bar + Complete/Screen/Quota lines.
const series = [
{ key: "totalCount", name: "Total", type: "bar", color: "#1CAE81" },
{ key: "completeCount", name: "Complete", type: "line", color: "#FF5B40" },
{ key: "screenCount", name: "Screen", type: "line", color: "#FFC950" },
{ key: "quotaCount", name: "Quota", type: "line", color: "#3789FF" },
] as const;
// Legacy charts ran on ECharts 5; pin its default grid so ECharts 6 lays out the same plot area.
export const legacyGrid = {
left: "10%",
right: "10%",
top: 60,
bottom: 70,
outerBoundsMode: "none",
} as const;
/** Glyphs drawn by axis/value labels besides the category names. */
export const chartDigits = "0123456789,.-";
export const seriesLabel = {
show: true,
position: "top",
fontSize: 15,
fontWeight: "bold",
valueAnimation: true,
formatter: (params: { value?: unknown }) =>
typeof params.value === "number" ? displayCount(params.value) : "",
} as const;
export function DailyChart({
rows,
zoom,
onZoom,
}: {
rows: ProgressDay[];
zoom: ZoomWindow;
onZoom: (event: unknown) => void;
}) {
const dates = rows.map((row) => displayDate(row.surveyDate));
const fontReady = useChartFontReady(
dates.join("") + series.map((item) => item.name).join("") + chartDigits,
);
const option: EChartsOption = {
textStyle: chartTextStyle,
grid: legacyGrid,
tooltip: { trigger: "axis", textStyle: chartTextStyle },
xAxis: { type: "category", data: dates },
yAxis: { type: "value" },
series: series.map((item, index) => ({
name: item.name,
type: item.type,
color: item.color,
data: rows.map((row) => row[item.key]),
...(item.type === "bar"
? { barMaxWidth: 100 }
: { symbolSize: 10, lineStyle: { width: 3 } }),
...(index === 0 ? { label: seriesLabel } : {}),
})) as EChartsOption["series"],
dataZoom: [
{
type: "slider",
height: 30,
// ECharts 6 draws the slider ~9px lower than the legacy ECharts 5 default (bottom: 7).
bottom: 16,
show: true,
xAxisIndex: [0],
start: zoom.start,
end: zoom.end,
},
],
};
if (!fontReady) return null;
return (
<BaseEChart
option={option}
height={370}
normalizeValues={false}
onEvents={{ datazoom: onZoom }}
/>
);
}

View File

@@ -0,0 +1,50 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import type { Route } from "next";
import { useSetAtom } from "jotai";
import { useQueryClient } from "@tanstack/react-query";
import { apiError } from "@kri/common/http";
import { useAuth } from "@/hooks/useAuth";
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
import { nextApi } from "@/lib/http-client";
import { isExternalSession, reportUrl, type ExternalSession } from "@/types/share";
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
export function ExternalEntry({ urlKey }: { urlKey: string }) {
const router = useRouter();
const { hydrated, setAuth, logout } = useAuth();
const setProject = useSetAtom(selectedProjectAtom);
const queryClient = useQueryClient();
const pending = useRef<Promise<ExternalSession> | null>(null);
const [error, setError] = useState("");
useEffect(() => {
if (!hydrated) return;
let active = true;
const enter = async () => {
logout();
setProject(null);
await queryClient.cancelQueries();
queryClient.clear();
const result = await nextApi.post<unknown>(`/external/${encodeURIComponent(urlKey)}/login`, null, {
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
});
if (!isExternalSession(result)) throw new Error("공유 링크 로그인 응답을 확인해 주세요.");
return result;
};
// Reuse the request during StrictMode effect replay; each entry records one landing.
pending.current ??= enter();
void pending.current.then((result) => {
if (!active) return;
setProject({ userId: result.user.userId, project: { projectType: result.link.projectType, pkey: result.link.pkey } });
setAuth({ user: result.user, external: result.link });
router.replace(reportUrl(result.link.realUrl) as Route);
}).catch((reason: unknown) => {
if (active) setError(apiError(reason, { fallbackMessage: "공유 링크를 확인해 주세요." }).message);
});
return () => { active = false; };
}, [hydrated, logout, setAuth, setProject, queryClient, router, urlKey]);
if (error) return <p role="alert" className="p-8 text-center text-sm">{error}</p>;
return <LoadingOverlayAdapter force label="공유 링크를 확인하는 중입니다." />;
}

View File

@@ -0,0 +1,125 @@
"use client";
import Image from "next/image";
import Link from "next/link";
import { useEffect } from "react";
import { KriPieChart } from "@/components/chart";
import { useProjectSummaryQuery } from "@/query/project";
import { useVisitLog } from "@/hooks/useVisitLog";
import { useAuth } from "@/hooks/useAuth";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { chartTextStyle, useChartFontReady } from "@/hooks/useChartFont";
import { projectKey } from "@/types/kart";
import { QueryState } from "./QueryState";
import { SpecialEffect, hasSpecialEffect } from "./SpecialEffect";
// Legacy Chart.js DoughnutChart palette and labels.
const colors = ["#B3D2FF", "#DAECAF", "#FFBEB3", "#FFE9B8"];
const labels = ["완료", "스크린", "쿼터", "진행중"];
export function ProjectOverview() {
const { auth } = useAuth();
const summary = useProjectSummaryQuery();
const fontReady = useChartFontReady(labels.join("") + "0123456789");
const { hydrated, select, clear } = useSelectedProject();
useVisitLog("/");
// Legacy Main.js resets the selected project whenever the overview opens.
useEffect(() => {
if (hydrated) clear();
}, [hydrated, clear]);
return (
<section aria-label="Project Overview TOP 6">
{auth.user && hasSpecialEffect(auth.user.userId) ? (
<SpecialEffect />
) : null}
{summary.isPending || summary.isError || !summary.data?.length ? (
<QueryState
pending={summary.isPending}
error={summary.error}
empty="조회 가능한 최근 프로젝트가 없습니다."
onRetry={() => void summary.refetch()}
/>
) : (
<div className="grid grid-cols-1 gap-[0.8332vw] py-[0.4166vw] min-[768px]:grid-cols-2 min-[1301px]:grid-cols-3">
{summary.data.map((project) => (
<div
key={projectKey(project)}
className="relative h-[420px] rounded-[15px] border border-kart-line bg-white"
>
<Link
href="/Report/Current"
onClick={() => select(project)}
title={project.title ?? project.pkey}
className="-m-px flex h-[55px] items-center justify-between rounded-[15px] border border-kart-line bg-kart-soft p-4"
>
<div className="flex min-w-0 items-center gap-2">
<Image
src="/images/kart/icon_circle.svg"
alt=""
width={36}
height={36}
className="size-9 shrink-0"
unoptimized
/>
<h3 className="line-clamp-2 text-base font-bold text-kart-title">
{project.title || project.pkey}
</h3>
</div>
<div className="flex shrink-0 gap-2">
{[project.surveyType, project.status].map((value, index) => (
<span
key={index}
className="inline-block h-[27px] min-w-[55px] rounded-[39px] border border-kart-line px-1 text-center text-sm leading-[25px] text-kart-text"
>
{value ?? "-"}
</span>
))}
</div>
</Link>
{/* Legacy chart_frame: 350px canvas whose top lands 48px below the card top. */}
<div className="absolute top-12 left-0 h-[350px] w-full">
{fontReady ? (
<KriPieChart
height={350}
option={{ textStyle: chartTextStyle }}
tooltip={{ trigger: "item", textStyle: chartTextStyle }}
legend={{ bottom: "0%", left: "center" }}
normalizeValues={false}
series={[
{
name: project.title ?? project.pkey,
radius: ["35%", "70%"],
center: ["50%", "50%"],
data: [
project.completeCount,
project.screenCount,
project.quotaCount,
project.ongoingCount,
].map((value, index) => ({
name: labels[index],
value: value ?? "-",
})),
option: {
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 5,
borderColor: "#fff",
borderWidth: 2,
},
label: { show: false, position: "center" },
emphasis: { label: { show: false } },
labelLine: { show: false },
color: colors,
},
},
]}
/>
) : null}
</div>
</div>
))}
</div>
)}
</section>
);
}

View File

@@ -0,0 +1,232 @@
"use client";
import Image from "next/image";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useRouter } from "next/navigation";
import { useProgressQuery } from "@/query/project";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { useVisitLog } from "@/hooks/useVisitLog";
import {
displayCount,
displayDate,
projectKey,
type ProjectRef,
type DateRange,
} from "@/types/kart";
import {
readZoomEvent,
zoomDateRange,
type ZoomWindow,
} from "@/lib/progress-zoom";
import { QueryState } from "./QueryState";
import { DailyChart } from "./DailyChart";
import { ScreenChart } from "./ScreenChart";
export function ProjectProgress() {
const router = useRouter();
const { project, hydrated } = useSelectedProject();
// Legacy AuthRoute sends project pages without a selected project back home.
const missing = hydrated && !project;
useEffect(() => {
if (missing) router.replace("/");
}, [missing, router]);
if (!project) return null;
return <ProgressDetails key={projectKey(project)} project={project} />;
}
/** Legacy Current.js layout; the daily chart's dataZoom drives the type/loi/screen date filter. */
function ProgressDetails({ project }: { project: ProjectRef }) {
const [range, setRange] = useState<DateRange>({ startDate: "", endDate: "" });
const [zoom, setZoom] = useState<ZoomWindow>({ start: 0, end: 100 });
const pendingZoom = useRef<ZoomWindow | null>(null);
const queries = useProgressQuery(project, range);
useVisitLog("/Report/Current", project);
const type = queries.type.data?.[0];
const loi = queries.loi.data?.[0];
const dates = (queries.daily.data ?? []).map((row) =>
displayDate(row.surveyDate),
);
// Legacy applies the zoomed dates on mouse release, not on every drag step.
const applyZoom = () => {
const next = pendingZoom.current;
pendingZoom.current = null;
if (!next) return;
setZoom(next);
const nextRange = zoomDateRange(dates, next);
if (
nextRange &&
(nextRange.startDate !== range.startDate ||
nextRange.endDate !== range.endDate)
)
setRange(nextRange);
};
return (
<section
aria-label="진행 현황"
className="flex flex-col"
onPointerUp={applyZoom}
>
<div className="flex w-full gap-2 max-[1024px]:flex-wrap">
<ProgressBox title="응답자 현황" table>
<ValueTable
header={["Total", "Complete", "Screen", "Quota", "Ongoing"]}
values={
type && [
displayCount(type.totalCount),
displayCount(type.completeCount),
displayCount(type.screenCount),
displayCount(type.quotaCount),
displayCount(type.goingCount),
]
}
/>
{queries.type.isError ? (
<QueryState
error={queries.type.error}
onRetry={() => void queries.type.refetch()}
/>
) : null}
</ProgressBox>
<ProgressBox title="응답시간" table>
<ValueTable
header={["N", "AVG", "AVG (제외 Top/Bot 2.5%)", "Min", "Max"]}
values={
loi && [
displayCount(loi.cnt),
loi.avgLoi ?? "-",
loi.avgLoiModify ?? "-",
loi.minLoi ?? "-",
loi.maxLoi ?? "-",
]
}
/>
{queries.loi.isError ? (
<QueryState
error={queries.loi.error}
onRetry={() => void queries.loi.refetch()}
/>
) : null}
</ProgressBox>
</div>
<ProgressBox title="일별 참여자 수">
{queries.daily.isError ? (
<QueryState
error={queries.daily.error}
onRetry={() => void queries.daily.refetch()}
/>
) : queries.daily.data && !queries.daily.data.length ? (
<QueryState empty="일별 참여 데이터가 없습니다." />
) : queries.daily.data ? (
<ChartFrame>
<DailyChart
rows={queries.daily.data}
zoom={zoom}
onZoom={(event) => {
pendingZoom.current = readZoomEvent(event);
}}
/>
</ChartFrame>
) : null}
</ProgressBox>
<ProgressBox title="문항별 SCREEN OUT 사례수">
{queries.screen.isError ? (
<QueryState
error={queries.screen.error}
onRetry={() => void queries.screen.refetch()}
/>
) : queries.screen.data ? (
<ChartFrame>
<ScreenChart rows={queries.screen.data} />
</ChartFrame>
) : null}
</ProgressBox>
</section>
);
}
/** Legacy chart_box: 420px card (chart_box2 for the tables: transparent, auto height). */
function ProgressBox({
title,
table = false,
children,
}: {
title: string;
table?: boolean;
children: ReactNode;
}) {
return (
<div
className={
table
? "mb-4 w-[calc((100%-8px)/2)] max-[1024px]:w-full"
: "relative mb-4 h-[420px] w-full rounded-[15px] border border-kart-line bg-white"
}
>
<div className="-m-px flex h-[55px] items-center gap-2 rounded-[15px] border border-kart-line bg-kart-soft p-2.5">
<Image
src="/images/kart/icon_circle.svg"
alt=""
width={36}
height={36}
className="size-9"
unoptimized
/>
<h3 className="text-base font-bold text-kart-title">{title}</h3>
</div>
{children}
</div>
);
}
/** Legacy chart_frame (width 98%): the 370px canvas starts 48px below the box top. */
function ChartFrame({ children }: { children: ReactNode }) {
return (
<div className="absolute top-12 left-1/2 h-[370px] w-[98%] -translate-x-1/2">
{children}
</div>
);
}
/** Legacy CurrentTable. */
function ValueTable({
header,
values,
}: {
header: string[];
values?: string[];
}) {
return (
<div className="mt-2 w-full overflow-hidden rounded-[4px]">
<div className="h-[70px] w-full overflow-x-auto max-[1024px]:h-auto">
<table className="h-full w-full table-fixed text-center text-sm whitespace-nowrap text-kart-text">
<thead>
<tr>
{header.map((label) => (
<th
key={label}
className="w-[150px] border border-[#d0d0d0] bg-kart-line px-2.5 py-1.5 font-bold"
>
{label}
</th>
))}
</tr>
</thead>
<tbody>
{values ? (
<tr>
{values.map((value, index) => (
<td
key={header[index]}
className="border-r border-b border-l border-[#d0d0d0] bg-white py-1.5 font-bold"
>
{value}
</td>
))}
</tr>
) : null}
</tbody>
</table>
</div>
</div>
);
}

View File

@@ -0,0 +1,58 @@
"use client";
import { useRouter, usePathname } from "next/navigation";
import { KriSingleSelect } from "@/components/common/KriAutoComplete";
import { useProjectListQuery } from "@/query/project";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { projectKey } from "@/types/kart";
import { projectPagePath } from "@/lib/report-navigation";
import { QueryState } from "./QueryState";
/** Legacy ProjectSelect: search dropdown that always reads "프로젝트 선택". */
export function ProjectSelector() {
const router = useRouter();
const pathname = usePathname();
const { project: selected, select } = useSelectedProject();
const projects = useProjectListQuery();
if (projects.isError)
return (
<QueryState
error={projects.error}
onRetry={() => void projects.refetch()}
/>
);
return (
<KriSingleSelect
// Remount after each selection so the trigger returns to the legacy fixed label.
key={selected ? projectKey(selected) : ""}
items={projects.data ?? []}
value=""
getValue={projectKey}
getLabel={(item) => "(" + item.pkey + ") " + (item.title ?? "")}
onChange={(value) => {
const project = projects.data?.find(
(item) => projectKey(item) === value,
);
if (!project) return;
// Same page for the new project (legacy keeps the current menu), progress from home.
select(project);
router.push(projectPagePath(pathname));
}}
placeholder={
projects.isPending
? "목록을 불러오는 중..."
: projects.data?.length
? "프로젝트 선택"
: "조회 가능한 프로젝트가 없습니다."
}
widthClassName="w-full"
className="h-8 min-h-8 rounded-[39px] border-[#d0d0d0] bg-kart-soft px-[22px] py-0 text-sm shadow-none"
spanClassName="text-sm [&_span]:text-kart-text"
searchable
resetScrollOnSearch
preventDeselect
hideOptionCheck
disabled={projects.isPending}
/>
);
}

View File

@@ -0,0 +1,51 @@
"use client";
import { apiError } from "@kri/common/http";
import { Button } from "@/components/ui/button";
export function QueryState({
pending,
error,
empty,
onRetry,
}: {
pending?: boolean;
error?: Error | null;
empty?: string;
onRetry?: () => void;
}) {
if (pending)
return (
<p
className="p-8 text-center text-sm text-muted-foreground"
role="status"
>
데이터를 불러오는 중입니다.
</p>
);
if (error)
return (
<div
role="alert"
className="space-y-3 rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-sm"
>
<p>
{
apiError(error, {
fallbackMessage: "데이터를 불러오지 못했습니다.",
}).message
}
</p>
{onRetry && (
<Button variant="outline" size="sm" onClick={onRetry}>
다시 시도
</Button>
)}
</div>
);
return (
<p className="p-8 text-center text-sm text-muted-foreground">
{empty ?? "조회 결과가 없습니다."}
</p>
);
}

View File

@@ -0,0 +1,52 @@
"use client";
import type { EChartsOption } from "echarts";
import { BaseEChart } from "@/components/chart";
import type { ProgressScreen } from "@/types/kart";
import { chartTextStyle, useChartFontReady } from "@/hooks/useChartFont";
import { chartDigits, legacyGrid, seriesLabel } from "./DailyChart";
const escapeHtml = (text: string) =>
text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
/** Legacy Current.js: VIEWTITLE with entities decoded, tags and &nbsp; removed. */
export function screenTooltipText(viewTitle: string | null): string {
return (viewTitle ?? "")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/<[^>]*>?/g, "")
.replace(/&nbsp;/gi, "");
}
// Legacy Chart.js BarChart for "문항별 SCREEN OUT 사례수".
export function ScreenChart({ rows }: { rows: ProgressScreen[] }) {
const pages = rows.map((row) => row.pageName ?? "");
const fontReady = useChartFontReady(pages.join("") + chartDigits);
const option: EChartsOption = {
textStyle: chartTextStyle,
grid: legacyGrid,
tooltip: {
trigger: "axis",
textStyle: chartTextStyle,
// ECharts renders the formatter result as HTML, so escape the stripped title.
formatter: (params) => {
const first = Array.isArray(params) ? params[0] : params;
const row = rows[first?.dataIndex ?? -1];
return "<p>" + escapeHtml(screenTooltipText(row?.viewTitle ?? null)) + "</p>";
},
},
xAxis: { type: "category", data: pages },
yAxis: { type: "value" },
series: [
{
type: "bar",
data: rows.map((row) => row.cnt),
barMaxWidth: 100,
color: "#1CAE81",
label: seriesLabel,
},
],
};
if (!fontReady) return null;
return <BaseEChart option={option} height={370} normalizeValues={false} />;
}

View File

@@ -0,0 +1,107 @@
"use client";
import { useEffect, useState } from "react";
// Legacy Main.js effectUser list (email local parts).
const effectUsers = [
"jspark",
"joohee",
"choins",
"shbaek",
"seoyun",
"cwpark",
"hrsim",
];
export function hasSpecialEffect(userId: string): boolean {
return effectUsers.includes(userId.toLowerCase().split("@")[0]);
}
type Particle = {
id: number;
left: number;
duration: number;
/** petal color or kring image index */
look: string;
};
/** Legacy SpecialEffect.js: FlowerPetals or KringEffect for 10 seconds on the home page. */
export function SpecialEffect() {
const [kind, setKind] = useState<"petal" | "kring" | null>(null);
const [particles, setParticles] = useState<Particle[]>([]);
useEffect(() => {
const selected = Math.random() < 0.5 ? "petal" : "kring";
setKind(selected);
let nextId = 0;
const removals = new Set<ReturnType<typeof setTimeout>>();
const spawn = setInterval(
() => {
const id = nextId++;
const look =
selected === "petal"
? "#" +
Math.floor(Math.random() * 0x1000000)
.toString(16)
.padStart(6, "0")
: String(Math.floor(Math.random() * 11) + 1);
setParticles((current) => [
...current,
{
id,
left: Math.random() * 100,
duration: Math.random() * 3 + 2,
look,
},
]);
const removal = setTimeout(() => {
removals.delete(removal);
setParticles((current) => current.filter((item) => item.id !== id));
}, 5000);
removals.add(removal);
},
selected === "petal" ? 100 : 250,
);
const stop = setTimeout(() => {
clearInterval(spawn);
setKind(null);
setParticles([]);
}, 10000);
return () => {
clearInterval(spawn);
clearTimeout(stop);
removals.forEach(clearTimeout);
};
}, []);
if (!kind) return null;
return (
<div aria-hidden="true" className="pointer-events-none">
{particles.map((particle) =>
kind === "petal" ? (
<span
key={particle.id}
className="kart-petal"
style={{
left: particle.left + "vw",
animationDuration: particle.duration + "s",
backgroundColor: particle.look,
}}
/>
) : (
// eslint-disable-next-line @next/next/no-img-element -- transient animated sprites
<img
key={particle.id}
className="kart-kring"
src={`/images/kart/kring/kring_${particle.look}.png`}
alt=""
style={{
left: particle.left + "vw",
animationDuration: particle.duration + "s",
}}
/>
),
)}
</div>
);
}

View File

@@ -0,0 +1,231 @@
"use client";
import Image from "next/image";
import { useDndContext, useDroppable } from "@dnd-kit/core";
import {
SortableContext,
arrayMove,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import type { Question } from "@/types/report";
import { isDerivedQuestion, questionViewTitle } from "@/lib/report-ui";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { plainText } from "./ReportResultView";
import {
QUESTION_COLOR,
VARIABLE_COLOR,
readDragData,
type DragBannerItem,
type DragData,
} from "./QuestionList";
export const MAX_BANNER_DEPTH = 5;
/**
* Legacy insertBanner / insertBannerSub / moveSelectedBanner. Returns the next banner groups for
* a drop, or null when the drop does not concern banners. Only "all" questions become banners.
*/
export function dropOnBanner(
banners: string[][],
data: DragData,
overId: string,
overData: DragData | null,
): string[][] | null {
if (data.kind === "question") {
if (data.loc !== "all") return null;
if (overId === "banner-new") return [...banners, [data.qid]];
if (!overId.startsWith("banner-sub:")) return null;
const group = Number(overId.slice("banner-sub:".length));
return banners.map((ids, index) =>
index === group && !ids.includes(data.qid) && ids.length < MAX_BANNER_DEPTH
? [...ids, data.qid]
: ids,
);
}
if (data.kind !== "banner-item") return null;
if (overData?.kind !== "banner-item" || overData.group !== data.group) return null;
return banners.map((ids, index) =>
index === data.group
? arrayMove(ids, ids.indexOf(data.qid), ids.indexOf(overData.qid))
: ids,
);
}
/** Removes one banner question; an emptied group disappears (legacy deleteSubBanner). */
export const removeBanner = (banners: string[][], group: number, qid: string) =>
banners
.map((ids, index) => (index === group ? ids.filter((id) => id !== qid) : ids))
.filter((ids) => ids.length > 0);
/** True while a banner-capable question is being dragged (legacy green dashed border). */
function useBannerDragActive(): boolean {
const { active } = useDndContext();
const data = readDragData(active?.data.current);
return data?.kind === "question" && data.loc === "all";
}
/** Legacy BannerBox: one column per banner group plus the trailing "Banner List" drop area. */
export function BannerBox({
banners,
questions,
onRemove,
}: {
banners: string[][];
questions: Question[];
onRemove: (group: number, qid: string) => void;
}) {
const find = (qid: string) => questions.find((item) => item.qid === qid);
return (
<div className="p-4">
<ul className="flex min-h-[210px] flex-wrap gap-2">
{banners.map((group, groupIndex) => (
<li
key={groupIndex + ":" + group.join("|")}
className="flex h-[210px] w-[280px] cursor-pointer flex-col"
>
<SortableContext
items={group.map((qid) => bannerItemId(groupIndex, qid))}
strategy={verticalListSortingStrategy}
>
{group.map((qid) => (
<BannerItem
key={qid}
group={groupIndex}
qid={qid}
question={find(qid)}
onRemove={() => onRemove(groupIndex, qid)}
/>
))}
</SortableContext>
{group.length < MAX_BANNER_DEPTH ? (
<SubDrop group={groupIndex} />
) : null}
</li>
))}
<NewBannerDrop />
</ul>
</div>
);
}
export const bannerItemId = (group: number, qid: string) =>
"banner:" + group + ":" + qid;
function BannerItem({
group,
qid,
question,
onRemove,
}: {
group: number;
qid: string;
question?: Question;
onRemove: () => void;
}) {
const data: DragBannerItem = { kind: "banner-item", group, qid };
const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
useSortable({ id: bannerItemId(group, qid), data });
const view = question ? questionViewTitle(question) : qid;
return (
<Tooltip>
<TooltipTrigger asChild>
<div
ref={setNodeRef}
{...attributes}
{...listeners}
className="mb-[3px] flex h-9 shrink-0 items-center justify-center pr-2.5"
style={{
background:
question && isDerivedQuestion(question)
? VARIABLE_COLOR
: QUESTION_COLOR,
opacity: isDragging ? 0 : 1,
transform: CSS.Transform.toString(transform),
transition,
}}
>
<span className="relative block min-w-0 flex-1 overflow-hidden px-3 py-2 text-sm leading-5 text-ellipsis whitespace-nowrap text-kart-text">
{plainText(view)}
</span>
<button
type="button"
aria-label={plainText(view) + " 배너에서 삭제"}
// Keep the delete click from starting a drag.
onPointerDown={(event) => event.stopPropagation()}
onClick={onRemove}
className="shrink-0 cursor-pointer"
>
<Image
src="/images/kart/ic_close.png"
alt=""
width={12}
height={12}
unoptimized
/>
</button>
</div>
</TooltipTrigger>
<TooltipContent side="right" className="max-w-md opacity-65">
{plainText(view)}
</TooltipContent>
</Tooltip>
);
}
function SubDrop({ group }: { group: number }) {
const { setNodeRef, isOver } = useDroppable({ id: "banner-sub:" + group });
const canDrop = useBannerDragActive();
return (
<div
ref={setNodeRef}
className="flex min-h-0 flex-1 flex-col items-center justify-center rounded-b-[15px] border-2 border-dashed bg-white"
style={{ borderColor: canDrop || isOver ? "#1cae81" : "#d0d0d0" }}
>
<Image
src="/images/kart/ic_drop.svg"
alt=""
width={16}
height={16}
className="size-4 grayscale"
unoptimized
/>
<p className="text-xs leading-[17px] font-bold text-[#989898]">
Drag&amp;Drop
</p>
</div>
);
}
function NewBannerDrop() {
const { setNodeRef, isOver } = useDroppable({ id: "banner-new" });
const canDrop = useBannerDragActive();
return (
<li className="h-[210px] min-w-[280px] flex-1">
<div
ref={setNodeRef}
className="flex h-full flex-col items-center justify-center rounded-[15px] border-2 border-dashed bg-white px-2.5"
style={{ borderColor: canDrop || isOver ? "#1cae81" : "#d0d0d0" }}
>
<Image
src="/images/kart/ic_drop.svg"
alt=""
width={48}
height={48}
unoptimized
/>
<p className="text-xs leading-[17px] font-bold text-[#989898]">
Banner List
</p>
<span className="text-sm leading-5 text-[#989898]">
Please, select a banner.
</span>
</div>
</li>
);
}

View File

@@ -0,0 +1,152 @@
"use client";
import Image from "next/image";
import { useState } from "react";
import { apiError } from "@kri/common/http";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
} from "@/components/ui/dialog";
import type { ReportBookmarks } from "@/hooks/useReportBookmarks";
import { LegacyCheck } from "./ReportParts";
/**
* Legacy BookmarkArea popup: Title, "Just for me", Information, then Save / Save as / Delete.
* Save updates the selected bookmark (creates one on "New"); Save as always creates.
*/
export function BookmarkPopup({
state,
buildJson,
onSaved,
onDeleted,
}: {
state: ReportBookmarks;
/** Current page conditions in the legacy BOOKMARK_JSON format. */
buildJson: () => string;
onSaved: () => void;
onDeleted: () => void;
}) {
const current = state.current;
const [title, setTitle] = useState(current?.bookmarkTitle ?? "");
const [info, setInfo] = useState(current?.bookmarkInfo ?? "");
// Legacy: unchecked only when IS_OPEN is 1 ("New" starts open).
const [justForMe, setJustForMe] = useState(current ? current.isOpen !== 1 : false);
const pending = state.save.isPending || state.remove.isPending;
const submit = async (asNew: boolean) => {
const request = {
bookmarkTitle: title,
bookmarkInfo: info,
bookmarkJson: buildJson(),
isOpen: justForMe ? (0 as const) : (1 as const),
};
try {
const bookmarkId = await state.save.mutateAsync({
bookmarkId: asNew || !current ? null : current.bookmarkId,
request,
});
state.select({ bookmarkId, ...request, isMine: true });
onSaved();
state.setPopupOpen(false);
} catch (error) {
window.alert(apiError(error, { fallbackMessage: "북마크를 저장하지 못했습니다." }).message);
}
};
const destroy = async () => {
if (!current || !window.confirm("정말 삭제 하시겠습니까?")) return;
try {
await state.remove.mutateAsync(current.bookmarkId);
onDeleted();
state.setPopupOpen(false);
} catch (error) {
window.alert(apiError(error, { fallbackMessage: "북마크를 삭제하지 못했습니다." }).message);
}
};
const buttonClass =
"my-2.5 inline-block h-[30px] w-[100px] cursor-pointer rounded-[4px] font-bold disabled:cursor-default";
return (
<Dialog open={state.popupOpen} onOpenChange={state.setPopupOpen}>
<DialogContent
showCloseButton={false}
className="h-[480px] w-[382px] max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-[10px] border-0 p-0 sm:max-w-[382px]"
>
<div className="relative flex h-[55px] items-center rounded-t-[10px] bg-kart-green p-2.5">
<Image src="/images/kart/ic_filter_pop.png" alt="" width={36} height={36} unoptimized />
<DialogTitle className="pl-2 text-base font-bold text-white">Bookmark</DialogTitle>
<DialogDescription className="sr-only">
현재 조건을 북마크로 저장하거나 삭제합니다.
</DialogDescription>
<DialogClose className="absolute top-5 right-5 cursor-pointer" aria-label="닫기">
<Image src="/images/kart/ic_close_w.png" alt="" width={18} height={18} unoptimized />
</DialogClose>
</div>
<div className="px-4">
<div className="mt-5">
<h3 className="mb-2.5 text-base font-bold text-kart-title">
<label htmlFor="bookmark_title">Title</label>
</h3>
<input
id="bookmark_title"
type="text"
value={title}
onChange={(event) => setTitle(event.target.value)}
className="mb-2.5 h-9 w-full rounded-[4px] border border-kart-line bg-white px-3.5 py-1 text-sm leading-[19px] font-light text-[#999] outline-none"
/>
<h3 className="mb-2.5 text-base font-bold text-kart-title">Information</h3>
<div className="mb-5">
<LegacyCheck
id="chk_bookmark"
label="Just for me"
checked={justForMe}
onChange={setJustForMe}
/>
</div>
<textarea
aria-label="Information"
cols={30}
rows={10}
value={info}
onChange={(event) => setInfo(event.target.value)}
// Fixed height: rows=10 grows with the line height and pushed the buttons out of the
// 480px legacy popup.
className="block h-[160px] w-full resize-none border border-kart-line p-1 text-sm text-justify text-black outline-[#17BBB0] [&::-webkit-scrollbar]:w-[6px] [&::-webkit-scrollbar-thumb]:rounded-[93px] [&::-webkit-scrollbar-thumb]:bg-[#9e9e9e] [&::-webkit-scrollbar-track]:bg-kart-line"
/>
<div className="text-center">
<button
type="button"
disabled={pending}
onClick={() => void submit(false)}
className={buttonClass + " bg-kart-green text-white"}
>
Save
</button>
{current ? (
<>
<button
type="button"
disabled={pending}
onClick={() => void submit(true)}
className={buttonClass + " ml-[5px] bg-kart-green text-white"}
>
Save as
</button>
<button
type="button"
disabled={pending}
onClick={() => void destroy()}
className={buttonClass + " ml-[5px] bg-kart-bg text-[#9e9e9e]"}
>
Delete
</button>
</>
) : null}
</div>
</div>
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,193 @@
"use client";
import Image from "next/image";
import { useEffect, useEffectEvent, useState } from "react";
import { useBookmarkListQuery } from "@/query/bookmark";
import { useCrosstabResults } from "@/query/report";
import type { ProjectRef } from "@/types/kart";
import type { Bookmark } from "@/types/bookmark";
import type { Question } from "@/types/report";
import { questionHead, questionViewTitle } from "@/lib/report-ui";
import { filterCondition } from "@/lib/legacy-filter";
import { bookmarkAxis, bookmarkTest, readBookmarkSetting } from "@/lib/bookmark-json";
import { cn } from "@/lib/utils";
import { bookmarkIndexes, crosstabBatch } from "./crosstab-conditions";
import { ResultBlock } from "./LegacyResultTable";
import { plainText } from "./ReportResultView";
/**
* Legacy Cross Tab on phones: saved bookmarks only (no "New"), the first one selected, shown
* read-only with its filter, banner and table lists and the re-run results.
*/
export function CrosstabPhone({
project,
questions,
}: {
project: ProjectRef;
questions: Question[];
}) {
const list = useBookmarkListQuery(project, "CROSSTAB");
const [selectedId, setSelectedId] = useState<string | null>(null);
const bookmarks = list.data ?? [];
const current =
bookmarks.find((bookmark) => bookmark.bookmarkId === selectedId) ?? bookmarks[0];
return (
<div className="min-h-[calc(100vh-146px)] bg-kart-bg">
<ul className="flex h-[60px] items-end gap-[30px] overflow-x-auto overflow-y-hidden bg-white px-4 [&::-webkit-scrollbar]:hidden">
{bookmarks.map((bookmark) => {
const active = bookmark.bookmarkId === current?.bookmarkId;
return (
<li key={bookmark.bookmarkId} className="shrink-0">
<button
type="button"
title={bookmark.bookmarkTitle}
aria-current={active ? "page" : undefined}
onClick={() => setSelectedId(bookmark.bookmarkId)}
className={cn(
"relative cursor-pointer pb-2 text-sm font-bold whitespace-nowrap",
active
? "text-kart-green after:absolute after:inset-x-0 after:bottom-0 after:h-1 after:bg-kart-green"
: "text-[#9e9e9e]",
)}
>
{bookmark.bookmarkTitle}
</button>
</li>
);
})}
</ul>
{current ? (
<PhoneBookmarkView
key={current.bookmarkId}
project={project}
bookmark={current}
questions={questions}
/>
) : (
<div className="w-full bg-white pt-10 text-center">
<Image
src="/images/kart/icon_none_bookmark.svg"
alt="저장된 북마크가 없습니다."
width={102}
height={140}
className="inline-block h-[70vh] w-auto"
unoptimized
/>
</div>
)}
</div>
);
}
function PhoneBookmarkView({
project,
bookmark,
questions,
}: {
project: ProjectRef;
bookmark: Bookmark;
questions: Question[];
}) {
const results = useCrosstabResults(project);
const setting = readBookmarkSetting(bookmark.bookmarkJson);
const indexes = bookmarkIndexes(setting.index, questions);
const run = () => {
if (!indexes.length) return;
try {
results.runAll(
crosstabBatch(indexes, {
banners: setting.banners,
filterLines: setting.filter.lines,
isTest: bookmarkTest(setting.option),
isAxis: bookmarkAxis(setting.option),
}),
);
} catch (error) {
window.alert(error instanceof Error ? error.message : "북마크 조건을 확인해 주세요.");
}
};
// Selecting a bookmark runs its tables, like the legacy effects.
const start = useEffectEvent(run);
useEffect(() => {
start();
}, []);
const find = (qid: string) => questions.find((question) => question.qid === qid);
const bannerIds = setting.banners
.flat()
.filter((qid, position, all) => all.indexOf(qid) === position);
return (
<div className="relative px-4 pt-6 pb-[100px]">
<button
type="button"
aria-label="다시 집계"
title="다시 집계"
onClick={run}
className="absolute top-2 right-4 size-9 cursor-pointer rounded-[4px] border border-kart-line bg-white bg-[url(/images/kart/ic_re.png)] bg-[length:18px_17px] bg-center bg-no-repeat"
/>
<section className="mb-2">
<h3 className="p-2 text-base font-bold text-kart-title">Filter</h3>
<input
type="text"
readOnly
aria-label="Filter"
value={setting.filter.condition || filterCondition(setting.filter.lines)}
className="w-full rounded-[4px] bg-white p-2 text-sm font-light text-kart-text outline-none"
/>
</section>
<PhoneList title="banner" questions={bannerIds.flatMap((qid) => find(qid) ?? [])} />
<PhoneList title="index" questions={indexes.flatMap((qid) => find(qid) ?? [])} />
<div className="mt-2 bg-white">
{indexes.map((qid) => {
const slot = results.slots[qid];
const question = find(qid);
return (
<ResultBlock
key={qid}
title={question ? questionHead(question) : qid}
result={slot?.result}
error={slot?.error}
pending={!!slot && !slot.result && !slot.error}
/>
);
})}
</div>
</div>
);
}
/** Legacy MobileBox: question titles that expand to the full question text. */
function PhoneList({ title, questions }: { title: string; questions: Question[] }) {
return (
<section className="mb-2">
<h3 className="p-2 text-base font-bold text-kart-title">{title}</h3>
{questions.map((question) => (
<PhoneListItem key={question.qid} question={question} />
))}
</section>
);
}
function PhoneListItem({ question }: { question: Question }) {
const [open, setOpen] = useState(false);
return (
<div className="mb-1.5 bg-white p-2 text-sm text-kart-text">
<button
type="button"
aria-expanded={open}
onClick={() => setOpen(!open)}
className="relative block w-full cursor-pointer pr-6 text-left font-bold"
>
{plainText(questionViewTitle(question))}
<Image
src={open ? "/images/kart/acc_arrow_close_s.png" : "/images/kart/acc_arrow_open_s.png"}
alt=""
width={17}
height={open ? 10 : 12}
className="absolute top-1 right-0"
unoptimized
/>
</button>
{open ? <p className="mt-1">{plainText(question.title ?? "")}</p> : null}
</div>
);
}

View File

@@ -0,0 +1,322 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import type { DragEndEvent } from "@dnd-kit/core";
import { arrayMove } from "@dnd-kit/sortable";
import { QueryState } from "@/components/project/QueryState";
import { useAuth } from "@/hooks/useAuth";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { usePhoneView } from "@/hooks/usePhoneView";
import { useReportBookmarks } from "@/hooks/useReportBookmarks";
import { useVisitLog } from "@/hooks/useVisitLog";
import { apiError } from "@kri/common/http";
import { useFileDownload } from "@/query/export";
import { EXPORT_PREFIX } from "@/lib/download-name";
import { useProjectTitle } from "@/query/project";
import { useCrosstabResults, useQuestionQuery } from "@/query/report";
import { projectKey, type ProjectRef } from "@/types/kart";
import type { Bookmark } from "@/types/bookmark";
import { canIndex } from "@/lib/report-contract";
import { isDerivedQuestion, questionHead } from "@/lib/report-ui";
import { filterCondition } from "@/lib/legacy-filter";
import {
bookmarkAxis,
bookmarkFilter,
bookmarkTest,
emptyBookmarkFilter,
emptyBookmarkSetting,
readBookmarkSetting,
writeBookmarkJson,
} from "@/lib/bookmark-json";
import { BannerBox, dropOnBanner, removeBanner } from "./BannerBox";
import { BookmarkPopup } from "./BookmarkPopup";
import { CrosstabPhone } from "./CrosstabPhone";
import { excelTables } from "./excel-tables";
import { bookmarkIndexes, crosstabBatch, type Conditions } from "./crosstab-conditions";
import { IndexBox } from "./IndexBox";
import { ReportTabs } from "./ReportChrome";
import { ReportFrame } from "./ReportFrame";
import { FilterStatBox, ResetButton, SquareButton, StatBox } from "./ReportParts";
import { ResultBlock } from "./LegacyResultTable";
import { QuestionList, readDragData } from "./QuestionList";
import { FilterPopup } from "./FilterPopup";
export function CrosstabWorkspace() {
const router = useRouter();
const { auth } = useAuth();
const { project, hydrated } = useSelectedProject();
const missing = hydrated && !project;
useEffect(() => {
if (missing) router.replace("/");
}, [missing, router]);
if (!project) return null;
return (
<Workspace
key={JSON.stringify([
projectKey(project),
auth.user?.userId,
auth.user?.userRole,
auth.user?.userTeam,
])}
project={project}
/>
);
}
/**
* Legacy Crosstab.js: questions dropped on Table are aggregated one by one; changing banner,
* filter or options re-runs every table.
*/
function Workspace({ project }: { project: ProjectRef }) {
const questions = useQuestionQuery(project);
const results = useCrosstabResults(project);
const [indexes, setIndexes] = useState<string[]>([]);
const [conditions, setConditions] = useState<Conditions>({
banners: [],
filterLines: [],
isTest: false,
isAxis: false,
});
const [filterOpen, setFilterOpen] = useState(false);
const bookmarks = useReportBookmarks(project, "CROSSTAB");
const download = useFileDownload();
const projectTitle = useProjectTitle(project);
// Stored filter strings and OPTION of the applied bookmark, kept verbatim when unchanged.
const [loadedFilter, setLoadedFilter] = useState(emptyBookmarkFilter);
const [option, setOption] = useState<Record<string, unknown>>({});
const phone = usePhoneView();
useVisitLog("/Report/Crosstab", project);
const all = (questions.data ?? []).filter(canIndex);
const find = (qid: string) =>
(questions.data ?? []).find((question) => question.qid === qid);
const done =
indexes.length > 0 &&
indexes.every((qid) => results.slots[qid]?.result || results.slots[qid]?.error);
// Legacy selectedBookMark effect: replace every condition, then re-run every table.
const applyBookmark = (bookmark: Bookmark | null) => {
const setting = bookmark ? readBookmarkSetting(bookmark.bookmarkJson) : emptyBookmarkSetting;
const ids = bookmarkIndexes(setting.index, questions.data ?? []);
const next: Conditions = {
banners: setting.banners,
filterLines: setting.filter.lines,
isTest: bookmarkTest(setting.option),
isAxis: bookmarkAxis(setting.option),
};
bookmarks.select(bookmark);
setIndexes(ids);
setConditions(next);
setLoadedFilter(setting.filter);
setOption(setting.option);
results.reset();
if (!ids.length) return;
try {
results.runAll(crosstabBatch(ids, next));
} catch (error) {
window.alert(error instanceof Error ? error.message : "북마크 조건을 확인해 주세요.");
}
};
const currentFilter = () => bookmarkFilter(conditions.filterLines, loadedFilter);
// Legacy ExportTable: every received table in Table order, word clouds with their picture.
const exportTable = () => {
const tables = excelTables(
indexes.map((qid) => ({ index: qid, result: results.slots[qid]?.result })),
find,
);
if (!tables.length) return;
download.mutate(
{
kind: "table",
project,
request: { tables, turn: conditions.isAxis },
name: { prefix: EXPORT_PREFIX.table, title: projectTitle },
},
{
onError: (error) =>
window.alert(apiError(error, { fallbackMessage: "Excel 파일을 만들지 못했습니다." }).message),
},
);
};
const runAll = (next: Conditions = conditions) => {
if (indexes.length) results.runAll(crosstabBatch(indexes, next));
};
const change = (patch: Partial<Conditions>) => {
const next = { ...conditions, ...patch };
setConditions(next);
runAll(next);
};
const onDragEnd = (event: DragEndEvent) => {
const data = readDragData(event.active.data.current);
if (!data) return;
const overId = event.over ? String(event.over.id) : "";
const overData = readDragData(event.over?.data.current);
if (data.kind === "question" && overId === "index-drop") {
if (indexes.includes(data.qid)) return;
setIndexes([...indexes, data.qid]);
results.runOne(crosstabBatch([data.qid], conditions));
return;
}
if (data.kind === "index-item") {
if (overData?.kind === "index-item")
setIndexes(arrayMove(indexes, indexes.indexOf(data.qid), indexes.indexOf(overData.qid)));
return;
}
const banners = dropOnBanner(conditions.banners, data, overId, overData);
if (banners) change({ banners });
};
if (questions.isPending || questions.isError)
return (
<QueryState
pending={questions.isPending}
error={questions.error}
onRetry={() => void questions.refetch()}
/>
);
return (
<>
<ReportFrame
label="Cross Tab"
tabs={
<ReportTabs
bookmarks={bookmarks.bookmarks}
selectedId={bookmarks.current?.bookmarkId ?? null}
onSelect={applyBookmark}
canSave={bookmarks.canSave}
onBookmark={() => bookmarks.setPopupOpen(true)}
onRefresh={() => runAll()}
/>
}
isTest={conditions.isTest}
onTestChange={(isTest) => change({ isTest })}
isAxis={conditions.isAxis}
onAxisChange={(isAxis) => change({ isAxis })}
findQuestion={find}
onDragEnd={onDragEnd}
phone={
// Legacy phones show saved bookmarks read-only; mounted only on phones so the hidden
// view never requests tables on a desktop.
phone ? <CrosstabPhone project={project} questions={questions.data ?? []} /> : null
}
lists={
<>
<QuestionList
title="Question List"
variant="question"
questions={all.filter((question) => !isDerivedQuestion(question))}
/>
<QuestionList
title="Variable List"
variant="variable"
questions={all.filter(isDerivedQuestion)}
/>
</>
}
>
{(collapsed) => (
<>
{collapsed ? null : (
<>
<FilterStatBox
condition={filterCondition(conditions.filterLines)}
onAdd={() => setFilterOpen(true)}
onReset={() => change({ filterLines: [] })}
/>
<div className="mb-4 text-center">
<SquareButton done={done} disabled={download.isPending} onClick={exportTable}>
Export Table
</SquareButton>
</div>
<StatBox
icon="document"
title="Banner"
action={
<ResetButton label="배너 초기화" onClick={() => change({ banners: [] })} />
}
>
<BannerBox
banners={conditions.banners}
questions={questions.data ?? []}
onRemove={(group, qid) =>
change({ banners: removeBanner(conditions.banners, group, qid) })
}
/>
</StatBox>
</>
)}
<div className="flex items-start gap-5">
{collapsed ? null : (
<StatBox
icon="document"
title="Table"
className="w-[20%] shrink-0"
action={
<ResetButton
label="표 초기화"
onClick={() => {
setIndexes([]);
results.reset();
}}
/>
}
>
<IndexBox
indexes={indexes}
questions={questions.data ?? []}
onRemove={(qid) => {
setIndexes(indexes.filter((id) => id !== qid));
results.remove(qid);
}}
/>
</StatBox>
)}
<div className={collapsed ? "w-full" : "w-[79%] min-w-0"}>
{indexes.map((qid) => {
const slot = results.slots[qid];
const question = find(qid);
return (
<ResultBlock
key={qid}
title={question ? questionHead(question) : qid}
result={slot?.result}
error={slot?.error}
pending={!!slot && !slot.result && !slot.error}
/>
);
})}
</div>
</div>
</>
)}
</ReportFrame>
{filterOpen ? (
<FilterPopup
open
initial={conditions.filterLines}
questions={questions.data ?? []}
onOpenChange={setFilterOpen}
onSave={(filterLines) => change({ filterLines })}
/>
) : null}
{bookmarks.popupOpen ? (
<BookmarkPopup
state={bookmarks}
buildJson={() =>
writeBookmarkJson({
index: indexes,
banners: conditions.banners,
filter: currentFilter(),
option,
isTest: conditions.isTest,
isAxis: conditions.isAxis,
})
}
onSaved={() => setLoadedFilter(currentFilter())}
onDeleted={() => applyBookmark(null)}
/>
) : null}
</>
);
}

View File

@@ -0,0 +1,357 @@
"use client";
import Image from "next/image";
import { useState } from "react";
import type { Question } from "@/types/report";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
} from "@/components/ui/dialog";
import { KriSelect } from "@/components/common/KriSelect";
import {
KriMultiSelect,
KriSingleSelect,
} from "@/components/common/KriAutoComplete";
import { choices } from "@/lib/report-contract";
import { questionViewTitle } from "@/lib/report-ui";
import {
FILTER_OPERATORS,
filterCondition,
newFilterLine,
toServerFilter,
type AndOr,
type LegacyFilterLine,
} from "@/lib/legacy-filter";
import { cn } from "@/lib/utils";
import { plainText } from "./ReportResultView";
type Update = (id: string, fn: (line: LegacyFilterLine) => LegacyFilterLine | null) => void;
/** Applies `fn` to the line with `id` anywhere in the tree; returning null removes it. */
function updateTree(
list: LegacyFilterLine[],
id: string,
fn: (line: LegacyFilterLine) => LegacyFilterLine | null,
): LegacyFilterLine[] {
return list.flatMap((line) => {
if (line.id === id) {
const next = fn(line);
return next ? [next] : [];
}
return [{ ...line, childList: updateTree(line.childList, id, fn) }];
});
}
/** Legacy FilterPopup: nested AND/OR condition lines with the "Selected Filter" preview. */
export function FilterPopup({
open,
initial,
questions,
onOpenChange,
onSave,
}: {
open: boolean;
initial: LegacyFilterLine[];
questions: Question[];
onOpenChange: (open: boolean) => void;
onSave: (lines: LegacyFilterLine[]) => void;
}) {
const [lines, setLines] = useState(initial);
const update: Update = (id, fn) => setLines((current) => updateTree(current, id, fn));
const options = questions.filter(
(question) => question.qtype !== "text" && question.isDerived !== "2",
);
const save = () => {
try {
toServerFilter(lines);
} catch (error) {
window.alert(error instanceof Error ? error.message : "필터를 확인해 주세요.");
return;
}
onSave(lines);
onOpenChange(false);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
showCloseButton={false}
className="w-[1200px] max-w-[calc(100vw-2rem)] gap-0 overflow-hidden rounded-[15px] border-0 p-0 sm:max-w-[1200px]"
>
<div className="flex h-[55px] items-center gap-2 bg-kart-green px-5">
{/* Legacy reuses the green filter tile; on the green header only the white glyph shows. */}
<Image src="/images/kart/ic_filter_36.png" alt="" width={36} height={36} className="h-[33px] w-9" unoptimized />
<DialogTitle className="text-base leading-[20.5px] font-bold text-white">
Filter
</DialogTitle>
<DialogDescription className="sr-only">
필터 조건을 만들고 Save로 적용합니다.
</DialogDescription>
<DialogClose className="ml-auto cursor-pointer" aria-label="닫기">
<Image src="/images/kart/ic_close_w.png" alt="" width={18} height={18} unoptimized />
</DialogClose>
</div>
<div className="p-4">
<div className="h-[550px] overflow-y-auto">
{lines.length === 0 ? (
<div className="pt-2.5 pl-1.5">
<PlusButton onClick={() => setLines([newFilterLine("fil_0")])} />
</div>
) : (
<FilterList
lines={lines}
parentId=""
questions={options}
update={update}
setRoot={setLines}
/>
)}
</div>
<h3 className="text-base leading-[20.5px] font-bold text-kart-text">
Selected Filter
</h3>
<input
type="text"
readOnly
aria-label="선택한 필터"
value={filterCondition(lines)}
className="mt-1 h-9 w-full rounded-[4px] border border-kart-line bg-kart-bg px-3.5 text-sm font-light text-kart-text outline-none"
/>
<div className="mt-2.5 text-center">
<button
type="button"
onClick={save}
className="h-[50px] w-[156px] cursor-pointer rounded-[4px] bg-kart-green text-base font-bold text-white"
>
Save
</button>
</div>
</div>
</DialogContent>
</Dialog>
);
}
function FilterList({
lines,
parentId,
questions,
update,
setRoot,
}: {
lines: LegacyFilterLine[];
parentId: string;
questions: Question[];
update: Update;
setRoot: (fn: (lines: LegacyFilterLine[]) => LegacyFilterLine[]) => void;
}) {
// Legacy ids: siblings share the parent prefix ("fil_" / "fil_0_") plus their index.
const addSibling = () => {
const prefix = parentId ? parentId + "_" : "fil_";
const append = (list: LegacyFilterLine[]) => [
...list,
newFilterLine(prefix + list.length, "AND"),
];
if (!parentId) setRoot(append);
else update(parentId, (line) => ({ ...line, childList: append(line.childList) }));
};
return (
<ul className="border-l-2 border-kart-line pl-2.5">
{lines.map((line, index) => (
<li key={line.id} className="py-1">
{index > 0 ? (
<AndOrToggle
value={line.preAndOr}
onChange={(value) => update(line.id, (item) => ({ ...item, preAndOr: value }))}
/>
) : null}
<FilterLineRow line={line} questions={questions} update={update} />
{line.childList.length > 0 ? (
<>
<AndOrToggle
value={line.postAndOr}
onChange={(value) => update(line.id, (item) => ({ ...item, postAndOr: value }))}
/>
<div className="ml-5">
<FilterList
lines={line.childList}
parentId={line.id}
questions={questions}
update={update}
setRoot={setRoot}
/>
</div>
</>
) : null}
{index === lines.length - 1 ? (
<div className="mt-1.5 flex gap-1">
<PlusButton onClick={addSibling} />
{line.childList.length === 0 ? (
<button
type="button"
aria-label="하위 조건 추가"
className="cursor-pointer"
onClick={() =>
update(line.id, (item) => ({
...item,
postAndOr: "AND",
childList: [newFilterLine(item.id + "_0")],
}))
}
>
<Image src="/images/kart/ic_return.png" alt="" width={22} height={22} unoptimized />
</button>
) : null}
</div>
) : null}
</li>
))}
</ul>
);
}
function FilterLineRow({
line,
questions,
update,
}: {
line: LegacyFilterLine;
questions: Question[];
update: Update;
}) {
const question = questions.find((item) => item.qid === line.qid);
const numeric = question?.qtype === "num";
const multi = line.op.includes("IN");
const values = line.value ? line.value.split(",") : [];
const valueOptions = question
? choices(question).map((option) => ({
value: option.value,
label: plainText(option.label),
}))
: [];
return (
<div className="flex items-center gap-3">
<KriSingleSelect
items={questions}
value={line.qid}
getValue={(item) => item.qid}
getLabel={(item) => plainText(questionViewTitle(item))}
placeholder="문항 선택"
widthClassName="w-[300px]"
className="h-[38px] min-h-[38px] rounded-[4px] border-[#d0d0d0] text-sm"
spanClassName="text-sm"
searchable
preventDeselect
hideOptionCheck
onChange={(qid) => {
const selected = questions.find((item) => item.qid === qid);
if (!selected) return;
update(line.id, (item) => ({
...item,
qid,
vname: selected.variable ?? selected.qid,
op: "IN",
value: "",
}));
}}
/>
<KriSelect
items={FILTER_OPERATORS}
value={line.op}
useAll={false}
getValue={(item) => item.value}
getLabel={(item) => item.label}
className="h-[38px] w-[150px] rounded-[4px] border-[#d0d0d0] text-sm"
onChange={(value) => {
const op = FILTER_OPERATORS.find((item) => item.value === value)?.value;
if (!op) return;
update(line.id, (item) => ({
...item,
op,
// Legacy: NULL checks drop values; single comparisons keep the first code.
value: op.includes("NULL") ? "" : op.includes("IN") ? item.value : item.value.split(",")[0],
}));
}}
/>
{line.op.includes("NULL") ? null : numeric ? (
<input
type="text"
value={line.value}
placeholder="숫자, ','만 가능"
aria-label="비교 값"
className="h-[38px] w-[150px] rounded-[4px] border border-[#d0d0d0] px-3.5 text-sm text-kart-text outline-none"
onChange={(event) => {
const value = event.target.value.replace(/[^0-9.,]/g, "").replace(/(\.*)\./g, "$1");
update(line.id, (item) => ({ ...item, value }));
}}
/>
) : (
<KriMultiSelect
// Remount when the question or operator changes so stale picks are dropped.
key={line.qid + ":" + (multi ? "multi" : "single")}
items={valueOptions}
value={values}
getValue={(item) => item.value}
getLabel={(item) => item.label}
placeholder="값 선택"
widthClassName="w-[250px]"
className="h-[38px] min-h-[38px] rounded-[4px] border-[#d0d0d0] text-sm"
spanClassName="text-sm"
badgeClassName="text-xs"
maxSelected={multi ? undefined : 1}
hideSelectAll={!multi}
onChange={(next) => {
// Legacy keeps codes sorted and comma-joined.
const value = [...next].sort().join(",");
update(line.id, (item) => ({ ...item, value }));
}}
/>
)}
<button
type="button"
aria-label="조건 삭제"
className="cursor-pointer"
onClick={() => update(line.id, () => null)}
>
<Image src="/images/kart/ic_minus.png" alt="" width={22} height={22} unoptimized />
</button>
</div>
);
}
function AndOrToggle({
value,
onChange,
}: {
value: AndOr;
onChange: (value: AndOr) => void;
}) {
return (
<div className="my-1.5 inline-flex overflow-hidden rounded-full border border-kart-line text-xs font-bold">
{(["AND", "OR"] as const).map((option) => (
<button
key={option}
type="button"
aria-pressed={value === option}
onClick={() => onChange(option)}
className={cn(
"cursor-pointer px-3 py-1",
value === option ? "bg-kart-green text-white" : "bg-white text-[#9e9e9e]",
)}
>
{option}
</button>
))}
</div>
);
}
function PlusButton({ onClick }: { onClick: () => void }) {
return (
<button type="button" aria-label="조건 추가" className="cursor-pointer" onClick={onClick}>
<Image src="/images/kart/ic_plus_filter.png" alt="" width={22} height={22} unoptimized />
</button>
);
}

View File

@@ -0,0 +1,119 @@
"use client";
import Image from "next/image";
import { useDndContext, useDroppable } from "@dnd-kit/core";
import {
SortableContext,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import type { Question } from "@/types/report";
import { isDerivedQuestion, questionViewTitle } from "@/lib/report-ui";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { plainText } from "./ReportResultView";
import {
QUESTION_COLOR,
VARIABLE_COLOR,
readDragData,
type DragIndexItem,
} from "./QuestionList";
export const indexItemId = (qid: string) => "index:" + qid;
/** Legacy Cross Tab IndexBox: ordered tables plus the "Drag&Drop" area accepting any question. */
export function IndexBox({
indexes,
questions,
onRemove,
}: {
indexes: string[];
questions: Question[];
onRemove: (qid: string) => void;
}) {
return (
<div className="p-4">
<SortableContext items={indexes.map(indexItemId)} strategy={verticalListSortingStrategy}>
{indexes.map((qid) => (
<IndexItem
key={qid}
qid={qid}
question={questions.find((item) => item.qid === qid)}
onRemove={() => onRemove(qid)}
/>
))}
</SortableContext>
<IndexDrop />
</div>
);
}
function IndexItem({
qid,
question,
onRemove,
}: {
qid: string;
question?: Question;
onRemove: () => void;
}) {
const data: DragIndexItem = { kind: "index-item", qid };
const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
useSortable({ id: indexItemId(qid), data });
const view = question ? questionViewTitle(question) : qid;
return (
<Tooltip>
<TooltipTrigger asChild>
<div
ref={setNodeRef}
{...attributes}
{...listeners}
className="mt-[3px] flex h-9 cursor-pointer items-center justify-center pr-2.5"
style={{
background:
question && isDerivedQuestion(question) ? VARIABLE_COLOR : QUESTION_COLOR,
opacity: isDragging ? 0 : 1,
transform: CSS.Transform.toString(transform),
transition,
}}
>
<span className="block min-w-0 flex-1 overflow-hidden px-3 py-2 text-sm leading-5 text-ellipsis whitespace-nowrap text-kart-text">
{plainText(view)}
</span>
<button
type="button"
aria-label={plainText(view) + " 표에서 삭제"}
onPointerDown={(event) => event.stopPropagation()}
onClick={onRemove}
className="shrink-0 cursor-pointer"
>
<Image src="/images/kart/ic_close.png" alt="" width={12} height={12} unoptimized />
</button>
</div>
</TooltipTrigger>
<TooltipContent side="right" className="max-w-md opacity-65">
{plainText(view)}
</TooltipContent>
</Tooltip>
);
}
function IndexDrop() {
const { setNodeRef, isOver } = useDroppable({ id: "index-drop" });
const { active } = useDndContext();
const canDrop = readDragData(active?.data.current)?.kind === "question";
return (
<div
ref={setNodeRef}
className="mt-[3px] flex h-14 flex-col items-center justify-center rounded-[15px] border-2 border-dashed bg-white py-1.5"
style={{ borderColor: canDrop || isOver ? "#1cae81" : "#d0d0d0" }}
>
<Image src="/images/kart/ic_drop.svg" alt="" width={16} height={16} className="size-4 grayscale" unoptimized />
<p className="text-xs leading-[17px] text-[#989898]">Drag&amp;Drop</p>
</div>
);
}

View File

@@ -0,0 +1,129 @@
"use client";
import type { ReportResult, ReportRow } from "@/types/report";
import { isTransposed, legacyCellText } from "@/lib/report-ui";
import { HtmlText, plainText } from "./ReportResultView";
import { TableLoading } from "./ReportParts";
import { WordCloud } from "./WordCloud";
/** Legacy Table.js ResultTable look: grey header grid, bold first column, centred values. */
export function LegacyResultTable({ result }: { result: ReportResult }) {
if (!result.headerRows.length && !result.rows.length)
return <ResultMessage message="Data가 없습니다." />;
return (
<div className="min-w-[320px] overflow-x-auto">
<table className="w-full border-collapse bg-kart-soft text-sm leading-5 whitespace-break-spaces text-kart-text">
<caption className="sr-only">
{plainText(result.title ?? result.questionId)}
</caption>
<thead>
{result.headerRows.map((row, index) => (
<Row key={row.rowIndex} row={row} result={result} header firstRow={index === 0} />
))}
</thead>
<tbody className="border-b border-kart-line">
{result.rows.map((row) => (
<Row key={row.rowIndex} row={row} result={result} />
))}
</tbody>
</table>
</div>
);
}
function Row({
row,
result,
header = false,
firstRow = false,
}: {
row: ReportRow;
result: ReportResult;
header?: boolean;
firstRow?: boolean;
}) {
const transposed = isTransposed(result);
return (
<tr className="border border-b-0 border-kart-line">
{row.cells.map((cell) => {
const th = header || cell.columnIndex === 0;
const Tag = th ? "th" : "td";
return (
<Tag
key={cell.columnIndex}
rowSpan={cell.rowSpan}
colSpan={cell.colSpan}
className={
th
? "max-w-[300px] border border-kart-line p-3.5 text-center font-bold" +
(firstRow && cell.columnIndex === 0
? " w-[300px] min-w-[300px]"
: "")
: "max-w-[300px] border-r border-kart-line bg-white p-3.5 text-center font-normal"
}
>
{cell.kind === "TEXT" ? (
<HtmlText text={cell.textValue} />
) : (
legacyCellText(
cell,
row.kind,
result.columns[cell.columnIndex]?.kind,
transposed,
)
)}
</Tag>
);
})}
</tr>
);
}
/** One legacy result: heading (EXPLAIN) then the table, word cloud, loading gif or message. */
export function ResultBlock({
title,
result,
error,
pending,
}: {
title: string;
result?: ReportResult;
error?: string;
pending: boolean;
}) {
return (
<div>
<h3 className="py-5 text-base leading-[20.5px] font-bold text-kart-title">
<HtmlText text={title} />
</h3>
{result ? (
result.type === "TEXT_ANALYSIS" ? (
<WordCloud result={result} />
) : (
<LegacyResultTable result={result} />
)
) : error ? (
<ResultMessage message={error} />
) : pending ? (
<TableLoading />
) : null}
</div>
);
}
/** Legacy non-array body: a single bordered message row. */
export function ResultMessage({ message }: { message: string }) {
return (
<div className="min-w-[320px] overflow-x-auto">
<table className="w-full bg-kart-soft text-sm text-kart-text">
<thead>
<tr className="border border-kart-line">
<td className="bg-white p-3.5 text-center" role="alert">
{message}
</td>
</tr>
</thead>
</table>
</div>
);
}

View File

@@ -0,0 +1,187 @@
"use client";
import Image from "next/image";
import { useState } from "react";
import { useDraggable } from "@dnd-kit/core";
import type { Question } from "@/types/report";
import { cn } from "@/lib/utils";
import { dragLocation, questionViewTitle } from "@/lib/report-ui";
import { isRecord } from "@/types/kart";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { plainText } from "./ReportResultView";
export type DragQuestion = { kind: "question"; qid: string; loc: "row" | "all" };
export type DragBannerItem = { kind: "banner-item"; group: number; qid: string };
export type DragIndexItem = { kind: "index-item"; qid: string };
export type DragData = DragQuestion | DragBannerItem | DragIndexItem;
/** Narrows dnd-kit's untyped `data.current` to the payloads this page attaches. */
export function readDragData(data: unknown): DragData | null {
if (!isRecord(data)) return null;
if (
data.kind === "question" &&
typeof data.qid === "string" &&
(data.loc === "row" || data.loc === "all")
)
return { kind: "question", qid: data.qid, loc: data.loc };
if (
data.kind === "banner-item" &&
typeof data.qid === "string" &&
typeof data.group === "number"
)
return { kind: "banner-item", qid: data.qid, group: data.group };
if (data.kind === "index-item" && typeof data.qid === "string")
return { kind: "index-item", qid: data.qid };
return null;
}
// Legacy item colours: survey questions vs derived variables.
export const QUESTION_COLOR = "#B7E8E3";
export const VARIABLE_COLOR = "#DAECAF";
/** Legacy QuestionBox / VariableBox: collapsible list whose items are drag sources. */
export function QuestionList({
title,
variant,
questions,
selected,
onToggle,
onSelectAll,
}: {
title: string;
variant: "question" | "variable";
questions: Question[];
/** Tabulation: click-to-select ids. Undefined in Cross Tab, where every item is coloured. */
selected?: string[];
onToggle?: (qid: string) => void;
onSelectAll?: (all: boolean) => void;
}) {
const [open, setOpen] = useState(true);
if (!questions.length) return null;
const allSelected =
!!selected && questions.every((question) => selected.includes(question.qid));
return (
<div className="mb-5 rounded-[15px] bg-white shadow-[1px_0_0_0_#e1e1e1,0_1px_0_0_#e1e1e1,1px_1px_0_0_#e1e1e1,inset_1px_0_0_0_#e1e1e1,inset_0_1px_0_0_#e1e1e1]">
<button
type="button"
aria-expanded={open}
onClick={() => setOpen(!open)}
className="relative mb-2 flex h-[55px] w-full cursor-pointer items-center gap-2 rounded-[15px] bg-kart-soft p-2.5 shadow-[1px_0_0_0_#e1e1e1,0_1px_0_0_#e1e1e1,1px_1px_0_0_#e1e1e1,inset_1px_0_0_0_#e1e1e1,inset_0_1px_0_0_#e1e1e1]"
>
<Image
src="/images/kart/icon_circle.svg"
alt=""
width={36}
height={36}
className="size-9"
unoptimized
/>
<h3 className="text-base leading-[20.5px] font-bold text-kart-title">
{title}
</h3>
<Image
src={
open
? "/images/kart/acc_arrow_open.png"
: "/images/kart/acc_arrow_close.png"
}
alt=""
width={24}
height={14}
className="absolute right-5"
unoptimized
/>
</button>
<div
className={cn(
"grid transition-[grid-template-rows] duration-500",
open ? "grid-rows-[1fr]" : "grid-rows-[0fr]",
)}
>
<div className="overflow-hidden">
{onSelectAll ? (
<div className="flex h-5 justify-end pr-2.5">
<button
type="button"
onClick={() => onSelectAll(!allSelected)}
className={cn(
"ml-2 cursor-pointer text-xs leading-5 font-bold",
allSelected ? "text-kart-green" : "text-[#9e9e9e]",
)}
>
Select All
</button>
</div>
) : null}
<ul className="max-h-[650px] overflow-y-scroll px-4 pb-2 [&::-webkit-scrollbar]:w-[6px][&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-[#9e9e9e] [&::-webkit-scrollbar-track]:bg-kart-line">
{questions.map((question) => (
<QuestionItem
key={question.qid}
question={question}
color={
!selected || selected.includes(question.qid)
? variant === "question"
? QUESTION_COLOR
: VARIABLE_COLOR
: undefined
}
onClick={onToggle ? () => onToggle(question.qid) : undefined}
/>
))}
</ul>
</div>
</div>
</div>
);
}
function QuestionItem({
question,
color,
onClick,
}: {
question: Question;
color?: string;
onClick?: () => void;
}) {
const view = questionViewTitle(question);
const data: DragQuestion = {
kind: "question",
qid: question.qid,
loc: dragLocation(question),
};
const { attributes, listeners, setNodeRef, isDragging } = useDraggable({
id: "question:" + question.qid,
data,
});
return (
<Tooltip>
<TooltipTrigger asChild>
<li
ref={setNodeRef}
{...attributes}
{...listeners}
onClick={onClick}
aria-current={onClick && color !== undefined ? "true" : undefined}
className="relative mt-2 cursor-pointer list-none overflow-hidden px-3 py-2 text-sm leading-5 whitespace-nowrap text-kart-text transition-all"
style={{
backgroundColor: color ?? "#f5f5f5",
opacity: isDragging ? 0.4 : 1,
}}
>
{/* Legacy list rows show the title as one plain line with an ellipsis. */}
<span className="inline-block w-full overflow-hidden text-ellipsis">
{plainText(view)}
</span>
</li>
</TooltipTrigger>
<TooltipContent side="right" className="max-w-md opacity-65">
{plainText(view)}
</TooltipContent>
</Tooltip>
);
}

View File

@@ -0,0 +1,62 @@
"use client";
import type { QuotaCell, QuotaResult } from "@/types/quota";
import { quotaCellStyle } from "@/lib/quota-ui";
import { HtmlText, plainText } from "./ReportResultView";
/** Legacy ResultTable with isQuota: complete (coloured) / target over an achievement gauge. */
export function QuotaTable({ result }: { result: QuotaResult }) {
return (
<div className="min-w-[320px] overflow-x-auto">
<table className="w-full border-collapse bg-kart-soft text-sm leading-5 whitespace-break-spaces text-kart-text">
<caption className="sr-only">{plainText(result.title ?? "")}</caption>
<thead>
{result.headerRows.map((row, index) => (
<tr key={row.rowIndex} className="border border-b-0 border-kart-line">
{row.cells.map((cell) => (
<th
key={cell.columnIndex}
rowSpan={cell.rowSpan}
colSpan={cell.colSpan}
className={
"border border-kart-line p-3.5 text-center font-bold" +
(index === 0 && cell.columnIndex === 0 ? " w-[200px] min-w-[200px]" : "")
}
>
<HtmlText text={cell.textValue} />
</th>
))}
</tr>
))}
</thead>
<tbody className="border-b border-kart-line">
{result.rows.map((row) => (
<tr key={row.rowIndex} className="border border-b-0 border-kart-line">
{row.cells.map((cell) =>
cell.kind === "QUOTA" ? (
<QuotaValue key={cell.columnIndex} cell={cell} />
) : (
<th key={cell.columnIndex} className="border border-kart-line p-3.5 text-center font-bold">
<HtmlText text={cell.textValue} />
</th>
),
)}
</tr>
))}
</tbody>
</table>
</div>
);
}
function QuotaValue({ cell }: { cell: QuotaCell }) {
const style = quotaCellStyle(cell);
return (
<td
className="border-r border-kart-line bg-white p-3.5 text-center font-normal"
style={style.background ? { background: style.background } : undefined}
>
<span style={{ color: style.color }}>{cell.complete ?? "-"}</span>/{cell.target ?? "-"}
</td>
);
}

View File

@@ -0,0 +1,163 @@
"use client";
import Image from "next/image";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { apiError } from "@kri/common/http";
import { QueryState } from "@/components/project/QueryState";
import { useAuth } from "@/hooks/useAuth";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { useVisitLog } from "@/hooks/useVisitLog";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useFileDownload } from "@/query/export";
import { EXPORT_PREFIX } from "@/lib/download-name";
import { useProjectTitle } from "@/query/project";
import { quotaResultQuery, useQuotaListQuery, useQuotaResultQuery } from "@/query/quota";
import { projectKey, type ProjectRef } from "@/types/kart";
import { quotaTooltip } from "@/types/quota";
import { quotaExcelBody, type ExcelTable } from "@/lib/report-excel";
import { cn } from "@/lib/utils";
import { LeftToggleBox } from "./ReportChrome";
import { LegacyCheck, TableLoading } from "./ReportParts";
import { ResultMessage } from "./LegacyResultTable";
import { plainText } from "./ReportResultView";
import { QuotaTable } from "./QuotaTable";
export function QuotaWorkspace() {
const router = useRouter();
const { auth } = useAuth();
const { project, hydrated } = useSelectedProject();
const missing = hydrated && !project;
useEffect(() => {
if (missing) router.replace("/");
}, [missing, router]);
if (!project) return null;
return (
<Workspace
key={JSON.stringify([
projectKey(project),
auth.user?.userId,
auth.user?.userRole,
auth.user?.userTeam,
])}
project={project}
/>
);
}
/** Legacy Quota.js: pick a saved quota setting (first one by default) and show complete/target. */
function Workspace({ project }: { project: ProjectRef }) {
const list = useQuotaListQuery(project);
const { auth } = useAuth();
const [chosen, setChosen] = useState<number | null>(null);
const [isTest, setIsTest] = useState(false);
const [collapsed, setCollapsed] = useState(false);
useVisitLog("/Report/Quota", project);
// Legacy selects the first quota once the list arrives.
const selected = chosen ?? list.data?.[0]?.qsOrder ?? null;
const result = useQuotaResultQuery(project, selected, isTest ? "TEST" : "ACTUAL");
const selectedSet = list.data?.find((set) => set.qsOrder === selected);
const queryClient = useQueryClient();
const download = useFileDownload();
const projectTitle = useProjectTitle(project);
// Legacy setExportQuota: every quota setting in list order, one sheet each.
const exportQuota = useMutation({
mutationFn: async () => {
const dataScope = isTest ? "TEST" : "ACTUAL";
const tables: ExcelTable[] = [];
for (const set of list.data ?? []) {
const quota = await queryClient.fetchQuery(
quotaResultQuery(auth.user, project, set.qsOrder, dataScope),
);
const body = quotaExcelBody(quota);
if (body) tables.push({ head: set.qsTitle ?? String(set.qsOrder), vname: "", qtype: "", body });
}
if (!tables.length) throw new Error("내보낼 쿼터 결과가 없습니다.");
await download.mutateAsync({
kind: "quota",
project,
request: { tables, turn: false },
name: { prefix: EXPORT_PREFIX.quota, title: projectTitle },
});
},
onError: (error) =>
window.alert(apiError(error, { fallbackMessage: "Excel 파일을 만들지 못했습니다." }).message),
});
return (
<section aria-label="Quota" className="-mt-2.5">
<div className="relative flex items-start justify-center gap-[1.041vw] py-5">
{collapsed ? (
<LeftToggleBox onExpand={() => setCollapsed(false)} />
) : (
<div className="min-h-[278px] w-[400px] shrink-0">
<div className="relative pr-5 pb-5">
<LegacyCheck id="chk_test" label="Use Test Data" checked={isTest} onChange={setIsTest} />
<button
type="button"
aria-label="조건 영역 접기"
onClick={() => setCollapsed(true)}
className="absolute -top-2 right-0 cursor-pointer"
>
<Image src="/images/kart/btn_left.png" alt="" width={36} height={36} unoptimized />
</button>
</div>
<div className="mb-5 rounded-[15px] bg-white shadow-[1px_0_0_0_#e1e1e1,0_1px_0_0_#e1e1e1,1px_1px_0_0_#e1e1e1,inset_1px_0_0_0_#e1e1e1,inset_0_1px_0_0_#e1e1e1]">
<div className="mb-2 flex h-[55px] items-center gap-2 rounded-[15px] bg-kart-soft p-2.5 shadow-[1px_0_0_0_#e1e1e1,0_1px_0_0_#e1e1e1,1px_1px_0_0_#e1e1e1,inset_1px_0_0_0_#e1e1e1,inset_0_1px_0_0_#e1e1e1]">
<Image src="/images/kart/icon_circle.svg" alt="" width={36} height={36} className="size-9" unoptimized />
<h3 className="text-base leading-[20.5px] font-bold text-kart-title">Quota List</h3>
<button
type="button"
disabled={exportQuota.isPending || !list.data?.length}
onClick={() => exportQuota.mutate()}
className="mr-2 ml-auto h-7 w-[113px] cursor-pointer rounded-[52px] bg-kart-green text-sm leading-[16px] font-bold text-white disabled:cursor-default"
>
Export Quota
</button>
</div>
{list.isError ? (
<div className="p-4">
<QueryState error={list.error} onRetry={() => void list.refetch()} />
</div>
) : (
<ul className="px-4 pb-2">
{(list.data ?? []).map((set) => (
<li key={set.qsOrder} title={quotaTooltip(set)} className="mt-2 list-none">
<button
type="button"
aria-current={set.qsOrder === selected ? "true" : undefined}
onClick={() => setChosen(set.qsOrder)}
className={cn(
"w-full cursor-pointer overflow-hidden px-3 py-2 text-left text-sm leading-5 text-ellipsis whitespace-nowrap transition-all",
set.qsOrder === selected
? "bg-kart-green text-white"
: "bg-kart-bg text-kart-text",
)}
>
{plainText(set.qsTitle ?? String(set.qsOrder))}
</button>
</li>
))}
</ul>
)}
</div>
</div>
)}
<div className={collapsed ? "ml-[75px] w-[calc(100%-100px)]" : "w-[calc(100%-400px)] min-w-0"}>
{selectedSet ? (
<h3 className="py-2.5 text-base leading-[20.5px] font-bold text-kart-title">
{plainText(selectedSet.qsTitle ?? "")}
</h3>
) : null}
{selected === null ? null : result.isError ? (
<ResultMessage message={apiError(result.error, { fallbackMessage: "쿼터 결과를 불러오지 못했습니다." }).message} />
) : result.data ? (
<QuotaTable result={result.data} />
) : (
<TableLoading />
)}
</div>
</div>
</section>
);
}

View File

@@ -0,0 +1,167 @@
"use client";
import Image from "next/image";
import { useEffect, useState } from "react";
import { Carousel, CarouselContent, CarouselItem, type CarouselApi } from "@/components/ui/carousel";
import { cn } from "@/lib/utils";
import type { Bookmark } from "@/types/bookmark";
/**
* Legacy tab_container (components/Bookmark.js): "New" plus the bookmark tabs in a slider that
* scrolls two tabs at a time, arrows when overflowing, and the bookmark / refresh side buttons.
*/
export function ReportTabs({
bookmarks,
selectedId,
onSelect,
canSave,
onBookmark,
onRefresh,
}: {
bookmarks: Bookmark[];
/** Null selects "New". */
selectedId: string | null;
onSelect: (bookmark: Bookmark | null) => void;
/** Legacy shows the bookmark button only on "New" and the user's own bookmarks. */
canSave: boolean;
onBookmark: () => void;
onRefresh: () => void;
}) {
const [api, setApi] = useState<CarouselApi>();
const [canScroll, setCanScroll] = useState({ prev: false, next: false });
useEffect(() => {
if (!api) return;
const update = () => {
setCanScroll({ prev: api.canScrollPrev(), next: api.canScrollNext() });
};
update();
api.on("select", update);
api.on("reInit", update);
return () => {
api.off("select", update);
api.off("reInit", update);
};
}, [api]);
const tabs = [
{ id: null, title: "New", bookmark: null },
...bookmarks.map((bookmark) => ({
id: bookmark.bookmarkId,
title: bookmark.bookmarkTitle,
bookmark,
})),
];
const arrows = canScroll.prev || canScroll.next;
return (
<div className="relative top-0.5 flex h-[67px] justify-between bg-kart-bg px-4 pt-[23px]">
{/* Bottom line drawn under the tabs so the active tab can cover it inside the slider. */}
<div aria-hidden className="absolute inset-x-0 bottom-0 h-0.5 bg-kart-line" />
<div className="relative w-[calc(100%-277px)] pr-[30px] pl-[38px]">
{arrows ? (
<TabArrow side="left" disabled={!canScroll.prev} onClick={() => api?.scrollPrev()} />
) : null}
<Carousel
setApi={setApi}
opts={{ align: "start", slidesToScroll: 2, containScroll: "trimSnaps" }}
>
<CarouselContent className="ml-0 gap-[0.416vw]">
{tabs.map((tab) => {
const active = tab.id === selectedId;
return (
<CarouselItem key={tab.id ?? ""} className="basis-auto pl-0">
<button
type="button"
title={tab.bookmark ? tab.title : undefined}
aria-current={active ? "page" : undefined}
onClick={() => onSelect(tab.bookmark)}
className={cn(
"block h-11 w-[175px] cursor-pointer overflow-hidden rounded-t-[15px] border-2 border-b-0 border-kart-line text-center text-sm leading-[42px] font-bold text-ellipsis whitespace-nowrap",
active ? "bg-white text-kart-green" : "bg-kart-line text-[#9e9e9e]",
)}
>
{tab.title}
</button>
</CarouselItem>
);
})}
</CarouselContent>
</Carousel>
{arrows ? (
<TabArrow side="right" disabled={!canScroll.next} onClick={() => api?.scrollNext()} />
) : null}
</div>
<div className="absolute top-4 right-[15px] flex items-center gap-2">
{canSave ? (
<button
type="button"
aria-label="북마크"
title="북마크"
onClick={onBookmark}
className="size-9 cursor-pointer rounded-[4px] border border-kart-line bg-white bg-[url(/images/kart/ic_bookmark_14.png)] bg-center bg-no-repeat"
/>
) : null}
<button
type="button"
aria-label="다시 집계"
title="다시 집계"
onClick={onRefresh}
className="size-9 cursor-pointer rounded-[4px] border border-kart-line bg-white bg-[url(/images/kart/ic_re.png)] bg-center bg-no-repeat"
/>
</div>
</div>
);
}
/** Legacy tab_arrows: 14x24 image buttons at the slider edges. */
function TabArrow({ side, disabled, onClick }: { side: "left" | "right"; disabled: boolean; onClick: () => void }) {
return (
<button
type="button"
aria-label={side === "left" ? "이전 북마크" : "다음 북마크"}
disabled={disabled}
onClick={onClick}
className={cn(
"absolute top-[11px] z-[1] h-6 w-3.5 cursor-pointer disabled:cursor-default disabled:opacity-30",
side === "left" ? "left-0" : "right-0",
)}
>
<Image
src={side === "left" ? "/images/kart/arrow_l.png" : "/images/kart/arrow_r.png"}
alt=""
width={14}
height={24}
unoptimized
/>
</button>
);
}
/** Legacy LeftToggleBox shown while the condition panels are collapsed. */
export function LeftToggleBox({ onExpand }: { onExpand: () => void }) {
return (
<button
type="button"
aria-label="조건 영역 펼치기"
onClick={onExpand}
className="absolute top-[19px] left-0 flex w-[86px] cursor-pointer flex-col items-center gap-[22px] rounded-r-[15px] border border-l-0 border-kart-line bg-white py-[18px]"
>
<Image src="/images/kart/btn_right.png" alt="" width={44} height={44} unoptimized />
<Image src="/images/kart/ic_filter_36.png" alt="" width={36} height={36} unoptimized />
<Image src="/images/kart/ic_document_36-1.svg" alt="" width={36} height={36} unoptimized />
</button>
);
}
/** Legacy mobile Tabulation: the PC-only illustration. */
export function PcOnlyNotice() {
return (
<div className="flex h-[80vh] items-center justify-center">
<Image
src="/images/kart/icon_pc.svg"
alt="PC 화면에서 사용할 수 있습니다."
width={233}
height={140}
unoptimized
/>
</div>
);
}

View File

@@ -0,0 +1,133 @@
"use client";
import Image from "next/image";
import { useState, type ReactNode } from "react";
import {
DndContext,
DragOverlay,
KeyboardSensor,
PointerSensor,
pointerWithin,
useSensor,
useSensors,
type DragEndEvent,
type DragStartEvent,
} from "@dnd-kit/core";
import { sortableKeyboardCoordinates } from "@dnd-kit/sortable";
import { TooltipProvider } from "@/components/ui/tooltip";
import type { Question } from "@/types/report";
import { questionViewTitle } from "@/lib/report-ui";
import { LeftToggleBox } from "./ReportChrome";
import { LegacyCheck } from "./ReportParts";
import { readDragData } from "./QuestionList";
import { plainText } from "./ReportResultView";
/**
* Shared legacy Tabulation / Cross Tab frame: bookmark tabs, the collapsible left panel with the
* Use Test Data / 세로 테이블 checks and question lists, drag-and-drop context, and the phone view.
*/
export function ReportFrame({
label,
tabs,
isTest,
onTestChange,
isAxis,
onAxisChange,
lists,
findQuestion,
onDragEnd,
phone,
children,
}: {
label: string;
/** Bookmark tab bar (`ReportTabs`). */
tabs: ReactNode;
isTest: boolean;
onTestChange: (value: boolean) => void;
isAxis: boolean;
onAxisChange: (value: boolean) => void;
lists: ReactNode;
findQuestion: (qid: string) => Question | undefined;
onDragEnd: (event: DragEndEvent) => void;
phone: ReactNode;
children: (collapsed: boolean) => ReactNode;
}) {
const [collapsed, setCollapsed] = useState(false);
const [dragging, setDragging] = useState<Question | null>(null);
const sensors = useSensors(
// A short movement threshold keeps plain clicks as selection toggles.
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
);
const onDragStart = (event: DragStartEvent) => {
const data = readDragData(event.active.data.current);
setDragging(data?.kind === "question" ? (findQuestion(data.qid) ?? null) : null);
};
return (
<TooltipProvider delayDuration={0}>
<section
aria-label={label}
className="-mx-[1.0416vw] -mt-2.5 -mb-6 min-h-[calc(100vh-146px)] bg-white"
>
{/* Legacy shows reduced content on phones (small touch screens). */}
<div className="[@media(pointer:coarse)_and_(max-width:767px)]:hidden">
{tabs}
<DndContext
sensors={sensors}
collisionDetection={pointerWithin}
onDragStart={onDragStart}
onDragEnd={(event) => {
setDragging(null);
onDragEnd(event);
}}
onDragCancel={() => setDragging(null)}
>
<div className="relative px-[1.0416vw]">
<div className="flex items-start justify-center gap-[1.041vw] py-5">
{collapsed ? (
<LeftToggleBox onExpand={() => setCollapsed(false)} />
) : (
<div className="min-h-[278px] w-[396px] shrink-0">
<div className="relative pt-0.5 pr-5 pb-[18px]">
<LegacyCheck id="chk_test" label="Use Test Data" checked={isTest} onChange={onTestChange} />
<LegacyCheck id="chk_axis" label="세로 테이블" checked={isAxis} onChange={onAxisChange} />
<button
type="button"
aria-label="조건 영역 접기"
onClick={() => setCollapsed(true)}
className="absolute -top-1.5 right-0 cursor-pointer"
>
<Image src="/images/kart/btn_left.png" alt="" width={36} height={36} unoptimized />
</button>
</div>
{lists}
</div>
)}
<div
className={
collapsed
? "relative ml-[75px] w-[calc(100%-100px)]"
: "relative min-w-0 flex-1"
}
>
{children(collapsed)}
</div>
</div>
</div>
{/* Legacy react-dnd drops in place; no animation back to the source item. */}
<DragOverlay dropAnimation={null}>
{dragging ? (
<div className="w-[356px] cursor-grabbing overflow-hidden bg-kart-bg px-3 py-2 text-sm leading-5 text-ellipsis whitespace-nowrap text-kart-text opacity-80 shadow">
{plainText(questionViewTitle(dragging))}
</div>
) : null}
</DragOverlay>
</DndContext>
</div>
<div className="hidden [@media(pointer:coarse)_and_(max-width:767px)]:block">
{phone}
</div>
</section>
</TooltipProvider>
);
}

View File

@@ -0,0 +1,186 @@
"use client";
import Image from "next/image";
import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
import { Checkbox } from "@/components/ui/checkbox";
/** Legacy statistic_box: white card whose 55px title bar overlaps the border by 1px. */
export function StatBox({
icon,
title,
action,
className,
children,
}: {
icon: "filter" | "document";
title: string;
action?: ReactNode;
className?: string;
children: ReactNode;
}) {
return (
<div
className={cn(
"mb-4 rounded-[15px] border border-kart-line bg-white",
className,
)}
>
<div className="-m-px flex h-[55px] items-center justify-between rounded-[15px] border border-kart-line bg-kart-soft p-2.5">
<div className="flex items-center gap-2">
<Image
src={
icon === "filter"
? "/images/kart/ic_filter_36.png"
: "/images/kart/ic_document_36-1.svg"
}
alt=""
width={36}
height={36}
className="h-[33px] w-9 object-contain"
unoptimized
/>
<h3 className="text-base leading-[20.5px] font-bold text-kart-title">
{title}
</h3>
</div>
{action}
</div>
{children}
</div>
);
}
/** Legacy Filter box: Add Filter opens the popup; the read-only line shows the condition text. */
export function FilterStatBox({
condition,
onAdd,
onReset,
}: {
condition: string;
onAdd: () => void;
onReset: () => void;
}) {
return (
<StatBox
icon="filter"
title="Filter"
action={
<button
type="button"
onClick={onAdd}
className="h-7 w-[113px] cursor-pointer rounded-[52px] bg-kart-green bg-[url(/images/kart/ic_plus.png)] bg-position-[left_12px_center] bg-no-repeat pl-5 text-sm leading-[16px] font-bold text-white"
>
Add Filter
</button>
}
>
<div className="flex gap-2 p-4">
<input
type="text"
readOnly
aria-label="적용된 필터"
value={condition}
className="h-9 min-w-0 flex-1 rounded-[4px] bg-kart-bg px-3.5 py-1 text-sm leading-[19px] font-light text-kart-text outline-none"
/>
<ResetButton label="필터 초기화" onClick={onReset} />
</div>
</StatBox>
);
}
/** Legacy 36px white reset square with the circular-arrow icon. */
export function ResetButton({
label,
onClick,
}: {
label: string;
onClick: () => void;
}) {
return (
<button
type="button"
aria-label={label}
title={label}
onClick={onClick}
className="size-9 shrink-0 cursor-pointer rounded-[4px] border border-kart-line bg-white bg-[url(/images/kart/ic_reset_16.png)] bg-size-[18px_17px] bg-center bg-no-repeat"
/>
);
}
/** Legacy 20px rounded checkbox: grey border, green fill with white check. */
export function LegacyCheck({
id,
label,
checked,
onChange,
}: {
id: string;
label: string;
checked: boolean;
onChange: (checked: boolean) => void;
}) {
return (
<span className="inline-flex h-5 w-[150px] items-center gap-2.5 align-top text-sm leading-5 text-kart-text">
<Checkbox
id={id}
checked={checked}
onCheckedChange={(value) => onChange(value === true)}
className="size-5 cursor-pointer rounded-[4px] border-[#ddd] bg-white shadow-none data-[state=checked]:border-kart-green data-[state=checked]:bg-kart-green data-[state=checked]:text-white"
/>
<label htmlFor={id} className="cursor-pointer">
{label}
</label>
</span>
);
}
/** Legacy square_btn (156x50). Grey until every requested table has arrived, then green. */
export function SquareButton({
done,
onClick,
children,
className,
disabled,
title,
}: {
done: boolean;
onClick?: () => void;
children: ReactNode;
className?: string;
disabled?: boolean;
title?: string;
}) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
title={title}
className={cn(
"h-[50px] w-[156px] cursor-pointer rounded-[4px] text-base leading-[18.4px] font-bold text-white",
done ? "bg-kart-green" : "bg-[#9e9e9e]",
disabled && "cursor-default",
className,
)}
>
{children}
</button>
);
}
/** Legacy TableLoading: 200px loading.gif centred in half the width. */
export function TableLoading() {
return (
<div className="w-1/2 text-center" role="status" aria-label="집계 중">
<Image
src="/images/kart/loading.gif"
alt=""
width={200}
height={200}
className="inline-block w-[200px]"
unoptimized
/>
</div>
);
}

View File

@@ -0,0 +1,166 @@
"use client";
import DOMPurify from "dompurify";
import type { DisplayMode, ReportCell, ReportResult } from "@/types/report";
import { cellDisplay } from "@/lib/report-contract";
export function HtmlText({ text }: { text: string | null | undefined }) {
if (!text) return null;
if (typeof window === "undefined") return <span>{text}</span>;
return (
<span
dangerouslySetInnerHTML={{
__html: DOMPurify.sanitize(text, {
ALLOWED_TAGS: [
"b",
"strong",
"em",
"i",
"u",
"br",
"span",
"sub",
"sup",
],
ALLOWED_ATTR: [],
}),
}}
/>
);
}
/** Text content of a server HTML fragment (tooltips, aria labels). */
export function plainText(html: string): string {
if (typeof window === "undefined") return html;
const safe = DOMPurify.sanitize(html, { ALLOWED_TAGS: [], ALLOWED_ATTR: [] });
return new DOMParser().parseFromString(safe, "text/html").body.textContent ?? "";
}
export function questionLabel(question: {
variable: string | null;
qid: string;
explain: string | null;
title: string | null;
}) {
const text =
(question.variable || question.qid) +
". " +
(question.explain || question.title || "");
if (typeof window === "undefined") return text;
const safe = DOMPurify.sanitize(text, { ALLOWED_TAGS: [], ALLOWED_ATTR: [] });
return (
new DOMParser().parseFromString(safe, "text/html").body.textContent ||
question.qid
);
}
export function ReportResultView({
result,
displayMode,
}: {
result: ReportResult;
displayMode: DisplayMode;
}) {
if (result.type === "TEXT_ANALYSIS") return <TextResult result={result} />;
const rows = [...result.headerRows, ...result.rows];
if (!rows.length)
return (
<p className="p-6 text-sm text-muted-foreground">집계 결과가 없습니다.</p>
);
return (
<div className="max-h-[75vh] overflow-auto rounded-lg border">
<table className="w-full border-collapse text-sm tabular-nums">
<caption className="sr-only">
{result.title ?? result.questionId}
</caption>
<tbody>
{rows.map((row, index) => (
<tr
key={row.rowIndex}
className={
row.kind === "TOTAL" ? "bg-[#eff8f3] font-semibold" : ""
}
>
{row.cells.map((cell) => {
const header =
index < result.headerRows.length || cell.columnIndex === 0;
const Tag = header ? "th" : "td";
return (
<Tag
key={cell.columnIndex}
rowSpan={cell.rowSpan}
colSpan={cell.colSpan}
className={
"min-w-24 whitespace-pre-wrap border px-3 py-2.5 " +
(header ? "bg-[#f5f6f7] font-medium " : "text-right ") +
(cell.columnIndex === 0
? "min-w-48 max-w-96 text-left "
: "")
}
title={
cell.base == null
? undefined
: "백분율 기준 사례수: " + cell.base
}
>
<CellContent cell={cell} mode={displayMode} />
</Tag>
);
})}
</tr>
))}
</tbody>
</table>
</div>
);
}
function CellContent({ cell, mode }: { cell: ReportCell; mode: DisplayMode }) {
return cell.kind === "TEXT" ? (
<HtmlText text={cell.textValue} />
) : (
<>{cellDisplay(cell, mode)}</>
);
}
function TextResult({ result }: { result: ReportResult }) {
if (!result.words.length)
return (
<p className="p-6 text-sm text-muted-foreground">
분석할 단어가 없습니다.
</p>
);
const maximum = Math.max(1, ...result.words.map((word) => word.count));
return (
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_240px]">
<div
className="flex min-h-64 flex-wrap content-center items-center justify-center gap-x-5 gap-y-3 rounded-lg bg-white p-6"
aria-label="주관식 단어 빈도"
>
{result.words.map((word, index) => (
<span
key={index}
title={word.text + ": " + word.count}
style={{
fontSize: 12 + Math.sqrt(word.count / maximum) * 36,
color: ["#1CAE81", "#0066FF", "#FF7386", "#B066FA"][index % 4],
}}
>
{word.text}
</span>
))}
</div>
<div>
<h3 className="mb-3 font-semibold">Top 10</h3>
<ol className="space-y-2 text-sm">
{result.words.slice(0, 10).map((word, index) => (
<li
key={index}
className="flex justify-between gap-3 border-b pb-2"
>
<span>
{index + 1}. {word.text}
</span>
<strong>{word.count.toLocaleString("ko-KR")}</strong>
</li>
))}
</ol>
</div>
</div>
);
}

View File

@@ -0,0 +1,315 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import type { DragEndEvent } from "@dnd-kit/core";
import { QueryState } from "@/components/project/QueryState";
import { useAuth } from "@/hooks/useAuth";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { useReportBookmarks } from "@/hooks/useReportBookmarks";
import { useVisitLog } from "@/hooks/useVisitLog";
import { apiError } from "@kri/common/http";
import { useFileDownload } from "@/query/export";
import { EXPORT_PREFIX } from "@/lib/download-name";
import { useProjectTitle } from "@/query/project";
import { useQuestionQuery, useReportStream } from "@/query/report";
import { projectKey, type ProjectRef } from "@/types/kart";
import type { Bookmark } from "@/types/bookmark";
import { canIndex, readReportBatch } from "@/lib/report-contract";
import { isDerivedQuestion, questionHead } from "@/lib/report-ui";
import {
filterCondition,
toServerFilter,
type LegacyFilterLine,
} from "@/lib/legacy-filter";
import {
bookmarkAxis,
bookmarkFilter,
bookmarkTest,
emptyBookmarkFilter,
emptyBookmarkSetting,
readBookmarkSetting,
writeBookmarkJson,
} from "@/lib/bookmark-json";
import { BannerBox, dropOnBanner, removeBanner } from "./BannerBox";
import { BookmarkPopup } from "./BookmarkPopup";
import { excelTables } from "./excel-tables";
import { PcOnlyNotice, ReportTabs } from "./ReportChrome";
import { ReportFrame } from "./ReportFrame";
import { FilterStatBox, ResetButton, SquareButton, StatBox } from "./ReportParts";
import { ResultBlock, ResultMessage } from "./LegacyResultTable";
import { QuestionList, readDragData } from "./QuestionList";
import { FilterPopup } from "./FilterPopup";
export function TabulationWorkspace() {
const router = useRouter();
const { auth } = useAuth();
const { project, hydrated } = useSelectedProject();
const missing = hydrated && !project;
useEffect(() => {
if (missing) router.replace("/");
}, [missing, router]);
if (!project) return null;
return (
<Workspace
key={JSON.stringify([
projectKey(project),
auth.user?.userId,
auth.user?.userRole,
auth.user?.userTeam,
])}
project={project}
/>
);
}
/** Legacy Tabulation.js: click-selected questions, dragged banners, Run → characteristic + tables. */
function Workspace({ project }: { project: ProjectRef }) {
const questions = useQuestionQuery(project);
const { run, start, reset } = useReportStream(project);
const [selectedQuestion, setSelectedQuestion] = useState<string[]>([]);
const [selectedVariable, setSelectedVariable] = useState<string[]>([]);
const [banners, setBanners] = useState<string[][]>([]);
const [filterLines, setFilterLines] = useState<LegacyFilterLine[]>([]);
const [filterOpen, setFilterOpen] = useState(false);
const [isTest, setIsTest] = useState(false);
const [isAxis, setIsAxis] = useState(false);
const bookmarks = useReportBookmarks(project, "TABULATION");
const download = useFileDownload();
const projectTitle = useProjectTitle(project);
// Stored filter strings and OPTION of the applied bookmark, kept verbatim when unchanged.
const [loadedFilter, setLoadedFilter] = useState(emptyBookmarkFilter);
const [option, setOption] = useState<Record<string, unknown>>({});
useVisitLog("/Report/Tabulation", project);
// Tabulation never lists open-ended (text) questions.
const all = (questions.data ?? []).filter(
(question) => canIndex(question) && question.qtype !== "text",
);
const questionItems = all.filter((question) => !isDerivedQuestion(question));
const variableItems = all.filter(isDerivedQuestion);
const find = (qid: string) =>
(questions.data ?? []).find((question) => question.qid === qid);
// Legacy order: questions in list order, then variables in click order.
const selectedIndex = [...selectedQuestion, ...selectedVariable];
const tables = run.slots.filter((slot) => slot.index !== "");
const done =
run.status === "complete" &&
tables.length > 0 &&
tables.every((slot) => slot.result || slot.error);
const makeTable = () => {
if (!selectedIndex.length) return;
start({
request: readReportBatch({
indexes: selectedIndex,
banners,
filter: toServerFilter(filterLines),
dataScope: isTest ? "TEST" : "ACTUAL",
transpose: isAxis,
// Legacy screens show percentages with 1 decimal and Mean with 2.
percentageDecimals: 1,
statisticDecimals: 2,
}),
titles: selectedIndex.map((qid) => {
const question = find(qid);
return question ? questionHead(question) : qid;
}),
// Legacy requests the hidden 표본의 특성 table for Excel export on every run.
characteristic: true,
});
};
const toggleQuestion = (qid: string) => {
const next = selectedQuestion.includes(qid)
? selectedQuestion.filter((id) => id !== qid)
: [...selectedQuestion, qid];
setSelectedQuestion(
questionItems.map((item) => item.qid).filter((id) => next.includes(id)),
);
};
const toggleVariable = (qid: string) =>
setSelectedVariable(
selectedVariable.includes(qid)
? selectedVariable.filter((id) => id !== qid)
: [...selectedVariable, qid],
);
// Legacy selectedBookMark effect: replace every condition and clear shown tables; no auto-run.
const applyBookmark = (bookmark: Bookmark | null) => {
const setting = bookmark ? readBookmarkSetting(bookmark.bookmarkJson) : emptyBookmarkSetting;
bookmarks.select(bookmark);
reset();
setSelectedQuestion(
questionItems.map((item) => item.qid).filter((qid) => setting.index.includes(qid)),
);
setSelectedVariable(
variableItems.map((item) => item.qid).filter((qid) => setting.index.includes(qid)),
);
setBanners(setting.banners);
setFilterLines(setting.filter.lines);
setLoadedFilter(setting.filter);
setOption(setting.option);
setIsTest(bookmarkTest(setting.option));
setIsAxis(bookmarkAxis(setting.option));
};
const currentFilter = () => bookmarkFilter(filterLines, loadedFilter);
// Legacy ExportTable: the hidden 표본의 특성 table first, then every received table.
const exportTable = () => {
const tables = excelTables(run.slots, find);
if (!tables.length) return;
download.mutate(
{
kind: "table",
project,
request: { tables, turn: isAxis },
name: { prefix: EXPORT_PREFIX.table, title: projectTitle },
},
{
onError: (error) =>
window.alert(apiError(error, { fallbackMessage: "Excel 파일을 만들지 못했습니다." }).message),
},
);
};
const onDragEnd = (event: DragEndEvent) => {
const data = readDragData(event.active.data.current);
if (!data) return;
const next = dropOnBanner(
banners,
data,
event.over ? String(event.over.id) : "",
readDragData(event.over?.data.current),
);
if (next) setBanners(next);
};
if (questions.isPending || questions.isError)
return (
<QueryState
pending={questions.isPending}
error={questions.error}
onRetry={() => void questions.refetch()}
/>
);
return (
<>
<ReportFrame
label="Tabulation"
tabs={
<ReportTabs
bookmarks={bookmarks.bookmarks}
selectedId={bookmarks.current?.bookmarkId ?? null}
onSelect={applyBookmark}
canSave={bookmarks.canSave}
onBookmark={() => bookmarks.setPopupOpen(true)}
onRefresh={makeTable}
/>
}
isTest={isTest}
onTestChange={setIsTest}
isAxis={isAxis}
onAxisChange={(value) => {
setIsAxis(value);
// Legacy clears shown tables when the orientation changes.
reset();
}}
findQuestion={find}
onDragEnd={onDragEnd}
phone={<PcOnlyNotice />}
lists={
<>
<QuestionList
title="Question List"
variant="question"
questions={questionItems}
selected={selectedQuestion}
onToggle={toggleQuestion}
onSelectAll={(value) =>
setSelectedQuestion(value ? questionItems.map((item) => item.qid) : [])
}
/>
<QuestionList
title="Variable List"
variant="variable"
questions={variableItems}
selected={selectedVariable}
onToggle={toggleVariable}
onSelectAll={(value) =>
setSelectedVariable(value ? variableItems.map((item) => item.qid) : [])
}
/>
</>
}
>
{(collapsed) => (
<>
{collapsed ? null : (
<>
<FilterStatBox
condition={filterCondition(filterLines)}
onAdd={() => setFilterOpen(true)}
onReset={() => setFilterLines([])}
/>
<div className="mb-4 text-center">
<SquareButton done={done} disabled={download.isPending} onClick={exportTable}>
Export Table
</SquareButton>
</div>
<StatBox
icon="document"
title="Banner"
action={<ResetButton label="배너 초기화" onClick={() => setBanners([])} />}
>
<BannerBox
banners={banners}
questions={questions.data ?? []}
onRemove={(group, qid) => setBanners(removeBanner(banners, group, qid))}
/>
</StatBox>
<div className="text-center">
<SquareButton done={done} onClick={makeTable}>
Run
</SquareButton>
</div>
</>
)}
{run.error ? <ResultMessage message={run.error} /> : null}
{tables.map((slot, index) => (
<ResultBlock
key={index}
title={slot.title}
result={slot.result}
error={slot.error}
pending={run.status === "running"}
/>
))}
</>
)}
</ReportFrame>
{filterOpen ? (
<FilterPopup
open
initial={filterLines}
questions={questions.data ?? []}
onOpenChange={setFilterOpen}
onSave={setFilterLines}
/>
) : null}
{bookmarks.popupOpen ? (
<BookmarkPopup
state={bookmarks}
buildJson={() =>
writeBookmarkJson({
index: selectedIndex,
banners,
filter: currentFilter(),
option,
isTest,
isAxis,
})
}
onSaved={() => setLoadedFilter(currentFilter())}
onDeleted={() => applyBookmark(null)}
/>
) : null}
</>
);
}

View File

@@ -0,0 +1,153 @@
"use client";
import { useEffect, useRef, useState } from "react";
import cloud from "d3-cloud";
import type { ReportResult } from "@/types/report";
import { CHART_FONT_FAMILY, useChartFontReady } from "@/hooks/useChartFont";
// Legacy react-wordcloud options (Table.js ResultCloud).
const COLORS = ["#FF2500", "#0066FF", "#1CAE81", "#94C81A", "#FFBF33", "#B066FA", "#FF7386"];
const FONT_SIZES = [10, 100] as const;
const HEIGHT = 400;
type Placed = { text: string; size: number; x: number; y: number; color: string };
// Drawn layouts by result, so Export Table can send the cloud the user is looking at.
const drawn = new WeakMap<ReportResult, { width: number; placed: Placed[] }>();
/**
* Base64 PNG of the word cloud as shown (legacy exported the on-screen SVG on a white
* background). Drawn on a canvas so the already loaded web font is used for every glyph.
*/
export function wordCloudPng(result: ReportResult): string | undefined {
const layout = drawn.get(result);
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
if (!layout || !context) return undefined;
canvas.width = layout.width;
canvas.height = HEIGHT;
context.fillStyle = "#ffffff";
context.fillRect(0, 0, canvas.width, canvas.height);
context.textAlign = "center";
for (const word of layout.placed) {
context.font = `700 ${word.size}px ${CHART_FONT_FAMILY}`;
context.fillStyle = word.color;
context.fillText(word.text, layout.width / 2 + word.x, HEIGHT / 2 + word.y);
}
return canvas.toDataURL("image/png").split(",")[1];
}
/** Legacy ResultCloud: d3-cloud layout (60%) beside the Top 10 table (40%). */
export function WordCloud({ result }: { result: ReportResult }) {
const words = result.words;
const container = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
const [placed, setPlaced] = useState<Placed[]>([]);
const fontReady = useChartFontReady(words.map((word) => word.text).join(""));
useEffect(() => {
if (width && placed.length) drawn.set(result, { width, placed });
}, [result, width, placed]);
useEffect(() => {
const element = container.current;
if (!element) return;
const observer = new ResizeObserver(([entry]) =>
setWidth(Math.floor(entry.contentRect.width)),
);
observer.observe(element);
return () => observer.disconnect();
}, []);
useEffect(() => {
if (!fontReady || !width || !words.length) return;
const counts = words.map((word) => word.count);
const low = Math.sqrt(Math.min(...counts));
const high = Math.sqrt(Math.max(...counts));
// scale: "sqrt" over the count domain, mapped onto fontSizes.
const size = (count: number) =>
high === low
? FONT_SIZES[1]
: FONT_SIZES[0] +
((Math.sqrt(count) - low) / (high - low)) * (FONT_SIZES[1] - FONT_SIZES[0]);
const layout = cloud<cloud.Word>()
.size([width, HEIGHT])
.words(words.map((word) => ({ text: word.text, size: size(word.count) })))
.padding(1)
.rotate(() => 0)
.font(CHART_FONT_FAMILY)
.fontWeight(700)
.fontSize((word) => word.size ?? FONT_SIZES[0])
.on("end", (output) =>
setPlaced(
output.map((word) => ({
text: word.text ?? "",
size: word.size ?? FONT_SIZES[0],
x: word.x ?? 0,
y: word.y ?? 0,
// deterministic: false — legacy picks a random palette colour per word.
color: COLORS[Math.floor(Math.random() * COLORS.length)],
})),
),
);
layout.start();
return () => {
layout.stop();
};
}, [fontReady, width, words]);
return (
<div className="flex gap-3">
<div ref={container} className="w-3/5">
{width ? (
<svg
width={width}
height={HEIGHT}
role="img"
aria-label="주관식 단어 빈도 워드클라우드"
>
<g transform={`translate(${width / 2},${HEIGHT / 2})`}>
{placed.map((word, index) => (
<text
key={index}
textAnchor="middle"
transform={`translate(${word.x},${word.y})`}
style={{
fontFamily: CHART_FONT_FAMILY,
fontSize: word.size,
fontWeight: 700,
fill: word.color,
}}
>
{word.text}
</text>
))}
</g>
</svg>
) : null}
</div>
<div className="w-2/5">
<h3 className="text-base leading-[20.5px] font-bold text-kart-title">
Top 10
</h3>
<table className="mt-3 w-full border-separate border-spacing-0 text-sm text-kart-text">
<tbody>
{words.slice(0, 10).map((word, index) => (
<tr key={index} className="bg-kart-bg">
<td className="h-9 w-10 rounded-[4px] border-8 border-white px-3 py-2 text-center font-bold">
{index + 1}
</td>
<td className="h-9 rounded-[4px] border-8 border-white px-3 py-2 text-left">
{word.text}
</td>
<td className="h-9 w-10 rounded-[4px] border-8 border-white px-3 py-2 text-center font-bold text-kart-green">
({word.count})
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}

View File

@@ -0,0 +1,31 @@
import type { Question, ReportBatch } from "@/types/report";
import { canIndex, readReportBatch } from "@/lib/report-contract";
import { toServerFilter, type LegacyFilterLine } from "@/lib/legacy-filter";
/** Cross Tab conditions that re-run every table when they change. */
export type Conditions = {
banners: string[][];
filterLines: LegacyFilterLine[];
isTest: boolean;
isAxis: boolean;
};
export const crosstabBatch = (ids: string[], conditions: Conditions): ReportBatch =>
readReportBatch({
indexes: ids,
banners: conditions.banners,
filter: toServerFilter(conditions.filterLines),
dataScope: conditions.isTest ? "TEST" : "ACTUAL",
transpose: conditions.isAxis,
// Legacy screens show percentages with 1 decimal and Mean with 2.
percentageDecimals: 1,
statisticDecimals: 2,
});
/** Bookmark INDEX entries that are still indexable questions, in saved order without repeats. */
export const bookmarkIndexes = (index: string[], questions: Question[]) =>
index.filter(
(qid, position) =>
index.indexOf(qid) === position &&
questions.some((question) => question.qid === qid && canIndex(question)),
);

View File

@@ -0,0 +1,33 @@
import type { Question, ReportResult } from "@/types/report";
import { questionHead } from "@/lib/report-ui";
import { reportExcelBody, type ExcelTable } from "@/lib/report-excel";
import { wordCloudPng } from "./WordCloud";
/** Legacy Tabulation characterArray head for the hidden TABULATION_0 table. */
export const CHARACTERISTIC_HEAD = "■ 표 본 의 특 성 ■";
/**
* Legacy ExportTable list: received tables in screen order (head = EXPLAIN, vname = VARIABLE,
* qtype = QTYPE), word clouds with their picture. Pending, failed and empty tables are skipped,
* like the legacy writer skipping an empty body.
*/
export function excelTables(
items: { index: string; result?: ReportResult }[],
find: (qid: string) => Question | undefined,
): ExcelTable[] {
return items.flatMap(({ index, result }) => {
const body = result ? reportExcelBody(result) : null;
if (!result || !body) return [];
const question = index ? find(index) : undefined;
const imagePng = result.type === "TEXT_ANALYSIS" ? wordCloudPng(result) : undefined;
return [
{
head: index ? (question ? questionHead(question) : index) : CHARACTERISTIC_HEAD,
vname: question?.variable ?? "",
qtype: question?.qtype ?? "",
body,
...(imagePng ? { imagePng } : {}),
},
];
});
}

View File

@@ -4,7 +4,7 @@ import { cn } from "cn"
import { Slot } from "radix-ui"
const buttonVariants = cva(
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 cursor-pointer",
{
variants: {
variant: {

View File

@@ -0,0 +1,241 @@
"use client"
import * as React from "react"
import { cn } from "cn"
import useEmblaCarousel, {
type UseEmblaCarouselType,
} from "embla-carousel-react"
import { ArrowLeft, ArrowRight } from "lucide-react"
import { Button } from "@/components/ui/button"
type CarouselApi = UseEmblaCarouselType[1]
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
type CarouselOptions = UseCarouselParameters[0]
type CarouselPlugin = UseCarouselParameters[1]
type CarouselProps = {
opts?: CarouselOptions
plugins?: CarouselPlugin
orientation?: "horizontal" | "vertical"
setApi?: (api: CarouselApi) => void
}
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
api: ReturnType<typeof useEmblaCarousel>[1]
scrollPrev: () => void
scrollNext: () => void
canScrollPrev: boolean
canScrollNext: boolean
} & CarouselProps
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
function useCarousel() {
const context = React.useContext(CarouselContext)
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />")
}
return context
}
function Carousel({
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
}: React.ComponentProps<"div"> & CarouselProps) {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins
)
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
const [canScrollNext, setCanScrollNext] = React.useState(false)
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) return
setCanScrollPrev(api.canScrollPrev())
setCanScrollNext(api.canScrollNext())
}, [])
const scrollPrev = React.useCallback(() => {
api?.scrollPrev()
}, [api])
const scrollNext = React.useCallback(() => {
api?.scrollNext()
}, [api])
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault()
scrollPrev()
} else if (event.key === "ArrowRight") {
event.preventDefault()
scrollNext()
}
},
[scrollPrev, scrollNext]
)
React.useEffect(() => {
if (!api || !setApi) return
setApi(api)
}, [api, setApi])
React.useEffect(() => {
if (!api) return
onSelect(api)
api.on("reInit", onSelect)
api.on("select", onSelect)
return () => {
api?.off("select", onSelect)
}
}, [api, onSelect])
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation:
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
data-slot="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
)
}
function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
const { carouselRef, orientation } = useCarousel()
return (
<div
ref={carouselRef}
className="overflow-hidden"
data-slot="carousel-content"
>
<div
className={cn(
"flex",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className
)}
{...props}
/>
</div>
)
}
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
const { orientation } = useCarousel()
return (
<div
role="group"
aria-roledescription="slide"
data-slot="carousel-item"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className
)}
{...props}
/>
)
}
function CarouselPrevious({
className,
variant = "outline",
size = "icon",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
return (
<Button
data-slot="carousel-previous"
variant={variant}
size={size}
className={cn(
"absolute size-8 rounded-full",
orientation === "horizontal"
? "top-1/2 -left-12 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft />
<span className="sr-only">Previous slide</span>
</Button>
)
}
function CarouselNext({
className,
variant = "outline",
size = "icon",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollNext, canScrollNext } = useCarousel()
return (
<Button
data-slot="carousel-next"
variant={variant}
size={size}
className={cn(
"absolute size-8 rounded-full",
orientation === "horizontal"
? "top-1/2 -right-12 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight />
<span className="sr-only">Next slide</span>
</Button>
)
}
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
}

View File

@@ -0,0 +1,56 @@
"use client"
import * as React from "react"
import { cn } from "cn"
import { Tooltip as TooltipPrimitive } from "radix-ui"
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
)
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
className
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
)
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }