Use the hash to store the path.
[armadillo.git] / web_frontend / main.js
1 goog.provide('armadillo');
2
3 goog.require('goog.array');
4 goog.require('goog.dom');
5 goog.require('goog.net.XhrIo');
6 goog.require('goog.Uri.QueryData');
7
8 armadillo = function() {
9 var start_path = '/';
10 if (window.location.hash) {
11 start_path = window.location.hash.substr(1);
12 }
13 this.list(start_path);
14 this.listeners_ = new Array();
15 goog.events.listen(window, goog.events.EventType.HASHCHANGE,
16 this.hashChanged_, false, this);
17 }
18
19 /**
20 * Starts a new XHR service request from the backend.
21 * @param {string} action Action to perform.
22 * @param {Object} extra_data Extra data to add.
23 * @param {Function} callback XHR callback.
24 */
25 armadillo.prototype.sendRequest_ = function(action, extra_data, callback) {
26 var data = new goog.Uri.QueryData();
27 data.set('action', 'list');
28 data.extend(extra_data);
29 goog.net.XhrIo.send('/service', callback, 'POST', data);
30 };
31
32 /**
33 * Updates the directory listing for a given path.
34 * @param {string} path Path to list; relative to jail.
35 */
36 armadillo.prototype.list = function(path) {
37 var callback = function(e) {
38 var data = e.target.getResponseJson();
39 if (data['status']) {
40 return; // Error.
41 }
42 // Unlisten all current listeners.
43 goog.array.forEach(app.listeners_, function(e) {
44 goog.events.unlistenByKey(e);
45 });
46
47 // Update the listing.
48 goog.dom.setTextContent(goog.dom.getElement('pwd'), path);
49 app.currentPath_ = path;
50 window.location.hash = path;
51 var list = goog.dom.getElement('ls');
52 goog.dom.removeChildren(list);
53
54 // Add items for each entry.
55 goog.array.forEach(data, function(file) {
56 var elm = goog.dom.createElement('li');
57 goog.dom.setTextContent(elm, file);
58 goog.dom.appendChild(list, elm);
59 app.listeners_.push(goog.events.listen(elm,
60 goog.events.EventType.CLICK, app.clickHandler_, false, app));
61 });
62 }
63 this.sendRequest_('list', {'path':path}, callback);
64 };
65
66 /**
67 * Click handler for elements.
68 * @param {Event} e
69 */
70 armadillo.prototype.clickHandler_ = function(e) {
71 if (this.isDirectory_(goog.dom.getTextContent(e.target))) {
72 this.list(this.currentPath_ + goog.dom.getTextContent(e.target));
73 }
74 };
75
76 /**
77 * Event for when the hash changes.
78 * @param {Event} e
79 */
80 armadillo.prototype.hashChanged_ = function(e) {
81 if (window.location.hash.length)
82 this.list(window.location.hash.substr(1));
83 };
84
85 /**
86 * Checks whether a path is a directory.
87 * @param {string} path
88 * @returns boolean
89 */
90 armadillo.prototype.isDirectory_ = function(path) {
91 return path[path.length - 1] == '/';
92 };