@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,285 +0,0 @@
1
- /**
2
- * @module DirectoryTreeGrid
3
- * @description Row, header and footer renderers for the TreeGrid (columns) mode. The name/tree
4
- * column is frozen on the left; numeric columns render in a horizontally-scrollable
5
- * track translated by the shared `--dt-hscroll` CSS variable (set on the container),
6
- * so header / body rows / footer stay aligned without per-row re-render.
7
- * TreeGrid(列)モードの行・ヘッダ・フッタ描画。名前列は凍結、数値列は共有変数で横移動。
8
- */
9
- // biome-ignore-all lint/a11y/useSemanticElements: 仮想スクロールの treegrid は絶対配置行を使うため native table 要素にできない。ARIA ロールで意味を提供する。
10
- // biome-ignore-all lint/a11y/useFocusableInteractive: treegrid の row/gridcell は widget ロールではなくフォーカス不要。フォーカスは行(tabIndex=0)が担う。
11
- import type { CSSProperties, MouseEvent, ReactNode } from "react"
12
- import { memo, useState } from "react"
13
- import { twMerge } from "tailwind-merge"
14
- import { directoryTreeClasses, getFileExtension, INDENT_SIZE, resolveEntryIcon, resolveExpandIcon, toDataAttributes } from "./entryRendering.tsx"
15
- import type { DirectoryEntry, DirectoryTreeColumn, DirectoryTreeIconOverrides, HighlightStyles } from "./types.ts"
16
- import { useEntryInteraction } from "./useEntryInteraction.ts"
17
-
18
- /** Visual options shared by grid rows (mirrors the subset of DirectoryTree visual props needed here). */
19
- export type GridRowVisual = {
20
- iconOverrides?: DirectoryTreeIconOverrides
21
- showExpandIcons?: boolean
22
- showDirectoryIcons?: boolean
23
- showFileIcons?: boolean
24
- useCanvasExpandIcons?: boolean
25
- expandIconSize?: number
26
- typeIconSize?: number
27
- fontSize?: number | string
28
- indentSize?: number
29
- highlightStyles?: HighlightStyles
30
- }
31
-
32
- /** Resolves the per-column alignment class. / 列の寄せクラスを解決。 */
33
- const alignClass = (align?: DirectoryTreeColumn["align"]): string => (align === "right" ? "dt-grid-cell--right" : align === "center" ? "dt-grid-cell--center" : "")
34
-
35
- /** True when the entry is an expanded directory. Files short-circuit without querying isDirOpen. / 展開済みディレクトリなら true。 */
36
- export const isEntryExpanded = (entry: DirectoryEntry, isDirOpen: (path: string) => boolean): boolean => entry.children !== undefined && isDirOpen(entry.absolutePath)
37
-
38
- /** Shared track style for header / body / footer numeric regions (identical geometry ⇒ alignment). */
39
- const numericTrackStyle = (numericTotal: number, numericTemplate: string): CSSProperties => ({
40
- width: numericTotal,
41
- gridTemplateColumns: numericTemplate,
42
- })
43
-
44
- export type DirectoryTreeGridRowProps = {
45
- entry: DirectoryEntry
46
- indentLevel: number
47
- /** 兄弟内の位置 (1 始まり)。`aria-posinset` として出力する。 */
48
- positionInSet: number
49
- /** 同一グループの兄弟数。`aria-setsize` として出力する。 */
50
- setSize: number
51
- /** treegrid 全体での 1 始まりの行番号 (`aria-rowindex`)。ヘッダ行を 1 とする。 */
52
- rowIndex: number
53
- /** 選択集合に含まれるか (`aria-selected`)。 */
54
- isSelectedForAria: boolean
55
- rowHeight: number
56
- isDirOpen: (path: string) => boolean
57
- columns: DirectoryTreeColumn[]
58
- numericTemplate: string
59
- numericTotal: number
60
- nameWidth: number
61
- rowClassName?: string | ((entry: DirectoryEntry) => string)
62
- selection: {
63
- selectedPath: string | null
64
- mode?: "none" | "single" | "multiple"
65
- selectedItems?: Set<string>
66
- onEntryClick: (event: import("./types.ts").DirectoryTreeClickEvent) => void
67
- onSelectionChange?: (entry: DirectoryEntry, isSelected: boolean) => void
68
- }
69
- expansion: {
70
- toggleDirectory: (path: string) => void
71
- onToggleDirectoryRecursive: (entry: DirectoryEntry) => void
72
- }
73
- visual: GridRowVisual
74
- }
75
-
76
- /**
77
- * @component DirectoryTreeGridRow
78
- * @description A single TreeGrid row: frozen name cell (indent + glyph + icon + label) plus a
79
- * horizontally-scrollable numeric track. Memoized; the `--dt-hscroll` variable is not
80
- * a prop, so horizontal scrolling never re-renders rows.
81
- */
82
- export const DirectoryTreeGridRow = memo<DirectoryTreeGridRowProps>(
83
- ({
84
- entry,
85
- indentLevel,
86
- positionInSet,
87
- setSize,
88
- rowIndex,
89
- isSelectedForAria,
90
- rowHeight,
91
- isDirOpen,
92
- columns,
93
- numericTemplate,
94
- numericTotal,
95
- nameWidth,
96
- rowClassName,
97
- selection: { onEntryClick, selectedPath, mode: selectionMode = "none", selectedItems, onSelectionChange },
98
- expansion: { toggleDirectory, onToggleDirectoryRecursive },
99
- visual: { iconOverrides, showExpandIcons = true, showDirectoryIcons = true, showFileIcons = true, useCanvasExpandIcons = false, expandIconSize, indentSize = INDENT_SIZE, highlightStyles },
100
- }) => {
101
- const [isHovered, setIsHovered] = useState(false)
102
-
103
- const isDirectory = entry.children !== undefined
104
- const isExpanded = isDirectory && isDirOpen(entry.absolutePath)
105
- const isSelected = entry.absolutePath === selectedPath
106
- const isItemSelected = !isDirectory && Boolean(selectedItems?.has(entry.absolutePath))
107
- const extension = isDirectory ? undefined : getFileExtension(entry.name) || getFileExtension(entry.relativePath) || getFileExtension(entry.absolutePath)
108
-
109
- const handleInteraction = useEntryInteraction({ entry, isDirectory, isExpanded, isItemSelected, selectionMode, onSelectionChange, onEntryClick, toggleDirectory, onToggleDirectoryRecursive })
110
-
111
- const hoverClass = isHovered ? (highlightStyles?.hoverClassName !== undefined ? highlightStyles.hoverClassName : directoryTreeClasses.entryHover) : ""
112
- const selectedClass = (() => {
113
- if (isDirectory) {
114
- if (isSelected) return highlightStyles?.directorySelectedClassName !== undefined ? highlightStyles.directorySelectedClassName : directoryTreeClasses.entrySelected
115
- } else if (isSelected || isItemSelected) {
116
- if (highlightStyles?.itemSelectedClassName !== undefined) return highlightStyles.itemSelectedClassName
117
- return twMerge(isSelected && directoryTreeClasses.entrySelected, isItemSelected && directoryTreeClasses.entryItemSelected)
118
- }
119
- return ""
120
- })()
121
-
122
- const resolvedRowClass = typeof rowClassName === "function" ? rowClassName(entry) : rowClassName
123
- const rowClasses = twMerge("dt-grid-row cursor-pointer select-none", hoverClass, selectedClass, resolvedRowClass, entry.className)
124
-
125
- const expandIconClasses = twMerge(directoryTreeClasses.expandIcon, (isSelected || isItemSelected) && directoryTreeClasses.expandIconSelected)
126
- const typeIconClasses = twMerge(directoryTreeClasses.typeIcon, (isSelected || isItemSelected) && directoryTreeClasses.typeIconSelected)
127
- const nameLabelClasses = twMerge("dt-grid-name-label ml-1", "text-gray-700 dark:text-gray-200", isDirectory && directoryTreeClasses.nameDirectory, (isSelected || isItemSelected) && directoryTreeClasses.nameSelected)
128
-
129
- const expandIconContent = resolveExpandIcon({ isDirectory, isExpanded, showExpandIcons, useCanvasExpandIcons, expandIconSize })
130
- const resolvedIcon = (isDirectory ? showDirectoryIcons : showFileIcons) ? resolveEntryIcon({ entry, isDirectory, isExpanded, isSelected, isItemSelected, extension, mimeType: entry.mimeType }, iconOverrides) : null
131
-
132
- const ctx = { indentLevel, isDirectory, isExpanded }
133
- const [nameColumn, ...numericColumns] = columns
134
- const nameContent = nameColumn?.render ? nameColumn.render(entry, ctx) : (entry.label ?? entry.name)
135
-
136
- const customHighlightStyle: CSSProperties = {
137
- ...(isHovered ? highlightStyles?.hoverStyle : {}),
138
- ...(isDirectory && isSelected ? highlightStyles?.directorySelectedStyle : {}),
139
- ...(!isDirectory && (isSelected || isItemSelected) ? highlightStyles?.itemSelectedStyle : {}),
140
- }
141
-
142
- return (
143
- <div
144
- className={rowClasses}
145
- style={{ height: rowHeight, ...customHighlightStyle, ...entry.style }}
146
- role="row"
147
- aria-expanded={isDirectory ? isExpanded : undefined}
148
- aria-level={indentLevel + 1}
149
- aria-posinset={positionInSet}
150
- aria-setsize={setSize}
151
- aria-rowindex={rowIndex}
152
- aria-selected={selectionMode === "none" ? undefined : isSelectedForAria}
153
- {...toDataAttributes(entry.data)}
154
- data-entry-type={isDirectory ? "directory" : "file"}
155
- data-entry-expanded={isDirectory ? String(isExpanded) : undefined}
156
- data-entry-selected={isSelected ? "true" : undefined}
157
- data-entry-item-selected={isItemSelected ? "true" : undefined}
158
- onClick={handleInteraction}
159
- onMouseEnter={() => setIsHovered(true)}
160
- onMouseLeave={() => setIsHovered(false)}
161
- onKeyDown={(e) => e.key === "Enter" && handleInteraction(e as unknown as MouseEvent<HTMLDivElement>)}
162
- tabIndex={0}>
163
- {/* Frozen name/tree cell — indent applied here only. / 凍結名前セル(インデントはここだけ)。 */}
164
- <div className={twMerge("dt-grid-name-cell", nameColumn?.className)} role="gridcell" style={{ width: nameWidth, paddingLeft: Math.max(0, indentLevel * indentSize) }}>
165
- {(showExpandIcons || useCanvasExpandIcons) && <span className={expandIconClasses}>{expandIconContent}</span>}
166
- {(isDirectory ? showDirectoryIcons : showFileIcons) && <span className={typeIconClasses}>{resolvedIcon}</span>}
167
- <span className={nameLabelClasses}>{nameContent}</span>
168
- </div>
169
- {/* Scrollable numeric region. / 横スクロールする数値領域。 */}
170
- {numericColumns.length > 0 && (
171
- <div className="dt-grid-numeric-viewport">
172
- <div className="dt-grid-numeric-track" style={numericTrackStyle(numericTotal, numericTemplate)}>
173
- {numericColumns.map((column) => (
174
- <div key={column.key} className={twMerge("dt-grid-cell", alignClass(column.align), column.className)} role="gridcell">
175
- {column.render ? column.render(entry, ctx) : null}
176
- </div>
177
- ))}
178
- </div>
179
- </div>
180
- )}
181
- </div>
182
- )
183
- },
184
- (prev, next) => {
185
- if (prev.entry !== next.entry) return false
186
- const prevExpanded = isEntryExpanded(prev.entry, prev.isDirOpen)
187
- const nextExpanded = isEntryExpanded(next.entry, next.isDirOpen)
188
- return (
189
- prev.indentLevel === next.indentLevel &&
190
- prev.positionInSet === next.positionInSet &&
191
- prev.setSize === next.setSize &&
192
- prev.rowIndex === next.rowIndex &&
193
- prev.isSelectedForAria === next.isSelectedForAria &&
194
- prev.rowHeight === next.rowHeight &&
195
- prevExpanded === nextExpanded &&
196
- prev.columns === next.columns &&
197
- prev.numericTemplate === next.numericTemplate &&
198
- prev.numericTotal === next.numericTotal &&
199
- prev.nameWidth === next.nameWidth &&
200
- prev.rowClassName === next.rowClassName &&
201
- prev.selection.selectedPath === next.selection.selectedPath &&
202
- prev.selection.mode === next.selection.mode &&
203
- prev.selection.selectedItems === next.selection.selectedItems &&
204
- prev.visual === next.visual
205
- )
206
- },
207
- )
208
- DirectoryTreeGridRow.displayName = "DirectoryTreeGridRow"
209
-
210
- /** Shared frozen-name + numeric-track layout used by header and footer. / ヘッダ/フッタ共通レイアウト。 */
211
- const GridEdgeRow = ({
212
- kind,
213
- columns,
214
- numericTemplate,
215
- numericTotal,
216
- nameWidth,
217
- scrollBarWidth,
218
- className,
219
- nameContent,
220
- renderCell,
221
- }: {
222
- kind: "header" | "footer"
223
- columns: DirectoryTreeColumn[]
224
- numericTemplate: string
225
- numericTotal: number
226
- nameWidth: number
227
- scrollBarWidth: number
228
- className?: string
229
- nameContent: ReactNode
230
- renderCell: (column: DirectoryTreeColumn) => ReactNode
231
- }) => {
232
- const [, ...numericColumns] = columns
233
- const nameClass = kind === "header" ? "dt-grid-name-header" : "dt-grid-name-footer"
234
- const rowClass = kind === "header" ? "dt-grid-header" : "dt-grid-footer"
235
- const cellRole = kind === "header" ? "columnheader" : "gridcell"
236
- return (
237
- <div className={twMerge(rowClass, "text-gray-600 dark:text-gray-300", className)} role="row">
238
- <div className={twMerge(nameClass, "px-1", columns[0]?.className)} role={cellRole} style={{ width: nameWidth }}>
239
- {nameContent}
240
- </div>
241
- {numericColumns.length > 0 && (
242
- <div className="dt-grid-numeric-viewport">
243
- <div className="dt-grid-numeric-track" style={numericTrackStyle(numericTotal, numericTemplate)}>
244
- {numericColumns.map((column) => (
245
- <div key={column.key} className={twMerge("dt-grid-cell", alignClass(column.align), column.className)} role={cellRole}>
246
- {renderCell(column)}
247
- </div>
248
- ))}
249
- </div>
250
- </div>
251
- )}
252
- {/* Right spacer aligns the numeric viewport with the body (reduced by the vertical scrollbar). */}
253
- <div className="dt-grid-scrollbar-spacer" style={{ width: scrollBarWidth }} aria-hidden="true" />
254
- </div>
255
- )
256
- }
257
-
258
- export type DirectoryTreeGridHeaderRowProps = {
259
- columns: DirectoryTreeColumn[]
260
- numericTemplate: string
261
- numericTotal: number
262
- nameWidth: number
263
- scrollBarWidth: number
264
- className?: string
265
- }
266
-
267
- export const DirectoryTreeGridHeaderRow = ({ columns, className, ...rest }: DirectoryTreeGridHeaderRowProps) => <GridEdgeRow kind="header" columns={columns} className={className} nameContent={columns[0]?.header ?? null} renderCell={(column) => column.header ?? null} {...rest} />
268
-
269
- export type DirectoryTreeGridFooterRowProps = {
270
- columns: DirectoryTreeColumn[]
271
- numericTemplate: string
272
- numericTotal: number
273
- nameWidth: number
274
- scrollBarWidth: number
275
- /** All nodes of the tree (collapsed included), for footer aggregation. / フッタ集計用の全ノード。 */
276
- allEntries: DirectoryEntry[]
277
- className?: string
278
- }
279
-
280
- /** Resolves a column footer that may be a node or an aggregator over all entries. / フッタ解決。 */
281
- const resolveFooter = (footer: DirectoryTreeColumn["footer"], allEntries: DirectoryEntry[]): ReactNode => (typeof footer === "function" ? footer(allEntries) : (footer ?? null))
282
-
283
- export const DirectoryTreeGridFooterRow = ({ columns, allEntries, className, ...rest }: DirectoryTreeGridFooterRowProps) => (
284
- <GridEdgeRow kind="footer" columns={columns} className={className} nameContent={resolveFooter(columns[0]?.footer, allEntries)} renderCell={(column) => resolveFooter(column.footer, allEntries)} {...rest} />
285
- )
package/src/TreeLine.tsx DELETED
@@ -1,300 +0,0 @@
1
- import { memo, useCallback, useEffect, useRef } from "react"
2
- import type { TreeLineGlyph, TreeLineProps, TreeLineSegment } from "./types.ts"
3
-
4
- /**
5
- * Collects the segments that fall inside the requested index window.
6
- *
7
- * 指定されたインデックス範囲に含まれるセグメントを収集する。
8
- *
9
- * @param segmentsByItem - アイテムごとのセグメント配列。
10
- * @param startIndex - 開始インデックス。
11
- * @param endExclusive - 終了インデックス (排他的)。
12
- * @returns 表示対象のセグメント配列。
13
- */
14
- const collectVisibleSegments = (segmentsByItem: TreeLineSegment[][], startIndex: number, endExclusive: number): TreeLineSegment[] => {
15
- const collected: TreeLineSegment[] = []
16
- for (let index = startIndex; index < endExclusive; index++) {
17
- const group = segmentsByItem[index]
18
- if (!group || group.length === 0) {
19
- continue
20
- }
21
- for (const segment of group) {
22
- collected.push(segment)
23
- }
24
- }
25
- return collected
26
- }
27
-
28
- /**
29
- * Collects the glyphs that fall inside the requested index window.
30
- *
31
- * 指定されたインデックス範囲に含まれるグリフを収集する。
32
- *
33
- * @param glyphsByItem - アイテムごとのグリフ配列。
34
- * @param startIndex - 開始インデックス。
35
- * @param endExclusive - 終了インデックス (排他的)。
36
- * @returns 表示対象のグリフ配列。
37
- */
38
- const collectVisibleGlyphs = (glyphsByItem: TreeLineGlyph[][], startIndex: number, endExclusive: number): TreeLineGlyph[] => {
39
- const collected: TreeLineGlyph[] = []
40
- for (let index = startIndex; index < endExclusive; index++) {
41
- const group = glyphsByItem[index]
42
- if (!group || group.length === 0) {
43
- continue
44
- }
45
- for (const glyph of group) {
46
- collected.push(glyph)
47
- }
48
- }
49
- return collected
50
- }
51
-
52
- /**
53
- * Adjusts the canvas backing store size to match CSS dimensions and device pixel ratio.
54
- *
55
- * Canvas の描画領域を CSS サイズとデバイスピクセル比に合わせて調整する。
56
- *
57
- * @param canvas - 対象のキャンバス要素。
58
- * @param width - CSS 上の幅。
59
- * @param height - CSS 上の高さ。
60
- * @param devicePixelRatio - デバイスピクセル比。
61
- */
62
- const resizeCanvas = (canvas: HTMLCanvasElement, width: number, height: number, devicePixelRatio: number): void => {
63
- const pixelWidth = Math.max(1, Math.floor(width * devicePixelRatio))
64
- const pixelHeight = Math.max(1, Math.floor(height * devicePixelRatio))
65
- if (canvas.width !== pixelWidth || canvas.height !== pixelHeight) {
66
- canvas.width = pixelWidth
67
- canvas.height = pixelHeight
68
- }
69
- const style = canvas.style
70
- if (style.width !== `${width}px`) {
71
- style.width = `${width}px`
72
- }
73
- if (style.height !== `${height}px`) {
74
- style.height = `${height}px`
75
- }
76
- }
77
-
78
- /**
79
- * Draws the tree line segments on the provided canvas context.
80
- *
81
- * 指定のキャンバスコンテキストにツリーラインを描画する。
82
- *
83
- * @param context - 2D コンテキスト。
84
- * @param segments - 描画対象のセグメント群。
85
- * @param strokeWidth - 線の太さ。
86
- */
87
- const drawSegments = (context: CanvasRenderingContext2D, segments: TreeLineSegment[], strokeWidth: number): void => {
88
- context.lineWidth = strokeWidth
89
- context.beginPath()
90
- for (const segment of segments) {
91
- context.moveTo(segment.x1, segment.y1)
92
- context.lineTo(segment.x2, segment.y2)
93
- }
94
- context.stroke()
95
- }
96
-
97
- /**
98
- * Generates an rgba() string with alpha applied to a hex color.
99
- *
100
- * 16 進数カラーにアルファ値を適用した rgba() 文字列を生成する。
101
- *
102
- * @param color - 元のカラー文字列。
103
- * @param alpha - 適用するアルファ値。
104
- * @returns rgba() 形式のカラー文字列。解析できない場合は null。
105
- */
106
- const deriveRgbaWithAlpha = (color: string, alpha: number): string | null => {
107
- const match = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim())
108
- if (!match) {
109
- return null
110
- }
111
- let hex = match[1]
112
- if (hex.length === 3) {
113
- hex = hex
114
- .split("")
115
- .map((digit) => digit + digit)
116
- .join("")
117
- }
118
- const red = Number.parseInt(hex.slice(0, 2), 16)
119
- const green = Number.parseInt(hex.slice(2, 4), 16)
120
- const blue = Number.parseInt(hex.slice(4, 6), 16)
121
- return `rgba(${red}, ${green}, ${blue}, ${alpha})`
122
- }
123
-
124
- /**
125
- * Draws modern circular glyphs representing expand/collapse states.
126
- *
127
- * 展開/折りたたみ状態を表す円形グリフを描画する。
128
- *
129
- * @param context - 2D コンテキスト。
130
- * @param glyphs - グリフ配列。
131
- * @param color - ベースとなるカラー。
132
- * @param overrideSize - サイズ上書き値。
133
- */
134
- const drawGlyphs = (context: CanvasRenderingContext2D, glyphs: TreeLineGlyph[], color: string, overrideSize?: number): void => {
135
- if (glyphs.length === 0) {
136
- return
137
- }
138
- const fillColor = deriveRgbaWithAlpha(color, 0.14)
139
- const previousStrokeStyle = context.strokeStyle
140
- const previousFillStyle = context.fillStyle
141
- const previousLineWidth = context.lineWidth
142
- const previousLineCap = context.lineCap
143
- const previousLineJoin = context.lineJoin
144
- context.strokeStyle = color
145
- context.lineCap = "round"
146
- context.lineJoin = "round"
147
- for (const glyph of glyphs) {
148
- const size = overrideSize ?? glyph.size
149
- const radius = Math.max(0, size / 2)
150
- const ringWidth = Math.max(1, Math.round(size * 0.08))
151
- const symbolWidth = Math.max(1, Math.round(size * 0.14))
152
- const innerRadius = Math.max(0, radius - ringWidth * 0.8)
153
- const symbolLength = Math.max(0, innerRadius * 0.55)
154
- if (fillColor) {
155
- context.fillStyle = fillColor
156
- context.beginPath()
157
- context.arc(glyph.centerX, glyph.centerY, innerRadius, 0, Math.PI * 2)
158
- context.fill()
159
- }
160
- context.lineWidth = ringWidth
161
- context.beginPath()
162
- context.arc(glyph.centerX, glyph.centerY, Math.max(0, radius - ringWidth * 0.3), 0, Math.PI * 2)
163
- context.stroke()
164
- context.lineWidth = symbolWidth
165
- context.beginPath()
166
- context.moveTo(glyph.centerX - symbolLength, glyph.centerY)
167
- context.lineTo(glyph.centerX + symbolLength, glyph.centerY)
168
- context.stroke()
169
- if (!glyph.isExpanded) {
170
- context.beginPath()
171
- context.moveTo(glyph.centerX, glyph.centerY - symbolLength)
172
- context.lineTo(glyph.centerX, glyph.centerY + symbolLength)
173
- context.stroke()
174
- }
175
- }
176
- context.strokeStyle = previousStrokeStyle
177
- context.fillStyle = previousFillStyle
178
- context.lineWidth = previousLineWidth
179
- context.lineCap = previousLineCap
180
- context.lineJoin = previousLineJoin
181
- }
182
-
183
- /**
184
- * Canvas based tree line renderer that repaints on animation frames.
185
- *
186
- * アニメーションフレーム単位で再描画する Canvas ベースのツリーラインレンダラ。
187
- */
188
- const TreeLine = memo<TreeLineProps>(({ segmentsByItem, glyphsByItem, itemHeight, width, viewportHeight, scrollPosition, color = "#a0aec0", strokeWidth = 1, renderStartIndex, renderEndIndex, lookaheadEndIndex, devicePixelRatio, expandGlyphColor, expandGlyphSize }) => {
189
- const canvasRef = useRef<HTMLCanvasElement | null>(null)
190
- const animationFrameRef = useRef<number | null>(null)
191
- const latestStateRef = useRef({
192
- segmentsByItem,
193
- glyphsByItem,
194
- itemHeight,
195
- width,
196
- viewportHeight,
197
- scrollPosition,
198
- color,
199
- strokeWidth,
200
- renderStartIndex,
201
- renderEndIndex,
202
- lookaheadEndIndex,
203
- devicePixelRatio,
204
- expandGlyphColor,
205
- expandGlyphSize,
206
- })
207
- const renderFrame = useCallback(() => {
208
- animationFrameRef.current = null
209
- const canvas = canvasRef.current
210
- if (!canvas) {
211
- return
212
- }
213
- const context = canvas.getContext("2d")
214
- if (!context) {
215
- return
216
- }
217
- const state = latestStateRef.current
218
- if (state.width <= 0 || state.viewportHeight <= 0) {
219
- context.clearRect(0, 0, canvas.width, canvas.height)
220
- return
221
- }
222
- const pixelRatio = Number.isFinite(state.devicePixelRatio ?? NaN) ? (state.devicePixelRatio as number) : typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1
223
- resizeCanvas(canvas, state.width, state.viewportHeight, pixelRatio)
224
- const totalItems = state.segmentsByItem.length
225
- const startIndex = (() => {
226
- if (typeof state.renderStartIndex === "number" && Number.isFinite(state.renderStartIndex)) {
227
- return Math.max(0, Math.floor(state.renderStartIndex))
228
- }
229
- return Math.max(0, Math.floor(state.scrollPosition / state.itemHeight))
230
- })()
231
- const defaultEndExclusive = Math.min(totalItems, Math.ceil((state.scrollPosition + state.viewportHeight) / state.itemHeight))
232
- const endExclusive = (() => {
233
- if (typeof state.renderEndIndex === "number" && Number.isFinite(state.renderEndIndex)) {
234
- const inclusive = Math.floor(state.renderEndIndex)
235
- return Math.max(Math.min(totalItems, inclusive + 1), startIndex)
236
- }
237
- return Math.max(defaultEndExclusive, startIndex)
238
- })()
239
- const lookaheadExclusive = (() => {
240
- if (typeof state.lookaheadEndIndex === "number" && Number.isFinite(state.lookaheadEndIndex)) {
241
- const inclusive = Math.floor(state.lookaheadEndIndex)
242
- const candidate = Math.min(totalItems, inclusive + 1)
243
- return Math.max(candidate, endExclusive)
244
- }
245
- return Math.max(defaultEndExclusive, endExclusive)
246
- })()
247
- const segments = collectVisibleSegments(state.segmentsByItem, startIndex, lookaheadExclusive)
248
- const glyphs = collectVisibleGlyphs(state.glyphsByItem, startIndex, lookaheadExclusive)
249
- context.save()
250
- context.scale(pixelRatio, pixelRatio)
251
- context.clearRect(0, 0, state.width, state.viewportHeight)
252
- context.translate(0, -state.scrollPosition)
253
- context.strokeStyle = state.color
254
- drawSegments(context, segments, state.strokeWidth)
255
- drawGlyphs(context, glyphs, state.expandGlyphColor ?? state.color, state.expandGlyphSize)
256
- context.restore()
257
- }, [])
258
-
259
- const scheduleRender = useCallback(() => {
260
- if (animationFrameRef.current !== null) {
261
- return
262
- }
263
- animationFrameRef.current = window.requestAnimationFrame(renderFrame)
264
- }, [renderFrame])
265
-
266
- useEffect(() => {
267
- latestStateRef.current = {
268
- segmentsByItem,
269
- glyphsByItem,
270
- itemHeight,
271
- width,
272
- viewportHeight,
273
- scrollPosition,
274
- color,
275
- strokeWidth,
276
- renderStartIndex,
277
- renderEndIndex,
278
- lookaheadEndIndex,
279
- devicePixelRatio,
280
- expandGlyphColor,
281
- expandGlyphSize,
282
- }
283
- scheduleRender()
284
- }, [segmentsByItem, glyphsByItem, itemHeight, width, viewportHeight, scrollPosition, color, strokeWidth, renderStartIndex, renderEndIndex, lookaheadEndIndex, devicePixelRatio, expandGlyphColor, expandGlyphSize, scheduleRender])
285
-
286
- useEffect(() => {
287
- return () => {
288
- if (animationFrameRef.current !== null) {
289
- window.cancelAnimationFrame(animationFrameRef.current)
290
- animationFrameRef.current = null
291
- }
292
- }
293
- }, [])
294
-
295
- return <canvas ref={canvasRef} className="pointer-events-none absolute top-0 left-0 z-0" />
296
- })
297
-
298
- TreeLine.displayName = "TreeLineCanvas"
299
-
300
- export { TreeLine }
package/src/cli.server.ts DELETED
@@ -1,38 +0,0 @@
1
- import { spawn } from "node:child_process"
2
- import path from "node:path"
3
- import { fileURLToPath } from "node:url"
4
- import { Logger, LogLevel } from "./logger"
5
-
6
- const __filename = fileURLToPath(import.meta.url)
7
- const __dirname = path.dirname(__filename)
8
-
9
- const logger = new Logger(LogLevel.INFO, "[directory-tree]")
10
-
11
- const args = process.argv.slice(2)
12
-
13
- if (args[0] === "demo") {
14
- logger.info("Starting demo server...")
15
-
16
- // The demo directory is inside the package
17
- const demoPath = path.join(__dirname, "..", "demo")
18
-
19
- const child = spawn("pnpm", ["run", "dev"], {
20
- cwd: demoPath,
21
- stdio: "inherit",
22
- shell: process.platform === "win32",
23
- })
24
-
25
- child.on("close", (code) => {
26
- if (code !== 0) {
27
- logger.error(`Demo server process exited with code ${code}`)
28
- }
29
- })
30
-
31
- child.on("error", (err) => {
32
- logger.error("Failed to start demo server:", err)
33
- })
34
- } else {
35
- logger.info(`Unknown command: ${args[0]}`)
36
- logger.info("Usage: npx @aiquants/directory-tree demo")
37
- process.exit(1)
38
- }