L2dhZGdldC9jcmlianMtaWRlLWdhZGdldC5qcw==.js 17.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
/*globals window, document, RSVP, rJS,
         location, console*/
/*jslint indent: 2, maxlen: 80*/
(function (window, document, RSVP, rJS, location, console) {
  "use strict";

  var CODE_CONTENT_KEY = "text_content";

  function getExtension(url) {
    var extension = url.split('.').pop();
    if (extension.endsWith('/')) {
      return ".html";
    }
    return "." + extension;
  }

  function createJio(gadget, jio_config) {
    var jio_gadget;
    return gadget.getDeclaredGadget("jio_gadget")
      .push(function (jio_g) {
        jio_gadget = jio_g;
        if (jio_config === undefined)
          jio_config = {type: "indexeddb", database: "cribjs"};
        console.log(jio_config);
        return jio_gadget.createJio(jio_config);
    });
  }

  function createDAVJio(gadget, event) {
    return createJio(gadget, {
      type:"dav",
      url: gadget.props.element.querySelector('.form-use-jio-dav .url').value,
      basic_login: btoa(gadget.props.element.querySelector(".form-use-jio-dav .credential").value)
    });
  }  


  function displayURLList(gadget, event) {
    return new RSVP.Queue()
    .push(function () {
       return gadget.crib_sw_allDocs()
    })
    .push(function(data) {
      var contentsElement = gadget.props.element.querySelector('.crib-url-list-content tbody'),
        footer_element = gadget.props.element.querySelector('.crib-url-list-content tfoot'),
        url_list = data.urls,
        url_number = 0, cached_number = 0,
        url, trElement, tdElement;
      // Clear out the existing items from the list.
      while (contentsElement.firstChild) {
        contentsElement.removeChild(contentsElement.firstChild);
      }
      console.log(url_list);
      // Add each cached URL to the list, one by one.
      for (url in url_list) {
        if (url_list.hasOwnProperty(url)) {
          var element;
          cached_number = url_list[url].cached ? cached_number + 1 : cached_number;
          url_number += 1;
          trElement = document.createElement('tr');
          tdElement = document.createElement('td');
          tdElement.innerHTML = (url_list[url].cached ? "<span>&#x2713;</span>" : "")
          trElement.appendChild(tdElement);
          tdElement = document.createElement('td');
          element = document.createElement('a');
          element.setAttribute('href', "#view=editor&url=" + url);
          element.textContent = url;
          tdElement.appendChild(element);
          trElement.appendChild(tdElement);
          tdElement = document.createElement('td');
          element = document.createElement('a');
          element.textContent = "Go";
          element.setAttribute('href', url);
          element.setAttribute('target', "_blank");
          element.setAttribute("class", "btn btn-primary btn-xs");
          tdElement.appendChild(element);
          trElement.appendChild(tdElement);
          contentsElement.appendChild(trElement);
        }
      };
      while (footer_element.firstChild) {
        footer_element.removeChild(footer_element.firstChild);
      }
      trElement = document.createElement('tr');
      tdElement = document.createElement('td');
      tdElement.innerHTML = "<span>" + cached_number + " &#x2713;</span>";
      trElement.appendChild(tdElement);
      tdElement = document.createElement('td');
      tdElement.innerHTML =  url_number + " URLs";
      trElement.appendChild(tdElement);      
      tdElement = document.createElement('td');
      trElement.appendChild(tdElement);
      footer_element.appendChild(trElement);
    })
    .fail(function(error) {
      // XXX An Error Should be thrown
      console.log(error);
      throw error;
    });
  }

  function saveTextContent(gadget, event) {
    var content,
      url = gadget.props.element.querySelector("form.crib-editor-get .url").value,
      mimetype = gadget.props.element.querySelector("form.crib-editor-save .mimetype").value;
    console.log("saving content");
    return new RSVP.Queue()
    .push(function () {
       return gadget.getDeclaredGadget('codeeditor');      
     })
    .push(function (code_editor_gadget) {
       return code_editor_gadget.getContent();
    })
    .push(function (data) {
       content = data[CODE_CONTENT_KEY] || "";
       return gadget.crib_sw_put(url, {content:content, type:mimetype});
    })
    .push(function() {
      gadget.props.element.querySelector(".crib-editor-save-status").textContent = "Saved " + url + " files at "+ Date ()
    })
    .fail(function(error) {
      console.log(error);
      gadget.props.element.querySelector(".crib-editor-save-status").textContent = error;
    });
  }

  function getUrlTextContent(gadget, event, url) {
    console.log("saving content");
    return new RSVP.Queue()
    .push(function () {
      return RSVP.all([gadget.crib_sw_get(url),
        gadget.getDeclaredGadget('codeeditor')])
    })
    .push(function(data_list) {
      //gadget.props.element.querySelector("form.crib-editor-save .content").value = data_list[0].responseText;
      gadget.props.element.querySelector("form.crib-editor-save .mimetype").value = data_list[0].responseType;
      return data_list[1].render({
        key: CODE_CONTENT_KEY,
        value: data_list[0].responseText,
        mode: data_list[0].responseType
        });
    })
    .fail(function(error) {
      console.log(error);
    });
  }

  function saveContentToJIO(gadget, event) {
    var path_to_save, path_to_save_length, application_id, crib_sw_gadget,
      jio_gadget, url_list = [], saved_number = 0;
    path_to_save = gadget.props.element.querySelector('form.crib-save-to-jio .save-path').value
    application_id = gadget.props.element.querySelector('form.crib-save-to-jio .save-id').value
    path_to_save_length = path_to_save.length;
    return new RSVP.Queue()
    .push(function () {
      return RSVP.all([
        gadget.getDeclaredGadget('jio_gadget')]);
    })
    .push(function (gadget_list) {
      jio_gadget = gadget_list[0];
      return gadget.crib_sw_allDocs({cached_only: true});
    })
    .push(function(data) {
      url_list = data.urls;
      // This is buggy, it fails if the document already exists with dav storage
      return RSVP.all(
        [jio_gadget.put("/" + application_id + ".attachment/", {
                 // url: path_to_save
                  }),
         jio_gadget.putAttachment("/", application_id, new Blob([JSON.stringify({url: path_to_save})],{type: "application/json"}))  
      ]);      
    })
    .push(function() {
      var promise_list = [],
        i, i_len, url;
      for (i = 0, i_len = url_list.length; i < i_len; i += 1) {
        url = new String(url_list[i]);
        if (url.indexOf(path_to_save) === 0) {
          saved_number += 1;
          promise_list.push(gadget.crib_sw_get(url));
        };
      };
      return RSVP.all(promise_list);
    })
    .push(function(response_list) {
      var promise_list = [],
        i, i_len, url, response, extension;
      for (i = 0, i_len = response_list.length; i < i_len; i += 1) {
        response = response_list[i];
        url = response.responseURL.substr(path_to_save_length)
        extension = getExtension(url)
        console.log("Will push attachment " + url + " to " + path_to_save);
        promise_list.push(
          jio_gadget.putAttachment("/" + application_id + ".attachment/", btoa(url) + extension,
            // XXX Not sure it would work with images
            new Blob([response.responseText], {type : response.responseType})
          )
        );
      };
      return RSVP.all(promise_list)
    })
    .push(function() {
      gadget.props.element.querySelector(".crib-save-to-jio-status").textContent = "Saved " + saved_number + " files at "+ Date ()
    })
    .fail(function(error) {
      gadget.props.element.querySelector(".crib-save-to-jio-status").textContent = error;
      console.log(error);
    });
  }


  function loadContentFromJIO(gadget, event) {
    var path_to_load, path_to_load_length, application_id, crib_sw_gadget,
      jio_gadget, url_list = [];
    path_to_load = gadget.props.element.querySelector('form.crib-load-from-jio .load-path').value
    application_id = gadget.props.element.querySelector('form.crib-load-from-jio .load-id').value
    path_to_load_length = path_to_load.length;
    return new RSVP.Queue()
    .push(function () {
      return RSVP.all([
        gadget.getDeclaredGadget('jio_gadget')]);
    })
    .push(function (gadget_list) {
      jio_gadget = gadget_list[0];
      return jio_gadget.allAttachments("/" + application_id + ".attachment/");
    })
      .push(function(response) {
        var promise_list = [],
          key, extension;
        for (key in response) {
          if (response.hasOwnProperty(key)) {
            extension = getExtension(key);
            console.log(key);
            url_list.push(atob(key.substr(0, key.length - extension.length)))
            promise_list.push(jio_gadget.getAttachment("/" + application_id + ".attachment/", key));
          }
        };
        return RSVP.all(promise_list)
      })
      .push(function(response_list) {
        var promise_list = [],
          i, i_len, url, index, response, location, location_len;
        location = document.location.origin;
        location_len = location.length
        console.log(url_list);
        console.log(response_list);
        for (i = 0, i_len = response_list.length; i < i_len; i += 1) {
          url = url_list[i]
          index = url.indexOf(location);
          if (index != -1)
            url = url.substr(index + location_len);
          promise_list.push( 
            gadget.crib_sw_put(path_to_load + url, {blob: response_list[i]})
          )
        }
      })
      .push(function() {
        gadget.props.element.querySelector(".crib-load-from-jio-status").textContent = "Loaded " + url_list.length + " files at "+ Date ()
      })
    .fail(function(error) {
      gadget.props.element.querySelector(".crib-load-from-jio-status").textContent = error;
      console.log(error);
    });
  }

  function massRemoveFromCache(gadget, event) {
    var url_list = gadget.props.element.querySelector("form.crib-mass-remove textarea").value.match(/[^\r\n]+/g),
      url_list_length = url_list.length;
    return new RSVP.Queue()
    .push(function () {
      var i,
        promise_list = [];
      for (i = 0; i < url_list_length; i += 1) {
        console.log(url_list[i])
        promise_list.push(gadget.crib_sw_remove(url_list[i]));
      };
      return RSVP.all(promise_list);
    })
    .push(function() {
      gadget.props.element.querySelector(".crib-mass-remove-status").textContent = "Removed " + url_list.length + " files at "+ Date ()
    })
    .fail(function(error) {
      gadget.props.element.querySelector(".crib-mass-remove-status").textContent = error;
      console.log(error);
    });
  }

  function displayTabContent(gadget, state) {
    var tab_content_list = gadget.props.element.querySelectorAll('.nav_content');
    console.log(tab_content_list.length);
    for (var i = 0; i < tab_content_list.length; i += 1 ){
      console.log('working with:');
      console.log(tab_content_list[i]);
      if (tab_content_list[i].getAttribute('class').indexOf(state) === -1) {
        tab_content_list[i].setAttribute('style', 'display:none;');
      } else {
        tab_content_list[i].setAttribute('style', '');
      }
    }
  }

  function listenHashChange(gadget) {

    function extractHashAndDispatch(evt) {
      var hash = (evt.newURL || window.location.toString()).split('#')[1],
        subhashes,
        subhash,
        keyvalue,
        index,
        options = {};
      if (hash === undefined) {
        hash = "";
      } else {
        hash = hash.split('?')[0];
      }

      function optionalize(key, value, dict) {
        var key_list = key.split("."),
          kk,
          i;
        for (i = 0; i < key_list.length; i += 1) {
          kk = key_list[i];
          if (i === key_list.length - 1) {
            dict[kk] = value;
          } else {
            if (!dict.hasOwnProperty(kk)) {
              dict[kk] = {};
            }
            dict = dict[kk];
          }
        }
      }

      subhashes = hash.split('&');
      for (index in subhashes) {
        if (subhashes.hasOwnProperty(index)) {
          subhash = subhashes[index];
          if (subhash !== '') {
            keyvalue = subhash.split('=');
            if (keyvalue.length === 2) {

              optionalize(decodeURIComponent(keyvalue[0]),
                decodeURIComponent(keyvalue[1]),
                options);

            }
          }
        }
      }

      if (gadget.render !== undefined) {
        return gadget.render(options);
      }
    }

    var result = loopEventListener(window, 'hashchange', false,
                                   extractHashAndDispatch),
        
      event = document.createEvent("Event");

    event.initEvent('hashchange', true, true);
    event.newURL = window.location.toString();
    window.dispatchEvent(event);
    return result;
  }

  rJS(window)
    .ready(function (g) {
      g.props = {};
      return g.getElement()
        .push(function (element) {
          g.props.element = element;
          g.props.start_deferred = RSVP.defer();
          g.props.deferred = RSVP.defer();
         });
    })
    .ready(function (g) {
      return createJio(g);
    })
    .ready(function (g) {
      // Empty Base Element
      var base_element = document.getElementsByTagName("base")[0];
      if (base_element != undefined) {
        base_element.removeAttribute("href");
        base_element.removeAttribute("target");
      }
    })
    .allowPublicAcquisition("editor_saveContent", function () {
      return saveTextContent(this, undefined);
    })
    .declareAcquiredMethod("crib_sw_allDocs", "crib_sw_allDocs")
    .declareAcquiredMethod("crib_sw_remove", "crib_sw_remove")
    .declareAcquiredMethod("crib_sw_put", "crib_sw_put")
    .declareAcquiredMethod("crib_sw_get", "crib_sw_get")
    .declareMethod('render', function (options) {
      var gadget = this;
      if (options === undefined) 
        options = {}
      gadget.props.element.querySelector('form.crib-save-to-jio .save-path').value = document.location.origin;
      gadget.props.element.querySelector('form.crib-load-from-jio .load-path').value = document.location.origin;
      gadget.props.options = options;
      return new RSVP.Queue()
        .push(function () {
          var promise_list = [];
          // Add promise for list Cache content
          if (options.url !== undefined) {
            gadget.props.element.querySelector("form.crib-editor-get .url").value = options.url;
            promise_list.push(getUrlTextContent(gadget, undefined, options.url))
          }
          promise_list.push(displayTabContent(gadget, options.view || 'cribjs'));
          promise_list.push(displayURLList(gadget, undefined));
          return RSVP.all(promise_list);
        })
        .push(function () {
          return gadget.props.start_deferred.resolve();
        })  
        .push(undefined, function(e) {
          console.log(e);
          throw e;
        });
    })
    .declareService(function () {
      var gadget = this;
      return new RSVP.Queue()
        .push(function () {
          return gadget.props.start_deferred.promise;
        })
        .push(function () {
          var promise_list = [];
          promise_list.push(loopEventListener(
            gadget.props.element.querySelector(".crib-url-list-content"),
            'submit',
            false,
            function (event) {displayURLList(gadget, event)}
          ));
          // promise to get content from URL
          promise_list.push(loopEventListener(
            gadget.props.element.querySelector(".crib-editor-get"),
            'submit',
            false,
            function (event) {
              var url = gadget.props.element.querySelector("form.crib-editor-get .url").value;
              return getUrlTextContent(gadget, event, url);
            }
          ));
          // promise to save content
          promise_list.push(loopEventListener(
            gadget.props.element.querySelector(".crib-editor-save"),
            'submit',
            false,
            function (event) {saveTextContent(gadget, event)}
          ));
          // promise to save content to jIO
          promise_list.push(loopEventListener(
            gadget.props.element.querySelector(".crib-save-to-jio"),
            'submit',
            false,
            function (event) {saveContentToJIO(gadget, event)}
          ));
          // promise to load content from jIO
          promise_list.push(loopEventListener(
            gadget.props.element.querySelector(".crib-load-from-jio"),
            'submit',
            false,
            function (event) {loadContentFromJIO(gadget, event)}
          ));
          // promise to remove content from cache
          promise_list.push(loopEventListener(
            gadget.props.element.querySelector(".crib-mass-remove"),
            'submit',
            false,
            function (event) {massRemoveFromCache(gadget, event)}
          ));
          // promise to use dav storage for jIO
          promise_list.push(loopEventListener(
            gadget.props.element.querySelector(".form-use-jio-dav"),
            'submit',
            false,
            function (event) {createDAVJio(gadget, event)}
          ));
          // promise to use local storage for jIO
          promise_list.push(loopEventListener(
            gadget.props.element.querySelector(".form-use-jio-local"),
            'submit',
            false,
            function (event) {createJio(gadget, {type: "indexeddb", database: "cribjs"})}
          ));
          return RSVP.all(promise_list);
        })
        .push(undefined, function(e) {
          console.log(e);
          throw e;
        });
    })
    .declareService(function () {
      var gadget = this;
      return new RSVP.Queue()
        .push(function () {
          return gadget.props.start_deferred.promise;
        })
        .push(function () {
          return listenHashChange(gadget);
        })
        .push(undefined, function(e) {
          console.log(e);
          throw e;
        });
    });

}(window, document, RSVP, rJS, location, console));