@aiquants/directory-tree 3.2.0 → 3.4.0

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 (39) hide show
  1. package/dist/DirectoryTree.d.ts +24 -0
  2. package/dist/DirectoryTree.d.ts.map +1 -0
  3. package/dist/DirectoryTreeGrid.d.ts +67 -0
  4. package/dist/DirectoryTreeGrid.d.ts.map +1 -0
  5. package/dist/TreeLine.d.ts +9 -0
  6. package/dist/TreeLine.d.ts.map +1 -0
  7. package/dist/cli.server.d.ts +2 -0
  8. package/dist/cli.server.d.ts.map +1 -0
  9. package/dist/entryRendering.d.ts +55 -0
  10. package/dist/entryRendering.d.ts.map +1 -0
  11. package/dist/gridUtils.d.ts +47 -0
  12. package/dist/gridUtils.d.ts.map +1 -0
  13. package/dist/index.cjs +2 -2
  14. package/dist/index.d.ts +14 -2
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +807 -799
  17. package/dist/logger.d.ts +98 -0
  18. package/dist/logger.d.ts.map +1 -0
  19. package/dist/scrollAnchor.d.ts +39 -0
  20. package/dist/scrollAnchor.d.ts.map +1 -0
  21. package/dist/src/DirectoryTree.d.ts.map +1 -1
  22. package/dist/src/entryRendering.d.ts +0 -5
  23. package/dist/src/entryRendering.d.ts.map +1 -1
  24. package/dist/src/types.d.ts +0 -11
  25. package/dist/src/types.d.ts.map +1 -1
  26. package/dist/styles/directory-tree.standalone.css +1 -1
  27. package/dist/types.d.ts +645 -0
  28. package/dist/types.d.ts.map +1 -0
  29. package/dist/useDirectoryTreeState.d.ts +15 -0
  30. package/dist/useDirectoryTreeState.d.ts.map +1 -0
  31. package/dist/useEntryInteraction.d.ts +20 -0
  32. package/dist/useEntryInteraction.d.ts.map +1 -0
  33. package/package.json +3 -3
  34. package/src/DirectoryTree.spec.md +51 -2
  35. package/src/DirectoryTree.tsx +36 -11
  36. package/src/DirectoryTreeGrid.tsx +6 -3
  37. package/src/entryRendering.tsx +20 -61
  38. package/src/index.ts +1 -0
  39. package/src/types.ts +49 -4
@@ -0,0 +1,20 @@
1
+ import { MouseEvent } from 'react';
2
+ import { DirectoryEntry, DirectoryTreeClickEvent } from './types.ts';
3
+ export type UseEntryInteractionArgs = {
4
+ entry: DirectoryEntry;
5
+ isDirectory: boolean;
6
+ isExpanded: boolean;
7
+ isItemSelected: boolean;
8
+ selectionMode: "none" | "single" | "multiple";
9
+ onSelectionChange?: (entry: DirectoryEntry, isSelected: boolean) => void;
10
+ onEntryClick: (event: DirectoryTreeClickEvent) => void;
11
+ toggleDirectory: (path: string) => void;
12
+ onToggleDirectoryRecursive: (entry: DirectoryEntry) => void;
13
+ };
14
+ /**
15
+ * Returns a click handler implementing: fire onEntryClick immediately; for files toggle
16
+ * selection; for directories, single click toggles (after a delay) and double click expands
17
+ * recursively — unless the consumer calls preventDefault() on the click event.
18
+ */
19
+ export declare const useEntryInteraction: ({ entry, isDirectory, isExpanded, isItemSelected, selectionMode, onSelectionChange, onEntryClick, toggleDirectory, onToggleDirectoryRecursive }: UseEntryInteractionArgs) => (e: MouseEvent<HTMLDivElement>) => void;
20
+ //# sourceMappingURL=useEntryInteraction.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useEntryInteraction.d.ts","sourceRoot":"","sources":["../src/useEntryInteraction.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,OAAO,CAAA;AAEvC,OAAO,KAAK,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAA;AAKzE,MAAM,MAAM,uBAAuB,GAAG;IAClC,KAAK,EAAE,cAAc,CAAA;IACrB,WAAW,EAAE,OAAO,CAAA;IACpB,UAAU,EAAE,OAAO,CAAA;IACnB,cAAc,EAAE,OAAO,CAAA;IACvB,aAAa,EAAE,MAAM,GAAG,QAAQ,GAAG,UAAU,CAAA;IAC7C,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,OAAO,KAAK,IAAI,CAAA;IACxE,YAAY,EAAE,CAAC,KAAK,EAAE,uBAAuB,KAAK,IAAI,CAAA;IACtD,eAAe,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;IACvC,0BAA0B,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,CAAA;CAC9D,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,GAAI,iJAAiJ,uBAAuB,SAWhM,UAAU,CAAC,cAAc,CAAC,SA+BrC,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiquants/directory-tree",
3
- "version": "3.2.0",
3
+ "version": "3.4.0",
4
4
  "description": "High-performance directory tree component for React with virtual scrolling and file selection",
5
5
  "sideEffects": [
6
6
  "**/*.css"
@@ -33,7 +33,7 @@
33
33
  "peerDependencies": {
34
34
  "react": "^19.2.7",
35
35
  "react-dom": "^19.2.7",
36
- "@aiquants/virtualscroll": "^1.22.0"
36
+ "@aiquants/virtualscroll": "^1.23.0"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@tailwindcss/cli": "^4.1.18",
@@ -54,7 +54,7 @@
54
54
  "vite": "^7.2.7",
55
55
  "vite-plugin-dts": "^4.5.4",
56
56
  "vitest": "^3.2.4",
57
- "@aiquants/virtualscroll": "1.22.0"
57
+ "@aiquants/virtualscroll": "1.23.0"
58
58
  },
59
59
  "keywords": [
60
60
  "react",
@@ -4,6 +4,7 @@
4
4
 
5
5
  | Version | Date | Author | Reviewer | Approver | Summary of Changes |
6
6
  | :--- | :--- | :--- | :--- | :--- | :--- |
7
+ | 3.4.0 | 2026-08-08 | Claude Opus 5 | | | Add the optional top-level `sort` prop (`DirectoryEntryComparator`), applied to every sibling group inside `collectTreeData` immediately before flattening. Only a shallow copy of each sibling array is sorted, so every `DirectoryEntry` object and every `children` array keeps its identity and consumer-side memoization (row memo, reference-preserving decorators, hydration caches) survives a re-sort; the caller's `entries` arrays are never mutated. `isLastChild` and the ancestor chain derive from the loop index, so connector geometry follows the sorted order automatically, in grid mode too. Ordering is deliberately a top-level prop rather than a `visual` member because it changes row semantics rather than presentation. Also fixes a latent defect exposed by any reordering: `virtualScroll.getItemKey` was accepted by the type but never destructured or forwarded, so `VirtualScroll` fell back to index keying and every row whose index-to-entry mapping changed was unmounted and remounted; it is now forwarded, defaulting to `entry.absolutePath`. |
7
8
  | 3.1.0 | 2026-07-31 | Claude Opus 5 | | | Add opt-in `virtualScroll.preserveScrollAnchor`: when the row list mutates (e.g. streaming insertions above the viewport), the first visible row is kept visually stationary via a pre-paint (`useLayoutEffect`) scroll correction. Pure helpers `captureScrollAnchor` / `resolveAnchorScroll` live in `scrollAnchor.ts` (unit-tested). The anchor is captured from the **live pane position** (`getScrollPosition()`, inset-adjusted) rather than the RAF-throttled `onScroll` mirror, so corrections landing mid-scroll do not rubber-band by the notification lag; the handle's clamped return value is adopted, and the component's own `scrollPosition` state is updated **in the same pre-paint flush** so the tree-line canvas / expand glyphs never misalign from the rows. No correction at the top of the list (scroll 0) and pixel-position fallback when the anchored row vanished. Known trade-off: the programmatic correction goes through the ScrollPane handle, which stops an in-progress pointer-drag inertia fling (same as the pre-existing compensation path). Also removed a leftover dead `isEmpty` local. |
8
9
  | 3.0.1 | 2026-07-07 | Antigravity | | | Fix: `columns[0].className` is now correctly applied to the name column cells in the header and footer (TreeGrid mode), ensuring consistency with body rows and data columns. |
9
10
  | 3.0.0 | 2026-07-07 | Claude Opus 4.8 | | | Add TreeGrid (columns) mode via the optional `grid` prop (`DirectoryTreeGrid` / `DirectoryTreeColumn`). The name/tree column is frozen on the left (indent + connector lines confined there); the remaining columns render as a vertically-aligned grid with an aligned column header, an optional footer that aggregates over **all** entries (collapsed subtrees included), and a horizontally scrollable numeric region (the name column stays frozen). Grid mode uses `role="treegrid"` / `row` / `gridcell` / `columnheader`. Enabled by a new opt-in `onWheelHorizontal` prop on `@aiquants/virtualscroll` (axis-aware wheel). `grid` and each `render` / `footer` must be stable references. Note: connector lines are rendered on a `<canvas>` (this document previously described them as a single SVG component — corrected here). |
@@ -134,6 +135,7 @@ The `DirectoryTree` component accepts the following props:
134
135
  | `visual` | `object` | No | - | Visual customization options. 表示のカスタマイズオプション。 |
135
136
  | `virtualScroll` | `DirectoryTreeVirtualScrollOptions` | No | - | Additional options for VirtualScroll integration. Includes `viewportHeightOverride` and `preserveScrollAnchor` (opt-in, default `false`: keeps the first visible row visually stationary across row-list mutations such as streaming insertions above the viewport; inactive at scroll 0; falls back to pixel-position when the anchored row vanished). VirtualScroll の設定を上書きするオプション。`preserveScrollAnchor` (既定 `false`) を有効化すると、行リスト変異時に先頭可視行を画面上で静止させる (最上部では不作動、アンカー行消失時はピクセル位置維持へフォールバック)。 |
136
137
  | `grid` | `DirectoryTreeGrid` | No | - | TreeGrid (columns) mode. When present, renders a frozen name column + aligned data columns with header/footer and a horizontally scrollable numeric region. See §3.2.4. TreeGrid(列)モード。指定時は凍結名前列+整列データ列を描画する(§3.2.4)。 |
138
+ | `sort` | `DirectoryEntryComparator` | No | - | Comparator applied to every sibling group before flattening. Only a shallow copy of each sibling array is sorted, so entry objects and their `children` arrays keep identity. Omit to render in the given order. **Stable reference required.** See §3.2.5. フラット化前に各兄弟グループへ適用する比較関数。兄弟配列の浅いコピーのみを並べ替えるため、エントリと `children` の identity は保持される。省略時は与えられた順序のまま。**参照安定必須**(§3.2.5)。 |
137
139
 
138
140
  #### 3.2.1. `expansion` Configuration
139
141
 
@@ -225,6 +227,44 @@ entries, and a horizontally scrollable numeric region. When omitted, the classic
225
227
  7. With empty `entries`, grid mode still renders the header and footer (footer aggregates over 0 entries) with the `treegrid` role; only the body has no rows.
226
228
  8. Horizontal scrolling only updates the shared CSS variable — the virtualized body is **not** re-rendered (the `VirtualScroll` element is memoized and the rows are `React.memo`-skipped).
227
229
 
230
+ #### 3.2.5. `sort` (sibling ordering)
231
+
232
+ `sort` is a plain comparator over two entries that share the same parent. It is applied inside the single
233
+ traversal that turns sibling order into row order, immediately before flattening, at **every** depth.
234
+ `sort` は同一の親を持つ 2 エントリを比較する関数で、兄弟順序が行順序へ変換される唯一の走査内で、フラット化直前に全階層へ適用される。
235
+
236
+ ```typescript
237
+ export type DirectoryEntryComparator = (a: DirectoryEntry, b: DirectoryEntry) => number
238
+ ```
239
+
240
+ **Guarantees / behavior:**
241
+
242
+ 1. **Entry identity is preserved.** Only a shallow copy of each sibling array is sorted (`[...siblings].sort(sort)`);
243
+ no `DirectoryEntry` object and no `children` array is cloned or mutated. Consumer-side memoization that keys on
244
+ entry identity — the internal row memo, reference-preserving decorators, hydration caches — therefore keeps working.
245
+ エントリ本体と `children` 配列は複製も変更もされないため、identity に依存する利用側のメモ化はそのまま機能する。
246
+ 2. **The `entries` prop is never mutated.** The caller's arrays are left in their original order.
247
+ 3. **Connector geometry follows the sorted order.** `isLastChild` and the ancestor chain derive from the loop index,
248
+ so the last *rendered* sibling receives the stub connector.
249
+ 4. Ordering is not a presentation concern (it changes row semantics and connector geometry, and applies identically in
250
+ grid mode), which is why `sort` is a top-level prop rather than a member of `visual`.
251
+ 5. **Stable reference required** (memoize with `useMemo` / `useCallback`) — a new identity each render re-runs the
252
+ whole traversal, the same constraint as `visual.itemHeight` and `grid.columns`.
253
+ 6. Omitting `sort` skips the copy entirely: entries render in exactly the order given.
254
+ 7. Sorting is applied to rows only; `grid.columns[].footer` still aggregates over all entries in input order, which is
255
+ order-insensitive by construction.
256
+
257
+ **Row keying.** `virtualScroll.getItemKey` is forwarded to `VirtualScroll`, and when it is omitted rows are keyed by
258
+ `entry.absolutePath` instead of by index. This is what lets a re-sort *move* existing rows rather than unmount and
259
+ remount every row whose index-to-entry mapping changed.
260
+ `virtualScroll.getItemKey` は `VirtualScroll` へ転送され、未指定時の既定行キーは `entry.absolutePath`。これにより並べ替え時に既存行は移動するだけで再生成されない。
261
+
262
+ ```typescript
263
+ const compare = useMemo<DirectoryEntryComparator>(() => (a, b) => a.name.localeCompare(b.name, "en", { numeric: true }), [])
264
+
265
+ <DirectoryTree entries={entries} expansion={...} selection={...} sort={compare} />
266
+ ```
267
+
228
268
  ### 3.3. Usage
229
269
 
230
270
  Here is a basic example of how to use the `DirectoryTree` component with the `useDirectoryTreeState` hook.
@@ -462,13 +502,22 @@ guards). Run `pnpm run test:coverage`.
462
502
  * **Memo comparator** (`isEntryExpanded`, entry-reference change, directory expansion change).
463
503
  * **`isEntryExpanded`** helper: directory expanded/collapsed, file short-circuit.
464
504
 
465
- ### 9.4. Pure helpers
505
+ ### 9.4. Sibling ordering & row keying ([DirectoryTree.sort.test.tsx](../tests/DirectoryTree.sort.test.tsx))
506
+
507
+ * **Default order**: without `sort`, rows appear in exactly the input order.
508
+ * **Ordering**: the comparator orders root siblings and, with the same comparator, the siblings of every expanded subtree; a descending comparator produces the exact inverse of the ascending one.
509
+ * **Identity preservation**: after sorting, the entry object handed to a row is `Object.is`-identical to the one in the input tree, and so is its `children` array.
510
+ * **Non-mutation**: the caller's `entries` arrays keep their original order.
511
+ * **Row stability**: re-rendering with a different comparator *moves* the DOM node of an unchanged entry rather than recreating it.
512
+ * **`getItemKey` forwarding**: a caller-supplied `virtualScroll.getItemKey` is actually invoked, and the default keys rows by `absolutePath` (proven by reordering `entries` and asserting DOM-node identity).
513
+
514
+ ### 9.5. Pure helpers
466
515
 
467
516
  * **[gridUtils.test.ts](../tests/gridUtils.test.ts)**: `buildNumericTemplate`, `computeGridMetrics`, `clampHScroll`, `flattenAllEntries` (incl. default/invalid widths, zero-width viewport, NaN clamp).
468
517
  * **[treeLineGeometry.test.ts](../tests/treeLineGeometry.test.ts)**: `buildTreeLineGeometry` — every connector variant (directory/file, last-child, ancestor lines, glyphs), `hideLines` skip, empty input, glyph-size fallback, and defensive out-of-bounds fallbacks.
469
518
  * **[useEntryInteraction.test.tsx](../tests/useEntryInteraction.test.tsx)**: file select, directory single-click (delayed toggle), double-click (recursive), `preventDefault`, unmount timer cleanup.
470
519
  * **[entryRendering.test.tsx](../tests/entryRendering.test.tsx)**: `resolveExpandIcon`, `resolveEntryIcon` (all icon paths + sanitizer edge cases), `getFileExtension`.
471
520
 
472
- ### 9.5. VirtualScroll horizontal wheel (`@aiquants/virtualscroll`)
521
+ ### 9.6. VirtualScroll horizontal wheel (`@aiquants/virtualscroll`)
473
522
 
474
523
  * **[wheel-horizontal.spec.tsx](../../virtualscroll/tests/integration/wheel-horizontal.spec.tsx)**: `onWheelHorizontal` fires on horizontal-dominant / shift+wheel gestures, not on vertical-dominant; `deltaMode` LINE/PAGE scaling; a no-op (backward-compatible) when the handler is absent.
@@ -12,7 +12,7 @@ import { DEFAULT_ITEM_HEIGHT, directoryTreeClasses, EXPAND_GLYPH_SIZE, getFileEx
12
12
  import { buildNumericTemplate, clampHScroll, computeGridMetrics, DEFAULT_GRID_SCROLLBAR_WIDTH, flattenAllEntries } from "./gridUtils.ts"
13
13
  import { captureScrollAnchor, resolveAnchorScroll } from "./scrollAnchor.ts"
14
14
  import { TreeLine } from "./TreeLine.tsx"
15
- import type { DirectoryEntry, DirectoryEntryItemProps, DirectoryTreeProps, DirectoryTreeVirtualScrollOptions, TreeLineGeometry, TreeLineGlyph, TreeLineItemInfo, TreeLineSegment } from "./types.ts"
15
+ import type { DirectoryEntry, DirectoryEntryComparator, DirectoryEntryItemProps, DirectoryTreeProps, DirectoryTreeVirtualScrollOptions, TreeLineGeometry, TreeLineGlyph, TreeLineItemInfo, TreeLineSegment } from "./types.ts"
16
16
  import { useEntryInteraction } from "./useEntryInteraction.ts"
17
17
 
18
18
  /**
@@ -54,17 +54,21 @@ type TreeTraversalResult = {
54
54
  /**
55
55
  * @function collectTreeData
56
56
  * @description Traverses directory entries to build flattened items and tree line metadata.
57
+ * Sibling groups are ordered by the optional comparator before flattening.
57
58
  * ディレクトリエントリを走査してフラットなアイテムとツリーライン用メタデータを構築する。
59
+ * フラット化の前に、任意の比較関数で兄弟グループを並べ替える。
58
60
  */
59
- const collectTreeData = (entries: DirectoryEntry[], resolver: (absolutePath: string, relativePath?: string) => boolean, includeTreeLines: boolean, removeRootIndent: boolean): TreeTraversalResult => {
61
+ const collectTreeData = (entries: DirectoryEntry[], resolver: (absolutePath: string, relativePath?: string) => boolean, includeTreeLines: boolean, removeRootIndent: boolean, sort?: DirectoryEntryComparator): TreeTraversalResult => {
60
62
  const flatItems: FlattenedEntry[] = []
61
63
  const lineItems: TreeLineItemInfo[] = []
62
64
  let maxIndent = 0
63
65
 
64
66
  const walk = (currentEntries: DirectoryEntry[], indentLevel: number, ancestorChain: boolean[]): void => {
65
- for (let index = 0; index < currentEntries.length; index++) {
66
- const entry = currentEntries[index]
67
- const isLastChild = index === currentEntries.length - 1
67
+ // 並べ替えは兄弟配列の浅いコピーに対してのみ行い、エントリと children の identity を保持する
68
+ const ordered = sort ? [...currentEntries].sort(sort) : currentEntries
69
+ for (let index = 0; index < ordered.length; index++) {
70
+ const entry = ordered[index]
71
+ const isLastChild = index === ordered.length - 1
68
72
  const nextAncestorChain = [...ancestorChain, isLastChild]
69
73
  const isDirectory = entry.children !== undefined
70
74
  const isExpanded = isDirectory && resolver(entry.absolutePath, entry.relativePath)
@@ -332,6 +336,9 @@ const DirectoryEntryItem = memo<DirectoryEntryItemProps>(
332
336
  showFileIcons = true,
333
337
  useCanvasExpandIcons = false,
334
338
  expandIconSize,
339
+ typeIconSize,
340
+ fontSize,
341
+ indentSize = INDENT_SIZE,
335
342
  highlightStyles,
336
343
  entryClassName,
337
344
  entryStyle,
@@ -350,7 +357,7 @@ const DirectoryEntryItem = memo<DirectoryEntryItemProps>(
350
357
  const isExpanded = isDirectory && isDirOpen(entry.absolutePath)
351
358
  const isSelected = entry.absolutePath === selectedPath
352
359
  const isItemSelected = !isDirectory && selectedItems?.has(entry.absolutePath)
353
- const extension = isDirectory ? undefined : (getFileExtension(entry.name) || getFileExtension(entry.relativePath) || getFileExtension(entry.absolutePath))
360
+ const extension = isDirectory ? undefined : getFileExtension(entry.name) || getFileExtension(entry.relativePath) || getFileExtension(entry.absolutePath)
354
361
 
355
362
  /**
356
363
  * @effect Lazy Children Loading
@@ -395,15 +402,19 @@ const DirectoryEntryItem = memo<DirectoryEntryItemProps>(
395
402
  ...(!isDirectory && (isSelected || isItemSelected) ? highlightStyles?.itemSelectedStyle : {}),
396
403
  }
397
404
 
405
+ const typeIconStyle = typeIconSize ? { width: typeIconSize, height: typeIconSize } : undefined
406
+ const fontSizeStyle = fontSize ? { fontSize: typeof fontSize === "number" ? `${fontSize}px` : fontSize } : undefined
407
+
398
408
  return (
399
409
  <Fragment key={entry.absolutePath}>
400
410
  <div
401
411
  className={entryClasses}
402
412
  style={{
403
- paddingLeft: `${Math.max(0, indentLevel * INDENT_SIZE)}px`,
404
- transform: indentLevel < 0 ? `translateX(${indentLevel * INDENT_SIZE}px)` : undefined,
405
- width: indentLevel < 0 ? `calc(100% + ${Math.abs(indentLevel * INDENT_SIZE)}px)` : undefined,
413
+ paddingLeft: `${Math.max(0, indentLevel * indentSize)}px`,
414
+ transform: indentLevel < 0 ? `translateX(${indentLevel * indentSize}px)` : undefined,
415
+ width: indentLevel < 0 ? `calc(100% + ${Math.abs(indentLevel * indentSize)}px)` : undefined,
406
416
  height: `${rowHeight}px`,
417
+ ...fontSizeStyle,
407
418
  ...customHighlightStyle,
408
419
  ...entryStyle,
409
420
  ...entry.style,
@@ -421,10 +432,15 @@ const DirectoryEntryItem = memo<DirectoryEntryItemProps>(
421
432
  aria-expanded={isDirectory ? isExpanded : undefined}
422
433
  aria-label={`${entry.name} (${isDirectory ? "directory" : "file"})`}>
423
434
  {(showExpandIcons || useCanvasExpandIcons) && <span className={expandIconClasses}>{expandIconContent}</span>}
424
- {(isDirectory ? showDirectoryIcons : showFileIcons) && <span className={typeIconClasses}>{resolvedIcon}</span>}
435
+ {(isDirectory ? showDirectoryIcons : showFileIcons) && (
436
+ <span className={typeIconClasses} style={typeIconStyle}>
437
+ {resolvedIcon}
438
+ </span>
439
+ )}
425
440
  <span
426
441
  className={nameClasses}
427
442
  style={{
443
+ ...fontSizeStyle,
428
444
  ...nameStyle,
429
445
  ...(isDirectory ? directoryNameStyle : fileNameStyle),
430
446
  }}
@@ -563,6 +579,7 @@ export const DirectoryTree = ({
563
579
  } = {},
564
580
  virtualScroll: virtualScrollOptions,
565
581
  grid,
582
+ sort,
566
583
  }: DirectoryTreeProps) => {
567
584
  const isGrid = grid !== undefined
568
585
  const [isClient, setIsClient] = useState(false)
@@ -589,6 +606,7 @@ export const DirectoryTree = ({
589
606
  scrollBarOptions,
590
607
  behaviorOptions,
591
608
  preserveScrollAnchor = false,
609
+ getItemKey: userGetItemKey,
592
610
  }: DirectoryTreeVirtualScrollOptions = virtualScrollOptions ?? {}
593
611
 
594
612
  const [scrollPosition, setScrollPosition] = useState(typeof initialScrollOffset === "number" ? initialScrollOffset : 0)
@@ -707,7 +725,7 @@ export const DirectoryTree = ({
707
725
  // frozen name column (which must start at x=0), so it is intentionally ignored in grid mode.
708
726
  // grid モードでは名前列を x=0 に凍結するため、負インデントに依存する removeRootIndent は無効化する。
709
727
  const effectiveRemoveRootIndent = isGrid ? false : removeRootIndent
710
- const { flatItems, lineItems, maxIndent } = useMemo(() => collectTreeData(entries, safeIsExpanded, showTreeLines, effectiveRemoveRootIndent), [entries, safeIsExpanded, showTreeLines, effectiveRemoveRootIndent])
728
+ const { flatItems, lineItems, maxIndent } = useMemo(() => collectTreeData(entries, safeIsExpanded, showTreeLines, effectiveRemoveRootIndent, sort), [entries, safeIsExpanded, showTreeLines, effectiveRemoveRootIndent, sort])
711
729
 
712
730
  // 各行の高さを解決する。number ならそのまま、関数なら (entry, flatIndex) で算出する。
713
731
  // 不正値 (NaN / Infinity / 0 / 負値) は既定高さにフォールバックし、オフセット表の単調性と CSS 高さの妥当性を保証する。
@@ -734,6 +752,11 @@ export const DirectoryTree = ({
734
752
  // VirtualScroll に渡す高さ取得関数。identity は itemHeights が変わったときだけ更新される。
735
753
  const getItemHeight = useCallback((index: number) => virtualItems[index]?.rowHeight ?? DEFAULT_ITEM_HEIGHT, [virtualItems])
736
754
 
755
+ // 行キーは既定で絶対パス。index キーのままだと並べ替えや挿入で index→entry の対応が変わるたびに
756
+ // 可視行が unmount/remount され、行メモも DOM 状態 (hover 等) も失われる。
757
+ const defaultGetItemKey = useCallback((index: number) => virtualItems[index]?.entry.absolutePath ?? index, [virtualItems])
758
+ const resolvedGetItemKey = userGetItemKey ?? defaultGetItemKey
759
+
737
760
  const treeLineGeometry = useMemo(
738
761
  () => (!showTreeLines || lineItems.length === 0 ? { segmentsByItem: [], glyphsByItem: [] } : buildTreeLineGeometry(lineItems, itemHeights, itemOffsets, INDENT_SIZE, showTreeLines, expandIconSize ?? EXPAND_GLYPH_SIZE)),
739
762
  [lineItems, itemHeights, itemOffsets, showTreeLines, expandIconSize],
@@ -855,6 +878,7 @@ export const DirectoryTree = ({
855
878
  itemCount={virtualItems.length}
856
879
  getItem={getItem}
857
880
  getItemHeight={getItemHeight}
881
+ getItemKey={resolvedGetItemKey}
858
882
  viewportSize={viewportHeight}
859
883
  overscanCount={userOverscanCount}
860
884
  onScroll={handleVirtualScroll}
@@ -939,6 +963,7 @@ export const DirectoryTree = ({
939
963
  virtualItems.length,
940
964
  getItem,
941
965
  getItemHeight,
966
+ resolvedGetItemKey,
942
967
  viewportHeight,
943
968
  userOverscanCount,
944
969
  handleVirtualScroll,
@@ -23,6 +23,9 @@ export type GridRowVisual = {
23
23
  showFileIcons?: boolean
24
24
  useCanvasExpandIcons?: boolean
25
25
  expandIconSize?: number
26
+ typeIconSize?: number
27
+ fontSize?: number | string
28
+ indentSize?: number
26
29
  highlightStyles?: HighlightStyles
27
30
  }
28
31
 
@@ -81,7 +84,7 @@ export const DirectoryTreeGridRow = memo<DirectoryTreeGridRowProps>(
81
84
  rowClassName,
82
85
  selection: { onEntryClick, selectedPath, mode: selectionMode = "none", selectedItems, onSelectionChange },
83
86
  expansion: { toggleDirectory, onToggleDirectoryRecursive },
84
- visual: { iconOverrides, showExpandIcons = true, showDirectoryIcons = true, showFileIcons = true, useCanvasExpandIcons = false, expandIconSize, highlightStyles },
87
+ visual: { iconOverrides, showExpandIcons = true, showDirectoryIcons = true, showFileIcons = true, useCanvasExpandIcons = false, expandIconSize, indentSize = INDENT_SIZE, highlightStyles },
85
88
  }) => {
86
89
  const [isHovered, setIsHovered] = useState(false)
87
90
 
@@ -89,7 +92,7 @@ export const DirectoryTreeGridRow = memo<DirectoryTreeGridRowProps>(
89
92
  const isExpanded = isDirectory && isDirOpen(entry.absolutePath)
90
93
  const isSelected = entry.absolutePath === selectedPath
91
94
  const isItemSelected = !isDirectory && Boolean(selectedItems?.has(entry.absolutePath))
92
- const extension = isDirectory ? undefined : (getFileExtension(entry.name) || getFileExtension(entry.relativePath) || getFileExtension(entry.absolutePath))
95
+ const extension = isDirectory ? undefined : getFileExtension(entry.name) || getFileExtension(entry.relativePath) || getFileExtension(entry.absolutePath)
93
96
 
94
97
  const handleInteraction = useEntryInteraction({ entry, isDirectory, isExpanded, isItemSelected, selectionMode, onSelectionChange, onEntryClick, toggleDirectory, onToggleDirectoryRecursive })
95
98
 
@@ -141,7 +144,7 @@ export const DirectoryTreeGridRow = memo<DirectoryTreeGridRowProps>(
141
144
  onKeyDown={(e) => e.key === "Enter" && handleInteraction(e as unknown as MouseEvent<HTMLDivElement>)}
142
145
  tabIndex={0}>
143
146
  {/* Frozen name/tree cell — indent applied here only. / 凍結名前セル(インデントはここだけ)。 */}
144
- <div className={twMerge("dt-grid-name-cell", nameColumn?.className)} role="gridcell" style={{ width: nameWidth, paddingLeft: Math.max(0, indentLevel * INDENT_SIZE) }}>
147
+ <div className={twMerge("dt-grid-name-cell", nameColumn?.className)} role="gridcell" style={{ width: nameWidth, paddingLeft: Math.max(0, indentLevel * indentSize) }}>
145
148
  {(showExpandIcons || useCanvasExpandIcons) && <span className={expandIconClasses}>{expandIconContent}</span>}
146
149
  {(isDirectory ? showDirectoryIcons : showFileIcons) && <span className={typeIconClasses}>{resolvedIcon}</span>}
147
150
  <span className={nameLabelClasses}>{nameContent}</span>
@@ -7,41 +7,27 @@
7
7
  * 従来行と TreeGrid 行が共有する定数・クラス・アイコン解決ヘルパ。循環 import 回避のため分離。
8
8
  */
9
9
  import { ChevronDownIcon, ChevronRightIcon, FolderIcon } from "@heroicons/react/24/solid"
10
- import {
11
- FileAudio,
12
- FileCode,
13
- FileCsv,
14
- FileDoc,
15
- FileIcon,
16
- FileImage,
17
- FileMd,
18
- FilePdf,
19
- FilePpt,
20
- FileText,
21
- FileVideo,
22
- FileXls,
23
- FileZip,
24
- } from "@phosphor-icons/react"
10
+ import { FileAudio, FileCode, FileCsv, FileDoc, FileIcon, FileImage, FileMd, FilePdf, FilePpt, FileText, FileVideo, FileXls, FileZip } from "@phosphor-icons/react"
25
11
  import type { ReactNode } from "react"
26
12
  import { twMerge } from "tailwind-merge"
27
13
  import type { DirectoryTreeIconOverrides, DirectoryTreeIconRenderContext, DirectoryTreeIconRenderer } from "./types.ts"
28
14
 
29
- /** Default row height in px. / 各行の高さの既定値 (px)。 */
30
- export const DEFAULT_ITEM_HEIGHT = 20
31
- /** Indentation per depth level in px. / 1 階層あたりのインデント幅 (px)。 */
32
- export const INDENT_SIZE = 16
33
- /** Standard expand glyph size. / 展開アイコンの標準サイズ。 */
34
- export const EXPAND_GLYPH_SIZE = 12
15
+ /** Default row height in px. / 各行の高さの既定値 (px)。 FHD環境に最適化されたコンパクト設計 (18px) */
16
+ export const DEFAULT_ITEM_HEIGHT = 18
17
+ /** Indentation per depth level in px. / 1 階層あたりのインデント幅 (px)。 FHD環境に最適化されたコンパクト設計 (12px) */
18
+ export const INDENT_SIZE = 12
19
+ /** Standard expand glyph size. / 展開アイコンの標準サイズ (10px)。 */
20
+ export const EXPAND_GLYPH_SIZE = 10
35
21
 
36
22
  /**
37
23
  * TailwindCSS v4 class names for DirectoryTree component.
38
24
  * DirectoryTreeコンポーネント用の TailwindCSS v4 クラス名。
39
25
  */
40
26
  export const directoryTreeClasses = {
41
- container: "directory-tree-container relative h-full transition-opacity duration-300 overflow-y-hidden pb-[5px] pr-[3px]",
27
+ container: "directory-tree-container relative h-full transition-opacity duration-300 overflow-y-hidden pb-[3px] pr-[2px]",
42
28
  containerPending: "opacity-70",
43
29
 
44
- entry: "directory-tree-entry flex items-center cursor-pointer relative select-none",
30
+ entry: "directory-tree-entry flex items-center cursor-pointer relative select-none text-xs leading-tight py-0.5",
45
31
 
46
32
  // ホバー時のスタイル(ライト/ダークモード対応)
47
33
  entryHover: twMerge("directory-tree-entry--hover hover:bg-gray-400/15", "dark:hover:bg-gray-200/10"),
@@ -53,20 +39,20 @@ export const directoryTreeClasses = {
53
39
  entryItemSelected: twMerge("directory-tree-entry--item-selected bg-blue-400/20 shadow-[0_0_0_1px_rgba(59,130,246,0.3)]", "dark:bg-blue-400/25 dark:shadow-[0_0_0_1px_rgba(96,165,250,0.4)]"),
54
40
 
55
41
  // アイコンのスタイル
56
- expandIcon: twMerge("directory-tree-expand-icon w-5 h-5 flex-shrink-0 flex items-center justify-center", "text-gray-500", "dark:text-gray-400"),
42
+ expandIcon: twMerge("directory-tree-expand-icon w-3.5 h-3.5 flex-shrink-0 flex items-center justify-center", "text-gray-500", "dark:text-gray-400"),
57
43
 
58
44
  expandIconSelected: twMerge("directory-tree-expand-icon--selected text-blue-700", "dark:text-blue-400"),
59
45
 
60
- typeIcon: twMerge("directory-tree-type-icon w-5 h-5 flex-shrink-0 flex items-center justify-center", "text-gray-500", "dark:text-gray-400"),
46
+ typeIcon: twMerge("directory-tree-type-icon w-3.5 h-3.5 flex-shrink-0 flex items-center justify-center", "text-gray-500", "dark:text-gray-400"),
61
47
 
62
48
  typeIconSelected: twMerge("directory-tree-type-icon--selected text-blue-700", "dark:text-blue-400"),
63
49
 
64
50
  // テキストのスタイル
65
- name: twMerge("directory-tree-name overflow-hidden text-ellipsis whitespace-nowrap ml-1", "text-gray-700", "dark:text-gray-200"),
51
+ name: twMerge("directory-tree-name overflow-hidden text-ellipsis whitespace-nowrap ml-1 text-xs font-normal", "text-gray-700", "dark:text-gray-200"),
66
52
 
67
- nameDirectory: "directory-tree-name--directory",
53
+ nameDirectory: "directory-tree-name--directory font-medium",
68
54
 
69
- nameSelected: twMerge("directory-tree-name--selected text-blue-800 font-medium", "dark:text-blue-300"),
55
+ nameSelected: twMerge("directory-tree-name--selected text-blue-800 font-semibold", "dark:text-blue-300"),
70
56
  }
71
57
 
72
58
  /**
@@ -135,11 +121,7 @@ const sanitizeIcon = (node: unknown, path: string): ReactNode | null => {
135
121
  * Resolves a file icon based on mimeType (primary) > extension (fallback).
136
122
  * mimeType (最優先) > 拡張子 (フォールバック) の順序でファイルアイコンを解決する。
137
123
  */
138
- export const getFileIconByMimeOrExtension = (
139
- mimeType?: string,
140
- extension?: string,
141
- filename?: string,
142
- ): ReactNode => {
124
+ export const getFileIconByMimeOrExtension = (mimeType?: string, extension?: string, filename?: string): ReactNode => {
143
125
  const cleanExt = (extension || (filename ? getFileExtension(filename) : "")).toLowerCase()
144
126
  const cleanMime = (mimeType || "").toLowerCase()
145
127
 
@@ -154,32 +136,18 @@ export const getFileIconByMimeOrExtension = (
154
136
  return <FilePdf className="h-4 w-4 text-red-500 dark:text-red-400" />
155
137
  }
156
138
  // Excel / 表計算 / CSV / Google Sheets (google-apps.spreadsheet)
157
- if (
158
- cleanMime.includes("excel") ||
159
- cleanMime.includes("spreadsheet") ||
160
- cleanMime.includes("google-apps.spreadsheet")
161
- ) {
139
+ if (cleanMime.includes("excel") || cleanMime.includes("spreadsheet") || cleanMime.includes("google-apps.spreadsheet")) {
162
140
  return <FileXls className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
163
141
  }
164
142
  if (cleanMime === "text/csv" || cleanMime === "text/tab-separated-values") {
165
143
  return <FileCsv className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
166
144
  }
167
145
  // Word / ドキュメント / Google Docs (google-apps.document)
168
- if (
169
- cleanMime.includes("word") ||
170
- cleanMime.includes("msword") ||
171
- cleanMime.includes("wordprocessingml") ||
172
- cleanMime.includes("google-apps.document") ||
173
- cleanMime === "application/rtf"
174
- ) {
146
+ if (cleanMime.includes("word") || cleanMime.includes("msword") || cleanMime.includes("wordprocessingml") || cleanMime.includes("google-apps.document") || cleanMime === "application/rtf") {
175
147
  return <FileDoc className="h-4 w-4 text-blue-600 dark:text-blue-400" />
176
148
  }
177
149
  // PowerPoint / プレゼンテーション / Google Slides (google-apps.presentation)
178
- if (
179
- cleanMime.includes("powerpoint") ||
180
- cleanMime.includes("presentation") ||
181
- cleanMime.includes("google-apps.presentation")
182
- ) {
150
+ if (cleanMime.includes("powerpoint") || cleanMime.includes("presentation") || cleanMime.includes("google-apps.presentation")) {
183
151
  return <FilePpt className="h-4 w-4 text-orange-500 dark:text-orange-400" />
184
152
  }
185
153
  // 画像
@@ -195,12 +163,7 @@ export const getFileIconByMimeOrExtension = (
195
163
  return <FileVideo className="h-4 w-4 text-violet-500 dark:text-violet-400" />
196
164
  }
197
165
  // アーカイブ / 圧縮
198
- if (
199
- cleanMime.includes("zip") ||
200
- cleanMime.includes("tar") ||
201
- cleanMime.includes("compressed") ||
202
- cleanMime.includes("archive")
203
- ) {
166
+ if (cleanMime.includes("zip") || cleanMime.includes("tar") || cleanMime.includes("compressed") || cleanMime.includes("archive")) {
204
167
  return <FileZip className="h-4 w-4 text-amber-500 dark:text-amber-400" />
205
168
  }
206
169
  // ソースコード / JSON / HTML / CSS
@@ -247,11 +210,7 @@ export const getFileIconByMimeOrExtension = (
247
210
  if (["png", "jpg", "jpeg", "gif", "svg", "webp", "ico", "bmp", "tiff", "avif"].includes(cleanExt)) {
248
211
  return <FileImage className="h-4 w-4 text-teal-500 dark:text-teal-400" />
249
212
  }
250
- if (
251
- ["js", "mjs", "cjs", "ts", "tsx", "jsx", "json", "html", "htm", "css", "scss", "py", "go", "rs", "c", "cpp", "h", "hpp", "sh", "bash", "yaml", "yml", "sql", "xml", "toml"].includes(
252
- cleanExt,
253
- )
254
- ) {
213
+ if (["js", "mjs", "cjs", "ts", "tsx", "jsx", "json", "html", "htm", "css", "scss", "py", "go", "rs", "c", "cpp", "h", "hpp", "sh", "bash", "yaml", "yml", "sql", "xml", "toml"].includes(cleanExt)) {
255
214
  return <FileCode className="h-4 w-4 text-purple-500 dark:text-purple-400" />
256
215
  }
257
216
  if (["mp3", "wav", "ogg", "m4a", "flac", "aac", "wma"].includes(cleanExt)) {
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@
12
12
  export { DirectoryTree, directoryTreeClasses } from "./DirectoryTree.tsx"
13
13
  export type {
14
14
  DirectoryEntry,
15
+ DirectoryEntryComparator,
15
16
  DirectoryEntryItemProps,
16
17
  DirectoryTreeClickEvent,
17
18
  DirectoryTreeColumn,
package/src/types.ts CHANGED
@@ -39,6 +39,16 @@ export type DirectoryEntry = {
39
39
  style?: CSSProperties
40
40
  }
41
41
 
42
+ /**
43
+ * Comparator applied to a sibling group before the tree is flattened into rows.
44
+ * Receives two entries that share the same parent and returns the usual
45
+ * `Array.prototype.sort` ordering number.
46
+ *
47
+ * ツリーを行へフラット化する前に、同一の親を持つ兄弟グループへ適用する比較関数。
48
+ * 戻り値は `Array.prototype.sort` と同じ順序数値。
49
+ */
50
+ export type DirectoryEntryComparator = (a: DirectoryEntry, b: DirectoryEntry) => number
51
+
42
52
  /**
43
53
  * Row height for directory tree entries.
44
54
  * Either a fixed pixel value applied to every row, or a function computing the
@@ -427,16 +437,31 @@ export type DirectoryTreeProps = {
427
437
  */
428
438
  iconOverrides?: DirectoryTreeIconOverrides
429
439
  /**
430
- * Size of the expand icon.
431
- * 展開アイコンのサイズ。
440
+ * Size of the expand icon in px.
441
+ * 展開アイコンのサイズ (px)。
432
442
  */
433
443
  expandIconSize?: number
434
444
  /**
435
- * Row height in px, or a function computing the height per entry. Default 20.
445
+ * Size of the file/directory type icon in px.
446
+ * ファイル/ディレクトリアイコンのサイズ (px)。
447
+ */
448
+ typeIconSize?: number
449
+ /**
450
+ * Font size of entry labels in px or CSS string (e.g. 12 or "0.75rem").
451
+ * ラベル文字のフォントサイズ (px または CSS 文字列)。
452
+ */
453
+ fontSize?: number | string
454
+ /**
455
+ * Indentation width per depth level in px.
456
+ * 1 階層あたりのインデント幅 (px)。
457
+ */
458
+ indentSize?: number
459
+ /**
460
+ * Row height in px, or a function computing the height per entry. Default 20 (or 18 in compact mode).
436
461
  * When a function is supplied, rows may have different heights and the tree
437
462
  * connector lines follow each row's cumulative offset.
438
463
  *
439
- * 各行の高さ (px)、またはエントリごとに高さを算出する関数。既定 20。
464
+ * 各行の高さ (px)、またはエントリごとに高さを算出する関数。既定 20 (コンパクトモード時 18)。
440
465
  * 関数を渡すと行ごとに高さを変えられ、ツリー接続線は各行の累積オフセットに追従する。
441
466
  */
442
467
  itemHeight?: ItemHeight
@@ -484,6 +509,23 @@ export type DirectoryTreeProps = {
484
509
  * `grid.columns` と各 `render` / `footer` は参照安定必須(`itemHeight` と同じ制約)。
485
510
  */
486
511
  grid?: DirectoryTreeGrid
512
+
513
+ /**
514
+ * Optional comparator applied to every sibling group before the tree is flattened
515
+ * into rows. Only a shallow copy of each sibling array is sorted, so every
516
+ * `DirectoryEntry` object and every `children` array keeps its identity and
517
+ * consumer-side memoization (row memo, reference-preserving decorators, hydration
518
+ * caches) continues to work. Omit it to render the entries in their given order.
519
+ *
520
+ * 各兄弟グループへフラット化前に適用する任意の比較関数。並べ替えは兄弟配列の浅いコピーに
521
+ * 対してのみ行うため、`DirectoryEntry` と `children` 配列の identity は保持され、利用側の
522
+ * メモ化 (行メモ・参照保持デコレータ・ハイドレーションキャッシュ) はそのまま機能する。
523
+ * 省略時は与えられた順序のまま描画。
524
+ *
525
+ * @remarks 参照を安定させること (`useMemo` / `useCallback`)。identity が毎レンダー変わると
526
+ * ツリー走査が都度再計算され、パフォーマンスが劣化する (`itemHeight` と同じ制約)。
527
+ */
528
+ sort?: DirectoryEntryComparator
487
529
  }
488
530
 
489
531
  /**
@@ -535,6 +577,9 @@ export type DirectoryEntryItemProps = {
535
577
  showFileIcons?: boolean
536
578
  iconOverrides?: DirectoryTreeIconOverrides
537
579
  expandIconSize?: number
580
+ typeIconSize?: number
581
+ fontSize?: number | string
582
+ indentSize?: number
538
583
  useCanvasExpandIcons?: boolean
539
584
  highlightStyles?: HighlightStyles
540
585
  entryClassName?: string