Skip to content

Instantly share code, notes, and snippets.

@mikkoh
Created March 15, 2014 03:24
Show Gist options
  • Save mikkoh/9561426 to your computer and use it in GitHub Desktop.
Save mikkoh/9561426 to your computer and use it in GitHub Desktop.
File Browser For Substacks Terminal-Menu
var fs = require( 'fs' );
var path = require( 'path' );
var terminalMenu = require( 'terminal-menu' );
var getUnderline = require( './getUnderline' );
var FileBrowser = function( settings, onFileSelect ) {
this.title = settings.title || 'Browse browse browse';
this.startIdx = 0;
this.maxFiles = settings.maxFiles || 10;
this.path = settings.startPath || './';
this.onFileSelect = onFileSelect;
this.drawFolder();
};
FileBrowser.prototype.drawFolder = function() {
if( this.menu ) {
this.menu.close();
}
this.menu = terminalMenu( { width: 29, x: 4, y: 2 } );
this.menu.reset();
this.menu.write( this.title + '\n' );
this.menu.write( getUnderline( this.title ) + '\n' );
var files = fs.readdirSync( this.path );
var hadMoreFiles = false;
if( this.startIdx != 0 ) {
this.menu.add( '---PREV---' );
this.menu.write( '\n' );
} else {
this.menu.add( '.' );
this.menu.add( '..' );
}
for( var i = this.startIdx, len = files.length; i < len && i - this.startIdx < this.maxFiles; i++ ) {
this.menu.add( files[ i ] );
hadMoreFiles = i + 1 - this.startIdx == this.maxFiles;
}
if( hadMoreFiles ) {
this.menu.write( '\n' );
this.menu.add( '---NEXT---' );
}
this.menu.on( 'select', this.onItemSelect.bind( this ) );
this.menu.createStream().pipe(process.stdout);
};
FileBrowser.prototype.onItemSelect = function( file ) {
if( file == '---NEXT---' ) {
this.startIdx += this.maxFiles;
this.drawFolder();
} else if( file == '---PREV---' ) {
this.startIdx -= this.maxFiles;
this.drawFolder();
} else {
var stat = fs.statSync( path.join( this.path, file ) );
if( stat.isDirectory() ) {
this.path = path.join( this.path, file );
this.startIdx = 0;
this.drawFolder();
} else {
this.menu.reset();
this.menu.close();
this.onFileSelect( file );
}
}
};
module.exports = FileBrowser;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment