├── src ├── ItemRendererWithIcon.tsx ├── index.ts ├── type.ts ├── useLatest.ts ├── DefaultFileItem.tsx ├── FileItem.tsx ├── node.ts ├── FileItemWithFileIcon.tsx ├── TreeItem.tsx ├── FileTree.tsx └── utils.ts ├── demo ├── demo.css ├── index.tsx └── Tree.tsx ├── assets └── appearence.png ├── .gitmodules ├── styles.css ├── index.html ├── .babelrc ├── LICENSE ├── icons.css ├── webpack.config.js ├── package.json ├── .gitignore ├── README.md └── tsconfig.json /src/ItemRendererWithIcon.tsx: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /demo/demo.css: -------------------------------------------------------------------------------- 1 | .file-tree__tree-item.activated { 2 | background: rgba(0, 0, 0, 0.1); 3 | } 4 | -------------------------------------------------------------------------------- /assets/appearence.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pansinm/react-file-tree/HEAD/assets/appearence.png -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "github-file-icons"] 2 | path = github-file-icons 3 | url = https://github.com/homerchen19/github-file-icons.git 4 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export type { TreeNode } from "./type"; 2 | export * from "./FileTree"; 3 | export { TreeItem } from "./TreeItem"; 4 | export * as utils from "./utils"; 5 | -------------------------------------------------------------------------------- /styles.css: -------------------------------------------------------------------------------- 1 | .file-tree__tree-item { 2 | display: flex; 3 | align-items: center; 4 | } 5 | 6 | .file-tree__tree-item--dragover { 7 | background: #eee; 8 | } 9 | 10 | .file-tree__icon { 11 | margin-right: 5px; 12 | } 13 | -------------------------------------------------------------------------------- /src/type.ts: -------------------------------------------------------------------------------- 1 | export type TreeNodeType = "directory" | "file"; 2 | 3 | export type TreeNode = { 4 | [x in K]: T[K]; 5 | } & { 6 | type: TreeNodeType; 7 | uri: string; 8 | expanded?: boolean; 9 | children?: TreeNode[]; 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |
11 | 12 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-env", 4 | "@babel/preset-react" 5 | ], 6 | "plugins": [ 7 | "@babel/plugin-transform-runtime", 8 | "react-hot-loader/babel" 9 | ], 10 | "env": { 11 | "production": { 12 | "presets": [ 13 | "minify" 14 | ] 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /src/useLatest.ts: -------------------------------------------------------------------------------- 1 | import { useCallback, useRef } from 'react'; 2 | 3 | 4 | function useLatest(handler: T) { 5 | const handlerRef = useRef(null); 6 | 7 | handlerRef.current = handler; 8 | 9 | return useCallback((...args) => { 10 | const fn = handlerRef.current; 11 | return fn?.(...args); 12 | }, []) as unknown as T; 13 | } 14 | 15 | export default useLatest; 16 | -------------------------------------------------------------------------------- /src/DefaultFileItem.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import FileItem from "./FileItem"; 3 | import { TreeNode } from "./type"; 4 | import { getFileName } from "./utils"; 5 | 6 | interface DefaultFileItemProps { 7 | treeNode: TreeNode; 8 | } 9 | 10 | function DefaultFileItem({ treeNode }: DefaultFileItemProps) { 11 | const emoji = 12 | treeNode.type === "directory" ? (treeNode.expanded ? "📂" : "📁") : "🗎"; 13 | return ; 14 | } 15 | 16 | export default DefaultFileItem; 17 | -------------------------------------------------------------------------------- /demo/index.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom"; 3 | import { Tree } from "./Tree"; 4 | import "../styles.css"; 5 | import "../icons.css"; 6 | import "./demo.css"; 7 | 8 | ReactDOM.render( 9 |
10 |
11 | 12 |
13 |
14 | 15 |
16 |
, 17 | 18 | document.getElementById("app") 19 | ); 20 | -------------------------------------------------------------------------------- /src/FileItem.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { TreeNode } from "./type"; 3 | 4 | interface FileItemProps { 5 | icon: React.ReactNode; 6 | filename: React.ReactNode; 7 | } 8 | 9 | function FileItem(props: FileItemProps) { 10 | return ( 11 |
12 | {props.icon} 13 | 22 | {props.filename} 23 | 24 |
25 | ); 26 | } 27 | 28 | export default FileItem; 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 panxin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /icons.css: -------------------------------------------------------------------------------- 1 | @import "./github-file-icons/src/file-icons/css/fonts.css"; 2 | @import "./github-file-icons/src/file-icons/css/colors.css"; 3 | @import "./github-file-icons/src/file-icons/css/icons.css"; 4 | 5 | .database-icon::before { 6 | left: 2px; 7 | } 8 | 9 | .dark { 10 | filter: brightness(125%) contrast(150%) drop-shadow(0 0 0 #fff) 11 | drop-shadow(1px 1px 1px #444); 12 | } 13 | 14 | .light-folder-color { 15 | color: rgb(108, 181, 254); 16 | } 17 | 18 | .folder-icon::before { 19 | font-family: FontAwesome; 20 | content: "\f07b"; 21 | font-size: 16px; 22 | } 23 | 24 | .folder-icon-open::before { 25 | font-family: FontAwesome; 26 | content: "\f07c"; 27 | font-size: 16px; 28 | } 29 | 30 | .file-icon::before { 31 | font-family: FontAwesome; 32 | content: '\f15b'; 33 | font-size: 16px; 34 | } 35 | 36 | 37 | /* https://github.com/homerchen19/github-file-icons/issues/128 */ 38 | .icon-file-pdf::before { 39 | font-family: FontAwesome; 40 | content: '\f1c1'; 41 | font-size: 16px; 42 | } 43 | 44 | /* https://github.com/homerchen19/github-file-icons/issues/130 */ 45 | .icon-file-text::before { 46 | font-family: FontAwesome; 47 | content: '\f15c'; 48 | font-size: 16px; 49 | } -------------------------------------------------------------------------------- /src/node.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import { pathToFileURL } from "url"; 3 | import fs from "fs/promises"; 4 | import { TreeNode } from "./type"; 5 | 6 | export async function getTreeNodeChildren(directory: string, recursive = true) { 7 | let children = await fs.readdir(directory, { withFileTypes: true }); 8 | return Promise.all( 9 | children.map(async (child): Promise => { 10 | const childPath = path.resolve(directory, child.name); 11 | return { 12 | type: child.isDirectory() ? "directory" : "file", 13 | uri: pathToFileURL(childPath).toString(), 14 | children: 15 | child.isDirectory() && recursive 16 | ? await getTreeNodeChildren(childPath) 17 | : undefined, 18 | }; 19 | }) 20 | ); 21 | } 22 | 23 | export async function getTreeNode(pathname: string, recursive = true): Promise { 24 | const fullpath = path.resolve(pathname); 25 | const stats = await fs.stat(fullpath); 26 | return { 27 | type: stats.isDirectory() ? "directory" : "file", 28 | uri: pathToFileURL(fullpath).toString(), 29 | children: (stats.isDirectory() && recursive) 30 | ? await getTreeNodeChildren(fullpath) 31 | : undefined, 32 | }; 33 | } 34 | -------------------------------------------------------------------------------- /src/FileItemWithFileIcon.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { db, getClassWithColor } from "./file-icons/file-icons"; 3 | import FileItem from "./FileItem"; 4 | import { TreeNode } from "./type"; 5 | import { getFileName } from "./utils"; 6 | 7 | interface FileItemWithFileIconProps { 8 | treeNode: TreeNode; 9 | } 10 | 11 | export function getFileIconClass(fileName: string, isDirectory: boolean, expanded?: boolean) { 12 | let className = ""; 13 | if (isDirectory) { 14 | className = expanded ? "folder-icon-open" : "folder-icon"; 15 | className += " light-folder-color"; 16 | } else { 17 | const icon = db.matchName(fileName, false); 18 | className = getClassWithColor(fileName, icon) as string; 19 | if (!className) { 20 | className = "file-icon light-blue"; 21 | } 22 | } 23 | return className; 24 | } 25 | 26 | function FileItemWithFileIcon({ treeNode }: FileItemWithFileIconProps) { 27 | const filename = getFileName(treeNode.uri); 28 | const iconClass = getFileIconClass( 29 | filename, 30 | treeNode.type === "directory", 31 | treeNode.expanded 32 | ); 33 | return ( 34 | } filename={filename} /> 35 | ); 36 | } 37 | 38 | export default FileItemWithFileIcon; 39 | -------------------------------------------------------------------------------- /demo/Tree.tsx: -------------------------------------------------------------------------------- 1 | import React, { FC, useEffect, useState } from "react"; 2 | import orderBy from "lodash/orderBy"; 3 | import { FileTree, FileTreeProps, TreeNode, utils } from "../src"; 4 | import FileItemWithFileIcon from "../src/FileItemWithFileIcon"; 5 | 6 | const sorter = (treeNodes: TreeNode[]) => 7 | orderBy( 8 | treeNodes, 9 | [ 10 | (node) => (node.type === "directory" ? 0 : 1), 11 | (node) => utils.getFileName(node.uri), 12 | ], 13 | ["asc", "asc"] 14 | ); 15 | 16 | export const Tree: FC<{ iconType: "emoji" | "file-icon" }> = ({ iconType }) => { 17 | const [tree, setTree] = useState(); 18 | const [activatedUri, setActivatedUri] = useState(""); 19 | 20 | useEffect(() => { 21 | fetch("/root") 22 | .then((res) => res.json()) 23 | .then((tree) => Object.assign(tree, { expanded: true })) 24 | .then(setTree); 25 | }, []); 26 | 27 | const toggleExpanded: FileTreeProps["onItemClick"] = (treeNode) => { 28 | if (treeNode.type === "directory") { 29 | setTree((tree) => 30 | utils.assignTreeNode(tree, treeNode.uri, { 31 | expanded: !treeNode.expanded, 32 | }) 33 | ); 34 | } 35 | setActivatedUri(treeNode.uri); 36 | }; 37 | const itemRender = 38 | iconType === "file-icon" 39 | ? (treeNode: TreeNode) => 40 | : undefined; 41 | return ( 42 | 49 | ); 50 | }; 51 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const webpack = require("webpack"); 2 | const HtmlWebpackPlugin = require("html-webpack-plugin"); 3 | const express = require("express"); 4 | const fs = require("fs/promises"); 5 | const path = require("path"); 6 | const {getTreeNode} = require('./lib/node') 7 | 8 | module.exports = { 9 | entry: [ 10 | // Runtime code for hot module replacement 11 | "webpack/hot/dev-server.js", 12 | // Dev server client for web socket transport, hot and live reload logic 13 | "webpack-dev-server/client/index.js?hot=true&live-reload=true", 14 | __dirname + "/demo/index.tsx", 15 | ], 16 | output: { 17 | filename: "bundle.js", 18 | path: __dirname + "/dist", 19 | }, 20 | 21 | mode: "development", 22 | 23 | // Enable sourcemaps for debugging webpack's output. 24 | devtool: "source-map", 25 | 26 | resolve: { 27 | // Add '.ts' and '.tsx' as resolvable extensions. 28 | extensions: [".ts", ".tsx", ".js", ".json"], 29 | }, 30 | 31 | devServer: { 32 | open: true, 33 | compress: true, 34 | port: 9000, 35 | onBeforeSetupMiddleware: function (devServer) { 36 | if (!devServer) { 37 | throw new Error("webpack-dev-server is not defined"); 38 | } 39 | devServer.app.use(express.json()); 40 | devServer.app.get("/root", async (req, res) => { 41 | res.send(await getTreeNode('.')); 42 | }); 43 | }, 44 | }, 45 | 46 | module: { 47 | rules: [ 48 | // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. 49 | { test: /\.jsx?$/, loader: "babel-loader" }, 50 | { test: /\.tsx?$/, loader: "ts-loader" }, 51 | { 52 | test: /\.css$/i, 53 | use: ["style-loader", "css-loader"], 54 | }, 55 | ], 56 | }, 57 | 58 | plugins: [ 59 | new webpack.ProvidePlugin({ 60 | process: "process/browser", 61 | }), 62 | new HtmlWebpackPlugin({ 63 | template: __dirname + "/index.html", 64 | title: "React File Tree", 65 | }), 66 | ], 67 | }; 68 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@sinm/react-file-tree", 3 | "description": "react file tree ", 4 | "version": "1.1.1", 5 | "main": "lib/index.js", 6 | "directories": { 7 | "example": "example" 8 | }, 9 | "scripts": { 10 | "test": "jest", 11 | "prepare": "git submodule update --init --recursive && cp -r github-file-icons/src/file-icons/db github-file-icons/src/file-icons/*.ts src/file-icons", 12 | "build": "yarn prepare && tsc", 13 | "start": "yarn tsc && webpack serve", 14 | "prepublishOnly": "yarn build" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/pansinm/react-file-tree.git" 19 | }, 20 | "keywords": [ 21 | "react", 22 | "explorer", 23 | "tree" 24 | ], 25 | "author": "pansinm ", 26 | "license": "MIT", 27 | "bugs": { 28 | "url": "https://github.com/pansinm/react-file-tree/issues" 29 | }, 30 | "homepage": "https://github.com/pansinm/react-file-tree#readme", 31 | "dependencies": { 32 | "@types/react-virtualized": "^9.21.15", 33 | "react-virtualized": "^9.22.3" 34 | }, 35 | "devDependencies": { 36 | "@babel/core": "^7.20.5", 37 | "@babel/plugin-transform-runtime": "^7.16.4", 38 | "@babel/preset-env": "^7.16.4", 39 | "@babel/preset-react": "^7.16.0", 40 | "@babel/runtime": "^7.16.3", 41 | "@types/fs-extra": "^9.0.13", 42 | "@types/lodash": "^4.14.191", 43 | "@types/mime-types": "^2.1.1", 44 | "@types/react": "^17.0.36", 45 | "@types/react-dom": "^17.0.11", 46 | "babel-loader": "^8.2.3", 47 | "css-loader": "^6.5.1", 48 | "fs-extra": "^10.1.0", 49 | "html-webpack-plugin": "^5.5.0", 50 | "lodash": "^4.17.21", 51 | "mime-types": "^2.1.35", 52 | "react": "^17.0.2", 53 | "react-contexify": "^5.0.0", 54 | "react-dom": "^17.0.2", 55 | "react-hot-loader": "^4.13.0", 56 | "style-loader": "^3.3.1", 57 | "ts-loader": "^9.4.2", 58 | "typescript": "^4.5.2", 59 | "webpack": "^5.64.2", 60 | "webpack-cli": "^4.9.1", 61 | "webpack-dev-server": "^4.5.0" 62 | }, 63 | "files": [ 64 | "lib", 65 | "*.css", 66 | "assets", 67 | "package.json", 68 | "github-file-icons/src/file-icons", 69 | "README.md" 70 | ] 71 | } 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | yarn.lock 9 | build/ 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | lib/* 14 | server/* 15 | 16 | output/ 17 | src/file-icons 18 | 19 | # Runtime data 20 | pids 21 | *.pid 22 | *.seed 23 | *.pid.lock 24 | 25 | # Directory for instrumented libs generated by jscoverage/JSCover 26 | lib-cov 27 | 28 | # Coverage directory used by tools like istanbul 29 | coverage 30 | *.lcov 31 | 32 | # nyc test coverage 33 | .nyc_output 34 | 35 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 36 | .grunt 37 | 38 | # Bower dependency directory (https://bower.io/) 39 | bower_components 40 | 41 | # node-waf configuration 42 | .lock-wscript 43 | 44 | # Compiled binary addons (https://nodejs.org/api/addons.html) 45 | build/Release 46 | 47 | # Dependency directories 48 | node_modules/ 49 | jspm_packages/ 50 | 51 | # TypeScript v1 declaration files 52 | typings/ 53 | 54 | # TypeScript cache 55 | *.tsbuildinfo 56 | 57 | # Optional npm cache directory 58 | .npm 59 | 60 | # Optional eslint cache 61 | .eslintcache 62 | 63 | # Microbundle cache 64 | .rpt2_cache/ 65 | .rts2_cache_cjs/ 66 | .rts2_cache_es/ 67 | .rts2_cache_umd/ 68 | 69 | # Optional REPL history 70 | .node_repl_history 71 | 72 | # Output of 'npm pack' 73 | *.tgz 74 | 75 | # Yarn Integrity file 76 | .yarn-integrity 77 | 78 | # dotenv environment variables file 79 | .env 80 | .env.test 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | 85 | # Next.js build output 86 | .next 87 | 88 | # Nuxt.js build / generate output 89 | .nuxt 90 | dist 91 | 92 | # Gatsby files 93 | .cache/ 94 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 95 | # https://nextjs.org/blog/next-9-1#public-directory-support 96 | # public 97 | 98 | # vuepress build output 99 | .vuepress/dist 100 | 101 | # Serverless directories 102 | .serverless/ 103 | 104 | # FuseBox cache 105 | .fusebox/ 106 | 107 | # DynamoDB Local files 108 | .dynamodb/ 109 | 110 | # TernJS port file 111 | .tern-port 112 | -------------------------------------------------------------------------------- /src/TreeItem.tsx: -------------------------------------------------------------------------------- 1 | import React, { CSSProperties, FC, memo } from "react"; 2 | import { TreeNode } from "./type"; 3 | 4 | export interface TreeItemProps { 5 | style: CSSProperties; 6 | indent: number; 7 | indentUnit: string; 8 | onContextMenu?: ( 9 | event: React.MouseEvent, 10 | treeNode: TreeNode 11 | ) => void; 12 | onDragOver?: ( 13 | event: React.DragEvent, 14 | treeNode: TreeNode 15 | ) => void; 16 | onDrop?: ( 17 | event: React.DragEvent, 18 | fromUri: string, 19 | toUri: string 20 | ) => void; 21 | activated: boolean; 22 | draggable?: boolean; 23 | onClick?: (treeNode: TreeNode) => void; 24 | treeNode: TreeNode; 25 | treeItemRenderer: (treeNode: TreeNode) => React.ReactNode; 26 | } 27 | 28 | export const TreeItem: FC = memo( 29 | ({ 30 | treeNode, 31 | onContextMenu, 32 | treeItemRenderer, 33 | indent, 34 | indentUnit, 35 | style, 36 | draggable, 37 | onClick, 38 | onDragOver, 39 | onDrop, 40 | activated, 41 | }) => { 42 | const className = "file-tree__tree-item " + (activated ? "activated" : ""); 43 | return ( 44 |
{ 49 | e.preventDefault(); 50 | const from = e.dataTransfer.getData("text/plain"); 51 | const to = treeNode.uri; 52 | onDrop?.(e, from, to); 53 | e.currentTarget.classList.remove("file-tree__tree-item--dragover"); 54 | }} 55 | onDragOver={(e) => { 56 | e.preventDefault(); 57 | onDragOver?.(e, treeNode); 58 | e.currentTarget.classList.add("file-tree__tree-item--dragover"); 59 | }} 60 | onDragEnter={(e) => { 61 | e.currentTarget.classList.add("file-tree__tree-item--dragover"); 62 | }} 63 | onDragLeave={(e) => { 64 | e.currentTarget.classList.remove("file-tree__tree-item--dragover"); 65 | }} 66 | onDragStart={(e) => { 67 | // e.dataTransfer.dropEffect = "move"; 68 | e.dataTransfer.setData("text/plain", treeNode.uri); 69 | }} 70 | onClick={() => onClick?.(treeNode)} 71 | style={{ 72 | whiteSpace: "nowrap", 73 | boxSizing: "border-box", 74 | ...style, 75 | paddingLeft: indent + indentUnit, 76 | }} 77 | onContextMenu={(e) => onContextMenu?.(e, treeNode)} 78 | > 79 | {treeItemRenderer(treeNode)} 80 |
81 | ); 82 | } 83 | ); 84 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-file-tree 2 | 3 | ![](./assets/appearence.png) 4 | 5 | [Online Demo](https://codesandbox.io/s/react-file-tree-demo-yc52pj) 6 | 7 | ## Install 8 | 9 | ```bash 10 | yarn add @sinm/react-file-tree 11 | ``` 12 | 13 | ## Usage 14 | 15 | 1. Render tree 16 | 17 | ```tsx 18 | import { FileTree } from '@sinm/react-file-tree'; 19 | // default style 20 | import '@sinm/react-file-tree/styles.css'; 21 | 22 | const [tree, setTree] = useState(defaultTree); 23 | 24 | 25 | ``` 26 | 27 | 2. Toggle expanded 28 | 29 | ```tsx 30 | import { utils } from "@sinm/react-file-tree"; 31 | 32 | const toggleExpanded: FileTreeProps["onItemClick"] = (treeNode) => { 33 | setTree((tree) => 34 | utils.assignTreeNode(tree, treeNode.uri, { expanded: !treeNode.expanded }) 35 | ); 36 | }; 37 | 38 | ; 39 | ``` 40 | 41 | 3. use [github-file-icons](https://github.com/homerchen19/github-file-icons) 42 | 43 | ```tsx 44 | import FileItemWithFileIcon from '@sinm/react-file-tree/lib/FileItemWithFileIcon'; 45 | // import { getFileIconClass } from '@sinm/react-file-tree/lib/FileItemWithFileIcon'; 46 | import '@sinm/react-file-tree/icons.css'; 47 | const itemRenderer = (treeNode: TreeNode) => 48 | 49 | 50 | ``` 51 | 52 | 4. Sort tree items 53 | 54 | ```tsx 55 | import orderBy from "lodash/orderBy"; 56 | 57 | // directory first and filename dict sort 58 | const sorter = (treeNodes: TreeNode[]) => 59 | orderBy( 60 | treeNodes, 61 | [ 62 | (node) => (node.type === "directory" ? 0 : 1), 63 | (node) => utils.getFileName(node.uri), 64 | ], 65 | ["asc", "asc"] 66 | ); 67 | 68 | 69 | ``` 70 | 71 | 5. Load tree from server 72 | 73 | ```tsx 74 | // backend 75 | import { getTreeNode } from "@sinm/react-file-tree/lib/node"; 76 | 77 | app.get("/root", async (req, res, next) => { 78 | try { 79 | const tree = await getTreeNode("."); // build tree for current directory 80 | res.send(tree); 81 | } catch (err) { 82 | next(err); 83 | } 84 | }); 85 | 86 | // frontend 87 | useEffect(() => { 88 | fetch("/root") 89 | .then((res) => res.json()) 90 | // expand root node 91 | .then((tree) => Object.assign(tree, { expanded: true })) 92 | .then(setTree); 93 | }, []); 94 | ``` 95 | 6. activated style 96 | ```css 97 | .file-tree__tree-item.activated { 98 | background: rgba(0, 0, 0, 0.1); 99 | } 100 | ``` 101 | 102 | ```tsx 103 | 104 | ``` 105 | 106 | ## Props 107 | 1. tree: TreeNode. Below is the TreeNode type,Examples can be found at https://codesandbox.io/s/react-file-tree-demo-yc52pj?file=/src/tree.json 108 | ```ts 109 | export type TreeNodeType = "directory" | "file"; 110 | 111 | export type TreeNode = { 112 | [x in K]: T[K]; 113 | } & { 114 | type: TreeNodeType; 115 | uri: string; 116 | expanded?: boolean; 117 | children?: TreeNode[]; 118 | }; 119 | ``` 120 | 2. activatedUri: string 121 | 3. onItemClick(treeNode: TreeNode):void 122 | 4. itemRenderer(treeNode: TreeNode): React.Element 123 | 5. sorter: (treeNodes: TreeNode[]) => TreeNode[] 124 | 125 | ## Demo 126 | 127 | ``` 128 | git clone https://github.com/pansinm/react-file-tree.git 129 | cd react-file-tree 130 | yarn 131 | git submodule update --init --recursive 132 | yarn start 133 | ``` 134 | -------------------------------------------------------------------------------- /src/FileTree.tsx: -------------------------------------------------------------------------------- 1 | import React, { forwardRef } from "react"; 2 | import { AutoSizer, List, ListRowProps } from "react-virtualized"; 3 | import FileItem from "./FileItem"; 4 | import { TreeItem, TreeItemProps } from "./TreeItem"; 5 | import { TreeNode } from "./type"; 6 | import { calcLevel, flatTreeData, getFileName } from "./utils"; 7 | 8 | export interface FileTreeProps { 9 | /** 10 | * 是否支持拖拽 11 | */ 12 | draggable?: boolean; 13 | 14 | tree?: TreeNode; 15 | 16 | activatedUri?: string; 17 | /** 18 | * 点击条目 19 | */ 20 | onItemClick?: (treeNode: TreeNode) => void; 21 | 22 | /** 23 | * 拖拽 24 | * @param fromUri 25 | * @param toDirUri 26 | */ 27 | onDrop?: TreeItemProps["onDrop"]; 28 | 29 | onDragOver?: TreeItemProps["onDragOver"]; 30 | 31 | sorter?: (treeNodes: TreeNode[]) => TreeNode[]; 32 | 33 | /** 34 | * 无数据时展示 35 | */ 36 | emptyRenderer?: () => React.ReactElement; 37 | 38 | /** 39 | * 右键回调 40 | */ 41 | onContextMenu?: ( 42 | event: React.MouseEvent, 43 | treeNode: TreeNode 44 | ) => void; 45 | 46 | /** 47 | * 渲染节点 48 | */ 49 | itemRenderer?: (treeNode: TreeNode) => React.ReactNode; 50 | 51 | /** 52 | * 子节点缩进尺寸 53 | */ 54 | indent?: number; 55 | /** 56 | * 节点高度,默认30 57 | */ 58 | rowHeight?: number; 59 | /** 60 | * 缩进单位,默认px 61 | */ 62 | indentUnit?: string; 63 | } 64 | 65 | function defaultEmptyRenderer() { 66 | return
Nothing
; 67 | } 68 | 69 | function defaultItemRenderer(treeNode: TreeNode) { 70 | const emoji = 71 | treeNode.type === "directory" ? (treeNode.expanded ? "📂" : "📁") : "🗎"; 72 | return ; 73 | } 74 | 75 | export const FileTree = forwardRef( 76 | ( 77 | { 78 | tree, 79 | draggable, 80 | indent, 81 | rowHeight, 82 | indentUnit, 83 | onContextMenu, 84 | onItemClick, 85 | onDrop, 86 | onDragOver, 87 | emptyRenderer, 88 | itemRenderer, 89 | sorter, 90 | activatedUri, 91 | }, 92 | ref 93 | ) => { 94 | const items = flatTreeData(tree ? [tree] : [], sorter); 95 | 96 | const itemRender = itemRenderer 97 | ? (treeNode: TreeNode) => itemRenderer?.(treeNode) 98 | : defaultItemRenderer; 99 | const rowRenderer = (params: ListRowProps) => { 100 | const treeNode = items[params.index]; 101 | const indentNum = indent || 10; 102 | return ( 103 | 117 | ); 118 | }; 119 | 120 | return ( 121 | 122 | {({ height, width }) => ( 123 | 135 | )} 136 | 137 | ); 138 | } 139 | ); 140 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | import { TreeNode } from "./type"; 2 | 3 | /** 4 | * 将树转换成列表 5 | * @param treeData 6 | * @returns 7 | */ 8 | export function flatTreeData(treeData: TreeNode[], sorter?: (treeNodes: TreeNode[]) => TreeNode[]): TreeNode[] { 9 | if (!treeData) { 10 | return []; 11 | } 12 | 13 | const fileTypeVal = { 14 | directory: 0, 15 | file: 1, 16 | }; 17 | // 按字符串排序,目录在前面 18 | let list: TreeNode[] = []; 19 | let sorted = sorter ? sorter(treeData) : [...treeData]; 20 | sorted.forEach((item) => { 21 | list.push(item); 22 | if (item.expanded && item.children) { 23 | list = list.concat(flatTreeData(item.children, sorter)); 24 | } 25 | }); 26 | return list; 27 | } 28 | 29 | /** 30 | * 计算层级 31 | * @param uri 32 | * @param rootUri 33 | * @returns 34 | */ 35 | export function calcLevel(uri: string, rootUri: string) { 36 | if (uri === rootUri) return 0; 37 | return uri.slice(rootUri.length).split("/").length; 38 | } 39 | 40 | /** 41 | * 根据uri获取文件名 42 | * @param uri 43 | * @returns 44 | */ 45 | export function getFileName(uri: string) { 46 | return decodeURIComponent(uri.split("/").pop() || ''); 47 | } 48 | 49 | /** 50 | * 根据uri获取节点路径 51 | * @param tree 52 | * @param uri 53 | * @returns 54 | */ 55 | export function getTreeNodePath(tree: TreeNode, uri: string) { 56 | if (tree.uri === uri) { 57 | return []; 58 | } 59 | let path: number[] = []; 60 | const found = tree.children?.find((item, index) => { 61 | if (item.uri === uri) { 62 | path.push(index); 63 | return true; 64 | } 65 | const subPath = getTreeNodePath(item, uri); 66 | if (subPath) { 67 | path.push(index); 68 | path = path.concat(subPath); 69 | return true; 70 | } 71 | return false; 72 | }); 73 | if (found) return path; 74 | return null; 75 | } 76 | 77 | /** 78 | * 根据子节点路径定位节点 79 | * @param tree 80 | * @param path 81 | * @returns 82 | */ 83 | function getTreeNodeByPath(tree: TreeNode, path: number[]): TreeNode { 84 | if (!path.length) { 85 | return tree; 86 | } 87 | const [first, ...rest] = path; 88 | return getTreeNodeByPath(tree?.children?.[first] as TreeNode, rest); 89 | } 90 | 91 | /** 92 | * 根据uri查询节点 93 | * @param tree 94 | * @param uri 95 | * @returns 96 | */ 97 | export function getTreeNodeByUri(tree: TreeNode | undefined, uri: string) { 98 | if (!tree) { 99 | return undefined; 100 | } 101 | const path = getTreeNodePath(tree, uri); 102 | if (!path) { 103 | return null; 104 | } 105 | return getTreeNodeByPath(tree, path); 106 | } 107 | 108 | /** 109 | * 获取父节点 110 | * @param tree 111 | * @param uri 112 | * @returns 113 | */ 114 | export function getParentNode(tree: TreeNode | undefined, uri: string) { 115 | if (!tree) { 116 | return null; 117 | } 118 | const path = getTreeNodePath(tree, uri); 119 | if (!path) { 120 | return null; 121 | } 122 | path.pop(); 123 | return getTreeNodeByPath(tree, path); 124 | } 125 | 126 | export function isParentUri(curUri: string, parentUri: string) { 127 | return curUri.startsWith(parentUri) && curUri[parentUri.length] === "/"; 128 | } 129 | 130 | /** 131 | * 更新节点属性,并返回新的树 132 | * @param tree 133 | * @param uri 134 | * @param newProps 135 | * @returns 136 | */ 137 | export function assignTreeNode( 138 | tree: TreeNode | undefined, 139 | uri: string, 140 | newProps: Partial 141 | ): TreeNode | undefined { 142 | if (!tree) { 143 | return undefined; 144 | } 145 | const path = getTreeNodePath(tree, uri); 146 | if (!path) { 147 | return tree; 148 | } 149 | let node = getTreeNodeByPath(tree, path); 150 | let newNode = { 151 | ...node, 152 | ...newProps, 153 | }; 154 | 155 | let index = path.pop() as number; 156 | while (index >= 0) { 157 | let parent = getTreeNodeByPath(tree, path); 158 | const children = [...parent.children!]; 159 | children.splice(index, 1, newNode); 160 | newNode = { 161 | ...parent, 162 | children, 163 | }; 164 | index = path.pop() as number; 165 | } 166 | return newNode; 167 | } 168 | 169 | /** 170 | * 为节点增加子节点 171 | * @param tree 172 | * @param parentUri 173 | * @param node 174 | * @returns 175 | */ 176 | export function appendTreeNode( 177 | tree: TreeNode | undefined, 178 | parentUri: string, 179 | node: TreeNode 180 | ) { 181 | if (!tree) { 182 | return undefined; 183 | } 184 | const path = getTreeNodePath(tree, parentUri); 185 | if (!path) { 186 | return tree; 187 | } 188 | let locatedNode = getTreeNodeByPath(tree, path); 189 | if (locatedNode?.children?.find((n) => n.uri === node.uri)) { 190 | console.warn("重复uri"); 191 | return tree; 192 | } 193 | const children = [...(locatedNode.children || []), node]; 194 | return assignTreeNode(tree, parentUri, { children }); 195 | } 196 | 197 | /** 198 | * 从树中删除某节点 199 | * @param tree 200 | * @param uri 201 | * @returns 202 | */ 203 | export function removeTreeNode(tree: TreeNode | undefined, uri: string) { 204 | if (!tree) { 205 | return undefined; 206 | } 207 | const path = getTreeNodePath(tree, uri); 208 | if (!path) { 209 | return tree; 210 | } 211 | // 删除根节点 212 | if (!path.length) { 213 | return undefined; 214 | } 215 | const index = path.pop() as number; 216 | const parentPath = path; 217 | const parent = getTreeNodeByPath(tree, parentPath); 218 | const children = [...(parent.children || [])]; 219 | children.splice(index, 1); 220 | return assignTreeNode(tree, parent.uri, { children }); 221 | } 222 | 223 | /** 224 | * 遍历树,生成新的树,叶子节点优先遍历 225 | * @param tree 226 | * @param fn 227 | * @returns 228 | */ 229 | export function treeMap( 230 | tree: TreeNode, 231 | fn: (treeNode: TreeNode) => TreeNode 232 | ): TreeNode { 233 | if (tree.children) { 234 | let childrenChanged = false; 235 | const newChildren = tree.children.map((node) => { 236 | const newNode = treeMap(node, fn); 237 | if (newNode !== node) { 238 | childrenChanged = true; 239 | } 240 | return newNode; 241 | }); 242 | if (childrenChanged) { 243 | return fn({ 244 | ...tree, 245 | children: newChildren, 246 | }); 247 | } 248 | } 249 | return fn(tree); 250 | } 251 | 252 | export const replaceTreeNode = ( 253 | tree: TreeNode | undefined, 254 | uri: string, 255 | newTreeNode: TreeNode 256 | ) => { 257 | if (!tree) { 258 | return undefined; 259 | } 260 | return treeMap(tree, (treeNode) => { 261 | if (treeNode.uri === uri) { 262 | return newTreeNode; 263 | } 264 | return treeNode; 265 | }); 266 | }; 267 | 268 | type Assert = (condition: unknown, message?: string) => asserts condition; 269 | export const assert: Assert = ( 270 | condition: unknown, 271 | msg?: string 272 | ): asserts condition => { 273 | if (!condition) { 274 | throw new Error(msg); 275 | } 276 | }; 277 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 15 | "lib": ["DOM", "ESNext"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | "jsx": "react", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ 22 | // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | 26 | /* Modules */ 27 | "module": "commonjs", /* Specify what module code is generated. */ 28 | // "rootDir": "./src", /* Specify the root folder within your source files. */ 29 | "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ 30 | "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 31 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 32 | // "rootDirs": ["./src", "./github-file-icons/src"], /* Allow multiple folders to be treated as one when resolving modules. */ 33 | // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ 34 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 35 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 36 | "resolveJsonModule": true, /* Enable importing .json files */ 37 | // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ 38 | 39 | /* JavaScript Support */ 40 | "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ 41 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 42 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ 43 | 44 | /* Emit */ 45 | "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 46 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 47 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 48 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 49 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ 50 | "outDir": "./lib", /* Specify an output folder for all emitted files. */ 51 | // "removeComments": true, /* Disable emitting comments. */ 52 | // "noEmit": true, /* Disable emitting files from a compilation. */ 53 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 54 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ 55 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 56 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 59 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 60 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 61 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 62 | // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ 63 | // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ 64 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 65 | // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ 66 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 67 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 68 | 69 | /* Interop Constraints */ 70 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 71 | "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 72 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ 73 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 74 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 75 | 76 | /* Type Checking */ 77 | "strict": true, /* Enable all strict type-checking options. */ 78 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ 79 | // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ 80 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 81 | // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ 82 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 83 | // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ 84 | // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ 85 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 86 | // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ 87 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ 88 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 89 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 90 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 91 | // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 92 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 93 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ 94 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 95 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 96 | 97 | /* Completeness */ 98 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 99 | "skipLibCheck": true, /* Skip type checking all .d.ts files. */ 100 | }, 101 | "include": ["src/"], 102 | "exclude": ["./server", "server/lib"] 103 | } 104 | --------------------------------------------------------------------------------