html5.js 8.9 KB
Newer Older
1
/*jslint indent: 2, nomen: true, sloppy: true */
2
/*global setTimeout, window, navigator */
3

4 5 6 7 8 9 10 11 12 13 14 15 16
(function () {
  ////////////////////////////////////////////////////////////
  // https://github.com/TristanCavelier/notesntools/blob/\
  // master/javascript/stringToUtf8Bytes.js
  /**
   * Converts a string into a Utf8 raw string (0 <= char <= 255)
   *
   * @param  {String} input String to convert
   * @return {String} Utf8 byte string
   */
  function stringToUtf8ByteString(input) {
    /*jslint bitwise: true */
    var output = "", i, x, y, l = input.length;
17

18 19 20 21 22 23 24 25
    for (i = 0; i < l; i += 1) {
      /* Decode utf-16 surrogate pairs */
      x = input.charCodeAt(i);
      y = i + 1 < l ? input.charCodeAt(i + 1) : 0;
      if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) {
        x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
        i += 1;
      }
26

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
      /* Encode output as utf-8 */
      if (x <= 0x7F) {
        output += String.fromCharCode(x);
      } else if (x <= 0x7FF) {
        output += String.fromCharCode(
          0xC0 | ((x >>> 6) & 0x1F),
          0x80 | (x & 0x3F)
        );
      } else if (x <= 0xFFFF) {
        output += String.fromCharCode(
          0xE0 | ((x >>> 12) & 0x0F),
          0x80 | ((x >>> 6) & 0x3F),
          0x80 | (x & 0x3F)
        );
      } else if (x <= 0x1FFFFF) {
        output += String.fromCharCode(
          0xF0 | ((x >>> 18) & 0x07),
          0x80 | ((x >>> 12) & 0x3F),
          0x80 | ((x >>> 6) & 0x3F),
          0x80 | (x & 0x3F)
        );
      }
49
    }
50
    return output;
51 52
  }

53 54 55 56 57 58 59 60 61
  /**
   * Converts a Utf8 raw string (0 <= char <= 255) into a real string
   *
   * @param  {String} input Utf8 encoded Bytes to convert
   * @return {String} Real string
   */
  function utf8ByteStringToString(input) {
    /*jslint bitwise: true */
    var output = "", i, x, l = input.length;
62

63 64 65 66 67 68 69 70 71 72 73 74 75 76
    for (i = 0; i < l; i += 1) {
      x = input.charCodeAt(i);
      if ((x & 0xF0) === 0xF0) {
        i += 1;
        x = ((x & 0x07) << 18) | (
          i < l ? (input.charCodeAt(i) & 0x3F) << 12 : 0
        );
        i += 1;
        x = x | (
          i < l ? (input.charCodeAt(i) & 0x3F) << 6 : 0
        );
        i += 1;
        x = x | (
          i < l ? input.charCodeAt(i) & 0x3F : 0
77
        );
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
        if (0x10000 <= x && x <= 0x10FFFF) {
          output += String.fromCharCode(
            (((x - 0x10000) >>> 10) & 0x03FF) | 0xD800,
            (x & 0x03FF) | 0xDC00
          );
        } else {
          output += String.fromCharCode(x);
        }
      } else if ((x & 0xE0) === 0xE0) {
        i += 1;
        x = ((x & 0x0F) << 12) | (
          i < l ? (input.charCodeAt(i) & 0x3F) << 6 : 0
        );
        i += 1;
        output += String.fromCharCode(x | (
          i < l ? input.charCodeAt(i) & 0x3F : 0
        ));
      } else if ((x & 0xC0) === 0xC0) {
        i += 1;
        output += String.fromCharCode(((x & 0x1F) << 6) | (
          i < l ? input.charCodeAt(i) & 0x3F : 0
        ));
100 101 102 103
      } else {
        output += String.fromCharCode(x);
      }
    }
104
    return output;
105 106
  }

107
  ////////////////////////////////////////////////////////////
108

109 110 111 112 113
  function Blob(parts, properties) {
    var i, part, raw = '', type;
    type = (properties && properties.type && properties.type.toString()) || "";
    if (!Array.isArray(parts)) {
      throw new TypeError("The method parameter is missing or invalid.");
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
    if (properties !== undefined &&
        (typeof properties !== 'object' ||
         Object.getPrototypeOf(properties || []) !== Object.prototype)) {
      throw new TypeError("Value can't be converted to a dictionnary.");
    }
    for (i = 0; i < parts.length; i += 1) {
      part = parts[i];
      if (part instanceof Blob) {
        raw += part._data;
      } else if (part) {
        raw += stringToUtf8ByteString(part.toString());
      } else if (part === undefined) {
        raw += "undefined";
      }
    }
    Object.defineProperty(this, "_data", {
      "configurable": true,
      "enumerable": false,
      "writable": true,
      "value": raw
    });
    Object.defineProperty(this, "size", {
      "configurable": false,
      "enumerable": true,
      "writable": false,
      "value": raw.length
    });
    Object.defineProperty(this, "type", {
      "configurable": false,
      "enumerable": true,
      "writable": false,
      "value": type
    });
148
  }
149 150 151 152 153 154 155 156 157 158 159 160
  Blob.prototype.type = "";
  Blob.prototype.size = 0;
  Blob.prototype.slice = function (start, end, contentType) {
    var data, blob, i, fake_data = '';
    data = this._data.slice(start, end);
    for (i = 0; i < data.length; i += 1) {
      fake_data += 'a';
    }
    blob = new Blob([fake_data], {"type": contentType});
    blob._data = data;
    return blob;
  };
161

162 163 164 165
  ////////////////////////////////////////////////////////////
  // https://github.com/TristanCavelier/notesntools/blob/\
  // master/javascript/emitter.js
  function FileReader() {
166 167 168
    return;
  }

169 170 171 172 173
  FileReader.prototype.addEventListener = function (eventName, callback) {
    // Check parameters
    if (typeof callback !== "function") {
      return;
    }
174

175 176 177 178 179
    // assign callback to event
    this._events = this._events || {};
    this._events[eventName] = this._events[eventName] || [];
    this._events[eventName].push(callback);
  };
180

181 182 183
  function dispatchEvent(fr, eventName) {
    var args, i, funs = fr._events && fr._events[eventName] &&
      fr._events[eventName].slice();
184 185

    // for html5 EventTarget compatibility
186 187 188 189
    if (fr.hasOwnProperty('on' + eventName) &&
        typeof fr['on' + eventName] === "function") {
      funs = funs || [];
      funs.before = fr['on' + eventName];
190 191
    }

192 193 194 195 196 197 198 199 200 201 202 203 204
    if (funs) {
      args = [].slice.call(arguments, 2);

      // for html5 EventTarget compatibility
      if (funs.before) {
        // no try catch wraps listeners on EventTarget API
        funs.before.apply(fr, args);
      }

      // call funs
      for (i = 0; i < funs.length; i += 1) {
        funs[i].apply(fr, args);
      }
205 206 207
    }
  }

208 209
  FileReader.prototype.removeEventListener = function (eventName, callback) {
    var i, funs = this._events && this._events[eventName];
210

211 212 213 214 215 216
    if (funs) {
      for (i = 0; i < funs.length; i += 1) {
        if (funs[i] === callback) {
          funs.splice(i, 1);
          break;
        }
217 218
      }
    }
219
  };
220

221 222 223 224
  FileReader.prototype.abort = function () {
    this.dispatchEvent("abort", {"target": this});
    delete this._events;
  };
225

226 227 228 229 230 231 232 233 234 235 236 237 238 239
  FileReader.prototype.readAsBinaryString = function (blob) {
    var that = this;
    setTimeout(function () {
      dispatchEvent(that, "progress", {
        "loaded": blob.size,
        "total": blob.size,
        "target": that
      });
      that.result = blob._data;
      dispatchEvent(that, "load", {
        "loaded": blob.size,
        "total": blob.size,
        "target": that
      });
240
    });
241
  };
242

243 244 245 246 247 248 249 250 251 252 253 254 255 256
  FileReader.prototype.readAsText = function (blob) {
    var that = this;
    setTimeout(function () {
      dispatchEvent(that, "progress", {
        "loaded": blob.size,
        "total": blob.size,
        "target": that
      });
      that.result = utf8ByteStringToString(blob._data);
      dispatchEvent(that, "load", {
        "loaded": blob.size,
        "total": blob.size,
        "target": that
      });
257
    });
258 259 260 261 262 263 264 265
  };

  ////////////////////////////////////////////////////////////

  if (typeof Blob !== 'function' || typeof FileReader !== 'function' ||
      (/\bPhantomJS\b/i).test(navigator.userAgent)) {
    window.Blob = Blob;
    window.FileReader = FileReader;
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
    //console.warn("Blob and FileReader have been replaced!");
  }

  if (!Function.prototype.bind) {
    //////////////////////////////////////////////////////////////////////
    // https://github.com/TristanCavelier/notesntools/blob/master/javascript/\
    // bind.js
    /**
     * Creates a new function that, when called, has its `this` keyword set to
     * the provided value, with a given sequence of arguments preceding any
     * provided when the new function is called. See Mozilla Developer Network:
     * Function.prototype.bind
     *
     * In PhantomJS, their is a bug with `Function.prototype.bind`. You can
     * reproduce this bug by testing this code:
     *
     *     function a(str) { console.log(this, str); }
     *     var b = a.bind({"a": "b"}, "test");
     *     b();
     *
     * @param {Object} thisArg The value to be passed as the `this` parameter to
     *   the target function when the bound function is called. The value is
     *   ignored if the bound function is constructed using the `new` operator.
     *
     * @param {Any} [arg]* Arguments to prepend to arguments provided to the
     *   bound function when invoking the target function.
     *
     * @return {Function} The bound function.
     */
    Function.prototype.bind = function (thisArg) {
      var fun = this, args = [].slice.call(arguments, 1);
      return function () {
        args.push.apply(args, arguments);
        return fun.apply(thisArg, args);
      };
    };
    //console.warn("Function.prototype.bind has been replaced!");
303
  }
304

305
}());