@floless/app 0.132.0 → 0.132.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,624 @@
1
+ /*
2
+ * steel-catalog-picker.js — environment-neutral catalogue browsing for the native steel editor.
3
+ *
4
+ * The editor owns WHAT a choice changes (Member.profile or Member.material). This module owns only
5
+ * catalogue view computation and two sibling dialogs. US/AISC and US/ASTM are today's providers;
6
+ * neither the search/list component nor the contract mutation knows that they are permanent.
7
+ */
8
+
9
+ export const MATERIAL_DEFAULT = '__profile_default__';
10
+
11
+ export function materialCatalogFor(environment, installedCatalog) {
12
+ return materialCatalogDescriptorFor(environment, installedCatalog)?.rows || [];
13
+ }
14
+
15
+ export function materialCatalogDescriptorFor(environment, installedCatalog) {
16
+ const wanted = String(environment || '').toUpperCase();
17
+ const installed = String(installedCatalog?.environment?.id || installedCatalog?.environment || '').toUpperCase();
18
+ return installed && installed === wanted ? installedCatalog : null;
19
+ }
20
+
21
+ export function materialNavigation(catalog) {
22
+ return [...(catalog?.navigation || [])];
23
+ }
24
+
25
+ export function normalizeCatalogText(value) {
26
+ return String(value == null ? '' : value)
27
+ .trim().toUpperCase()
28
+ .replace(/[×✕✖]/g, 'X')
29
+ .replace(/[‐-―−]/g, '-')
30
+ .replace(/[‘’ʹ′]/g, "'")
31
+ .replace(/[“”ʺ″]/g, '"')
32
+ .replace(/\u00a0/g, ' ')
33
+ .replace(/\s+/g, '');
34
+ }
35
+
36
+ const COLLATOR = new Intl.Collator('en', { numeric: true, sensitivity: 'base' });
37
+ export function naturalProfileCompare(a, b) {
38
+ return COLLATOR.compare(typeof a === 'string' ? a : a.designation, typeof b === 'string' ? b : b.designation);
39
+ }
40
+
41
+ function propertyKey(row, map) {
42
+ const candidates = [row.designation, ...(row.aliases || [])].map(normalizeCatalogText);
43
+ return candidates.find((key) => map && Object.prototype.hasOwnProperty.call(map, key)) || candidates[0];
44
+ }
45
+
46
+ export function buildProfileRows(catalog, sections, weights) {
47
+ return (catalog?.rows || []).map((row) => {
48
+ const key = propertyKey(row, weights || sections || {});
49
+ const sec = (sections || {})[key];
50
+ return {
51
+ designation: row.designation,
52
+ family: row.family,
53
+ aliases: [...(row.aliases || [])],
54
+ ...(typeof row.geometrySupported === 'boolean' ? { geometrySupported: row.geometrySupported } : {}),
55
+ ...(row.sectionShape ? { sectionShape: row.sectionShape } : {}),
56
+ depth: sec?.[0] ?? null,
57
+ width: sec?.[1] ?? null,
58
+ web: sec?.[2] ?? null,
59
+ flange: sec?.[3] ?? null,
60
+ weight: (weights || {})[key] ?? null,
61
+ };
62
+ }).sort(naturalProfileCompare);
63
+ }
64
+
65
+ export function profileFamilyGroups(catalog) {
66
+ return [...(catalog?.families || [])];
67
+ }
68
+
69
+ export function profileNavigation(catalog) {
70
+ if (catalog?.navigation?.length) return catalog.navigation;
71
+ return [
72
+ { id: 'all', label: 'All profiles', families: (catalog?.families || []).map(({ id }) => id), count: catalog?.rows?.length || 0 },
73
+ ...(catalog?.families || []).map((group) => ({ ...group, family: group.id, families: [group.id] })),
74
+ ];
75
+ }
76
+
77
+ function queryMatches(haystack, query) {
78
+ const whole = normalizeCatalogText(query);
79
+ if (!whole) return true;
80
+ const hay = normalizeCatalogText(haystack);
81
+ if (hay.includes(whole)) return true;
82
+ const tokens = String(query).trim().split(/\s+/).map(normalizeCatalogText).filter(Boolean);
83
+ return tokens.length > 1 && tokens.every((token) => hay.includes(token));
84
+ }
85
+
86
+ /** @param {any[]} rows @param {{query?: string, family?: string|string[]}} [options] */
87
+ export function filterProfileRows(rows, { query = '', family = 'all' } = {}) {
88
+ const familySet = Array.isArray(family) ? new Set(family) : null;
89
+ return (rows || []).filter((row) => (family === 'all' || (familySet ? familySet.has(row.family) : row.family === family))
90
+ && queryMatches([row.designation, ...(row.aliases || [])].join(' '), query));
91
+ }
92
+
93
+ /** Exact primary first; a unique/equivalent alias resolves to its provider row, conflicting aliases do not. */
94
+ export function resolveProfileCatalogRow(rows, value) {
95
+ const key = normalizeCatalogText(value);
96
+ if (!key) return null;
97
+ const primary = (rows || []).find((row) => normalizeCatalogText(row.designation) === key);
98
+ if (primary) return primary;
99
+ const aliases = (rows || []).filter((row) => (row.aliases || []).some((alias) => normalizeCatalogText(alias) === key));
100
+ if (aliases.length === 1) return aliases[0];
101
+ if (aliases.length > 1) {
102
+ const signature = (row) => JSON.stringify([
103
+ row.family, row.sectionShape, row.depth, row.width, row.web, row.flange, row.weight,
104
+ ]);
105
+ if (new Set(aliases.map(signature)).size === 1) return aliases[0];
106
+ }
107
+ return null;
108
+ }
109
+
110
+ export function filterMaterialRows(rows, query = '') {
111
+ const tokens = String(query).trim().toUpperCase().replace(/[×✕✖]/g, 'X').split(/[^A-Z0-9]+/).filter(Boolean);
112
+ if (!tokens.length) return [...(rows || [])];
113
+ return (rows || []).filter((row) => {
114
+ const names = [row.value, ...(row.aliases || [])].join(' ');
115
+ const structured = `${names} ${row.standard}`.toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean);
116
+ const prose = `${names} ${row.standard} ${row.note}`.toUpperCase();
117
+ // A one-letter grade token (B/C) must be a real designation token. Letting it match the C in
118
+ // "cold-formed" makes "500 C" return Grade B too, which is a materially wrong search result.
119
+ return tokens.every((token) => token.length === 1 ? structured.includes(token) : prose.includes(token));
120
+ });
121
+ }
122
+
123
+ /** Preserve provider-owned category membership while filtering material leaves by row text/aliases. */
124
+ export function filterMaterialNavigation(catalog, rows, query = '') {
125
+ const matches = new Set(filterMaterialRows(rows, query).map((row) => normalizeCatalogText(row.value)));
126
+ return materialNavigation(catalog).map((node) => ({
127
+ ...node,
128
+ children: (node.children || []).filter((child) => matches.has(normalizeCatalogText(child.value))),
129
+ })).filter((node) => node.children.length);
130
+ }
131
+
132
+ export function canApplyCatalogSelection(selected, { error = false, fallbackChosen = false } = {}) {
133
+ return !!selected && selected.geometrySupported !== false && (!error || fallbackChosen);
134
+ }
135
+
136
+ function esc(value) {
137
+ return String(value == null ? '' : value).replace(/[&<>"']/g, (c) => ({
138
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
139
+ })[c]);
140
+ }
141
+
142
+ function ensureStyles(doc) {
143
+ if (doc.getElementById('steelCatalogPickerStyles')) return;
144
+ const style = doc.createElement('style');
145
+ style.id = 'steelCatalogPickerStyles';
146
+ style.textContent = `
147
+ .scp-modal{position:fixed;inset:0;z-index:120;display:none;align-items:center;justify-content:center;padding:24px;color:var(--text);font:12px system-ui,sans-serif}
148
+ .scp-modal.open{display:flex}.scp-backdrop{position:absolute;inset:0;background:rgba(2,6,23,.72);backdrop-filter:blur(2px)}
149
+ .scp-panel{position:relative;width:min(980px,calc(100vw - 48px));height:min(720px,calc(100vh - 48px));display:grid;grid-template-rows:auto auto minmax(0,1fr) auto;background:var(--panel);border:1px solid var(--line);border-radius:10px;box-shadow:0 24px 70px rgba(0,0,0,.55);overflow:hidden}
150
+ .scp-modal.material .scp-panel{width:min(900px,calc(100vw - 48px))}
151
+ .scp-head,.scp-foot{display:flex;align-items:center;gap:10px;padding:12px 14px;border-color:var(--line);background:var(--panel)}
152
+ .scp-head{border-bottom:1px solid var(--line)}.scp-foot{border-top:1px solid var(--line)}
153
+ .scp-title{font-size:14px;font-weight:700}.scp-scope{font-size:11px;color:var(--mut);margin-top:2px}.scp-spacer{flex:1}
154
+ .scp-modal button,.scp-modal input{font:inherit}.scp-modal button{border:1px solid var(--ctrl-border,var(--line));border-radius:6px;background:var(--field);color:var(--text);padding:7px 10px;cursor:pointer}
155
+ .scp-modal button:hover{border-color:var(--brand);background:var(--hover,var(--field))}.scp-modal button.primary{background:var(--brand);border-color:var(--brand);color:#fff;font-weight:650}.scp-modal button.ghost{background:transparent}
156
+ .scp-close{width:30px;height:30px;padding:0!important;display:grid;place-items:center}.scp-modal :focus-visible{outline:2px solid var(--brand);outline-offset:2px}.scp-tree-item:focus-visible{outline:0}.scp-tree-item:focus-visible>.scp-family{outline:2px solid var(--brand);outline-offset:-1px}
157
+ .scp-searchbar{display:flex;align-items:center;gap:10px;padding:10px 14px;border-bottom:1px solid var(--line);background:var(--bg)}
158
+ .scp-searchbar input,.scp-custom input{min-width:0;border:1px solid var(--ctrl-border,var(--line));border-radius:6px;background:var(--field);color:var(--text);padding:8px 10px;outline:0}.scp-searchbar input{flex:1}.scp-count{color:var(--mut);font-variant-numeric:tabular-nums;white-space:nowrap}
159
+ .scp-body{display:grid;grid-template-columns:170px minmax(300px,1fr) 240px;min-height:0;background:var(--bg)}.scp-modal.material .scp-body{grid-template-columns:minmax(0,3fr) minmax(260px,2fr)}
160
+ .scp-families,.scp-results,.scp-details{min-height:0;overflow:auto;scrollbar-width:thin;scrollbar-color:var(--scroll) transparent}.scp-families{padding:10px;border-right:1px solid var(--line)}
161
+ .scp-families::-webkit-scrollbar,.scp-results::-webkit-scrollbar,.scp-details::-webkit-scrollbar{width:8px;height:8px}.scp-families::-webkit-scrollbar-thumb,.scp-results::-webkit-scrollbar-thumb,.scp-details::-webkit-scrollbar-thumb{background:var(--scroll);border-radius:8px}
162
+ .scp-family{display:flex;width:100%;min-height:25px;align-items:center;gap:5px;border:0;border-radius:4px;background:transparent;text-align:left;padding:4px 5px;margin:1px 0;cursor:pointer}.scp-tree-item:hover>.scp-family{background:var(--hover,var(--field))}.scp-tree-item.on>.scp-family{color:var(--info-ink,var(--brand));background:var(--brand-soft,rgba(59,130,246,.12))}.scp-family .n{margin-left:auto;color:var(--mut);font-variant-numeric:tabular-nums}.scp-family .twisty{width:10px;flex:0 0 10px;color:var(--mut);font-size:9px;transition:transform .12s ease}.scp-tree-item[aria-expanded=true]>.scp-family .twisty{transform:rotate(90deg);color:var(--brand)}.scp-tree-group{padding-left:14px}.scp-tree-group[hidden]{display:none}
163
+ .scp-modal.material .scp-family{min-height:28px}.scp-modal.material .scp-tree-group .scp-family{font-weight:400}.scp-modal.material .scp-tree-item[aria-expanded]>.scp-family{font-weight:650}
164
+ .scp-material-browser{min-height:0;display:flex;flex-direction:column;border-right:1px solid var(--line);background:var(--bg)}.scp-material-browser .scp-families{flex:1;border-right:0}.scp-material-actions{flex:none;padding:10px 10px 7px;border-bottom:1px solid var(--line)}
165
+ .scp-semantic{width:100%;display:flex!important;align-items:center;gap:9px;text-align:left;padding:8px 9px!important;background:transparent!important;border-color:transparent!important}.scp-semantic:hover{background:var(--field)!important}.scp-semantic[aria-pressed=true]{background:var(--brand-soft,rgba(59,130,246,.14))!important;border-color:var(--brand)!important}.scp-semantic .icon{color:var(--brand);font-size:14px}.scp-semantic .label{font-weight:650}.scp-semantic .meta{display:block;color:var(--mut);font-size:11px;margin-top:2px}.scp-material-current[hidden]{display:none!important}
166
+ .scp-tree-state{flex:none;color:var(--mut);padding:12px 14px 16px;text-align:center}.scp-tree-state[hidden]{display:none}.scp-tree-state .scp-clear{margin-top:9px}
167
+ .scp-option.default{margin-bottom:9px!important;border-bottom-color:var(--line)!important}.scp-option.current .name{color:var(--warn)}
168
+ .scp-results{padding:8px}.scp-option{width:100%;display:grid;grid-template-columns:minmax(130px,1fr) 72px 84px;align-items:center;gap:8px;text-align:left;margin:0 0 3px;padding:8px 9px!important;background:transparent!important;border-color:transparent!important}.scp-option:hover{background:var(--field)!important}.scp-option.on{background:var(--brand-soft,rgba(59,130,246,.14))!important;border-color:var(--brand)!important}.scp-option .name{font-weight:650}.scp-option .meta{color:var(--mut);text-align:right;font-variant-numeric:tabular-nums}.scp-option.default{grid-template-columns:1fr}.scp-option.default .name:before{content:'↺';display:inline-block;margin-right:8px;color:var(--brand)}
169
+ .scp-details{width:auto;box-sizing:border-box;border-left:1px solid var(--line);padding:14px;background:var(--panel)}.scp-preview{height:126px;display:grid;place-items:center;border:1px solid var(--line);border-radius:8px;background:var(--bg);margin-bottom:12px}.scp-preview svg{width:110px;height:94px;color:var(--brand)}
170
+ .scp-modal.material .scp-details{border-left:0}
171
+ .scp-detail-name{font-size:15px;font-weight:750;margin-bottom:3px}.scp-detail-sub{color:var(--mut);margin-bottom:12px}.scp-fact-group{margin-top:14px}.scp-fact-group h4{margin:0 0 3px;color:var(--mut);font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.04em}.scp-facts{display:grid;grid-template-columns:1fr auto;gap:0}.scp-facts dt,.scp-facts dd{margin:0;padding:6px 0;border-bottom:1px solid var(--line)}.scp-facts dt{color:var(--mut)}.scp-facts dd{text-align:right;font-variant-numeric:tabular-nums}.scp-note{line-height:1.5;color:var(--mut)}.scp-warning{margin-top:10px;color:var(--warn);line-height:1.45}
172
+ .scp-custom{margin-top:14px;padding-top:12px;border-top:1px solid var(--line)}.scp-custom label{display:block;color:var(--mut);font-size:11px;font-weight:650;margin-bottom:5px}.scp-custom .row{display:flex;gap:6px}.scp-custom input{width:100%}
173
+ .scp-empty,.scp-error{height:100%;display:grid;place-items:center;text-align:center;color:var(--mut);padding:30px}.scp-error b{display:block;color:var(--warn);font-size:13px;margin-bottom:5px}.scp-clear{margin-top:10px}.scp-source{color:var(--mut);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.scp-applyhint{color:var(--mut);margin-left:auto}.scp-more{width:100%;margin-top:5px!important;background:transparent!important;color:var(--brand)!important}
174
+ @media(max-width:760px){.scp-modal{padding:10px}.scp-panel,.scp-modal.material .scp-panel{width:calc(100vw - 20px);height:calc(100vh - 20px)}.scp-body{grid-template-columns:1fr;grid-template-rows:minmax(140px,180px) minmax(230px,1fr) auto}.scp-modal.material .scp-body{grid-template-columns:1fr;grid-template-rows:minmax(230px,1fr) minmax(170px,auto)}.scp-families{overflow:auto;border-right:0;border-bottom:1px solid var(--line);padding:7px}.scp-material-browser{border-right:0;border-bottom:1px solid var(--line)}.scp-material-browser .scp-families{border-bottom:0}.scp-details{border-left:0;border-top:1px solid var(--line);max-height:230px}.scp-modal.material .scp-details{border-top:0}.scp-preview{display:none}.scp-foot{flex-wrap:wrap}.scp-source{width:100%}}
175
+ `;
176
+ doc.head.appendChild(style);
177
+ }
178
+
179
+ function schematic(family) {
180
+ const f = String(family || '').toUpperCase();
181
+ const common = 'fill="none" stroke="currentColor" stroke-width="7" stroke-linejoin="round" stroke-linecap="round"';
182
+ if (f === 'HSS') return `<svg viewBox="0 0 100 100" aria-hidden="true"><rect x="17" y="17" width="66" height="66" rx="4" ${common}/><rect x="31" y="31" width="38" height="38" rx="2" ${common}/></svg>`;
183
+ if (f === 'PIPE' || f === 'CHS') return `<svg viewBox="0 0 100 100" aria-hidden="true"><circle cx="50" cy="50" r="34" ${common}/><circle cx="50" cy="50" r="21" ${common}/></svg>`;
184
+ if (f === 'RE') return `<svg viewBox="0 0 100 100" aria-hidden="true"><circle cx="50" cy="50" r="31" fill="currentColor"/><path d="M28 40L72 60M28 60L72 40" fill="none" stroke="var(--panel)" stroke-width="4" stroke-linecap="round"/></svg>`;
185
+ if (f === 'L') return `<svg viewBox="0 0 100 100" aria-hidden="true"><path d="M25 18V78H82" ${common}/></svg>`;
186
+ if (f === '2L') return `<svg viewBox="0 0 100 100" aria-hidden="true"><path d="M18 24H43V82M82 24H57V82" ${common}/></svg>`;
187
+ if (f === 'C' || f === 'MC') return `<svg viewBox="0 0 100 100" aria-hidden="true"><path d="M76 20H30V80H76" ${common}/></svg>`;
188
+ if (f === 'WT' || f === 'MT' || f === 'ST') return `<svg viewBox="0 0 100 100" aria-hidden="true"><path d="M18 24H82M50 24V82" ${common}/></svg>`;
189
+ if (f === 'W' || f === 'M' || f === 'S' || f === 'HP') return `<svg viewBox="0 0 100 100" aria-hidden="true"><path d="M18 20H82M50 20V80M18 80H82" ${common}/></svg>`;
190
+ return '';
191
+ }
192
+
193
+ function factsHtml(row) {
194
+ const facts = [];
195
+ if (row.depth != null) facts.push(['Depth', `${row.depth}"`]);
196
+ if (row.width != null) facts.push(['Width', `${row.width}"`]);
197
+ if (row.web != null) facts.push(['Web / wall', `${row.web}"`]);
198
+ if (row.flange != null) facts.push(['Flange', `${row.flange}"`]);
199
+ if (row.weight != null) facts.push(['Weight', `${row.weight} lb/ft`]);
200
+ return facts.length
201
+ ? `<dl class=scp-facts>${facts.map(([k, v]) => `<dt>${esc(k)}</dt><dd>${esc(v)}</dd>`).join('')}</dl>`
202
+ : '<div class=scp-note>Section dimensions and weight are unavailable for this catalog entry.</div>';
203
+ }
204
+
205
+ function materialFactsHtml(row) {
206
+ const groups = new Map();
207
+ for (const fact of row.facts || []) {
208
+ if (!fact || fact.value == null || !fact.label || fact.unit == null) continue;
209
+ const group = fact.group || 'Properties';
210
+ if (!groups.has(group)) groups.set(group, []);
211
+ groups.get(group).push(fact);
212
+ }
213
+ return [...groups].map(([group, facts]) => `<section class=scp-fact-group><h4>${esc(group)}</h4><dl class=scp-facts>${facts.map((fact) => `<dt>${esc(fact.label)}</dt><dd>${esc(`${fact.value}${fact.unit ? ` ${fact.unit}` : ''}`)}</dd>`).join('')}</dl></section>`).join('');
214
+ }
215
+
216
+ /** Create one dialog instance. Call twice: once for Profile, once for Material. */
217
+ export function createCatalogPicker({ kind, catalog, rows, onRetry, document: doc = globalThis.document } = {}) {
218
+ if (!doc) throw new Error('createCatalogPicker requires a document');
219
+ ensureStyles(doc);
220
+ const isMaterial = kind === 'material';
221
+ const modal = doc.createElement('div');
222
+ modal.className = `scp-modal ${isMaterial ? 'material' : 'profile'}`;
223
+ modal.id = isMaterial ? 'materialPickerModal' : 'profilePickerModal';
224
+ modal.setAttribute('role', 'dialog');
225
+ modal.setAttribute('aria-modal', 'true');
226
+ modal.setAttribute('aria-labelledby', `${modal.id}Title`);
227
+ const pickerBody = isMaterial
228
+ ? `<div class=scp-material-browser><div class=scp-material-actions><button data-command-id="steel.catalog-material-default" class="scp-semantic scp-material-default" type=button aria-pressed=false><span class=icon aria-hidden=true>↺</span><span><span class=label>Use profile default</span><span class=meta>Automatic per member profile</span></span></button><button data-command-id="steel.catalog-material-current" class="scp-semantic scp-material-current" type=button aria-pressed=false hidden><span class=icon aria-hidden=true>•</span><span><span class=label></span><span class=meta>Current model value · not in this catalog</span></span></button></div><nav class=scp-families role=tree aria-label="Material categories and materials"></nav><div class=scp-tree-state role=status aria-live=polite hidden></div></div><aside class=scp-details></aside>`
229
+ : `<nav class=scp-families role=tree aria-label="Profile categories"></nav><div class=scp-results role=listbox aria-label="Profiles"></div><aside class=scp-details></aside>`;
230
+ modal.innerHTML = `<div class=scp-backdrop></div><div class=scp-panel>
231
+ <div class=scp-head><div><div class=scp-title id=${modal.id}Title>${isMaterial ? 'Select material' : 'Select profile'}</div><div class=scp-scope></div></div><span class=scp-spacer></span><button data-command-id="steel.dialog-close#the ${isMaterial ? 'material' : 'profile'} picker" class="scp-close ghost" aria-label="Close" data-tip="Close">✕</button></div>
232
+ <div class=scp-searchbar><input data-command-id="steel.catalog-search#${isMaterial ? 'materials' : 'profiles'}" class=scp-search autocomplete=off aria-label="Search ${isMaterial ? 'materials' : 'profiles'}" placeholder="Search ${isMaterial ? 'material name or alias' : 'designation or alias'}"><span class=scp-count role=status aria-live=polite></span></div>
233
+ <div class=scp-body>${pickerBody}</div>
234
+ <div class=scp-foot><span class=scp-source></span><span class=scp-spacer></span><span class=scp-applyhint role=status aria-live=polite>Choose a ${isMaterial ? 'material' : 'profile'}</span><button data-command-id="steel.catalog-cancel" class="scp-cancel ghost">Cancel</button><button data-command-id="steel.catalog-apply" class="scp-apply primary" hidden>Apply</button></div>
235
+ </div>`;
236
+ doc.body.appendChild(modal);
237
+
238
+ const panel = modal.querySelector('.scp-panel');
239
+ const search = modal.querySelector('.scp-search');
240
+ const familyNav = modal.querySelector('.scp-families');
241
+ const results = modal.querySelector('.scp-results');
242
+ const treeState = modal.querySelector('.scp-tree-state');
243
+ const materialDefault = modal.querySelector('.scp-material-default');
244
+ const materialCurrent = modal.querySelector('.scp-material-current');
245
+ const details = modal.querySelector('.scp-details');
246
+ const count = modal.querySelector('.scp-count');
247
+ const source = modal.querySelector('.scp-source');
248
+ const apply = modal.querySelector('.scp-apply');
249
+ const hint = modal.querySelector('.scp-applyhint');
250
+ let config = null, family = 'all', selected = null, visible = 300, filtered = [], invoker = null;
251
+ let resultFocusIndex = 0;
252
+ let treeFocusId = isMaterial ? (materialNavigation(catalog)[0]?.id || '') : 'all', fallbackChosen = false;
253
+ let expanded = new Set();
254
+
255
+ function availableRows() {
256
+ const base = [...(rows || [])];
257
+ if (isMaterial) {
258
+ const out = [{ value: MATERIAL_DEFAULT, standard: 'Use profile default', note: 'No explicit material is stored; each member follows the default for its own profile.', default: true }, ...base];
259
+ const current = config?.current;
260
+ if (current && !base.some((row) => normalizeCatalogText(row.value) === normalizeCatalogText(current))) {
261
+ out.splice(1, 0, { value: current, standard: 'Current model value · not in this catalog', note: 'This project value is stored exactly as entered.', custom: true, current: true });
262
+ }
263
+ return out;
264
+ }
265
+ const current = config?.current;
266
+ if (current && !resolveProfileCatalogRow(base, current)) {
267
+ base.unshift({ designation: current, family: '__current', aliases: [], current: true, depth: null, width: null, web: null, flange: null, weight: null });
268
+ }
269
+ return base;
270
+ }
271
+
272
+ function rowValue(row) { return isMaterial ? row.value : row.designation; }
273
+ function optionRows() {
274
+ const all = availableRows();
275
+ if (config?.error) return [];
276
+ if (isMaterial) return [];
277
+ if (family === '__current') return filterProfileRows(all, { query: search.value, family });
278
+ const node = findNavigationNode(family);
279
+ return filterProfileRows(all, { query: search.value, family: family === 'all' ? 'all' : (node?.families || node?.family || 'all') });
280
+ }
281
+
282
+ function navigation() { return isMaterial ? materialNavigation(catalog) : profileNavigation(catalog); }
283
+ function findNavigationNode(id) {
284
+ const pending = [...navigation()];
285
+ while (pending.length) {
286
+ const node = pending.shift();
287
+ if (node.id === id) return node;
288
+ pending.unshift(...(node.children || []));
289
+ }
290
+ return null;
291
+ }
292
+
293
+ function materialRow(value) {
294
+ return (rows || []).find((row) => normalizeCatalogText(row.value) === normalizeCatalogText(value)) || null;
295
+ }
296
+
297
+ function materialParentForNode(id) {
298
+ return materialNavigation(catalog).find((node) => (node.children || []).some((child) => child.id === id)) || null;
299
+ }
300
+
301
+ function materialLeafForValue(value) {
302
+ for (const parent of materialNavigation(catalog)) {
303
+ const leaf = (parent.children || []).find((child) => normalizeCatalogText(child.value) === normalizeCatalogText(value));
304
+ if (leaf) return { parent, leaf };
305
+ }
306
+ return null;
307
+ }
308
+
309
+ function treeRow(node, parent = '') {
310
+ if (isMaterial) {
311
+ const hasChildren = !!node.children?.length;
312
+ const open = hasChildren && (!!search.value.trim() || expanded.has(node.id));
313
+ if (hasChildren) {
314
+ const countValue = node.count ?? node.children.length;
315
+ return `<div data-command-id="steel.catalog-category#${esc(node.label)}" class=scp-tree-item role=treeitem tabindex="${treeFocusId === node.id ? '0' : '-1'}" data-node="${esc(node.id)}" aria-expanded="${open}" aria-label="${esc(node.label)}, ${countValue} ${countValue === 1 ? 'material' : 'materials'}"><div class=scp-family><span class=twisty aria-hidden=true>▶</span><span>${esc(node.label)}</span><span class=n aria-hidden=true>${countValue}</span></div><div class=scp-tree-group role=group${open ? '' : ' hidden'}>${node.children.map((child) => treeRow(child, node)).join('')}</div></div>`;
316
+ }
317
+ const active = selected && normalizeCatalogText(rowValue(selected)) === normalizeCatalogText(node.value);
318
+ return `<div data-command-id="steel.catalog-material#${esc(node.value)}" class="scp-tree-item${active ? ' on' : ''}" role=treeitem tabindex="${treeFocusId === node.id ? '0' : '-1'}" data-node="${esc(node.id)}" data-parent="${esc(parent.id)}" data-value="${esc(node.value)}" aria-selected="${!!active}" aria-label="${esc(node.label)}, ${esc(parent.label)} material"><div class=scp-family><span class=twisty aria-hidden=true></span><span>${esc(node.label)}</span></div></div>`;
319
+ }
320
+ const hasChildren = !!node.children?.length;
321
+ const open = expanded.has(node.id);
322
+ const active = family === node.id;
323
+ const countValue = isMaterial ? (node.values || []).length : (node.id === 'all' ? availableRows().length : node.count);
324
+ const itemName = isMaterial ? 'material' : 'profile';
325
+ const countLabel = `${countValue} ${countValue === 1 ? itemName : `${itemName}s`}`;
326
+ const row = `<div data-command-id="steel.catalog-category#${esc(node.label)}" class="scp-tree-item${active ? ' on' : ''}" role=treeitem tabindex="${treeFocusId === node.id ? '0' : '-1'}" data-node="${esc(node.id)}"${parent ? ` data-parent="${esc(parent)}"` : ''} aria-selected="${active}"${hasChildren ? ` aria-expanded="${open}"` : ''} aria-label="${esc(node.label)}, ${countLabel}"><div class=scp-family><span class=twisty aria-hidden=true>${hasChildren ? '▶' : ''}</span><span>${esc(node.label)}</span><span class=n aria-hidden=true>${countValue}</span></div>${hasChildren ? `<div class=scp-tree-group role=group${open ? '' : ' hidden'}>${node.children.map((child) => treeRow(child, node.id)).join('')}</div>` : ''}</div>`;
327
+ return row;
328
+ }
329
+
330
+ function renderFamilies() {
331
+ if (isMaterial) {
332
+ const current = availableRows().find((row) => row.current);
333
+ materialDefault.setAttribute('aria-pressed', String(!!selected?.default));
334
+ materialCurrent.hidden = !current;
335
+ if (current) {
336
+ materialCurrent.querySelector('.label').textContent = current.value;
337
+ materialCurrent.setAttribute('aria-pressed', String(!!selected && normalizeCatalogText(rowValue(selected)) === normalizeCatalogText(current.value)));
338
+ }
339
+ if (config?.error) {
340
+ familyNav.hidden = true;
341
+ treeState.hidden = false;
342
+ treeState.innerHTML = `<b>Material catalog unavailable</b><div>${esc(config.error)}</div>${onRetry ? '<button data-command-id="steel.catalog-retry#materials" class=scp-clear>Retry</button>' : ''}`;
343
+ const retry = treeState.querySelector('button'); if (retry) retry.onclick = onRetry;
344
+ count.textContent = '0 materials';
345
+ return;
346
+ }
347
+ familyNav.hidden = false;
348
+ const query = search.value.trim();
349
+ const filteredNavigation = filterMaterialNavigation(catalog, rows, query);
350
+ const matchingCount = filteredNavigation.reduce((sum, node) => sum + node.children.length, 0);
351
+ count.textContent = query ? `${matchingCount.toLocaleString()} ${matchingCount === 1 ? 'match' : 'matches'}` : `${(rows || []).length.toLocaleString()} materials`;
352
+ treeState.hidden = matchingCount > 0 || !query;
353
+ treeState.innerHTML = matchingCount || !query ? '' : `No catalog materials match “${esc(search.value)}”.<br><button data-command-id="steel.catalog-clear-search#materials" class=scp-clear>Clear search</button>`;
354
+ const clear = treeState.querySelector('button'); if (clear) clear.onclick = () => { search.value = ''; renderFamilies(); search.focus(); };
355
+
356
+ const visibleIds = [];
357
+ for (const node of filteredNavigation) {
358
+ visibleIds.push(node.id);
359
+ if (query || expanded.has(node.id)) visibleIds.push(...node.children.map((child) => child.id));
360
+ }
361
+ if (!visibleIds.includes(treeFocusId)) {
362
+ const parent = materialParentForNode(treeFocusId);
363
+ treeFocusId = parent && visibleIds.includes(parent.id) ? parent.id : (visibleIds[0] || '');
364
+ }
365
+ familyNav.innerHTML = filteredNavigation.map((node) => treeRow(node)).join('');
366
+ return;
367
+ }
368
+ familyNav.hidden = false;
369
+ const currentN = isMaterial ? 0 : availableRows().filter((row) => row.family === '__current').length;
370
+ familyNav.innerHTML = navigation().map((node) => treeRow(node)).join('')
371
+ + (currentN ? `<div data-command-id="steel.catalog-category#Current value" class="scp-tree-item${family === '__current' ? ' on' : ''}" role=treeitem tabindex="${treeFocusId === '__current' ? '0' : '-1'}" data-node="__current" aria-selected="${family === '__current'}" aria-label="Current value, ${currentN} profile"><div class=scp-family><span class=twisty aria-hidden=true></span><span>Current value</span><span class=n aria-hidden=true>${currentN}</span></div></div>` : '');
372
+ if (!familyNav.querySelector('[tabindex="0"]')) {
373
+ const first = familyNav.querySelector('.scp-tree-item');
374
+ if (first) { treeFocusId = first.dataset.node; first.tabIndex = 0; }
375
+ }
376
+ }
377
+
378
+ function renderDetails() {
379
+ if (config?.error) {
380
+ const currentValue = isMaterial ? (selected?.value === MATERIAL_DEFAULT ? '' : selected?.value) : selected?.designation;
381
+ details.innerHTML = `<div class=scp-detail-name>Available without the catalog</div><div class=scp-detail-sub>Choose a catalog-independent fallback explicitly.</div>`
382
+ + `<div class=scp-custom><label for=${modal.id}Fallback>Custom ${isMaterial ? 'material' : 'profile'} designation</label><div class=row><input data-command-id="steel.catalog-custom#${isMaterial ? 'material' : 'profile'}" id=${modal.id}Fallback value="${esc(currentValue || '')}" placeholder="${isMaterial ? 'e.g. A913-GR.65' : 'e.g. MF1'}" autocomplete=off><button data-command-id="steel.catalog-use-custom#${isMaterial ? 'material' : 'profile'}" class=scp-error-custom>Use</button></div></div><div class="scp-note scp-fallback-status" role=status aria-live=polite></div>`;
383
+ const status = details.querySelector('.scp-fallback-status');
384
+ const custom = details.querySelector('input');
385
+ const useCustom = () => {
386
+ const value = custom.value.trim();
387
+ if (!value) { custom.focus(); return; }
388
+ selected = isMaterial
389
+ ? { value, standard: 'Custom project designation', note: 'This value is stored exactly as entered.', custom: true }
390
+ : { designation: value, family: '__custom', aliases: [], custom: true, depth: null, width: null, web: null, flange: null, weight: null };
391
+ fallbackChosen = true; status.textContent = `Selected: ${value}`; reflectApply();
392
+ };
393
+ details.querySelector('.scp-error-custom').onclick = useCustom;
394
+ custom.onkeydown = (event) => { if (event.key === 'Enter') { event.preventDefault(); useCustom(); } };
395
+ const useDefault = details.querySelector('.scp-error-default');
396
+ if (useDefault) useDefault.onclick = () => {
397
+ selected = { value: MATERIAL_DEFAULT, standard: 'Use profile default', default: true };
398
+ fallbackChosen = true; status.textContent = 'Selected: Profile default'; reflectApply();
399
+ };
400
+ return;
401
+ }
402
+ if (!selected) {
403
+ details.innerHTML = `<div class=scp-empty><div>Select a ${isMaterial ? 'material' : 'profile'} to inspect it.</div></div>`;
404
+ return;
405
+ }
406
+ if (isMaterial) {
407
+ details.innerHTML = `<div class=scp-detail-name>${selected.default ? 'Profile default' : esc(selected.value)}</div><div class=scp-detail-sub>${esc(selected.standard || '')}</div><div class=scp-note>${esc(selected.note || '')}</div>`
408
+ + ((selected.aliases || []).length ? `<div class=scp-note style="margin-top:10px">Aliases: ${esc(selected.aliases.join(', '))}</div>` : '')
409
+ + (selected.warning ? `<div class=scp-warning>${esc(selected.warning)}</div>` : '')
410
+ + materialFactsHtml(selected)
411
+ + `<div class=scp-custom><label for=${modal.id}Custom>Custom material designation</label><div class=row><input data-command-id="steel.catalog-custom#material" id=${modal.id}Custom value="${selected.custom ? esc(selected.value) : ''}" placeholder="e.g. A913-GR.65" autocomplete=off><button data-command-id="steel.catalog-use-custom#material" class=scp-use-custom>Use</button></div></div>`;
412
+ } else {
413
+ const supported = selected.geometrySupported !== false;
414
+ const preview = supported ? schematic(selected.family) : '';
415
+ details.innerHTML = `<div class=scp-preview>${preview || '<div class=scp-note>Section preview unavailable for this catalog entry.</div>'}</div><div class=scp-detail-name>${esc(selected.designation)}</div><div class=scp-detail-sub>${selected.current ? 'Current model value · not in this catalog' : esc((catalog?.families || []).find((g) => g.id === selected.family)?.label || selected.family)}</div>${factsHtml(selected)}`
416
+ + ((selected.aliases || []).length ? `<div class=scp-note style="margin-top:10px">Related catalog names: ${esc(selected.aliases.join(', '))}</div>` : '')
417
+ + (!supported ? '<div class=scp-warning>This catalog record includes envelope and weight, but not chord or web geometry, so FloLess cannot model this joist faithfully.</div>' : '')
418
+ + `<div class=scp-custom><label for=${modal.id}Custom>Custom / unresolved designation</label><div class=row><input data-command-id="steel.catalog-custom#profile" id=${modal.id}Custom value="${selected.custom ? esc(selected.designation) : ''}" placeholder="e.g. MF1" autocomplete=off><button data-command-id="steel.catalog-use-custom#profile" class=scp-use-custom>Use</button></div></div>`;
419
+ }
420
+ const custom = details.querySelector('input');
421
+ details.querySelector('.scp-use-custom').onclick = () => {
422
+ const value = custom.value.trim();
423
+ if (!value) { custom.focus(); return; }
424
+ selected = isMaterial
425
+ ? { value, standard: 'Custom project designation', note: 'This value is stored exactly as entered.', custom: true }
426
+ : { designation: value, family: '__custom', aliases: [], custom: true, depth: null, width: null, web: null, flange: null, weight: null };
427
+ reflectApply(); renderDetails(); if (isMaterial) renderFamilies(); else renderResults();
428
+ };
429
+ custom.onkeydown = (event) => { if (event.key === 'Enter') { event.preventDefault(); details.querySelector('.scp-use-custom').click(); } };
430
+ }
431
+
432
+ function reflectApply() {
433
+ const value = selected ? rowValue(selected) : '';
434
+ const canApply = canApplyCatalogSelection(selected, { error: !!config?.error, fallbackChosen });
435
+ apply.hidden = !canApply;
436
+ apply.setAttribute('data-command-id', value ? `steel.catalog-apply#${value}` : 'steel.catalog-apply');
437
+ hint.hidden = canApply;
438
+ hint.textContent = selected?.geometrySupported === false
439
+ ? 'Joist geometry unavailable — choose another profile.'
440
+ : `Choose a ${isMaterial ? 'material' : 'profile'}`;
441
+ if (!canApply) return;
442
+ const scope = config?.count > 1 ? ` to ${config.count} members` : '';
443
+ apply.textContent = value === MATERIAL_DEFAULT ? `Use profile default${scope}` : `Apply ${value}${scope}`;
444
+ }
445
+
446
+ function focusProfileResult(index) {
447
+ const options = [...results.querySelectorAll('.scp-option')];
448
+ if (!options.length) return;
449
+ resultFocusIndex = Math.max(0, Math.min(index, options.length - 1));
450
+ options.forEach((option, at) => { option.tabIndex = at === resultFocusIndex ? 0 : -1; });
451
+ options[resultFocusIndex]?.focus();
452
+ options[resultFocusIndex]?.scrollIntoView?.({ block: 'nearest' });
453
+ }
454
+
455
+ function renderResults({ restoreFocus = false } = {}) {
456
+ if (isMaterial) return;
457
+ filtered = optionRows();
458
+ const resultCount = filtered.length;
459
+ count.textContent = `${resultCount.toLocaleString()} ${resultCount === 1 ? 'profile' : 'profiles'}`;
460
+ if (config?.error) {
461
+ results.innerHTML = `<div class=scp-error><div><b>Profile catalog unavailable</b><div>${esc(config.error)}</div>${onRetry ? '<button data-command-id="steel.catalog-retry#profiles" class=scp-clear>Retry</button>' : ''}</div></div>`;
462
+ const retry = results.querySelector('button'); if (retry) retry.onclick = onRetry;
463
+ return;
464
+ }
465
+ if (!filtered.length) {
466
+ results.innerHTML = `<div class=scp-empty><div>No profiles match “${esc(search.value)}”.<br><button data-command-id="steel.catalog-clear-search#profiles" class=scp-clear>Clear search</button></div></div>`;
467
+ results.querySelector('button').onclick = () => { search.value = ''; visible = 300; resultFocusIndex = 0; render(); search.focus(); };
468
+ return;
469
+ }
470
+ const shown = filtered.slice(0, visible);
471
+ resultFocusIndex = Math.max(0, Math.min(resultFocusIndex, shown.length - 1));
472
+ results.innerHTML = shown.map((row, index) => {
473
+ const value = rowValue(row), on = selected && normalizeCatalogText(rowValue(selected)) === normalizeCatalogText(value);
474
+ const dims = row.depth != null && row.width != null ? `${row.depth} × ${row.width} in` : '—';
475
+ return `<button data-command-id="steel.catalog-profile#${esc(row.designation)}" class="scp-option${on ? ' on' : ''}" role=option aria-selected="${on}" tabindex="${index === resultFocusIndex ? '0' : '-1'}" data-index=${index}><span class=name>${esc(row.designation)}</span><span class=meta>${esc(row.family)}</span><span class=meta>${row.weight == null ? '—' : esc(row.weight + ' lb/ft')}</span><span class=sr-only>${esc(dims)}</span></button>`;
476
+ }).join('') + (visible < filtered.length ? `<button data-command-id="steel.catalog-show-more#profiles" class=scp-more>Show ${Math.min(300, filtered.length - visible)} more</button>` : '');
477
+ const clear = results.querySelector('.scp-clear'); if (clear) clear.onclick = () => { search.value = ''; visible = 300; resultFocusIndex = 0; render(); search.focus(); };
478
+ results.querySelectorAll('.scp-option').forEach((button) => {
479
+ button.onclick = () => { resultFocusIndex = Number(button.dataset.index); selected = filtered[resultFocusIndex]; renderResults({ restoreFocus: true }); renderDetails(); reflectApply(); };
480
+ button.ondblclick = () => { selected = filtered[Number(button.dataset.index)]; commit(); };
481
+ button.onkeydown = (event) => {
482
+ const opts = [...results.querySelectorAll('.scp-option')], at = opts.indexOf(button);
483
+ let next = null;
484
+ if (event.key === 'ArrowDown') next = Math.min(opts.length - 1, at + 1);
485
+ else if (event.key === 'ArrowUp') next = Math.max(0, at - 1);
486
+ else if (event.key === 'Home') next = 0;
487
+ else if (event.key === 'End') next = opts.length - 1;
488
+ else if (event.key === 'PageDown') next = Math.min(opts.length - 1, at + 10);
489
+ else if (event.key === 'PageUp') next = Math.max(0, at - 10);
490
+ else if (event.key === 'Enter') { event.preventDefault(); button.click(); if (event.ctrlKey) commit(); return; }
491
+ if (next != null) { event.preventDefault(); focusProfileResult(next); }
492
+ };
493
+ });
494
+ const more = results.querySelector('.scp-more'); if (more) more.onclick = () => { visible += 300; renderResults(); };
495
+ if (restoreFocus) focusProfileResult(resultFocusIndex);
496
+ }
497
+
498
+ function render() { renderFamilies(); renderResults(); renderDetails(); reflectApply(); }
499
+ function commit() {
500
+ if (!config || !canApplyCatalogSelection(selected, { error: !!config.error, fallbackChosen })) return;
501
+ config.onApply(rowValue(selected)); close();
502
+ }
503
+ function close() {
504
+ const returnId = invoker?.id;
505
+ const returnTarget = invoker?.isConnected ? invoker : (returnId ? doc.getElementById(returnId) : null);
506
+ modal.classList.remove('open'); config = null;
507
+ if (returnTarget?.isConnected) returnTarget.focus();
508
+ invoker = null;
509
+ }
510
+
511
+ function open(next) {
512
+ config = next;
513
+ invoker = next.invoker || doc.activeElement;
514
+ family = 'all'; treeFocusId = isMaterial ? (materialNavigation(catalog)[0]?.id || '') : 'all'; fallbackChosen = false;
515
+ expanded = new Set();
516
+ visible = 300; resultFocusIndex = 0; search.value = '';
517
+ selected = null;
518
+ const current = next.current;
519
+ if (current !== null && current !== undefined && current !== '') {
520
+ selected = isMaterial
521
+ ? availableRows().find((row) => normalizeCatalogText(rowValue(row)) === normalizeCatalogText(current)) || null
522
+ : resolveProfileCatalogRow(rows, current);
523
+ if (!selected && isMaterial) selected = { value: current, standard: 'Custom project designation', note: 'This value is stored exactly as entered.', custom: true };
524
+ } else if (isMaterial && current === '') {
525
+ selected = availableRows()[0];
526
+ }
527
+ if (isMaterial && selected && !selected.default && !selected.custom) {
528
+ const match = materialLeafForValue(selected.value);
529
+ if (match) { expanded.add(match.parent.id); treeFocusId = match.leaf.id; }
530
+ }
531
+ if (!isMaterial && selected) {
532
+ const selectedIndex = optionRows().findIndex((row) => normalizeCatalogText(rowValue(row)) === normalizeCatalogText(rowValue(selected)));
533
+ if (selectedIndex >= 0) {
534
+ resultFocusIndex = selectedIndex;
535
+ visible = Math.max(visible, Math.ceil((selectedIndex + 1) / 300) * 300);
536
+ }
537
+ }
538
+ modal.querySelector('.scp-scope').textContent = next.scope || '';
539
+ source.textContent = next.source || `${catalog?.standard || ''}${catalog?.environment ? ` · ${catalog.environment}` : ''}`;
540
+ modal.classList.add('open'); render(); search.focus();
541
+ }
542
+
543
+ modal.querySelector('.scp-backdrop').onclick = close;
544
+ modal.querySelector('.scp-close').onclick = close;
545
+ modal.querySelector('.scp-cancel').onclick = close;
546
+ apply.onclick = commit;
547
+ function activateTreeItem(button) {
548
+ const id = button.dataset.node;
549
+ treeFocusId = id;
550
+ const node = findNavigationNode(id);
551
+ if (isMaterial) {
552
+ if (button.dataset.value) {
553
+ selected = materialRow(button.dataset.value);
554
+ fallbackChosen = false;
555
+ } else if (node?.children?.length) {
556
+ expanded.has(id) ? expanded.delete(id) : expanded.add(id);
557
+ }
558
+ renderFamilies(); renderDetails(); reflectApply(); focusTreeItem(id);
559
+ return;
560
+ }
561
+ if (node?.children?.length) {
562
+ if (family === id) expanded.has(id) ? expanded.delete(id) : expanded.add(id);
563
+ else { family = id; expanded.add(id); }
564
+ } else family = id;
565
+ visible = 300; resultFocusIndex = 0;
566
+ render();
567
+ focusTreeItem(id);
568
+ }
569
+ function focusTreeItem(id) {
570
+ treeFocusId = id;
571
+ const target = familyNav.querySelector(`[data-node="${globalThis.CSS?.escape ? globalThis.CSS.escape(id) : id}"]`);
572
+ familyNav.querySelectorAll('.scp-tree-item').forEach((item) => { item.tabIndex = item === target ? 0 : -1; });
573
+ target?.focus();
574
+ target?.scrollIntoView?.({ block: 'nearest' });
575
+ }
576
+ if (materialDefault) materialDefault.onclick = () => {
577
+ selected = { value: MATERIAL_DEFAULT, standard: 'Use profile default', note: 'No explicit material is stored; each member follows the default for its own profile.', default: true };
578
+ fallbackChosen = !!config?.error;
579
+ renderFamilies(); renderDetails(); reflectApply();
580
+ };
581
+ if (materialCurrent) materialCurrent.onclick = () => {
582
+ const current = availableRows().find((row) => row.current);
583
+ if (!current) return;
584
+ selected = current; fallbackChosen = !!config?.error;
585
+ renderFamilies(); renderDetails(); reflectApply();
586
+ };
587
+ familyNav.onclick = (event) => { const button = event.target.closest('.scp-tree-item'); if (button) activateTreeItem(button); };
588
+ familyNav.onkeydown = (event) => {
589
+ const button = event.target.closest('.scp-tree-item'); if (!button) return;
590
+ const items = [...familyNav.querySelectorAll('.scp-tree-item')].filter((item) => item.offsetParent !== null);
591
+ const at = items.indexOf(button); let next = null;
592
+ if (event.key === 'ArrowDown') next = Math.min(items.length - 1, at + 1);
593
+ else if (event.key === 'ArrowUp') next = Math.max(0, at - 1);
594
+ else if (event.key === 'Home') next = 0;
595
+ else if (event.key === 'End') next = items.length - 1;
596
+ else if (event.key === 'ArrowRight' && button.hasAttribute('aria-expanded')) {
597
+ if (button.getAttribute('aria-expanded') === 'false') { event.preventDefault(); expanded.add(button.dataset.node); treeFocusId = button.dataset.node; renderFamilies(); focusTreeItem(button.dataset.node); }
598
+ else next = at + 1;
599
+ } else if (event.key === 'ArrowLeft') {
600
+ if (button.getAttribute('aria-expanded') === 'true') { event.preventDefault(); expanded.delete(button.dataset.node); treeFocusId = button.dataset.node; renderFamilies(); focusTreeItem(button.dataset.node); }
601
+ else if (button.dataset.parent) { event.preventDefault(); focusTreeItem(button.dataset.parent); }
602
+ } else if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); activateTreeItem(button); return; }
603
+ if (next != null && items[next]) { event.preventDefault(); focusTreeItem(items[next].dataset.node); }
604
+ };
605
+ search.oninput = () => { visible = 300; resultFocusIndex = 0; if (isMaterial) renderFamilies(); else renderResults(); };
606
+ search.onkeydown = (event) => {
607
+ if (event.key === 'ArrowDown') {
608
+ const first = isMaterial ? familyNav.querySelector('.scp-tree-item') : results.querySelector('.scp-option');
609
+ if (first) { event.preventDefault(); if (isMaterial) first.focus(); else focusProfileResult(resultFocusIndex); }
610
+ }
611
+ else if (event.key === 'Enter' && event.ctrlKey) { event.preventDefault(); commit(); }
612
+ };
613
+ panel.addEventListener('keydown', (event) => {
614
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(); return; }
615
+ if (event.key !== 'Tab') return;
616
+ const focusable = [...new Set(panel.querySelectorAll('button:not([hidden]),input:not([hidden]),[tabindex="0"]'))].filter((el) => el.offsetParent !== null);
617
+ if (!focusable.length) return;
618
+ const first = focusable[0], last = focusable.at(-1);
619
+ if (event.shiftKey && doc.activeElement === first) { event.preventDefault(); last.focus(); }
620
+ else if (!event.shiftKey && doc.activeElement === last) { event.preventDefault(); first.focus(); }
621
+ });
622
+
623
+ return { open, close, element: modal };
624
+ }