@aiquants/directory-tree 3.11.0 → 3.11.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.
Files changed (45) hide show
  1. package/dist/DirectoryTree.d.ts +2 -21
  2. package/dist/DirectoryTreeGrid.d.ts +3 -17
  3. package/dist/TreeLine.d.ts +2 -8
  4. package/dist/cli.server.d.ts +0 -1
  5. package/dist/entryRendering.d.ts +2 -42
  6. package/dist/gridUtils.d.ts +1 -30
  7. package/dist/index.cjs +2 -2
  8. package/dist/index.d.ts +3 -14
  9. package/dist/index.js +101 -101
  10. package/dist/logger.d.ts +0 -63
  11. package/dist/scrollAnchor.d.ts +0 -28
  12. package/dist/styles/directory-tree.standalone.css +1 -1
  13. package/dist/types.d.ts +3 -497
  14. package/dist/useDirectoryTreeState.d.ts +1 -14
  15. package/dist/useEntryInteraction.d.ts +2 -8
  16. package/package.json +6 -7
  17. package/dist/DirectoryTree.d.ts.map +0 -1
  18. package/dist/DirectoryTreeGrid.d.ts.map +0 -1
  19. package/dist/TreeLine.d.ts.map +0 -1
  20. package/dist/cli.server.d.ts.map +0 -1
  21. package/dist/entryRendering.d.ts.map +0 -1
  22. package/dist/gridUtils.d.ts.map +0 -1
  23. package/dist/index.d.ts.map +0 -1
  24. package/dist/logger.d.ts.map +0 -1
  25. package/dist/scrollAnchor.d.ts.map +0 -1
  26. package/dist/types.d.ts.map +0 -1
  27. package/dist/useDirectoryTreeState.d.ts.map +0 -1
  28. package/dist/useEntryInteraction.d.ts.map +0 -1
  29. package/src/DirectoryTree.tsx +0 -1257
  30. package/src/DirectoryTreeGrid.tsx +0 -285
  31. package/src/TreeLine.tsx +0 -300
  32. package/src/cli.server.ts +0 -38
  33. package/src/entryRendering.tsx +0 -299
  34. package/src/gridUtils.ts +0 -88
  35. package/src/index.ts +0 -32
  36. package/src/logger.ts +0 -162
  37. package/src/scrollAnchor.spec.ts +0 -105
  38. package/src/scrollAnchor.ts +0 -86
  39. package/src/styles/components.entry.css +0 -10
  40. package/src/styles/directory-tree.css +0 -87
  41. package/src/styles/standalone.entry.css +0 -12
  42. package/src/types.ts +0 -761
  43. package/src/useDirectoryTreeState.ts +0 -133
  44. package/src/useEntryInteraction.ts +0 -74
  45. package/src/virtualScrollOptionsSeal.spec.ts +0 -43
@@ -1,1257 +0,0 @@
1
- /**
2
- * @module DirectoryTree
3
- * @description A component to display a directory tree structure.
4
- * ディレクトリツリー構造を表示するためのコンポーネント。
5
- */
6
- import { ScrollBar, VirtualScroll, type VirtualScrollHandle, type VirtualScrollRange } from "@aiquants/virtualscroll"
7
- import type { CSSProperties, MouseEvent } from "react"
8
- import { Fragment, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"
9
- import { twMerge } from "tailwind-merge"
10
- import { DirectoryTreeGridFooterRow, DirectoryTreeGridHeaderRow, DirectoryTreeGridRow } from "./DirectoryTreeGrid.tsx"
11
- import { DEFAULT_ITEM_HEIGHT, directoryTreeClasses, EXPAND_GLYPH_SIZE, getFileExtension, INDENT_SIZE, resolveEntryIcon, resolveExpandIcon, toDataAttributes } from "./entryRendering.tsx"
12
- import { buildNumericTemplate, clampHScroll, computeGridMetrics, DEFAULT_GRID_SCROLLBAR_WIDTH, flattenAllEntries } from "./gridUtils.ts"
13
- import { captureScrollAnchor, resolveAnchorScroll } from "./scrollAnchor.ts"
14
- import { TreeLine } from "./TreeLine.tsx"
15
- import type { DirectoryEntry, DirectoryEntryComparator, DirectoryEntryItemProps, DirectoryTreeProps, DirectoryTreeVirtualScrollOptions, TreeLineGeometry, TreeLineGlyph, TreeLineItemInfo, TreeLineSegment } from "./types.ts"
16
- import { useEntryInteraction } from "./useEntryInteraction.ts"
17
-
18
- /**
19
- * カスタムスクロールバー非表示スタイル
20
- * Custom styles to hide scrollbar
21
- */
22
- const scrollbarHideStyle: CSSProperties = {
23
- msOverflowStyle: "none" /* IE and Edge */,
24
- scrollbarWidth: "none" /* Firefox */,
25
- }
26
-
27
- /**
28
- * Webkit スクロールバー非表示のスタイルを動的に適用
29
- * Apply webkit scrollbar hiding styles dynamically
30
- */
31
- const applyWebkitScrollbarHide = () => {
32
- // 既存のスタイルタグがあるかチェック
33
- let styleElement = document.getElementById("directory-tree-webkit-scrollbar-hide")
34
-
35
- if (!styleElement) {
36
- styleElement = document.createElement("style")
37
- styleElement.id = "directory-tree-webkit-scrollbar-hide"
38
- styleElement.textContent = ".directory-tree-container::-webkit-scrollbar { display: none; }"
39
- document.head.appendChild(styleElement)
40
- }
41
- }
42
-
43
- type FlattenedEntry = {
44
- entry: DirectoryEntry
45
- /** 視覚的インデント段数 (removeRootIndent で負になり得る)。 */
46
- indentLevel: number
47
- /** ルートからの論理的な深さ (0 始まり)。`aria-level` の算出に使う。 */
48
- depth: number
49
- /** 兄弟内の位置 (1 始まり)。 */
50
- positionInSet: number
51
- /** 同一グループの兄弟数。 */
52
- setSize: number
53
- parentIsLast: boolean[]
54
- }
55
-
56
- /** A flattened entry with its resolved row height. / 解決済みの行高を持つフラット化エントリ。 */
57
- type VirtualItem = FlattenedEntry & { rowHeight: number }
58
-
59
- type TreeTraversalResult = {
60
- flatItems: FlattenedEntry[]
61
- lineItems: TreeLineItemInfo[]
62
- maxIndent: number
63
- }
64
-
65
- /**
66
- * @function collectTreeData
67
- * @description Traverses directory entries to build flattened items and tree line metadata.
68
- * Sibling groups are ordered by the optional comparator before flattening.
69
- * ディレクトリエントリを走査してフラットなアイテムとツリーライン用メタデータを構築する。
70
- * フラット化の前に、任意の比較関数で兄弟グループを並べ替える。
71
- */
72
- const collectTreeData = (entries: DirectoryEntry[], resolver: (absolutePath: string, relativePath?: string) => boolean, includeTreeLines: boolean, removeRootIndent: boolean, sort?: DirectoryEntryComparator): TreeTraversalResult => {
73
- const flatItems: FlattenedEntry[] = []
74
- const lineItems: TreeLineItemInfo[] = []
75
- let maxIndent = 0
76
-
77
- const walk = (currentEntries: DirectoryEntry[], indentLevel: number, ancestorChain: boolean[]): void => {
78
- // 並べ替えは兄弟配列の浅いコピーに対してのみ行い、エントリと children の identity を保持する
79
- const ordered = sort ? [...currentEntries].sort(sort) : currentEntries
80
- for (let index = 0; index < ordered.length; index++) {
81
- const entry = ordered[index]
82
- const isLastChild = index === ordered.length - 1
83
- const nextAncestorChain = [...ancestorChain, isLastChild]
84
- const isDirectory = entry.children !== undefined
85
- const isExpanded = isDirectory && resolver(entry.absolutePath, entry.relativePath)
86
-
87
- let effectiveIndentLevel = indentLevel
88
- let effectiveNextAncestorChain = nextAncestorChain
89
- let effectiveAncestorChain = ancestorChain
90
-
91
- if (removeRootIndent) {
92
- effectiveIndentLevel = indentLevel - 1
93
- effectiveNextAncestorChain = nextAncestorChain.slice(1)
94
- effectiveAncestorChain = ancestorChain.slice(1)
95
- }
96
-
97
- // 位置情報は並べ替え後の ordered から採るため、aria の申告は実際の描画順と常に一致する
98
- flatItems.push({ entry, indentLevel: effectiveIndentLevel, depth: indentLevel, positionInSet: index + 1, setSize: ordered.length, parentIsLast: effectiveNextAncestorChain })
99
-
100
- if (includeTreeLines) {
101
- if (effectiveIndentLevel > maxIndent) {
102
- maxIndent = effectiveIndentLevel
103
- }
104
- lineItems.push({
105
- id: entry.absolutePath,
106
- name: entry.name,
107
- absolutePath: entry.absolutePath,
108
- indentLevel: effectiveIndentLevel,
109
- isLastChild,
110
- isDirectory,
111
- isExpanded,
112
- ancestorIsLast: [...effectiveAncestorChain],
113
- hideLines: removeRootIndent && indentLevel === 0,
114
- })
115
- }
116
-
117
- if (isDirectory && isExpanded && entry.children) {
118
- walk(entry.children, indentLevel + 1, nextAncestorChain)
119
- }
120
- }
121
- }
122
-
123
- walk(entries, 0, [])
124
- return { flatItems, lineItems, maxIndent }
125
- }
126
-
127
- type RangeMetrics = {
128
- renderStart: number
129
- renderEnd: number
130
- lookaheadEnd: number
131
- }
132
-
133
- /**
134
- * @function findItemIndexAtOffset
135
- * @description Binary-searches a cumulative offset table for the item covering a pixel position.
136
- * 累積オフセット表を二分探索し、指定ピクセル位置を含むアイテムのインデックスを返す。
137
- * @param offsets - 累積オフセット表 (長さ = アイテム数 + 1、offsets[i] が item i の上端)。
138
- * @param position - ピクセル位置。
139
- * @returns offsets[i] <= position を満たす最大の i (0..itemCount-1 にクランプ)。
140
- */
141
- const findItemIndexAtOffset = (offsets: number[], position: number): number => {
142
- const itemCount = offsets.length - 1
143
- if (itemCount <= 0) return 0
144
- let low = 0
145
- let high = itemCount - 1
146
- let result = 0
147
- while (low <= high) {
148
- const mid = (low + high) >>> 1
149
- if (offsets[mid] <= position) {
150
- result = mid
151
- low = mid + 1
152
- } else {
153
- high = mid - 1
154
- }
155
- }
156
- return result
157
- }
158
-
159
- /**
160
- * @function computeRangeMetrics
161
- * @description Calculates render range metrics for tree line drawing.
162
- * ツリーライン描画のためのレンダリング範囲指標を算出する。
163
- * itemOffsets を用いるため可変高さの行でも正しく機能する。
164
- */
165
- const computeRangeMetrics = (itemCount: number, viewportHeight: number, overscanCount: number, renderingRange: { renderStart: number; renderEnd: number } | null, scrollPosition: number, itemOffsets: number[]): RangeMetrics => {
166
- const fallbackStart = renderingRange?.renderStart ?? Math.max(0, findItemIndexAtOffset(itemOffsets, scrollPosition))
167
- const fallbackEndByHeight = viewportHeight > 0 ? findItemIndexAtOffset(itemOffsets, scrollPosition + viewportHeight) + overscanCount : fallbackStart + overscanCount
168
- const fallbackEnd = itemCount > 0 ? Math.min(itemCount - 1, Math.max(fallbackStart, fallbackEndByHeight)) : fallbackStart
169
- const renderEnd = renderingRange?.renderEnd ?? fallbackEnd
170
- const lookaheadEnd = itemCount > 0 ? Math.min(itemCount - 1, renderEnd + overscanCount) : renderEnd
171
- return { renderStart: fallbackStart, renderEnd, lookaheadEnd }
172
- }
173
-
174
- /**
175
- * Builds geometry data for the canvas based tree line renderer, including segments and glyphs.
176
- *
177
- * Canvas ベースのツリーラインレンダラ用に線分とグリフのジオメトリデータを構築する。
178
- *
179
- * @param items - ツリーラインアイテムの配列。
180
- * @param itemHeights - 各アイテムの高さの配列 (items と同じ順序・長さ)。
181
- * @param itemOffsets - 各アイテムの累積上端オフセット表 (長さ = items.length + 1)。
182
- * @param segmentWidth - インデントセグメントの幅。
183
- * @param includeGlyphs - グリフ情報を含めるかどうか。
184
- * @param glyphSizeOverride - グリフサイズの上書き値。
185
- * @returns セグメントおよびグリフの配列をまとめたジオメトリデータ。
186
- */
187
- export const buildTreeLineGeometry = (items: TreeLineItemInfo[], itemHeights: number[], itemOffsets: number[], segmentWidth: number, includeGlyphs: boolean, glyphSizeOverride?: number): TreeLineGeometry => {
188
- if (items.length === 0) {
189
- return { segmentsByItem: [], glyphsByItem: [] }
190
- }
191
-
192
- const segmentsByItem: TreeLineSegment[][] = Array.from({ length: items.length }, () => [])
193
- const glyphsByItem: TreeLineGlyph[][] = Array.from({ length: items.length }, () => [])
194
- // グリフサイズは行ごとの高さから解決する(override があればそれを優先)。可変高さ行に対応するため行内で算出する。
195
- const resolveGlyphSize = (rowHeight: number): number => {
196
- if (!includeGlyphs) {
197
- return 0
198
- }
199
- if (typeof glyphSizeOverride === "number" && Number.isFinite(glyphSizeOverride) && glyphSizeOverride > 0) {
200
- return glyphSizeOverride
201
- }
202
- return Math.max(8, Math.min(segmentWidth * 0.9, rowHeight * 0.7))
203
- }
204
-
205
- const xOffset = 3
206
-
207
- for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
208
- const item = items[itemIndex]
209
- if (item.hideLines) {
210
- continue
211
- }
212
- const group: TreeLineSegment[] = []
213
- const rowHeight = itemHeights[itemIndex] ?? 0
214
- const yBase = itemOffsets[itemIndex] ?? 0
215
- const yCenter = yBase + rowHeight / 2
216
- const computedGlyphSize = resolveGlyphSize(rowHeight)
217
- const iconGap = computedGlyphSize > 0 ? computedGlyphSize / 2 + 2 : segmentWidth / 1.5
218
-
219
- for (let depth = 0; depth < item.indentLevel; depth++) {
220
- const ancestorIsLast = item.ancestorIsLast[depth] ?? false
221
- if (ancestorIsLast) {
222
- continue
223
- }
224
-
225
- let drawVerticalLine = false
226
- for (let forwardIndex = itemIndex; forwardIndex < items.length; forwardIndex++) {
227
- const candidate = items[forwardIndex]
228
- if (candidate.indentLevel > depth && candidate.ancestorIsLast.length > depth && !candidate.ancestorIsLast[depth]) {
229
- drawVerticalLine = true
230
- break
231
- }
232
- /* v8 ignore next 3 -- 到達不能: forwardIndex===itemIndex(自分自身)が上の条件を常に満たすため、この break には到達しない。 */
233
- if (forwardIndex > itemIndex && candidate.indentLevel === depth) {
234
- break
235
- }
236
- }
237
-
238
- if (drawVerticalLine) {
239
- const x = depth * segmentWidth + segmentWidth / 2 + xOffset
240
- group.push({
241
- key: `${item.id}-ancestor-${depth}`,
242
- x1: x,
243
- y1: yBase,
244
- x2: x,
245
- y2: yBase + rowHeight,
246
- itemIndex,
247
- })
248
- }
249
- }
250
-
251
- const connectorXBase = item.indentLevel * segmentWidth
252
- const connectorX = connectorXBase + segmentWidth / 2 + xOffset
253
-
254
- if (item.isDirectory) {
255
- group.push({
256
- key: `${item.id}-connector-top`,
257
- x1: connectorX,
258
- y1: yBase,
259
- x2: connectorX,
260
- y2: yCenter - iconGap,
261
- itemIndex,
262
- })
263
- } else {
264
- group.push({
265
- key: `${item.id}-connector-top`,
266
- x1: connectorX,
267
- y1: yBase,
268
- x2: connectorX,
269
- y2: yCenter,
270
- itemIndex,
271
- })
272
- }
273
-
274
- if (!item.isDirectory && item.isLastChild) {
275
- group.push({
276
- key: `${item.id}-connector-horizontal`,
277
- x1: connectorX,
278
- y1: yCenter,
279
- x2: connectorXBase + segmentWidth + xOffset,
280
- y2: yCenter,
281
- itemIndex,
282
- })
283
- }
284
-
285
- if (!item.isLastChild) {
286
- if (item.isDirectory) {
287
- group.push({
288
- key: `${item.id}-connector-bottom`,
289
- x1: connectorX,
290
- y1: yCenter + iconGap,
291
- x2: connectorX,
292
- y2: yBase + rowHeight,
293
- itemIndex,
294
- })
295
- } else {
296
- group.push({
297
- key: `${item.id}-connector-bottom`,
298
- x1: connectorX,
299
- y1: yCenter,
300
- x2: connectorX,
301
- y2: yBase + rowHeight,
302
- itemIndex,
303
- })
304
- }
305
- }
306
-
307
- segmentsByItem[itemIndex] = group
308
-
309
- if (includeGlyphs && item.isDirectory) {
310
- const size = computedGlyphSize
311
- const centerX = connectorX
312
- const centerY = yCenter
313
- glyphsByItem[itemIndex] = [
314
- {
315
- key: `${item.id}-glyph`,
316
- itemIndex,
317
- centerX,
318
- centerY,
319
- size,
320
- isExpanded: item.isExpanded,
321
- },
322
- ]
323
- }
324
- }
325
-
326
- return { segmentsByItem, glyphsByItem }
327
- }
328
-
329
- /**
330
- * @component DirectoryEntryItem
331
- * @description Renders a single entry (file or directory) in the directory tree. Memoized for performance.
332
- * ディレクトリツリー内の単一エントリ (ファイルまたはディレクトリ) をレンダリングする。パフォーマンスのためにメモ化されている。
333
- */
334
- const DirectoryEntryItem = memo<DirectoryEntryItemProps>(
335
- ({
336
- entry,
337
- indentLevel,
338
- depth,
339
- positionInSet,
340
- setSize,
341
- isSelectedForAria,
342
- flatIndex,
343
- isActive,
344
- registerRowRef,
345
- onNavigationKeyDown,
346
- rowHeight,
347
- isDirOpen,
348
- parentIsLast,
349
- renderChildren = true,
350
- expansion: { toggleDirectory, onToggleDirectoryRecursive },
351
- selection: { onEntryClick, selectedPath, mode: selectionMode = "none", selectedItems, onSelectionChange },
352
- visual: {
353
- iconOverrides,
354
- showExpandIcons = true,
355
- showDirectoryIcons = true,
356
- showFileIcons = true,
357
- useCanvasExpandIcons = false,
358
- expandIconSize,
359
- typeIconSize,
360
- fontSize,
361
- indentSize = INDENT_SIZE,
362
- highlightStyles,
363
- entryClassName,
364
- entryStyle,
365
- nameClassName,
366
- nameStyle,
367
- directoryNameClassName,
368
- directoryNameStyle,
369
- fileNameClassName,
370
- fileNameStyle,
371
- },
372
- }) => {
373
- const [childrenToRender, setChildrenToRender] = useState<DirectoryEntry[] | null>(null)
374
- const [isHovered, setIsHovered] = useState(false)
375
-
376
- const isDirectory = entry.children !== undefined
377
- const isExpanded = isDirectory && isDirOpen(entry.absolutePath)
378
- const isSelected = entry.absolutePath === selectedPath
379
- const isItemSelected = !isDirectory && selectedItems?.has(entry.absolutePath)
380
- const extension = isDirectory ? undefined : getFileExtension(entry.name) || getFileExtension(entry.relativePath) || getFileExtension(entry.absolutePath)
381
-
382
- /**
383
- * @effect Lazy Children Loading
384
- * @description Loads children only when expanded to optimize rendering performance.
385
- * レンダリングパフォーマンス最適化のため、展開時のみ子要素を読み込む。
386
- */
387
- useEffect(() => {
388
- setChildrenToRender(isExpanded && entry.children ? entry.children : null)
389
- }, [isExpanded, entry.children])
390
-
391
- const handleInteraction = useEntryInteraction({ entry, isDirectory, isExpanded, isItemSelected: Boolean(isItemSelected), selectionMode, onSelectionChange, onEntryClick, toggleDirectory, onToggleDirectoryRecursive })
392
-
393
- const hoverClass = isHovered ? (highlightStyles?.hoverClassName !== undefined ? highlightStyles.hoverClassName : directoryTreeClasses.entryHover) : ""
394
-
395
- const selectedClass = (() => {
396
- if (isDirectory) {
397
- if (isSelected) {
398
- return highlightStyles?.directorySelectedClassName !== undefined ? highlightStyles.directorySelectedClassName : directoryTreeClasses.entrySelected
399
- }
400
- } else {
401
- if (isSelected || isItemSelected) {
402
- if (highlightStyles?.itemSelectedClassName !== undefined) {
403
- return highlightStyles.itemSelectedClassName
404
- }
405
- return twMerge(isSelected && directoryTreeClasses.entrySelected, isItemSelected && directoryTreeClasses.entryItemSelected)
406
- }
407
- }
408
- return ""
409
- })()
410
-
411
- const entryClasses = twMerge(directoryTreeClasses.entry, hoverClass, selectedClass, entryClassName, entry.className)
412
- const expandIconClasses = twMerge(directoryTreeClasses.expandIcon, (isSelected || isItemSelected) && directoryTreeClasses.expandIconSelected)
413
- const typeIconClasses = twMerge(directoryTreeClasses.typeIcon, (isSelected || isItemSelected) && directoryTreeClasses.typeIconSelected)
414
- const nameClasses = twMerge(directoryTreeClasses.name, nameClassName, isDirectory && directoryTreeClasses.nameDirectory, isDirectory && directoryNameClassName, !isDirectory && fileNameClassName, (isSelected || isItemSelected) && directoryTreeClasses.nameSelected)
415
-
416
- const expandIconContent = resolveExpandIcon({ isDirectory, isExpanded, showExpandIcons, useCanvasExpandIcons, expandIconSize })
417
- const resolvedIcon = (isDirectory ? showDirectoryIcons : showFileIcons) ? resolveEntryIcon({ entry, isDirectory, isExpanded, isSelected, isItemSelected: Boolean(isItemSelected), extension, mimeType: entry.mimeType }, iconOverrides) : null
418
-
419
- const customHighlightStyle = {
420
- ...(isHovered ? highlightStyles?.hoverStyle : {}),
421
- ...(isDirectory && isSelected ? highlightStyles?.directorySelectedStyle : {}),
422
- ...(!isDirectory && (isSelected || isItemSelected) ? highlightStyles?.itemSelectedStyle : {}),
423
- }
424
-
425
- // 利用側が渡した data-* 属性。自身が出力する data-entry-* より前に展開し、後勝ちで守る
426
- const customDataAttributes = toDataAttributes(entry.data)
427
-
428
- const typeIconStyle = typeIconSize ? { width: typeIconSize, height: typeIconSize } : undefined
429
- const fontSizeStyle = fontSize ? { fontSize: typeof fontSize === "number" ? `${fontSize}px` : fontSize } : undefined
430
-
431
- return (
432
- <Fragment key={entry.absolutePath}>
433
- <div
434
- className={entryClasses}
435
- style={{
436
- paddingLeft: `${Math.max(0, indentLevel * indentSize)}px`,
437
- transform: indentLevel < 0 ? `translateX(${indentLevel * indentSize}px)` : undefined,
438
- width: indentLevel < 0 ? `calc(100% + ${Math.abs(indentLevel * indentSize)}px)` : undefined,
439
- height: `${rowHeight}px`,
440
- ...fontSizeStyle,
441
- ...customHighlightStyle,
442
- ...entryStyle,
443
- ...entry.style,
444
- }}
445
- {...customDataAttributes}
446
- data-entry-type={isDirectory ? "directory" : "file"}
447
- data-entry-expanded={isDirectory ? String(isExpanded) : undefined}
448
- data-entry-selected={isSelected ? "true" : undefined}
449
- data-entry-item-selected={isItemSelected ? "true" : undefined}
450
- onClick={handleInteraction}
451
- onMouseEnter={() => setIsHovered(true)}
452
- onMouseLeave={() => setIsHovered(false)}
453
- ref={(node) => registerRowRef(flatIndex, node)}
454
- onKeyDown={(e) => {
455
- if (e.key === "Enter" || e.key === " ") {
456
- e.preventDefault()
457
- handleInteraction(e as unknown as MouseEvent<HTMLDivElement>)
458
- return
459
- }
460
- onNavigationKeyDown(e, flatIndex)
461
- }}
462
- // roving tabindex: ツリー全体で 1 つだけがタブ停止点。全行を停止点にすると
463
- // 大きなツリーではタブキーだけで抜けるのに数百回の打鍵が要る
464
- tabIndex={isActive ? 0 : -1}
465
- role="treeitem"
466
- aria-expanded={isDirectory ? isExpanded : undefined}
467
- aria-level={depth + 1}
468
- aria-posinset={positionInSet}
469
- aria-setsize={setSize}
470
- aria-selected={selectionMode === "none" ? undefined : isSelectedForAria}
471
- aria-label={`${entry.name} (${isDirectory ? "directory" : "file"})`}>
472
- {(showExpandIcons || useCanvasExpandIcons) && <span className={expandIconClasses}>{expandIconContent}</span>}
473
- {(isDirectory ? showDirectoryIcons : showFileIcons) && (
474
- <span className={typeIconClasses} style={typeIconStyle}>
475
- {resolvedIcon}
476
- </span>
477
- )}
478
- <span
479
- className={nameClasses}
480
- style={{
481
- ...fontSizeStyle,
482
- ...nameStyle,
483
- ...(isDirectory ? directoryNameStyle : fileNameStyle),
484
- }}
485
- data-entry-type={isDirectory ? "directory" : "file"}
486
- data-entry-role="name">
487
- {entry.label ?? entry.name}
488
- </span>
489
- </div>
490
- {/* v8 ignore start -- 到達不能: DirectoryTree は常に renderChildren=false で描画し(仮想化)、本コンポーネントは非公開のため、この非仮想化の再帰描画経路は使われない。 */}
491
- {isExpanded && childrenToRender && renderChildren && (
492
- <fieldset>
493
- {childrenToRender.map((child, index) => (
494
- <DirectoryEntryItem
495
- key={child.absolutePath}
496
- entry={child}
497
- indentLevel={indentLevel + 1}
498
- depth={depth + 1}
499
- positionInSet={index + 1}
500
- setSize={childrenToRender.length}
501
- isSelectedForAria={Boolean(selectedItems?.has(child.absolutePath))}
502
- // この再帰経路は仮想化により到達しない。キーボード制御はツリー本体が持つため無効値を渡す
503
- flatIndex={-1}
504
- isActive={false}
505
- registerRowRef={registerRowRef}
506
- onNavigationKeyDown={onNavigationKeyDown}
507
- // 非仮想化の再帰描画では親行の高さを一様に流用する (DirectoryTree は renderChildren=false のため通常この経路は通らない)。
508
- rowHeight={rowHeight}
509
- isDirOpen={isDirOpen}
510
- parentIsLast={[...parentIsLast, index === childrenToRender.length - 1]}
511
- expansion={{ toggleDirectory, onToggleDirectoryRecursive }}
512
- selection={{ onEntryClick, selectedPath, mode: selectionMode, selectedItems, onSelectionChange }}
513
- visual={{
514
- iconOverrides,
515
- showExpandIcons,
516
- showDirectoryIcons,
517
- showFileIcons,
518
- useCanvasExpandIcons,
519
- expandIconSize,
520
- highlightStyles,
521
- entryClassName,
522
- entryStyle,
523
- nameClassName,
524
- nameStyle,
525
- directoryNameClassName,
526
- directoryNameStyle,
527
- fileNameClassName,
528
- fileNameStyle,
529
- }}
530
- />
531
- ))}
532
- </fieldset>
533
- )}
534
- {/* v8 ignore stop */}
535
- </Fragment>
536
- )
537
- },
538
- (prev, next) => {
539
- if (prev.entry !== next.entry) return false
540
- const prevIsDir = prev.entry.children !== undefined
541
- const nextIsDir = next.entry.children !== undefined
542
- const prevExpanded = prevIsDir && prev.isDirOpen(prev.entry.absolutePath)
543
- const nextExpanded = nextIsDir && next.isDirOpen(next.entry.absolutePath)
544
-
545
- return (
546
- prev.indentLevel === next.indentLevel &&
547
- // 位置情報は aria として描画されるため、変化したら再描画が必要
548
- prev.depth === next.depth &&
549
- prev.positionInSet === next.positionInSet &&
550
- prev.setSize === next.setSize &&
551
- prev.isSelectedForAria === next.isSelectedForAria &&
552
- prev.flatIndex === next.flatIndex &&
553
- prev.isActive === next.isActive &&
554
- prev.rowHeight === next.rowHeight &&
555
- prevExpanded === nextExpanded &&
556
- prev.selection.selectedPath === next.selection.selectedPath &&
557
- prev.selection.mode === next.selection.mode &&
558
- prev.selection.selectedItems === next.selection.selectedItems &&
559
- prev.visual.iconOverrides === next.visual.iconOverrides &&
560
- prev.visual.showExpandIcons === next.visual.showExpandIcons &&
561
- prev.visual.showDirectoryIcons === next.visual.showDirectoryIcons &&
562
- prev.visual.showFileIcons === next.visual.showFileIcons &&
563
- prev.visual.useCanvasExpandIcons === next.visual.useCanvasExpandIcons &&
564
- prev.visual.expandIconSize === next.visual.expandIconSize &&
565
- prev.visual.highlightStyles === next.visual.highlightStyles &&
566
- prev.visual.entryClassName === next.visual.entryClassName &&
567
- prev.visual.entryStyle === next.visual.entryStyle &&
568
- prev.visual.nameClassName === next.visual.nameClassName &&
569
- prev.visual.nameStyle === next.visual.nameStyle &&
570
- prev.visual.directoryNameClassName === next.visual.directoryNameClassName &&
571
- prev.visual.directoryNameStyle === next.visual.directoryNameStyle &&
572
- prev.visual.fileNameClassName === next.visual.fileNameClassName &&
573
- prev.visual.fileNameStyle === next.visual.fileNameStyle &&
574
- prev.parentIsLast.length === next.parentIsLast.length &&
575
- prev.parentIsLast.every((val, i) => val === next.parentIsLast[i])
576
- )
577
- },
578
- )
579
- DirectoryEntryItem.displayName = "DirectoryEntryItem"
580
-
581
- // TreeLine コンポーネントが使用する props の型は TreeLine.tsx からインポートされる
582
-
583
- /**
584
- * @function getAllDescendantPaths
585
- * @description Recursively gets all descendant directory paths for a given entry.
586
- * 指定されたエントリのすべての子孫ディレクトリパスを再帰的に取得する。
587
- * @param {DirectoryEntry} entry - The directory entry to start from. 開始点となるディレクトリのエントリ。
588
- * @returns {string[]} An array of absolute paths of all descendant directories. すべての子孫ディレクトリの絶対パスの配列。
589
- */
590
- const getAllDescendantPaths = (entry: DirectoryEntry): string[] => {
591
- const paths: string[] = []
592
- if (entry.children) {
593
- for (const child of entry.children) {
594
- if (child.type === "directory") {
595
- paths.push(child.absolutePath)
596
- paths.push(...getAllDescendantPaths(child))
597
- }
598
- }
599
- }
600
- return paths
601
- }
602
-
603
- /**
604
- * @component DirectoryTree
605
- * @description A component to display a directory tree structure. It allows navigation and selection of files.
606
- * ディレクトリツリー構造を表示するコンポーネント。ファイルのナビゲーションと選択が可能。
607
- */
608
- export const DirectoryTree = ({
609
- entries,
610
- expansion: { toggle, isExpanded, expandMultiple, collapseMultiple, isPending, alwaysExpanded = false, doubleClickAction = "recursive" },
611
- selection: { onEntryClick, selectedPath, mode: selectionMode = "none", selectedItems, onSelectionChange },
612
- visual: {
613
- className,
614
- style,
615
- ariaLabel,
616
- ariaLabelledBy,
617
- lineColor = "#A0AEC0",
618
- showTreeLines = true,
619
- showExpandIcons = true,
620
- showDirectoryIcons = true,
621
- showFileIcons = true,
622
- iconOverrides,
623
- expandIconSize,
624
- itemHeight = DEFAULT_ITEM_HEIGHT,
625
- removeRootIndent = false,
626
- highlightStyles,
627
- entryClassName,
628
- entryStyle,
629
- nameClassName,
630
- nameStyle,
631
- directoryNameClassName,
632
- directoryNameStyle,
633
- fileNameClassName,
634
- fileNameStyle,
635
- } = {},
636
- virtualScroll: virtualScrollOptions,
637
- grid,
638
- sort,
639
- }: DirectoryTreeProps) => {
640
- const isGrid = grid !== undefined
641
- const [isClient, setIsClient] = useState(false)
642
- const containerRef = useRef<HTMLDivElement | null>(null)
643
- const bodyRef = useRef<HTMLDivElement | null>(null)
644
- const virtualScrollRef = useRef<VirtualScrollHandle>(null)
645
- const [measuredViewportHeight, setMeasuredViewportHeight] = useState(0)
646
- const [measuredWidth, setMeasuredWidth] = useState(0)
647
- const [hscroll, setHscroll] = useState(0)
648
- const [renderingRange, setRenderingRange] = useState<{ renderStart: number; renderEnd: number } | null>(null)
649
-
650
- const {
651
- overscanCount: userOverscanCount = 15,
652
- className: virtualScrollClassName,
653
- background: virtualScrollBackground,
654
- onScroll: virtualScrollOnScroll,
655
- onRangeChange: virtualScrollOnRangeChange,
656
- initialScrollIndex,
657
- initialScrollOffset,
658
- initialScrollAnchor,
659
- callbackThrottleMs = 5,
660
- contentInsets: virtualScrollContentInsets,
661
- onItemFocus,
662
- viewportHeightOverride,
663
- scrollBarOptions,
664
- behaviorOptions,
665
- preserveScrollAnchor = false,
666
- getItemKey: userGetItemKey,
667
- // 素通しの pass-through。型で受け付けているものは実際に転送する
668
- // (`role="tree"` は本コンポーネント自身のコンテナに付くため contentProps とは別要素で衝突しない)
669
- testId,
670
- contentProps,
671
- }: DirectoryTreeVirtualScrollOptions = virtualScrollOptions ?? {}
672
-
673
- // 合成ウィジェットのロールは行だけを直接所有するコンテンツ要素へ置く (VirtualScroll の契約)。
674
- // grid モードでは本体行をまとめる rowgroup がここに当たる。利用側指定を土台にし、
675
- // role は利用側が明示した場合のみ譲る
676
- const resolvedContentProps = useMemo(() => (isGrid ? { role: "rowgroup", ...contentProps } : contentProps), [isGrid, contentProps])
677
-
678
- const [scrollPosition, setScrollPosition] = useState(typeof initialScrollOffset === "number" ? initialScrollOffset : 0)
679
- // アンカー補正用の最新スクロール位置 (effect の依存に scrollPosition を入れないための鏡)
680
- const scrollPositionRef = useRef(typeof initialScrollOffset === "number" ? initialScrollOffset : 0)
681
-
682
- const handleVirtualScroll = useCallback(
683
- (position: number, totalHeight: number) => {
684
- scrollPositionRef.current = position
685
- setScrollPosition(position)
686
- virtualScrollOnScroll?.(position, totalHeight)
687
- },
688
- [virtualScrollOnScroll],
689
- )
690
-
691
- const handleRangeChange = useCallback(
692
- (range: VirtualScrollRange) => {
693
- const { renderingStartIndex: start, renderingEndIndex: end } = range
694
- setRenderingRange((prev) => (prev && prev.renderStart === start && prev.renderEnd === end ? prev : { renderStart: start, renderEnd: end }))
695
- virtualScrollOnRangeChange?.(range)
696
- },
697
- [virtualScrollOnRangeChange],
698
- )
699
-
700
- /**
701
- * @effect Client Mount & Scrollbar Hide
702
- * @description Sets client-side flag and injects styles to hide Webkit scrollbars.
703
- * クライアントサイドフラグを設定し、Webkit スクロールバーを非表示にするスタイルを注入する。
704
- */
705
- useEffect(() => {
706
- setIsClient(true)
707
- applyWebkitScrollbarHide()
708
- }, [])
709
-
710
- /**
711
- * @effect Viewport Height Observer
712
- * @description Monitors the container's height using ResizeObserver to update the virtual scroll viewport.
713
- * ResizeObserver を使用してコンテナの高さを監視し、仮想スクロールのビューポートを更新する。
714
- */
715
- useEffect(() => {
716
- const container = containerRef.current
717
- // In grid mode header/footer are siblings of the body, so the viewport height must come
718
- // from the body region only — the whole container would over-count by their heights.
719
- // grid モードではヘッダ/フッタが本体の兄弟なので、ビューポート高は本体領域のみから取る。
720
- const heightTarget = isGrid ? bodyRef.current : container
721
-
722
- const measure = () => {
723
- if (container) {
724
- const nextWidth = container.clientWidth
725
- setMeasuredWidth((prev) => (Math.abs(prev - nextWidth) > 1 ? nextWidth : prev))
726
- }
727
- if (typeof viewportHeightOverride === "number") {
728
- setMeasuredViewportHeight((prev) => (Math.abs(prev - viewportHeightOverride) > 1 ? viewportHeightOverride : prev))
729
- } else if (heightTarget) {
730
- const nextHeight = heightTarget.clientHeight
731
- setMeasuredViewportHeight((prev) => (Math.abs(prev - nextHeight) > 1 ? nextHeight : prev))
732
- }
733
- }
734
-
735
- if (!(container || heightTarget)) return setMeasuredViewportHeight(0)
736
- measure()
737
-
738
- const resizeObserver = new ResizeObserver(measure)
739
- if (container) resizeObserver.observe(container)
740
- if (heightTarget && heightTarget !== container) resizeObserver.observe(heightTarget)
741
- return () => resizeObserver.disconnect()
742
- }, [viewportHeightOverride, isGrid])
743
-
744
- const viewportHeight = typeof viewportHeightOverride === "number" ? viewportHeightOverride : measuredViewportHeight
745
-
746
- const safeIsExpanded = useCallback((path: string) => alwaysExpanded || (isClient ? isExpanded(path) : false), [isClient, isExpanded, alwaysExpanded])
747
-
748
- const containerClasses = twMerge(directoryTreeClasses.container, isPending && directoryTreeClasses.containerPending, className)
749
- const containerStyle = useMemo(
750
- () => ({
751
- ...scrollbarHideStyle,
752
- ...(style ?? {}),
753
- ...(typeof viewportHeightOverride === "number" ? { height: viewportHeightOverride, minHeight: viewportHeightOverride } : {}),
754
- }),
755
- [style, viewportHeightOverride],
756
- )
757
-
758
- /**
759
- * @callback handleDirectoryDoubleClick
760
- * @description Handles double-click actions on directories (recursive expand/collapse or toggle).
761
- * ディレクトリのダブルクリックアクション (再帰的展開/折りたたみ、または切り替え) を処理する。
762
- */
763
- const handleDirectoryDoubleClick = useCallback(
764
- (entry: DirectoryEntry, overrideAction?: "toggle" | "recursive") => {
765
- const allPaths = [entry.absolutePath, ...getAllDescendantPaths(entry)]
766
- const action = overrideAction || doubleClickAction
767
- const allExpanded = allPaths.every((path) => safeIsExpanded(path))
768
-
769
- if (allExpanded) return collapseMultiple(allPaths)
770
-
771
- const allCollapsed = allPaths.every((path) => !safeIsExpanded(path))
772
- if (allCollapsed || action === "recursive") return expandMultiple(allPaths)
773
- if (action === "toggle") return collapseMultiple(allPaths)
774
-
775
- /* v8 ignore next -- 到達不能: doubleClickAction は "toggle" | "recursive" のみ(型で保証)。防御的フォールバック。 */
776
- console.warn(`[DirectoryTree] Unknown double click action: ${action}. No action taken.`)
777
- },
778
- [safeIsExpanded, expandMultiple, collapseMultiple, doubleClickAction],
779
- )
780
-
781
- // `removeRootIndent` relies on a negative-indent translateX shift that conflicts with the
782
- // frozen name column (which must start at x=0), so it is intentionally ignored in grid mode.
783
- // grid モードでは名前列を x=0 に凍結するため、負インデントに依存する removeRootIndent は無効化する。
784
- const effectiveRemoveRootIndent = isGrid ? false : removeRootIndent
785
- const { flatItems, lineItems, maxIndent } = useMemo(() => collectTreeData(entries, safeIsExpanded, showTreeLines, effectiveRemoveRootIndent, sort), [entries, safeIsExpanded, showTreeLines, effectiveRemoveRootIndent, sort])
786
-
787
- // 各行の高さを解決する。number ならそのまま、関数なら (entry, flatIndex) で算出する。
788
- // 不正値 (NaN / Infinity / 0 / 負値) は既定高さにフォールバックし、オフセット表の単調性と CSS 高さの妥当性を保証する。
789
- const virtualItems = useMemo<VirtualItem[]>(
790
- () =>
791
- flatItems.map((item, index) => {
792
- const resolved = typeof itemHeight === "function" ? itemHeight(item.entry, index) : itemHeight
793
- return { ...item, rowHeight: Number.isFinite(resolved) && resolved > 0 ? resolved : DEFAULT_ITEM_HEIGHT }
794
- }),
795
- [flatItems, itemHeight],
796
- )
797
-
798
- // ツリーライン幾何・可視範囲計算に用いる高さ配列と累積オフセット表 (offsets[i] が item i の上端)。
799
- const itemHeights = useMemo(() => virtualItems.map((item) => item.rowHeight), [virtualItems])
800
- const itemOffsets = useMemo(() => {
801
- const offsets = new Array<number>(itemHeights.length + 1)
802
- offsets[0] = 0
803
- for (let index = 0; index < itemHeights.length; index++) {
804
- offsets[index + 1] = offsets[index] + itemHeights[index]
805
- }
806
- return offsets
807
- }, [itemHeights])
808
-
809
- // VirtualScroll に渡す高さ取得関数。identity は itemHeights が変わったときだけ更新される。
810
- const getItemHeight = useCallback((index: number) => virtualItems[index]?.rowHeight ?? DEFAULT_ITEM_HEIGHT, [virtualItems])
811
-
812
- // 行キーは既定で絶対パス。index キーのままだと並べ替えや挿入で index→entry の対応が変わるたびに
813
- // 可視行が unmount/remount され、行メモも DOM 状態 (hover 等) も失われる。
814
- const defaultGetItemKey = useCallback((index: number) => virtualItems[index]?.entry.absolutePath ?? index, [virtualItems])
815
- const resolvedGetItemKey = userGetItemKey ?? defaultGetItemKey
816
-
817
- // ハンドラの identity を安定させるための鏡。依存に直接入れると毎レンダーで全行の memo が壊れる
818
- const flatItemsRef = useRef(flatItems)
819
- flatItemsRef.current = flatItems
820
- const safeIsExpandedRef = useRef(safeIsExpanded)
821
- safeIsExpandedRef.current = safeIsExpanded
822
- const toggleRef = useRef(toggle)
823
- toggleRef.current = toggle
824
-
825
- // --- キーボードナビゲーション (WAI-ARIA tree パターン) ---
826
- // 仮想化のため目的の行が DOM に無いことがある。まず scrollToIndex で描画ウィンドウへ入れ、
827
- // 行が現れてからフォーカスする (pendingFocusRef が「まだ掴めていない行」を保持する)
828
- const [activeIndex, setActiveIndex] = useState(0)
829
- const rowRefs = useRef(new Map<number, HTMLDivElement>())
830
- const pendingFocusRef = useRef<number | null>(null)
831
-
832
- const registerRowRef = useCallback((index: number, node: HTMLDivElement | null) => {
833
- if (node) {
834
- rowRefs.current.set(index, node)
835
- if (pendingFocusRef.current === index) {
836
- pendingFocusRef.current = null
837
- node.focus()
838
- }
839
- } else {
840
- rowRefs.current.delete(index)
841
- }
842
- }, [])
843
-
844
- const focusRowAt = useCallback((index: number) => {
845
- setActiveIndex(index)
846
- const node = rowRefs.current.get(index)
847
- if (node) {
848
- node.focus()
849
- return
850
- }
851
- // 未描画ならスクロールして、登録時にフォーカスする
852
- pendingFocusRef.current = index
853
- virtualScrollRef.current?.scrollToIndex(index)
854
- }, [])
855
-
856
- // 行数が減ったとき (折り畳みなど) に活性行が範囲外へ出ないようにする
857
- useEffect(() => {
858
- setActiveIndex((previous) => (flatItems.length === 0 ? 0 : Math.min(previous, flatItems.length - 1)))
859
- }, [flatItems.length])
860
-
861
- const handleNavigationKeyDown = useCallback(
862
- (event: React.KeyboardEvent<HTMLDivElement>, index: number) => {
863
- const items = flatItemsRef.current
864
- const lastIndex = items.length - 1
865
- if (lastIndex < 0) return
866
-
867
- const current = items[index]
868
- const isDirectoryRow = current?.entry.children !== undefined
869
- const isExpandedRow = isDirectoryRow && safeIsExpandedRef.current(current.entry.absolutePath)
870
-
871
- switch (event.key) {
872
- case "ArrowDown":
873
- event.preventDefault()
874
- focusRowAt(Math.min(index + 1, lastIndex))
875
- break
876
- case "ArrowUp":
877
- event.preventDefault()
878
- focusRowAt(Math.max(index - 1, 0))
879
- break
880
- case "Home":
881
- event.preventDefault()
882
- focusRowAt(0)
883
- break
884
- case "End":
885
- event.preventDefault()
886
- focusRowAt(lastIndex)
887
- break
888
- case "ArrowRight":
889
- event.preventDefault()
890
- // 折り畳み中のディレクトリは開く。既に開いているなら最初の子へ進む
891
- if (isDirectoryRow && !isExpandedRow) {
892
- toggleRef.current(current.entry.absolutePath)
893
- } else if (isDirectoryRow && index < lastIndex) {
894
- focusRowAt(index + 1)
895
- }
896
- break
897
- case "ArrowLeft": {
898
- event.preventDefault()
899
- // 開いているディレクトリは閉じる。それ以外は親へ戻る
900
- if (isDirectoryRow && isExpandedRow) {
901
- toggleRef.current(current.entry.absolutePath)
902
- break
903
- }
904
- const currentDepth = current?.depth ?? 0
905
- for (let candidate = index - 1; candidate >= 0; candidate--) {
906
- if (items[candidate].depth < currentDepth) {
907
- focusRowAt(candidate)
908
- break
909
- }
910
- }
911
- break
912
- }
913
- default:
914
- break
915
- }
916
- },
917
- [focusRowAt],
918
- )
919
-
920
- const treeLineGeometry = useMemo(
921
- () => (!showTreeLines || lineItems.length === 0 ? { segmentsByItem: [], glyphsByItem: [] } : buildTreeLineGeometry(lineItems, itemHeights, itemOffsets, INDENT_SIZE, showTreeLines, expandIconSize ?? EXPAND_GLYPH_SIZE)),
922
- [lineItems, itemHeights, itemOffsets, showTreeLines, expandIconSize],
923
- )
924
-
925
- const treeLineWidth = useMemo(() => (!showTreeLines || entries.length === 0 ? 0 : (maxIndent + 2) * INDENT_SIZE), [entries.length, maxIndent, showTreeLines])
926
- const { renderStart, renderEnd, lookaheadEnd } = useMemo(
927
- () => computeRangeMetrics(virtualItems.length, viewportHeight, userOverscanCount, renderingRange, scrollPosition, itemOffsets),
928
- [virtualItems.length, viewportHeight, userOverscanCount, renderingRange, scrollPosition, itemOffsets],
929
- )
930
-
931
- const treeLineBackground = useMemo(() => {
932
- if (!showTreeLines || treeLineWidth <= 0 || viewportHeight <= 0 || treeLineGeometry.segmentsByItem.length === 0) return null
933
- return (
934
- <div className="pointer-events-none absolute inset-0 z-0" aria-hidden="true">
935
- <div className="absolute top-0 left-0" style={{ width: treeLineWidth, height: viewportHeight }}>
936
- <TreeLine
937
- segmentsByItem={treeLineGeometry.segmentsByItem}
938
- glyphsByItem={treeLineGeometry.glyphsByItem}
939
- itemHeight={itemHeights[0] ?? DEFAULT_ITEM_HEIGHT}
940
- width={treeLineWidth}
941
- viewportHeight={viewportHeight}
942
- scrollPosition={scrollPosition}
943
- color={lineColor}
944
- expandGlyphColor={lineColor}
945
- expandGlyphSize={expandIconSize ?? EXPAND_GLYPH_SIZE}
946
- renderStartIndex={renderStart}
947
- renderEndIndex={renderEnd}
948
- lookaheadEndIndex={lookaheadEnd}
949
- />
950
- </div>
951
- </div>
952
- )
953
- }, [treeLineWidth, viewportHeight, renderStart, renderEnd, lookaheadEnd, scrollPosition, treeLineGeometry, lineColor, showTreeLines, expandIconSize, itemHeights])
954
-
955
- const getItem = useCallback((index: number) => virtualItems[index], [virtualItems])
956
-
957
- // 直前レンダーの行リストと累積オフセット (スクロールアンカー補正用)
958
- const prevAnchorSourceRef = useRef<{ items: VirtualItem[]; offsets: number[] } | null>(null)
959
-
960
- // 目的: 行リストの変異 (ストリーミング追記・finalize 再構築など) を跨いで、先頭可視行を
961
- // 画面上で静止させる (viewport より上への挿入によるコンテンツのずれを打ち消す)。
962
- // useLayoutEffect で描画前に補正するため、ユーザーにはずれが一切見えない。
963
- // 依存関係: virtualItems / itemOffsets (行リスト変異ごと), preserveScrollAnchor。
964
- // スクロール位置はハンドルから同期読取し、スクロール操作では発火させない。
965
- // 座標系: ハンドル (virtualscroll 2.0.0) は getScrollPosition / scrollTo の入出力とも
966
- // **論理座標**で自己完結するため、この effect に座標換算は一切存在しない。
967
- // ❗ inset 換算 (± topInset) を持ち込まないこと: 旧仕様の名残の換算が
968
- // 「inset 二重適用で topInset px 深く着地する」実害バグの原因だった。
969
- // クリーンアップ: 不要 (ref / state 更新のみ)。
970
- useLayoutEffect(() => {
971
- const previous = prevAnchorSourceRef.current
972
- prevAnchorSourceRef.current = { items: virtualItems, offsets: itemOffsets }
973
-
974
- // アンカー無効・初回レンダー・行リスト同一のいずれかなら補正不要
975
- if (!preserveScrollAnchor) {
976
- return
977
- }
978
- if (!previous || previous.items === virtualItems) {
979
- return
980
- }
981
-
982
- // スクロール位置は onScroll ミラー (RAF + スロットルで 1〜2 フレーム遅延する) ではなく、
983
- // ハンドルから同期読取する。アクティブスクロール中にチャンクが着地しても、
984
- // 実位置基準で補正され「遅延分だけ跳ねる」ラバーバンドが起こらない。
985
- // 未接続の -1 番兵はミラーへフォールバック
986
- const pane = virtualScrollRef.current
987
- const reported = pane?.getScrollPosition()
988
- const liveLogicalPosition = typeof reported === "number" && reported >= 0 ? reported : scrollPositionRef.current
989
-
990
- // 変更前の先頭可視行を捕捉し、新リスト内の同一行が同じ画面位置に来る量へ補正する
991
- const anchor = captureScrollAnchor(previous.items, previous.offsets, liveLogicalPosition)
992
- if (!anchor) {
993
- return
994
- }
995
- const nextLogicalPosition = resolveAnchorScroll(anchor, virtualItems, itemOffsets)
996
- if (nextLogicalPosition === null) {
997
- return
998
- }
999
- if (Math.abs(nextLogicalPosition - liveLogicalPosition) < 1) {
1000
- return
1001
- }
1002
-
1003
- // ハンドルの返値 (クランプ後の実効論理位置) をミラーへ採用し、同じ描画前フラッシュで
1004
- // 自コンポーネントの scrollPosition state も更新する。state を遅延させると、
1005
- // ツリーライン canvas と展開グリフが補正量ぶんだけ 1〜2 フレーム行からずれて描画される。
1006
- const appliedLogicalPosition = pane ? pane.scrollTo(nextLogicalPosition) : nextLogicalPosition
1007
- scrollPositionRef.current = appliedLogicalPosition
1008
- setScrollPosition(appliedLogicalPosition)
1009
- }, [virtualItems, itemOffsets, preserveScrollAnchor])
1010
-
1011
- // ===== TreeGrid (columns) mode derived values =====
1012
- const gridColumns = grid?.columns
1013
- // Align the header/footer spacer with the body's vertical scrollbar: default to the actual
1014
- // VirtualScroll scrollbar width so columns stay aligned even when a consumer customizes it.
1015
- const gridScrollBarWidth = grid?.scrollBarWidth ?? scrollBarOptions?.width ?? DEFAULT_GRID_SCROLLBAR_WIDTH
1016
- const gridMetrics = useMemo(() => (gridColumns ? computeGridMetrics({ measuredWidth, columns: gridColumns, scrollBarWidth: gridScrollBarWidth }) : null), [gridColumns, measuredWidth, gridScrollBarWidth])
1017
- const numericTemplate = useMemo(() => (gridColumns ? buildNumericTemplate(gridColumns) : ""), [gridColumns])
1018
- // Footer aggregates over ALL nodes (collapsed included); only compute when a footer is shown.
1019
- const allEntriesFlat = useMemo(() => (grid?.showFooter && gridColumns ? flattenAllEntries(entries) : []), [grid?.showFooter, gridColumns, entries])
1020
- const maxHScroll = gridMetrics?.maxHScroll ?? 0
1021
- // Re-clamp the horizontal offset when the layout shrinks (resize / column change).
1022
- useEffect(() => {
1023
- setHscroll((prev) => clampHScroll(prev, maxHScroll))
1024
- }, [maxHScroll])
1025
- const handleWheelHorizontal = useCallback((deltaX: number) => setHscroll((prev) => clampHScroll(prev + deltaX, maxHScroll)), [maxHScroll])
1026
- // Stable visual object so horizontal scrolling (which changes --dt-hscroll only) never churns the memoized rows.
1027
- const gridRowVisual = useMemo(
1028
- () => ({ iconOverrides, showExpandIcons, showDirectoryIcons, showFileIcons, useCanvasExpandIcons: showTreeLines, expandIconSize, highlightStyles }),
1029
- [iconOverrides, showExpandIcons, showDirectoryIcons, showFileIcons, showTreeLines, expandIconSize, highlightStyles],
1030
- )
1031
-
1032
- // The VirtualScroll element is memoized WITHOUT hscroll in its deps: a horizontal-scroll tick only
1033
- // updates the container's `--dt-hscroll` variable (the numeric tracks translate via CSS and the
1034
- // memoized rows are skipped), so the virtualized body is not re-rendered. It still recomputes on
1035
- // vertical scroll (via treeLineBackground) and on any data/selection/visual change.
1036
- const virtualScrollElement = useMemo(
1037
- () => (
1038
- <VirtualScroll
1039
- ref={virtualScrollRef}
1040
- itemCount={virtualItems.length}
1041
- getItem={getItem}
1042
- getItemHeight={getItemHeight}
1043
- getItemKey={resolvedGetItemKey}
1044
- testId={testId}
1045
- contentProps={resolvedContentProps}
1046
- viewportSize={viewportHeight}
1047
- overscanCount={userOverscanCount}
1048
- onScroll={handleVirtualScroll}
1049
- onRangeChange={handleRangeChange}
1050
- className={virtualScrollClassName}
1051
- onWheelHorizontal={isGrid ? handleWheelHorizontal : undefined}
1052
- background={
1053
- <>
1054
- {isGrid && gridMetrics ? (
1055
- // Clip the connector-line canvas to the frozen name column so deep trees never bleed into the numeric region.
1056
- <div className="pointer-events-none absolute top-0 left-0 z-0 h-full overflow-hidden" style={{ width: gridMetrics.nameWidth }} aria-hidden="true">
1057
- {treeLineBackground}
1058
- </div>
1059
- ) : (
1060
- treeLineBackground
1061
- )}
1062
- {virtualScrollBackground}
1063
- </>
1064
- }
1065
- initialScrollIndex={initialScrollIndex}
1066
- initialScrollOffset={initialScrollOffset}
1067
- initialScrollAnchor={initialScrollAnchor}
1068
- onItemFocus={onItemFocus}
1069
- callbackThrottleMs={callbackThrottleMs}
1070
- contentInsets={virtualScrollContentInsets}
1071
- scrollBarOptions={scrollBarOptions}
1072
- behaviorOptions={behaviorOptions}>
1073
- {(item, index) => {
1074
- if (!item) return null
1075
- if (isGrid && grid && gridMetrics) {
1076
- return (
1077
- <DirectoryTreeGridRow
1078
- key={item.entry.absolutePath}
1079
- entry={item.entry}
1080
- indentLevel={item.indentLevel}
1081
- positionInSet={item.positionInSet}
1082
- setSize={item.setSize}
1083
- rowIndex={index + ((grid.showHeader ?? true) ? 2 : 1)}
1084
- isSelectedForAria={Boolean(selectedItems?.has(item.entry.absolutePath))}
1085
- rowHeight={item.rowHeight}
1086
- isDirOpen={safeIsExpanded}
1087
- columns={grid.columns}
1088
- numericTemplate={numericTemplate}
1089
- numericTotal={gridMetrics.numericTotal}
1090
- nameWidth={gridMetrics.nameWidth}
1091
- rowClassName={grid.rowClassName}
1092
- selection={{ onEntryClick, selectedPath: selectedPath ?? null, mode: selectionMode, selectedItems, onSelectionChange }}
1093
- expansion={{ toggleDirectory: toggle, onToggleDirectoryRecursive: handleDirectoryDoubleClick }}
1094
- visual={gridRowVisual}
1095
- />
1096
- )
1097
- }
1098
- return (
1099
- <DirectoryEntryItem
1100
- key={item.entry.absolutePath}
1101
- entry={item.entry}
1102
- indentLevel={item.indentLevel}
1103
- depth={item.depth}
1104
- positionInSet={item.positionInSet}
1105
- setSize={item.setSize}
1106
- isSelectedForAria={Boolean(selectedItems?.has(item.entry.absolutePath))}
1107
- flatIndex={index}
1108
- isActive={index === activeIndex}
1109
- registerRowRef={registerRowRef}
1110
- onNavigationKeyDown={handleNavigationKeyDown}
1111
- rowHeight={item.rowHeight}
1112
- isDirOpen={safeIsExpanded}
1113
- parentIsLast={item.parentIsLast}
1114
- renderChildren={false}
1115
- expansion={{ toggleDirectory: toggle, onToggleDirectoryRecursive: handleDirectoryDoubleClick }}
1116
- selection={{ onEntryClick, selectedPath: selectedPath ?? null, mode: selectionMode, selectedItems, onSelectionChange }}
1117
- visual={{
1118
- iconOverrides,
1119
- showExpandIcons,
1120
- showDirectoryIcons,
1121
- showFileIcons,
1122
- useCanvasExpandIcons: showTreeLines,
1123
- expandIconSize,
1124
- highlightStyles,
1125
- entryClassName,
1126
- entryStyle,
1127
- nameClassName,
1128
- nameStyle,
1129
- directoryNameClassName,
1130
- directoryNameStyle,
1131
- fileNameClassName,
1132
- fileNameStyle,
1133
- }}
1134
- />
1135
- )
1136
- }}
1137
- </VirtualScroll>
1138
- ),
1139
- [
1140
- virtualItems.length,
1141
- getItem,
1142
- getItemHeight,
1143
- resolvedGetItemKey,
1144
- testId,
1145
- resolvedContentProps,
1146
- activeIndex,
1147
- registerRowRef,
1148
- handleNavigationKeyDown,
1149
- viewportHeight,
1150
- userOverscanCount,
1151
- handleVirtualScroll,
1152
- handleRangeChange,
1153
- virtualScrollClassName,
1154
- isGrid,
1155
- handleWheelHorizontal,
1156
- gridMetrics,
1157
- treeLineBackground,
1158
- virtualScrollBackground,
1159
- initialScrollIndex,
1160
- initialScrollOffset,
1161
- initialScrollAnchor,
1162
- onItemFocus,
1163
- callbackThrottleMs,
1164
- virtualScrollContentInsets,
1165
- scrollBarOptions,
1166
- behaviorOptions,
1167
- grid,
1168
- numericTemplate,
1169
- safeIsExpanded,
1170
- onEntryClick,
1171
- selectedPath,
1172
- selectionMode,
1173
- selectedItems,
1174
- onSelectionChange,
1175
- toggle,
1176
- handleDirectoryDoubleClick,
1177
- gridRowVisual,
1178
- iconOverrides,
1179
- showExpandIcons,
1180
- showDirectoryIcons,
1181
- showFileIcons,
1182
- showTreeLines,
1183
- expandIconSize,
1184
- highlightStyles,
1185
- entryClassName,
1186
- entryStyle,
1187
- nameClassName,
1188
- nameStyle,
1189
- directoryNameClassName,
1190
- directoryNameStyle,
1191
- fileNameClassName,
1192
- fileNameStyle,
1193
- ],
1194
- )
1195
-
1196
- if (!(grid && gridMetrics)) {
1197
- return (
1198
- <div ref={containerRef} className={containerClasses} style={containerStyle} role="tree" aria-label={ariaLabelledBy ? undefined : ariaLabel} aria-labelledby={ariaLabelledBy} aria-multiselectable={selectionMode === "multiple" ? true : undefined}>
1199
- {virtualScrollElement}
1200
- </div>
1201
- )
1202
- }
1203
-
1204
- const showHeader = grid.showHeader ?? true
1205
- const showFooter = grid.showFooter ?? false
1206
- const gridContainerStyle = { ...containerStyle, "--dt-hscroll": `${hscroll}px` } as CSSProperties
1207
-
1208
- return (
1209
- <div
1210
- ref={containerRef}
1211
- className={twMerge(containerClasses, "dt-grid")}
1212
- style={gridContainerStyle}
1213
- role="treegrid"
1214
- aria-label={ariaLabelledBy ? undefined : ariaLabel}
1215
- aria-labelledby={ariaLabelledBy}
1216
- aria-multiselectable={selectionMode === "multiple" ? true : undefined}
1217
- aria-rowcount={virtualItems.length + ((grid.showHeader ?? true) ? 1 : 0)}>
1218
- {/* treegrid が直接所有するのは rowgroup。行を裸で置くと所有関係が壊れる */}
1219
- {showHeader && (
1220
- // biome-ignore lint/a11y/useSemanticElements: 仮想スクロールの treegrid は絶対配置行を使うため native table 要素にできない。ARIA ロールで意味を提供する
1221
- <div role="rowgroup">
1222
- <DirectoryTreeGridHeaderRow columns={grid.columns} numericTemplate={numericTemplate} numericTotal={gridMetrics.numericTotal} nameWidth={gridMetrics.nameWidth} scrollBarWidth={gridScrollBarWidth} className={grid.headerClassName} />
1223
- </div>
1224
- )}
1225
- <div ref={bodyRef} className="dt-grid-body">
1226
- {virtualScrollElement}
1227
- </div>
1228
- {maxHScroll > 0 && (
1229
- <div className="dt-grid-hscrollbar-row">
1230
- <div className="dt-grid-scrollbar-spacer" style={{ width: gridMetrics.nameWidth }} aria-hidden="true" />
1231
- <ScrollBar
1232
- horizontal
1233
- contentSize={gridMetrics.numericTotal}
1234
- viewportSize={gridMetrics.numericVisible}
1235
- scrollPosition={hscroll}
1236
- scrollBarWidth={gridScrollBarWidth}
1237
- onScroll={(next) => {
1238
- const resolved = typeof next === "function" ? next(hscroll) : next
1239
- const clamped = clampHScroll(resolved, maxHScroll)
1240
- setHscroll(clamped)
1241
- return clamped
1242
- }}
1243
- />
1244
- <div className="dt-grid-scrollbar-spacer" style={{ width: gridScrollBarWidth }} aria-hidden="true" />
1245
- </div>
1246
- )}
1247
- {showFooter && (
1248
- // biome-ignore lint/a11y/useSemanticElements: 同上 (フッタ行も絶対配置レイアウトの一部)
1249
- <div role="rowgroup">
1250
- <DirectoryTreeGridFooterRow columns={grid.columns} numericTemplate={numericTemplate} numericTotal={gridMetrics.numericTotal} nameWidth={gridMetrics.nameWidth} scrollBarWidth={gridScrollBarWidth} allEntries={allEntriesFlat} className={grid.footerClassName} />
1251
- </div>
1252
- )}
1253
- </div>
1254
- )
1255
- }
1256
-
1257
- export { directoryTreeClasses }