2
0

dom_utils.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /* Copyright 2017 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. 'use strict';
  16. Object.defineProperty(exports, "__esModule", {
  17. value: true
  18. });
  19. exports.SimpleXMLParser = exports.DOMSVGFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = exports.getDefaultSetting = exports.LinkTarget = exports.getFilenameFromUrl = exports.isValidUrl = exports.isExternalLinkTargetSet = exports.addLinkAttributes = exports.RenderingCancelledException = exports.CustomStyle = undefined;
  20. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  21. var _util = require('../shared/util');
  22. var _global_scope = require('../shared/global_scope');
  23. var _global_scope2 = _interopRequireDefault(_global_scope);
  24. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  26. var DEFAULT_LINK_REL = 'noopener noreferrer nofollow';
  27. var SVG_NS = 'http://www.w3.org/2000/svg';
  28. var DOMCanvasFactory = function () {
  29. function DOMCanvasFactory() {
  30. _classCallCheck(this, DOMCanvasFactory);
  31. }
  32. _createClass(DOMCanvasFactory, [{
  33. key: 'create',
  34. value: function create(width, height) {
  35. if (width <= 0 || height <= 0) {
  36. throw new Error('invalid canvas size');
  37. }
  38. var canvas = document.createElement('canvas');
  39. var context = canvas.getContext('2d');
  40. canvas.width = width;
  41. canvas.height = height;
  42. return {
  43. canvas: canvas,
  44. context: context
  45. };
  46. }
  47. }, {
  48. key: 'reset',
  49. value: function reset(canvasAndContext, width, height) {
  50. if (!canvasAndContext.canvas) {
  51. throw new Error('canvas is not specified');
  52. }
  53. if (width <= 0 || height <= 0) {
  54. throw new Error('invalid canvas size');
  55. }
  56. canvasAndContext.canvas.width = width;
  57. canvasAndContext.canvas.height = height;
  58. }
  59. }, {
  60. key: 'destroy',
  61. value: function destroy(canvasAndContext) {
  62. if (!canvasAndContext.canvas) {
  63. throw new Error('canvas is not specified');
  64. }
  65. canvasAndContext.canvas.width = 0;
  66. canvasAndContext.canvas.height = 0;
  67. canvasAndContext.canvas = null;
  68. canvasAndContext.context = null;
  69. }
  70. }]);
  71. return DOMCanvasFactory;
  72. }();
  73. var DOMCMapReaderFactory = function () {
  74. function DOMCMapReaderFactory(_ref) {
  75. var _ref$baseUrl = _ref.baseUrl,
  76. baseUrl = _ref$baseUrl === undefined ? null : _ref$baseUrl,
  77. _ref$isCompressed = _ref.isCompressed,
  78. isCompressed = _ref$isCompressed === undefined ? false : _ref$isCompressed;
  79. _classCallCheck(this, DOMCMapReaderFactory);
  80. this.baseUrl = baseUrl;
  81. this.isCompressed = isCompressed;
  82. }
  83. _createClass(DOMCMapReaderFactory, [{
  84. key: 'fetch',
  85. value: function fetch(_ref2) {
  86. var _this = this;
  87. var name = _ref2.name;
  88. if (!name) {
  89. return Promise.reject(new Error('CMap name must be specified.'));
  90. }
  91. return new Promise(function (resolve, reject) {
  92. var url = _this.baseUrl + name + (_this.isCompressed ? '.bcmap' : '');
  93. var request = new XMLHttpRequest();
  94. request.open('GET', url, true);
  95. if (_this.isCompressed) {
  96. request.responseType = 'arraybuffer';
  97. }
  98. request.onreadystatechange = function () {
  99. if (request.readyState !== XMLHttpRequest.DONE) {
  100. return;
  101. }
  102. if (request.status === 200 || request.status === 0) {
  103. var data = void 0;
  104. if (_this.isCompressed && request.response) {
  105. data = new Uint8Array(request.response);
  106. } else if (!_this.isCompressed && request.responseText) {
  107. data = (0, _util.stringToBytes)(request.responseText);
  108. }
  109. if (data) {
  110. resolve({
  111. cMapData: data,
  112. compressionType: _this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE
  113. });
  114. return;
  115. }
  116. }
  117. reject(new Error('Unable to load ' + (_this.isCompressed ? 'binary ' : '') + 'CMap at: ' + url));
  118. };
  119. request.send(null);
  120. });
  121. }
  122. }]);
  123. return DOMCMapReaderFactory;
  124. }();
  125. var DOMSVGFactory = function () {
  126. function DOMSVGFactory() {
  127. _classCallCheck(this, DOMSVGFactory);
  128. }
  129. _createClass(DOMSVGFactory, [{
  130. key: 'create',
  131. value: function create(width, height) {
  132. (0, _util.assert)(width > 0 && height > 0, 'Invalid SVG dimensions');
  133. var svg = document.createElementNS(SVG_NS, 'svg:svg');
  134. svg.setAttribute('version', '1.1');
  135. svg.setAttribute('width', width + 'px');
  136. svg.setAttribute('height', height + 'px');
  137. svg.setAttribute('preserveAspectRatio', 'none');
  138. svg.setAttribute('viewBox', '0 0 ' + width + ' ' + height);
  139. return svg;
  140. }
  141. }, {
  142. key: 'createElement',
  143. value: function createElement(type) {
  144. (0, _util.assert)(typeof type === 'string', 'Invalid SVG element type');
  145. return document.createElementNS(SVG_NS, type);
  146. }
  147. }]);
  148. return DOMSVGFactory;
  149. }();
  150. var SimpleDOMNode = function () {
  151. function SimpleDOMNode(nodeName, nodeValue) {
  152. _classCallCheck(this, SimpleDOMNode);
  153. this.nodeName = nodeName;
  154. this.nodeValue = nodeValue;
  155. Object.defineProperty(this, 'parentNode', {
  156. value: null,
  157. writable: true
  158. });
  159. }
  160. _createClass(SimpleDOMNode, [{
  161. key: 'hasChildNodes',
  162. value: function hasChildNodes() {
  163. return this.childNodes && this.childNodes.length > 0;
  164. }
  165. }, {
  166. key: 'firstChild',
  167. get: function get() {
  168. return this.childNodes[0];
  169. }
  170. }, {
  171. key: 'nextSibling',
  172. get: function get() {
  173. var index = this.parentNode.childNodes.indexOf(this);
  174. return this.parentNode.childNodes[index + 1];
  175. }
  176. }, {
  177. key: 'textContent',
  178. get: function get() {
  179. if (!this.childNodes) {
  180. return this.nodeValue || '';
  181. }
  182. return this.childNodes.map(function (child) {
  183. return child.textContent;
  184. }).join('');
  185. }
  186. }]);
  187. return SimpleDOMNode;
  188. }();
  189. var SimpleXMLParser = function () {
  190. function SimpleXMLParser() {
  191. _classCallCheck(this, SimpleXMLParser);
  192. }
  193. _createClass(SimpleXMLParser, [{
  194. key: 'parseFromString',
  195. value: function parseFromString(data) {
  196. var _this2 = this;
  197. var nodes = [];
  198. data = data.replace(/<\?[\s\S]*?\?>|<!--[\s\S]*?-->/g, '').trim();
  199. data = data.replace(/<!DOCTYPE[^>\[]+(\[[^\]]+)?[^>]+>/g, '').trim();
  200. data = data.replace(/>([^<][\s\S]*?)</g, function (all, text) {
  201. var length = nodes.length;
  202. var node = new SimpleDOMNode('#text', _this2._decodeXML(text));
  203. nodes.push(node);
  204. if (node.textContent.trim().length === 0) {
  205. return '><';
  206. }
  207. return '>' + length + ',<';
  208. });
  209. data = data.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, function (all, text) {
  210. var length = nodes.length;
  211. var node = new SimpleDOMNode('#text', text);
  212. nodes.push(node);
  213. return length + ',';
  214. });
  215. var regex = /<([\w\:]+)((?:[\s\w:=]|'[^']*'|"[^"]*")*)(?:\/>|>([\d,]*)<\/[^>]+>)/g;
  216. var lastLength = void 0;
  217. do {
  218. lastLength = nodes.length;
  219. data = data.replace(regex, function (all, name, attrs, data) {
  220. var length = nodes.length;
  221. var node = new SimpleDOMNode(name);
  222. var children = [];
  223. if (data) {
  224. data = data.split(',');
  225. data.pop();
  226. data.forEach(function (child) {
  227. var childNode = nodes[+child];
  228. childNode.parentNode = node;
  229. children.push(childNode);
  230. });
  231. }
  232. node.childNodes = children;
  233. nodes.push(node);
  234. return length + ',';
  235. });
  236. } while (lastLength < nodes.length);
  237. return { documentElement: nodes.pop() };
  238. }
  239. }, {
  240. key: '_decodeXML',
  241. value: function _decodeXML(text) {
  242. if (text.indexOf('&') < 0) {
  243. return text;
  244. }
  245. return text.replace(/&(#(x[0-9a-f]+|\d+)|\w+);/gi, function (all, entityName, number) {
  246. if (number) {
  247. if (number[0] === 'x') {
  248. number = parseInt(number.substring(1), 16);
  249. } else {
  250. number = +number;
  251. }
  252. return String.fromCharCode(number);
  253. }
  254. switch (entityName) {
  255. case 'amp':
  256. return '&';
  257. case 'lt':
  258. return '<';
  259. case 'gt':
  260. return '>';
  261. case 'quot':
  262. return '\"';
  263. case 'apos':
  264. return '\'';
  265. }
  266. return '&' + entityName + ';';
  267. });
  268. }
  269. }]);
  270. return SimpleXMLParser;
  271. }();
  272. var CustomStyle = function CustomStyleClosure() {
  273. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  274. var _cache = Object.create(null);
  275. function CustomStyle() {}
  276. CustomStyle.getProp = function get(propName, element) {
  277. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  278. return _cache[propName];
  279. }
  280. element = element || document.documentElement;
  281. var style = element.style,
  282. prefixed,
  283. uPropName;
  284. if (typeof style[propName] === 'string') {
  285. return _cache[propName] = propName;
  286. }
  287. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  288. for (var i = 0, l = prefixes.length; i < l; i++) {
  289. prefixed = prefixes[i] + uPropName;
  290. if (typeof style[prefixed] === 'string') {
  291. return _cache[propName] = prefixed;
  292. }
  293. }
  294. return _cache[propName] = 'undefined';
  295. };
  296. CustomStyle.setProp = function set(propName, element, str) {
  297. var prop = this.getProp(propName);
  298. if (prop !== 'undefined') {
  299. element.style[prop] = str;
  300. }
  301. };
  302. return CustomStyle;
  303. }();
  304. var RenderingCancelledException = function RenderingCancelledException() {
  305. function RenderingCancelledException(msg, type) {
  306. this.message = msg;
  307. this.type = type;
  308. }
  309. RenderingCancelledException.prototype = new Error();
  310. RenderingCancelledException.prototype.name = 'RenderingCancelledException';
  311. RenderingCancelledException.constructor = RenderingCancelledException;
  312. return RenderingCancelledException;
  313. }();
  314. var LinkTarget = {
  315. NONE: 0,
  316. SELF: 1,
  317. BLANK: 2,
  318. PARENT: 3,
  319. TOP: 4
  320. };
  321. var LinkTargetStringMap = ['', '_self', '_blank', '_parent', '_top'];
  322. function addLinkAttributes(link, params) {
  323. var url = params && params.url;
  324. link.href = link.title = url ? (0, _util.removeNullCharacters)(url) : '';
  325. if (url) {
  326. var target = params.target;
  327. if (typeof target === 'undefined') {
  328. target = getDefaultSetting('externalLinkTarget');
  329. }
  330. link.target = LinkTargetStringMap[target];
  331. var rel = params.rel;
  332. if (typeof rel === 'undefined') {
  333. rel = getDefaultSetting('externalLinkRel');
  334. }
  335. link.rel = rel;
  336. }
  337. }
  338. function getFilenameFromUrl(url) {
  339. var anchor = url.indexOf('#');
  340. var query = url.indexOf('?');
  341. var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  342. return url.substring(url.lastIndexOf('/', end) + 1, end);
  343. }
  344. function getDefaultSetting(id) {
  345. var globalSettings = _global_scope2.default.PDFJS;
  346. switch (id) {
  347. case 'pdfBug':
  348. return globalSettings ? globalSettings.pdfBug : false;
  349. case 'disableAutoFetch':
  350. return globalSettings ? globalSettings.disableAutoFetch : false;
  351. case 'disableStream':
  352. return globalSettings ? globalSettings.disableStream : false;
  353. case 'disableRange':
  354. return globalSettings ? globalSettings.disableRange : false;
  355. case 'disableFontFace':
  356. return globalSettings ? globalSettings.disableFontFace : false;
  357. case 'disableCreateObjectURL':
  358. return globalSettings ? globalSettings.disableCreateObjectURL : false;
  359. case 'disableWebGL':
  360. return globalSettings ? globalSettings.disableWebGL : true;
  361. case 'cMapUrl':
  362. return globalSettings ? globalSettings.cMapUrl : null;
  363. case 'cMapPacked':
  364. return globalSettings ? globalSettings.cMapPacked : false;
  365. case 'postMessageTransfers':
  366. return globalSettings ? globalSettings.postMessageTransfers : true;
  367. case 'workerPort':
  368. return globalSettings ? globalSettings.workerPort : null;
  369. case 'workerSrc':
  370. return globalSettings ? globalSettings.workerSrc : null;
  371. case 'disableWorker':
  372. return globalSettings ? globalSettings.disableWorker : false;
  373. case 'maxImageSize':
  374. return globalSettings ? globalSettings.maxImageSize : -1;
  375. case 'imageResourcesPath':
  376. return globalSettings ? globalSettings.imageResourcesPath : '';
  377. case 'isEvalSupported':
  378. return globalSettings ? globalSettings.isEvalSupported : true;
  379. case 'externalLinkTarget':
  380. if (!globalSettings) {
  381. return LinkTarget.NONE;
  382. }
  383. switch (globalSettings.externalLinkTarget) {
  384. case LinkTarget.NONE:
  385. case LinkTarget.SELF:
  386. case LinkTarget.BLANK:
  387. case LinkTarget.PARENT:
  388. case LinkTarget.TOP:
  389. return globalSettings.externalLinkTarget;
  390. }
  391. (0, _util.warn)('PDFJS.externalLinkTarget is invalid: ' + globalSettings.externalLinkTarget);
  392. globalSettings.externalLinkTarget = LinkTarget.NONE;
  393. return LinkTarget.NONE;
  394. case 'externalLinkRel':
  395. return globalSettings ? globalSettings.externalLinkRel : DEFAULT_LINK_REL;
  396. case 'enableStats':
  397. return !!(globalSettings && globalSettings.enableStats);
  398. case 'pdfjsNext':
  399. return !!(globalSettings && globalSettings.pdfjsNext);
  400. default:
  401. throw new Error('Unknown default setting: ' + id);
  402. }
  403. }
  404. function isExternalLinkTargetSet() {
  405. var externalLinkTarget = getDefaultSetting('externalLinkTarget');
  406. switch (externalLinkTarget) {
  407. case LinkTarget.NONE:
  408. return false;
  409. case LinkTarget.SELF:
  410. case LinkTarget.BLANK:
  411. case LinkTarget.PARENT:
  412. case LinkTarget.TOP:
  413. return true;
  414. }
  415. }
  416. function isValidUrl(url, allowRelative) {
  417. (0, _util.deprecated)('isValidUrl(), please use createValidAbsoluteUrl() instead.');
  418. var baseUrl = allowRelative ? 'http://example.com' : null;
  419. return (0, _util.createValidAbsoluteUrl)(url, baseUrl) !== null;
  420. }
  421. exports.CustomStyle = CustomStyle;
  422. exports.RenderingCancelledException = RenderingCancelledException;
  423. exports.addLinkAttributes = addLinkAttributes;
  424. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  425. exports.isValidUrl = isValidUrl;
  426. exports.getFilenameFromUrl = getFilenameFromUrl;
  427. exports.LinkTarget = LinkTarget;
  428. exports.getDefaultSetting = getDefaultSetting;
  429. exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;
  430. exports.DOMCanvasFactory = DOMCanvasFactory;
  431. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  432. exports.DOMSVGFactory = DOMSVGFactory;
  433. exports.SimpleXMLParser = SimpleXMLParser;