/**
* Dialogs of the modify / level / selection commands: pick levels (copy to
* levels, paste aligned to selected levels), duplicate level, edit level
* (name, number, elevation, move the levels above), selection filter, save
* selection, and the keyboard shortcut cheat sheet.
*/
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { useEditorDispatch, useEditorState } from '../state/EditorContext.tsx';
import { openDialog, showNotice, useModifyUi, type ModifyDialog } from '../state/modifyUi.ts';
import { filterSelection, selectionCategories } from '../state/selectionOps.ts';
import { pasteAligned, readClipboard } from '../state/clipboardCommands.ts';
import { LAYER_STYLES } from '../types.ts';
import { formatElevation, getProjectUnits } from '../utils/units.ts';
import { SINGLE_KEYS, TWO_LETTER, type Shortcut, type ShortcutGroup } from '../tools/shortcuts.ts';
import { Input } from './ui/input';
import RenumberDialog from './RenumberDialog.tsx';
import { FLOOR_SLAB_TABLES } from '../state/levelEdits.ts';
import { toElementId } from '../model/ids.ts';
import { cn } from '../lib/utils';
import { levelLabel } from '../model/displayNames.ts';
const primary = 'cursor-pointer rounded border-none bg-[var(--color-accent)] px-3 py-1.5 text-[11px] font-medium text-white hover:opacity-90 disabled:opacity-40';
const secondary = 'cursor-pointer rounded border border-border bg-transparent px-3 py-1.5 text-[11px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground';
const label = 'mb-1 block text-[10px] font-medium uppercase tracking-wide text-muted-foreground';
function Modal({ title, onClose, children, wide, testId }: { title: string; onClose: () => void; children: ReactNode; wide?: boolean; testId?: string }) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopPropagation();
onClose();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [onClose]);
return (
{ if (e.target === e.currentTarget) onClose(); }}>
);
}
function Buttons({ onClose, onOk, okLabel, disabled }: { onClose: () => void; onOk: () => void; okLabel: string; disabled?: boolean }) {
const { t } = useTranslation();
return (
);
}
function LevelsDialog({ mode, onClose }: { mode: 'copy' | 'paste'; onClose: () => void }) {
const { t } = useTranslation();
const state = useEditorState();
const dispatch = useEditorDispatch();
const unit = getProjectUnits(state);
const levels = [...(state.project?.levels ?? [])].reverse();
const [picked, setPicked] = useState>(new Set());
const [roofOnTop, setRoofOnTop] = useState(true);
const toggle = (id: string) => setPicked(p => { const n = new Set(p); if (n.has(id)) n.delete(id); else n.add(id); return n; });
// Copying floor slabs to the top level: offer to make them roof slabs.
const topId = levels[0]?.id;
const hasFloorSlabs = mode === 'copy' && [...state.selectedIds].some(sid => {
const el = state.document?.elements.get(toElementId(sid));
return !!el && FLOOR_SLAB_TABLES.has(el.tableName) && (el.attrs.function || 'floor') === 'floor';
});
const ok = async () => {
const ids = [...picked];
if (mode === 'copy') {
dispatch({ type: 'COPY_TO_LEVELS', ids: [...state.selectedIds], levelIds: ids, roofOnTop: hasFloorSlabs && roofOnTop });
showNotice('notice.copiedToLevels', { count: ids.length });
return;
}
const p = await readClipboard();
if (!p) { showNotice('notice.clipboardEmpty'); return; }
const err = pasteAligned(state, dispatch, p, { levels: ids });
showNotice(err ?? 'notice.pastedToLevels', { count: ids.length });
};
return (
{levels.map(l => {
const disabled = mode === 'copy' && l.id === state.currentLevel;
return (
);
})}
{hasFloorSlabs && topId && picked.has(topId) && (
)}
);
}
function nextLevelId(levels: { id: string }[]): { id: string; n: number } {
const ids = new Set(levels.map(l => l.id));
let n = 1;
while (ids.has(`lv-${n}`)) n++;
return { id: `lv-${n}`, n };
}
function DuplicateLevelDialog({ levelId, onClose }: { levelId: string; onClose: () => void }) {
const { t } = useTranslation();
const state = useEditorState();
const dispatch = useEditorDispatch();
const levels = state.project?.levels ?? [];
const src = levels.find(l => l.id === levelId);
const sorted = [...levels].sort((a, b) => a.elevation - b.elevation);
const top = sorted[sorted.length - 1];
const storey = (() => {
const i = sorted.findIndex(l => l.id === levelId);
const above = sorted[i + 1];
return above && src ? above.elevation - src.elevation : 3;
})();
const [name, setName] = useState(`${src?.name || levelId} ${t('levels.copySuffix')}`);
const [elevation, setElevation] = useState(String(Math.round(((top?.elevation ?? 0) + (storey > 0 ? storey : 3)) * 1000) / 1000));
const ok = () => {
const e = parseFloat(elevation);
if (!Number.isFinite(e)) return;
const { id, n } = nextLevelId(levels);
dispatch({ type: 'DUPLICATE_LEVEL', levelId, level: { id, number: String(n), name: name.trim() || id, elevation: e } });
showNotice('notice.levelDuplicated', { name: name.trim() || id });
};
return (
{t('levels.duplicateHint', { name: src?.name || levelId })}
setName(e.target.value)} autoFocus data-testid="dup-name" />
setElevation(e.target.value)} data-testid="dup-elevation" />
);
}
function EditLevelDialog({ levelId, onClose }: { levelId: string; onClose: () => void }) {
const { t } = useTranslation();
const state = useEditorState();
const dispatch = useEditorDispatch();
const level = state.project?.levels.find(l => l.id === levelId);
const [name, setName] = useState(level?.name ?? '');
const [number, setNumber] = useState(level?.number ?? '');
const [elevation, setElevation] = useState(String(level?.elevation ?? 0));
const [moveAbove, setMoveAbove] = useState(true);
if (!level) return null;
const e = parseFloat(elevation);
const changed = Number.isFinite(e) && e !== level.elevation;
const ok = () => {
if (!Number.isFinite(e)) return;
dispatch({ type: 'RENAME_LEVEL', levelId, name: name.trim() || level.name, number: number.trim() || level.number, elevation: e, moveAbove: changed && moveAbove });
};
return (
setName(ev.target.value)} autoFocus />
setNumber(ev.target.value)} />
setElevation(ev.target.value)} data-testid="level-elevation" />
{changed && (
)}
{t('levels.elevationRule')}
);
}
function FilterDialog({ onClose }: { onClose: () => void }) {
const { t } = useTranslation();
const state = useEditorState();
const dispatch = useEditorDispatch();
const cats = useMemo(() => selectionCategories(state), [state]);
const [keep, setKeep] = useState>(() => new Set(cats.map(c => c.table)));
const total = cats.reduce((n, c) => n + (keep.has(c.table) ? c.count : 0), 0);
return (
{cats.map(c => {
const style = LAYER_STYLES[c.table];
return (
);
})}
{t('filter.total', { count: total })}
filterSelection(state, dispatch, keep)} okLabel={t('type.ok')} disabled={keep.size === 0} />
);
}
/** VV: Revit's Visibility/Graphics — which categories the view draws. */
function VisibilityDialog({ onClose }: { onClose: () => void }) {
const { t } = useTranslation();
const state = useEditorState();
const dispatch = useEditorDispatch();
const cats = useMemo(() => {
const keys = new Map();
for (const floor of state.project?.floors.values() ?? []) {
for (const l of floor.layers) keys.set(`${l.discipline}/${l.tableName}`, l.tableName);
}
for (const gl of state.project?.globalLayers ?? []) keys.set(`${gl.discipline}/${gl.tableName}`, gl.tableName);
if (state.grids.length) keys.set('reference/grid', 'grid');
return [...keys].map(([key, table]) => ({ key, table }))
.sort((a, b) => (LAYER_STYLES[a.table]?.order ?? 99) - (LAYER_STYLES[b.table]?.order ?? 99));
}, [state.project, state.grids]);
const [shown, setShown] = useState>(() => new Set(cats.filter(c => state.visibleLayers.has(c.key)).map(c => c.key)));
const apply = () => {
const next = new Set(state.visibleLayers);
for (const c of cats) { if (shown.has(c.key)) next.add(c.key); else next.delete(c.key); }
dispatch({ type: 'SET_VISIBLE_LAYERS', keys: next });
};
return (
{cats.map(c => {
const style = LAYER_STYLES[c.table];
return (
);
})}
);
}
function SaveSetDialog({ onClose }: { onClose: () => void }) {
const { t } = useTranslation();
const dispatch = useEditorDispatch();
const state = useEditorState();
const [name, setName] = useState(() => `${t('selectionSet.default')} ${(state.selectionSets?.length ?? 0) + 1}`);
const ref = useRef(null);
useEffect(() => { setTimeout(() => ref.current?.select(), 0); }, []);
return (
setName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') { dispatch({ type: 'SAVE_SELECTION_SET', name }); onClose(); } }} />
dispatch({ type: 'SAVE_SELECTION_SET', name })} okLabel={t('dialog.save')} disabled={!name.trim()} />
);
}
const GROUP_ORDER: ShortcutGroup[] = ['draw', 'modify', 'annotate', 'select', 'view'];
/** One row per command: its two-letter and single-key shortcuts together. */
function merged(list: Shortcut[]): [string, string[]][] {
const byLabel = new Map();
for (const s of list) byLabel.set(s.labelKey, [...(byLabel.get(s.labelKey) ?? []), s.keys]);
return [...byLabel];
}
export function ShortcutsPanel({ onClose }: { onClose: () => void }) {
const { t } = useTranslation();
const rows = (list: Shortcut[], g: ShortcutGroup) => list.filter(s => s.group === g);
return (
{t('shortcut.intro')}
{GROUP_ORDER.map(g => (
{t(`shortcut.group.${g}`)}
{merged([...rows(TWO_LETTER, g), ...rows(SINGLE_KEYS, g)]).map(([labelKey, keys]) => (
{t(labelKey)}
{keys.map(k => {k})}
))}
))}
);
}
export default function ModifyDialogs() {
const ui = useModifyUi();
const close = () => openDialog(null);
const d: ModifyDialog | null = ui.dialog;
if (!d) return null;
switch (d.kind) {
case 'levels': return ;
case 'duplicateLevel': return ;
case 'editLevel': return ;
case 'filter': return ;
case 'saveSet': return ;
case 'shortcuts': return ;
case 'renumber': return ;
case 'visibility': return ;
}
}