dom_utils.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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.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 (!this.baseUrl) {
  89. return Promise.reject(new Error('CMap baseUrl must be specified, ' + 'see "PDFJS.cMapUrl" (and also "PDFJS.cMapPacked").'));
  90. }
  91. if (!name) {
  92. return Promise.reject(new Error('CMap name must be specified.'));
  93. }
  94. return new Promise(function (resolve, reject) {
  95. var url = _this.baseUrl + name + (_this.isCompressed ? '.bcmap' : '');
  96. var request = new XMLHttpRequest();
  97. request.open('GET', url, true);
  98. if (_this.isCompressed) {
  99. request.responseType = 'arraybuffer';
  100. }
  101. request.onreadystatechange = function () {
  102. if (request.readyState !== XMLHttpRequest.DONE) {
  103. return;
  104. }
  105. if (request.status === 200 || request.status === 0) {
  106. var data = void 0;
  107. if (_this.isCompressed && request.response) {
  108. data = new Uint8Array(request.response);
  109. } else if (!_this.isCompressed && request.responseText) {
  110. data = (0, _util.stringToBytes)(request.responseText);
  111. }
  112. if (data) {
  113. resolve({
  114. cMapData: data,
  115. compressionType: _this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE
  116. });
  117. return;
  118. }
  119. }
  120. reject(new Error('Unable to load ' + (_this.isCompressed ? 'binary ' : '') + 'CMap at: ' + url));
  121. };
  122. request.send(null);
  123. });
  124. }
  125. }]);
  126. return DOMCMapReaderFactory;
  127. }();
  128. var DOMSVGFactory = function () {
  129. function DOMSVGFactory() {
  130. _classCallCheck(this, DOMSVGFactory);
  131. }
  132. _createClass(DOMSVGFactory, [{
  133. key: 'create',
  134. value: function create(width, height) {
  135. (0, _util.assert)(width > 0 && height > 0, 'Invalid SVG dimensions');
  136. var svg = document.createElementNS(SVG_NS, 'svg:svg');
  137. svg.setAttribute('version', '1.1');
  138. svg.setAttribute('width', width + 'px');
  139. svg.setAttribute('height', height + 'px');
  140. svg.setAttribute('preserveAspectRatio', 'none');
  141. svg.setAttribute('viewBox', '0 0 ' + width + ' ' + height);
  142. return svg;
  143. }
  144. }, {
  145. key: 'createElement',
  146. value: function createElement(type) {
  147. (0, _util.assert)(typeof type === 'string', 'Invalid SVG element type');
  148. return document.createElementNS(SVG_NS, type);
  149. }
  150. }]);
  151. return DOMSVGFactory;
  152. }();
  153. var SimpleDOMNode = function () {
  154. function SimpleDOMNode(nodeName, nodeValue) {
  155. _classCallCheck(this, SimpleDOMNode);
  156. this.nodeName = nodeName;
  157. this.nodeValue = nodeValue;
  158. Object.defineProperty(this, 'parentNode', {
  159. value: null,
  160. writable: true
  161. });
  162. }
  163. _createClass(SimpleDOMNode, [{
  164. key: 'hasChildNodes',
  165. value: function hasChildNodes() {
  166. return this.childNodes && this.childNodes.length > 0;
  167. }
  168. }, {
  169. key: 'firstChild',
  170. get: function get() {
  171. return this.childNodes[0];
  172. }
  173. }, {
  174. key: 'nextSibling',
  175. get: function get() {
  176. var index = this.parentNode.childNodes.indexOf(this);
  177. return this.parentNode.childNodes[index + 1];
  178. }
  179. }, {
  180. key: 'textContent',
  181. get: function get() {
  182. if (!this.childNodes) {
  183. return this.nodeValue || '';
  184. }
  185. return this.childNodes.map(function (child) {
  186. return child.textContent;
  187. }).join('');
  188. }
  189. }]);
  190. return SimpleDOMNode;
  191. }();
  192. var SimpleXMLParser = function () {
  193. function SimpleXMLParser() {
  194. _classCallCheck(this, SimpleXMLParser);
  195. }
  196. _createClass(SimpleXMLParser, [{
  197. key: 'parseFromString',
  198. value: function parseFromString(data) {
  199. var _this2 = this;
  200. var nodes = [];
  201. data = data.replace(/<\?[\s\S]*?\?>|<!--[\s\S]*?-->/g, '').trim();
  202. data = data.replace(/<!DOCTYPE[^>\[]+(\[[^\]]+)?[^>]+>/g, '').trim();
  203. data = data.replace(/>([^<][\s\S]*?)</g, function (all, text) {
  204. var length = nodes.length;
  205. var node = new SimpleDOMNode('#text', _this2._decodeXML(text));
  206. nodes.push(node);
  207. if (node.textContent.trim().length === 0) {
  208. return '><';
  209. }
  210. return '>' + length + ',<';
  211. });
  212. data = data.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, function (all, text) {
  213. var length = nodes.length;
  214. var node = new SimpleDOMNode('#text', text);
  215. nodes.push(node);
  216. return length + ',';
  217. });
  218. var regex = /<([\w\:]+)((?:[\s\w:=]|'[^']*'|"[^"]*")*)(?:\/>|>([\d,]*)<\/[^>]+>)/g;
  219. var lastLength = void 0;
  220. do {
  221. lastLength = nodes.length;
  222. data = data.replace(regex, function (all, name, attrs, data) {
  223. var length = nodes.length;
  224. var node = new SimpleDOMNode(name);
  225. var children = [];
  226. if (data) {
  227. data = data.split(',');
  228. data.pop();
  229. data.forEach(function (child) {
  230. var childNode = nodes[+child];
  231. childNode.parentNode = node;
  232. children.push(childNode);
  233. });
  234. }
  235. node.childNodes = children;
  236. nodes.push(node);
  237. return length + ',';
  238. });
  239. } while (lastLength < nodes.length);
  240. return { documentElement: nodes.pop() };
  241. }
  242. }, {
  243. key: '_decodeXML',
  244. value: function _decodeXML(text) {
  245. if (text.indexOf('&') < 0) {
  246. return text;
  247. }
  248. return text.replace(/&(#(x[0-9a-f]+|\d+)|\w+);/gi, function (all, entityName, number) {
  249. if (number) {
  250. if (number[0] === 'x') {
  251. number = parseInt(number.substring(1), 16);
  252. } else {
  253. number = +number;
  254. }
  255. return String.fromCharCode(number);
  256. }
  257. switch (entityName) {
  258. case 'amp':
  259. return '&';
  260. case 'lt':
  261. return '<';
  262. case 'gt':
  263. return '>';
  264. case 'quot':
  265. return '\"';
  266. case 'apos':
  267. return '\'';
  268. }
  269. return '&' + entityName + ';';
  270. });
  271. }
  272. }]);
  273. return SimpleXMLParser;
  274. }();
  275. var CustomStyle = function CustomStyleClosure() {
  276. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  277. var _cache = Object.create(null);
  278. function CustomStyle() {}
  279. CustomStyle.getProp = function get(propName, element) {
  280. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  281. return _cache[propName];
  282. }
  283. element = element || document.documentElement;
  284. var style = element.style,
  285. prefixed,
  286. uPropName;
  287. if (typeof style[propName] === 'string') {
  288. return _cache[propName] = propName;
  289. }
  290. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  291. for (var i = 0, l = prefixes.length; i < l; i++) {
  292. prefixed = prefixes[i] + uPropName;
  293. if (typeof style[prefixed] === 'string') {
  294. return _cache[propName] = prefixed;
  295. }
  296. }
  297. return _cache[propName] = 'undefined';
  298. };
  299. CustomStyle.setProp = function set(propName, element, str) {
  300. var prop = this.getProp(propName);
  301. if (prop !== 'undefined') {
  302. element.style[prop] = str;
  303. }
  304. };
  305. return CustomStyle;
  306. }();
  307. var RenderingCancelledException = function RenderingCancelledException() {
  308. function RenderingCancelledException(msg, type) {
  309. this.message = msg;
  310. this.type = type;
  311. }
  312. RenderingCancelledException.prototype = new Error();
  313. RenderingCancelledException.prototype.name = 'RenderingCancelledException';
  314. RenderingCancelledException.constructor = RenderingCancelledException;
  315. return RenderingCancelledException;
  316. }();
  317. var LinkTarget = {
  318. NONE: 0,
  319. SELF: 1,
  320. BLANK: 2,
  321. PARENT: 3,
  322. TOP: 4
  323. };
  324. var LinkTargetStringMap = ['', '_self', '_blank', '_parent', '_top'];
  325. function addLinkAttributes(link, params) {
  326. var url = params && params.url;
  327. link.href = link.title = url ? (0, _util.removeNullCharacters)(url) : '';
  328. if (url) {
  329. var target = params.target;
  330. if (typeof target === 'undefined') {
  331. target = getDefaultSetting('externalLinkTarget');
  332. }
  333. link.target = LinkTargetStringMap[target];
  334. var rel = params.rel;
  335. if (typeof rel === 'undefined') {
  336. rel = getDefaultSetting('externalLinkRel');
  337. }
  338. link.rel = rel;
  339. }
  340. }
  341. function getFilenameFromUrl(url) {
  342. var anchor = url.indexOf('#');
  343. var query = url.indexOf('?');
  344. var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  345. return url.substring(url.lastIndexOf('/', end) + 1, end);
  346. }
  347. function getDefaultSetting(id) {
  348. var globalSettings = _global_scope2.default.PDFJS;
  349. switch (id) {
  350. case 'pdfBug':
  351. return globalSettings ? globalSettings.pdfBug : false;
  352. case 'disableAutoFetch':
  353. return globalSettings ? globalSettings.disableAutoFetch : false;
  354. case 'disableStream':
  355. return globalSettings ? globalSettings.disableStream : false;
  356. case 'disableRange':
  357. return globalSettings ? globalSettings.disableRange : false;
  358. case 'disableFontFace':
  359. return globalSettings ? globalSettings.disableFontFace : false;
  360. case 'disableCreateObjectURL':
  361. return globalSettings ? globalSettings.disableCreateObjectURL : false;
  362. case 'disableWebGL':
  363. return globalSettings ? globalSettings.disableWebGL : true;
  364. case 'cMapUrl':
  365. return globalSettings ? globalSettings.cMapUrl : null;
  366. case 'cMapPacked':
  367. return globalSettings ? globalSettings.cMapPacked : false;
  368. case 'postMessageTransfers':
  369. return globalSettings ? globalSettings.postMessageTransfers : true;
  370. case 'workerPort':
  371. return globalSettings ? globalSettings.workerPort : null;
  372. case 'workerSrc':
  373. return globalSettings ? globalSettings.workerSrc : null;
  374. case 'disableWorker':
  375. return globalSettings ? globalSettings.disableWorker : false;
  376. case 'maxImageSize':
  377. return globalSettings ? globalSettings.maxImageSize : -1;
  378. case 'imageResourcesPath':
  379. return globalSettings ? globalSettings.imageResourcesPath : '';
  380. case 'isEvalSupported':
  381. return globalSettings ? globalSettings.isEvalSupported : true;
  382. case 'externalLinkTarget':
  383. if (!globalSettings) {
  384. return LinkTarget.NONE;
  385. }
  386. switch (globalSettings.externalLinkTarget) {
  387. case LinkTarget.NONE:
  388. case LinkTarget.SELF:
  389. case LinkTarget.BLANK:
  390. case LinkTarget.PARENT:
  391. case LinkTarget.TOP:
  392. return globalSettings.externalLinkTarget;
  393. }
  394. (0, _util.warn)('PDFJS.externalLinkTarget is invalid: ' + globalSettings.externalLinkTarget);
  395. globalSettings.externalLinkTarget = LinkTarget.NONE;
  396. return LinkTarget.NONE;
  397. case 'externalLinkRel':
  398. return globalSettings ? globalSettings.externalLinkRel : DEFAULT_LINK_REL;
  399. case 'enableStats':
  400. return !!(globalSettings && globalSettings.enableStats);
  401. default:
  402. throw new Error('Unknown default setting: ' + id);
  403. }
  404. }
  405. function isExternalLinkTargetSet() {
  406. var externalLinkTarget = getDefaultSetting('externalLinkTarget');
  407. switch (externalLinkTarget) {
  408. case LinkTarget.NONE:
  409. return false;
  410. case LinkTarget.SELF:
  411. case LinkTarget.BLANK:
  412. case LinkTarget.PARENT:
  413. case LinkTarget.TOP:
  414. return true;
  415. }
  416. }
  417. exports.CustomStyle = CustomStyle;
  418. exports.RenderingCancelledException = RenderingCancelledException;
  419. exports.addLinkAttributes = addLinkAttributes;
  420. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  421. exports.getFilenameFromUrl = getFilenameFromUrl;
  422. exports.LinkTarget = LinkTarget;
  423. exports.getDefaultSetting = getDefaultSetting;
  424. exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;
  425. exports.DOMCanvasFactory = DOMCanvasFactory;
  426. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  427. exports.DOMSVGFactory = DOMSVGFactory;
  428. exports.SimpleXMLParser = SimpleXMLParser;