You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4518 lines
151 KiB

  1. /*
  2. html2canvas 0.5.0-alpha2 <http://html2canvas.hertzen.com>
  3. Copyright (c) 2015 Niklas von Hertzen
  4. Released under MIT License
  5. */
  6. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.html2canvas=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  7. (function (process,global){
  8. /*!
  9. * @overview es6-promise - a tiny implementation of Promises/A+.
  10. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  11. * @license Licensed under MIT license
  12. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  13. * @version 2.0.1
  14. */
  15. (function() {
  16. "use strict";
  17. function $$utils$$objectOrFunction(x) {
  18. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  19. }
  20. function $$utils$$isFunction(x) {
  21. return typeof x === 'function';
  22. }
  23. function $$utils$$isMaybeThenable(x) {
  24. return typeof x === 'object' && x !== null;
  25. }
  26. var $$utils$$_isArray;
  27. if (!Array.isArray) {
  28. $$utils$$_isArray = function (x) {
  29. return Object.prototype.toString.call(x) === '[object Array]';
  30. };
  31. } else {
  32. $$utils$$_isArray = Array.isArray;
  33. }
  34. var $$utils$$isArray = $$utils$$_isArray;
  35. var $$utils$$now = Date.now || function() { return new Date().getTime(); };
  36. function $$utils$$F() { }
  37. var $$utils$$o_create = (Object.create || function (o) {
  38. if (arguments.length > 1) {
  39. throw new Error('Second argument not supported');
  40. }
  41. if (typeof o !== 'object') {
  42. throw new TypeError('Argument must be an object');
  43. }
  44. $$utils$$F.prototype = o;
  45. return new $$utils$$F();
  46. });
  47. var $$asap$$len = 0;
  48. var $$asap$$default = function asap(callback, arg) {
  49. $$asap$$queue[$$asap$$len] = callback;
  50. $$asap$$queue[$$asap$$len + 1] = arg;
  51. $$asap$$len += 2;
  52. if ($$asap$$len === 2) {
  53. // If len is 1, that means that we need to schedule an async flush.
  54. // If additional callbacks are queued before the queue is flushed, they
  55. // will be processed by this flush that we are scheduling.
  56. $$asap$$scheduleFlush();
  57. }
  58. };
  59. var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {};
  60. var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver;
  61. // test for web worker but not in IE10
  62. var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  63. typeof importScripts !== 'undefined' &&
  64. typeof MessageChannel !== 'undefined';
  65. // node
  66. function $$asap$$useNextTick() {
  67. return function() {
  68. process.nextTick($$asap$$flush);
  69. };
  70. }
  71. function $$asap$$useMutationObserver() {
  72. var iterations = 0;
  73. var observer = new $$asap$$BrowserMutationObserver($$asap$$flush);
  74. var node = document.createTextNode('');
  75. observer.observe(node, { characterData: true });
  76. return function() {
  77. node.data = (iterations = ++iterations % 2);
  78. };
  79. }
  80. // web worker
  81. function $$asap$$useMessageChannel() {
  82. var channel = new MessageChannel();
  83. channel.port1.onmessage = $$asap$$flush;
  84. return function () {
  85. channel.port2.postMessage(0);
  86. };
  87. }
  88. function $$asap$$useSetTimeout() {
  89. return function() {
  90. setTimeout($$asap$$flush, 1);
  91. };
  92. }
  93. var $$asap$$queue = new Array(1000);
  94. function $$asap$$flush() {
  95. for (var i = 0; i < $$asap$$len; i+=2) {
  96. var callback = $$asap$$queue[i];
  97. var arg = $$asap$$queue[i+1];
  98. callback(arg);
  99. $$asap$$queue[i] = undefined;
  100. $$asap$$queue[i+1] = undefined;
  101. }
  102. $$asap$$len = 0;
  103. }
  104. var $$asap$$scheduleFlush;
  105. // Decide what async method to use to triggering processing of queued callbacks:
  106. if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
  107. $$asap$$scheduleFlush = $$asap$$useNextTick();
  108. } else if ($$asap$$BrowserMutationObserver) {
  109. $$asap$$scheduleFlush = $$asap$$useMutationObserver();
  110. } else if ($$asap$$isWorker) {
  111. $$asap$$scheduleFlush = $$asap$$useMessageChannel();
  112. } else {
  113. $$asap$$scheduleFlush = $$asap$$useSetTimeout();
  114. }
  115. function $$$internal$$noop() {}
  116. var $$$internal$$PENDING = void 0;
  117. var $$$internal$$FULFILLED = 1;
  118. var $$$internal$$REJECTED = 2;
  119. var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject();
  120. function $$$internal$$selfFullfillment() {
  121. return new TypeError("You cannot resolve a promise with itself");
  122. }
  123. function $$$internal$$cannotReturnOwn() {
  124. return new TypeError('A promises callback cannot return that same promise.')
  125. }
  126. function $$$internal$$getThen(promise) {
  127. try {
  128. return promise.then;
  129. } catch(error) {
  130. $$$internal$$GET_THEN_ERROR.error = error;
  131. return $$$internal$$GET_THEN_ERROR;
  132. }
  133. }
  134. function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  135. try {
  136. then.call(value, fulfillmentHandler, rejectionHandler);
  137. } catch(e) {
  138. return e;
  139. }
  140. }
  141. function $$$internal$$handleForeignThenable(promise, thenable, then) {
  142. $$asap$$default(function(promise) {
  143. var sealed = false;
  144. var error = $$$internal$$tryThen(then, thenable, function(value) {
  145. if (sealed) { return; }
  146. sealed = true;
  147. if (thenable !== value) {
  148. $$$internal$$resolve(promise, value);
  149. } else {
  150. $$$internal$$fulfill(promise, value);
  151. }
  152. }, function(reason) {
  153. if (sealed) { return; }
  154. sealed = true;
  155. $$$internal$$reject(promise, reason);
  156. }, 'Settle: ' + (promise._label || ' unknown promise'));
  157. if (!sealed && error) {
  158. sealed = true;
  159. $$$internal$$reject(promise, error);
  160. }
  161. }, promise);
  162. }
  163. function $$$internal$$handleOwnThenable(promise, thenable) {
  164. if (thenable._state === $$$internal$$FULFILLED) {
  165. $$$internal$$fulfill(promise, thenable._result);
  166. } else if (promise._state === $$$internal$$REJECTED) {
  167. $$$internal$$reject(promise, thenable._result);
  168. } else {
  169. $$$internal$$subscribe(thenable, undefined, function(value) {
  170. $$$internal$$resolve(promise, value);
  171. }, function(reason) {
  172. $$$internal$$reject(promise, reason);
  173. });
  174. }
  175. }
  176. function $$$internal$$handleMaybeThenable(promise, maybeThenable) {
  177. if (maybeThenable.constructor === promise.constructor) {
  178. $$$internal$$handleOwnThenable(promise, maybeThenable);
  179. } else {
  180. var then = $$$internal$$getThen(maybeThenable);
  181. if (then === $$$internal$$GET_THEN_ERROR) {
  182. $$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error);
  183. } else if (then === undefined) {
  184. $$$internal$$fulfill(promise, maybeThenable);
  185. } else if ($$utils$$isFunction(then)) {
  186. $$$internal$$handleForeignThenable(promise, maybeThenable, then);
  187. } else {
  188. $$$internal$$fulfill(promise, maybeThenable);
  189. }
  190. }
  191. }
  192. function $$$internal$$resolve(promise, value) {
  193. if (promise === value) {
  194. $$$internal$$reject(promise, $$$internal$$selfFullfillment());
  195. } else if ($$utils$$objectOrFunction(value)) {
  196. $$$internal$$handleMaybeThenable(promise, value);
  197. } else {
  198. $$$internal$$fulfill(promise, value);
  199. }
  200. }
  201. function $$$internal$$publishRejection(promise) {
  202. if (promise._onerror) {
  203. promise._onerror(promise._result);
  204. }
  205. $$$internal$$publish(promise);
  206. }
  207. function $$$internal$$fulfill(promise, value) {
  208. if (promise._state !== $$$internal$$PENDING) { return; }
  209. promise._result = value;
  210. promise._state = $$$internal$$FULFILLED;
  211. if (promise._subscribers.length === 0) {
  212. } else {
  213. $$asap$$default($$$internal$$publish, promise);
  214. }
  215. }
  216. function $$$internal$$reject(promise, reason) {
  217. if (promise._state !== $$$internal$$PENDING) { return; }
  218. promise._state = $$$internal$$REJECTED;
  219. promise._result = reason;
  220. $$asap$$default($$$internal$$publishRejection, promise);
  221. }
  222. function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  223. var subscribers = parent._subscribers;
  224. var length = subscribers.length;
  225. parent._onerror = null;
  226. subscribers[length] = child;
  227. subscribers[length + $$$internal$$FULFILLED] = onFulfillment;
  228. subscribers[length + $$$internal$$REJECTED] = onRejection;
  229. if (length === 0 && parent._state) {
  230. $$asap$$default($$$internal$$publish, parent);
  231. }
  232. }
  233. function $$$internal$$publish(promise) {
  234. var subscribers = promise._subscribers;
  235. var settled = promise._state;
  236. if (subscribers.length === 0) { return; }
  237. var child, callback, detail = promise._result;
  238. for (var i = 0; i < subscribers.length; i += 3) {
  239. child = subscribers[i];
  240. callback = subscribers[i + settled];
  241. if (child) {
  242. $$$internal$$invokeCallback(settled, child, callback, detail);
  243. } else {
  244. callback(detail);
  245. }
  246. }
  247. promise._subscribers.length = 0;
  248. }
  249. function $$$internal$$ErrorObject() {
  250. this.error = null;
  251. }
  252. var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject();
  253. function $$$internal$$tryCatch(callback, detail) {
  254. try {
  255. return callback(detail);
  256. } catch(e) {
  257. $$$internal$$TRY_CATCH_ERROR.error = e;
  258. return $$$internal$$TRY_CATCH_ERROR;
  259. }
  260. }
  261. function $$$internal$$invokeCallback(settled, promise, callback, detail) {
  262. var hasCallback = $$utils$$isFunction(callback),
  263. value, error, succeeded, failed;
  264. if (hasCallback) {
  265. value = $$$internal$$tryCatch(callback, detail);
  266. if (value === $$$internal$$TRY_CATCH_ERROR) {
  267. failed = true;
  268. error = value.error;
  269. value = null;
  270. } else {
  271. succeeded = true;
  272. }
  273. if (promise === value) {
  274. $$$internal$$reject(promise, $$$internal$$cannotReturnOwn());
  275. return;
  276. }
  277. } else {
  278. value = detail;
  279. succeeded = true;
  280. }
  281. if (promise._state !== $$$internal$$PENDING) {
  282. // noop
  283. } else if (hasCallback && succeeded) {
  284. $$$internal$$resolve(promise, value);
  285. } else if (failed) {
  286. $$$internal$$reject(promise, error);
  287. } else if (settled === $$$internal$$FULFILLED) {
  288. $$$internal$$fulfill(promise, value);
  289. } else if (settled === $$$internal$$REJECTED) {
  290. $$$internal$$reject(promise, value);
  291. }
  292. }
  293. function $$$internal$$initializePromise(promise, resolver) {
  294. try {
  295. resolver(function resolvePromise(value){
  296. $$$internal$$resolve(promise, value);
  297. }, function rejectPromise(reason) {
  298. $$$internal$$reject(promise, reason);
  299. });
  300. } catch(e) {
  301. $$$internal$$reject(promise, e);
  302. }
  303. }
  304. function $$$enumerator$$makeSettledResult(state, position, value) {
  305. if (state === $$$internal$$FULFILLED) {
  306. return {
  307. state: 'fulfilled',
  308. value: value
  309. };
  310. } else {
  311. return {
  312. state: 'rejected',
  313. reason: value
  314. };
  315. }
  316. }
  317. function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) {
  318. this._instanceConstructor = Constructor;
  319. this.promise = new Constructor($$$internal$$noop, label);
  320. this._abortOnReject = abortOnReject;
  321. if (this._validateInput(input)) {
  322. this._input = input;
  323. this.length = input.length;
  324. this._remaining = input.length;
  325. this._init();
  326. if (this.length === 0) {
  327. $$$internal$$fulfill(this.promise, this._result);
  328. } else {
  329. this.length = this.length || 0;
  330. this._enumerate();
  331. if (this._remaining === 0) {
  332. $$$internal$$fulfill(this.promise, this._result);
  333. }
  334. }
  335. } else {
  336. $$$internal$$reject(this.promise, this._validationError());
  337. }
  338. }
  339. $$$enumerator$$Enumerator.prototype._validateInput = function(input) {
  340. return $$utils$$isArray(input);
  341. };
  342. $$$enumerator$$Enumerator.prototype._validationError = function() {
  343. return new Error('Array Methods must be provided an Array');
  344. };
  345. $$$enumerator$$Enumerator.prototype._init = function() {
  346. this._result = new Array(this.length);
  347. };
  348. var $$$enumerator$$default = $$$enumerator$$Enumerator;
  349. $$$enumerator$$Enumerator.prototype._enumerate = function() {
  350. var length = this.length;
  351. var promise = this.promise;
  352. var input = this._input;
  353. for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) {
  354. this._eachEntry(input[i], i);
  355. }
  356. };
  357. $$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  358. var c = this._instanceConstructor;
  359. if ($$utils$$isMaybeThenable(entry)) {
  360. if (entry.constructor === c && entry._state !== $$$internal$$PENDING) {
  361. entry._onerror = null;
  362. this._settledAt(entry._state, i, entry._result);
  363. } else {
  364. this._willSettleAt(c.resolve(entry), i);
  365. }
  366. } else {
  367. this._remaining--;
  368. this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry);
  369. }
  370. };
  371. $$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  372. var promise = this.promise;
  373. if (promise._state === $$$internal$$PENDING) {
  374. this._remaining--;
  375. if (this._abortOnReject && state === $$$internal$$REJECTED) {
  376. $$$internal$$reject(promise, value);
  377. } else {
  378. this._result[i] = this._makeResult(state, i, value);
  379. }
  380. }
  381. if (this._remaining === 0) {
  382. $$$internal$$fulfill(promise, this._result);
  383. }
  384. };
  385. $$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) {
  386. return value;
  387. };
  388. $$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  389. var enumerator = this;
  390. $$$internal$$subscribe(promise, undefined, function(value) {
  391. enumerator._settledAt($$$internal$$FULFILLED, i, value);
  392. }, function(reason) {
  393. enumerator._settledAt($$$internal$$REJECTED, i, reason);
  394. });
  395. };
  396. var $$promise$all$$default = function all(entries, label) {
  397. return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise;
  398. };
  399. var $$promise$race$$default = function race(entries, label) {
  400. /*jshint validthis:true */
  401. var Constructor = this;
  402. var promise = new Constructor($$$internal$$noop, label);
  403. if (!$$utils$$isArray(entries)) {
  404. $$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  405. return promise;
  406. }
  407. var length = entries.length;
  408. function onFulfillment(value) {
  409. $$$internal$$resolve(promise, value);
  410. }
  411. function onRejection(reason) {
  412. $$$internal$$reject(promise, reason);
  413. }
  414. for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) {
  415. $$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  416. }
  417. return promise;
  418. };
  419. var $$promise$resolve$$default = function resolve(object, label) {
  420. /*jshint validthis:true */
  421. var Constructor = this;
  422. if (object && typeof object === 'object' && object.constructor === Constructor) {
  423. return object;
  424. }
  425. var promise = new Constructor($$$internal$$noop, label);
  426. $$$internal$$resolve(promise, object);
  427. return promise;
  428. };
  429. var $$promise$reject$$default = function reject(reason, label) {
  430. /*jshint validthis:true */
  431. var Constructor = this;
  432. var promise = new Constructor($$$internal$$noop, label);
  433. $$$internal$$reject(promise, reason);
  434. return promise;
  435. };
  436. var $$es6$promise$promise$$counter = 0;
  437. function $$es6$promise$promise$$needsResolver() {
  438. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  439. }
  440. function $$es6$promise$promise$$needsNew() {
  441. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  442. }
  443. var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise;
  444. /**
  445. Promise objects represent the eventual result of an asynchronous operation. The
  446. primary way of interacting with a promise is through its `then` method, which
  447. registers callbacks to receive either a promises eventual value or the reason
  448. why the promise cannot be fulfilled.
  449. Terminology
  450. -----------
  451. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  452. - `thenable` is an object or function that defines a `then` method.
  453. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  454. - `exception` is a value that is thrown using the throw statement.
  455. - `reason` is a value that indicates why a promise was rejected.
  456. - `settled` the final resting state of a promise, fulfilled or rejected.
  457. A promise can be in one of three states: pending, fulfilled, or rejected.
  458. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  459. state. Promises that are rejected have a rejection reason and are in the
  460. rejected state. A fulfillment value is never a thenable.
  461. Promises can also be said to *resolve* a value. If this value is also a
  462. promise, then the original promise's settled state will match the value's
  463. settled state. So a promise that *resolves* a promise that rejects will
  464. itself reject, and a promise that *resolves* a promise that fulfills will
  465. itself fulfill.
  466. Basic Usage:
  467. ------------
  468. ```js
  469. var promise = new Promise(function(resolve, reject) {
  470. // on success
  471. resolve(value);
  472. // on failure
  473. reject(reason);
  474. });
  475. promise.then(function(value) {
  476. // on fulfillment
  477. }, function(reason) {
  478. // on rejection
  479. });
  480. ```
  481. Advanced Usage:
  482. ---------------
  483. Promises shine when abstracting away asynchronous interactions such as
  484. `XMLHttpRequest`s.
  485. ```js
  486. function getJSON(url) {
  487. return new Promise(function(resolve, reject){
  488. var xhr = new XMLHttpRequest();
  489. xhr.open('GET', url);
  490. xhr.onreadystatechange = handler;
  491. xhr.responseType = 'json';
  492. xhr.setRequestHeader('Accept', 'application/json');
  493. xhr.send();
  494. function handler() {
  495. if (this.readyState === this.DONE) {
  496. if (this.status === 200) {
  497. resolve(this.response);
  498. } else {
  499. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  500. }
  501. }
  502. };
  503. });
  504. }
  505. getJSON('/posts.json').then(function(json) {
  506. // on fulfillment
  507. }, function(reason) {
  508. // on rejection
  509. });
  510. ```
  511. Unlike callbacks, promises are great composable primitives.
  512. ```js
  513. Promise.all([
  514. getJSON('/posts'),
  515. getJSON('/comments')
  516. ]).then(function(values){
  517. values[0] // => postsJSON
  518. values[1] // => commentsJSON
  519. return values;
  520. });
  521. ```
  522. @class Promise
  523. @param {function} resolver
  524. Useful for tooling.
  525. @constructor
  526. */
  527. function $$es6$promise$promise$$Promise(resolver) {
  528. this._id = $$es6$promise$promise$$counter++;
  529. this._state = undefined;
  530. this._result = undefined;
  531. this._subscribers = [];
  532. if ($$$internal$$noop !== resolver) {
  533. if (!$$utils$$isFunction(resolver)) {
  534. $$es6$promise$promise$$needsResolver();
  535. }
  536. if (!(this instanceof $$es6$promise$promise$$Promise)) {
  537. $$es6$promise$promise$$needsNew();
  538. }
  539. $$$internal$$initializePromise(this, resolver);
  540. }
  541. }
  542. $$es6$promise$promise$$Promise.all = $$promise$all$$default;
  543. $$es6$promise$promise$$Promise.race = $$promise$race$$default;
  544. $$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default;
  545. $$es6$promise$promise$$Promise.reject = $$promise$reject$$default;
  546. $$es6$promise$promise$$Promise.prototype = {
  547. constructor: $$es6$promise$promise$$Promise,
  548. /**
  549. The primary way of interacting with a promise is through its `then` method,
  550. which registers callbacks to receive either a promise's eventual value or the
  551. reason why the promise cannot be fulfilled.
  552. ```js
  553. findUser().then(function(user){
  554. // user is available
  555. }, function(reason){
  556. // user is unavailable, and you are given the reason why
  557. });
  558. ```
  559. Chaining
  560. --------
  561. The return value of `then` is itself a promise. This second, 'downstream'
  562. promise is resolved with the return value of the first promise's fulfillment
  563. or rejection handler, or rejected if the handler throws an exception.
  564. ```js
  565. findUser().then(function (user) {
  566. return user.name;
  567. }, function (reason) {
  568. return 'default name';
  569. }).then(function (userName) {
  570. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  571. // will be `'default name'`
  572. });
  573. findUser().then(function (user) {
  574. throw new Error('Found user, but still unhappy');
  575. }, function (reason) {
  576. throw new Error('`findUser` rejected and we're unhappy');
  577. }).then(function (value) {
  578. // never reached
  579. }, function (reason) {
  580. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  581. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  582. });
  583. ```
  584. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  585. ```js
  586. findUser().then(function (user) {
  587. throw new PedagogicalException('Upstream error');
  588. }).then(function (value) {
  589. // never reached
  590. }).then(function (value) {
  591. // never reached
  592. }, function (reason) {
  593. // The `PedgagocialException` is propagated all the way down to here
  594. });
  595. ```
  596. Assimilation
  597. ------------
  598. Sometimes the value you want to propagate to a downstream promise can only be
  599. retrieved asynchronously. This can be achieved by returning a promise in the
  600. fulfillment or rejection handler. The downstream promise will then be pending
  601. until the returned promise is settled. This is called *assimilation*.
  602. ```js
  603. findUser().then(function (user) {
  604. return findCommentsByAuthor(user);
  605. }).then(function (comments) {
  606. // The user's comments are now available
  607. });
  608. ```
  609. If the assimliated promise rejects, then the downstream promise will also reject.
  610. ```js
  611. findUser().then(function (user) {
  612. return findCommentsByAuthor(user);
  613. }).then(function (comments) {
  614. // If `findCommentsByAuthor` fulfills, we'll have the value here
  615. }, function (reason) {
  616. // If `findCommentsByAuthor` rejects, we'll have the reason here
  617. });
  618. ```
  619. Simple Example
  620. --------------
  621. Synchronous Example
  622. ```javascript
  623. var result;
  624. try {
  625. result = findResult();
  626. // success
  627. } catch(reason) {
  628. // failure
  629. }
  630. ```
  631. Errback Example
  632. ```js
  633. findResult(function(result, err){
  634. if (err) {
  635. // failure
  636. } else {
  637. // success
  638. }
  639. });
  640. ```
  641. Promise Example;
  642. ```javascript
  643. findResult().then(function(result){
  644. // success
  645. }, function(reason){
  646. // failure
  647. });
  648. ```
  649. Advanced Example
  650. --------------
  651. Synchronous Example
  652. ```javascript
  653. var author, books;
  654. try {
  655. author = findAuthor();
  656. books = findBooksByAuthor(author);
  657. // success
  658. } catch(reason) {
  659. // failure
  660. }
  661. ```
  662. Errback Example
  663. ```js
  664. function foundBooks(books) {
  665. }
  666. function failure(reason) {
  667. }
  668. findAuthor(function(author, err){
  669. if (err) {
  670. failure(err);
  671. // failure
  672. } else {
  673. try {
  674. findBoooksByAuthor(author, function(books, err) {
  675. if (err) {
  676. failure(err);
  677. } else {
  678. try {
  679. foundBooks(books);
  680. } catch(reason) {
  681. failure(reason);
  682. }
  683. }
  684. });
  685. } catch(error) {
  686. failure(err);
  687. }
  688. // success
  689. }
  690. });
  691. ```
  692. Promise Example;
  693. ```javascript
  694. findAuthor().
  695. then(findBooksByAuthor).
  696. then(function(books){
  697. // found books
  698. }).catch(function(reason){
  699. // something went wrong
  700. });
  701. ```
  702. @method then
  703. @param {Function} onFulfilled
  704. @param {Function} onRejected
  705. Useful for tooling.
  706. @return {Promise}
  707. */
  708. then: function(onFulfillment, onRejection) {
  709. var parent = this;
  710. var state = parent._state;
  711. if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) {
  712. return this;
  713. }
  714. var child = new this.constructor($$$internal$$noop);
  715. var result = parent._result;
  716. if (state) {
  717. var callback = arguments[state - 1];
  718. $$asap$$default(function(){
  719. $$$internal$$invokeCallback(state, child, callback, result);
  720. });
  721. } else {
  722. $$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  723. }
  724. return child;
  725. },
  726. /**
  727. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  728. as the catch block of a try/catch statement.
  729. ```js
  730. function findAuthor(){
  731. throw new Error('couldn't find that author');
  732. }
  733. // synchronous
  734. try {
  735. findAuthor();
  736. } catch(reason) {
  737. // something went wrong
  738. }
  739. // async with promises
  740. findAuthor().catch(function(reason){
  741. // something went wrong
  742. });
  743. ```
  744. @method catch
  745. @param {Function} onRejection
  746. Useful for tooling.
  747. @return {Promise}
  748. */
  749. 'catch': function(onRejection) {
  750. return this.then(null, onRejection);
  751. }
  752. };
  753. var $$es6$promise$polyfill$$default = function polyfill() {
  754. var local;
  755. if (typeof global !== 'undefined') {
  756. local = global;
  757. } else if (typeof window !== 'undefined' && window.document) {
  758. local = window;
  759. } else {
  760. local = self;
  761. }
  762. var es6PromiseSupport =
  763. "Promise" in local &&
  764. // Some of these methods are missing from
  765. // Firefox/Chrome experimental implementations
  766. "resolve" in local.Promise &&
  767. "reject" in local.Promise &&
  768. "all" in local.Promise &&
  769. "race" in local.Promise &&
  770. // Older version of the spec had a resolver object
  771. // as the arg rather than a function
  772. (function() {
  773. var resolve;
  774. new local.Promise(function(r) { resolve = r; });
  775. return $$utils$$isFunction(resolve);
  776. }());
  777. if (!es6PromiseSupport) {
  778. local.Promise = $$es6$promise$promise$$default;
  779. }
  780. };
  781. var es6$promise$umd$$ES6Promise = {
  782. 'Promise': $$es6$promise$promise$$default,
  783. 'polyfill': $$es6$promise$polyfill$$default
  784. };
  785. /* global define:true module:true window: true */
  786. if (typeof define === 'function' && define['amd']) {
  787. define(function() { return es6$promise$umd$$ES6Promise; });
  788. } else if (typeof module !== 'undefined' && module['exports']) {
  789. module['exports'] = es6$promise$umd$$ES6Promise;
  790. } else if (typeof this !== 'undefined') {
  791. this['ES6Promise'] = es6$promise$umd$$ES6Promise;
  792. }
  793. }).call(this);
  794. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  795. },{"_process":2}],2:[function(require,module,exports){
  796. // shim for using process in browser
  797. var process = module.exports = {};
  798. var queue = [];
  799. var draining = false;
  800. function drainQueue() {
  801. if (draining) {
  802. return;
  803. }
  804. draining = true;
  805. var currentQueue;
  806. var len = queue.length;
  807. while(len) {
  808. currentQueue = queue;
  809. queue = [];
  810. var i = -1;
  811. while (++i < len) {
  812. currentQueue[i]();
  813. }
  814. len = queue.length;
  815. }
  816. draining = false;
  817. }
  818. process.nextTick = function (fun) {
  819. queue.push(fun);
  820. if (!draining) {
  821. setTimeout(drainQueue, 0);
  822. }
  823. };
  824. process.title = 'browser';
  825. process.browser = true;
  826. process.env = {};
  827. process.argv = [];
  828. process.version = ''; // empty string to avoid regexp issues
  829. function noop() {}
  830. process.on = noop;
  831. process.addListener = noop;
  832. process.once = noop;
  833. process.off = noop;
  834. process.removeListener = noop;
  835. process.removeAllListeners = noop;
  836. process.emit = noop;
  837. process.binding = function (name) {
  838. throw new Error('process.binding is not supported');
  839. };
  840. // TODO(shtylman)
  841. process.cwd = function () { return '/' };
  842. process.chdir = function (dir) {
  843. throw new Error('process.chdir is not supported');
  844. };
  845. process.umask = function() { return 0; };
  846. },{}],3:[function(require,module,exports){
  847. (function (global){
  848. /*! http://mths.be/punycode v1.2.4 by @mathias */
  849. ;(function(root) {
  850. /** Detect free variables */
  851. var freeExports = typeof exports == 'object' && exports;
  852. var freeModule = typeof module == 'object' && module &&
  853. module.exports == freeExports && module;
  854. var freeGlobal = typeof global == 'object' && global;
  855. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  856. root = freeGlobal;
  857. }
  858. /**
  859. * The `punycode` object.
  860. * @name punycode
  861. * @type Object
  862. */
  863. var punycode,
  864. /** Highest positive signed 32-bit float value */
  865. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  866. /** Bootstring parameters */
  867. base = 36,
  868. tMin = 1,
  869. tMax = 26,
  870. skew = 38,
  871. damp = 700,
  872. initialBias = 72,
  873. initialN = 128, // 0x80
  874. delimiter = '-', // '\x2D'
  875. /** Regular expressions */
  876. regexPunycode = /^xn--/,
  877. regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
  878. regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
  879. /** Error messages */
  880. errors = {
  881. 'overflow': 'Overflow: input needs wider integers to process',
  882. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  883. 'invalid-input': 'Invalid input'
  884. },
  885. /** Convenience shortcuts */
  886. baseMinusTMin = base - tMin,
  887. floor = Math.floor,
  888. stringFromCharCode = String.fromCharCode,
  889. /** Temporary variable */
  890. key;
  891. /*--------------------------------------------------------------------------*/
  892. /**
  893. * A generic error utility function.
  894. * @private
  895. * @param {String} type The error type.
  896. * @returns {Error} Throws a `RangeError` with the applicable error message.
  897. */
  898. function error(type) {
  899. throw RangeError(errors[type]);
  900. }
  901. /**
  902. * A generic `Array#map` utility function.
  903. * @private
  904. * @param {Array} array The array to iterate over.
  905. * @param {Function} callback The function that gets called for every array
  906. * item.
  907. * @returns {Array} A new array of values returned by the callback function.
  908. */
  909. function map(array, fn) {
  910. var length = array.length;
  911. while (length--) {
  912. array[length] = fn(array[length]);
  913. }
  914. return array;
  915. }
  916. /**
  917. * A simple `Array#map`-like wrapper to work with domain name strings.
  918. * @private
  919. * @param {String} domain The domain name.
  920. * @param {Function} callback The function that gets called for every
  921. * character.
  922. * @returns {Array} A new string of characters returned by the callback
  923. * function.
  924. */
  925. function mapDomain(string, fn) {
  926. return map(string.split(regexSeparators), fn).join('.');
  927. }
  928. /**
  929. * Creates an array containing the numeric code points of each Unicode
  930. * character in the string. While JavaScript uses UCS-2 internally,
  931. * this function will convert a pair of surrogate halves (each of which
  932. * UCS-2 exposes as separate characters) into a single code point,
  933. * matching UTF-16.
  934. * @see `punycode.ucs2.encode`
  935. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  936. * @memberOf punycode.ucs2
  937. * @name decode
  938. * @param {String} string The Unicode input string (UCS-2).
  939. * @returns {Array} The new array of code points.
  940. */
  941. function ucs2decode(string) {
  942. var output = [],
  943. counter = 0,
  944. length = string.length,
  945. value,
  946. extra;
  947. while (counter < length) {
  948. value = string.charCodeAt(counter++);
  949. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  950. // high surrogate, and there is a next character
  951. extra = string.charCodeAt(counter++);
  952. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  953. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  954. } else {
  955. // unmatched surrogate; only append this code unit, in case the next
  956. // code unit is the high surrogate of a surrogate pair
  957. output.push(value);
  958. counter--;
  959. }
  960. } else {
  961. output.push(value);
  962. }
  963. }
  964. return output;
  965. }
  966. /**
  967. * Creates a string based on an array of numeric code points.
  968. * @see `punycode.ucs2.decode`
  969. * @memberOf punycode.ucs2
  970. * @name encode
  971. * @param {Array} codePoints The array of numeric code points.
  972. * @returns {String} The new Unicode string (UCS-2).
  973. */
  974. function ucs2encode(array) {
  975. return map(array, function(value) {
  976. var output = '';
  977. if (value > 0xFFFF) {
  978. value -= 0x10000;
  979. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  980. value = 0xDC00 | value & 0x3FF;
  981. }
  982. output += stringFromCharCode(value);
  983. return output;
  984. }).join('');
  985. }
  986. /**
  987. * Converts a basic code point into a digit/integer.
  988. * @see `digitToBasic()`
  989. * @private
  990. * @param {Number} codePoint The basic numeric code point value.
  991. * @returns {Number} The numeric value of a basic code point (for use in
  992. * representing integers) in the range `0` to `base - 1`, or `base` if
  993. * the code point does not represent a value.
  994. */
  995. function basicToDigit(codePoint) {
  996. if (codePoint - 48 < 10) {
  997. return codePoint - 22;
  998. }
  999. if (codePoint - 65 < 26) {
  1000. return codePoint - 65;
  1001. }
  1002. if (codePoint - 97 < 26) {
  1003. return codePoint - 97;
  1004. }
  1005. return base;
  1006. }
  1007. /**
  1008. * Converts a digit/integer into a basic code point.
  1009. * @see `basicToDigit()`
  1010. * @private
  1011. * @param {Number} digit The numeric value of a basic code point.
  1012. * @returns {Number} The basic code point whose value (when used for
  1013. * representing integers) is `digit`, which needs to be in the range
  1014. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  1015. * used; else, the lowercase form is used. The behavior is undefined
  1016. * if `flag` is non-zero and `digit` has no uppercase form.
  1017. */
  1018. function digitToBasic(digit, flag) {
  1019. // 0..25 map to ASCII a..z or A..Z
  1020. // 26..35 map to ASCII 0..9
  1021. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  1022. }
  1023. /**
  1024. * Bias adaptation function as per section 3.4 of RFC 3492.
  1025. * http://tools.ietf.org/html/rfc3492#section-3.4
  1026. * @private
  1027. */
  1028. function adapt(delta, numPoints, firstTime) {
  1029. var k = 0;
  1030. delta = firstTime ? floor(delta / damp) : delta >> 1;
  1031. delta += floor(delta / numPoints);
  1032. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  1033. delta = floor(delta / baseMinusTMin);
  1034. }
  1035. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  1036. }
  1037. /**
  1038. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  1039. * symbols.
  1040. * @memberOf punycode
  1041. * @param {String} input The Punycode string of ASCII-only symbols.
  1042. * @returns {String} The resulting string of Unicode symbols.
  1043. */
  1044. function decode(input) {
  1045. // Don't use UCS-2
  1046. var output = [],
  1047. inputLength = input.length,
  1048. out,
  1049. i = 0,
  1050. n = initialN,
  1051. bias = initialBias,
  1052. basic,
  1053. j,
  1054. index,
  1055. oldi,
  1056. w,
  1057. k,
  1058. digit,
  1059. t,
  1060. /** Cached calculation results */
  1061. baseMinusT;
  1062. // Handle the basic code points: let `basic` be the number of input code
  1063. // points before the last delimiter, or `0` if there is none, then copy
  1064. // the first basic code points to the output.
  1065. basic = input.lastIndexOf(delimiter);
  1066. if (basic < 0) {
  1067. basic = 0;
  1068. }
  1069. for (j = 0; j < basic; ++j) {
  1070. // if it's not a basic code point
  1071. if (input.charCodeAt(j) >= 0x80) {
  1072. error('not-basic');
  1073. }
  1074. output.push(input.charCodeAt(j));
  1075. }
  1076. // Main decoding loop: start just after the last delimiter if any basic code
  1077. // points were copied; start at the beginning otherwise.
  1078. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  1079. // `index` is the index of the next character to be consumed.
  1080. // Decode a generalized variable-length integer into `delta`,
  1081. // which gets added to `i`. The overflow checking is easier
  1082. // if we increase `i` as we go, then subtract off its starting
  1083. // value at the end to obtain `delta`.
  1084. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  1085. if (index >= inputLength) {
  1086. error('invalid-input');
  1087. }
  1088. digit = basicToDigit(input.charCodeAt(index++));
  1089. if (digit >= base || digit > floor((maxInt - i) / w)) {
  1090. error('overflow');
  1091. }
  1092. i += digit * w;
  1093. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  1094. if (digit < t) {
  1095. break;
  1096. }
  1097. baseMinusT = base - t;
  1098. if (w > floor(maxInt / baseMinusT)) {
  1099. error('overflow');
  1100. }
  1101. w *= baseMinusT;
  1102. }
  1103. out = output.length + 1;
  1104. bias = adapt(i - oldi, out, oldi == 0);
  1105. // `i` was supposed to wrap around from `out` to `0`,
  1106. // incrementing `n` each time, so we'll fix that now:
  1107. if (floor(i / out) > maxInt - n) {
  1108. error('overflow');
  1109. }
  1110. n += floor(i / out);
  1111. i %= out;
  1112. // Insert `n` at position `i` of the output
  1113. output.splice(i++, 0, n);
  1114. }
  1115. return ucs2encode(output);
  1116. }
  1117. /**
  1118. * Converts a string of Unicode symbols to a Punycode string of ASCII-only
  1119. * symbols.
  1120. * @memberOf punycode
  1121. * @param {String} input The string of Unicode symbols.
  1122. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  1123. */
  1124. function encode(input) {
  1125. var n,
  1126. delta,
  1127. handledCPCount,
  1128. basicLength,
  1129. bias,
  1130. j,
  1131. m,
  1132. q,
  1133. k,
  1134. t,
  1135. currentValue,
  1136. output = [],
  1137. /** `inputLength` will hold the number of code points in `input`. */
  1138. inputLength,
  1139. /** Cached calculation results */
  1140. handledCPCountPlusOne,
  1141. baseMinusT,
  1142. qMinusT;
  1143. // Convert the input in UCS-2 to Unicode
  1144. input = ucs2decode(input);
  1145. // Cache the length
  1146. inputLength = input.length;
  1147. // Initialize the state
  1148. n = initialN;
  1149. delta = 0;
  1150. bias = initialBias;
  1151. // Handle the basic code points
  1152. for (j = 0; j < inputLength; ++j) {
  1153. currentValue = input[j];
  1154. if (currentValue < 0x80) {
  1155. output.push(stringFromCharCode(currentValue));
  1156. }
  1157. }
  1158. handledCPCount = basicLength = output.length;
  1159. // `handledCPCount` is the number of code points that have been handled;
  1160. // `basicLength` is the number of basic code points.
  1161. // Finish the basic string - if it is not empty - with a delimiter
  1162. if (basicLength) {
  1163. output.push(delimiter);
  1164. }
  1165. // Main encoding loop:
  1166. while (handledCPCount < inputLength) {
  1167. // All non-basic code points < n have been handled already. Find the next
  1168. // larger one:
  1169. for (m = maxInt, j = 0; j < inputLength; ++j) {
  1170. currentValue = input[j];
  1171. if (currentValue >= n && currentValue < m) {
  1172. m = currentValue;
  1173. }
  1174. }
  1175. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  1176. // but guard against overflow
  1177. handledCPCountPlusOne = handledCPCount + 1;
  1178. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  1179. error('overflow');
  1180. }
  1181. delta += (m - n) * handledCPCountPlusOne;
  1182. n = m;
  1183. for (j = 0; j < inputLength; ++j) {
  1184. currentValue = input[j];
  1185. if (currentValue < n && ++delta > maxInt) {
  1186. error('overflow');
  1187. }
  1188. if (currentValue == n) {
  1189. // Represent delta as a generalized variable-length integer
  1190. for (q = delta, k = base; /* no condition */; k += base) {
  1191. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  1192. if (q < t) {
  1193. break;
  1194. }
  1195. qMinusT = q - t;
  1196. baseMinusT = base - t;
  1197. output.push(
  1198. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  1199. );
  1200. q = floor(qMinusT / baseMinusT);
  1201. }
  1202. output.push(stringFromCharCode(digitToBasic(q, 0)));
  1203. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  1204. delta = 0;
  1205. ++handledCPCount;
  1206. }
  1207. }
  1208. ++delta;
  1209. ++n;
  1210. }
  1211. return output.join('');
  1212. }
  1213. /**
  1214. * Converts a Punycode string representing a domain name to Unicode. Only the
  1215. * Punycoded parts of the domain name will be converted, i.e. it doesn't
  1216. * matter if you call it on a string that has already been converted to
  1217. * Unicode.
  1218. * @memberOf punycode
  1219. * @param {String} domain The Punycode domain name to convert to Unicode.
  1220. * @returns {String} The Unicode representation of the given Punycode
  1221. * string.
  1222. */
  1223. function toUnicode(domain) {
  1224. return mapDomain(domain, function(string) {
  1225. return regexPunycode.test(string)
  1226. ? decode(string.slice(4).toLowerCase())
  1227. : string;
  1228. });
  1229. }
  1230. /**
  1231. * Converts a Unicode string representing a domain name to Punycode. Only the
  1232. * non-ASCII parts of the domain name will be converted, i.e. it doesn't
  1233. * matter if you call it with a domain that's already in ASCII.
  1234. * @memberOf punycode
  1235. * @param {String} domain The domain name to convert, as a Unicode string.
  1236. * @returns {String} The Punycode representation of the given domain name.
  1237. */
  1238. function toASCII(domain) {
  1239. return mapDomain(domain, function(string) {
  1240. return regexNonASCII.test(string)
  1241. ? 'xn--' + encode(string)
  1242. : string;
  1243. });
  1244. }
  1245. /*--------------------------------------------------------------------------*/
  1246. /** Define the public API */
  1247. punycode = {
  1248. /**
  1249. * A string representing the current Punycode.js version number.
  1250. * @memberOf punycode
  1251. * @type String
  1252. */
  1253. 'version': '1.2.4',
  1254. /**
  1255. * An object of methods to convert from JavaScript's internal character
  1256. * representation (UCS-2) to Unicode code points, and back.
  1257. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  1258. * @memberOf punycode
  1259. * @type Object
  1260. */
  1261. 'ucs2': {
  1262. 'decode': ucs2decode,
  1263. 'encode': ucs2encode
  1264. },
  1265. 'decode': decode,
  1266. 'encode': encode,
  1267. 'toASCII': toASCII,
  1268. 'toUnicode': toUnicode
  1269. };
  1270. /** Expose `punycode` */
  1271. // Some AMD build optimizers, like r.js, check for specific condition patterns
  1272. // like the following:
  1273. if (
  1274. typeof define == 'function' &&
  1275. typeof define.amd == 'object' &&
  1276. define.amd
  1277. ) {
  1278. define('punycode', function() {
  1279. return punycode;
  1280. });
  1281. } else if (freeExports && !freeExports.nodeType) {
  1282. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  1283. freeModule.exports = punycode;
  1284. } else { // in Narwhal or RingoJS v0.7.0-
  1285. for (key in punycode) {
  1286. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  1287. }
  1288. }
  1289. } else { // in Rhino or a web browser
  1290. root.punycode = punycode;
  1291. }
  1292. }(this));
  1293. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1294. },{}],4:[function(require,module,exports){
  1295. var log = require('./log');
  1296. var Promise = require('./promise');
  1297. function restoreOwnerScroll(ownerDocument, x, y) {
  1298. if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
  1299. ownerDocument.defaultView.scrollTo(x, y);
  1300. }
  1301. }
  1302. function cloneCanvasContents(canvas, clonedCanvas) {
  1303. try {
  1304. if (clonedCanvas) {
  1305. clonedCanvas.width = canvas.width;
  1306. clonedCanvas.height = canvas.height;
  1307. clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
  1308. }
  1309. } catch(e) {
  1310. log("Unable to copy canvas content from", canvas, e);
  1311. }
  1312. }
  1313. function cloneNode(node, javascriptEnabled) {
  1314. var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
  1315. var child = node.firstChild;
  1316. while(child) {
  1317. if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
  1318. clone.appendChild(cloneNode(child, javascriptEnabled));
  1319. }
  1320. child = child.nextSibling;
  1321. }
  1322. if (node.nodeType === 1) {
  1323. clone._scrollTop = node.scrollTop;
  1324. clone._scrollLeft = node.scrollLeft;
  1325. if (node.nodeName === "CANVAS") {
  1326. cloneCanvasContents(node, clone);
  1327. } else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
  1328. clone.value = node.value;
  1329. }
  1330. }
  1331. return clone;
  1332. }
  1333. function initNode(node) {
  1334. if (node.nodeType === 1) {
  1335. node.scrollTop = node._scrollTop;
  1336. node.scrollLeft = node._scrollLeft;
  1337. var child = node.firstChild;
  1338. while(child) {
  1339. initNode(child);
  1340. child = child.nextSibling;
  1341. }
  1342. }
  1343. }
  1344. module.exports = function(ownerDocument, containerDocument, width, height, options, x ,y) {
  1345. var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
  1346. var container = containerDocument.createElement("iframe");
  1347. container.className = "html2canvas-container";
  1348. container.style.visibility = "hidden";
  1349. container.style.position = "fixed";
  1350. container.style.left = "-10000px";
  1351. container.style.top = "0px";
  1352. container.style.border = "0";
  1353. container.width = width;
  1354. container.height = height;
  1355. container.scrolling = "no"; // ios won't scroll without it
  1356. containerDocument.body.appendChild(container);
  1357. return new Promise(function(resolve) {
  1358. var documentClone = container.contentWindow.document;
  1359. /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
  1360. if window url is about:blank, we can assign the url to current by writing onto the document
  1361. */
  1362. container.contentWindow.onload = container.onload = function() {
  1363. var interval = setInterval(function() {
  1364. if (documentClone.body.childNodes.length > 0) {
  1365. initNode(documentClone.documentElement);
  1366. clearInterval(interval);
  1367. if (options.type === "view") {
  1368. container.contentWindow.scrollTo(x, y);
  1369. if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
  1370. documentClone.documentElement.style.top = (-y) + "px";
  1371. documentClone.documentElement.style.left = (-x) + "px";
  1372. documentClone.documentElement.style.position = 'absolute';
  1373. }
  1374. }
  1375. resolve(container);
  1376. }
  1377. }, 50);
  1378. };
  1379. documentClone.open();
  1380. documentClone.write("<!DOCTYPE html><html></html>");
  1381. // Chrome scrolls the parent document for some reason after the write to the cloned window???
  1382. restoreOwnerScroll(ownerDocument, x, y);
  1383. documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
  1384. documentClone.close();
  1385. });
  1386. };
  1387. },{"./log":15,"./promise":18}],5:[function(require,module,exports){
  1388. // http://dev.w3.org/csswg/css-color/
  1389. function Color(value) {
  1390. this.r = 0;
  1391. this.g = 0;
  1392. this.b = 0;
  1393. this.a = null;
  1394. var result = this.fromArray(value) ||
  1395. this.namedColor(value) ||
  1396. this.rgb(value) ||
  1397. this.rgba(value) ||
  1398. this.hex6(value) ||
  1399. this.hex3(value);
  1400. }
  1401. Color.prototype.darken = function(amount) {
  1402. var a = 1 - amount;
  1403. return new Color([
  1404. Math.round(this.r * a),
  1405. Math.round(this.g * a),
  1406. Math.round(this.b * a),
  1407. this.a
  1408. ]);
  1409. };
  1410. Color.prototype.isTransparent = function() {
  1411. return this.a === 0;
  1412. };
  1413. Color.prototype.isBlack = function() {
  1414. return this.r === 0 && this.g === 0 && this.b === 0;
  1415. };
  1416. Color.prototype.fromArray = function(array) {
  1417. if (Array.isArray(array)) {
  1418. this.r = Math.min(array[0], 255);
  1419. this.g = Math.min(array[1], 255);
  1420. this.b = Math.min(array[2], 255);
  1421. if (array.length > 3) {
  1422. this.a = array[3];
  1423. }
  1424. }
  1425. return (Array.isArray(array));
  1426. };
  1427. var _hex3 = /^#([a-f0-9]{3})$/i;
  1428. Color.prototype.hex3 = function(value) {
  1429. var match = null;
  1430. if ((match = value.match(_hex3)) !== null) {
  1431. this.r = parseInt(match[1][0] + match[1][0], 16);
  1432. this.g = parseInt(match[1][1] + match[1][1], 16);
  1433. this.b = parseInt(match[1][2] + match[1][2], 16);
  1434. }
  1435. return match !== null;
  1436. };
  1437. var _hex6 = /^#([a-f0-9]{6})$/i;
  1438. Color.prototype.hex6 = function(value) {
  1439. var match = null;
  1440. if ((match = value.match(_hex6)) !== null) {
  1441. this.r = parseInt(match[1].substring(0, 2), 16);
  1442. this.g = parseInt(match[1].substring(2, 4), 16);
  1443. this.b = parseInt(match[1].substring(4, 6), 16);
  1444. }
  1445. return match !== null;
  1446. };
  1447. var _rgb = /^rgb\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3})\)$/;
  1448. Color.prototype.rgb = function(value) {
  1449. var match = null;
  1450. if ((match = value.match(_rgb)) !== null) {
  1451. this.r = Number(match[1]);
  1452. this.g = Number(match[2]);
  1453. this.b = Number(match[3]);
  1454. }
  1455. return match !== null;
  1456. };
  1457. var _rgba = /^rgba\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3}) *, *(\d+\.?\d*)\)$/;
  1458. Color.prototype.rgba = function(value) {
  1459. var match = null;
  1460. if ((match = value.match(_rgba)) !== null) {
  1461. this.r = Number(match[1]);
  1462. this.g = Number(match[2]);
  1463. this.b = Number(match[3]);
  1464. this.a = Number(match[4]);
  1465. }
  1466. return match !== null;
  1467. };
  1468. Color.prototype.toString = function() {
  1469. return this.a !== null && this.a !== 1 ?
  1470. "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
  1471. "rgb(" + [this.r, this.g, this.b].join(",") + ")";
  1472. };
  1473. Color.prototype.namedColor = function(value) {
  1474. var color = colors[value.toLowerCase()];
  1475. if (color) {
  1476. this.r = color[0];
  1477. this.g = color[1];
  1478. this.b = color[2];
  1479. } else if (value.toLowerCase() === "transparent") {
  1480. this.r = this.g = this.b = this.a = 0;
  1481. return true;
  1482. }
  1483. return !!color;
  1484. };
  1485. Color.prototype.isColor = true;
  1486. // JSON.stringify([].slice.call($$('.named-color-table tr'), 1).map(function(row) { return [row.childNodes[3].textContent, row.childNodes[5].textContent.trim().split(",").map(Number)] }).reduce(function(data, row) {data[row[0]] = row[1]; return data}, {}))
  1487. var colors = {
  1488. "aliceblue": [240, 248, 255],
  1489. "antiquewhite": [250, 235, 215],
  1490. "aqua": [0, 255, 255],
  1491. "aquamarine": [127, 255, 212],
  1492. "azure": [240, 255, 255],
  1493. "beige": [245, 245, 220],
  1494. "bisque": [255, 228, 196],
  1495. "black": [0, 0, 0],
  1496. "blanchedalmond": [255, 235, 205],
  1497. "blue": [0, 0, 255],
  1498. "blueviolet": [138, 43, 226],
  1499. "brown": [165, 42, 42],
  1500. "burlywood": [222, 184, 135],
  1501. "cadetblue": [95, 158, 160],
  1502. "chartreuse": [127, 255, 0],
  1503. "chocolate": [210, 105, 30],
  1504. "coral": [255, 127, 80],
  1505. "cornflowerblue": [100, 149, 237],
  1506. "cornsilk": [255, 248, 220],
  1507. "crimson": [220, 20, 60],
  1508. "cyan": [0, 255, 255],
  1509. "darkblue": [0, 0, 139],
  1510. "darkcyan": [0, 139, 139],
  1511. "darkgoldenrod": [184, 134, 11],
  1512. "darkgray": [169, 169, 169],
  1513. "darkgreen": [0, 100, 0],
  1514. "darkgrey": [169, 169, 169],
  1515. "darkkhaki": [189, 183, 107],
  1516. "darkmagenta": [139, 0, 139],
  1517. "darkolivegreen": [85, 107, 47],
  1518. "darkorange": [255, 140, 0],
  1519. "darkorchid": [153, 50, 204],
  1520. "darkred": [139, 0, 0],
  1521. "darksalmon": [233, 150, 122],
  1522. "darkseagreen": [143, 188, 143],
  1523. "darkslateblue": [72, 61, 139],
  1524. "darkslategray": [47, 79, 79],
  1525. "darkslategrey": [47, 79, 79],
  1526. "darkturquoise": [0, 206, 209],
  1527. "darkviolet": [148, 0, 211],
  1528. "deeppink": [255, 20, 147],
  1529. "deepskyblue": [0, 191, 255],
  1530. "dimgray": [105, 105, 105],
  1531. "dimgrey": [105, 105, 105],
  1532. "dodgerblue": [30, 144, 255],
  1533. "firebrick": [178, 34, 34],
  1534. "floralwhite": [255, 250, 240],
  1535. "forestgreen": [34, 139, 34],
  1536. "fuchsia": [255, 0, 255],
  1537. "gainsboro": [220, 220, 220],
  1538. "ghostwhite": [248, 248, 255],
  1539. "gold": [255, 215, 0],
  1540. "goldenrod": [218, 165, 32],
  1541. "gray": [128, 128, 128],
  1542. "green": [0, 128, 0],
  1543. "greenyellow": [173, 255, 47],
  1544. "grey": [128, 128, 128],
  1545. "honeydew": [240, 255, 240],
  1546. "hotpink": [255, 105, 180],
  1547. "indianred": [205, 92, 92],
  1548. "indigo": [75, 0, 130],
  1549. "ivory": [255, 255, 240],
  1550. "khaki": [240, 230, 140],
  1551. "lavender": [230, 230, 250],
  1552. "lavenderblush": [255, 240, 245],
  1553. "lawngreen": [124, 252, 0],
  1554. "lemonchiffon": [255, 250, 205],
  1555. "lightblue": [173, 216, 230],
  1556. "lightcoral": [240, 128, 128],
  1557. "lightcyan": [224, 255, 255],
  1558. "lightgoldenrodyellow": [250, 250, 210],
  1559. "lightgray": [211, 211, 211],
  1560. "lightgreen": [144, 238, 144],
  1561. "lightgrey": [211, 211, 211],
  1562. "lightpink": [255, 182, 193],
  1563. "lightsalmon": [255, 160, 122],
  1564. "lightseagreen": [32, 178, 170],
  1565. "lightskyblue": [135, 206, 250],
  1566. "lightslategray": [119, 136, 153],
  1567. "lightslategrey": [119, 136, 153],
  1568. "lightsteelblue": [176, 196, 222],
  1569. "lightyellow": [255, 255, 224],
  1570. "lime": [0, 255, 0],
  1571. "limegreen": [50, 205, 50],
  1572. "linen": [250, 240, 230],
  1573. "magenta": [255, 0, 255],
  1574. "maroon": [128, 0, 0],
  1575. "mediumaquamarine": [102, 205, 170],
  1576. "mediumblue": [0, 0, 205],
  1577. "mediumorchid": [186, 85, 211],
  1578. "mediumpurple": [147, 112, 219],
  1579. "mediumseagreen": [60, 179, 113],
  1580. "mediumslateblue": [123, 104, 238],
  1581. "mediumspringgreen": [0, 250, 154],
  1582. "mediumturquoise": [72, 209, 204],
  1583. "mediumvioletred": [199, 21, 133],
  1584. "midnightblue": [25, 25, 112],
  1585. "mintcream": [245, 255, 250],
  1586. "mistyrose": [255, 228, 225],
  1587. "moccasin": [255, 228, 181],
  1588. "navajowhite": [255, 222, 173],
  1589. "navy": [0, 0, 128],
  1590. "oldlace": [253, 245, 230],
  1591. "olive": [128, 128, 0],
  1592. "olivedrab": [107, 142, 35],
  1593. "orange": [255, 165, 0],
  1594. "orangered": [255, 69, 0],
  1595. "orchid": [218, 112, 214],
  1596. "palegoldenrod": [238, 232, 170],
  1597. "palegreen": [152, 251, 152],
  1598. "paleturquoise": [175, 238, 238],
  1599. "palevioletred": [219, 112, 147],
  1600. "papayawhip": [255, 239, 213],
  1601. "peachpuff": [255, 218, 185],
  1602. "peru": [205, 133, 63],
  1603. "pink": [255, 192, 203],
  1604. "plum": [221, 160, 221],
  1605. "powderblue": [176, 224, 230],
  1606. "purple": [128, 0, 128],
  1607. "rebeccapurple": [102, 51, 153],
  1608. "red": [255, 0, 0],
  1609. "rosybrown": [188, 143, 143],
  1610. "royalblue": [65, 105, 225],
  1611. "saddlebrown": [139, 69, 19],
  1612. "salmon": [250, 128, 114],
  1613. "sandybrown": [244, 164, 96],
  1614. "seagreen": [46, 139, 87],
  1615. "seashell": [255, 245, 238],
  1616. "sienna": [160, 82, 45],
  1617. "silver": [192, 192, 192],
  1618. "skyblue": [135, 206, 235],
  1619. "slateblue": [106, 90, 205],
  1620. "slategray": [112, 128, 144],
  1621. "slategrey": [112, 128, 144],
  1622. "snow": [255, 250, 250],
  1623. "springgreen": [0, 255, 127],
  1624. "steelblue": [70, 130, 180],
  1625. "tan": [210, 180, 140],
  1626. "teal": [0, 128, 128],
  1627. "thistle": [216, 191, 216],
  1628. "tomato": [255, 99, 71],
  1629. "turquoise": [64, 224, 208],
  1630. "violet": [238, 130, 238],
  1631. "wheat": [245, 222, 179],
  1632. "white": [255, 255, 255],
  1633. "whitesmoke": [245, 245, 245],
  1634. "yellow": [255, 255, 0],
  1635. "yellowgreen": [154, 205, 50]
  1636. };
  1637. module.exports = Color;
  1638. },{}],6:[function(require,module,exports){
  1639. var Promise = require('./promise');
  1640. var Support = require('./support');
  1641. var CanvasRenderer = require('./renderers/canvas');
  1642. var ImageLoader = require('./imageloader');
  1643. var NodeParser = require('./nodeparser');
  1644. var NodeContainer = require('./nodecontainer');
  1645. var log = require('./log');
  1646. var utils = require('./utils');
  1647. var createWindowClone = require('./clone');
  1648. var loadUrlDocument = require('./proxy').loadUrlDocument;
  1649. var getBounds = utils.getBounds;
  1650. var html2canvasNodeAttribute = "data-html2canvas-node";
  1651. var html2canvasCloneIndex = 0;
  1652. function html2canvas(nodeList, options) {
  1653. var index = html2canvasCloneIndex++;
  1654. options = options || {};
  1655. if (options.logging) {
  1656. window.html2canvas.logging = true;
  1657. window.html2canvas.start = Date.now();
  1658. }
  1659. options.async = typeof(options.async) === "undefined" ? true : options.async;
  1660. options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
  1661. options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
  1662. options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
  1663. options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
  1664. options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
  1665. options.strict = !!options.strict;
  1666. if (typeof(nodeList) === "string") {
  1667. if (typeof(options.proxy) !== "string") {
  1668. return Promise.reject("Proxy must be used when rendering url");
  1669. }
  1670. var width = options.width != null ? options.width : window.innerWidth;
  1671. var height = options.height != null ? options.height : window.innerHeight;
  1672. return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
  1673. return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
  1674. });
  1675. }
  1676. var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
  1677. node.setAttribute(html2canvasNodeAttribute + index, index);
  1678. return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
  1679. if (typeof(options.onrendered) === "function") {
  1680. log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
  1681. options.onrendered(canvas);
  1682. }
  1683. return canvas;
  1684. });
  1685. }
  1686. html2canvas.Promise = Promise;
  1687. html2canvas.CanvasRenderer = CanvasRenderer;
  1688. html2canvas.NodeContainer = NodeContainer;
  1689. html2canvas.log = log;
  1690. html2canvas.utils = utils;
  1691. module.exports = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ? function() {
  1692. return Promise.reject("No canvas support");
  1693. } : html2canvas;
  1694. function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
  1695. return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
  1696. log("Document cloned");
  1697. var attributeName = html2canvasNodeAttribute + html2canvasIndex;
  1698. var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
  1699. document.querySelector(selector).removeAttribute(attributeName);
  1700. var clonedWindow = container.contentWindow;
  1701. var node = clonedWindow.document.querySelector(selector);
  1702. var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
  1703. return oncloneHandler.then(function() {
  1704. return renderWindow(node, container, options, windowWidth, windowHeight);
  1705. });
  1706. });
  1707. }
  1708. function renderWindow(node, container, options, windowWidth, windowHeight) {
  1709. var clonedWindow = container.contentWindow;
  1710. var support = new Support(clonedWindow.document);
  1711. var imageLoader = new ImageLoader(options, support);
  1712. var bounds = getBounds(node);
  1713. var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
  1714. var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
  1715. var renderer = new options.renderer(width, height, imageLoader, options, document);
  1716. var parser = new NodeParser(node, renderer, support, imageLoader, options);
  1717. return parser.ready.then(function() {
  1718. log("Finished rendering");
  1719. var canvas;
  1720. if (options.type === "view") {
  1721. canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
  1722. } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
  1723. canvas = renderer.canvas;
  1724. } else {
  1725. canvas = crop(renderer.canvas, {width: options.width != null ? options.width : bounds.width, height: options.height != null ? options.height : bounds.height, top: bounds.top, left: bounds.left, x: clonedWindow.pageXOffset, y: clonedWindow.pageYOffset});
  1726. }
  1727. cleanupContainer(container, options);
  1728. return canvas;
  1729. });
  1730. }
  1731. function cleanupContainer(container, options) {
  1732. if (options.removeContainer) {
  1733. container.parentNode.removeChild(container);
  1734. log("Cleaned up container");
  1735. }
  1736. }
  1737. function crop(canvas, bounds) {
  1738. var croppedCanvas = document.createElement("canvas");
  1739. var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
  1740. var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
  1741. var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
  1742. var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
  1743. croppedCanvas.width = bounds.width;
  1744. croppedCanvas.height = bounds.height;
  1745. log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", (x2-x1), "height:", (y2-y1));
  1746. log("Resulting crop with width", bounds.width, "and height", bounds.height, " with x", x1, "and y", y1);
  1747. croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, x2-x1, y2-y1, bounds.x, bounds.y, x2-x1, y2-y1);
  1748. return croppedCanvas;
  1749. }
  1750. function documentWidth (doc) {
  1751. return Math.max(
  1752. Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
  1753. Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
  1754. Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
  1755. );
  1756. }
  1757. function documentHeight (doc) {
  1758. return Math.max(
  1759. Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
  1760. Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
  1761. Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
  1762. );
  1763. }
  1764. function absoluteUrl(url) {
  1765. var link = document.createElement("a");
  1766. link.href = url;
  1767. link.href = link.href;
  1768. return link;
  1769. }
  1770. },{"./clone":4,"./imageloader":13,"./log":15,"./nodecontainer":16,"./nodeparser":17,"./promise":18,"./proxy":19,"./renderers/canvas":23,"./support":25,"./utils":29}],7:[function(require,module,exports){
  1771. var Promise = require('./promise');
  1772. var log = require('./log');
  1773. var smallImage = require('./utils').smallImage;
  1774. function DummyImageContainer(src) {
  1775. this.src = src;
  1776. log("DummyImageContainer for", src);
  1777. if (!this.promise || !this.image) {
  1778. log("Initiating DummyImageContainer");
  1779. DummyImageContainer.prototype.image = new Image();
  1780. var image = this.image;
  1781. DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
  1782. image.onload = resolve;
  1783. image.onerror = reject;
  1784. image.src = smallImage();
  1785. if (image.complete === true) {
  1786. resolve(image);
  1787. }
  1788. });
  1789. }
  1790. }
  1791. module.exports = DummyImageContainer;
  1792. },{"./log":15,"./promise":18,"./utils":29}],8:[function(require,module,exports){
  1793. var smallImage = require('./utils').smallImage;
  1794. function Font(family, size) {
  1795. var container = document.createElement('div'),
  1796. img = document.createElement('img'),
  1797. span = document.createElement('span'),
  1798. sampleText = 'Hidden Text',
  1799. baseline,
  1800. middle;
  1801. container.style.visibility = "hidden";
  1802. container.style.fontFamily = family;
  1803. container.style.fontSize = size;
  1804. container.style.margin = 0;
  1805. container.style.padding = 0;
  1806. document.body.appendChild(container);
  1807. img.src = smallImage();
  1808. img.width = 1;
  1809. img.height = 1;
  1810. img.style.margin = 0;
  1811. img.style.padding = 0;
  1812. img.style.verticalAlign = "baseline";
  1813. span.style.fontFamily = family;
  1814. span.style.fontSize = size;
  1815. span.style.margin = 0;
  1816. span.style.padding = 0;
  1817. span.appendChild(document.createTextNode(sampleText));
  1818. container.appendChild(span);
  1819. container.appendChild(img);
  1820. baseline = (img.offsetTop - span.offsetTop) + 1;
  1821. container.removeChild(span);
  1822. container.appendChild(document.createTextNode(sampleText));
  1823. container.style.lineHeight = "normal";
  1824. img.style.verticalAlign = "super";
  1825. middle = (img.offsetTop-container.offsetTop) + 1;
  1826. document.body.removeChild(container);
  1827. this.baseline = baseline;
  1828. this.lineWidth = 1;
  1829. this.middle = middle;
  1830. }
  1831. module.exports = Font;
  1832. },{"./utils":29}],9:[function(require,module,exports){
  1833. var Font = require('./font');
  1834. function FontMetrics() {
  1835. this.data = {};
  1836. }
  1837. FontMetrics.prototype.getMetrics = function(family, size) {
  1838. if (this.data[family + "-" + size] === undefined) {
  1839. this.data[family + "-" + size] = new Font(family, size);
  1840. }
  1841. return this.data[family + "-" + size];
  1842. };
  1843. module.exports = FontMetrics;
  1844. },{"./font":8}],10:[function(require,module,exports){
  1845. var utils = require('./utils');
  1846. var Promise = require('./promise');
  1847. var getBounds = utils.getBounds;
  1848. var loadUrlDocument = require('./proxy').loadUrlDocument;
  1849. function FrameContainer(container, sameOrigin, options) {
  1850. this.image = null;
  1851. this.src = container;
  1852. var self = this;
  1853. var bounds = getBounds(container);
  1854. this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
  1855. if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
  1856. container.contentWindow.onload = container.onload = function() {
  1857. resolve(container);
  1858. };
  1859. } else {
  1860. resolve(container);
  1861. }
  1862. })).then(function(container) {
  1863. var html2canvas = require('./core');
  1864. return html2canvas(container.contentWindow.document.documentElement, {type: 'view', width: container.width, height: container.height, proxy: options.proxy, javascriptEnabled: options.javascriptEnabled, removeContainer: options.removeContainer, allowTaint: options.allowTaint, imageTimeout: options.imageTimeout / 2});
  1865. }).then(function(canvas) {
  1866. return self.image = canvas;
  1867. });
  1868. }
  1869. FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
  1870. var container = this.src;
  1871. return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
  1872. };
  1873. module.exports = FrameContainer;
  1874. },{"./core":6,"./promise":18,"./proxy":19,"./utils":29}],11:[function(require,module,exports){
  1875. var Promise = require('./promise');
  1876. function GradientContainer(imageData) {
  1877. this.src = imageData.value;
  1878. this.colorStops = [];
  1879. this.type = null;
  1880. this.x0 = 0.5;
  1881. this.y0 = 0.5;
  1882. this.x1 = 0.5;
  1883. this.y1 = 0.5;
  1884. this.promise = Promise.resolve(true);
  1885. }
  1886. GradientContainer.prototype.TYPES = {
  1887. LINEAR: 1,
  1888. RADIAL: 2
  1889. };
  1890. module.exports = GradientContainer;
  1891. },{"./promise":18}],12:[function(require,module,exports){
  1892. var Promise = require('./promise');
  1893. function ImageContainer(src, cors) {
  1894. this.src = src;
  1895. this.image = new Image();
  1896. var self = this;
  1897. this.tainted = null;
  1898. this.promise = new Promise(function(resolve, reject) {
  1899. self.image.onload = resolve;
  1900. self.image.onerror = reject;
  1901. if (cors) {
  1902. self.image.crossOrigin = "anonymous";
  1903. }
  1904. self.image.src = src;
  1905. if (self.image.complete === true) {
  1906. resolve(self.image);
  1907. }
  1908. });
  1909. }
  1910. module.exports = ImageContainer;
  1911. },{"./promise":18}],13:[function(require,module,exports){
  1912. var Promise = require('./promise');
  1913. var log = require('./log');
  1914. var ImageContainer = require('./imagecontainer');
  1915. var DummyImageContainer = require('./dummyimagecontainer');
  1916. var ProxyImageContainer = require('./proxyimagecontainer');
  1917. var FrameContainer = require('./framecontainer');
  1918. var SVGContainer = require('./svgcontainer');
  1919. var SVGNodeContainer = require('./svgnodecontainer');
  1920. var LinearGradientContainer = require('./lineargradientcontainer');
  1921. var WebkitGradientContainer = require('./webkitgradientcontainer');
  1922. var bind = require('./utils').bind;
  1923. function ImageLoader(options, support) {
  1924. this.link = null;
  1925. this.options = options;
  1926. this.support = support;
  1927. this.origin = this.getOrigin(window.location.href);
  1928. }
  1929. ImageLoader.prototype.findImages = function(nodes) {
  1930. var images = [];
  1931. nodes.reduce(function(imageNodes, container) {
  1932. switch(container.node.nodeName) {
  1933. case "IMG":
  1934. return imageNodes.concat([{
  1935. args: [container.node.src],
  1936. method: "url"
  1937. }]);
  1938. case "svg":
  1939. case "IFRAME":
  1940. return imageNodes.concat([{
  1941. args: [container.node],
  1942. method: container.node.nodeName
  1943. }]);
  1944. }
  1945. return imageNodes;
  1946. }, []).forEach(this.addImage(images, this.loadImage), this);
  1947. return images;
  1948. };
  1949. ImageLoader.prototype.findBackgroundImage = function(images, container) {
  1950. container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
  1951. return images;
  1952. };
  1953. ImageLoader.prototype.addImage = function(images, callback) {
  1954. return function(newImage) {
  1955. newImage.args.forEach(function(image) {
  1956. if (!this.imageExists(images, image)) {
  1957. images.splice(0, 0, callback.call(this, newImage));
  1958. log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
  1959. }
  1960. }, this);
  1961. };
  1962. };
  1963. ImageLoader.prototype.hasImageBackground = function(imageData) {
  1964. return imageData.method !== "none";
  1965. };
  1966. ImageLoader.prototype.loadImage = function(imageData) {
  1967. if (imageData.method === "url") {
  1968. var src = imageData.args[0];
  1969. if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
  1970. return new SVGContainer(src);
  1971. } else if (src.match(/data:image\/.*;base64,/i)) {
  1972. return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
  1973. } else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
  1974. return new ImageContainer(src, false);
  1975. } else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
  1976. return new ImageContainer(src, true);
  1977. } else if (this.options.proxy) {
  1978. return new ProxyImageContainer(src, this.options.proxy);
  1979. } else {
  1980. return new DummyImageContainer(src);
  1981. }
  1982. } else if (imageData.method === "linear-gradient") {
  1983. return new LinearGradientContainer(imageData);
  1984. } else if (imageData.method === "gradient") {
  1985. return new WebkitGradientContainer(imageData);
  1986. } else if (imageData.method === "svg") {
  1987. return new SVGNodeContainer(imageData.args[0], this.support.svg);
  1988. } else if (imageData.method === "IFRAME") {
  1989. return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
  1990. } else {
  1991. return new DummyImageContainer(imageData);
  1992. }
  1993. };
  1994. ImageLoader.prototype.isSVG = function(src) {
  1995. return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
  1996. };
  1997. ImageLoader.prototype.imageExists = function(images, src) {
  1998. return images.some(function(image) {
  1999. return image.src === src;
  2000. });
  2001. };
  2002. ImageLoader.prototype.isSameOrigin = function(url) {
  2003. return (this.getOrigin(url) === this.origin);
  2004. };
  2005. ImageLoader.prototype.getOrigin = function(url) {
  2006. var link = this.link || (this.link = document.createElement("a"));
  2007. link.href = url;
  2008. link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
  2009. return link.protocol + link.hostname + link.port;
  2010. };
  2011. ImageLoader.prototype.getPromise = function(container) {
  2012. return this.timeout(container, this.options.imageTimeout)['catch'](function() {
  2013. var dummy = new DummyImageContainer(container.src);
  2014. return dummy.promise.then(function(image) {
  2015. container.image = image;
  2016. });
  2017. });
  2018. };
  2019. ImageLoader.prototype.get = function(src) {
  2020. var found = null;
  2021. return this.images.some(function(img) {
  2022. return (found = img).src === src;
  2023. }) ? found : null;
  2024. };
  2025. ImageLoader.prototype.fetch = function(nodes) {
  2026. this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
  2027. this.images.forEach(function(image, index) {
  2028. image.promise.then(function() {
  2029. log("Succesfully loaded image #"+ (index+1), image);
  2030. }, function(e) {
  2031. log("Failed loading image #"+ (index+1), image, e);
  2032. });
  2033. });
  2034. this.ready = Promise.all(this.images.map(this.getPromise, this));
  2035. log("Finished searching images");
  2036. return this;
  2037. };
  2038. ImageLoader.prototype.timeout = function(container, timeout) {
  2039. var timer;
  2040. var promise = Promise.race([container.promise, new Promise(function(res, reject) {
  2041. timer = setTimeout(function() {
  2042. log("Timed out loading image", container);
  2043. reject(container);
  2044. }, timeout);
  2045. })]).then(function(container) {
  2046. clearTimeout(timer);
  2047. return container;
  2048. });
  2049. promise['catch'](function() {
  2050. clearTimeout(timer);
  2051. });
  2052. return promise;
  2053. };
  2054. module.exports = ImageLoader;
  2055. },{"./dummyimagecontainer":7,"./framecontainer":10,"./imagecontainer":12,"./lineargradientcontainer":14,"./log":15,"./promise":18,"./proxyimagecontainer":20,"./svgcontainer":26,"./svgnodecontainer":27,"./utils":29,"./webkitgradientcontainer":30}],14:[function(require,module,exports){
  2056. var GradientContainer = require('./gradientcontainer');
  2057. var Color = require('./color');
  2058. function LinearGradientContainer(imageData) {
  2059. GradientContainer.apply(this, arguments);
  2060. this.type = this.TYPES.LINEAR;
  2061. var hasDirection = imageData.args[0].match(this.stepRegExp) === null;
  2062. if (hasDirection) {
  2063. imageData.args[0].split(" ").reverse().forEach(function(position) {
  2064. switch(position) {
  2065. case "left":
  2066. this.x0 = 0;
  2067. this.x1 = 1;
  2068. break;
  2069. case "top":
  2070. this.y0 = 0;
  2071. this.y1 = 1;
  2072. break;
  2073. case "right":
  2074. this.x0 = 1;
  2075. this.x1 = 0;
  2076. break;
  2077. case "bottom":
  2078. this.y0 = 1;
  2079. this.y1 = 0;
  2080. break;
  2081. case "to":
  2082. var y0 = this.y0;
  2083. var x0 = this.x0;
  2084. this.y0 = this.y1;
  2085. this.x0 = this.x1;
  2086. this.x1 = x0;
  2087. this.y1 = y0;
  2088. break;
  2089. }
  2090. }, this);
  2091. } else {
  2092. this.y0 = 0;
  2093. this.y1 = 1;
  2094. }
  2095. this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
  2096. var colorStopMatch = colorStop.match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)|\w+)\s*(\d{1,3})?(%|px)?/);
  2097. return {
  2098. color: new Color(colorStopMatch[1]),
  2099. stop: colorStopMatch[3] === "%" ? colorStopMatch[2] / 100 : null
  2100. };
  2101. }, this);
  2102. if (this.colorStops[0].stop === null) {
  2103. this.colorStops[0].stop = 0;
  2104. }
  2105. if (this.colorStops[this.colorStops.length - 1].stop === null) {
  2106. this.colorStops[this.colorStops.length - 1].stop = 1;
  2107. }
  2108. this.colorStops.forEach(function(colorStop, index) {
  2109. if (colorStop.stop === null) {
  2110. this.colorStops.slice(index).some(function(find, count) {
  2111. if (find.stop !== null) {
  2112. colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
  2113. return true;
  2114. } else {
  2115. return false;
  2116. }
  2117. }, this);
  2118. }
  2119. }, this);
  2120. }
  2121. LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
  2122. LinearGradientContainer.prototype.stepRegExp = /((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/;
  2123. module.exports = LinearGradientContainer;
  2124. },{"./color":5,"./gradientcontainer":11}],15:[function(require,module,exports){
  2125. module.exports = function() {
  2126. if (window.html2canvas.logging && window.console && window.console.log) {
  2127. Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - window.html2canvas.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
  2128. }
  2129. };
  2130. },{}],16:[function(require,module,exports){
  2131. var Color = require('./color');
  2132. var utils = require('./utils');
  2133. var getBounds = utils.getBounds;
  2134. var parseBackgrounds = utils.parseBackgrounds;
  2135. var offsetBounds = utils.offsetBounds;
  2136. function NodeContainer(node, parent) {
  2137. this.node = node;
  2138. this.parent = parent;
  2139. this.stack = null;
  2140. this.bounds = null;
  2141. this.borders = null;
  2142. this.clip = [];
  2143. this.backgroundClip = [];
  2144. this.offsetBounds = null;
  2145. this.visible = null;
  2146. this.computedStyles = null;
  2147. this.colors = {};
  2148. this.styles = {};
  2149. this.backgroundImages = null;
  2150. this.transformData = null;
  2151. this.transformMatrix = null;
  2152. this.isPseudoElement = false;
  2153. this.opacity = null;
  2154. }
  2155. NodeContainer.prototype.cloneTo = function(stack) {
  2156. stack.visible = this.visible;
  2157. stack.borders = this.borders;
  2158. stack.bounds = this.bounds;
  2159. stack.clip = this.clip;
  2160. stack.backgroundClip = this.backgroundClip;
  2161. stack.computedStyles = this.computedStyles;
  2162. stack.styles = this.styles;
  2163. stack.backgroundImages = this.backgroundImages;
  2164. stack.opacity = this.opacity;
  2165. };
  2166. NodeContainer.prototype.getOpacity = function() {
  2167. return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
  2168. };
  2169. NodeContainer.prototype.assignStack = function(stack) {
  2170. this.stack = stack;
  2171. stack.children.push(this);
  2172. };
  2173. NodeContainer.prototype.isElementVisible = function() {
  2174. return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
  2175. this.css('display') !== "none" &&
  2176. this.css('visibility') !== "hidden" &&
  2177. !this.node.hasAttribute("data-html2canvas-ignore") &&
  2178. (this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
  2179. );
  2180. };
  2181. NodeContainer.prototype.css = function(attribute) {
  2182. if (!this.computedStyles) {
  2183. this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
  2184. }
  2185. return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
  2186. };
  2187. NodeContainer.prototype.prefixedCss = function(attribute) {
  2188. var prefixes = ["webkit", "moz", "ms", "o"];
  2189. var value = this.css(attribute);
  2190. if (value === undefined) {
  2191. prefixes.some(function(prefix) {
  2192. value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
  2193. return value !== undefined;
  2194. }, this);
  2195. }
  2196. return value === undefined ? null : value;
  2197. };
  2198. NodeContainer.prototype.computedStyle = function(type) {
  2199. return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
  2200. };
  2201. NodeContainer.prototype.cssInt = function(attribute) {
  2202. var value = parseInt(this.css(attribute), 10);
  2203. return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
  2204. };
  2205. NodeContainer.prototype.color = function(attribute) {
  2206. return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
  2207. };
  2208. NodeContainer.prototype.cssFloat = function(attribute) {
  2209. var value = parseFloat(this.css(attribute));
  2210. return (isNaN(value)) ? 0 : value;
  2211. };
  2212. NodeContainer.prototype.fontWeight = function() {
  2213. var weight = this.css("fontWeight");
  2214. switch(parseInt(weight, 10)){
  2215. case 401:
  2216. weight = "bold";
  2217. break;
  2218. case 400:
  2219. weight = "normal";
  2220. break;
  2221. }
  2222. return weight;
  2223. };
  2224. NodeContainer.prototype.parseClip = function() {
  2225. var matches = this.css('clip').match(this.CLIP);
  2226. if (matches) {
  2227. return {
  2228. top: parseInt(matches[1], 10),
  2229. right: parseInt(matches[2], 10),
  2230. bottom: parseInt(matches[3], 10),
  2231. left: parseInt(matches[4], 10)
  2232. };
  2233. }
  2234. return null;
  2235. };
  2236. NodeContainer.prototype.parseBackgroundImages = function() {
  2237. return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
  2238. };
  2239. NodeContainer.prototype.cssList = function(property, index) {
  2240. var value = (this.css(property) || '').split(',');
  2241. value = value[index || 0] || value[0] || 'auto';
  2242. value = value.trim().split(' ');
  2243. if (value.length === 1) {
  2244. value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
  2245. }
  2246. return value;
  2247. };
  2248. NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
  2249. var size = this.cssList("backgroundSize", index);
  2250. var width, height;
  2251. if (isPercentage(size[0])) {
  2252. width = bounds.width * parseFloat(size[0]) / 100;
  2253. } else if (/contain|cover/.test(size[0])) {
  2254. var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
  2255. return (targetRatio < currentRatio ^ size[0] === 'contain') ? {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio};
  2256. } else {
  2257. width = parseInt(size[0], 10);
  2258. }
  2259. if (size[0] === 'auto' && size[1] === 'auto') {
  2260. height = image.height;
  2261. } else if (size[1] === 'auto') {
  2262. height = width / image.width * image.height;
  2263. } else if (isPercentage(size[1])) {
  2264. height = bounds.height * parseFloat(size[1]) / 100;
  2265. } else {
  2266. height = parseInt(size[1], 10);
  2267. }
  2268. if (size[0] === 'auto') {
  2269. width = height / image.height * image.width;
  2270. }
  2271. return {width: width, height: height};
  2272. };
  2273. NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
  2274. var position = this.cssList('backgroundPosition', index);
  2275. var left, top;
  2276. if (isPercentage(position[0])){
  2277. left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
  2278. } else {
  2279. left = parseInt(position[0], 10);
  2280. }
  2281. if (position[1] === 'auto') {
  2282. top = left / image.width * image.height;
  2283. } else if (isPercentage(position[1])){
  2284. top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
  2285. } else {
  2286. top = parseInt(position[1], 10);
  2287. }
  2288. if (position[0] === 'auto') {
  2289. left = top / image.height * image.width;
  2290. }
  2291. return {left: left, top: top};
  2292. };
  2293. NodeContainer.prototype.parseBackgroundRepeat = function(index) {
  2294. return this.cssList("backgroundRepeat", index)[0];
  2295. };
  2296. NodeContainer.prototype.parseTextShadows = function() {
  2297. var textShadow = this.css("textShadow");
  2298. var results = [];
  2299. if (textShadow && textShadow !== 'none') {
  2300. var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
  2301. for (var i = 0; shadows && (i < shadows.length); i++) {
  2302. var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
  2303. results.push({
  2304. color: new Color(s[0]),
  2305. offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
  2306. offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
  2307. blur: s[3] ? s[3].replace('px', '') : 0
  2308. });
  2309. }
  2310. }
  2311. return results;
  2312. };
  2313. NodeContainer.prototype.parseTransform = function() {
  2314. if (!this.transformData) {
  2315. if (this.hasTransform()) {
  2316. var offset = this.parseBounds();
  2317. var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
  2318. origin[0] += offset.left;
  2319. origin[1] += offset.top;
  2320. this.transformData = {
  2321. origin: origin,
  2322. matrix: this.parseTransformMatrix()
  2323. };
  2324. } else {
  2325. this.transformData = {
  2326. origin: [0, 0],
  2327. matrix: [1, 0, 0, 1, 0, 0]
  2328. };
  2329. }
  2330. }
  2331. return this.transformData;
  2332. };
  2333. NodeContainer.prototype.parseTransformMatrix = function() {
  2334. if (!this.transformMatrix) {
  2335. var transform = this.prefixedCss("transform");
  2336. var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
  2337. this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
  2338. }
  2339. return this.transformMatrix;
  2340. };
  2341. NodeContainer.prototype.parseBounds = function() {
  2342. return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
  2343. };
  2344. NodeContainer.prototype.hasTransform = function() {
  2345. return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
  2346. };
  2347. NodeContainer.prototype.getValue = function() {
  2348. var value = this.node.value || "";
  2349. if (this.node.tagName === "SELECT") {
  2350. value = selectionValue(this.node);
  2351. } else if (this.node.type === "password") {
  2352. value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
  2353. }
  2354. return value.length === 0 ? (this.node.placeholder || "") : value;
  2355. };
  2356. NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
  2357. NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
  2358. NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
  2359. NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
  2360. function selectionValue(node) {
  2361. var option = node.options[node.selectedIndex || 0];
  2362. return option ? (option.text || "") : "";
  2363. }
  2364. function parseMatrix(match) {
  2365. if (match && match[1] === "matrix") {
  2366. return match[2].split(",").map(function(s) {
  2367. return parseFloat(s.trim());
  2368. });
  2369. } else if (match && match[1] === "matrix3d") {
  2370. var matrix3d = match[2].split(",").map(function(s) {
  2371. return parseFloat(s.trim());
  2372. });
  2373. return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
  2374. }
  2375. }
  2376. function isPercentage(value) {
  2377. return value.toString().indexOf("%") !== -1;
  2378. }
  2379. function removePx(str) {
  2380. return str.replace("px", "");
  2381. }
  2382. function asFloat(str) {
  2383. return parseFloat(str);
  2384. }
  2385. module.exports = NodeContainer;
  2386. },{"./color":5,"./utils":29}],17:[function(require,module,exports){
  2387. var log = require('./log');
  2388. var punycode = require('punycode');
  2389. var NodeContainer = require('./nodecontainer');
  2390. var TextContainer = require('./textcontainer');
  2391. var PseudoElementContainer = require('./pseudoelementcontainer');
  2392. var FontMetrics = require('./fontmetrics');
  2393. var Color = require('./color');
  2394. var Promise = require('./promise');
  2395. var StackingContext = require('./stackingcontext');
  2396. var utils = require('./utils');
  2397. var bind = utils.bind;
  2398. var getBounds = utils.getBounds;
  2399. var parseBackgrounds = utils.parseBackgrounds;
  2400. var offsetBounds = utils.offsetBounds;
  2401. function NodeParser(element, renderer, support, imageLoader, options) {
  2402. log("Starting NodeParser");
  2403. this.renderer = renderer;
  2404. this.options = options;
  2405. this.range = null;
  2406. this.support = support;
  2407. this.renderQueue = [];
  2408. this.stack = new StackingContext(true, 1, element.ownerDocument, null);
  2409. var parent = new NodeContainer(element, null);
  2410. if (options.background) {
  2411. renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
  2412. }
  2413. if (element === element.ownerDocument.documentElement) {
  2414. // http://www.w3.org/TR/css3-background/#special-backgrounds
  2415. var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
  2416. renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
  2417. }
  2418. parent.visibile = parent.isElementVisible();
  2419. this.createPseudoHideStyles(element.ownerDocument);
  2420. this.disableAnimations(element.ownerDocument);
  2421. this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
  2422. return container.visible = container.isElementVisible();
  2423. }).map(this.getPseudoElements, this));
  2424. this.fontMetrics = new FontMetrics();
  2425. log("Fetched nodes, total:", this.nodes.length);
  2426. log("Calculate overflow clips");
  2427. this.calculateOverflowClips();
  2428. log("Start fetching images");
  2429. this.images = imageLoader.fetch(this.nodes.filter(isElement));
  2430. this.ready = this.images.ready.then(bind(function() {
  2431. log("Images loaded, starting parsing");
  2432. log("Creating stacking contexts");
  2433. this.createStackingContexts();
  2434. log("Sorting stacking contexts");
  2435. this.sortStackingContexts(this.stack);
  2436. this.parse(this.stack);
  2437. log("Render queue created with " + this.renderQueue.length + " items");
  2438. return new Promise(bind(function(resolve) {
  2439. if (!options.async) {
  2440. this.renderQueue.forEach(this.paint, this);
  2441. resolve();
  2442. } else if (typeof(options.async) === "function") {
  2443. options.async.call(this, this.renderQueue, resolve);
  2444. } else if (this.renderQueue.length > 0){
  2445. this.renderIndex = 0;
  2446. this.asyncRenderer(this.renderQueue, resolve);
  2447. } else {
  2448. resolve();
  2449. }
  2450. }, this));
  2451. }, this));
  2452. }
  2453. NodeParser.prototype.calculateOverflowClips = function() {
  2454. this.nodes.forEach(function(container) {
  2455. if (isElement(container)) {
  2456. if (isPseudoElement(container)) {
  2457. container.appendToDOM();
  2458. }
  2459. container.borders = this.parseBorders(container);
  2460. var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
  2461. var cssClip = container.parseClip();
  2462. if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
  2463. clip.push([["rect",
  2464. container.bounds.left + cssClip.left,
  2465. container.bounds.top + cssClip.top,
  2466. cssClip.right - cssClip.left,
  2467. cssClip.bottom - cssClip.top
  2468. ]]);
  2469. }
  2470. container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
  2471. container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
  2472. if (isPseudoElement(container)) {
  2473. container.cleanDOM();
  2474. }
  2475. } else if (isTextNode(container)) {
  2476. container.clip = hasParentClip(container) ? container.parent.clip : [];
  2477. }
  2478. if (!isPseudoElement(container)) {
  2479. container.bounds = null;
  2480. }
  2481. }, this);
  2482. };
  2483. function hasParentClip(container) {
  2484. return container.parent && container.parent.clip.length;
  2485. }
  2486. NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
  2487. asyncTimer = asyncTimer || Date.now();
  2488. this.paint(queue[this.renderIndex++]);
  2489. if (queue.length === this.renderIndex) {
  2490. resolve();
  2491. } else if (asyncTimer + 20 > Date.now()) {
  2492. this.asyncRenderer(queue, resolve, asyncTimer);
  2493. } else {
  2494. setTimeout(bind(function() {
  2495. this.asyncRenderer(queue, resolve);
  2496. }, this), 0);
  2497. }
  2498. };
  2499. NodeParser.prototype.createPseudoHideStyles = function(document) {
  2500. this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
  2501. '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
  2502. };
  2503. NodeParser.prototype.disableAnimations = function(document) {
  2504. this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
  2505. '-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
  2506. };
  2507. NodeParser.prototype.createStyles = function(document, styles) {
  2508. var hidePseudoElements = document.createElement('style');
  2509. hidePseudoElements.innerHTML = styles;
  2510. document.body.appendChild(hidePseudoElements);
  2511. };
  2512. NodeParser.prototype.getPseudoElements = function(container) {
  2513. var nodes = [[container]];
  2514. if (container.node.nodeType === Node.ELEMENT_NODE) {
  2515. var before = this.getPseudoElement(container, ":before");
  2516. var after = this.getPseudoElement(container, ":after");
  2517. if (before) {
  2518. nodes.push(before);
  2519. }
  2520. if (after) {
  2521. nodes.push(after);
  2522. }
  2523. }
  2524. return flatten(nodes);
  2525. };
  2526. function toCamelCase(str) {
  2527. return str.replace(/(\-[a-z])/g, function(match){
  2528. return match.toUpperCase().replace('-','');
  2529. });
  2530. }
  2531. NodeParser.prototype.getPseudoElement = function(container, type) {
  2532. var style = container.computedStyle(type);
  2533. if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
  2534. return null;
  2535. }
  2536. var content = stripQuotes(style.content);
  2537. var isImage = content.substr(0, 3) === 'url';
  2538. var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
  2539. var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
  2540. for (var i = style.length-1; i >= 0; i--) {
  2541. var property = toCamelCase(style.item(i));
  2542. pseudoNode.style[property] = style[property];
  2543. }
  2544. pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
  2545. if (isImage) {
  2546. pseudoNode.src = parseBackgrounds(content)[0].args[0];
  2547. return [pseudoContainer];
  2548. } else {
  2549. var text = document.createTextNode(content);
  2550. pseudoNode.appendChild(text);
  2551. return [pseudoContainer, new TextContainer(text, pseudoContainer)];
  2552. }
  2553. };
  2554. NodeParser.prototype.getChildren = function(parentContainer) {
  2555. return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
  2556. var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
  2557. return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
  2558. }, this));
  2559. };
  2560. NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
  2561. var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
  2562. container.cloneTo(stack);
  2563. var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
  2564. parentStack.contexts.push(stack);
  2565. container.stack = stack;
  2566. };
  2567. NodeParser.prototype.createStackingContexts = function() {
  2568. this.nodes.forEach(function(container) {
  2569. if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
  2570. this.newStackingContext(container, true);
  2571. } else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
  2572. this.newStackingContext(container, false);
  2573. } else {
  2574. container.assignStack(container.parent.stack);
  2575. }
  2576. }, this);
  2577. };
  2578. NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
  2579. return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
  2580. };
  2581. NodeParser.prototype.isRootElement = function(container) {
  2582. return container.parent === null;
  2583. };
  2584. NodeParser.prototype.sortStackingContexts = function(stack) {
  2585. stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
  2586. stack.contexts.forEach(this.sortStackingContexts, this);
  2587. };
  2588. NodeParser.prototype.parseTextBounds = function(container) {
  2589. return function(text, index, textList) {
  2590. if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
  2591. if (this.support.rangeBounds && !container.parent.hasTransform()) {
  2592. var offset = textList.slice(0, index).join("").length;
  2593. return this.getRangeBounds(container.node, offset, text.length);
  2594. } else if (container.node && typeof(container.node.data) === "string") {
  2595. var replacementNode = container.node.splitText(text.length);
  2596. var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
  2597. container.node = replacementNode;
  2598. return bounds;
  2599. }
  2600. } else if(!this.support.rangeBounds || container.parent.hasTransform()){
  2601. container.node = container.node.splitText(text.length);
  2602. }
  2603. return {};
  2604. };
  2605. };
  2606. NodeParser.prototype.getWrapperBounds = function(node, transform) {
  2607. var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
  2608. var parent = node.parentNode,
  2609. backupText = node.cloneNode(true);
  2610. wrapper.appendChild(node.cloneNode(true));
  2611. parent.replaceChild(wrapper, node);
  2612. var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
  2613. parent.replaceChild(backupText, wrapper);
  2614. return bounds;
  2615. };
  2616. NodeParser.prototype.getRangeBounds = function(node, offset, length) {
  2617. var range = this.range || (this.range = node.ownerDocument.createRange());
  2618. range.setStart(node, offset);
  2619. range.setEnd(node, offset + length);
  2620. return range.getBoundingClientRect();
  2621. };
  2622. function ClearTransform() {}
  2623. NodeParser.prototype.parse = function(stack) {
  2624. // http://www.w3.org/TR/CSS21/visuren.html#z-index
  2625. var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
  2626. var descendantElements = stack.children.filter(isElement);
  2627. var descendantNonFloats = descendantElements.filter(not(isFloating));
  2628. var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
  2629. var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
  2630. var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  2631. var stackLevel0 = stack.contexts.concat(descendantNonFloats.filter(isPositioned)).filter(zIndex0); // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  2632. var text = stack.children.filter(isTextNode).filter(hasText);
  2633. var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
  2634. negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
  2635. .concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
  2636. this.renderQueue.push(container);
  2637. if (isStackingContext(container)) {
  2638. this.parse(container);
  2639. this.renderQueue.push(new ClearTransform());
  2640. }
  2641. }, this);
  2642. };
  2643. NodeParser.prototype.paint = function(container) {
  2644. try {
  2645. if (container instanceof ClearTransform) {
  2646. this.renderer.ctx.restore();
  2647. } else if (isTextNode(container)) {
  2648. if (isPseudoElement(container.parent)) {
  2649. container.parent.appendToDOM();
  2650. }
  2651. this.paintText(container);
  2652. if (isPseudoElement(container.parent)) {
  2653. container.parent.cleanDOM();
  2654. }
  2655. } else {
  2656. this.paintNode(container);
  2657. }
  2658. } catch(e) {
  2659. log(e);
  2660. if (this.options.strict) {
  2661. throw e;
  2662. }
  2663. }
  2664. };
  2665. NodeParser.prototype.paintNode = function(container) {
  2666. if (isStackingContext(container)) {
  2667. this.renderer.setOpacity(container.opacity);
  2668. this.renderer.ctx.save();
  2669. if (container.hasTransform()) {
  2670. this.renderer.setTransform(container.parseTransform());
  2671. }
  2672. }
  2673. if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
  2674. this.paintCheckbox(container);
  2675. } else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
  2676. this.paintRadio(container);
  2677. } else {
  2678. this.paintElement(container);
  2679. }
  2680. };
  2681. NodeParser.prototype.paintElement = function(container) {
  2682. var bounds = container.parseBounds();
  2683. this.renderer.clip(container.backgroundClip, function() {
  2684. this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
  2685. }, this);
  2686. this.renderer.clip(container.clip, function() {
  2687. this.renderer.renderBorders(container.borders.borders);
  2688. }, this);
  2689. this.renderer.clip(container.backgroundClip, function() {
  2690. switch (container.node.nodeName) {
  2691. case "svg":
  2692. case "IFRAME":
  2693. var imgContainer = this.images.get(container.node);
  2694. if (imgContainer) {
  2695. this.renderer.renderImage(container, bounds, container.borders, imgContainer);
  2696. } else {
  2697. log("Error loading <" + container.node.nodeName + ">", container.node);
  2698. }
  2699. break;
  2700. case "IMG":
  2701. var imageContainer = this.images.get(container.node.src);
  2702. if (imageContainer) {
  2703. this.renderer.renderImage(container, bounds, container.borders, imageContainer);
  2704. } else {
  2705. log("Error loading <img>", container.node.src);
  2706. }
  2707. break;
  2708. case "CANVAS":
  2709. this.renderer.renderImage(container, bounds, container.borders, {image: container.node});
  2710. break;
  2711. case "SELECT":
  2712. case "INPUT":
  2713. case "TEXTAREA":
  2714. this.paintFormValue(container);
  2715. break;
  2716. }
  2717. }, this);
  2718. };
  2719. NodeParser.prototype.paintCheckbox = function(container) {
  2720. var b = container.parseBounds();
  2721. var size = Math.min(b.width, b.height);
  2722. var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left};
  2723. var r = [3, 3];
  2724. var radius = [r, r, r, r];
  2725. var borders = [1,1,1,1].map(function(w) {
  2726. return {color: new Color('#A5A5A5'), width: w};
  2727. });
  2728. var borderPoints = calculateCurvePoints(bounds, radius, borders);
  2729. this.renderer.clip(container.backgroundClip, function() {
  2730. this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
  2731. this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
  2732. if (container.node.checked) {
  2733. this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
  2734. this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
  2735. }
  2736. }, this);
  2737. };
  2738. NodeParser.prototype.paintRadio = function(container) {
  2739. var bounds = container.parseBounds();
  2740. var size = Math.min(bounds.width, bounds.height) - 2;
  2741. this.renderer.clip(container.backgroundClip, function() {
  2742. this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
  2743. if (container.node.checked) {
  2744. this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
  2745. }
  2746. }, this);
  2747. };
  2748. NodeParser.prototype.paintFormValue = function(container) {
  2749. var value = container.getValue();
  2750. if (value.length > 0) {
  2751. var document = container.node.ownerDocument;
  2752. var wrapper = document.createElement('html2canvaswrapper');
  2753. var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
  2754. 'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
  2755. 'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
  2756. 'boxSizing', 'whiteSpace', 'wordWrap'];
  2757. properties.forEach(function(property) {
  2758. try {
  2759. wrapper.style[property] = container.css(property);
  2760. } catch(e) {
  2761. // Older IE has issues with "border"
  2762. log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
  2763. }
  2764. });
  2765. var bounds = container.parseBounds();
  2766. wrapper.style.position = "fixed";
  2767. wrapper.style.left = bounds.left + "px";
  2768. wrapper.style.top = bounds.top + "px";
  2769. wrapper.textContent = value;
  2770. document.body.appendChild(wrapper);
  2771. this.paintText(new TextContainer(wrapper.firstChild, container));
  2772. document.body.removeChild(wrapper);
  2773. }
  2774. };
  2775. NodeParser.prototype.paintText = function(container) {
  2776. container.applyTextTransform();
  2777. var characters = punycode.ucs2.decode(container.node.data);
  2778. var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
  2779. return punycode.ucs2.encode([character]);
  2780. });
  2781. var weight = container.parent.fontWeight();
  2782. var size = container.parent.css('fontSize');
  2783. var family = container.parent.css('fontFamily');
  2784. var shadows = container.parent.parseTextShadows();
  2785. this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
  2786. if (shadows.length) {
  2787. // TODO: support multiple text shadows
  2788. this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
  2789. } else {
  2790. this.renderer.clearShadow();
  2791. }
  2792. this.renderer.clip(container.parent.clip, function() {
  2793. textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
  2794. if (bounds) {
  2795. this.renderer.text(textList[index], bounds.left, bounds.bottom);
  2796. this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
  2797. }
  2798. }, this);
  2799. }, this);
  2800. };
  2801. NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
  2802. switch(container.css("textDecoration").split(" ")[0]) {
  2803. case "underline":
  2804. // Draws a line at the baseline of the font
  2805. // TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size
  2806. this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
  2807. break;
  2808. case "overline":
  2809. this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
  2810. break;
  2811. case "line-through":
  2812. // TODO try and find exact position for line-through
  2813. this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
  2814. break;
  2815. }
  2816. };
  2817. var borderColorTransforms = {
  2818. inset: [
  2819. ["darken", 0.60],
  2820. ["darken", 0.10],
  2821. ["darken", 0.10],
  2822. ["darken", 0.60]
  2823. ]
  2824. };
  2825. NodeParser.prototype.parseBorders = function(container) {
  2826. var nodeBounds = container.parseBounds();
  2827. var radius = getBorderRadiusData(container);
  2828. var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
  2829. var style = container.css('border' + side + 'Style');
  2830. var color = container.color('border' + side + 'Color');
  2831. if (style === "inset" && color.isBlack()) {
  2832. color = new Color([255, 255, 255, color.a]); // this is wrong, but
  2833. }
  2834. var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
  2835. return {
  2836. width: container.cssInt('border' + side + 'Width'),
  2837. color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
  2838. args: null
  2839. };
  2840. });
  2841. var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
  2842. return {
  2843. clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
  2844. borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
  2845. };
  2846. };
  2847. function calculateBorders(borders, nodeBounds, borderPoints, radius) {
  2848. return borders.map(function(border, borderSide) {
  2849. if (border.width > 0) {
  2850. var bx = nodeBounds.left;
  2851. var by = nodeBounds.top;
  2852. var bw = nodeBounds.width;
  2853. var bh = nodeBounds.height - (borders[2].width);
  2854. switch(borderSide) {
  2855. case 0:
  2856. // top border
  2857. bh = borders[0].width;
  2858. border.args = drawSide({
  2859. c1: [bx, by],
  2860. c2: [bx + bw, by],
  2861. c3: [bx + bw - borders[1].width, by + bh],
  2862. c4: [bx + borders[3].width, by + bh]
  2863. }, radius[0], radius[1],
  2864. borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
  2865. break;
  2866. case 1:
  2867. // right border
  2868. bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
  2869. bw = borders[1].width;
  2870. border.args = drawSide({
  2871. c1: [bx + bw, by],
  2872. c2: [bx + bw, by + bh + borders[2].width],
  2873. c3: [bx, by + bh],
  2874. c4: [bx, by + borders[0].width]
  2875. }, radius[1], radius[2],
  2876. borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
  2877. break;
  2878. case 2:
  2879. // bottom border
  2880. by = (by + nodeBounds.height) - (borders[2].width);
  2881. bh = borders[2].width;
  2882. border.args = drawSide({
  2883. c1: [bx + bw, by + bh],
  2884. c2: [bx, by + bh],
  2885. c3: [bx + borders[3].width, by],
  2886. c4: [bx + bw - borders[3].width, by]
  2887. }, radius[2], radius[3],
  2888. borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
  2889. break;
  2890. case 3:
  2891. // left border
  2892. bw = borders[3].width;
  2893. border.args = drawSide({
  2894. c1: [bx, by + bh + borders[2].width],
  2895. c2: [bx, by],
  2896. c3: [bx + bw, by + borders[0].width],
  2897. c4: [bx + bw, by + bh]
  2898. }, radius[3], radius[0],
  2899. borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
  2900. break;
  2901. }
  2902. }
  2903. return border;
  2904. });
  2905. }
  2906. NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
  2907. var backgroundClip = container.css('backgroundClip'),
  2908. borderArgs = [];
  2909. switch(backgroundClip) {
  2910. case "content-box":
  2911. case "padding-box":
  2912. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
  2913. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
  2914. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
  2915. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
  2916. break;
  2917. default:
  2918. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
  2919. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
  2920. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
  2921. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
  2922. break;
  2923. }
  2924. return borderArgs;
  2925. };
  2926. function getCurvePoints(x, y, r1, r2) {
  2927. var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
  2928. var ox = (r1) * kappa, // control point offset horizontal
  2929. oy = (r2) * kappa, // control point offset vertical
  2930. xm = x + r1, // x-middle
  2931. ym = y + r2; // y-middle
  2932. return {
  2933. topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}),
  2934. topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}),
  2935. bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}),
  2936. bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y})
  2937. };
  2938. }
  2939. function calculateCurvePoints(bounds, borderRadius, borders) {
  2940. var x = bounds.left,
  2941. y = bounds.top,
  2942. width = bounds.width,
  2943. height = bounds.height,
  2944. tlh = borderRadius[0][0],
  2945. tlv = borderRadius[0][1],
  2946. trh = borderRadius[1][0],
  2947. trv = borderRadius[1][1],
  2948. brh = borderRadius[2][0],
  2949. brv = borderRadius[2][1],
  2950. blh = borderRadius[3][0],
  2951. blv = borderRadius[3][1];
  2952. var topWidth = width - trh,
  2953. rightHeight = height - brv,
  2954. bottomWidth = width - brh,
  2955. leftHeight = height - blv;
  2956. return {
  2957. topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
  2958. topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - borders[3].width), Math.max(0, tlv - borders[0].width)).topLeft.subdivide(0.5),
  2959. topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
  2960. topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (topWidth > width + borders[3].width) ? 0 :trh - borders[3].width, trv - borders[0].width).topRight.subdivide(0.5),
  2961. bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
  2962. bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width - borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - borders[1].width), brv - borders[2].width).bottomRight.subdivide(0.5),
  2963. bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
  2964. bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
  2965. };
  2966. }
  2967. function bezierCurve(start, startControl, endControl, end) {
  2968. var lerp = function (a, b, t) {
  2969. return {
  2970. x: a.x + (b.x - a.x) * t,
  2971. y: a.y + (b.y - a.y) * t
  2972. };
  2973. };
  2974. return {
  2975. start: start,
  2976. startControl: startControl,
  2977. endControl: endControl,
  2978. end: end,
  2979. subdivide: function(t) {
  2980. var ab = lerp(start, startControl, t),
  2981. bc = lerp(startControl, endControl, t),
  2982. cd = lerp(endControl, end, t),
  2983. abbc = lerp(ab, bc, t),
  2984. bccd = lerp(bc, cd, t),
  2985. dest = lerp(abbc, bccd, t);
  2986. return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
  2987. },
  2988. curveTo: function(borderArgs) {
  2989. borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
  2990. },
  2991. curveToReversed: function(borderArgs) {
  2992. borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
  2993. }
  2994. };
  2995. }
  2996. function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
  2997. var borderArgs = [];
  2998. if (radius1[0] > 0 || radius1[1] > 0) {
  2999. borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
  3000. outer1[1].curveTo(borderArgs);
  3001. } else {
  3002. borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
  3003. }
  3004. if (radius2[0] > 0 || radius2[1] > 0) {
  3005. borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
  3006. outer2[0].curveTo(borderArgs);
  3007. borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
  3008. inner2[0].curveToReversed(borderArgs);
  3009. } else {
  3010. borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
  3011. borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
  3012. }
  3013. if (radius1[0] > 0 || radius1[1] > 0) {
  3014. borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
  3015. inner1[1].curveToReversed(borderArgs);
  3016. } else {
  3017. borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
  3018. }
  3019. return borderArgs;
  3020. }
  3021. function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
  3022. if (radius1[0] > 0 || radius1[1] > 0) {
  3023. borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
  3024. corner1[0].curveTo(borderArgs);
  3025. corner1[1].curveTo(borderArgs);
  3026. } else {
  3027. borderArgs.push(["line", x, y]);
  3028. }
  3029. if (radius2[0] > 0 || radius2[1] > 0) {
  3030. borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
  3031. }
  3032. }
  3033. function negativeZIndex(container) {
  3034. return container.cssInt("zIndex") < 0;
  3035. }
  3036. function positiveZIndex(container) {
  3037. return container.cssInt("zIndex") > 0;
  3038. }
  3039. function zIndex0(container) {
  3040. return container.cssInt("zIndex") === 0;
  3041. }
  3042. function inlineLevel(container) {
  3043. return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  3044. }
  3045. function isStackingContext(container) {
  3046. return (container instanceof StackingContext);
  3047. }
  3048. function hasText(container) {
  3049. return container.node.data.trim().length > 0;
  3050. }
  3051. function noLetterSpacing(container) {
  3052. return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
  3053. }
  3054. function getBorderRadiusData(container) {
  3055. return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
  3056. var value = container.css('border' + side + 'Radius');
  3057. var arr = value.split(" ");
  3058. if (arr.length <= 1) {
  3059. arr[1] = arr[0];
  3060. }
  3061. return arr.map(asInt);
  3062. });
  3063. }
  3064. function renderableNode(node) {
  3065. return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
  3066. }
  3067. function isPositionedForStacking(container) {
  3068. var position = container.css("position");
  3069. var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
  3070. return zIndex !== "auto";
  3071. }
  3072. function isPositioned(container) {
  3073. return container.css("position") !== "static";
  3074. }
  3075. function isFloating(container) {
  3076. return container.css("float") !== "none";
  3077. }
  3078. function isInlineBlock(container) {
  3079. return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  3080. }
  3081. function not(callback) {
  3082. var context = this;
  3083. return function() {
  3084. return !callback.apply(context, arguments);
  3085. };
  3086. }
  3087. function isElement(container) {
  3088. return container.node.nodeType === Node.ELEMENT_NODE;
  3089. }
  3090. function isPseudoElement(container) {
  3091. return container.isPseudoElement === true;
  3092. }
  3093. function isTextNode(container) {
  3094. return container.node.nodeType === Node.TEXT_NODE;
  3095. }
  3096. function zIndexSort(contexts) {
  3097. return function(a, b) {
  3098. return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
  3099. };
  3100. }
  3101. function hasOpacity(container) {
  3102. return container.getOpacity() < 1;
  3103. }
  3104. function asInt(value) {
  3105. return parseInt(value, 10);
  3106. }
  3107. function getWidth(border) {
  3108. return border.width;
  3109. }
  3110. function nonIgnoredElement(nodeContainer) {
  3111. return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
  3112. }
  3113. function flatten(arrays) {
  3114. return [].concat.apply([], arrays);
  3115. }
  3116. function stripQuotes(content) {
  3117. var first = content.substr(0, 1);
  3118. return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
  3119. }
  3120. function getWords(characters) {
  3121. var words = [], i = 0, onWordBoundary = false, word;
  3122. while(characters.length) {
  3123. if (isWordBoundary(characters[i]) === onWordBoundary) {
  3124. word = characters.splice(0, i);
  3125. if (word.length) {
  3126. words.push(punycode.ucs2.encode(word));
  3127. }
  3128. onWordBoundary =! onWordBoundary;
  3129. i = 0;
  3130. } else {
  3131. i++;
  3132. }
  3133. if (i >= characters.length) {
  3134. word = characters.splice(0, i);
  3135. if (word.length) {
  3136. words.push(punycode.ucs2.encode(word));
  3137. }
  3138. }
  3139. }
  3140. return words;
  3141. }
  3142. function isWordBoundary(characterCode) {
  3143. return [
  3144. 32, // <space>
  3145. 13, // \r
  3146. 10, // \n
  3147. 9, // \t
  3148. 45 // -
  3149. ].indexOf(characterCode) !== -1;
  3150. }
  3151. function hasUnicode(string) {
  3152. return (/[^\u0000-\u00ff]/).test(string);
  3153. }
  3154. module.exports = NodeParser;
  3155. },{"./color":5,"./fontmetrics":9,"./log":15,"./nodecontainer":16,"./promise":18,"./pseudoelementcontainer":21,"./stackingcontext":24,"./textcontainer":28,"./utils":29,"punycode":3}],18:[function(require,module,exports){
  3156. module.exports = require('es6-promise').Promise;
  3157. },{"es6-promise":1}],19:[function(require,module,exports){
  3158. var Promise = require('./promise');
  3159. var XHR = require('./xhr');
  3160. var utils = require('./utils');
  3161. var log = require('./log');
  3162. var createWindowClone = require('./clone');
  3163. var decode64 = utils.decode64;
  3164. function Proxy(src, proxyUrl, document) {
  3165. var supportsCORS = ('withCredentials' in new XMLHttpRequest());
  3166. if (!proxyUrl) {
  3167. return Promise.reject("No proxy configured");
  3168. }
  3169. var callback = createCallback(supportsCORS);
  3170. var url = createProxyUrl(proxyUrl, src, callback);
  3171. return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
  3172. return decode64(response.content);
  3173. }));
  3174. }
  3175. var proxyCount = 0;
  3176. function ProxyURL(src, proxyUrl, document) {
  3177. var supportsCORSImage = ('crossOrigin' in new Image());
  3178. var callback = createCallback(supportsCORSImage);
  3179. var url = createProxyUrl(proxyUrl, src, callback);
  3180. return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
  3181. return "data:" + response.type + ";base64," + response.content;
  3182. }));
  3183. }
  3184. function jsonp(document, url, callback) {
  3185. return new Promise(function(resolve, reject) {
  3186. var s = document.createElement("script");
  3187. var cleanup = function() {
  3188. delete window.html2canvas.proxy[callback];
  3189. document.body.removeChild(s);
  3190. };
  3191. window.html2canvas.proxy[callback] = function(response) {
  3192. cleanup();
  3193. resolve(response);
  3194. };
  3195. s.src = url;
  3196. s.onerror = function(e) {
  3197. cleanup();
  3198. reject(e);
  3199. };
  3200. document.body.appendChild(s);
  3201. });
  3202. }
  3203. function createCallback(useCORS) {
  3204. return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
  3205. }
  3206. function createProxyUrl(proxyUrl, src, callback) {
  3207. return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
  3208. }
  3209. function documentFromHTML(src) {
  3210. return function(html) {
  3211. var parser = new DOMParser(), doc;
  3212. try {
  3213. doc = parser.parseFromString(html, "text/html");
  3214. } catch(e) {
  3215. log("DOMParser not supported, falling back to createHTMLDocument");
  3216. doc = document.implementation.createHTMLDocument("");
  3217. try {
  3218. doc.open();
  3219. doc.write(html);
  3220. doc.close();
  3221. } catch(ee) {
  3222. log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
  3223. doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
  3224. }
  3225. }
  3226. var b = doc.querySelector("base");
  3227. if (!b || !b.href.host) {
  3228. var base = doc.createElement("base");
  3229. base.href = src;
  3230. doc.head.insertBefore(base, doc.head.firstChild);
  3231. }
  3232. return doc;
  3233. };
  3234. }
  3235. function loadUrlDocument(src, proxy, document, width, height, options) {
  3236. return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
  3237. return createWindowClone(doc, document, width, height, options, 0, 0);
  3238. });
  3239. }
  3240. exports.Proxy = Proxy;
  3241. exports.ProxyURL = ProxyURL;
  3242. exports.loadUrlDocument = loadUrlDocument;
  3243. },{"./clone":4,"./log":15,"./promise":18,"./utils":29,"./xhr":31}],20:[function(require,module,exports){
  3244. var ProxyURL = require('./proxy').ProxyURL;
  3245. var Promise = require('./promise');
  3246. function ProxyImageContainer(src, proxy) {
  3247. var link = document.createElement("a");
  3248. link.href = src;
  3249. src = link.href;
  3250. this.src = src;
  3251. this.image = new Image();
  3252. var self = this;
  3253. this.promise = new Promise(function(resolve, reject) {
  3254. self.image.crossOrigin = "Anonymous";
  3255. self.image.onload = resolve;
  3256. self.image.onerror = reject;
  3257. new ProxyURL(src, proxy, document).then(function(url) {
  3258. self.image.src = url;
  3259. })['catch'](reject);
  3260. });
  3261. }
  3262. module.exports = ProxyImageContainer;
  3263. },{"./promise":18,"./proxy":19}],21:[function(require,module,exports){
  3264. var NodeContainer = require('./nodecontainer');
  3265. function PseudoElementContainer(node, parent, type) {
  3266. NodeContainer.call(this, node, parent);
  3267. this.isPseudoElement = true;
  3268. this.before = type === ":before";
  3269. }
  3270. PseudoElementContainer.prototype.cloneTo = function(stack) {
  3271. PseudoElementContainer.prototype.cloneTo.call(this, stack);
  3272. stack.isPseudoElement = true;
  3273. stack.before = this.before;
  3274. };
  3275. PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
  3276. PseudoElementContainer.prototype.appendToDOM = function() {
  3277. if (this.before) {
  3278. this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
  3279. } else {
  3280. this.parent.node.appendChild(this.node);
  3281. }
  3282. this.parent.node.className += " " + this.getHideClass();
  3283. };
  3284. PseudoElementContainer.prototype.cleanDOM = function() {
  3285. this.node.parentNode.removeChild(this.node);
  3286. this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
  3287. };
  3288. PseudoElementContainer.prototype.getHideClass = function() {
  3289. return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
  3290. };
  3291. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
  3292. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
  3293. module.exports = PseudoElementContainer;
  3294. },{"./nodecontainer":16}],22:[function(require,module,exports){
  3295. var log = require('./log');
  3296. function Renderer(width, height, images, options, document) {
  3297. this.width = width;
  3298. this.height = height;
  3299. this.images = images;
  3300. this.options = options;
  3301. this.document = document;
  3302. }
  3303. Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
  3304. var paddingLeft = container.cssInt('paddingLeft'),
  3305. paddingTop = container.cssInt('paddingTop'),
  3306. paddingRight = container.cssInt('paddingRight'),
  3307. paddingBottom = container.cssInt('paddingBottom'),
  3308. borders = borderData.borders;
  3309. var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
  3310. var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
  3311. this.drawImage(
  3312. imageContainer,
  3313. 0,
  3314. 0,
  3315. imageContainer.image.width || width,
  3316. imageContainer.image.height || height,
  3317. bounds.left + paddingLeft + borders[3].width,
  3318. bounds.top + paddingTop + borders[0].width,
  3319. width,
  3320. height
  3321. );
  3322. };
  3323. Renderer.prototype.renderBackground = function(container, bounds, borderData) {
  3324. if (bounds.height > 0 && bounds.width > 0) {
  3325. this.renderBackgroundColor(container, bounds);
  3326. this.renderBackgroundImage(container, bounds, borderData);
  3327. }
  3328. };
  3329. Renderer.prototype.renderBackgroundColor = function(container, bounds) {
  3330. var color = container.color("backgroundColor");
  3331. if (!color.isTransparent()) {
  3332. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
  3333. }
  3334. };
  3335. Renderer.prototype.renderBorders = function(borders) {
  3336. borders.forEach(this.renderBorder, this);
  3337. };
  3338. Renderer.prototype.renderBorder = function(data) {
  3339. if (!data.color.isTransparent() && data.args !== null) {
  3340. this.drawShape(data.args, data.color);
  3341. }
  3342. };
  3343. Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
  3344. var backgroundImages = container.parseBackgroundImages();
  3345. backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
  3346. switch(backgroundImage.method) {
  3347. case "url":
  3348. var image = this.images.get(backgroundImage.args[0]);
  3349. if (image) {
  3350. this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData);
  3351. } else {
  3352. log("Error loading background-image", backgroundImage.args[0]);
  3353. }
  3354. break;
  3355. case "linear-gradient":
  3356. case "gradient":
  3357. var gradientImage = this.images.get(backgroundImage.value);
  3358. if (gradientImage) {
  3359. this.renderBackgroundGradient(gradientImage, bounds, borderData);
  3360. } else {
  3361. log("Error loading background-image", backgroundImage.args[0]);
  3362. }
  3363. break;
  3364. case "none":
  3365. break;
  3366. default:
  3367. log("Unknown background-image type", backgroundImage.args[0]);
  3368. }
  3369. }, this);
  3370. };
  3371. Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
  3372. var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
  3373. var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
  3374. var repeat = container.parseBackgroundRepeat(index);
  3375. switch (repeat) {
  3376. case "repeat-x":
  3377. case "repeat no-repeat":
  3378. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
  3379. break;
  3380. case "repeat-y":
  3381. case "no-repeat repeat":
  3382. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
  3383. break;
  3384. case "no-repeat":
  3385. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
  3386. break;
  3387. default:
  3388. this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]);
  3389. break;
  3390. }
  3391. };
  3392. module.exports = Renderer;
  3393. },{"./log":15}],23:[function(require,module,exports){
  3394. var Renderer = require('../renderer');
  3395. var LinearGradientContainer = require('../lineargradientcontainer');
  3396. var log = require('../log');
  3397. function CanvasRenderer(width, height) {
  3398. Renderer.apply(this, arguments);
  3399. this.canvas = this.options.canvas || this.document.createElement("canvas");
  3400. if (!this.options.canvas) {
  3401. this.canvas.width = width;
  3402. this.canvas.height = height;
  3403. }
  3404. this.ctx = this.canvas.getContext("2d");
  3405. this.taintCtx = this.document.createElement("canvas").getContext("2d");
  3406. this.ctx.textBaseline = "bottom";
  3407. this.variables = {};
  3408. log("Initialized CanvasRenderer with size", width, "x", height);
  3409. }
  3410. CanvasRenderer.prototype = Object.create(Renderer.prototype);
  3411. CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
  3412. this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
  3413. return this.ctx;
  3414. };
  3415. CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
  3416. this.setFillStyle(color).fillRect(left, top, width, height);
  3417. };
  3418. CanvasRenderer.prototype.circle = function(left, top, size, color) {
  3419. this.setFillStyle(color);
  3420. this.ctx.beginPath();
  3421. this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true);
  3422. this.ctx.closePath();
  3423. this.ctx.fill();
  3424. };
  3425. CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
  3426. this.circle(left, top, size, color);
  3427. this.ctx.strokeStyle = strokeColor.toString();
  3428. this.ctx.stroke();
  3429. };
  3430. CanvasRenderer.prototype.drawShape = function(shape, color) {
  3431. this.shape(shape);
  3432. this.setFillStyle(color).fill();
  3433. };
  3434. CanvasRenderer.prototype.taints = function(imageContainer) {
  3435. if (imageContainer.tainted === null) {
  3436. this.taintCtx.drawImage(imageContainer.image, 0, 0);
  3437. try {
  3438. this.taintCtx.getImageData(0, 0, 1, 1);
  3439. imageContainer.tainted = false;
  3440. } catch(e) {
  3441. this.taintCtx = document.createElement("canvas").getContext("2d");
  3442. imageContainer.tainted = true;
  3443. }
  3444. }
  3445. return imageContainer.tainted;
  3446. };
  3447. CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
  3448. if (!this.taints(imageContainer) || this.options.allowTaint) {
  3449. this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
  3450. }
  3451. };
  3452. CanvasRenderer.prototype.clip = function(shapes, callback, context) {
  3453. this.ctx.save();
  3454. shapes.filter(hasEntries).forEach(function(shape) {
  3455. this.shape(shape).clip();
  3456. }, this);
  3457. callback.call(context);
  3458. this.ctx.restore();
  3459. };
  3460. CanvasRenderer.prototype.shape = function(shape) {
  3461. this.ctx.beginPath();
  3462. shape.forEach(function(point, index) {
  3463. if (point[0] === "rect") {
  3464. this.ctx.rect.apply(this.ctx, point.slice(1));
  3465. } else {
  3466. this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1));
  3467. }
  3468. }, this);
  3469. this.ctx.closePath();
  3470. return this.ctx;
  3471. };
  3472. CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
  3473. this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
  3474. };
  3475. CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
  3476. this.setVariable("shadowColor", color.toString())
  3477. .setVariable("shadowOffsetY", offsetX)
  3478. .setVariable("shadowOffsetX", offsetY)
  3479. .setVariable("shadowBlur", blur);
  3480. };
  3481. CanvasRenderer.prototype.clearShadow = function() {
  3482. this.setVariable("shadowColor", "rgba(0,0,0,0)");
  3483. };
  3484. CanvasRenderer.prototype.setOpacity = function(opacity) {
  3485. this.ctx.globalAlpha = opacity;
  3486. };
  3487. CanvasRenderer.prototype.setTransform = function(transform) {
  3488. this.ctx.translate(transform.origin[0], transform.origin[1]);
  3489. this.ctx.transform.apply(this.ctx, transform.matrix);
  3490. this.ctx.translate(-transform.origin[0], -transform.origin[1]);
  3491. };
  3492. CanvasRenderer.prototype.setVariable = function(property, value) {
  3493. if (this.variables[property] !== value) {
  3494. this.variables[property] = this.ctx[property] = value;
  3495. }
  3496. return this;
  3497. };
  3498. CanvasRenderer.prototype.text = function(text, left, bottom) {
  3499. this.ctx.fillText(text, left, bottom);
  3500. };
  3501. CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
  3502. var shape = [
  3503. ["line", Math.round(left), Math.round(top)],
  3504. ["line", Math.round(left + width), Math.round(top)],
  3505. ["line", Math.round(left + width), Math.round(height + top)],
  3506. ["line", Math.round(left), Math.round(height + top)]
  3507. ];
  3508. this.clip([shape], function() {
  3509. this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
  3510. }, this);
  3511. };
  3512. CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
  3513. var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
  3514. this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
  3515. this.ctx.translate(offsetX, offsetY);
  3516. this.ctx.fill();
  3517. this.ctx.translate(-offsetX, -offsetY);
  3518. };
  3519. CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
  3520. if (gradientImage instanceof LinearGradientContainer) {
  3521. var gradient = this.ctx.createLinearGradient(
  3522. bounds.left + bounds.width * gradientImage.x0,
  3523. bounds.top + bounds.height * gradientImage.y0,
  3524. bounds.left + bounds.width * gradientImage.x1,
  3525. bounds.top + bounds.height * gradientImage.y1);
  3526. gradientImage.colorStops.forEach(function(colorStop) {
  3527. gradient.addColorStop(colorStop.stop, colorStop.color.toString());
  3528. });
  3529. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
  3530. }
  3531. };
  3532. CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
  3533. var image = imageContainer.image;
  3534. if(image.width === size.width && image.height === size.height) {
  3535. return image;
  3536. }
  3537. var ctx, canvas = document.createElement('canvas');
  3538. canvas.width = size.width;
  3539. canvas.height = size.height;
  3540. ctx = canvas.getContext("2d");
  3541. ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height );
  3542. return canvas;
  3543. };
  3544. function hasEntries(array) {
  3545. return array.length > 0;
  3546. }
  3547. module.exports = CanvasRenderer;
  3548. },{"../lineargradientcontainer":14,"../log":15,"../renderer":22}],24:[function(require,module,exports){
  3549. var NodeContainer = require('./nodecontainer');
  3550. function StackingContext(hasOwnStacking, opacity, element, parent) {
  3551. NodeContainer.call(this, element, parent);
  3552. this.ownStacking = hasOwnStacking;
  3553. this.contexts = [];
  3554. this.children = [];
  3555. this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
  3556. }
  3557. StackingContext.prototype = Object.create(NodeContainer.prototype);
  3558. StackingContext.prototype.getParentStack = function(context) {
  3559. var parentStack = (this.parent) ? this.parent.stack : null;
  3560. return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
  3561. };
  3562. module.exports = StackingContext;
  3563. },{"./nodecontainer":16}],25:[function(require,module,exports){
  3564. function Support(document) {
  3565. this.rangeBounds = this.testRangeBounds(document);
  3566. this.cors = this.testCORS();
  3567. this.svg = this.testSVG();
  3568. }
  3569. Support.prototype.testRangeBounds = function(document) {
  3570. var range, testElement, rangeBounds, rangeHeight, support = false;
  3571. if (document.createRange) {
  3572. range = document.createRange();
  3573. if (range.getBoundingClientRect) {
  3574. testElement = document.createElement('boundtest');
  3575. testElement.style.height = "123px";
  3576. testElement.style.display = "block";
  3577. document.body.appendChild(testElement);
  3578. range.selectNode(testElement);
  3579. rangeBounds = range.getBoundingClientRect();
  3580. rangeHeight = rangeBounds.height;
  3581. if (rangeHeight === 123) {
  3582. support = true;
  3583. }
  3584. document.body.removeChild(testElement);
  3585. }
  3586. }
  3587. return support;
  3588. };
  3589. Support.prototype.testCORS = function() {
  3590. return typeof((new Image()).crossOrigin) !== "undefined";
  3591. };
  3592. Support.prototype.testSVG = function() {
  3593. var img = new Image();
  3594. var canvas = document.createElement("canvas");
  3595. var ctx = canvas.getContext("2d");
  3596. img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
  3597. try {
  3598. ctx.drawImage(img, 0, 0);
  3599. canvas.toDataURL();
  3600. } catch(e) {
  3601. return false;
  3602. }
  3603. return true;
  3604. };
  3605. module.exports = Support;
  3606. },{}],26:[function(require,module,exports){
  3607. var Promise = require('./promise');
  3608. var XHR = require('./xhr');
  3609. var decode64 = require('./utils').decode64;
  3610. function SVGContainer(src) {
  3611. this.src = src;
  3612. this.image = null;
  3613. var self = this;
  3614. this.promise = this.hasFabric().then(function() {
  3615. return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
  3616. }).then(function(svg) {
  3617. return new Promise(function(resolve) {
  3618. window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
  3619. });
  3620. });
  3621. }
  3622. SVGContainer.prototype.hasFabric = function() {
  3623. return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
  3624. };
  3625. SVGContainer.prototype.inlineFormatting = function(src) {
  3626. return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
  3627. };
  3628. SVGContainer.prototype.removeContentType = function(src) {
  3629. return src.replace(/^data:image\/svg\+xml(;base64)?,/,'');
  3630. };
  3631. SVGContainer.prototype.isInline = function(src) {
  3632. return (/^data:image\/svg\+xml/i.test(src));
  3633. };
  3634. SVGContainer.prototype.createCanvas = function(resolve) {
  3635. var self = this;
  3636. return function (objects, options) {
  3637. var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
  3638. self.image = canvas.lowerCanvasEl;
  3639. canvas
  3640. .setWidth(options.width)
  3641. .setHeight(options.height)
  3642. .add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
  3643. .renderAll();
  3644. resolve(canvas.lowerCanvasEl);
  3645. };
  3646. };
  3647. SVGContainer.prototype.decode64 = function(str) {
  3648. return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
  3649. };
  3650. module.exports = SVGContainer;
  3651. },{"./promise":18,"./utils":29,"./xhr":31}],27:[function(require,module,exports){
  3652. var SVGContainer = require('./svgcontainer');
  3653. var Promise = require('./promise');
  3654. function SVGNodeContainer(node, _native) {
  3655. this.src = node;
  3656. this.image = null;
  3657. var self = this;
  3658. this.promise = _native ? new Promise(function(resolve, reject) {
  3659. self.image = new Image();
  3660. self.image.onload = resolve;
  3661. self.image.onerror = reject;
  3662. self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
  3663. if (self.image.complete === true) {
  3664. resolve(self.image);
  3665. }
  3666. }) : this.hasFabric().then(function() {
  3667. return new Promise(function(resolve) {
  3668. window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
  3669. });
  3670. });
  3671. }
  3672. SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
  3673. module.exports = SVGNodeContainer;
  3674. },{"./promise":18,"./svgcontainer":26}],28:[function(require,module,exports){
  3675. var NodeContainer = require('./nodecontainer');
  3676. function TextContainer(node, parent) {
  3677. NodeContainer.call(this, node, parent);
  3678. }
  3679. TextContainer.prototype = Object.create(NodeContainer.prototype);
  3680. TextContainer.prototype.applyTextTransform = function() {
  3681. this.node.data = this.transform(this.parent.css("textTransform"));
  3682. };
  3683. TextContainer.prototype.transform = function(transform) {
  3684. var text = this.node.data;
  3685. switch(transform){
  3686. case "lowercase":
  3687. return text.toLowerCase();
  3688. case "capitalize":
  3689. return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
  3690. case "uppercase":
  3691. return text.toUpperCase();
  3692. default:
  3693. return text;
  3694. }
  3695. };
  3696. function capitalize(m, p1, p2) {
  3697. if (m.length > 0) {
  3698. return p1 + p2.toUpperCase();
  3699. }
  3700. }
  3701. module.exports = TextContainer;
  3702. },{"./nodecontainer":16}],29:[function(require,module,exports){
  3703. exports.smallImage = function smallImage() {
  3704. return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
  3705. };
  3706. exports.bind = function(callback, context) {
  3707. return function() {
  3708. return callback.apply(context, arguments);
  3709. };
  3710. };
  3711. /*
  3712. * base64-arraybuffer
  3713. * https://github.com/niklasvh/base64-arraybuffer
  3714. *
  3715. * Copyright (c) 2012 Niklas von Hertzen
  3716. * Licensed under the MIT license.
  3717. */
  3718. exports.decode64 = function(base64) {
  3719. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3720. var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
  3721. var output = "";
  3722. for (i = 0; i < len; i+=4) {
  3723. encoded1 = chars.indexOf(base64[i]);
  3724. encoded2 = chars.indexOf(base64[i+1]);
  3725. encoded3 = chars.indexOf(base64[i+2]);
  3726. encoded4 = chars.indexOf(base64[i+3]);
  3727. byte1 = (encoded1 << 2) | (encoded2 >> 4);
  3728. byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  3729. byte3 = ((encoded3 & 3) << 6) | encoded4;
  3730. if (encoded3 === 64) {
  3731. output += String.fromCharCode(byte1);
  3732. } else if (encoded4 === 64 || encoded4 === -1) {
  3733. output += String.fromCharCode(byte1, byte2);
  3734. } else{
  3735. output += String.fromCharCode(byte1, byte2, byte3);
  3736. }
  3737. }
  3738. return output;
  3739. };
  3740. exports.getBounds = function(node) {
  3741. if (node.getBoundingClientRect) {
  3742. var clientRect = node.getBoundingClientRect();
  3743. var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
  3744. return {
  3745. top: clientRect.top,
  3746. bottom: clientRect.bottom || (clientRect.top + clientRect.height),
  3747. right: clientRect.left + width,
  3748. left: clientRect.left,
  3749. width: width,
  3750. height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
  3751. };
  3752. }
  3753. return {};
  3754. };
  3755. exports.offsetBounds = function(node) {
  3756. var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : {top: 0, left: 0};
  3757. return {
  3758. top: node.offsetTop + parent.top,
  3759. bottom: node.offsetTop + node.offsetHeight + parent.top,
  3760. right: node.offsetLeft + parent.left + node.offsetWidth,
  3761. left: node.offsetLeft + parent.left,
  3762. width: node.offsetWidth,
  3763. height: node.offsetHeight
  3764. };
  3765. };
  3766. exports.parseBackgrounds = function(backgroundImage) {
  3767. var whitespace = ' \r\n\t',
  3768. method, definition, prefix, prefix_i, block, results = [],
  3769. mode = 0, numParen = 0, quote, args;
  3770. var appendResult = function() {
  3771. if(method) {
  3772. if (definition.substr(0, 1) === '"') {
  3773. definition = definition.substr(1, definition.length - 2);
  3774. }
  3775. if (definition) {
  3776. args.push(definition);
  3777. }
  3778. if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) {
  3779. prefix = method.substr(0, prefix_i);
  3780. method = method.substr(prefix_i);
  3781. }
  3782. results.push({
  3783. prefix: prefix,
  3784. method: method.toLowerCase(),
  3785. value: block,
  3786. args: args,
  3787. image: null
  3788. });
  3789. }
  3790. args = [];
  3791. method = prefix = definition = block = '';
  3792. };
  3793. args = [];
  3794. method = prefix = definition = block = '';
  3795. backgroundImage.split("").forEach(function(c) {
  3796. if (mode === 0 && whitespace.indexOf(c) > -1) {
  3797. return;
  3798. }
  3799. switch(c) {
  3800. case '"':
  3801. if(!quote) {
  3802. quote = c;
  3803. } else if(quote === c) {
  3804. quote = null;
  3805. }
  3806. break;
  3807. case '(':
  3808. if(quote) {
  3809. break;
  3810. } else if(mode === 0) {
  3811. mode = 1;
  3812. block += c;
  3813. return;
  3814. } else {
  3815. numParen++;
  3816. }
  3817. break;
  3818. case ')':
  3819. if (quote) {
  3820. break;
  3821. } else if(mode === 1) {
  3822. if(numParen === 0) {
  3823. mode = 0;
  3824. block += c;
  3825. appendResult();
  3826. return;
  3827. } else {
  3828. numParen--;
  3829. }
  3830. }
  3831. break;
  3832. case ',':
  3833. if (quote) {
  3834. break;
  3835. } else if(mode === 0) {
  3836. appendResult();
  3837. return;
  3838. } else if (mode === 1) {
  3839. if (numParen === 0 && !method.match(/^url$/i)) {
  3840. args.push(definition);
  3841. definition = '';
  3842. block += c;
  3843. return;
  3844. }
  3845. }
  3846. break;
  3847. }
  3848. block += c;
  3849. if (mode === 0) {
  3850. method += c;
  3851. } else {
  3852. definition += c;
  3853. }
  3854. });
  3855. appendResult();
  3856. return results;
  3857. };
  3858. },{}],30:[function(require,module,exports){
  3859. var GradientContainer = require('./gradientcontainer');
  3860. function WebkitGradientContainer(imageData) {
  3861. GradientContainer.apply(this, arguments);
  3862. this.type = (imageData.args[0] === "linear") ? this.TYPES.LINEAR : this.TYPES.RADIAL;
  3863. }
  3864. WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
  3865. module.exports = WebkitGradientContainer;
  3866. },{"./gradientcontainer":11}],31:[function(require,module,exports){
  3867. var Promise = require('./promise');
  3868. function XHR(url) {
  3869. return new Promise(function(resolve, reject) {
  3870. var xhr = new XMLHttpRequest();
  3871. xhr.open('GET', url);
  3872. xhr.onload = function() {
  3873. if (xhr.status === 200) {
  3874. resolve(xhr.responseText);
  3875. } else {
  3876. reject(new Error(xhr.statusText));
  3877. }
  3878. };
  3879. xhr.onerror = function() {
  3880. reject(new Error("Network Error"));
  3881. };
  3882. xhr.send();
  3883. });
  3884. }
  3885. module.exports = XHR;
  3886. },{"./promise":18}]},{},[6])(6)
  3887. });