feat(org-chart): finalize chart features and AI generation rules

This commit is contained in:
shkim4 committed 2026-10-13 14:39:42 +09:00
1 parent 7614507583
commit d0828a7ff4
80 files changed
+8152 -221

No files matched your search

+238 -38
View File
@@ -1,54 +1,254 @@
import { StrictMode, useId, useState } from 'react';
import { StrictMode, useEffect, useId, useMemo, useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { Button, Checkbox, Label, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@hm-design/ui';
import { OrgChart } from '@hm-design/org-chart-react';
import { companyColorPresets, JsonOrgChartDataSource, type OrgChartConnectionDirection } from '@hm-design/org-chart';
import { ChevronDownIcon } from 'lucide-react';
import {
Button, Checkbox, FilterBar, FilterBarActions, Label,
Popover, PopoverContent, PopoverTrigger, Separator,
Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Switch,
} from '@hm-design/ui';
import { OrgChart, type OrgChartProps } from '@hm-design/org-chart-react';
import {
companyColorPresets, createOrgChartExampleDataset, JsonOrgChartDataSource,
type CompanyId, type OrgChartAutoLayoutOptions, type OrgChartDataset, type OrgChartExampleSelection, type OrgChartInteractionOptions,
} from '@hm-design/org-chart';
import engineUrl from '@hm-design/org-chart/engine.css?url';
import coreUrl from '@hm-design/org-chart/style.css?url';
import small from '../../examples/org-chart/data-expanded-small.json';
import medium from '../../examples/org-chart/data-expanded-medium.json';
import { StoryPage, StoryPageHeader, StorySection } from '@/components/story-page';
import large from '../../examples/org-chart/data-expanded-large.json';
import './org-chart-stories.css';
import '../center/center-stories.css';
import './org-chart-expanded-story.css';
const fixtures = { small, medium, large };
const sources = { small: new JsonOrgChartDataSource(small), medium: new JsonOrgChartDataSource(medium), large: new JsonOrgChartDataSource(large) };
const template = large as OrgChartDataset;
const companies = Object.values(companyColorPresets);
const allCompanies = companies.map(company => company.companyId as CompanyId);
const compositionStylesheets = { engine: engineUrl, core: coreUrl };
const topNodes = { ptc: { title: '기술총괄', name: '가상책임자 5' } };
const connections: Record<string, OrgChartConnectionDirection> = Object.fromEntries(large.organizations.map((org, index) => [org.id, (['top', 'left', 'right'] as const)[index % 3]! ]));
type DataSettings = Required<Pick<OrgChartExampleSelection, 'employeeCount' | 'companyIds'>>;
const initialSettings: DataSettings = { employeeCount: 20, companyIds: allCompanies };
/** Company state is passed to the shared Core without filtering/mutating JSON. */
/** Existing Expanded Story only: public FilterBar layout/actions match data
* conditions. The preview selects samples rather than searching employees. */
function ExpandedPreview() {
const id = useId();
const [size, setSize] = useState<keyof typeof fixtures>('small');
const [selected, setSelected] = useState<string[] | undefined>();
const companies = fixtures[size].affiliations;
const visible = selected ?? companies.map(company => company.id);
return <section className="hm-orgchart-story" aria-label="Expanded OrgChart · P5-4">
<p className="hm-orgchart-story-note"><strong>확장형 조직도</strong> — 회사별 독립 조직 · 타이틀 클릭으로 접기·펼치기 · 확대 및 드래그 이동. 모든 직원은 가상 데이터입니다.</p>
<div className="hm-orgchart-story-controls">
<div className="hm-orgchart-story-instance">
<Label id={`${id}-data-label`} htmlFor={`${id}-data`}>가상 데이터</Label>
<Select value={size} onValueChange={value => { setSize(value as keyof typeof fixtures); setSelected(undefined); }}>
<SelectTrigger id={`${id}-data`} aria-labelledby={`${id}-data-label`} size="medium"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="small">Small · 20명</SelectItem><SelectItem value="medium">Medium · 100명</SelectItem><SelectItem value="large">Large · 300명</SelectItem></SelectContent>
</Select>
const [draft, setDraft] = useState<DataSettings>(initialSettings);
const [applied, setApplied] = useState<DataSettings>(initialSettings);
const [dataRevision, setDataRevision] = useState(0);
const [layout, setLayout] = useState<OrgChartAutoLayoutOptions>({ type: 'tb', hybridStartDepth: 2, initialVisibleDepth: 'all' });
const [popup, setPopup] = useState<OrgChartProps['employeePopup']>('hm-dialog');
const [interactions, setInteractions] = useState<OrgChartInteractionOptions>({ collapse: true, zoom: true, pan: true });
const [dragDropEnabled, setDragDropEnabled] = useState(false);
const [error, setError] = useState<string | null>(null);
const dataset = useMemo(() => createOrgChartExampleDataset(template, {
scope: 'per-company',
employeeCount: applied.employeeCount,
// Company selection is view state. Keep every company in the canonical
// session source so hiding/revealing a company retains successful moves.
companyIds: allCompanies,
}), [applied.employeeCount, dataRevision]);
const source = useMemo(() => new JsonOrgChartDataSource(dataset), [dataset]);
// Core owns edits. This read model updates counts/options without replacing
// dataSource and reloading the unchanged fixture over a successful move.
const [session, setSession] = useState(() => ({ baseline: dataset, current: dataset }));
const currentDataset = session.baseline === dataset ? session.current : dataset;
const organizationCompanies = useMemo(() => {
const byId = new Map(currentDataset.organizations.map(organization => [organization.id, organization]));
const companyById = new Map<string, CompanyId>();
for (const organization of currentDataset.organizations) {
let current = organization;
while (!current.companyId && current.parentId && byId.has(current.parentId)) current = byId.get(current.parentId)!;
if (current.companyId) companyById.set(organization.id, current.companyId as CompanyId);
}
return companyById;
}, [currentDataset]);
const groupChoices = useMemo(() => {
const parents = new Set(currentDataset.organizations.map(organization => organization.parentId));
return currentDataset.organizations.filter(organization => parents.has(organization.id)).map(organization => {
const companyId = organizationCompanies.get(organization.id);
if (!companyId || !applied.companyIds.includes(companyId)) return null;
const company = companies.find(item => item.companyId === companyId);
const prefix = company ? `${company.companyName} · ` : '';
return { id: organization.id, name: organization.name.startsWith(prefix) ? organization.name : `${prefix}${organization.name}` };
}).filter((organization): organization is { id: string; name: string } => organization !== null);
}, [currentDataset, organizationCompanies, applied.companyIds]);
useEffect(() => {
const valid = new Set(groupChoices.map(organization => organization.id));
setLayout(current => {
const previous = current.hybridOrganizationIds ?? [];
const ids = previous.filter(organizationId => valid.has(organizationId));
return ids.length === previous.length ? current : { ...current, hybridOrganizationIds: ids };
});
}, [groupChoices]);
const predicted = draft.companyIds.length * draft.employeeCount;
const displayedTotal = new Set(currentDataset.employees.filter(employee => {
const companyId = organizationCompanies.get(employee.organizationId);
return companyId !== undefined && applied.companyIds.includes(companyId);
}).map(employee => employee.id)).size;
const sessionTotal = new Set(currentDataset.employees.map(employee => employee.id)).size;
const companyEmployeeCounts = useMemo(() => {
const employeeIds = new Map<CompanyId, Set<string>>(allCompanies.map(companyId => [companyId, new Set<string>()]));
for (const employee of currentDataset.employees) {
const companyId = organizationCompanies.get(employee.organizationId);
if (companyId) employeeIds.get(companyId)?.add(employee.id);
}
return new Map([...employeeIds].map(([companyId, ids]) => [companyId, ids.size]));
}, [currentDataset, organizationCompanies]);
const companyCountSummary = applied.companyIds.map(companyId => `${companies.find(company => company.companyId === companyId)!.companyName} ${companyEmployeeCounts.get(companyId) ?? 0}명`).join(' · ');
const pending = draft.employeeCount !== applied.employeeCount
|| draft.companyIds.join() !== applied.companyIds.join();
const selectedCompanyCount = draft.companyIds.length;
const companySummary = selectedCompanyCount === allCompanies.length ? `전체 회사 (${allCompanies.length}개)`
: selectedCompanyCount === 1 ? companies.find(company => company.companyId === draft.companyIds[0])!.companyName
: selectedCompanyCount > 1 ? `${selectedCompanyCount}개 회사 선택` : '회사를 선택하세요';
const allCompaniesChecked = selectedCompanyCount === allCompanies.length ? true
: selectedCompanyCount > 0 ? 'indeterminate' : false;
const changeCompanies = (companyIds: readonly CompanyId[]) => {
const selected = allCompanies.filter(companyId => companyIds.includes(companyId));
setError(null);
// Company filtering is immediate; pending employee-count changes still belong
// to the existing Data Apply action and P7 dataset generation contract.
setDraft(current => ({ ...current, companyIds: selected }));
setApplied(current => ({ ...current, companyIds: selected }));
};
return <StoryPage className="hm-orgchart-story-page hm-orgchart-story-expanded">
<StoryPageHeader
kicker="HM DESIGN SYSTEM / ORGCHART"
title="Expanded OrgChart"
description="데이터·회사·표시 유형을 선택하고 직원 카드를 눌러 정보를 확인하세요. 모든 직원은 가상 데이터입니다."
/>
<StorySection title="데이터 설정" description="회사 선택은 즉시 반영됩니다. 회사당 직원 수 변경은 데이터 적용을 눌러 반영합니다.">
<fieldset className="hm-orgchart-story-settings">
<legend className="hm-orgchart-story-section-legend">데이터 설정</legend>
<FilterBar layout="list-extended">
<div className="hm-orgchart-story-instance">
<Label id={`${id}-companies-label`} htmlFor={`${id}-companies`}>회사 선택</Label>
<Popover>
<PopoverTrigger asChild>
<Button id={`${id}-companies`} type="button" variant="cancel" appearance="outline"
className="hm-orgchart-story-company-trigger" aria-labelledby={`${id}-companies-label ${id}-companies-summary`}>
<span id={`${id}-companies-summary`} className="hm-orgchart-story-company-summary">{companySummary}</span>
<ChevronDownIcon aria-hidden="true" />
</Button>
</PopoverTrigger>
<PopoverContent align="start" aria-labelledby={`${id}-companies-label`} data-component="OrgChartCompanySelection" className="hm-orgchart-story-company-popover">
<fieldset className="hm-orgchart-story-company-options">
<legend className="sr-only">표시할 회사 · 복수 선택 가능</legend>
<div className="hm-orgchart-story-company">
<Checkbox id={`${id}-companies-all`} checked={allCompaniesChecked} onCheckedChange={checked => changeCompanies(checked === true ? allCompanies : [])} />
<Label htmlFor={`${id}-companies-all`}>전체 선택</Label>
</div>
<Separator />
{companies.map(company => <div key={company.companyId} className="hm-orgchart-story-company">
<Checkbox id={`${id}-${company.companyId}`} checked={draft.companyIds.includes(company.companyId as CompanyId)} onCheckedChange={checked => {
changeCompanies(checked === true ? [...draft.companyIds, company.companyId as CompanyId] : draft.companyIds.filter(value => value !== company.companyId));
}} />
<Label htmlFor={`${id}-${company.companyId}`}>{company.companyName}</Label>
</div>)}
</fieldset>
</PopoverContent>
</Popover>
</div>
<div className="hm-orgchart-story-instance">
<Label id={`${id}-size-label`} htmlFor={`${id}-size`}>회사당 직원 수</Label>
<Select value={String(draft.employeeCount)} onValueChange={value => setDraft(current => ({ ...current, employeeCount: Number(value) as DataSettings['employeeCount'] }))}>
<SelectTrigger id={`${id}-size`} aria-labelledby={`${id}-size-label`} size="medium"><SelectValue /></SelectTrigger>
<SelectContent>{[20, 100, 300].map(count => <SelectItem key={count} value={String(count)}>{count}명</SelectItem>)}</SelectContent>
</Select>
</div>
<FilterBarActions>
<Button variant="primary" appearance="solid" onClick={() => { setError(null); setApplied({ ...draft, companyIds: [...draft.companyIds] }); setDataRevision(current => current + 1); }}>데이터 적용</Button>
<Button variant="cancel" appearance="outline" onClick={() => { setError(null); setDraft(initialSettings); setApplied(initialSettings); setDataRevision(current => current + 1); }}>초기화</Button>
</FilterBarActions>
</FilterBar>
<p className="hm-orgchart-story-note" role="status" aria-live="polite">
{pending ? '적용 예정' : '예시 생성 기준'}: {draft.companyIds.length}개 회사 · 회사당 {draft.employeeCount}명 · 총 {predicted.toLocaleString('ko-KR')}명{pending ? ' · 데이터 적용을 눌러 반영하세요.' : ''}
</p>
<p className="hm-orgchart-story-note">회사 숨김·다시 표시는 현재 소속 변경을 유지합니다. 데이터 적용은 선택한 조건의 예시를 새로 만들고, 초기화는 최초 데이터 설정과 소속으로 돌아갑니다.</p>
</fieldset>
</StorySection>
<StorySection title="레이아웃 설정" description="TB·LR·Hybrid 표시 유형과 초기 표시 Depth를 설정합니다.">
<fieldset className="hm-orgchart-story-settings">
<legend className="hm-orgchart-story-section-legend">레이아웃 설정</legend>
<div className="hm-orgchart-story-controls">
<div className="hm-orgchart-story-instance">
<Label id={`${id}-layout-label`} htmlFor={`${id}-layout`}>조직도 표시 유형</Label>
<Select value={layout.type} onValueChange={value => setLayout(current => ({ ...current, type: value as OrgChartAutoLayoutOptions['type'], hybridOrganizationIds: [] }))}>
<SelectTrigger id={`${id}-layout`} aria-labelledby={`${id}-layout-label`} size="medium"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="tb">세로형 TB</SelectItem><SelectItem value="lr">가로형 LR</SelectItem><SelectItem value="hybrid">혼합형 Hybrid</SelectItem></SelectContent>
</Select>
</div>
<div className="hm-orgchart-story-instance">
<Label id={`${id}-hybrid-label`} htmlFor={`${id}-hybrid`}>혼합형 시작 Depth</Label>
<Select value={String(layout.hybridStartDepth)} disabled={layout.type !== 'hybrid'} onValueChange={value => setLayout(current => ({ ...current, hybridStartDepth: Number(value) as 2 | 3 | 4 }))}>
<SelectTrigger id={`${id}-hybrid`} aria-labelledby={`${id}-hybrid-label`} aria-describedby={`${id}-hybrid-help`} size="medium"><SelectValue /></SelectTrigger>
<SelectContent>{[2, 3, 4].map(depth => <SelectItem key={depth} value={String(depth)}>Depth {depth}부터 세로 배치</SelectItem>)}</SelectContent>
</Select>
<span id={`${id}-hybrid-help`} className="hm-orgchart-story-note">Hybrid에만 적용합니다.</span>
</div>
<div className="hm-orgchart-story-instance">
<Label id={`${id}-group-hybrid-label`} htmlFor={`${id}-group-hybrid`}>특정 그룹 세로 배치</Label>
<Select value={layout.hybridOrganizationIds?.[0] ?? 'none'} disabled={layout.type !== 'tb' || !applied.companyIds.length} onValueChange={value => setLayout(current => ({ ...current, hybridOrganizationIds: value === 'none' ? [] : [value] }))}>
<SelectTrigger id={`${id}-group-hybrid`} aria-labelledby={`${id}-group-hybrid-label`} aria-describedby={`${id}-group-hybrid-help`} size="medium"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="none">사용 안 함</SelectItem>{groupChoices.map(organization => <SelectItem key={organization.id} value={organization.id}>{organization.name}</SelectItem>)}</SelectContent>
</Select>
<span id={`${id}-group-hybrid-help`} className="hm-orgchart-story-note">TB에서 선택한 그룹 아래만 적용합니다. LR·Hybrid 전환 시 해제됩니다.</span>
</div>
<div className="hm-orgchart-story-instance">
<Label id={`${id}-depth-label`} htmlFor={`${id}-depth`}>초기 표시 Depth</Label>
<Select value={String(layout.initialVisibleDepth)} onValueChange={value => setLayout(current => ({ ...current, initialVisibleDepth: value === 'all' ? 'all' : Number(value) as 1 | 2 | 3 }))}>
<SelectTrigger id={`${id}-depth`} aria-labelledby={`${id}-depth-label`} size="medium"><SelectValue /></SelectTrigger>
<SelectContent>{[1, 2, 3].map(depth => <SelectItem key={depth} value={String(depth)}>{depth}Depth까지</SelectItem>)}<SelectItem value="all">전체 펼침</SelectItem></SelectContent>
</Select>
</div>
</div>
<p className="hm-orgchart-story-note">Compact: 미지원. 기존 직원 카드 디자인을 보존하며, 압축 배치 선택은 제공하지 않습니다.</p>
</fieldset>
</StorySection>
<StorySection title="인터랙션·직원 정보" description="Drag & Drop과 탐색 기능을 개별 선택하고 직원 카드의 팝업 방식을 설정합니다.">
<div className="hm-orgchart-story-settings">
<fieldset className="hm-orgchart-story-companies">
<legend>독립 기능 설정 · 모든 표시 유형에서 개별 선택</legend>
<div className="hm-orgchart-story-company">
<Switch id={`${id}-drag-drop`} checked={dragDropEnabled} onCheckedChange={setDragDropEnabled} aria-describedby={`${id}-drag-drop-state`} />
<Label htmlFor={`${id}-drag-drop`}>Drag &amp; Drop</Label>
<span id={`${id}-drag-drop-state`}>{dragDropEnabled ? 'ON' : 'OFF'}</span>
</div>
{([
['collapse', '접기·펼치기 사용'], ['zoom', 'Zoom 사용'], ['pan', 'Pan 사용'],
] as const).map(([key, label]) => <div key={key} className="hm-orgchart-story-company">
<Checkbox id={`${id}-interaction-${key}`} checked={interactions[key]} onCheckedChange={checked => setInteractions(current => ({ ...current, [key]: checked === true }))} />
<Label htmlFor={`${id}-interaction-${key}`}>{label}</Label>
</div>)}
</fieldset>
<div className="hm-orgchart-story-controls">
<div className="hm-orgchart-story-instance hm-orgchart-story-popup-setting">
<Label id={`${id}-popup-label`} htmlFor={`${id}-popup`}>직원 정보 팝업</Label>
<Select value={popup} onValueChange={value => setPopup(value as OrgChartProps['employeePopup'])}>
<SelectTrigger id={`${id}-popup`} aria-labelledby={`${id}-popup-label`} size="medium"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="hm-dialog">HMDesign Dialog</SelectItem><SelectItem value="core">Core 기본 팝업</SelectItem><SelectItem value="none">사용 안 함</SelectItem></SelectContent>
</Select>
</div>
</div>
</div>
<Button variant="secondary" appearance="outline" onClick={() => setSelected(undefined)}>전체 회사</Button>
<Button variant="secondary" appearance="outline" onClick={() => setSelected([])}>선택 해제</Button>
</div>
<fieldset className="hm-orgchart-story-companies">
<legend>표시할 회사 · 복수 선택 가능</legend>
{companies.map(company => <div key={company.id} className="hm-orgchart-story-company">
<Checkbox id={`${id}-${company.id}`} checked={visible.includes(company.id)} onCheckedChange={checked => setSelected(checked === true ? [...visible, company.id] : visible.filter(value => value !== company.id))} />
<Label htmlFor={`${id}-${company.id}`}>{company.name}</Label>
<span className="hm-orgchart-story-note">{companyColorPresets[company.id as keyof typeof companyColorPresets].primary}</span>
</div>)}
</fieldset>
<OrgChart dataSource={sources[size]} stylesheetUrls={compositionStylesheets} displayMode="readOnly" layoutMode="auto" selectedCompanyIds={selected} companyTopNodes={topNodes} employeeConnections={connections} className="hm-orgchart-story-chart" />
</section>;
</StorySection>
<StorySection title="조직도 미리보기" description="직원 카드를 눌러 정보를 확인하고, 활성화한 탐색 기능으로 조직도를 살펴봅니다.">
<div className="hm-orgchart-story">
<p className="hm-orgchart-story-note">빈 공간 드래그는 Pan입니다. {dragDropEnabled ? '직원 카드·그룹 타이틀 드래그로 회사 안팎의 소속을 변경합니다. 키보드: Alt+M → 방향키 → Enter / ESC 취소.' : '소속 변경은 Drag & Drop을 ON으로 설정하면 사용할 수 있습니다.'} 클릭은 직원 정보·그룹 접기입니다.</p>
<p className="hm-orgchart-story-note" data-component="OrgChartExampleCounts" aria-live="polite">
표시 중: {applied.companyIds.length}개 회사 · 현재 소속 기준 직원 합계 {displayedTotal.toLocaleString('ko-KR')}명 / 전체 {sessionTotal.toLocaleString('ko-KR')}명
{companyCountSummary ? ` · ${companyCountSummary}` : ''}
</p>
{error ? <p role="alert" className="hm-orgchart-story-note">{error}</p> : null}
<div className="hm-orgchart-story-preview sb-center">
<OrgChart dataSource={source} stylesheetUrls={compositionStylesheets} displayMode="readOnly" layoutMode="auto" autoLayout={layout} interactions={interactions} dragDropEnabled={dragDropEnabled} selectedCompanyIds={applied.companyIds} companyTopNodes={topNodes} employeePopup={popup} className="hm-orgchart-story-chart" onMove={result => { if (result.moved) setSession({ baseline: dataset, current: result.data }); }} onLifecycleError={cause => setError(cause instanceof Error ? cause.message : '조직도 설정을 적용할 수 없습니다.')} onStateChange={state => { if (state.status === 'error') setError(state.issues.map(issue => issue.message).join(' / ')); }} />
</div>
</div>
</StorySection>
</StoryPage>;
}
const meta = { title: 'OrgChart', component: ExpandedPreview, parameters: { layout: 'padded', controls: { disable: true } }, decorators: [(Story) => <StrictMode><Story /></StrictMode>] } satisfies Meta<typeof ExpandedPreview>;
const meta = { title: 'OrgChart/Expanded OrgChart', component: ExpandedPreview, parameters: { layout: 'fullscreen', controls: { disable: true } }, decorators: [(Story) => <StrictMode><Story /></StrictMode>] } satisfies Meta<typeof ExpandedPreview>;
export default meta;
type Story = StoryObj<typeof meta>;
export const ExpandedOrgChart: Story = { name: 'Expanded OrgChart' };
export const ExpandedOrgChart: Story = { name: 'Expanded OrgChart', parameters: { __id: 'orgchart--expanded-org-chart' } };