diff --git a/DOCS.md b/DOCS.md index 40a8681..0f8f3ad 100644 --- a/DOCS.md +++ b/DOCS.md @@ -9,5 +9,6 @@ To view the documentation for a specific component or class, click on the links * [ButtonPopup](docs/ButtonPopup.md) * [ConfirmPopup](docs/ConfirmPopup.md) * [CustomPopup](docs/CustomPopup.md) +* [FileManagerPopup](docs/FileManagerPopup.md) * [InputPopup](docs/InputPopup.md) * [OptionPopup](docs/OptionPopup.md) diff --git a/docs/FileManagerPopup.md b/docs/FileManagerPopup.md new file mode 100644 index 0000000..f1bf7b4 --- /dev/null +++ b/docs/FileManagerPopup.md @@ -0,0 +1,156 @@ +## Classes + +
+
FileManagerPopupEventEmitter
+
+
+ +## Constants + +
+
CM : ConsoleManager
+

the instance of ConsoleManager (singleton)

+
+
+ + + +## FileManagerPopup ⇐ EventEmitter +**Kind**: global class +**Extends**: EventEmitter + +* [FileManagerPopup](#FileManagerPopup) ⇐ EventEmitter + * [new FileManagerPopup(id, title, basePath, [limitToPath], [allowedExtensions], visible)](#new_FileManagerPopup_new) + * [.listDir(path)](#FileManagerPopup+listDir) ⇒ Promise.<Array.<object>> + * [.updateList(path)](#FileManagerPopup+updateList) + * [.keyListner(str, key)](#FileManagerPopup+keyListner) + * [.getSelected()](#FileManagerPopup+getSelected) ⇒ string \| number + * [.setSelected(selected)](#FileManagerPopup+setSelected) ⇒ [FileManagerPopup](#FileManagerPopup) + * [.show()](#FileManagerPopup+show) ⇒ [FileManagerPopup](#FileManagerPopup) + * [.hide()](#FileManagerPopup+hide) ⇒ [FileManagerPopup](#FileManagerPopup) + * [.isVisible()](#FileManagerPopup+isVisible) ⇒ boolean + * [.manageInput()](#FileManagerPopup+manageInput) ⇒ [FileManagerPopup](#FileManagerPopup) + * [.unManageInput()](#FileManagerPopup+unManageInput) ⇒ [FileManagerPopup](#FileManagerPopup) + * [.draw()](#FileManagerPopup+draw) ⇒ [FileManagerPopup](#FileManagerPopup) + + + +### new FileManagerPopup(id, title, basePath, [limitToPath], [allowedExtensions], visible) +This class is used to create a popup with a file input to select a file or a directory. It will run a promise with fs.readdir to get the list of files and directories. The user can select a file or a directory and the popup will be closed. ![FileManagerPopup](https://user-images.githubusercontent.com/14907987/165938464-c1426102-b598-42bb-8597-6337f0bcb009.gif) Emits the following events: - "confirm" when the user confirm the file or directory selection. The file or directory path is passed as parameter like this: {path: "path/to/file", name: "file.ext"} - "cancel" when the user cancel the file or directory selection. - "exit" when the user exit + + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| id | string | | The id of the popup. | +| title | string | | The title of the popup. | +| basePath | string | | The main path of the popup. re case sensitive. | +| [limitToPath] | boolean | false | If true, the user * @param {boolean} [selectDirectory=false] - If true, the user can select a directory. Otherwise, only files are selectable. When true, to enter a directory, the user must press the space key instead of the enter key. | +| [allowedExtensions] | Array.<string> | [] | The allowed extensions. If not set, all extensions are allowed. The extensions a can only select files in the path. If false, the user can select files in the path and parent directories. | +| visible | boolean | | If the popup is visible. Default is false (make it appears using show()). | + +**Example** +```js +const popup = new FileManagerPopup("popup1", "Choose the file", "./examples").show().on("confirm", (selected) => { console.log(selected) }) // show the popup and wait for the user to confirm +``` + + +### fileManagerPopup.listDir(path) ⇒ Promise.<Array.<object>> +This function is used to load the list of files and directories in the current path. it return a promise with the list of files and directories. The list is an array of objects like this: [{text: "📄 file.ext", name: "file.ext", type: "file", path: "path/to/file.ext"}, {text: "📁 dir/", name: "dir", type: "dir", path: "path/to/dir"}] + +**Kind**: instance method of [FileManagerPopup](#FileManagerPopup) +**Returns**: Promise.<Array.<object>> - The list of files and directories. + +| Param | Type | Description | +| --- | --- | --- | +| path | string | The path to load the list. | + + + +### fileManagerPopup.updateList(path) +This function calls the updateList function and store the result to this.options, it also refresh the list of files and directories. + +**Kind**: instance method of [FileManagerPopup](#FileManagerPopup) + +| Param | Type | Description | +| --- | --- | --- | +| path | string | The path to load the list. | + + + +### fileManagerPopup.keyListner(str, key) +This function is used to make the ConsoleManager handle the key events when the popup is showed. Inside this function are defined all the keys that can be pressed and the actions to do when they are pressed. + +**Kind**: instance method of [FileManagerPopup](#FileManagerPopup) + +| Param | Type | Description | +| --- | --- | --- | +| str | string | The string of the input. | +| key | Object | The key object. | + + + +### fileManagerPopup.getSelected() ⇒ string \| number +This function is used to get the selected option. + +**Kind**: instance method of [FileManagerPopup](#FileManagerPopup) +**Returns**: string \| number - The selected value of the popup. + + +### fileManagerPopup.setSelected(selected) ⇒ [FileManagerPopup](#FileManagerPopup) +This function is used to change the selection of the popup. It also refresh the ConsoleManager. + +**Kind**: instance method of [FileManagerPopup](#FileManagerPopup) +**Returns**: [FileManagerPopup](#FileManagerPopup) - The instance of the FileManagerPopup. + +| Param | Type | Description | +| --- | --- | --- | +| selected | string \| number | The new value of the selection. | + + + +### fileManagerPopup.show() ⇒ [FileManagerPopup](#FileManagerPopup) +This function is used to show the popup. It also register the key events and refresh the ConsoleManager. + +**Kind**: instance method of [FileManagerPopup](#FileManagerPopup) +**Returns**: [FileManagerPopup](#FileManagerPopup) - The instance of the FileManagerPopup. + + +### fileManagerPopup.hide() ⇒ [FileManagerPopup](#FileManagerPopup) +This function is used to hide the popup. It also unregister the key events and refresh the ConsoleManager. + +**Kind**: instance method of [FileManagerPopup](#FileManagerPopup) +**Returns**: [FileManagerPopup](#FileManagerPopup) - The instance of the FileManagerPopup. + + +### fileManagerPopup.isVisible() ⇒ boolean +This function is used to get the visibility of the popup. + +**Kind**: instance method of [FileManagerPopup](#FileManagerPopup) +**Returns**: boolean - The visibility of the popup. + + +### fileManagerPopup.manageInput() ⇒ [FileManagerPopup](#FileManagerPopup) +This function is used to add the FileManagerPopup key listener callback to te ConsoleManager. + +**Kind**: instance method of [FileManagerPopup](#FileManagerPopup) +**Returns**: [FileManagerPopup](#FileManagerPopup) - The instance of the FileManagerPopup. + + +### fileManagerPopup.unManageInput() ⇒ [FileManagerPopup](#FileManagerPopup) +This function is used to remove the FileManagerPopup key listener callback to te ConsoleManager. + +**Kind**: instance method of [FileManagerPopup](#FileManagerPopup) +**Returns**: [FileManagerPopup](#FileManagerPopup) - The instance of the FileManagerPopup. + + +### fileManagerPopup.draw() ⇒ [FileManagerPopup](#FileManagerPopup) +This function is used to draw the FileManagerPopup to the screen in the middle. + +**Kind**: instance method of [FileManagerPopup](#FileManagerPopup) +**Returns**: [FileManagerPopup](#FileManagerPopup) - The instance of the FileManagerPopup. + + +## CM : ConsoleManager +the instance of ConsoleManager (singleton) + +**Kind**: global constant diff --git a/examples/tcp_simulator.mjs b/examples/tcp_simulator.mjs index ce65a89..08b3a11 100644 --- a/examples/tcp_simulator.mjs +++ b/examples/tcp_simulator.mjs @@ -12,7 +12,7 @@ const modeList = ["random", "linear"] const clientManager = new EventEmitter() -import { ConsoleManager, OptionPopup, InputPopup, PageBuilder, ButtonPopup, ConfirmPopup, CustomPopup } from '../src/ConsoleGui.js' +import { ConsoleManager, OptionPopup, InputPopup, PageBuilder, ButtonPopup, ConfirmPopup, CustomPopup, FileManagerPopup } from '../src/ConsoleGui.js' const GUI = new ConsoleManager({ title: 'TCP Simulator', // Title of the console logsPageSize: 8, // Number of lines to show in logs page @@ -201,6 +201,9 @@ GUI.on("keypressed", (key) => { p.addRow({ text: `Message period: `, color: 'green' }, { text: `${period} ms`, color: 'white' }) new CustomPopup("popupCustom1", "See that values", p, 32).show() break + case 'f': + new FileManagerPopup("popupFileManager", "File Manager", "./").show() + break case 'q': new ConfirmPopup("popupQuit", "Are you sure you want to quit?").show().on("confirm", () => closeApp()) break diff --git a/src/ConsoleGui.js b/src/ConsoleGui.js index ee4e9b4..9a89830 100644 --- a/src/ConsoleGui.js +++ b/src/ConsoleGui.js @@ -2,7 +2,7 @@ import { EventEmitter } from "events" import readline from 'readline'; import { PageBuilder, Screen } from './components/index.js'; import { DoubleLayout } from "./components/layout/index.js"; -import { InputPopup, OptionPopup, ButtonPopup, ConfirmPopup, CustomPopup } from "./components/widgets/index.js"; +import { InputPopup, OptionPopup, ButtonPopup, ConfirmPopup, CustomPopup, FileManagerPopup } from "./components/widgets/index.js"; /** * @class ConsoleManager @@ -285,5 +285,6 @@ export { InputPopup, ConfirmPopup, ButtonPopup, - CustomPopup + CustomPopup, + FileManagerPopup } \ No newline at end of file diff --git a/src/components/widgets/FileManagerPopup.js b/src/components/widgets/FileManagerPopup.js new file mode 100644 index 0000000..218c309 --- /dev/null +++ b/src/components/widgets/FileManagerPopup.js @@ -0,0 +1,338 @@ +import { EventEmitter } from "events" +import { ConsoleManager } from "../../ConsoleGui.js" +import fs from "fs" +import path from "path" + +/** + * @class FileManagerPopup + * @extends EventEmitter + * @description This class is used to create a popup with a file input to select a file or a directory. + * It will run a promise with fs.readdir to get the list of files and directories. + * The user can select a file or a directory and the popup will be closed. + * + * ![FileManagerPopup](https://user-images.githubusercontent.com/14907987/165938464-c1426102-b598-42bb-8597-6337f0bcb009.gif) + * + * Emits the following events: + * - "confirm" when the user confirm the file or directory selection. The file or directory path is passed as parameter like this: {path: "path/to/file", name: "file.ext"} + * - "cancel" when the user cancel the file or directory selection. + * - "exit" when the user exit + * @param {string} id - The id of the popup. + * @param {string} title - The title of the popup. + * @param {string} basePath - The main path of the popup. +re case sensitive. + * @param {boolean} [limitToPath=false] - If true, the user * @param {boolean} [selectDirectory=false] - If true, the user can select a directory. Otherwise, only files are selectable. When true, to enter a directory, the user must press the space key instead of the enter key. + * @param {Array} [allowedExtensions=[]] - The allowed extensions. If not set, all extensions are allowed. The extensions a can only select files in the path. If false, the user can select files in the path and parent directories. + * @param {boolean} visible - If the popup is visible. Default is false (make it appears using show()). + * + * @example const popup = new FileManagerPopup("popup1", "Choose the file", "./examples").show().on("confirm", (selected) => { console.log(selected) }) // show the popup and wait for the user to confirm + */ +export class FileManagerPopup extends EventEmitter { + constructor(id, title, basePath, selectDirectory = false, allowedExtensions = [], limitToPath = false, visible = false) { + super(); + /** @const {ConsoleManager} CM the instance of ConsoleManager (singleton) */ + this.CM = new ConsoleManager(); + this.id = id; + this.title = title; + this.basePath = basePath; + this.currentPath = basePath; + this.selectDirectory = selectDirectory; + this.allowedExtensions = allowedExtensions; + this.limitToPath = limitToPath; + this.visible = visible; + this.marginTop = 4; + this.startIndex = 0; + this.selected = { text: `../`, name: "../", type: "dir", path: path.join(basePath, "../") }; + if (this.CM.widgetsCollection[this.id]) { + this.CM.unRegisterWidget(this); + const message = `FileManagerPopup ${this.id} already exists.`; + this.CM.error(message); + throw new Error(message); + } + this.CM.registerWiget(this); + this.options = [{ text: `../`, name: "../" }]; + this.updateList(this.basePath); + } + + /** + * @description This function is used to load the list of files and directories in the current path. + * it return a promise with the list of files and directories. The list is an array of objects like this: + * [{text: "📄 file.ext", name: "file.ext", type: "file", path: "path/to/file.ext"}, {text: "📁 dir/", name: "dir", type: "dir", path: "path/to/dir"}] + * @param {string} path - The path to load the list. + * @returns {Promise>} The list of files and directories. + * @memberof FileManagerPopup + */ + listDir(dir) { + return new Promise((resolve, reject) => { + fs.readdir(dir, (err, files) => { + if (err) { + reject(err) + } else { + resolve(files.map(file => { + const filePath = path.join(dir, file) + const stats = fs.statSync(filePath) + const isDirectory = stats.isDirectory() + const isFile = stats.isFile() + if (isDirectory) { + return { text: `📁 ${file}/`, name: file, type: "dir", path: filePath } + } else if (isFile) { + return { text: `📄 ${file}`, name: file, type: "file", path: filePath } + } + }).filter(file => { + const isAllowed = this.allowedExtensions.length === 0 || this.allowedExtensions.includes(path.extname(file.name)) + if (this.selectDirectory && file.type === "file") { + return false + } + return isAllowed || file.type === "dir" + })) + } + }) + }) + } + + /** + * @description This function calls the updateList function and store the result to this.options, it also refresh the list of files and directories. + * @param {string} path - The path to load the list. + * @memberof FileManagerPopup + */ + updateList(_path) { + if (this.limitToPath) { + if (!path.resolve(_path).includes(path.resolve(this.basePath))) { + return + } + } + this.currentPath = _path + this.listDir(this.currentPath).then((files) => { + this.options = [{ text: `../`, name: "../", type: "dir", path: path.join(this.currentPath, "../") }].concat(files) + this.setSelected(this.options[0], false) + this.CM.refresh() + }) + } + + adaptOptions() { + return this.options.slice(this.startIndex, this.startIndex + this.CM.Screen.height - this.marginTop - 6) + } + + /** + * @description This function is used to make the ConsoleManager handle the key events when the popup is showed. + * Inside this function are defined all the keys that can be pressed and the actions to do when they are pressed. + * @param {string} str - The string of the input. + * @param {Object} key - The key object. + * @memberof FileManagerPopup + */ + keyListner(str, key) { + const ind = this.options.indexOf(this.selected) + switch (key.name) { + case 'down': + this.setSelected(this.options[(ind + 1) % this.options.length], false) + if (this.CM.Screen.height - this.marginTop - 4 < this.options.length) { + if (this.selected === this.options[this.adaptOptions().length + this.startIndex]) { + this.startIndex++ + } + } else { + this.startIndex = 0 + } + break + case 'up': + this.setSelected(this.options[(ind - 1 + this.options.length) % this.options.length], false) + if (this.startIndex > 0 && this.selected === this.adaptOptions()[0]) { + this.startIndex-- + } + break + case 'pagedown': + if (this.CM.Screen.height - this.marginTop - 4 < this.options.length) { + this.setSelected(this.options[(ind + this.adaptOptions().length) % this.options.length], false) + if (this.startIndex + this.adaptOptions().length < this.options.length) { + this.startIndex += this.adaptOptions().length + } else { + this.startIndex = 0 + } + } else { + return + } + break + case 'pageup': + if (this.CM.Screen.height - this.marginTop - 4 < this.options.length) { + this.setSelected(this.options[(ind - this.adaptOptions().length + this.options.length) % this.options.length], false) + if (this.startIndex > this.adaptOptions().length) { + this.startIndex -= this.adaptOptions().length + } else { + this.startIndex = 0 + } + } else { + return + } + break + case 'return': + { + if (this.selectDirectory) { + if (this.selected.type === "dir") { + this.emit("confirm", { path: this.selected.path, name: this.selected.name }) + this.CM.unRegisterWidget(this) + this.hide() + delete this + } + } else { + if (this.selected.type === "dir") { + this.updateList(this.selected.path) + } else { + this.emit("confirm", { path: this.selected.path, name: this.selected.name }) + this.CM.unRegisterWidget(this) + this.hide() + delete this + } + } + } + break + case 'space': + if (this.selected.type === "dir") { + this.updateList(this.selected.path) + } + break + case 'escape': + { + this.emit(`cancel`) + this.CM.unRegisterWidget(this) + this.hide() + delete this + } + break + case 'q': + { + this.CM.emit('exit') + this.CM.unRegisterWidget(this) + this.hide() + delete this + } + break + default: + break + } + this.CM.refresh() + } + + /** + * @description This function is used to get the selected option. + * @returns {string | number} The selected value of the popup. + * @memberof FileManagerPopup + */ + getSelected() { + return this.selected + } + + /** + * @description This function is used to change the selection of the popup. It also refresh the ConsoleManager. + * @param {string | number} selected - The new value of the selection. + * @memberof FileManagerPopup + * @returns {FileManagerPopup} The instance of the FileManagerPopup. + */ + setSelected(selected, refresh = true) { + this.selected = selected + this.CM.refresh() + return this + } + + /** + * @description This function is used to show the popup. It also register the key events and refresh the ConsoleManager. + * @returns {FileManagerPopup} The instance of the FileManagerPopup. + * @memberof FileManagerPopup + */ + show() { + if (!this.visible) { + this.manageInput() + this.visible = true + this.CM.refresh() + } + return this + } + + /** + * @description This function is used to hide the popup. It also unregister the key events and refresh the ConsoleManager. + * @returns {FileManagerPopup} The instance of the FileManagerPopup. + * @memberof FileManagerPopup + */ + hide() { + if (this.visible) { + this.unManageInput() + this.visible = false + this.CM.refresh() + } + return this + } + + /** + * @description This function is used to get the visibility of the popup. + * @returns {boolean} The visibility of the popup. + * @memberof FileManagerPopup + */ + isVisible() { + return this.visible + } + + /** + * @description This function is used to add the FileManagerPopup key listener callback to te ConsoleManager. + * @returns {FileManagerPopup} The instance of the FileManagerPopup. + * @memberof FileManagerPopup + */ + manageInput() { + // Add a command input listener to change mode + this.CM.setKeyListener(this.id, this.keyListner.bind(this)) + return this + } + + /** + * @description This function is used to remove the FileManagerPopup key listener callback to te ConsoleManager. + * @returns {FileManagerPopup} The instance of the FileManagerPopup. + * @memberof FileManagerPopup + */ + unManageInput() { + // Add a command input listener to change mode + this.CM.removeKeyListener(this.id) + return this + } + + /** + * @description This function is used to draw the FileManagerPopup to the screen in the middle. + * @returns {FileManagerPopup} The instance of the FileManagerPopup. + * @memberof FileManagerPopup + */ + draw() { + // Change start index if selected is not in the adaptOptions return array + const ind = this.adaptOptions().indexOf(this.selected) + const ind1 = this.options.indexOf(this.selected) + if (ind === -1) { + this.startIndex = ind1 - this.adaptOptions().length + 1 > 0 ? ind1 - this.adaptOptions().length + 1 : 0 + } + const offset = 2 + const maxOptionsLength = this.options.map((o) => o.text).reduce((max, option) => Math.max(max, option.length), 0) + const windowWidth = maxOptionsLength > this.title.length ? maxOptionsLength + (2 * offset) : this.title.length + (2 * offset) + const halfWidth = Math.round((windowWidth - this.title.length) / 2) + + let header = "┌" + for (let i = 0; i < windowWidth; i++) { + header += "─" + } + header += "┐\n" + header += `│${" ".repeat(halfWidth)}${this.title}${" ".repeat(windowWidth - halfWidth - this.title.length)}│\n` + header += "├" + "─".repeat(windowWidth) + "┤\n" + + let footer = "└" + for (let i = 0; i < windowWidth; i++) { + footer += "─" + } + footer += "┘\n" + + let content = "" + this.adaptOptions().forEach((option, index) => { + content += `│${option.name === this.selected.name ? "<" : " "} ${option.text}${option.name === this.selected.name ? " >" : " "}${" ".repeat(windowWidth - option.text.toString().length - 4)}│\n` + }) + + const windowDesign = `${header}${content}${footer}` + windowDesign.split('\n').forEach((line, index) => { + this.CM.Screen.cursorTo(Math.round((this.CM.Screen.width / 2) - (windowWidth / 2)), this.marginTop + index) + this.CM.Screen.write({ text: line, style: { color: 'white' } }) + }) + return this + } +} + +export default FileManagerPopup \ No newline at end of file diff --git a/src/components/widgets/index.js b/src/components/widgets/index.js index d22b4b3..65cb038 100644 --- a/src/components/widgets/index.js +++ b/src/components/widgets/index.js @@ -2,4 +2,5 @@ export * from './InputPopup.js'; export * from './OptionPopup.js'; export * from './ButtonPopup.js'; export * from './ConfirmPopup.js'; -export * from './CustomPopup.js'; \ No newline at end of file +export * from './CustomPopup.js'; +export * from './FileManagerPopup.js'; \ No newline at end of file